diff --git a/.github/workflows/javasteam-build-pr.yml b/.github/workflows/javasteam-build-pr.yml index f6642f6e3..9ee262741 100644 --- a/.github/workflows/javasteam-build-pr.yml +++ b/.github/workflows/javasteam-build-pr.yml @@ -35,4 +35,4 @@ jobs: - name: Setup Gradle uses: gradle/actions/setup-gradle@v4 - name: Build with Gradle, skip signing - run: ./gradlew build -x signMavenJavaPublication --build-cache + run: ./gradlew build -x signMavenJavaPublication diff --git a/.github/workflows/javasteam-build-push.yml b/.github/workflows/javasteam-build-push.yml index 11d6c56fc..5138049e9 100644 --- a/.github/workflows/javasteam-build-push.yml +++ b/.github/workflows/javasteam-build-push.yml @@ -33,8 +33,8 @@ jobs: uses: gradle/actions/wrapper-validation@v4 - name: Setup Gradle uses: gradle/actions/setup-gradle@v4 - - name: Build with Gradle, skip signing - run: ./gradlew build -x signMavenJavaPublication + - name: Build with Gradle and docs, skip signing + run: ./gradlew build javadocJar -x signMavenJavaPublication - uses: actions/upload-artifact@v4 with: name: javasteam diff --git a/build.gradle.kts b/build.gradle.kts index 10acc0d71..72eeb1a8f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -29,8 +29,6 @@ repositories { } java { - sourceCompatibility = JavaVersion.toVersion(libs.versions.java.get()) - targetCompatibility = JavaVersion.toVersion(libs.versions.java.get()) withSourcesJar() } @@ -38,6 +36,13 @@ kotlin { compilerOptions { jvmTarget.set(JvmTarget.fromTarget(libs.versions.java.get())) } + jvmToolchain(17) +} + +// The JDK 17 toolchain makes javac run in a forked worker (512 MB heap by default), +// which is too small for the huge generated protobuf sources. +tasks.withType().configureEach { + options.forkOptions.memoryMaximumSize = "2g" } /* Protobufs */ @@ -70,6 +75,10 @@ tasks.jacocoTestReport { /* Java-Kotlin Docs */ dokka { moduleName.set("JavaSteam") + // Dokka's analysis skips Java sources over 2.5 MB by default, raise the limit in KB. + dokkaGeneratorIsolation = ProcessIsolation { + systemProperties.put("idea.max.intellisense.filesize", "65536") + } dokkaSourceSets.main { suppressGeneratedFiles.set(false) // Allow generated files to be documented. perPackageOption { @@ -80,15 +89,13 @@ dokka { } } -// Make sure Maven Publishing gets javadoc +// Make sure Maven Publishing gets javadoc. +// Not part of `build`, dokka is slow. Publishing still builds it, or run `javadocJar` directly. val javadocJar by tasks.registering(Jar::class) { dependsOn(tasks.dokkaGenerate) archiveClassifier.set("javadoc") from(layout.buildDirectory.dir("dokka/html")) } -artifacts { - archives(javadocJar) -} /* Configuration */ configurations { @@ -104,7 +111,8 @@ sourceSets.main { java.srcDirs( // builtBy() fixes gradle warning "Execution optimizations have been disabled for task" files("build/generated/source/steamd/main/java").builtBy("generateSteamLanguage"), - files("build/generated/source/javasteam/main/java").builtBy("generateProjectVersion", "generateRpcMethods") + files("build/generated/source/javasteam/main/java").builtBy("generateRpcMethods"), + files("build/generated/source/version/main/java").builtBy("generateProjectVersion") ) } @@ -151,7 +159,6 @@ tasks.withType { dependencies { mockitoAgent(libs.test.mock.core) { isTransitive = false } - implementation(libs.bundles.ktor) implementation(libs.bundles.okHttp) implementation(libs.commons.lang3) implementation(libs.kotlin.coroutines) 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 5ba67b11a..266115a88 100644 --- a/buildSrc/src/main/kotlin/in/dragonbra/generators/rpc/RpcGenTask.kt +++ b/buildSrc/src/main/kotlin/in/dragonbra/generators/rpc/RpcGenTask.kt @@ -48,6 +48,8 @@ abstract class RpcGenTask : DefaultTask { val outputDir = getOutputDir().get().asFile val protoDirectory = getProtoDirectory().get().asFile + // Drop interfaces of services that no longer exist + outputDir.deleteRecursively() outputDir.mkdirs() val protoParser = ProtoParser(outputDir) diff --git a/buildSrc/src/main/kotlin/in/dragonbra/generators/steamlanguage/SteamLanguageGenTask.kt b/buildSrc/src/main/kotlin/in/dragonbra/generators/steamlanguage/SteamLanguageGenTask.kt index c6450f58a..25be72d1c 100644 --- a/buildSrc/src/main/kotlin/in/dragonbra/generators/steamlanguage/SteamLanguageGenTask.kt +++ b/buildSrc/src/main/kotlin/in/dragonbra/generators/steamlanguage/SteamLanguageGenTask.kt @@ -12,6 +12,7 @@ import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputDirectory import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.TaskAction @@ -31,6 +32,10 @@ abstract class SteamLanguageGenTask : DefaultTask { @InputFile abstract fun getInputFile(): RegularFileProperty + // The input file imports its sibling .steamd files, so all of them have to be tracked + @InputDirectory + abstract fun getInputDir(): DirectoryProperty + @OutputDirectory abstract fun getOutputDir(): DirectoryProperty @@ -40,6 +45,9 @@ abstract class SteamLanguageGenTask : DefaultTask { getInputFile().convention { project.file("src/main/steamd/in/dragonbra/javasteam/steammsg.steamd") } + getInputDir().convention( + project.layout.projectDirectory.dir("src/main/steamd/in/dragonbra/javasteam") + ) getOutputDir().convention( project.layout.buildDirectory.dir( "generated/source/steamd/main/java/in/dragonbra/javasteam" diff --git a/buildSrc/src/main/kotlin/in/dragonbra/generators/versions/VersionGenTask.kt b/buildSrc/src/main/kotlin/in/dragonbra/generators/versions/VersionGenTask.kt index ba0fa5ad8..d922e7226 100644 --- a/buildSrc/src/main/kotlin/in/dragonbra/generators/versions/VersionGenTask.kt +++ b/buildSrc/src/main/kotlin/in/dragonbra/generators/versions/VersionGenTask.kt @@ -22,6 +22,10 @@ abstract class VersionGenTask : DefaultTask { @Input abstract fun getPackage(): Property + // Tracked as an input so a version bump regenerates the class + @Input + abstract fun getVersion(): Property + @OutputDirectory abstract fun getOutputDir(): DirectoryProperty @@ -29,9 +33,11 @@ abstract class VersionGenTask : DefaultTask { constructor() { getClassName().convention(CLASS_NAME) getPackage().convention(PACKAGE) + getVersion().convention(project.provider { project.version.toString() }) + // Kept apart from the RPC generator's output, overlapping outputs can't be cached getOutputDir().convention( project.layout.buildDirectory.dir( - "generated/source/javasteam/main/java/in/dragonbra/javasteam/util" + "generated/source/version/main/java/in/dragonbra/javasteam/util" ) ) } @@ -40,7 +46,7 @@ abstract class VersionGenTask : DefaultTask { fun generate() { println("Generating version class") JavaGen(getPackage().get(), getOutputDir().get().asFile).run { - emit(getClassName().get(), project.version.toString()) + emit(getClassName().get(), getVersion().get()) flush() close() } diff --git a/gradle.properties b/gradle.properties index 7ad79a48d..11202a53f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,7 +8,12 @@ signing.secretKeyRingFile=~/.gnupg/secring.gpg ossrhUsername= ossrhPassword= -org.gradle.jvmargs=-Xmx2048m -Didea.max.content.load.filesize=65536 +# Build modules side by side and reuse task outputs across clean builds and branches +org.gradle.parallel=true +org.gradle.caching=true + +# The protobuf modules compile inside the daemon, several at once when building in parallel +org.gradle.jvmargs=-Xmx4g -Didea.max.content.load.filesize=65536 # The Kotlin compiler refuses to index Java sources larger than 20 MB kotlin.daemon.jvmargs=-Xmx2048m -Didea.max.content.load.filesize=65536 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index ae5e6b263..eda83f5ea 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -5,37 +5,37 @@ [versions] java = "17" -kotlin = "2.4.0" # https://kotlinlang.org/docs/releases.html#release-details -dokka = "2.2.0" # https://mvnrepository.com/artifact/org.jetbrains.dokka/dokka-gradle-plugin -kotlinter = "5.5.0" # https://plugins.gradle.org/plugin/org.jmailen.kotlinter -jacoco = "0.8.15" # https://www.eclemma.org/jacoco +kotlin = "2.4.21" # https://kotlinlang.org/docs/releases.html#release-details +dokka = "2.3.0" # https://mvnrepository.com/artifact/org.jetbrains.dokka/dokka-gradle-plugin +kotlinter = "5.7.0" # https://plugins.gradle.org/plugin/org.jmailen.kotlinter +jacoco = "0.8.16" # https://www.eclemma.org/jacoco # Standard Library versions -commons-lang3 = "3.20.0" # https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 +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.5.0" # https://mvnrepository.com/artifact/io.ktor/ktor-client-cio -okHttp = "5.4.0" # https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -protobuf = "4.35.1" # https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java -protobuf-gradle = "0.10.0" # https://mvnrepository.com/artifact/com.google.protobuf/protobuf-gradle-plugin +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 publishPlugin = "2.0.0" # https://mvnrepository.com/artifact/io.github.gradle-nexus/publish-plugin xz = "1.12" # https://mvnrepository.com/artifact/org.tukaani/xz -zstd = "1.5.7-11" # https://search.maven.org/artifact/com.github.luben/zstd-jni +zstd = "1.5.7-26" # https://search.maven.org/artifact/com.github.luben/zstd-jni # Depot Downloader -kotlin-serialization-json = "1.11.0" # https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-serialization-json-jvm -okio = "3.17.0" # https://mvnrepository.com/artifact/com.squareup.okio/okio +kotlin-serialization-json = "1.12.0" # https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-serialization-json-jvm +okio = "3.18.2" # https://mvnrepository.com/artifact/com.squareup.okio/okio # Testing Lib versions commons-io = "2.22.0" # https://mvnrepository.com/artifact/commons-io/commons-io -commonsCodec = "1.22.0" # https://mvnrepository.com/artifact/commons-codec/commons-codec +commonsCodec = "1.23.0" # https://mvnrepository.com/artifact/commons-codec/commons-codec coroutinesTest = "1.11.0" # https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-test -junit5 = "6.1.0" # https://mvnrepository.com/artifact/org.junit/junit-bom -mockWebServer = "5.4.0" # https://mvnrepository.com/artifact/com.squareup.okhttp3/mockwebserver3-junit5 -mockitoVersion = "5.23.0" # https://mvnrepository.com/artifact/org.mockito/mockito-core +junit5 = "6.1.3" # https://mvnrepository.com/artifact/org.junit/junit-bom +mockWebServer = "5.5.1" # https://mvnrepository.com/artifact/com.squareup.okhttp3/mockwebserver3-junit5 +mockitoVersion = "5.24.0" # https://mvnrepository.com/artifact/org.mockito/mockito-core # Samples -bouncyCastle = "1.84" # https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk18on -gson = "2.14.0" # https://mvnrepository.com/artifact/com.google.code.gson/gson +bouncyCastle = "1.86" # https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk18on +gson = "2.15.0" # https://mvnrepository.com/artifact/com.google.code.gson/gson qrCode = "1.0.1" # https://mvnrepository.com/artifact/pro.leaco.qrcode/console-qrcode [libraries] @@ -62,6 +62,7 @@ test-commons-io = { module = "commons-io:commons-io", version.ref = "commons-io" test-mock-core = { module = "org.mockito:mockito-core", version.ref = "mockitoVersion" } test-mock-jupiter = { module = "org.mockito:mockito-junit-jupiter", version.ref = "mockitoVersion" } test-mock-webserver3 = { module = "com.squareup.okhttp3:mockwebserver3-junit5", version.ref = "mockWebServer" } +test-okhttp-tls = { module = "com.squareup.okhttp3:okhttp-tls", version.ref = "okHttp" } tests-coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutinesTest" } tests-junit-bom = { module = "org.junit:junit-bom", version.ref = "junit5" } tests-junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" } @@ -88,6 +89,7 @@ testing = [ "test-mock-core", "test-mock-jupiter", "test-mock-webserver3", + "test-okhttp-tls", "tests-coroutines", "tests-junit-jupiter", "xz", diff --git a/javasteam-depotdownloader/build.gradle.kts b/javasteam-depotdownloader/build.gradle.kts index 7404d70c6..5e01a53d0 100644 --- a/javasteam-depotdownloader/build.gradle.kts +++ b/javasteam-depotdownloader/build.gradle.kts @@ -47,15 +47,13 @@ dokka { } } -// Make sure Maven Publishing gets javadoc +// Make sure Maven Publishing gets javadoc. +// Not part of `build`, dokka is slow. Publishing still builds it, or run `javadocJar` directly. val javadocJar by tasks.registering(Jar::class) { dependsOn(tasks.dokkaGenerate) archiveClassifier.set("javadoc") from(layout.buildDirectory.dir("dokka/html")) } -artifacts { - archives(javadocJar) -} /* Kotlinter */ tasks.withType { diff --git a/javasteam-protobufs-webui/build.gradle.kts b/javasteam-protobufs-webui/build.gradle.kts index 1ec9affcc..b6cb35677 100644 --- a/javasteam-protobufs-webui/build.gradle.kts +++ b/javasteam-protobufs-webui/build.gradle.kts @@ -69,15 +69,13 @@ dokka { } } -// Make sure Maven Publishing gets javadoc +// Make sure Maven Publishing gets javadoc. +// Not part of `build`, dokka is slow. Publishing still builds it, or run `javadocJar` directly. val javadocJar by tasks.registering(Jar::class) { dependsOn(tasks.dokkaGenerate) archiveClassifier.set("javadoc") from(layout.buildDirectory.dir("dokka/html")) } -artifacts { - archives(javadocJar) -} /* Kotlinter */ tasks.withType { diff --git a/settings.gradle.kts b/settings.gradle.kts index c28c3bf79..8e02387f8 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,4 +1,9 @@ +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" +} + rootProject.name = "javasteam" + include(":javasteam-cs") include(":javasteam-deadlock") include(":javasteam-depotdownloader") diff --git a/src/main/java/in/dragonbra/javasteam/base/gc/ClientGCMsg.kt b/src/main/java/in/dragonbra/javasteam/base/gc/ClientGCMsg.kt index 4a1820417..ad1d10518 100644 --- a/src/main/java/in/dragonbra/javasteam/base/gc/ClientGCMsg.kt +++ b/src/main/java/in/dragonbra/javasteam/base/gc/ClientGCMsg.kt @@ -6,7 +6,6 @@ import `in`.dragonbra.javasteam.util.log.LogManager import `in`.dragonbra.javasteam.util.log.Logger import `in`.dragonbra.javasteam.util.stream.MemoryStream import `in`.dragonbra.javasteam.util.stream.SeekOrigin -import java.io.ByteArrayOutputStream import java.io.IOException import java.lang.reflect.InvocationTargetException diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/Connection.java b/src/main/java/in/dragonbra/javasteam/networking/steam3/Connection.java deleted file mode 100644 index cb6bbe112..000000000 --- a/src/main/java/in/dragonbra/javasteam/networking/steam3/Connection.java +++ /dev/null @@ -1,96 +0,0 @@ -package in.dragonbra.javasteam.networking.steam3; - -import in.dragonbra.javasteam.util.event.Event; -import in.dragonbra.javasteam.util.event.EventArgs; - -import java.net.InetAddress; -import java.net.InetSocketAddress; - -/** - * @author lngtr - * @since 2018-02-20 - */ -public abstract class Connection { - - /** - * Occurs when a net message is received over the network. - */ - protected final Event netMsgReceived = new Event<>(); - - /** - * Occurs when the physical connection is established. - */ - protected final Event connected = new Event<>(); - - /** - * Occurs when the physical connection is broken. - */ - protected final Event disconnected = new Event<>(); - - protected void onNetMsgReceived(NetMsgEventArgs e) { - netMsgReceived.handleEvent(this, e); - } - - protected void onConnected() { - connected.handleEvent(this, EventArgs.EMPTY); - } - - protected void onDisconnected(boolean e) { - disconnected.handleEvent(this, new DisconnectedEventArgs(e)); - } - - /** - * Connects to the specified end point. - * - * @param endPoint The end point to connect to. - * @param timeout Timeout in milliseconds - */ - public abstract void connect(InetSocketAddress endPoint, int timeout); - - /** - * Connects to the specified end point. - * - * @param endPoint The end point to connect to. - */ - public final void connect(InetSocketAddress endPoint) { - connect(endPoint, 5000); - } - - /** - * Disconnects this instance. - */ - public abstract void disconnect(boolean userInitiated); - - /** - * Sends the specified data packet. - * - * @param data The data packet to send. - */ - public abstract void send(byte[] data); - - /** - * Gets the local IP. - * - * @return The local IP. - */ - public abstract InetAddress getLocalIP(); - - public abstract InetSocketAddress getCurrentEndPoint(); - - /** - * @return The type of communication protocol that this connection uses. - */ - public abstract ProtocolTypes getProtocolTypes(); - - public Event getNetMsgReceived() { - return netMsgReceived; - } - - public Event getConnected() { - return connected; - } - - public Event getDisconnected() { - return disconnected; - } -} diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/Connection.kt b/src/main/java/in/dragonbra/javasteam/networking/steam3/Connection.kt new file mode 100644 index 000000000..4768f1cdb --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/networking/steam3/Connection.kt @@ -0,0 +1,82 @@ +package `in`.dragonbra.javasteam.networking.steam3 + +import `in`.dragonbra.javasteam.util.event.Event +import `in`.dragonbra.javasteam.util.event.EventArgs +import java.net.InetAddress +import java.net.InetSocketAddress + +/** + * @author lngtr + * @since 2018-02-20 + */ +abstract class Connection { + /** + * Occurs when a net message is received over the network. + */ + val netMsgReceived: Event = Event() + + /** + * Occurs when the physical connection is established. + */ + val connected: Event = Event() + + /** + * Occurs when the physical connection is broken. + */ + val disconnected: Event = Event() + + protected fun onNetMsgReceived(e: NetMsgEventArgs) { + netMsgReceived.handleEvent(this, e) + } + + protected fun onConnected() { + connected.handleEvent(this, EventArgs.EMPTY) + } + + protected fun onDisconnected(e: Boolean) { + disconnected.handleEvent(this, DisconnectedEventArgs(e)) + } + + /** + * Connects to the specified end point. + * + * @param endPoint The end point to connect to. + * @param timeout Timeout in milliseconds + */ + abstract fun connect(endPoint: InetSocketAddress, timeout: Int) + + /** + * Connects to the specified end point. + * + * @param endPoint The end point to connect to. + */ + fun connect(endPoint: InetSocketAddress) { + connect(endPoint, 5000) + } + + /** + * Disconnects this instance. + */ + abstract fun disconnect(userInitiated: Boolean) + + /** + * Sends the specified data packet. + * + * @param data The data packet to send. + */ + abstract fun send(data: ByteArray) + + /** + * Gets the local IP. + * + * @return The local IP. + */ + abstract val localIP: InetAddress? + + abstract val currentEndPoint: InetSocketAddress? + + /** + * @return The type of communication protocol that this connection uses. + */ + abstract val protocolTypes: ProtocolTypes? +} diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/DisconnectedEventArgs.java b/src/main/java/in/dragonbra/javasteam/networking/steam3/DisconnectedEventArgs.java deleted file mode 100644 index 5d063dc52..000000000 --- a/src/main/java/in/dragonbra/javasteam/networking/steam3/DisconnectedEventArgs.java +++ /dev/null @@ -1,20 +0,0 @@ -package in.dragonbra.javasteam.networking.steam3; - -import in.dragonbra.javasteam.util.event.EventArgs; - -/** - * @author lngtr - * @since 2018-02-20 - */ -public class DisconnectedEventArgs extends EventArgs { - - private final boolean userInitiated; - - public DisconnectedEventArgs(boolean userInitiated) { - this.userInitiated = userInitiated; - } - - public boolean isUserInitiated() { - return userInitiated; - } -} diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/DisconnectedEventArgs.kt b/src/main/java/in/dragonbra/javasteam/networking/steam3/DisconnectedEventArgs.kt new file mode 100644 index 000000000..b4171aa75 --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/networking/steam3/DisconnectedEventArgs.kt @@ -0,0 +1,9 @@ +package `in`.dragonbra.javasteam.networking.steam3 + +import `in`.dragonbra.javasteam.util.event.EventArgs + +/** + * @author lngtr + * @since 2018-02-20 + */ +class DisconnectedEventArgs(val isUserInitiated: Boolean) : EventArgs() diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/EnvelopeEncryptedConnection.java b/src/main/java/in/dragonbra/javasteam/networking/steam3/EnvelopeEncryptedConnection.java deleted file mode 100644 index 8be60831d..000000000 --- a/src/main/java/in/dragonbra/javasteam/networking/steam3/EnvelopeEncryptedConnection.java +++ /dev/null @@ -1,243 +0,0 @@ -package in.dragonbra.javasteam.networking.steam3; - -import in.dragonbra.javasteam.base.IPacketMsg; -import in.dragonbra.javasteam.base.Msg; -import in.dragonbra.javasteam.enums.EMsg; -import in.dragonbra.javasteam.enums.EResult; -import in.dragonbra.javasteam.enums.EUniverse; -import in.dragonbra.javasteam.generated.MsgChannelEncryptRequest; -import in.dragonbra.javasteam.generated.MsgChannelEncryptResponse; -import in.dragonbra.javasteam.generated.MsgChannelEncryptResult; -import in.dragonbra.javasteam.steam.CMClient; -import in.dragonbra.javasteam.util.KeyDictionary; -import in.dragonbra.javasteam.util.crypto.CryptoHelper; -import in.dragonbra.javasteam.util.crypto.RSACrypto; -import in.dragonbra.javasteam.util.event.EventArgs; -import in.dragonbra.javasteam.util.event.EventHandler; -import in.dragonbra.javasteam.util.log.LogManager; -import in.dragonbra.javasteam.util.log.Logger; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; - -/** - * @author lngtr - * @since 2018-02-24 - */ -public class EnvelopeEncryptedConnection extends Connection { - - private static final Logger logger = LogManager.getLogger(EnvelopeEncryptedConnection.class); - - private final Connection inner; - private final EUniverse universe; - private EncryptionState state; - private INetFilterEncryption encryption; - - @SuppressWarnings("FieldCanBeLocal") - private final EventHandler onConnected = new EventHandler<>() { - @Override - public void handleEvent(Object sender, EventArgs e) { - state = EncryptionState.CONNECTED; - } - }; - - @SuppressWarnings("FieldCanBeLocal") - private final EventHandler onDisconnected = new EventHandler<>() { - @Override - public void handleEvent(Object sender, DisconnectedEventArgs e) { - state = EncryptionState.DISCONNECTED; - encryption = null; - - disconnected.handleEvent(EnvelopeEncryptedConnection.this, e); - } - }; - - @SuppressWarnings("FieldCanBeLocal") - private final EventHandler onNetMsgReceived = new EventHandler<>() { - @Override - public void handleEvent(Object sender, NetMsgEventArgs e) { - if (state == EncryptionState.ENCRYPTED) { - byte[] plaintextData = encryption.processIncoming(e.getData()); - netMsgReceived.handleEvent(EnvelopeEncryptedConnection.this, e.withData(plaintextData)); - return; - } - - IPacketMsg packetMsg = CMClient.getPacketMsg(e.getData()); - - if (!isExpectedEMsg(packetMsg.getMsgType())) { - logger.debug("Rejected EMsg: " + packetMsg.getMsgType() + " during channel setup"); - return; - } - - switch (packetMsg.getMsgType()) { - case ChannelEncryptRequest: - handleEncryptRequest(packetMsg); - break; - case ChannelEncryptResult: - handleEncryptResult(packetMsg); - break; - } - } - }; - - public EnvelopeEncryptedConnection(Connection inner, EUniverse universe) { - if (inner == null) { - throw new IllegalArgumentException("inner connection is null"); - } - this.inner = inner; - this.universe = universe; - - inner.getNetMsgReceived().addEventHandler(onNetMsgReceived); - inner.getConnected().addEventHandler(onConnected); - inner.getDisconnected().addEventHandler(onDisconnected); - } - - private void handleEncryptRequest(IPacketMsg packetMsg) { - Msg request = new Msg<>(MsgChannelEncryptRequest.class, packetMsg); - - EUniverse connectedUniverse = request.getBody().getUniverse(); - long protoVersion = request.getBody().getProtocolVersion(); - - logger.debug("Got encryption request. Universe: " + connectedUniverse + " Protocol ver: " + protoVersion); - - if (protoVersion != MsgChannelEncryptRequest.PROTOCOL_VERSION) { - logger.debug("Encryption handshake protocol version mismatch!"); - } - - if (connectedUniverse != universe) { - logger.debug("Expected universe " + universe + " but server reported universe " + connectedUniverse); - } - - byte[] randomChallenge = null; - if (request.getPayload().getLength() >= 16) { - randomChallenge = request.getPayload().toByteArray(); - } - - byte[] publicKey = KeyDictionary.getPublicKey(connectedUniverse); - - if (publicKey == null) { - logger.debug("HandleEncryptRequest got request for invalid universe! Universe: " + connectedUniverse + " Protocol ver: " + protoVersion); - disconnect(false); - } - - Msg response = new Msg<>(MsgChannelEncryptResponse.class); - - byte[] tempSessionKey = CryptoHelper.generateRandomBlock(32); - byte[] encryptedHandshakeBlob; - - RSACrypto rsa = new RSACrypto(publicKey); - - if (randomChallenge != null) { - byte[] blobToEncrypt = new byte[tempSessionKey.length + randomChallenge.length]; - - System.arraycopy(tempSessionKey, 0, blobToEncrypt, 0, tempSessionKey.length); - System.arraycopy(randomChallenge, 0, blobToEncrypt, tempSessionKey.length, randomChallenge.length); - - encryptedHandshakeBlob = rsa.encrypt(blobToEncrypt); - } else { - encryptedHandshakeBlob = rsa.encrypt(tempSessionKey); - } - - byte[] keyCrc = CryptoHelper.crcHash(encryptedHandshakeBlob); - - try { - response.writeBytes(encryptedHandshakeBlob); - response.writeBytes(keyCrc); - response.writeInt(0); - } catch (IOException e) { - logger.debug(e); - } - - if (randomChallenge != null) { - encryption = new NetFilterEncryptionWithHMAC(tempSessionKey); - } else { - encryption = new NetFilterEncryption(tempSessionKey); - } - - state = EncryptionState.CHALLENGED; - - send(response.serialize()); - } - - private void handleEncryptResult(IPacketMsg packetMsg) { - Msg result = new Msg<>(MsgChannelEncryptResult.class, packetMsg); - - logger.debug("Encryption result: " + result.getBody().getResult()); - - assert encryption != null; - - if (result.getBody().getResult() == EResult.OK && encryption != null) { - state = EncryptionState.ENCRYPTED; - connected.handleEvent(this, EventArgs.EMPTY); - } else { - logger.debug("Encryption channel setup failed"); - disconnect(false); - } - } - - private boolean isExpectedEMsg(EMsg msg) { - switch (state) { - case DISCONNECTED: - return false; - case CONNECTED: - return msg == EMsg.ChannelEncryptRequest; - case CHALLENGED: - return msg == EMsg.ChannelEncryptResult; - case ENCRYPTED: - return true; - default: - throw new IllegalStateException("Unreachable - landed up in undefined state."); - } - } - - @Override - public void connect(InetSocketAddress endPoint, int timeout) { - inner.connect(endPoint, timeout); - } - - @Override - public void disconnect(boolean userInitiated) { - inner.disconnect(userInitiated); - } - - @Override - public void send(byte[] data) { - if (state != EncryptionState.ENCRYPTED) { - inner.send(data); - return; - } - - // A disconnect on the network thread can clear the encryption between the state check and here - var currentEncryption = encryption; - - if (currentEncryption == null) { - logger.debug("Attempting to send client data when not connected."); - return; - } - - inner.send(currentEncryption.processOutgoing(data)); - } - - @Override - public InetAddress getLocalIP() { - return inner.getLocalIP(); - } - - @Override - public InetSocketAddress getCurrentEndPoint() { - return inner.getCurrentEndPoint(); - } - - @Override - public ProtocolTypes getProtocolTypes() { - return inner.getProtocolTypes(); - } - - private enum EncryptionState { - DISCONNECTED, - CONNECTED, - CHALLENGED, - ENCRYPTED - } -} diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/EnvelopeEncryptedConnection.kt b/src/main/java/in/dragonbra/javasteam/networking/steam3/EnvelopeEncryptedConnection.kt new file mode 100644 index 000000000..0ad7b0952 --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/networking/steam3/EnvelopeEncryptedConnection.kt @@ -0,0 +1,249 @@ +package `in`.dragonbra.javasteam.networking.steam3 + +import `in`.dragonbra.javasteam.base.IPacketMsg +import `in`.dragonbra.javasteam.base.Msg +import `in`.dragonbra.javasteam.enums.EMsg +import `in`.dragonbra.javasteam.enums.EResult +import `in`.dragonbra.javasteam.enums.EUniverse +import `in`.dragonbra.javasteam.generated.MsgChannelEncryptRequest +import `in`.dragonbra.javasteam.generated.MsgChannelEncryptResponse +import `in`.dragonbra.javasteam.generated.MsgChannelEncryptResult +import `in`.dragonbra.javasteam.steam.CMClient +import `in`.dragonbra.javasteam.util.IDebugNetworkListener +import `in`.dragonbra.javasteam.util.KeyDictionary +import `in`.dragonbra.javasteam.util.crypto.CryptoHelper +import `in`.dragonbra.javasteam.util.crypto.RSACrypto +import `in`.dragonbra.javasteam.util.event.EventArgs +import `in`.dragonbra.javasteam.util.event.EventHandler +import `in`.dragonbra.javasteam.util.log.LogManager +import java.io.IOException +import java.net.InetAddress +import java.net.InetSocketAddress + +/** + * @author lngtr + * @since 2018-02-24 + */ +class EnvelopeEncryptedConnection( + private val inner: Connection, + private val universe: EUniverse, + private val debugNetworkListener: IDebugNetworkListener?, +) : Connection() { + + @Volatile + private var state: EncryptionState = EncryptionState.Disconnected + + @Volatile + private var encryption: INetFilterEncryption? = null + + override val currentEndPoint: InetSocketAddress? + get() = inner.currentEndPoint + + override val protocolTypes: ProtocolTypes? + get() = inner.protocolTypes + + override fun connect(endPoint: InetSocketAddress, timeout: Int) { + inner.connect(endPoint, timeout) + } + + override fun disconnect(userInitiated: Boolean) { + inner.disconnect(userInitiated) + } + + override val localIP: InetAddress? + get() = inner.localIP + init { + inner.netMsgReceived += EventHandler(::handleNetMsgReceived) + inner.connected += EventHandler(::handleConnected) + inner.disconnected += EventHandler(::handleDisconnected) + } + + override fun send(data: ByteArray) { + if (state != EncryptionState.Encrypted) { + inner.send(data) + return + } + + // A disconnect on the network thread can clear the encryption between the state check and here + val currentEncryption = encryption + + if (currentEncryption == null) { + logger.debug("Attempting to send client data when not connected.") + return + } + + inner.send(currentEncryption.processOutgoing(data)) + } + + @Suppress("UNUSED_PARAMETER") + private fun handleConnected(sender: Any, e: EventArgs) { + state = EncryptionState.Connected + } + + @Suppress("UNUSED_PARAMETER") + private fun handleDisconnected(sender: Any, e: DisconnectedEventArgs) { + state = EncryptionState.Disconnected + encryption = null + disconnected.invoke(this, e) + } + + @Suppress("UNUSED_PARAMETER") + private fun handleNetMsgReceived(sender: Any, e: NetMsgEventArgs) { + if (state == EncryptionState.Disconnected) { + return + } + + if (state == EncryptionState.Encrypted) { + // A disconnect on another thread can clear the encryption between the state check and here + val currentEncryption = encryption ?: return + + val plaintextData: ByteArray + + try { + plaintextData = currentEncryption.processIncoming(e.data) + } catch (_: IOException) { + logger.debug("Failed to decrypt incoming packet, shutting down connection") + disconnect(userInitiated = false) + return + } + + netMsgReceived.invoke(this, e.withData(plaintextData)) + return + } + + val packetMsg = CMClient.getPacketMsg(e.data) + + if (packetMsg == null) { + logger.debug("Failed to parse message during channel setup, shutting down connection") + disconnect(userInitiated = false) + return + } + + try { + debugNetworkListener?.onIncomingNetworkMessage(packetMsg.msgType, packetMsg.data) + } catch (e: Exception) { + logger.debug("DebugNetworkListener threw an exception", e) + } + + if (!isExpectedEMsg(packetMsg.msgType)) { + logger.debug("Rejected EMsg: ${packetMsg.msgType} during channel setup") + return + } + + when (packetMsg.msgType) { + EMsg.ChannelEncryptRequest -> handleEncryptRequest(packetMsg) + EMsg.ChannelEncryptResult -> handleEncryptResult(packetMsg) + else -> Unit + } + } + + private fun handleEncryptRequest(packetMsg: IPacketMsg) { + val request = Msg(MsgChannelEncryptRequest::class.java, packetMsg) + + val connectedUniverse = request.body.universe + val protoVersion = request.body.protocolVersion + + logger.debug("Got encryption request. Universe: $connectedUniverse Protocol ver: $protoVersion") + + if (protoVersion != MsgChannelEncryptRequest.PROTOCOL_VERSION) { + logger.debug("Encryption handshake protocol version mismatch!") + } + + if (connectedUniverse != universe) { + logger.debug("Expected universe $universe but server reported universe $connectedUniverse") + } + + var randomChallenge: ByteArray? = null + if (request.payload.length >= 16) { + randomChallenge = request.payload.toByteArray() + } + + val publicKey = KeyDictionary.getPublicKey(connectedUniverse) + + if (publicKey == null) { + logger.debug("HandleEncryptRequest got request for invalid universe! Universe: $connectedUniverse Protocol ver: $protoVersion") + disconnect(userInitiated = false) + return + } + + val response = Msg(MsgChannelEncryptResponse::class.java) + val tempSessionKey = CryptoHelper.generateRandomBlock(32) + + val rsa = RSACrypto(publicKey) + + val encryptedHandshakeBlob = if (randomChallenge != null) { + val blobToEncrypt = ByteArray(tempSessionKey.size + randomChallenge.size) + + System.arraycopy(tempSessionKey, 0, blobToEncrypt, 0, tempSessionKey.size) + System.arraycopy(randomChallenge, 0, blobToEncrypt, tempSessionKey.size, randomChallenge.size) + + rsa.encrypt(blobToEncrypt) + } else { + rsa.encrypt(tempSessionKey) + } ?: run { + logger.debug("Failed to encrypt the handshake blob, shutting down connection") + disconnect(userInitiated = false) + return + } + + val keyCrc = CryptoHelper.crcHash(encryptedHandshakeBlob) + + try { + response.writeBytes(encryptedHandshakeBlob) + response.writeBytes(keyCrc) + response.writeInt(0) + } catch (e: IOException) { + logger.debug(e) + } + + encryption = if (randomChallenge != null) { + NetFilterEncryptionWithHMAC(tempSessionKey) + } else { + NetFilterEncryption(tempSessionKey) + } + + val serialized = response.serialize() + + try { + debugNetworkListener?.onOutgoingNetworkMessage(response.msgType, serialized) + } catch (e: Exception) { + logger.debug("DebugNetworkListener threw an exception", e) + } + + state = EncryptionState.Challenged + send(serialized) + } + + private fun handleEncryptResult(packetMsg: IPacketMsg) { + val result = Msg(MsgChannelEncryptResult::class.java, packetMsg) + + logger.debug("Encryption result: ${result.body.result}") + // DebugLog.Assert( encryption != null, nameof( EnvelopeEncryptedConnection ), "Encryption is null" ) + + if (result.body.result == EResult.OK && encryption != null) { + state = EncryptionState.Encrypted + connected.invoke(this, EventArgs.EMPTY) + } else { + logger.debug("Encryption channel setup failed") + disconnect(userInitiated = false) + } + } + + private fun isExpectedEMsg(msg: EMsg): Boolean = when (state) { + EncryptionState.Disconnected -> false + EncryptionState.Connected -> msg == EMsg.ChannelEncryptRequest + EncryptionState.Challenged -> msg == EMsg.ChannelEncryptResult + EncryptionState.Encrypted -> true + } + + enum class EncryptionState { + Disconnected, + Connected, + Challenged, + Encrypted, + } + + companion object { + private val logger = LogManager.getLogger(EnvelopeEncryptedConnection::class.java) + } +} diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/IConnectionFactory.java b/src/main/java/in/dragonbra/javasteam/networking/steam3/IConnectionFactory.java index 42adb273e..34e87a950 100644 --- a/src/main/java/in/dragonbra/javasteam/networking/steam3/IConnectionFactory.java +++ b/src/main/java/in/dragonbra/javasteam/networking/steam3/IConnectionFactory.java @@ -1,6 +1,7 @@ package in.dragonbra.javasteam.networking.steam3; import in.dragonbra.javasteam.steam.steamclient.configuration.SteamConfiguration; +import in.dragonbra.javasteam.util.IDebugNetworkListener; import org.jetbrains.annotations.Nullable; import java.util.EnumSet; @@ -9,17 +10,29 @@ @FunctionalInterface public interface IConnectionFactory { - IConnectionFactory DEFAULT = (configuration, protocol) -> { - if (protocol.contains(ProtocolTypes.WEB_SOCKET)) { - return new WebSocketConnection(); + IConnectionFactory DEFAULT = new IConnectionFactory() { + @Override + public @Nullable Connection createConnection(SteamConfiguration configuration, EnumSet protocol) { + return createConnection(configuration, protocol, null); } - if (protocol.contains(ProtocolTypes.TCP)) { - return new EnvelopeEncryptedConnection(new TcpConnection(), configuration.getUniverse()); - } - if (protocol.contains(ProtocolTypes.UDP)) { - return new EnvelopeEncryptedConnection(new UdpConnection(), configuration.getUniverse()); + + @Override + public @Nullable Connection createConnection( + SteamConfiguration configuration, + EnumSet protocol, + @Nullable IDebugNetworkListener debugNetworkListener + ) { + if (protocol.contains(ProtocolTypes.WEB_SOCKET)) { + return new WebSocketConnection(configuration.getHttpClient()); + } + if (protocol.contains(ProtocolTypes.TCP)) { + return new EnvelopeEncryptedConnection(new TcpConnection(), configuration.getUniverse(), debugNetworkListener); + } + if (protocol.contains(ProtocolTypes.UDP)) { + return new EnvelopeEncryptedConnection(new UdpConnection(), configuration.getUniverse(), debugNetworkListener); + } + return null; } - return null; }; /** @@ -27,17 +40,42 @@ public interface IConnectionFactory { */ @Nullable Connection createConnection(SteamConfiguration configuration, EnumSet protocol); + /** + * Creates a connection that reports its encryption handshake to the given debug network listener. + * Factories that only implement {@link #createConnection(SteamConfiguration, EnumSet)} ignore the listener. + * If the final method returns null, an exception will be thrown. + */ + default @Nullable Connection createConnection( + SteamConfiguration configuration, + EnumSet protocol, + @Nullable IDebugNetworkListener debugNetworkListener + ) { + return createConnection(configuration, protocol); + } + /** * If this method returns null, the subConnectionFactory will be used. */ default IConnectionFactory thenResolve(IConnectionFactory subConnectionFactory) { Objects.requireNonNull(subConnectionFactory); - return (configuration, protocol) -> { - Connection connection = createConnection(configuration, protocol); - if (connection == null) { - return subConnectionFactory.createConnection(configuration, protocol); + return new IConnectionFactory() { + @Override + public @Nullable Connection createConnection(SteamConfiguration configuration, EnumSet protocol) { + return createConnection(configuration, protocol, null); + } + + @Override + public @Nullable Connection createConnection( + SteamConfiguration configuration, + EnumSet protocol, + @Nullable IDebugNetworkListener debugNetworkListener + ) { + Connection connection = IConnectionFactory.this.createConnection(configuration, protocol, debugNetworkListener); + if (connection == null) { + return subConnectionFactory.createConnection(configuration, protocol, debugNetworkListener); + } + return connection; } - return connection; }; } } diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/INetFilterEncryption.java b/src/main/java/in/dragonbra/javasteam/networking/steam3/INetFilterEncryption.java deleted file mode 100644 index b53f3a55d..000000000 --- a/src/main/java/in/dragonbra/javasteam/networking/steam3/INetFilterEncryption.java +++ /dev/null @@ -1,10 +0,0 @@ -package in.dragonbra.javasteam.networking.steam3; - -/** - * @author lngtr - * @since 2018-02-24 - */ -public interface INetFilterEncryption { - byte[] processIncoming(byte[] data); - byte[] processOutgoing(byte[] data); -} diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/INetFilterEncryption.kt b/src/main/java/in/dragonbra/javasteam/networking/steam3/INetFilterEncryption.kt new file mode 100644 index 000000000..b31c9048a --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/networking/steam3/INetFilterEncryption.kt @@ -0,0 +1,13 @@ +package `in`.dragonbra.javasteam.networking.steam3 + +import java.io.IOException + +/** + * @author lngtr + * @since 2018-02-24 + */ +interface INetFilterEncryption { + @Throws(IOException::class) + fun processIncoming(data: ByteArray): ByteArray + fun processOutgoing(data: ByteArray): ByteArray +} diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/NetFilterEncryption.java b/src/main/java/in/dragonbra/javasteam/networking/steam3/NetFilterEncryption.java deleted file mode 100644 index dbdce7891..000000000 --- a/src/main/java/in/dragonbra/javasteam/networking/steam3/NetFilterEncryption.java +++ /dev/null @@ -1,42 +0,0 @@ -package in.dragonbra.javasteam.networking.steam3; - -import in.dragonbra.javasteam.util.crypto.CryptoException; -import in.dragonbra.javasteam.util.crypto.CryptoHelper; -import in.dragonbra.javasteam.util.log.LogManager; -import in.dragonbra.javasteam.util.log.Logger; - -/** - * @author lngtr - * @since 2018-02-24 - */ -public class NetFilterEncryption implements INetFilterEncryption { - - private static final Logger logger = LogManager.getLogger(NetFilterEncryption.class); - - private final byte[] sessionKey; - - public NetFilterEncryption(byte[] sessionKey) { - if (sessionKey.length != 32) { - logger.debug("AES session key was not 32 bytes!"); - } - this.sessionKey = sessionKey; - } - - @Override - public byte[] processIncoming(byte[] data) { - try { - return CryptoHelper.symmetricDecrypt(data, sessionKey); - } catch (CryptoException e) { - throw new IllegalStateException("Unable to decrypt incoming packet", e); - } - } - - @Override - public byte[] processOutgoing(byte[] data) { - try { - return CryptoHelper.symmetricEncrypt(data, sessionKey); - } catch (CryptoException e) { - throw new IllegalStateException("Unable to encrypt outgoing packet", e); - } - } -} diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/NetFilterEncryption.kt b/src/main/java/in/dragonbra/javasteam/networking/steam3/NetFilterEncryption.kt new file mode 100644 index 000000000..f86a75c73 --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/networking/steam3/NetFilterEncryption.kt @@ -0,0 +1,42 @@ +package `in`.dragonbra.javasteam.networking.steam3 + +import `in`.dragonbra.javasteam.util.crypto.CryptoException +import `in`.dragonbra.javasteam.util.crypto.CryptoHelper +import `in`.dragonbra.javasteam.util.log.LogManager.getLogger +import java.io.IOException + +/** + * @author lngtr + * @since 2018-02-24 + */ +class NetFilterEncryption(private val sessionKey: ByteArray) : INetFilterEncryption { + init { + if (sessionKey.size != 32) { + logger.debug("AES session key was not 32 bytes!") + } + } + + @Throws(IOException::class) + override fun processIncoming(data: ByteArray): ByteArray { + // JavaSteam Addition - Short Circuit. + if (data.size < 16) { + throw IOException("Encrypted packet is too short") + } + + try { + return CryptoHelper.symmetricDecrypt(data, sessionKey) + } catch (e: CryptoException) { + throw IOException("Unable to decrypt incoming packet", e) + } + } + + override fun processOutgoing(data: ByteArray): ByteArray = try { + return CryptoHelper.symmetricEncrypt(data, sessionKey) + } catch (e: CryptoException) { + throw IllegalStateException("Unable to encrypt outgoing packet", e) + } + + companion object { + private val logger = getLogger(NetFilterEncryption::class.java) + } +} diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/NetFilterEncryptionWithHMAC.java b/src/main/java/in/dragonbra/javasteam/networking/steam3/NetFilterEncryptionWithHMAC.java index 37e786a6c..00520dd37 100644 --- a/src/main/java/in/dragonbra/javasteam/networking/steam3/NetFilterEncryptionWithHMAC.java +++ b/src/main/java/in/dragonbra/javasteam/networking/steam3/NetFilterEncryptionWithHMAC.java @@ -5,6 +5,8 @@ import in.dragonbra.javasteam.util.log.LogManager; import in.dragonbra.javasteam.util.log.Logger; +import java.io.IOException; + /** * @author lngtr * @since 2018-02-24 @@ -26,11 +28,16 @@ public NetFilterEncryptionWithHMAC(byte[] sessionKey) { } @Override - public byte[] processIncoming(byte[] data) { + public byte[] processIncoming(byte[] data) throws IOException { + if (data.length < 16) { + throw new IOException("Packet is shorter than the initialization vector."); + } + try { return CryptoHelper.symmetricDecryptHMACIV(data, sessionKey, hmacSecret); } catch (CryptoException e) { - throw new IllegalStateException("Unable to decrypt incoming packet", e); + // rethrow as an IO exception so it's handled in the network thread + throw new IOException("Unable to decrypt incoming packet", e); } } diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/NetMsgEventArgs.java b/src/main/java/in/dragonbra/javasteam/networking/steam3/NetMsgEventArgs.java deleted file mode 100644 index 77df61503..000000000 --- a/src/main/java/in/dragonbra/javasteam/networking/steam3/NetMsgEventArgs.java +++ /dev/null @@ -1,34 +0,0 @@ -package in.dragonbra.javasteam.networking.steam3; - -import in.dragonbra.javasteam.util.event.EventArgs; - -import java.net.InetSocketAddress; - -/** - * @author lngtr - * @since 2018-02-20 - */ -@SuppressWarnings("unused") -public class NetMsgEventArgs extends EventArgs { - - private final byte[] data; - - private final InetSocketAddress endPoint; - - public NetMsgEventArgs(byte[] data, InetSocketAddress endPoint) { - this.data = data; - this.endPoint = endPoint; - } - - public NetMsgEventArgs withData(byte[] data) { - return new NetMsgEventArgs(data, this.endPoint); - } - - public byte[] getData() { - return data; - } - - public InetSocketAddress getEndPoint() { - return endPoint; - } -} diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/NetMsgEventArgs.kt b/src/main/java/in/dragonbra/javasteam/networking/steam3/NetMsgEventArgs.kt new file mode 100644 index 000000000..57f7ac7f8 --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/networking/steam3/NetMsgEventArgs.kt @@ -0,0 +1,15 @@ +package `in`.dragonbra.javasteam.networking.steam3 + +import `in`.dragonbra.javasteam.util.event.EventArgs +import java.net.InetSocketAddress + +/** + * @author lngtr + * @since 2018-02-20 + * + * Represents data that has been received over the network. + */ +@Suppress("unused") +class NetMsgEventArgs(val data: ByteArray, val endPoint: InetSocketAddress?) : EventArgs() { + fun withData(data: ByteArray): NetMsgEventArgs = NetMsgEventArgs(data, endPoint) +} diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/ProtocolTypes.java b/src/main/java/in/dragonbra/javasteam/networking/steam3/ProtocolTypes.java deleted file mode 100644 index 6233f696e..000000000 --- a/src/main/java/in/dragonbra/javasteam/networking/steam3/ProtocolTypes.java +++ /dev/null @@ -1,46 +0,0 @@ -package in.dragonbra.javasteam.networking.steam3; - -import java.util.EnumSet; - -/** - * @author lngtr - * @since 2018-02-20 - */ -public enum ProtocolTypes { - - TCP(1), - - UDP(1 << 1), - - WEB_SOCKET(1 << 2); - - public static final EnumSet ALL = EnumSet.of(TCP, UDP, WEB_SOCKET); - - private final int code; - - ProtocolTypes(int code) { - this.code = code; - } - - public int code() { - return this.code; - } - - public static EnumSet from(int code) { - EnumSet set = EnumSet.noneOf(ProtocolTypes.class); - for (ProtocolTypes e : ProtocolTypes.values()) { - if ((e.code & code) == e.code) { - set.add(e); - } - } - return set; - } - - public static int code(EnumSet flags) { - int code = 0; - for (ProtocolTypes flag : flags) { - code |= flag.code; - } - return code; - } -} diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/ProtocolTypes.kt b/src/main/java/in/dragonbra/javasteam/networking/steam3/ProtocolTypes.kt new file mode 100644 index 000000000..7a6e0c64f --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/networking/steam3/ProtocolTypes.kt @@ -0,0 +1,45 @@ +package `in`.dragonbra.javasteam.networking.steam3 + +import java.util.EnumSet + +/** + * The type of communications protocol to use when communicating with the Steam backend + * + * @author lngtr + * @since 2018-02-20 + */ +enum class ProtocolTypes(private val code: Int) { + // TCP + TCP(1), + + // UDP + UDP(1 shl 1), + + // WebSockets (HTTP / TLS) + WEB_SOCKET(1 shl 2), + ; + + fun code(): Int = code + + companion object { + /** + * All available protocol types + */ + @JvmField + val ALL: EnumSet = EnumSet.allOf(ProtocolTypes::class.java) + + @JvmStatic + fun from(code: Int): EnumSet { + val set = EnumSet.noneOf(ProtocolTypes::class.java) + for (e in entries) { + if ((e.code and code) != 0) { + set.add(e) + } + } + return set + } + + @JvmStatic + fun code(flags: EnumSet): Int = flags.fold(0) { acc, flag -> acc or flag.code } + } +} diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/TcpConnection.java b/src/main/java/in/dragonbra/javasteam/networking/steam3/TcpConnection.java index 05fd3a1d8..eaad8be8c 100644 --- a/src/main/java/in/dragonbra/javasteam/networking/steam3/TcpConnection.java +++ b/src/main/java/in/dragonbra/javasteam/networking/steam3/TcpConnection.java @@ -240,19 +240,29 @@ public void run() { byte[] packData; try { + // read the packet off the network packData = readPacket(); - onNetMsgReceived(new NetMsgEventArgs(packData, currentEndPoint)); } catch (IOException e) { logger.debug("Socket exception occurred while reading packet", e); break; } + + try { + onNetMsgReceived(new NetMsgEventArgs(packData, currentEndPoint)); + } catch (Exception e) { + logger.error("Unexpected exception propagated back to NetLoop", e); + } } + // Thread is shutting down, ensure socket is shut down and disposed + boolean userShutdown = cancelRequested && userRequested; + if (cancelRequested) { shutdown(); } - release(cancelRequested && userRequested); + + release(userShutdown); } } } diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/UdpConnection.java b/src/main/java/in/dragonbra/javasteam/networking/steam3/UdpConnection.java index 56b6c7183..65c880aef 100644 --- a/src/main/java/in/dragonbra/javasteam/networking/steam3/UdpConnection.java +++ b/src/main/java/in/dragonbra/javasteam/networking/steam3/UdpConnection.java @@ -358,7 +358,11 @@ private boolean dispatchMessage() { logger.debug("Dispatching message: " + data.length + " bytes"); - onNetMsgReceived(new NetMsgEventArgs(data, currentEndPoint)); + try { + onNetMsgReceived(new NetMsgEventArgs(data, currentEndPoint)); + } catch (Exception e) { + logger.error("Unexpected exception propagated back to NetLoop", e); + } return true; } diff --git a/src/main/java/in/dragonbra/javasteam/networking/steam3/WebSocketConnection.kt b/src/main/java/in/dragonbra/javasteam/networking/steam3/WebSocketConnection.kt index 1f14159ab..923430da6 100644 --- a/src/main/java/in/dragonbra/javasteam/networking/steam3/WebSocketConnection.kt +++ b/src/main/java/in/dragonbra/javasteam/networking/steam3/WebSocketConnection.kt @@ -1,182 +1,227 @@ package `in`.dragonbra.javasteam.networking.steam3 import `in`.dragonbra.javasteam.util.log.LogManager -import io.ktor.client.HttpClient -import io.ktor.client.engine.cio.CIO -import io.ktor.client.plugins.websocket.WebSockets -import io.ktor.client.plugins.websocket.pingInterval -import io.ktor.client.plugins.websocket.webSocketSession -import io.ktor.http.URLProtocol -import io.ktor.http.path -import io.ktor.websocket.Frame -import io.ktor.websocket.WebSocketSession -import io.ktor.websocket.close -import io.ktor.websocket.readBytes -import io.ktor.websocket.readText -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.channels.consumeEach -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch +import okhttp3.HttpUrl +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response +import okhttp3.WebSocket +import okhttp3.WebSocketListener +import okio.ByteString +import okio.ByteString.Companion.toByteString import java.net.InetAddress import java.net.InetSocketAddress -import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicLong -import kotlin.time.DurationUnit -import kotlin.time.toDuration - -class WebSocketConnection : Connection() { +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference + +/** + * A [Connection] to a Steam CM over a secure WebSocket, backed by OkHttp. + * + * @param httpClient The base client to derive the WebSocket client from. It shares the base client's + * connection pool, dispatcher, proxy and interceptors; only the timeouts are overridden. + */ +class WebSocketConnection @JvmOverloads constructor( + private val httpClient: OkHttpClient = OkHttpClient(), +) : Connection() { companion object { private val logger = LogManager.getLogger() - private const val WATCHDOG_TIMEOUT_MS = 30_000L - private val PING_INTERVAL = 30.toDuration(DurationUnit.SECONDS) - private val WATCHDOG_POLL = 5.toDuration(DurationUnit.SECONDS) + + private const val NORMAL_CLOSURE = 1000 } - private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) - private val disconnecting = AtomicBoolean(false) - private val lastFrameTime = AtomicLong(0L) + // The live connection attempt. Every teardown swaps it out, so callbacks from any other context are stale. + private val currentContext = AtomicReference(null) - @Volatile private var client: HttpClient? = null + @Volatile + private var endpoint: InetSocketAddress? = null - @Volatile private var session: WebSocketSession? = null + override val localIP: InetAddress + get() = runCatching { InetAddress.getLocalHost() }.getOrElse { InetAddress.getByAddress(ByteArray(4)) } - @Volatile private var connectionJob: Job? = null + override val currentEndPoint: InetSocketAddress? + get() = endpoint - @Volatile private var endpoint: InetSocketAddress? = null + override val protocolTypes: ProtocolTypes + get() = ProtocolTypes.WEB_SOCKET override fun connect(endPoint: InetSocketAddress, timeout: Int) { - disconnecting.set(false) - connectionJob?.cancel() + val newContext = WebSocketContext() + val oldContext = currentContext.getAndSet(newContext) - connectionJob = scope.launch { - logger.debug("Trying connection to ${endPoint.hostName}:${endPoint.port}") - endpoint = endPoint - lastFrameTime.set(System.currentTimeMillis()) + if (oldContext != null) { + logger.debug("Attempted to connect while already connected. Closing old connection...") + oldContext.release(sendClose = true) + onDisconnected(false) + } - try { - val newClient = HttpClient(CIO) { - install(WebSockets) { - pingInterval = PING_INTERVAL - } - } - client = newClient - - val newSession = newClient.webSocketSession { - url { - host = endPoint.hostName - port = endPoint.port - protocol = URLProtocol.WSS - path("cmsocket/") - } - } - session = newSession - - logger.debug("Connected to ${endPoint.hostName}:${endPoint.port}") - onConnected() + logger.debug("Trying connection to ${endPoint.hostString}:${endPoint.port}") + endpoint = endPoint + + val client = httpClient.newBuilder() + // Max time to open the TCP socket, before TLS and the WebSocket upgrade + .connectTimeout(timeout.toLong(), TimeUnit.MILLISECONDS) + // Max time for the whole handshake; CMs in maintenance may accept TCP and never finish it + .callTimeout(timeout.toLong(), TimeUnit.MILLISECONDS) + // Idle is healthy before logon; CMClient's watchdog decides when silence means dead + .readTimeout(0, TimeUnit.MILLISECONDS) + // CMs never answer WebSocket pings, and OkHttp fails the socket on a missing pong + .pingInterval(0, TimeUnit.MILLISECONDS) + .build() + + // HttpUrl brackets IPv6 literals; OkHttp treats https as wss for WebSockets + val url = HttpUrl.Builder() + .scheme("https") + .host(endPoint.hostString) + .port(endPoint.port) + .addPathSegment("cmsocket") + .addPathSegment("") + .build() + + val request = Request.Builder() + .url(url) + .build() + + newContext.socket = client.newWebSocket(request, newContext) + } - launch { runWatchdog() } + override fun disconnect(userInitiated: Boolean) { + disconnectCore(userInitiated, specificContext = null, sendClose = true) + } - newSession.incoming.consumeEach { frame -> - when (frame) { - is Frame.Binary -> { - lastFrameTime.set(System.currentTimeMillis()) - onNetMsgReceived(NetMsgEventArgs(frame.readBytes(), currentEndPoint)) - } + /** + * Retires [specificContext], or whichever context is live when it is null, and raises Disconnected for it. + * A context can only be retired once, so racing teardowns (server close, send failure, user disconnect) + * raise Disconnected exactly once, and a stale context can never tear down a newer one. + * + * Disconnected is raised before this returns, like TcpConnection. + */ + private fun disconnectCore(userInitiated: Boolean, specificContext: WebSocketContext?, sendClose: Boolean) { + val oldContext = if (specificContext == null) { + currentContext.getAndSet(null) + } else if (currentContext.compareAndSet(specificContext, null)) { + specificContext + } else { + null + } - is Frame.Close -> doDisconnect(false) + if (oldContext == null) { + return + } - is Frame.Ping -> logger.debug("Received ping") + oldContext.release(sendClose) + onDisconnected(userInitiated) + endpoint = null + } - is Frame.Pong -> logger.debug("Received pong") + override fun send(data: ByteArray) { + val context = currentContext.get() + val socket = context?.socket - is Frame.Text -> logger.debug("Received text: ${frame.readText()}") - } - } + if (socket == null) { + logger.debug("Attempted to send ${data.size} bytes while not connected") + return + } - // Session ended without a Close frame - doDisconnect(false) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - logger.error("An error occurred with the WebSocket connection", e) - doDisconnect(false) - } + // OkHttp queues sends in order; false means the socket is closing or the 16 MiB outgoing queue is full + if (!socket.send(data.toByteString())) { + logger.debug("Failed to queue ${data.size} bytes for sending, disconnecting") + disconnectCore(userInitiated = false, specificContext = context, sendClose = false) } } - override fun disconnect(userInitiated: Boolean) { - doDisconnect(userInitiated) - } + /** + * A single connection attempt and its socket. OkHttp delivers its callbacks on the socket's + * reader thread, one at a time and in order. + */ + private inner class WebSocketContext : WebSocketListener() { + + @Volatile + var socket: WebSocket? = null + + // False until the WebSocket upgrade completes + @Volatile + private var opened = false + + private val isCurrent: Boolean + get() = currentContext.get() === this + + fun release(sendClose: Boolean) { + if (sendClose && opened) { + socket?.close(NORMAL_CLOSURE, null) + } else { + // A failed, stalled or half-open socket may never answer a close handshake, so drop it outright + socket?.cancel() + } + } - private fun doDisconnect(userInitiated: Boolean) { - if (!disconnecting.compareAndSet(false, true)) return + override fun onOpen(webSocket: WebSocket, response: Response) { + // OkHttp can open on its own thread before connect() has stored the socket it returned + socket = webSocket - scope.launch { - val currentJob = connectionJob - val currentSession = session - val currentClient = client - connectionJob = null - session = null - client = null + if (!isCurrent) { + webSocket.cancel() + return + } + + val ep = endpoint + logger.debug("Connected to ${ep?.hostString}:${ep?.port} using ${response.handshake?.tlsVersion}") + + opened = true try { - currentSession?.close() + onConnected() } catch (e: Exception) { - logger.debug("Error closing WebSocket session: ${e.message}") + logger.error("Exception while setting up connection to ${ep?.hostString}:${ep?.port}", e) + disconnectCore(userInitiated = false, specificContext = this, sendClose = true) + } + } + + override fun onMessage(webSocket: WebSocket, bytes: ByteString) { + if (!isCurrent || bytes.size == 0) { + return } + + // A throwing handler must not take the socket down with it try { - currentClient?.close() + onNetMsgReceived(NetMsgEventArgs(bytes.toByteArray(), endpoint)) } catch (e: Exception) { - logger.debug("Error closing HTTP client: ${e.message}") + logger.error("Unexpected exception propagated back to the read loop", e) } + } - currentJob?.cancel() - currentJob?.join() + override fun onMessage(webSocket: WebSocket, text: String) { + if (!isCurrent) { + return + } - onDisconnected(userInitiated) + // Steam only ever sends binary messages + logger.debug("Received websocket text message, disconnecting") + disconnectCore(userInitiated = false, specificContext = this, sendClose = true) } - } - - private suspend fun runWatchdog() { - while (true) { - delay(WATCHDOG_POLL) - val elapsed = System.currentTimeMillis() - lastFrameTime.get() - when { - elapsed > WATCHDOG_TIMEOUT_MS -> { - logger.error("Watchdog: No response for ${WATCHDOG_TIMEOUT_MS / 1000} seconds, disconnecting") - doDisconnect(false) - return - } + override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { + if (!isCurrent) { + return + } - elapsed > 25_000 -> logger.debug("Watchdog: No response for 25 seconds") + logger.debug("Server is closing the connection: $code $reason") - elapsed > 20_000 -> logger.debug("Watchdog: No response for 20 seconds") + // Answer the close frame, then report the disconnect + disconnectCore(userInitiated = false, specificContext = this, sendClose = true) + } - elapsed > 15_000 -> logger.debug("Watchdog: No response for 15 seconds") - } + override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { + disconnectCore(userInitiated = false, specificContext = this, sendClose = false) } - } - override fun send(data: ByteArray) { - scope.launch { - try { - session?.send(Frame.Binary(true, data)) - } catch (e: Exception) { - logger.error("An error occurred while sending data", e) - doDisconnect(false) + override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { + if (!isCurrent) { + return } + + logger.error("An error occurred with the WebSocket connection", t) + disconnectCore(userInitiated = false, specificContext = this, sendClose = false) } } - - override fun getLocalIP(): InetAddress = InetAddress.getLocalHost() - - override fun getCurrentEndPoint(): InetSocketAddress? = endpoint - - override fun getProtocolTypes(): ProtocolTypes = ProtocolTypes.WEB_SOCKET } diff --git a/src/main/java/in/dragonbra/javasteam/steam/CMClient.java b/src/main/java/in/dragonbra/javasteam/steam/CMClient.java index f67ef1783..451c385dc 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/CMClient.java +++ b/src/main/java/in/dragonbra/javasteam/steam/CMClient.java @@ -34,6 +34,7 @@ import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.EnumSet; +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; /** * This base client handles the underlying connection to a CM server. This class should not be use directly, but through @@ -43,6 +44,9 @@ public abstract class CMClient { private static final Logger logger = LogManager.getLogger(CMClient.class); + private static final AtomicReferenceFieldUpdater CONNECTION = + AtomicReferenceFieldUpdater.newUpdater(CMClient.class, Connection.class, "connection"); + private final SteamConfiguration configuration; @Nullable @@ -79,12 +83,42 @@ public abstract class CMClient { private final ScheduledFunction heartBeatFunc; - private final EventHandler netMsgReceived = (sender, e) -> onClientMsgReceived(getPacketMsg(e.getData())); + // Steam can stop sending during maintenance without closing the connection or logging off, and sends + // still succeed, so silence is the only signal. Heartbeats ask for a reply, so once logged on, a healthy + // connection always has incoming traffic. + @JavaSteamAddition + private final ScheduledFunction watchdogFunc; + + @JavaSteamAddition + private volatile long lastMessageTime; + + private final EventHandler netMsgReceived = (sender, e) -> { + // A released connection can still raise events from its network thread after Disconnected + if (sender != connection) { + return; + } + + lastMessageTime = System.currentTimeMillis(); + + onClientMsgReceived(getPacketMsg(e.getData())); + }; private final EventHandler connected = (sender, e) -> { logger.debug("EventHandler `connected` called"); - getServers().tryMark(connection.getCurrentEndPoint(), connection.getProtocolTypes(), ServerQuality.GOOD); + var currentConnection = connection; + + if (currentConnection != sender) { + return; + } + + var endPoint = currentConnection.getCurrentEndPoint(); + + if (endPoint == null) { + logger.debug("No connection endpoint after connecting - cannot update server list"); + } else { + getServers().tryMark(endPoint, currentConnection.getProtocolTypes(), ServerQuality.GOOD); + } isConnected = true; @@ -102,24 +136,32 @@ public void handleEvent(Object sender, DisconnectedEventArgs e) { logger.debug("EventHandler `disconnected` called. User Initiated: " + e.isUserInitiated() + ", Expected Disconnection: " + expectDisconnection); - isConnected = false; + if (!(sender instanceof Connection conn)) { + return; + } - var conn = connection; - if (conn != null) { - if (!e.isUserInitiated() && !expectDisconnection) { - getServers().tryMark(conn.getCurrentEndPoint(), conn.getProtocolTypes(), ServerQuality.BAD); - } + // Always unsubscribe from the connection that raised this, even if it has already been released + conn.getNetMsgReceived().removeEventHandler(netMsgReceived); + conn.getConnected().removeEventHandler(connected); + conn.getDisconnected().removeEventHandler(this); + + // Connection teardown is asynchronous, so a released connection can report its disconnect + // after a new connection was created. Only release the connection that raised this event. + if (!CONNECTION.compareAndSet(CMClient.this, conn, null)) { + return; + } + + isConnected = false; - conn.getNetMsgReceived().removeEventHandler(netMsgReceived); - conn.getConnected().removeEventHandler(connected); - conn.getDisconnected().removeEventHandler(this); + if (!e.isUserInitiated() && !expectDisconnection) { + getServers().tryMark(conn.getCurrentEndPoint(), conn.getProtocolTypes(), ServerQuality.BAD); } sessionID = null; steamID = null; - connection = null; heartBeatFunc.stop(); + watchdogFunc.stop(); onClientDisconnected(e.isUserInitiated() || expectDisconnection); } @@ -138,6 +180,41 @@ public CMClient(SteamConfiguration configuration) { heartbeat.getBody().setSendReply(true); // Ping Pong send(heartbeat); }, 5000); + + watchdogFunc = new ScheduledFunction(this::checkWatchdog, watchdogPollInterval(configuration.getWatchdogTimeout())); + } + + /** + * Starts the watchdog, if enabled. Silence before now doesn't count. + */ + @JavaSteamAddition + private void startWatchdog() { + if (configuration.getWatchdogTimeout() <= 0) { + return; + } + + lastMessageTime = System.currentTimeMillis(); + watchdogFunc.start(); + } + + @JavaSteamAddition + private void checkWatchdog() { + var timeout = configuration.getWatchdogTimeout(); + var elapsed = System.currentTimeMillis() - lastMessageTime; + + if (elapsed > timeout) { + logger.error("Watchdog: Nothing received for " + elapsed + " ms, disconnecting"); + watchdogFunc.stop(); + disconnect(false); + } else if (elapsed > timeout / 2) { + logger.debug("Watchdog: Nothing received for " + elapsed + " ms"); + } + } + + // Poll often enough to act close to the deadline, without spinning on short (test) timeouts + @JavaSteamAddition + private static long watchdogPollInterval(long timeout) { + return Math.max(50L, Math.min(timeout / 6, 5_000L)); } /** @@ -181,8 +258,6 @@ public void connect(ServerRecord cmServer) { try { disconnect(true); - assert connection == null; - expectDisconnection = false; if (cmServer == null) { @@ -195,13 +270,25 @@ public void connect(ServerRecord cmServer) { return; } - connection = createConnection(cmServer.getProtocolTypes()); - connection.getNetMsgReceived().addEventHandler(netMsgReceived); - connection.getConnected().addEventHandler(connected); - connection.getDisconnected().addEventHandler(disconnected); + // Only use protocols that both the server and the configuration allow + var protocolTypes = EnumSet.copyOf(cmServer.getProtocolTypes()); + protocolTypes.retainAll(configuration.getProtocolTypes()); + + var newConnection = createConnection(protocolTypes); + + // Connection teardown is asynchronous, so the previous connection may not have reported its disconnect yet. + // Its late Disconnected event is ignored by the sender check in the disconnected handler. + var connectionRelease = CONNECTION.getAndSet(this, newConnection); + if (connectionRelease != null) { + logger.debug("Previous connection was not released before connecting"); + } + + newConnection.getNetMsgReceived().addEventHandler(netMsgReceived); + newConnection.getConnected().addEventHandler(connected); + newConnection.getDisconnected().addEventHandler(disconnected); logger.debug(String.format("Connecting to %s with protocol %s, and with connection impl %s", - cmServer.getEndpoint(), cmServer.getProtocolTypes(), connection.getClass().getSimpleName())); - connection.connect(cmServer.getEndpoint()); + cmServer.getEndpoint(), protocolTypes, newConnection.getClass().getSimpleName())); + newConnection.connect(cmServer.getEndpoint(), (int) configuration.getConnectionTimeout()); } catch (Exception e) { logger.debug("Failed to connect to Steam network", e); onClientDisconnected(false); @@ -219,6 +306,7 @@ public void disconnect() { private void disconnect(boolean userInitiated) { synchronized (connectionLock) { heartBeatFunc.stop(); + watchdogFunc.stop(); if (connection != null) { connection.disconnect(userInitiated); @@ -328,7 +416,7 @@ protected void onClientDisconnected(boolean userInitiated) { private Connection createConnection(EnumSet protocol) { IConnectionFactory connectionFactory = configuration.getConnectionFactory(); - Connection connection = connectionFactory.createConnection(configuration, protocol); + Connection connection = connectionFactory.createConnection(configuration, protocol, debugNetworkListener); if (connection == null) { logger.error(String.format("Connection factory returned null connection for protocols %s", protocol)); throw new IllegalArgumentException("Connection factory returned null connection."); @@ -344,7 +432,7 @@ public static IPacketMsg getPacketMsg(byte[] data) { int rawEMsg = 0; try (var buffer = new Buffer().write(data)) { - rawEMsg = buffer.readIntLe(); + rawEMsg = buffer.readIntLe(); } catch (IOException e) { logger.debug("Exception while getting EMsg code", e); } @@ -437,6 +525,9 @@ private void handleLogOnResponse(IPacketMsg packetMsg) { heartBeatFunc.stop(); heartBeatFunc.setDelay(logonResp.getBody().getLegacyOutOfGameHeartbeatSeconds() * 1000L); heartBeatFunc.start(); + + // Heartbeat replies now guarantee traffic, so silence means the connection is dead + startWatchdog(); } else if (logonResponse == EResult.TryAnotherCM || logonResponse == EResult.ServiceUnavailable) { var connection = this.connection; if (connection != null) { @@ -457,6 +548,7 @@ private void handleLoggedOff(IPacketMsg packetMsg) { userCountryCode = null; heartBeatFunc.stop(); + watchdogFunc.stop(); if (packetMsg.isProto()) { ClientMsgProtobuf logoffMsg = new ClientMsgProtobuf<>(CMsgClientLoggedOff.class, packetMsg); 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 5f3cce65d..53adbb1c5 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/authentication/AuthSession.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/authentication/AuthSession.kt @@ -15,6 +15,7 @@ import kotlinx.coroutines.future.await import kotlinx.coroutines.future.future import kotlinx.coroutines.withContext import java.util.concurrent.CompletableFuture +import kotlin.time.Duration.Companion.seconds /** * Represents an authentication session which can be used to finish the authentication and get access tokens. @@ -172,8 +173,8 @@ open class AuthSession( @Throws(AuthenticationException::class) private suspend fun pollDeviceConfirmation(parentScope: CoroutineScope): AuthPollResult { while (true) { + delay(pollingInterval.toLong().seconds) pollAuthSessionStatus(parentScope).await()?.let { return it } - delay(pollingInterval.toLong()) } } diff --git a/src/main/java/in/dragonbra/javasteam/steam/cdn/ClientLancache.kt b/src/main/java/in/dragonbra/javasteam/steam/cdn/ClientLancache.kt index 442920b8a..110f4db1b 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/cdn/ClientLancache.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/cdn/ClientLancache.kt @@ -100,6 +100,8 @@ object ClientLancache { * @return OkHttp Request object configured for Lancache */ fun buildLancacheRequest(server: Server, command: String, query: String? = null): Request { + // SK ClientLancache.cs has 'http'. + @Suppress("HttpUrlsUsage") val urlBuilder = "http://lancache.steamcontent.com:80".toHttpUrl().newBuilder() .addPathSegments(command.trimStart('/')) diff --git a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/PICSProductInfo.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/PICSProductInfo.kt index 7978873b5..3be9f4949 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/PICSProductInfo.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/PICSProductInfo.kt @@ -20,6 +20,23 @@ class PICSProductInfo : CallbackMsg { companion object { private val logger = LogManager.getLogger() + + /** + * Reads a [KeyValue] from a non-empty text buffer, which may end with a null byte. + * @return the parsed [KeyValue]. If the buffer cannot be read, [onError] is called and an empty one is returned. + */ + internal fun readTextBuffer(buffer: ByteArray, onError: (Exception) -> Unit): KeyValue { + val textLength = if (buffer.last() == 0.toByte()) buffer.size - 1 else buffer.size + + return try { + KeyValue().apply { + MemoryStream(buffer, 0, textLength).use { ms -> readAsText(ms) } + } + } catch (e: Exception) { + onError(e) + KeyValue() + } + } } /** @@ -89,25 +106,30 @@ class PICSProductInfo : CallbackMsg { isMissingToken = appInfo.missingToken shaHash = appInfo.sha.toByteArray() - keyValues = KeyValue() - - if (appInfo.hasBuffer() && !appInfo.buffer.isEmpty) { - try { - // we don't want to read the trailing null byte - MemoryStream(appInfo.buffer.toByteArray(), 0, appInfo.buffer.size() - 1).use { ms -> - keyValues.readAsText(ms) - } - } catch (e: IOException) { - logger.error("failed to read buffer", e) + keyValues = if (appInfo.hasBuffer() && !appInfo.buffer.isEmpty) { + readTextBuffer(appInfo.buffer.toByteArray()) { error -> + logger.error("Failed to load text buffer for app $id, change number $changeNumber", error) } + } else { + if (!parentResponse.metaDataOnly && !appInfo.missingToken) { + logger.debug("Empty buffer for app $id, change number $changeNumber") + } + KeyValue() } isOnlyPublic = appInfo.onlyPublic httpHost = parentResponse.httpHost - isUseHttp = httpUri != null && appInfo.size >= parentResponse.httpMinSize + + // a minimum size of zero means HTTP is not available for this response + val httpMinSize = parentResponse.httpMinSize + val httpAvailable = parentResponse.metaDataOnly && httpMinSize > 0 + isUseHttp = httpAvailable && hasValidHttpUri && appInfo.size >= httpMinSize } - constructor(packageInfo: CMsgClientPICSProductInfoResponse.PackageInfo) { + constructor( + parentResponse: CMsgClientPICSProductInfoResponse.Builder, + packageInfo: CMsgClientPICSProductInfoResponse.PackageInfo, + ) { id = packageInfo.packageid changeNumber = packageInfo.changeNumber isMissingToken = packageInfo.missingToken @@ -115,20 +137,26 @@ class PICSProductInfo : CallbackMsg { keyValues = KeyValue() - if (packageInfo.hasBuffer()) { - // we don't want to read the trailing null byte + if (packageInfo.hasBuffer() && packageInfo.buffer.size() >= Int.SIZE_BYTES) { try { - // TODO memory stream like SK? BinaryReader(ByteArrayInputStream(packageInfo.buffer.toByteArray())).use { br -> // steamclient checks this value == 1 before it attempts to read the KV from the buffer // see: CPackageInfo::UpdateFromBuffer(CSHA const&,uint,CUtlBuffer &) - // todo: (SK) we've apparently ignored this with zero ill effects, but perhaps we want to respect it? - br.readInt() - keyValues.tryReadAsBinary(br) + val format = br.readInt() + + if (format != 1) { + logger.debug( + "Unknown package info format $format for package $id, size ${packageInfo.buffer.size()}" + ) + } else if (!keyValues.tryReadAsBinary(br)) { + logger.debug("Failed to parse binary buffer for package $id, change number $changeNumber") + } } } catch (e: IOException) { - logger.error("failed to read buffer", e) + logger.error("Failed to parse binary buffer for package $id, change number $changeNumber", e) } + } else if (!parentResponse.metaDataOnly && !packageInfo.missingToken) { + logger.debug("Empty or truncated buffer for package $id, change number $changeNumber") } } } diff --git a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/SteamApps.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/SteamApps.kt index c2f9a7b82..9da26c0ff 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/SteamApps.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/SteamApps.kt @@ -42,7 +42,6 @@ import `in`.dragonbra.javasteam.types.AsyncJobSingle import `in`.dragonbra.javasteam.types.GameID import `in`.dragonbra.javasteam.util.JavaSteamAddition import `in`.dragonbra.javasteam.util.NetHelpers -import io.ktor.client.request.request /** * This handler is used for interacting with apps and packages on the Steam network. diff --git a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/callback/PICSProductInfoCallback.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/callback/PICSProductInfoCallback.kt index f67cfa25e..c758eb3e8 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/callback/PICSProductInfoCallback.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/callback/PICSProductInfoCallback.kt @@ -58,6 +58,6 @@ class PICSProductInfoCallback(packetMsg: IPacketMsg) : CallbackMsg() { unknownApps = msg.unknownAppidsList apps = msg.appsList.associate { it.appid to PICSProductInfo(msg, it) } - packages = msg.packagesList.associate { it.packageid to PICSProductInfo(it) } + packages = msg.packagesList.associate { it.packageid to PICSProductInfo(msg, it) } } } diff --git a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/callback/PrivateBetaCallback.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/callback/PrivateBetaCallback.kt index f92783c8a..069ef6efd 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/callback/PrivateBetaCallback.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/callback/PrivateBetaCallback.kt @@ -4,9 +4,10 @@ import `in`.dragonbra.javasteam.base.ClientMsgProtobuf import `in`.dragonbra.javasteam.base.IPacketMsg import `in`.dragonbra.javasteam.enums.EResult import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientserverAppinfo.CMsgClientPICSPrivateBetaResponse +import `in`.dragonbra.javasteam.steam.handlers.steamapps.PICSProductInfo import `in`.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackMsg import `in`.dragonbra.javasteam.types.KeyValue -import `in`.dragonbra.javasteam.util.stream.MemoryStream +import `in`.dragonbra.javasteam.util.log.LogManager /** * This callback is received when a private beta request has been completed @@ -34,13 +35,16 @@ class PrivateBetaCallback(packetMsg: IPacketMsg) : CallbackMsg() { result = EResult.from(msg.eresult) - depotSection = KeyValue() - - if (msg.depotSection != null && msg.depotSection.size() > 0) { - // we don't want to read the trailing null byte - MemoryStream(msg.depotSection.toByteArray(), 0, msg.depotSection.size() - 1).use { ms -> - depotSection.readAsText(ms) + depotSection = if (msg.depotSection.isEmpty) { + KeyValue() + } else { + PICSProductInfo.readTextBuffer(msg.depotSection.toByteArray()) { error -> + logger.error("Failed to load text buffer for depot section", error) } } } + + companion object { + private val logger = LogManager.getLogger() + } } diff --git a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/SteamCloud.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/SteamCloud.kt index a91ca7533..6d5f3b68e 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/SteamCloud.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/SteamCloud.kt @@ -6,18 +6,10 @@ import `in`.dragonbra.javasteam.enums.EOSType import `in`.dragonbra.javasteam.enums.EPlatformType import `in`.dragonbra.javasteam.enums.EResult import `in`.dragonbra.javasteam.enums.ESteamRealm -import `in`.dragonbra.javasteam.protobufs.steamclient.Enums.EBluetoothDeviceType -import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientmetricsSteamclient.CClientMetrics_CloudAppSyncStats_Notification -import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesCloudSteamclient -import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesCloudSteamclient.CCloud_AppExitSyncDone_Notification -import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesCloudSteamclient.CCloud_AppLaunchIntent_Request -import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesCloudSteamclient.CCloud_BeginAppUploadBatch_Request -import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesCloudSteamclient.CCloud_ClientBeginFileUpload_Request -import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesCloudSteamclient.CCloud_ClientCommitFileUpload_Request -import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesCloudSteamclient.CCloud_ClientFileDownload_Request -import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesCloudSteamclient.CCloud_CompleteAppUploadBatch_Request -import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesCloudSteamclient.CCloud_ExternalStorageTransferReport_Notification -import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesCloudSteamclient.CCloud_GetAppFileChangelist_Request +import `in`.dragonbra.javasteam.protobufs.steamclient.* +import `in`.dragonbra.javasteam.protobufs.steamclient.Enums.* +import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientmetricsSteamclient.* +import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesCloudSteamclient.* import `in`.dragonbra.javasteam.rpc.service.ClientMetrics import `in`.dragonbra.javasteam.rpc.service.Cloud import `in`.dragonbra.javasteam.steam.authentication.AuthSession @@ -29,12 +21,10 @@ import `in`.dragonbra.javasteam.steam.handlers.steamunifiedmessages.SteamUnified import `in`.dragonbra.javasteam.types.UGCHandle import `in`.dragonbra.javasteam.util.HardwareUtils import `in`.dragonbra.javasteam.util.JavaSteamAddition -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.future.await -import kotlinx.coroutines.future.future -import java.util.Date -import java.util.concurrent.CompletableFuture +import kotlinx.coroutines.* +import kotlinx.coroutines.future.* +import java.util.* +import java.util.concurrent.* /** * This handler is used for interacting with remote storage and user generated content. @@ -64,7 +54,7 @@ class SteamCloud : ClientMsgHandler() { @JvmOverloads fun requestUGCDetails( ugcId: UGCHandle, - parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + parentScope: CoroutineScope = client.defaultScope, ): CompletableFuture = parentScope.future { requestUGCDetails(ugcId) } /** @@ -97,7 +87,7 @@ class SteamCloud : ClientMsgHandler() { fun getSingleFileInfo( appId: Int, filename: String, - parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + parentScope: CoroutineScope = client.defaultScope, ): CompletableFuture = parentScope.future { getSingleFileInfo(appId, filename) } /** @@ -132,7 +122,7 @@ class SteamCloud : ClientMsgHandler() { fun shareFile( appId: Int, filename: String, - parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + parentScope: CoroutineScope = client.defaultScope, ): CompletableFuture = parentScope.future { shareFile(appId, filename) } /** @@ -167,7 +157,7 @@ class SteamCloud : ClientMsgHandler() { fun getAppFileListChange( appId: Int, syncedChangeNumber: Long = 0, - parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + parentScope: CoroutineScope = client.defaultScope, ): CompletableFuture = parentScope.future { val request = CCloud_GetAppFileChangelist_Request.newBuilder().apply { this.appid = appId @@ -195,7 +185,7 @@ class SteamCloud : ClientMsgHandler() { fileName: String, realm: ESteamRealm = ESteamRealm.SteamGlobal, forceProxy: Boolean = false, - parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + parentScope: CoroutineScope = client.defaultScope, ): CompletableFuture = parentScope.future { val request = CCloud_ClientFileDownload_Request.newBuilder().apply { this.appid = appId @@ -229,7 +219,7 @@ class SteamCloud : ClientMsgHandler() { filesToDelete: List = emptyList(), clientId: Long, appBuildId: Long, - parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + parentScope: CoroutineScope = client.defaultScope, ): CompletableFuture = parentScope.future { val request = CCloud_BeginAppUploadBatch_Request.newBuilder().apply { this.appid = appId @@ -270,7 +260,7 @@ class SteamCloud : ClientMsgHandler() { isSharedFile: Boolean = false, deprecatedRealm: Int? = null, uploadBatchId: Long, - parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + parentScope: CoroutineScope = client.defaultScope, ): CompletableFuture = parentScope.future { val request = CCloud_ClientBeginFileUpload_Request.newBuilder().apply { this.appid = appId @@ -308,7 +298,7 @@ class SteamCloud : ClientMsgHandler() { appId: Int, fileSha: ByteArray, filename: String, - parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + parentScope: CoroutineScope = client.defaultScope, ): CompletableFuture = parentScope.future { val request = CCloud_ClientCommitFileUpload_Request.newBuilder().apply { this.transferSucceeded = transferSucceeded @@ -335,7 +325,7 @@ class SteamCloud : ClientMsgHandler() { appId: Int, batchId: Long, batchEResult: EResult = EResult.OK, - parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + parentScope: CoroutineScope = client.defaultScope, ): CompletableFuture = parentScope.future { val request = CCloud_CompleteAppUploadBatch_Request.newBuilder().apply { this.appid = appId @@ -455,7 +445,7 @@ class SteamCloud : ClientMsgHandler() { osType: EOSType, // I doubt this is EBluetoothDeviceType, but it's the only enum I can find that has to do with device type deviceType: EBluetoothDeviceType = EBluetoothDeviceType.k_BluetoothDeviceType_Unknown, - parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + parentScope: CoroutineScope = client.defaultScope, ): CompletableFuture> = parentScope.future { val request = CCloud_AppLaunchIntent_Request.newBuilder().apply { this.appid = appId diff --git a/src/main/java/in/dragonbra/javasteam/steam/handlers/steammatchmaking/SteamMatchmaking.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steammatchmaking/SteamMatchmaking.kt index 964f82949..724b67cc4 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/handlers/steammatchmaking/SteamMatchmaking.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steammatchmaking/SteamMatchmaking.kt @@ -106,7 +106,7 @@ class SteamMatchmaking : ClientMsgHandler() { sourceJobID = client.getNextJobID() } - createLobby.body.metadataList.addAll(Lobby.encodeMetadata(metadata)) + createLobby.body.addAllMetadata(Lobby.encodeMetadata(metadata)) send(msg = createLobby, appId = appId) @@ -149,7 +149,7 @@ class SteamMatchmaking : ClientMsgHandler() { sourceJobID = client.getNextJobID() } - setLobbyData.body.metadataList.addAll(Lobby.encodeMetadata(metadata)) + setLobbyData.body.addAllMetadata(Lobby.encodeMetadata(metadata)) send(msg = setLobbyData, appId = appId) @@ -186,7 +186,7 @@ class SteamMatchmaking : ClientMsgHandler() { sourceJobID = client.getNextJobID() } - setLobbyData.body.metadataList.addAll(Lobby.encodeMetadata(metadata)) + setLobbyData.body.addAllMetadata(Lobby.encodeMetadata(metadata)) send(msg = setLobbyData, appId = appId) diff --git a/src/main/java/in/dragonbra/javasteam/steam/steamclient/SteamClient.kt b/src/main/java/in/dragonbra/javasteam/steam/steamclient/SteamClient.kt index 54be73b90..2abe961c9 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/steamclient/SteamClient.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/steamclient/SteamClient.kt @@ -33,6 +33,7 @@ import `in`.dragonbra.javasteam.util.log.LogManager import `in`.dragonbra.javasteam.util.log.Logger import kotlinx.coroutines.* import kotlinx.coroutines.channels.* +import kotlinx.coroutines.future.future import java.io.Closeable import java.util.* import java.util.concurrent.* @@ -208,17 +209,13 @@ class SteamClient @JvmOverloads constructor( * [CompletableFuture.get] to block. * @return A future that resolves to the next callback in the queue. */ - fun waitForCallbackFuture(): CompletableFuture { - val future = CompletableFuture() - defaultScope.launch { - try { - future.complete(callbackQueue.receive()) - } catch (e: Exception) { - future.completeExceptionally(e) - } + fun waitForCallbackFuture(): CompletableFuture = + // Undispatched, so the receiver is registered before the future is returned. Otherwise a future + // that is canceled right away could still take (and lose) a callback posted in the meantime. + defaultScope.future(start = CoroutineStart.UNDISPATCHED) { + ensureActive() // An undispatched start runs even after close(), so fail here instead. + callbackQueue.receive() } - return future - } /** * Returns a [CompletableFuture] that completes with the next callback posted to the queue, @@ -230,15 +227,10 @@ class SteamClient @JvmOverloads constructor( if (timeout <= 0L) { return CompletableFuture.completedFuture(callbackQueue.tryReceive().getOrNull()) } - val future = CompletableFuture() - defaultScope.launch { - try { - future.complete(withTimeoutOrNull(timeout.milliseconds) { callbackQueue.receive() }) - } catch (e: Exception) { - future.completeExceptionally(e) - } + return defaultScope.future(start = CoroutineStart.UNDISPATCHED) { + ensureActive() + withTimeoutOrNull(timeout.milliseconds) { callbackQueue.receive() } } - return future } /** diff --git a/src/main/java/in/dragonbra/javasteam/steam/steamclient/callbackmgr/Callback.kt b/src/main/java/in/dragonbra/javasteam/steam/steamclient/callbackmgr/Callback.kt index 6ac12d5db..64f6b26bc 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/steamclient/callbackmgr/Callback.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/steamclient/callbackmgr/Callback.kt @@ -1,7 +1,6 @@ package `in`.dragonbra.javasteam.steam.steamclient.callbackmgr import `in`.dragonbra.javasteam.types.JobID -import `in`.dragonbra.javasteam.util.compat.Consumer import java.io.Closeable @Suppress("unused") diff --git a/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/ISteamConfigurationBuilder.kt b/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/ISteamConfigurationBuilder.kt index 9c91907a4..a0b3be428 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/ISteamConfigurationBuilder.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/ISteamConfigurationBuilder.kt @@ -5,6 +5,7 @@ import `in`.dragonbra.javasteam.enums.EUniverse import `in`.dragonbra.javasteam.networking.steam3.IConnectionFactory import `in`.dragonbra.javasteam.networking.steam3.ProtocolTypes import `in`.dragonbra.javasteam.steam.discovery.IServerListProvider +import `in`.dragonbra.javasteam.util.JavaSteamAddition import okhttp3.OkHttpClient import java.util.* @@ -39,6 +40,18 @@ interface ISteamConfigurationBuilder { */ fun withConnectionTimeout(connectionTimeout: Long): ISteamConfigurationBuilder + /** + * Configures how long a logged on connection may go without receiving anything before it is considered + * dead and disconnected. Steam can stop sending during maintenance without closing the connection, + * and heartbeat replies are the only traffic guaranteed on a healthy one, so the watchdog only runs + * between a successful logon and logging off. + * + * @param watchdogTimeout The timeout in milliseconds, or 0 to disable the watchdog. + * @return A builder with modified configuration. + */ + @JavaSteamAddition + fun withWatchdogTimeout(watchdogTimeout: Long): ISteamConfigurationBuilder + /** * Configures this [SteamConfiguration] with custom HTTP behaviour. * diff --git a/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/SteamConfiguration.kt b/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/SteamConfiguration.kt index 44a7c41a3..4f49a0f2c 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/SteamConfiguration.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/SteamConfiguration.kt @@ -8,6 +8,7 @@ import `in`.dragonbra.javasteam.steam.discovery.IServerListProvider import `in`.dragonbra.javasteam.steam.discovery.SmartCMServerList import `in`.dragonbra.javasteam.steam.steamclient.SteamClient import `in`.dragonbra.javasteam.steam.webapi.WebAPI +import `in`.dragonbra.javasteam.util.JavaSteamAddition import `in`.dragonbra.javasteam.util.compat.Consumer import okhttp3.OkHttpClient import java.util.* @@ -54,6 +55,14 @@ class SteamConfiguration internal constructor(private val state: SteamConfigurat val connectionTimeout: Long get() = state.connectionTimeout + /** + * How long a logged on connection may go without receiving anything before it is disconnected, + * in milliseconds. 0 disables the watchdog. + */ + @JavaSteamAddition + val watchdogTimeout: Long + get() = state.watchdogTimeout + /** * The http client */ diff --git a/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/SteamConfigurationBuilder.kt b/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/SteamConfigurationBuilder.kt index c275477a6..cb5fcde76 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/SteamConfigurationBuilder.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/SteamConfigurationBuilder.kt @@ -7,6 +7,7 @@ import `in`.dragonbra.javasteam.networking.steam3.ProtocolTypes import `in`.dragonbra.javasteam.steam.discovery.IServerListProvider import `in`.dragonbra.javasteam.steam.discovery.MemoryServerListProvider import `in`.dragonbra.javasteam.steam.webapi.WebAPI +import `in`.dragonbra.javasteam.util.JavaSteamAddition import okhttp3.OkHttpClient import java.util.* @@ -35,6 +36,13 @@ class SteamConfigurationBuilder : ISteamConfigurationBuilder { return this } + @JavaSteamAddition + override fun withWatchdogTimeout(watchdogTimeout: Long): ISteamConfigurationBuilder { + require(watchdogTimeout >= 0) { "watchdogTimeout must not be negative" } + state.watchdogTimeout = watchdogTimeout + return this + } + override fun withHttpClient(httpClient: OkHttpClient): ISteamConfigurationBuilder { state.httpClient = httpClient return this @@ -86,6 +94,12 @@ class SteamConfigurationBuilder : ISteamConfigurationBuilder { } companion object { + /** + * The default for [withWatchdogTimeout], in milliseconds. + */ + @JavaSteamAddition + const val DEFAULT_WATCHDOG_TIMEOUT: Long = 30_000L + @JvmStatic fun createDefaultState(): SteamConfigurationState = SteamConfigurationState( connectionFactory = IConnectionFactory.DEFAULT, @@ -105,6 +119,7 @@ class SteamConfigurationBuilder : ISteamConfigurationBuilder { webAPIBaseAddress = WebAPI.DEFAULT_BASE_ADDRESS, cellID = 0, webAPIKey = null, + watchdogTimeout = DEFAULT_WATCHDOG_TIMEOUT, ) } } diff --git a/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/SteamConfigurationState.kt b/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/SteamConfigurationState.kt index 00bf1ff47..5abe3c01c 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/SteamConfigurationState.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/steamclient/configuration/SteamConfigurationState.kt @@ -5,6 +5,7 @@ import `in`.dragonbra.javasteam.enums.EUniverse import `in`.dragonbra.javasteam.networking.steam3.IConnectionFactory import `in`.dragonbra.javasteam.networking.steam3.ProtocolTypes import `in`.dragonbra.javasteam.steam.discovery.IServerListProvider +import `in`.dragonbra.javasteam.util.JavaSteamAddition import okhttp3.OkHttpClient import java.util.* @@ -24,4 +25,6 @@ data class SteamConfigurationState( var universe: EUniverse, var webAPIBaseAddress: String, var webAPIKey: String?, + @JavaSteamAddition + var watchdogTimeout: Long = SteamConfigurationBuilder.DEFAULT_WATCHDOG_TIMEOUT, ) diff --git a/src/main/java/in/dragonbra/javasteam/types/AsyncJob.kt b/src/main/java/in/dragonbra/javasteam/types/AsyncJob.kt index f84e42fa9..649f8f6b9 100644 --- a/src/main/java/in/dragonbra/javasteam/types/AsyncJob.kt +++ b/src/main/java/in/dragonbra/javasteam/types/AsyncJob.kt @@ -2,7 +2,9 @@ package `in`.dragonbra.javasteam.types import `in`.dragonbra.javasteam.steam.steamclient.SteamClient import `in`.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackMsg -import java.time.Instant +import java.util.concurrent.atomic.AtomicLong +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.TimeSource /** * The base class for awaitable versions of a [JobID]. @@ -13,12 +15,22 @@ import java.time.Instant */ abstract class AsyncJob(val client: SteamClient, val jobID: JobID) { - @Volatile private var jobStart = Instant.now() + // Monotonic, so a wall clock adjustment can neither expire a job early nor keep it alive + private val jobStart = TimeSource.Monotonic.markNow() - @Volatile var timeout: Long = 10000 // 10 Seconds + // Heartbeats arrive on the network thread while callers may set the timeout from any other + private val timeoutMillis = AtomicLong(DEFAULT_TIMEOUT_MS) + + /** + * The period of time, in milliseconds, before this job is considered timed out and is canceled. + * By default this is 10 seconds. + */ + var timeout: Long + get() = timeoutMillis.get() + set(value) = timeoutMillis.set(value) val isTimedOut: Boolean - get() = Instant.now() >= jobStart.plusMillis(timeout) + get() = jobStart.elapsedNow() >= timeout.milliseconds protected fun registerJob(client: SteamClient) { client.startJob(this) @@ -29,6 +41,10 @@ abstract class AsyncJob(val client: SteamClient, val jobID: JobID) { abstract fun setFailed(dueToRemoteFailure: Boolean) fun heartbeat() { - timeout += 10000 + timeoutMillis.addAndGet(DEFAULT_TIMEOUT_MS) + } + + private companion object { + const val DEFAULT_TIMEOUT_MS = 10_000L } } diff --git a/src/main/java/in/dragonbra/javasteam/types/AsyncJobMultiple.kt b/src/main/java/in/dragonbra/javasteam/types/AsyncJobMultiple.kt index 7e433f13b..849c7ff5a 100644 --- a/src/main/java/in/dragonbra/javasteam/types/AsyncJobMultiple.kt +++ b/src/main/java/in/dragonbra/javasteam/types/AsyncJobMultiple.kt @@ -4,7 +4,8 @@ import `in`.dragonbra.javasteam.steam.steamclient.AsyncJobFailedException import `in`.dragonbra.javasteam.steam.steamclient.SteamClient import `in`.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackMsg import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.future.await +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.future.asCompletableFuture import java.util.* import java.util.concurrent.CompletableFuture @@ -24,7 +25,10 @@ class AsyncJobMultiple( var results: List = listOf(), ) - private val future = CompletableFuture>() + private val deferred = CompletableDeferred>() + + // One view of the deferred, so every toFuture() call hands back the same instance + private val future: CompletableFuture> = deferred.asCompletableFuture() private val results = mutableListOf() @@ -35,9 +39,19 @@ class AsyncJobMultiple( @Deprecated("Use toFuture() instead", ReplaceWith("toFuture()")) fun toDeferred(): CompletableFuture> = toFuture() + /** + * Java interop. Always returns the same future. + * + * Non-async continuations (`thenAccept`, `thenApply`, ...) run on the thread that completes the job, + * which is normally the network thread. Use the `*Async` variants for anything slow or blocking. + */ fun toFuture(): CompletableFuture> = future - suspend fun await(): ResultSet = future.await() + /** + * Suspends until this job completes. The caller resumes on its own dispatcher, + * not on the network thread that completed the job. + */ + suspend fun await(): ResultSet = deferred.await() @Suppress("unused") @Throws(CancellationException::class) @@ -51,7 +65,7 @@ class AsyncJobMultiple( results.add(callbackMsg) return if (finishCondition(callbackMsg) == true) { - future.complete( + deferred.complete( ResultSet( complete = true, failed = false, @@ -71,13 +85,13 @@ class AsyncJobMultiple( // if we have zero callbacks in our result set, we cancel this task if (dueToRemoteFailure) { // if we're canceling with a remote failure, post a job failure exception - future.completeExceptionally(AsyncJobFailedException()) + deferred.completeExceptionally(AsyncJobFailedException()) } else { // otherwise, normal task cancellation for timeouts - future.cancel(true) + deferred.cancel() } } else { - future.complete(ResultSet(false, dueToRemoteFailure, Collections.unmodifiableList(results.toList()))) + 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 2bea7c786..16f06046d 100644 --- a/src/main/java/in/dragonbra/javasteam/types/AsyncJobSingle.kt +++ b/src/main/java/in/dragonbra/javasteam/types/AsyncJobSingle.kt @@ -16,15 +16,26 @@ class AsyncJobSingle(client: SteamClient, jobId: JobID) : Async private val deferred = CompletableDeferred() + // One view of the deferred, so every toFuture() call hands back the same instance + private val future: CompletableFuture = deferred.asCompletableFuture() + init { registerJob(client) } - // Kotlin + /** + * Suspends until this job completes. The caller resumes on its own dispatcher, + * not on the network thread that completed the job. + */ suspend fun await(): T = deferred.await() - // Java interop - fun toFuture(): CompletableFuture = deferred.asCompletableFuture() + /** + * Java interop. Always returns the same future. + * + * Non-async continuations (`thenAccept`, `thenApply`, ...) run on the thread that completes the job, + * which is normally the network thread. Use the `*Async` variants for anything slow or blocking. + */ + fun toFuture(): CompletableFuture = future @Suppress("unused") @Throws(ExecutionException::class, InterruptedException::class) diff --git a/src/main/java/in/dragonbra/javasteam/types/DepotManifest.kt b/src/main/java/in/dragonbra/javasteam/types/DepotManifest.kt index 102336873..485190bda 100644 --- a/src/main/java/in/dragonbra/javasteam/types/DepotManifest.kt +++ b/src/main/java/in/dragonbra/javasteam/types/DepotManifest.kt @@ -249,7 +249,6 @@ class DepotManifest { } } - @OptIn(ExperimentalStdlibApi::class) private fun internalDeserialize(stream: InputStream) { var payload: ContentManifestPayload? = null var metadata: ContentManifestMetadata? = null diff --git a/src/main/java/in/dragonbra/javasteam/types/FileData.kt b/src/main/java/in/dragonbra/javasteam/types/FileData.kt index 41ee3ead4..65f2624a0 100644 --- a/src/main/java/in/dragonbra/javasteam/types/FileData.kt +++ b/src/main/java/in/dragonbra/javasteam/types/FileData.kt @@ -72,7 +72,7 @@ data class FileData( result = 31 * result + chunks.hashCode() result = 31 * result + flags.hashCode() result = 31 * result + fileHash.contentHashCode() - result = 31 * result + (linkTarget?.hashCode() ?: 0) + result = 31 * result + linkTarget.hashCode() return result } } diff --git a/src/main/java/in/dragonbra/javasteam/types/GlobalID.kt b/src/main/java/in/dragonbra/javasteam/types/GlobalID.kt index ecb31a939..db217bace 100644 --- a/src/main/java/in/dragonbra/javasteam/types/GlobalID.kt +++ b/src/main/java/in/dragonbra/javasteam/types/GlobalID.kt @@ -28,7 +28,7 @@ open class GlobalID @JvmOverloads constructor(gid: Long = Long.MAX_VALUE) { var startTime: Date get() { val startTimeS = gidBits.getMask(20, 0x3FFFFFFFL) - return Date(startTimeS * 1000L) + return Date(1104537600000L + startTimeS * 1000L) } set(startTime) { val startTimeS: Long = (startTime.time - 1104537600000L) / 1000L diff --git a/src/main/java/in/dragonbra/javasteam/types/KVTextReader.kt b/src/main/java/in/dragonbra/javasteam/types/KVTextReader.kt index a27afc72d..e1c4c75c4 100644 --- a/src/main/java/in/dragonbra/javasteam/types/KVTextReader.kt +++ b/src/main/java/in/dragonbra/javasteam/types/KVTextReader.kt @@ -21,7 +21,7 @@ internal constructor( companion object { @JvmField - val ESCAPED_MAPPING = mapOf( + val ESCAPED_MAPPING = mapOf( '\\' to '\\', 'n' to '\n', 'r' to '\r', @@ -57,9 +57,11 @@ internal constructor( val wasQuoted = Passable(false) val wasConditional = Passable(false) + @Suppress("CanBeVal") var currentKey: KeyValue? = kv do { + @Suppress("CanBeVal") var s = readToken(wasQuoted, wasConditional) if (s.isNullOrEmpty()) { @@ -201,7 +203,6 @@ internal constructor( } var bConditionalStart = false - val count = 0 sb.clear() while (!endOfStream) { next = peek.toChar() @@ -222,13 +223,7 @@ internal constructor( break } - // count isn't used anymore, but still defined in SK. - @Suppress("KotlinConstantConditions") - if (count < 1023) { - sb.append(next) - } else { - throw IOException("ReadToken overflow") - } + sb.append(next) read() } diff --git a/src/main/java/in/dragonbra/javasteam/types/Steam3Manifest.kt b/src/main/java/in/dragonbra/javasteam/types/Steam3Manifest.kt index 63377a440..e94590628 100644 --- a/src/main/java/in/dragonbra/javasteam/types/Steam3Manifest.kt +++ b/src/main/java/in/dragonbra/javasteam/types/Steam3Manifest.kt @@ -2,6 +2,7 @@ package `in`.dragonbra.javasteam.types import `in`.dragonbra.javasteam.enums.EDepotFileFlag import `in`.dragonbra.javasteam.util.stream.BinaryReader +import java.io.IOException import java.nio.charset.StandardCharsets import java.util.Date import java.util.EnumSet @@ -106,13 +107,19 @@ class Steam3Manifest { var i = fileMappingSize while (i > 0) { - val start = ds.position.toLong() + val start = ds.position val fileMapping = FileMapping() fileMapping.deserialize(ds) mapping.add(fileMapping) - i -= (ds.position - start.toInt()) + val consumed = ds.position - start + + if (consumed > i) { + throw IOException("data is not a valid steam3 manifest: file mapping exceeds the declared size.") + } + + i -= consumed } } } diff --git a/src/main/java/in/dragonbra/javasteam/util/Annotation.kt b/src/main/java/in/dragonbra/javasteam/util/Annotation.kt index a40d5d6de..e20dfb1cd 100644 --- a/src/main/java/in/dragonbra/javasteam/util/Annotation.kt +++ b/src/main/java/in/dragonbra/javasteam/util/Annotation.kt @@ -10,7 +10,8 @@ package `in`.dragonbra.javasteam.util AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY, - AnnotationTarget.CONSTRUCTOR + AnnotationTarget.CONSTRUCTOR, + AnnotationTarget.FIELD, ) @Retention(AnnotationRetention.SOURCE) // Only in source @MustBeDocumented diff --git a/src/main/java/in/dragonbra/javasteam/util/Utils.kt b/src/main/java/in/dragonbra/javasteam/util/Utils.kt index 2dac4e3d6..7c7a750c7 100644 --- a/src/main/java/in/dragonbra/javasteam/util/Utils.kt +++ b/src/main/java/in/dragonbra/javasteam/util/Utils.kt @@ -12,7 +12,7 @@ object Utils { private val javaRuntime: String? = getSystemProperty("java.runtime.name") - private val winOsMap: Map = linkedMapOf( + private val winOsTypes: List> = listOf( SystemUtils.IS_OS_WINDOWS_95 to EOSType.Win95, SystemUtils.IS_OS_WINDOWS_98 to EOSType.Win98, SystemUtils.IS_OS_WINDOWS_ME to EOSType.WinME, @@ -32,7 +32,10 @@ object Utils { checkOS("Windows Server 2022", "10.0") to EOSType.Win2022, ) - private val osxOsMap: Map = linkedMapOf( + // Big Sur point releases (11.1 and later) have their own EOSType + private val isMacOS111: Boolean = checkOS("Mac OS X", "11.") && !checkOS("Mac OS X", "11.0") + + private val osxOsTypes: List> = listOf( SystemUtils.IS_OS_MAC_OSX_TIGER to EOSType.MacOS104, SystemUtils.IS_OS_MAC_OSX_LEOPARD to EOSType.MacOS105, SystemUtils.IS_OS_MAC_OSX_SNOW_LEOPARD to EOSType.MacOS106, @@ -45,11 +48,24 @@ object Utils { SystemUtils.IS_OS_MAC_OSX_HIGH_SIERRA to EOSType.Macos1013, SystemUtils.IS_OS_MAC_OSX_MOJAVE to EOSType.Macos1014, SystemUtils.IS_OS_MAC_OSX_CATALINA to EOSType.Macos1015, - SystemUtils.IS_OS_MAC_OSX_BIG_SUR to EOSType.MacOS11, + // 10.16 and later are what macOS reports to apps linked against an older SDK + checkOS("Mac OS X", "10.16") to EOSType.MacOS1016, + checkOS("Mac OS X", "10.17") to EOSType.MacOS1017, + checkOS("Mac OS X", "10.18") to EOSType.MacOS1018, + checkOS("Mac OS X", "10.19") to EOSType.MacOS1019, + checkOS("Mac OS X", "10.20") to EOSType.MacOS1020, + checkOS("Mac OS X", "10.21") to EOSType.MacOS1021, + checkOS("Mac OS X", "10.22") to EOSType.MacOS1022, + checkOS("Mac OS X", "10.23") to EOSType.MacOS1023, + (SystemUtils.IS_OS_MAC_OSX_BIG_SUR && !isMacOS111) to EOSType.MacOS11, + isMacOS111 to EOSType.MacOS111, SystemUtils.IS_OS_MAC_OSX_MONTEREY to EOSType.MacOS12, SystemUtils.IS_OS_MAC_OSX_VENTURA to EOSType.MacOS13, SystemUtils.IS_OS_MAC_OSX_SONOMA to EOSType.MacOS14, SystemUtils.IS_OS_MAC_OSX_SEQUOIA to EOSType.MacOS15, + checkOS("Mac OS X", "26") to EOSType.MacOS26, // Tahoe + checkOS("Mac OS X", "27") to EOSType.MacOS27, // Golden Gate + checkOS("Mac OS X", "28") to EOSType.MacOS28, // Codename: Poppy ) private val linuxOsMap: Map = linkedMapOf( @@ -80,61 +96,30 @@ object Utils { ) // Sorted in history order by each OS release. + // Android also reports itself as Linux, so it has to be checked before Linux. @JvmStatic - fun getOSType(): EOSType { - // Windows - if (SystemUtils.IS_OS_WINDOWS) { - for ((matched, type) in winOsMap) { - if (matched) { - return type - } - } - - return EOSType.WinUnknown - } - - // Mac OS - if (SystemUtils.IS_OS_MAC) { - for ((matched, type) in osxOsMap) { - if (matched) { - return type - } - } - - return EOSType.MacOSUnknown - } - - // Android - if (javaRuntime?.startsWith("Android") == true) { - return EOSType.AndroidUnknown - } - - // Linux - if (SystemUtils.IS_OS_LINUX) { - val linuxOsVersion = getSystemProperty("os.version") ?: return EOSType.LinuxUnknown - - val osVersion = linuxOsVersion.split(".") - if (osVersion.size < 2) { - return EOSType.LinuxUnknown - } - - val version = "${osVersion[0]}.${osVersion[1]}" - - // Found Major/Minor version - linuxOsMap[version]?.let { return it } - - // Found generic Linux version - val majorVersion = "${osVersion[0]}x" - genericLinuxOsMap[majorVersion]?.let { return it } + fun getOSType(): EOSType = when { + SystemUtils.IS_OS_WINDOWS -> winOsTypes.firstMatch() ?: EOSType.WinUnknown + SystemUtils.IS_OS_MAC -> osxOsTypes.firstMatch() ?: EOSType.MacOSUnknown + javaRuntime?.startsWith("Android") == true -> EOSType.AndroidUnknown + SystemUtils.IS_OS_LINUX -> getLinuxOSType() + else -> EOSType.Unknown + } + private fun getLinuxOSType(): EOSType { + val osVersion = getSystemProperty("os.version")?.split(".") ?: return EOSType.LinuxUnknown + if (osVersion.size < 2) { return EOSType.LinuxUnknown } - // Unknown OS - return EOSType.Unknown + // Exact major.minor version first, then the generic major version + return linuxOsMap["${osVersion[0]}.${osVersion[1]}"] + ?: genericLinuxOsMap["${osVersion[0]}x"] + ?: EOSType.LinuxUnknown } - @Suppress("SameParameterValue") + private fun List>.firstMatch(): EOSType? = firstOrNull { it.first }?.second + private fun checkOS(namePrefix: String, versionPrefix: String): Boolean = SystemUtils.OS_NAME.startsWith(namePrefix) && SystemUtils.OS_VERSION.startsWith(versionPrefix) 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 9651393aa..08083784a 100644 --- a/src/main/java/in/dragonbra/javasteam/util/crypto/CryptoHelper.java +++ b/src/main/java/in/dragonbra/javasteam/util/crypto/CryptoHelper.java @@ -320,16 +320,19 @@ public static byte[] symmetricDecryptHMACIV(byte[] input, byte[] key, byte[] hma mac.init(new SecretKeySpec(hmacSecret, "HmacSHA1")); hmacBytes = mac.doFinal(ms.toByteArray()); - for (int i = 0; i < iv.getValue().length - 3; i++) { - if (hmacBytes[i] != iv.getValue()[i]) { - throw new CryptoException("NetFilterEncryption was unable to decrypt packet: HMAC from server did not match computed HMAC."); - } + // Compare in constant time + int hashLength = iv.getValue().length - 3; + if (!MessageDigest.isEqual(Arrays.copyOf(hmacBytes, hashLength), Arrays.copyOf(iv.getValue(), hashLength))) { + throw new CryptoException("NetFilterEncryption was unable to decrypt packet: HMAC from server did not match computed HMAC."); } } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new CryptoException("NetFilterEncryption was unable to decrypt packet", e); } return plaintextData; + } catch (CryptoException e) { + // Let the HMAC mismatch reach the caller instead of being reported as a stream failure + throw e; } catch (Exception e) { throw new RuntimeException("MemoryStream closed"); } diff --git a/src/main/java/in/dragonbra/javasteam/util/event/Event.kt b/src/main/java/in/dragonbra/javasteam/util/event/Event.kt index c11e4f2ea..a3bd659cb 100644 --- a/src/main/java/in/dragonbra/javasteam/util/event/Event.kt +++ b/src/main/java/in/dragonbra/javasteam/util/event/Event.kt @@ -13,6 +13,12 @@ class Event { handlers.remove(handler) } + operator fun plusAssign(handler: EventHandler) = addEventHandler(handler) + + operator fun minusAssign(handler: EventHandler) = removeEventHandler(handler) + + operator fun invoke(sender: Any, e: T) = handleEvent(sender, e) + fun handleEvent(sender: Any, e: T) { handlers.forEach { it.handleEvent(sender, e) } } diff --git a/src/main/java/in/dragonbra/javasteam/util/stream/MemoryStream.java b/src/main/java/in/dragonbra/javasteam/util/stream/MemoryStream.java index fe9277320..4ca28e233 100644 --- a/src/main/java/in/dragonbra/javasteam/util/stream/MemoryStream.java +++ b/src/main/java/in/dragonbra/javasteam/util/stream/MemoryStream.java @@ -302,20 +302,11 @@ public void setPosition(long value) { * reference point and the offset. */ public long seek(long offset, SeekOrigin loc) { - int reference; - switch (loc) { - case BEGIN: - reference = origin; - break; - case CURRENT: - reference = position; - break; - case END: - reference = length; - break; - default: - throw new IllegalArgumentException("loc"); - } + int reference = switch (loc) { + case BEGIN -> origin; + case CURRENT -> position; + case END -> length; + }; if (offset < Integer.MIN_VALUE || offset > Integer.MAX_VALUE) { throw new IllegalArgumentException("offset out of range: " + offset); diff --git a/src/main/steamd/in/dragonbra/javasteam/enums.steamd b/src/main/steamd/in/dragonbra/javasteam/enums.steamd index 2a02fb745..23e5eaa2f 100644 --- a/src/main/steamd/in/dragonbra/javasteam/enums.steamd +++ b/src/main/steamd/in/dragonbra/javasteam/enums.steamd @@ -790,6 +790,12 @@ enum EOSType MacOS14 = -73; MacOS1020 = -72; MacOS15 = -71; + MacOS1021 = -70; + MacOS26 = -69; + MacOS1022 = -68; + MacOS27 = -67; + MacOS1023 = -66; + MacOS28 = -65; MacOSMax = -1; diff --git a/src/test/java/in/dragonbra/javasteam/PacketTests.java b/src/test/java/in/dragonbra/javasteam/PacketTests.java index 607134b33..6751be887 100644 --- a/src/test/java/in/dragonbra/javasteam/PacketTests.java +++ b/src/test/java/in/dragonbra/javasteam/PacketTests.java @@ -28,55 +28,41 @@ */ public class PacketTests { - private static final class TestPacket { - private final EMsg eMsg; - private final byte[] data; - - public TestPacket(EMsg eMsg, byte[] data) { - this.eMsg = eMsg; - this.data = data; - } - + private record TestPacket(EMsg eMsg, byte[] data) { public EMsg getEMsg() { return eMsg; } - - public byte[] getData() { - return data; - } } @SuppressWarnings({"EnumSwitchStatementWhichMissesCases", "SwitchStatementWithTooFewBranches"}) private static Class getCallback(EMsg msg) { - switch (msg) { - case ClientPICSProductInfoResponse: - return PICSProductInfoCallback.class; - default: - return null; - } + return switch (msg) { + case ClientPICSProductInfoResponse -> PICSProductInfoCallback.class; + default -> null; + }; } @SuppressWarnings("DataFlowIssue") @Test public void postsExpectedCallbacks() { - var steamClient = new SteamClient(); + try (var steamClient = new SteamClient()) { + getPackets("in").forEach(packet -> { + var expectedCallback = getCallback(packet.getEMsg()); + Assertions.assertNotNull(expectedCallback); - getPackets("in").forEach(packet -> { - var expectedCallback = getCallback(packet.getEMsg()); - Assertions.assertNotNull(expectedCallback); + var packetMsg = CMClient.getPacketMsg(packet.data()); + Assertions.assertNotNull(packetMsg); - var packetMsg = CMClient.getPacketMsg(packet.getData()); - Assertions.assertNotNull(packetMsg); + Assertions.assertInstanceOf(PacketClientMsgProtobuf.class, packetMsg); - Assertions.assertInstanceOf(PacketClientMsgProtobuf.class, packetMsg); + Assertions.assertNull(steamClient.getCallback()); + steamClient.receiveTestPacketMsg(packetMsg); - Assertions.assertNull(steamClient.getCallback()); - steamClient.receiveTestPacketMsg(packetMsg); - - var callback = steamClient.getCallback(); - Assertions.assertNotNull(callback); - Assertions.assertEquals(expectedCallback, callback.getClass()); - }); + var callback = steamClient.getCallback(); + Assertions.assertNotNull(callback); + Assertions.assertEquals(expectedCallback, callback.getClass()); + }); + } } @SuppressWarnings("SameParameterValue") diff --git a/src/test/java/in/dragonbra/javasteam/TestPackets.java b/src/test/java/in/dragonbra/javasteam/TestPackets.java index 1746b9edc..b2c6e9eb5 100644 --- a/src/test/java/in/dragonbra/javasteam/TestPackets.java +++ b/src/test/java/in/dragonbra/javasteam/TestPackets.java @@ -25,92 +25,50 @@ public abstract class TestPackets { public static byte[] getPacket(EMsg msgType, boolean isProto) { - switch (msgType) { - case ClientLogOnResponse: - return clientLogOnResponse(isProto); - case ClientLoggedOff: - return clientLoggedOff(isProto); - case ClientNewLoginKey: - return clientNewLoginKey(); - case ClientSessionToken: - return clientSessionToken(); - case ClientUpdateMachineAuth: - return clientUpdateMachineAuth(); - case ClientAccountInfo: - return clientAccountInfo(); - case ClientWalletInfoUpdate: - return clientWalletInfoUpdate(); - case ClientRequestWebAPIAuthenticateUserNonceResponse: - return clientRequestWebAPIAuthenticateUserNonceResponse(); - case ClientMarketingMessageUpdate2: - return clientMarketingMessageUpdate2(); - case ClientFriendMsgIncoming: - return clientFriendMsgIncoming(); - case ClientFriendMsgEchoToSender: - return clientFriendMsgEchoToSender(); - case ClientChatGetFriendMessageHistoryResponse: - return clientChatGetFriendMessageHistoryResponse(); - case ClientFriendsList: - return clientFriendsList(); - case ClientPersonaState: - return clientPersonaState(); - case ClientClanState: - return clientClanState(); - case ClientAddFriendResponse: - return clientAddFriendResponse(); - case ClientChatEnter: - return clientChatEnter(); - case ClientChatMsg: - return clientChatMsg(); - case ClientChatMemberInfo: - return clientChatMemberInfo(); - case ClientChatRoomInfo: - return clientChatRoomInfo(); - case ClientChatActionResult: - return clientChatActionResult(); - case ClientChatInvite: - return clientChatInvite(); - case ClientSetIgnoreFriendResponse: - return clientSetIgnoreFriendResponse(); - case ClientFriendProfileInfoResponse: - return clientFriendProfileInfoResponse(); - case ClientPersonaChangeResponse: - return clientPersonaChangeResponse(); - case ClientPlayerNicknameList: - return clientPlayerNicknameList(); - case AMClientSetPlayerNicknameResponse: - return aMClientSetPlayerNicknameResponse(); - case ClientAMGetPersonaNameHistoryResponse: - return clientAMGetPersonaNameHistoryResponse(); - case ClientPICSProductInfoResponse: - return clientPICSProductInfoResponse(); - case ClientUpdateGuestPassesList: - return clientUpdateGuestPassesList(); - case ClientPICSChangesSinceResponse: - return clientPICSChangesSinceResponse(); - case ClientPICSAccessTokenResponse: - return clientPICSAccessTokenResponse(); - case ClientLicenseList: - return clientLicenseList(); - case ClientGameConnectTokens: - return clientGameConnectTokens(); - case ClientVACBanStatus: - return clientVACBanStatus(); - case ClientRequestFreeLicenseResponse: - return clientRequestFreeLicenseResponse(); - case ClientGetAppOwnershipTicketResponse: - return clientGetAppOwnershipTicketResponse(); - case ClientGetDepotDecryptionKeyResponse: - return clientGetDepotDecryptionKeyResponse(); - // case ClientGetCDNAuthTokenResponse: - // return clientGetCDNAuthTokenResponse(); - case ClientCheckAppBetaPasswordResponse: - return clientCheckAppBetaPasswordResponse(); - case ClientGetUserStatsResponse: - return clientGetUserStatsResponse(); - default: - throw new NullPointerException(); - } + return switch (msgType) { + case ClientLogOnResponse -> clientLogOnResponse(isProto); + case ClientLoggedOff -> clientLoggedOff(isProto); + case ClientNewLoginKey -> clientNewLoginKey(); + case ClientSessionToken -> clientSessionToken(); + case ClientUpdateMachineAuth -> clientUpdateMachineAuth(); + case ClientAccountInfo -> clientAccountInfo(); + case ClientWalletInfoUpdate -> clientWalletInfoUpdate(); + case ClientRequestWebAPIAuthenticateUserNonceResponse -> clientRequestWebAPIAuthenticateUserNonceResponse(); + case ClientMarketingMessageUpdate2 -> clientMarketingMessageUpdate2(); + case ClientFriendMsgIncoming -> clientFriendMsgIncoming(); + case ClientFriendMsgEchoToSender -> clientFriendMsgEchoToSender(); + case ClientChatGetFriendMessageHistoryResponse -> clientChatGetFriendMessageHistoryResponse(); + case ClientFriendsList -> clientFriendsList(); + case ClientPersonaState -> clientPersonaState(); + case ClientClanState -> clientClanState(); + case ClientAddFriendResponse -> clientAddFriendResponse(); + case ClientChatEnter -> clientChatEnter(); + case ClientChatMsg -> clientChatMsg(); + case ClientChatMemberInfo -> clientChatMemberInfo(); + case ClientChatRoomInfo -> clientChatRoomInfo(); + case ClientChatActionResult -> clientChatActionResult(); + case ClientChatInvite -> clientChatInvite(); + case ClientSetIgnoreFriendResponse -> clientSetIgnoreFriendResponse(); + case ClientFriendProfileInfoResponse -> clientFriendProfileInfoResponse(); + case ClientPersonaChangeResponse -> clientPersonaChangeResponse(); + case ClientPlayerNicknameList -> clientPlayerNicknameList(); + case AMClientSetPlayerNicknameResponse -> aMClientSetPlayerNicknameResponse(); + case ClientAMGetPersonaNameHistoryResponse -> clientAMGetPersonaNameHistoryResponse(); + case ClientPICSProductInfoResponse -> clientPICSProductInfoResponse(); + case ClientUpdateGuestPassesList -> clientUpdateGuestPassesList(); + case ClientPICSChangesSinceResponse -> clientPICSChangesSinceResponse(); + case ClientPICSAccessTokenResponse -> clientPICSAccessTokenResponse(); + case ClientLicenseList -> clientLicenseList(); + case ClientGameConnectTokens -> clientGameConnectTokens(); + case ClientVACBanStatus -> clientVACBanStatus(); + case ClientRequestFreeLicenseResponse -> clientRequestFreeLicenseResponse(); + case ClientGetAppOwnershipTicketResponse -> clientGetAppOwnershipTicketResponse(); + case ClientGetDepotDecryptionKeyResponse -> clientGetDepotDecryptionKeyResponse(); + // case ClientGetCDNAuthTokenResponse -> clientGetCDNAuthTokenResponse(); + case ClientCheckAppBetaPasswordResponse -> clientCheckAppBetaPasswordResponse(); + case ClientGetUserStatsResponse -> clientGetUserStatsResponse(); + default -> throw new NullPointerException(); + }; } private static byte[] loadFile(String name) { @@ -215,10 +173,7 @@ private static byte[] clientFriendMsgIncoming() { ClientMsgProtobuf msg = new ClientMsgProtobuf<>(CMsgClientFriendMsgIncoming.class, EMsg.ClientFriendMsgIncoming); - try { - msg.getBody().setMessage(ByteString.copyFrom("testmessage", "utf-8")); - } catch (UnsupportedEncodingException ignored) { - } + msg.getBody().setMessage(ByteString.copyFromUtf8("testmessage")); msg.getBody().setSteamidFrom(123); return msg.serialize(); @@ -228,10 +183,7 @@ private static byte[] clientFriendMsgEchoToSender() { ClientMsgProtobuf msg = new ClientMsgProtobuf<>(CMsgClientFriendMsgIncoming.class, EMsg.ClientFriendMsgEchoToSender); - try { - msg.getBody().setMessage(ByteString.copyFrom("testmessage", "utf-8")); - } catch (UnsupportedEncodingException ignored) { - } + msg.getBody().setMessage(ByteString.copyFromUtf8("testmessage")); msg.getBody().setSteamidFrom(123); return msg.serialize(); diff --git a/src/test/java/in/dragonbra/javasteam/networking/steam3/EnvelopeEncryptedConnectionTest.java b/src/test/java/in/dragonbra/javasteam/networking/steam3/EnvelopeEncryptedConnectionTest.java new file mode 100644 index 000000000..215cf3896 --- /dev/null +++ b/src/test/java/in/dragonbra/javasteam/networking/steam3/EnvelopeEncryptedConnectionTest.java @@ -0,0 +1,137 @@ + package in.dragonbra.javasteam.networking.steam3; + +import in.dragonbra.javasteam.TestBase; +import in.dragonbra.javasteam.base.Msg; +import in.dragonbra.javasteam.enums.EResult; +import in.dragonbra.javasteam.enums.EUniverse; +import in.dragonbra.javasteam.generated.MsgChannelEncryptRequest; +import in.dragonbra.javasteam.generated.MsgChannelEncryptResult; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Ported from SteamKit2 EnvelopeEncryptedConnectionFacts (SK PR 1658) + */ +public class EnvelopeEncryptedConnectionTest extends TestBase { + + private static final SecureRandom RANDOM = new SecureRandom(); + + private static final class FakeConnection extends Connection { + private static final InetSocketAddress FAKE_END_POINT = new InetSocketAddress(InetAddress.getLoopbackAddress(), 27015); + + final List disconnects = new ArrayList<>(); + + @Override + public void connect(@NotNull InetSocketAddress endPoint, int timeout) { + } + + @Override + public void disconnect(boolean userInitiated) { + disconnects.add(userInitiated); + } + + @Override + public void send(byte @NotNull [] data) { + } + + @Override + public @NotNull InetAddress getLocalIP() { + return InetAddress.getLoopbackAddress(); + } + + @Override + public @Nullable InetSocketAddress getCurrentEndPoint() { + return FAKE_END_POINT; + } + + @Override + public @Nullable ProtocolTypes getProtocolTypes() { + return ProtocolTypes.TCP; + } + + void raiseConnected() { + onConnected(); + } + + void raiseDisconnected() { + onDisconnected(false); + } + + void raiseNetMsgReceived(byte[] data) { + onNetMsgReceived(new NetMsgEventArgs(data, FAKE_END_POINT)); + } + } + + private static byte[] randomBytes(int length) { + var bytes = new byte[length]; + RANDOM.nextBytes(bytes); + return bytes; + } + + private static byte[] serializeEncryptRequest() throws IOException { + var request = new Msg<>(MsgChannelEncryptRequest.class); + request.getBody().setUniverse(EUniverse.Public); + request.getBody().setProtocolVersion(1); + request.writeBytes(randomBytes(16)); + + return request.serialize(); + } + + private static byte[] serializeEncryptResult() { + var result = new Msg<>(MsgChannelEncryptResult.class); + result.getBody().setResult(EResult.OK); + + return result.serialize(); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1, 15, 16, 20, 48}) + public void disconnectsWhenEncryptedPacketCannotBeDecrypted(int length) throws IOException { + var inner = new FakeConnection(); + var connection = new EnvelopeEncryptedConnection(inner, EUniverse.Public, null); + + var connectedCount = new AtomicInteger(); + var receivedCount = new AtomicInteger(); + connection.getConnected().addEventHandler((sender, e) -> connectedCount.incrementAndGet()); + connection.getNetMsgReceived().addEventHandler((sender, e) -> receivedCount.incrementAndGet()); + + inner.raiseConnected(); + inner.raiseNetMsgReceived(serializeEncryptRequest()); + inner.raiseNetMsgReceived(serializeEncryptResult()); + + Assertions.assertEquals(1, connectedCount.get()); + Assertions.assertTrue(inner.disconnects.isEmpty()); + + var garbage = randomBytes(length); + Assertions.assertDoesNotThrow(() -> inner.raiseNetMsgReceived(garbage)); + + Assertions.assertEquals(0, receivedCount.get()); + Assertions.assertEquals(List.of(false), inner.disconnects); + } + + @Test + public void ignoresPacketsAfterDisconnected() { + var inner = new FakeConnection(); + new EnvelopeEncryptedConnection(inner, EUniverse.Public, null); + + inner.raiseConnected(); + inner.raiseDisconnected(); + + var garbage = randomBytes(48); + Assertions.assertDoesNotThrow(() -> inner.raiseNetMsgReceived(garbage)); + + Assertions.assertTrue(inner.disconnects.isEmpty()); + } +} diff --git a/src/test/java/in/dragonbra/javasteam/networking/steam3/WebSocketConnectionTest.java b/src/test/java/in/dragonbra/javasteam/networking/steam3/WebSocketConnectionTest.java new file mode 100644 index 000000000..b7506bf22 --- /dev/null +++ b/src/test/java/in/dragonbra/javasteam/networking/steam3/WebSocketConnectionTest.java @@ -0,0 +1,680 @@ +package in.dragonbra.javasteam.networking.steam3; + +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import mockwebserver3.SocketEffect; +import okhttp3.OkHttpClient; +import okhttp3.Response; +import okhttp3.WebSocket; +import okhttp3.WebSocketListener; +import okhttp3.tls.HandshakeCertificates; +import okhttp3.tls.HeldCertificate; +import okio.ByteString; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Plays out connection and failure conditions against a local TLS {@link MockWebServer}, + * standing in for a Steam CM over wss://. + * Includes the cases from SteamKit2 WebSocketConnectionFacts (SK PR 1657). + */ +public class WebSocketConnectionTest { + + private static final int CONNECT_TIMEOUT_MS = 500; + + // Generous wait for an event that should happen; short wait to prove one doesn't. + private static final long EXPECT_MS = 5_000L; + + private static final long QUIET_MS = 750L; + + private static HandshakeCertificates serverCertificates; + + private static OkHttpClient trustingClient; + + private MockWebServer server; + + @BeforeAll + static void setUpCertificates() { + var localhost = new HeldCertificate.Builder() + .addSubjectAlternativeName("localhost") + .addSubjectAlternativeName("::1") + .build(); + + serverCertificates = new HandshakeCertificates.Builder() + .heldCertificate(localhost) + .build(); + + var clientCertificates = new HandshakeCertificates.Builder() + .addTrustedCertificate(localhost.certificate()) + .build(); + + trustingClient = new OkHttpClient.Builder() + .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager()) + .build(); + } + + @BeforeEach + void setUp() throws IOException { + server = new MockWebServer(); + server.useHttps(serverCertificates.sslSocketFactory()); + server.start(); + } + + @AfterEach + void tearDown() { + server.close(); + } + + // region Happy path + + @Test + void connectsAndReceivesMessagesInOrder() throws Exception { + var cm = new FakeCm().echo(); + server.enqueue(upgrade(cm)); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + + events.expect("connected"); + assertEquals("/cmsocket/", server.takeRequest().getUrl().encodedPath()); + assertEquals(endpoint(), connection.getCurrentEndPoint()); + + cm.awaitOpen().send(ByteString.of((byte) 1, (byte) 2, (byte) 3)); + assertArrayEquals(new byte[]{1, 2, 3}, events.expectMessage()); + + // Echoed back in the order they were sent + for (byte i = 0; i < 10; i++) { + connection.send(new byte[]{i}); + } + for (byte i = 0; i < 10; i++) { + assertArrayEquals(new byte[]{i}, events.expectMessage()); + } + + connection.disconnect(true); + } + + @Test + void largeMessageArrivesOnce() throws Exception { + var cm = new FakeCm(); + server.enqueue(upgrade(cm)); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("connected"); + + var payload = new byte[1024 * 1024]; + for (int i = 0; i < payload.length; i++) { + payload[i] = (byte) i; + } + cm.awaitOpen().send(ByteString.of(payload)); + + assertArrayEquals(payload, events.expectMessage()); + events.expectQuiet(); + + connection.disconnect(true); + } + + @Test + void sendDeliversASingleBinaryMessage() throws Exception { + var cm = new FakeCm(); + server.enqueue(upgrade(cm)); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("connected"); + cm.awaitOpen(); + + connection.send(new byte[]{9, 8, 7, 6}); + + assertArrayEquals(new byte[]{9, 8, 7, 6}, cm.expectMessage()); + assertNull(cm.received.poll(QUIET_MS, TimeUnit.MILLISECONDS), "unexpected extra message"); + + connection.disconnect(true); + } + + @Test + void textMessageRaisesDisconnected() throws Exception { + var cm = new FakeCm(); + server.enqueue(upgrade(cm)); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("connected"); + + cm.awaitOpen().send("hello"); + + // Not user initiated, so apps reconnect + events.expect("disconnected:false"); + events.expectQuiet(); + } + + @Test + void emptyMessagesAreIgnored() throws Exception { + var cm = new FakeCm(); + server.enqueue(upgrade(cm)); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("connected"); + + var serverSocket = cm.awaitOpen(); + serverSocket.send(ByteString.EMPTY); + serverSocket.send(ByteString.of((byte) 1)); + + // Only the binary message with data surfaces, and the socket stays up + assertArrayEquals(new byte[]{1}, events.expectMessage()); + events.expectQuiet(); + + connection.disconnect(true); + } + + @Test + void idleConnectionStaysUp() throws Exception { + // Connected but not logged on yet, e.g. waiting on the user for a Steam Guard code: nothing guarantees + // traffic, so silence alone must not drop the socket. CMClient's watchdog handles silence after logon. + server.enqueue(upgrade(new FakeCm())); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("connected"); + + Thread.sleep(QUIET_MS * 2); + + events.expectQuiet(); + + connection.disconnect(true); + } + + @Test + void connectsToAnIpv6Address() throws Exception { + var loopback = InetAddress.getByName("::1"); + + var ipv6Server = new MockWebServer(); + + try (ipv6Server) { + ipv6Server.useHttps(serverCertificates.sslSocketFactory()); + try { + ipv6Server.start(loopback, 0); + } catch (IOException e) { + Assumptions.abort("IPv6 loopback unavailable: " + e.getMessage()); + } + ipv6Server.enqueue(upgrade(new FakeCm())); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(new InetSocketAddress(loopback, ipv6Server.getPort()), CONNECT_TIMEOUT_MS); + + // A raw "wss://::1:port" URL is rejected outright; the host needs brackets + events.expect("connected"); + assertEquals("/cmsocket/", ipv6Server.takeRequest().getUrl().encodedPath()); + + connection.disconnect(true); + } + } + + // endregion + + // region Connect failures (maintenance: CMs accept TCP but misbehave) + + @Test + void stalledHandshakeTimesOut() throws Exception { + // TLS completes, then the server never reads the upgrade request or answers it + server.enqueue(new MockResponse.Builder().onRequestStart(SocketEffect.Stall.INSTANCE).build()); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + + events.expect("disconnected:false"); + events.expectQuiet(); + } + + @Test + void rejectedUpgradeDisconnects() throws Exception { + server.enqueue(new MockResponse.Builder().code(503).build()); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + + events.expect("disconnected:false"); + events.expectQuiet(); + } + + @Test + void failedTlsHandshakeDisconnects() throws Exception { + server.enqueue(new MockResponse.Builder().failHandshake().build()); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + + events.expect("disconnected:false"); + events.expectQuiet(); + } + + @Test + void nothingListeningDisconnects() throws Exception { + var port = server.getPort(); + server.close(); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(new InetSocketAddress("localhost", port), CONNECT_TIMEOUT_MS); + + events.expect("disconnected:false"); + } + + // endregion + + // region Failures after connecting + + @Test + void serverCloseIsNotUserInitiated() throws Exception { + var cm = new FakeCm(); + server.enqueue(upgrade(cm)); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("connected"); + + cm.awaitOpen().close(1000, "bye"); + + // Not user initiated, so apps reconnect + events.expect("disconnected:false"); + events.expectQuiet(); + + // The close frame is answered + assertEquals(1000, cm.awaitClosed()); + + // CMClient reads the endpoint inside the Disconnected handler to mark the server bad, + // and it is cleared once the handler has run + assertEquals(endpoint(), events.endpointOnDisconnect.get()); + assertNull(connection.getCurrentEndPoint()); + } + + @Test + void abruptDropIsNotUserInitiated() throws Exception { + var cm = new FakeCm(); + server.enqueue(upgrade(cm)); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("connected"); + + // Closes every socket outright, with no close frame: like a CM process dying + cm.awaitOpen(); + server.close(); + + events.expect("disconnected:false"); + events.expectQuiet(); + } + + // endregion + + // region Throwing handlers (SK PR 1657) + + @Test + void throwingNetMsgReceivedHandlerKeepsReading() throws Exception { + var cm = new FakeCm(); + server.enqueue(upgrade(cm)); + + var connection = newConnection(); + var events = new Events(connection); + var calls = new AtomicInteger(); + connection.getNetMsgReceived().addEventHandler((sender, e) -> { + if (calls.getAndIncrement() == 0) { + throw new IllegalStateException("handler failure"); + } + }); + + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("connected"); + + var serverSocket = cm.awaitOpen(); + serverSocket.send(ByteString.of((byte) 1)); + serverSocket.send(ByteString.of((byte) 2)); + + // The first message reached the recorder before the throwing handler, and the read loop kept going + assertArrayEquals(new byte[]{1}, events.expectMessage()); + assertArrayEquals(new byte[]{2}, events.expectMessage()); + events.expectQuiet(); + + connection.disconnect(true); + } + + @Test + void throwingConnectedHandlerDisconnects() throws Exception { + var cm = new FakeCm(); + server.enqueue(upgrade(cm)); + + var connection = newConnection(); + var events = new Events(connection); + connection.getConnected().addEventHandler((sender, e) -> { + throw new IllegalStateException("handler failure"); + }); + + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + + events.expect("connected"); + events.expect("disconnected:false"); + events.expectQuiet(); + assertEquals(1000, cm.awaitClosed()); + } + + @Test + void disconnectFromConnectedHandlerFiresOnce() throws Exception { + server.enqueue(upgrade(new FakeCm())); + + var connection = newConnection(); + var events = new Events(connection); + connection.getConnected().addEventHandler((sender, e) -> connection.disconnect(true)); + + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + + events.expect("connected"); + events.expect("disconnected:true"); + events.expectQuiet(); + } + + @Test + void disconnectWhileDispatchingAMessageFiresOnce() throws Exception { + var cm = new FakeCm(); + server.enqueue(upgrade(cm)); + + var connection = newConnection(); + var events = new Events(connection); + connection.getNetMsgReceived().addEventHandler((sender, e) -> connection.disconnect(false)); + + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("connected"); + + cm.awaitOpen().send(ByteString.of((byte) 1)); + + events.expectMessage(); + events.expect("disconnected:false"); + events.expectQuiet(); + } + + // endregion + + // region Disconnect contract + + @Test + void userDisconnectIsSynchronousAndClosesTheServer() throws Exception { + var cm = new FakeCm(); + server.enqueue(upgrade(cm)); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("connected"); + cm.awaitOpen(); + + connection.disconnect(true); + + // The disconnected event has fired before disconnect() returns + assertEquals("disconnected:true", events.log.poll()); + events.expectQuiet(); + + // A normal close frame reaches the server + assertEquals(1000, cm.awaitClosed()); + } + + @Test + void disconnectWhenNeverConnectedDoesNothing() throws Exception { + var connection = newConnection(); + var events = new Events(connection); + + connection.disconnect(true); + connection.disconnect(false); + + events.expectQuiet(); + } + + @Test + void competingDisconnectsFireOnce() throws Exception { + var cm = new FakeCm(); + server.enqueue(upgrade(cm)); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("connected"); + + // Server close and several local disconnects, all racing + var start = new CountDownLatch(1); + var threads = new Thread[4]; + for (int i = 0; i < threads.length; i++) { + threads[i] = new Thread(() -> { + try { + start.await(); + connection.disconnect(false); + } catch (InterruptedException ignored) { + } + }); + threads[i].start(); + } + + cm.awaitOpen().close(1000, null); + start.countDown(); + + for (var thread : threads) { + thread.join(); + } + + Thread.sleep(QUIET_MS); + + assertEquals(1, events.disconnects.get(), "disconnected should fire exactly once"); + } + + @Test + void reconnectRetiresTheOldSocket() throws Exception { + var first = new FakeCm(); + var second = new FakeCm(); + server.enqueue(upgrade(first)); + server.enqueue(upgrade(second)); + + var connection = newConnection(); + var events = new Events(connection); + + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("connected"); + var firstSocket = first.awaitOpen(); + + // Connect again on the same instance without disconnecting first: like SteamKit, the old one is + // reported disconnected and closed + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("disconnected:false"); + events.expect("connected"); + assertEquals(1000, first.awaitClosed()); + + // Late activity from the replaced socket must not surface + firstSocket.send(ByteString.of((byte) 9)); + events.expectQuiet(); + + // Sends reach the new server + second.awaitOpen(); + connection.send(new byte[]{9, 8, 7, 6}); + assertArrayEquals(new byte[]{9, 8, 7, 6}, second.expectMessage()); + assertNull(first.received.poll(), "send reached the replaced server"); + + connection.disconnect(true); + events.expect("disconnected:true"); + } + + @Test + void sendWhileNotConnectedIsIgnored() throws Exception { + var connection = newConnection(); + var events = new Events(connection); + + assertDoesNotThrow(() -> connection.send(new byte[]{1, 2, 3})); + + events.expectQuiet(); + } + + @Test + void sendAfterDisconnectIsIgnored() throws Exception { + server.enqueue(upgrade(new FakeCm())); + + var connection = newConnection(); + var events = new Events(connection); + connection.connect(endpoint(), CONNECT_TIMEOUT_MS); + events.expect("connected"); + + connection.disconnect(true); + events.expect("disconnected:true"); + + assertDoesNotThrow(() -> connection.send(new byte[]{1, 2, 3})); + events.expectQuiet(); + } + + // endregion + + // region Helpers + + private WebSocketConnection newConnection() { + return new WebSocketConnection(trustingClient); + } + + private InetSocketAddress endpoint() { + return new InetSocketAddress("localhost", server.getPort()); + } + + private static MockResponse upgrade(FakeCm cm) { + return new MockResponse.Builder().webSocketUpgrade(cm).build(); + } + + /** + * The server side of the socket. By default it accepts and stays silent; tests drive it from there. + */ + private static final class FakeCm extends WebSocketListener { + + private final CompletableFuture open = new CompletableFuture<>(); + + private final CompletableFuture closed = new CompletableFuture<>(); + + final BlockingQueue received = new LinkedBlockingQueue<>(); + + private boolean echo; + + FakeCm echo() { + echo = true; + return this; + } + + WebSocket awaitOpen() throws Exception { + return open.get(EXPECT_MS, TimeUnit.MILLISECONDS); + } + + /** + * @return the close code the client sent. + */ + int awaitClosed() throws Exception { + return closed.get(EXPECT_MS, TimeUnit.MILLISECONDS); + } + + byte[] expectMessage() throws InterruptedException { + var message = received.poll(EXPECT_MS, TimeUnit.MILLISECONDS); + assertNotNull(message, "timed out waiting for the server to receive a message"); + return message; + } + + @Override + public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) { + open.complete(webSocket); + } + + @Override + public void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) { + received.add(bytes.toByteArray()); + if (echo) { + webSocket.send(bytes); + } + } + + @Override + public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) { + closed.complete(code); + // Complete the close handshake like a real CM; otherwise the server socket lingers + webSocket.close(1000, null); + } + + @Override + public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) { + // The server started the close and the client answered it + closed.complete(code); + } + } + + /** + * Records what the connection reports, in order. + */ + private static final class Events { + + final BlockingQueue log = new LinkedBlockingQueue<>(); + + final BlockingQueue messages = new LinkedBlockingQueue<>(); + + final AtomicInteger disconnects = new AtomicInteger(); + + // The endpoint as seen from inside the last Disconnected handler + final AtomicReference endpointOnDisconnect = new AtomicReference<>(); + + Events(Connection connection) { + connection.getConnected().addEventHandler((sender, e) -> log.add("connected")); + connection.getDisconnected().addEventHandler((sender, e) -> { + disconnects.incrementAndGet(); + endpointOnDisconnect.set(connection.getCurrentEndPoint()); + log.add("disconnected:" + e.isUserInitiated()); + }); + connection.getNetMsgReceived().addEventHandler((sender, e) -> messages.add(e.getData())); + } + + void expect(String event) throws InterruptedException { + assertEquals(event, log.poll(EXPECT_MS, TimeUnit.MILLISECONDS)); + } + + byte[] expectMessage() throws InterruptedException { + var message = messages.poll(EXPECT_MS, TimeUnit.MILLISECONDS); + assertNotNull(message, "timed out waiting for a message"); + return message; + } + + void expectQuiet() throws InterruptedException { + assertNull(log.poll(QUIET_MS, TimeUnit.MILLISECONDS), "unexpected connection event"); + assertNull(messages.poll(), "unexpected message"); + } + } + + // endregion +} diff --git a/src/test/java/in/dragonbra/javasteam/steam/CMClientWatchdogTest.java b/src/test/java/in/dragonbra/javasteam/steam/CMClientWatchdogTest.java new file mode 100644 index 000000000..980a332d9 --- /dev/null +++ b/src/test/java/in/dragonbra/javasteam/steam/CMClientWatchdogTest.java @@ -0,0 +1,226 @@ +package in.dragonbra.javasteam.steam; + +import in.dragonbra.javasteam.TestBase; +import in.dragonbra.javasteam.base.ClientMsgProtobuf; +import in.dragonbra.javasteam.enums.EMsg; +import in.dragonbra.javasteam.enums.EResult; +import in.dragonbra.javasteam.networking.steam3.Connection; +import in.dragonbra.javasteam.networking.steam3.NetMsgEventArgs; +import in.dragonbra.javasteam.networking.steam3.ProtocolTypes; +import in.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientserverLogin.CMsgClientHeartBeat; +import in.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientserverLogin.CMsgClientLoggedOff; +import in.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientserverLogin.CMsgClientLogonResponse; +import in.dragonbra.javasteam.steam.discovery.ServerRecord; +import in.dragonbra.javasteam.steam.steamclient.configuration.SteamConfiguration; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * CMClient's watchdog, which disconnects a logged on connection that stops receiving anything. + * Steam does this during maintenance: no close, no logoff, and sends still succeed. + */ +public class CMClientWatchdogTest extends TestBase { + + private static final long WATCHDOG_TIMEOUT_MS = 500L; + + // Generous wait for an event that should happen; long enough to prove one doesn't. + private static final long EXPECT_MS = 5_000L; + + private static final long QUIET_MS = WATCHDOG_TIMEOUT_MS * 3; + + private final FakeConnection connection = new FakeConnection(); + + private TestClient client; + + @AfterEach + void tearDown() { + if (client != null) { + client.disconnect(); + } + } + + @Test + void silenceAfterLogonDisconnects() throws Exception { + client = connectedClient(WATCHDOG_TIMEOUT_MS); + + connection.receive(logonResponse()); + + // Not user initiated, so apps reconnect + assertEquals(Boolean.FALSE, client.disconnects.poll(EXPECT_MS, TimeUnit.MILLISECONDS)); + assertEquals(Boolean.FALSE, connection.disconnects.poll()); + } + + @Test + void trafficKeepsTheWatchdogAway() throws Exception { + client = connectedClient(WATCHDOG_TIMEOUT_MS); + + connection.receive(logonResponse()); + + // Like heartbeat replies: a message every 100ms, well inside the 500ms watchdog + ScheduledExecutorService replies = Executors.newSingleThreadScheduledExecutor(); + try { + replies.scheduleAtFixedRate(() -> connection.receive(heartbeat()), 0, 100, TimeUnit.MILLISECONDS); + + assertNull(client.disconnects.poll(QUIET_MS, TimeUnit.MILLISECONDS), "watchdog fired despite steady traffic"); + } finally { + replies.shutdownNow(); + } + } + + @Test + void silenceBeforeLogonIsAllowed() throws Exception { + // Connected but not logged on yet, e.g. waiting on the user for a Steam Guard code: nothing guarantees traffic + client = connectedClient(WATCHDOG_TIMEOUT_MS); + + assertNull(client.disconnects.poll(QUIET_MS, TimeUnit.MILLISECONDS), "watchdog fired before logon"); + } + + @Test + void loggingOffStopsTheWatchdog() throws Exception { + // Logged off, but the CM keeps the socket open + client = connectedClient(WATCHDOG_TIMEOUT_MS); + + connection.receive(logonResponse()); + connection.receive(loggedOff()); + + assertNull(client.disconnects.poll(QUIET_MS, TimeUnit.MILLISECONDS), "watchdog fired after logging off"); + } + + @Test + void zeroTimeoutDisablesTheWatchdog() throws Exception { + client = connectedClient(0L); + + connection.receive(logonResponse()); + + assertNull(client.disconnects.poll(QUIET_MS, TimeUnit.MILLISECONDS), "watchdog fired while disabled"); + } + + @Test + void reconnectingRestartsTheWatchdog() throws Exception { + client = connectedClient(WATCHDOG_TIMEOUT_MS); + + connection.receive(logonResponse()); + assertEquals(Boolean.FALSE, client.disconnects.poll(EXPECT_MS, TimeUnit.MILLISECONDS)); + + // The watchdog is off again until the next logon + client.connect(server()); + connection.raiseConnected(); + assertNull(client.disconnects.poll(QUIET_MS, TimeUnit.MILLISECONDS), "watchdog fired before the new logon"); + + connection.receive(logonResponse()); + assertEquals(Boolean.FALSE, client.disconnects.poll(EXPECT_MS, TimeUnit.MILLISECONDS)); + } + + // region Helpers + + private TestClient connectedClient(long watchdogTimeout) { + var configuration = SteamConfiguration.create(builder -> builder + .withConnectionFactory((config, protocol) -> connection) + .withWatchdogTimeout(watchdogTimeout)); + + var testClient = new TestClient(configuration); + testClient.connect(server()); + connection.raiseConnected(); + + return testClient; + } + + private static ServerRecord server() { + return ServerRecord.createServer("127.0.0.1", 443, ProtocolTypes.WEB_SOCKET); + } + + private static byte[] logonResponse() { + var msg = new ClientMsgProtobuf(CMsgClientLogonResponse.class, EMsg.ClientLogOnResponse); + msg.getBody().setEresult(EResult.OK.code()); + msg.getBody().setLegacyOutOfGameHeartbeatSeconds(9); + return msg.serialize(); + } + + private static byte[] loggedOff() { + var msg = new ClientMsgProtobuf(CMsgClientLoggedOff.class, EMsg.ClientLoggedOff); + msg.getBody().setEresult(EResult.LoggedInElsewhere.code()); + return msg.serialize(); + } + + private static byte[] heartbeat() { + return new ClientMsgProtobuf(CMsgClientHeartBeat.class, EMsg.ClientHeartBeat).serialize(); + } + + private static final class TestClient extends CMClient { + + final BlockingQueue disconnects = new LinkedBlockingQueue<>(); + + TestClient(SteamConfiguration configuration) { + super(configuration); + } + + @Override + protected void onClientDisconnected(boolean userInitiated) { + super.onClientDisconnected(userInitiated); + disconnects.add(userInitiated); + } + } + + /** + * Stands in for the transport: CMClient's sends go nowhere, and like the real connections it raises + * Disconnected before disconnect() returns. + */ + private static final class FakeConnection extends Connection { + + private static final InetSocketAddress FAKE_END_POINT = new InetSocketAddress(InetAddress.getLoopbackAddress(), 443); + + final BlockingQueue disconnects = new LinkedBlockingQueue<>(); + + @Override + public void connect(@NotNull InetSocketAddress endPoint, int timeout) { + } + + @Override + public void disconnect(boolean userInitiated) { + disconnects.add(userInitiated); + onDisconnected(userInitiated); + } + + @Override + public void send(byte @NotNull [] data) { + } + + @Override + public @Nullable InetAddress getLocalIP() { + return InetAddress.getLoopbackAddress(); + } + + @Override + public @Nullable InetSocketAddress getCurrentEndPoint() { + return FAKE_END_POINT; + } + + @Override + public @Nullable ProtocolTypes getProtocolTypes() { + return ProtocolTypes.WEB_SOCKET; + } + + void raiseConnected() { + onConnected(); + } + + void receive(byte[] data) { + onNetMsgReceived(new NetMsgEventArgs(data, FAKE_END_POINT)); + } + } + + // endregion +} 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 cf65a2fc1..bf05e6ab7 100644 --- a/src/test/java/in/dragonbra/javasteam/steam/cdn/DepotChunkTest.java +++ b/src/test/java/in/dragonbra/javasteam/steam/cdn/DepotChunkTest.java @@ -16,13 +16,14 @@ public class DepotChunkTest extends TestBase { @Test public void decryptsAndDecompressesDepotChunkPKZip() throws IOException, NoSuchAlgorithmException { - var stream = getClass().getClassLoader() - .getResourceAsStream("depot/depot_440_chunk_bac8e2657470b2eb70d6ddcd6c07004be8738697.bin"); + var resource = "depot/depot_440_chunk_bac8e2657470b2eb70d6ddcd6c07004be8738697.bin"; - var ms = new MemoryStream(); - IOUtils.copy(stream, ms.asOutputStream()); - - var chunkData = ms.toByteArray(); + byte[] chunkData; + try (var stream = getClass().getClassLoader().getResourceAsStream(resource); + var ms = new MemoryStream()) { + IOUtils.copy(stream, ms.asOutputStream()); + chunkData = ms.toByteArray(); + } var chunk = new ChunkData( new byte[0], // id is not needed here @@ -55,13 +56,14 @@ public void decryptsAndDecompressesDepotChunkPKZip() throws IOException, NoSuchA @Test public void decryptsAndDecompressesDepotChunkVZip() throws IOException, NoSuchAlgorithmException { - var stream = getClass().getClassLoader() - .getResourceAsStream("depot/depot_232250_chunk_7b8567d9b3c09295cdbf4978c32b348d8e76c750.bin"); - - var ms = new MemoryStream(); - IOUtils.copy(stream, ms.asOutputStream()); + var resource = "depot/depot_232250_chunk_7b8567d9b3c09295cdbf4978c32b348d8e76c750.bin"; - var chunkData = ms.toByteArray(); + byte[] chunkData; + try (var stream = getClass().getClassLoader().getResourceAsStream(resource); + var ms = new MemoryStream()) { + IOUtils.copy(stream, ms.asOutputStream()); + chunkData = ms.toByteArray(); + } var chunk = new ChunkData( new byte[0], // id is not needed here @@ -94,13 +96,14 @@ public void decryptsAndDecompressesDepotChunkVZip() throws IOException, NoSuchAl @Test public void decryptsAndDecompressesDepotChunkZStd() throws IOException, NoSuchAlgorithmException { - var stream = getClass().getClassLoader() - .getResourceAsStream("depot/depot_3441461_chunk_9e72678e305540630a665b93e1463bc3983eb55a.bin"); - - var ms = new MemoryStream(); - IOUtils.copy(stream, ms.asOutputStream()); - - var chunkData = ms.toByteArray(); + var resource = "depot/depot_3441461_chunk_9e72678e305540630a665b93e1463bc3983eb55a.bin"; + + byte[] chunkData; + try (var stream = getClass().getClassLoader().getResourceAsStream(resource); + var ms = new MemoryStream()) { + IOUtils.copy(stream, ms.asOutputStream()); + chunkData = ms.toByteArray(); + } var chunk = new ChunkData( new byte[0], // id is not needed here diff --git a/src/test/java/in/dragonbra/javasteam/steam/handlers/steamapps/PICSProductInfoTest.java b/src/test/java/in/dragonbra/javasteam/steam/handlers/steamapps/PICSProductInfoTest.java new file mode 100644 index 000000000..ecc7eee5c --- /dev/null +++ b/src/test/java/in/dragonbra/javasteam/steam/handlers/steamapps/PICSProductInfoTest.java @@ -0,0 +1,116 @@ +package in.dragonbra.javasteam.steam.handlers.steamapps; + +import com.google.protobuf.ByteString; +import in.dragonbra.javasteam.TestBase; +import in.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientserverAppinfo.CMsgClientPICSProductInfoResponse; +import in.dragonbra.javasteam.types.KeyValue; +import in.dragonbra.javasteam.util.stream.MemoryStream; +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.nio.charset.StandardCharsets; + +public class PICSProductInfoTest extends TestBase { + + private static final String APP_INFO_TEXT = "\"appinfo\"\n{\n\t\"appid\"\t\t\"440\"\n}"; + + private static CMsgClientPICSProductInfoResponse.AppInfo.Builder appInfo(byte[] buffer) { + return CMsgClientPICSProductInfoResponse.AppInfo.newBuilder() + .setAppid(440) + .setChangeNumber(1) + .setBuffer(ByteString.copyFrom(buffer)); + } + + private static byte[] packageBuffer(int format) throws IOException { + var kv = new KeyValue("440"); + kv.getChildren().add(new KeyValue("billingtype", "10")); + + try (var ms = new MemoryStream()) { + kv.saveToStream(ms.asOutputStream(), true); + var kvBytes = ms.toByteArray(); + + return ByteBuffer.allocate(Integer.BYTES + kvBytes.length) + .order(ByteOrder.LITTLE_ENDIAN) + .putInt(format) + .put(kvBytes) + .array(); + } + } + + private static PICSProductInfo packageInfo(byte[] buffer) { + var packageInfo = CMsgClientPICSProductInfoResponse.PackageInfo.newBuilder() + .setPackageid(440) + .setChangeNumber(1) + .setBuffer(ByteString.copyFrom(buffer)) + .build(); + + return new PICSProductInfo(CMsgClientPICSProductInfoResponse.newBuilder(), packageInfo); + } + + @Test + public void appTextBufferWithTrailingNullIsRead() { + var buffer = (APP_INFO_TEXT + "\0").getBytes(StandardCharsets.UTF_8); + + var info = new PICSProductInfo(CMsgClientPICSProductInfoResponse.newBuilder(), appInfo(buffer).build()); + + Assertions.assertEquals("440", info.getKeyValues().get("appid").asString()); + } + + @Test + public void appTextBufferWithoutTrailingNullIsRead() { + var buffer = APP_INFO_TEXT.getBytes(StandardCharsets.UTF_8); + + var info = new PICSProductInfo(CMsgClientPICSProductInfoResponse.newBuilder(), appInfo(buffer).build()); + + Assertions.assertEquals("440", info.getKeyValues().get("appid").asString()); + } + + @Test + public void useHttpRequiresMetaDataOnlyAndMinimumSize() { + var app = CMsgClientPICSProductInfoResponse.AppInfo.newBuilder() + .setAppid(440) + .setSha(ByteString.copyFrom(new byte[20])) + .setSize(200) + .build(); + + var available = CMsgClientPICSProductInfoResponse.newBuilder() + .setMetaDataOnly(true) + .setHttpHost("example.invalid") + .setHttpMinSize(100); + Assertions.assertTrue(new PICSProductInfo(available, app).isUseHttp()); + + // a minimum size of zero means HTTP is not available for this response + var zeroMinSize = available.clone().setHttpMinSize(0); + Assertions.assertFalse(new PICSProductInfo(zeroMinSize, app).isUseHttp()); + + var notMetaDataOnly = available.clone().setMetaDataOnly(false); + Assertions.assertFalse(new PICSProductInfo(notMetaDataOnly, app).isUseHttp()); + + var tooSmall = available.clone().setHttpMinSize(500); + Assertions.assertFalse(new PICSProductInfo(tooSmall, app).isUseHttp()); + } + + @Test + public void packageBufferWithKnownFormatIsRead() throws IOException { + var info = packageInfo(packageBuffer(1)); + + Assertions.assertEquals("10", info.getKeyValues().get("billingtype").asString()); + } + + @Test + public void packageBufferWithUnknownFormatIsIgnored() throws IOException { + var info = packageInfo(packageBuffer(2)); + + Assertions.assertTrue(info.getKeyValues().getChildren().isEmpty()); + } + + @Test + public void truncatedPackageBufferIsIgnored() { + var info = packageInfo(new byte[]{1, 0}); + + Assertions.assertTrue(info.getKeyValues().getChildren().isEmpty()); + } +} 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 4601ef3cf..4c6e36ac9 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 @@ -65,7 +65,7 @@ public void sendChatMessage() throws UnsupportedEncodingException { ClientMsgProtobuf msg = verifySend(EMsg.ClientFriendMsg); assertEquals(123456789L, msg.getBody().getSteamid()); - assertEquals("testmessage", msg.getBody().getMessage().toString("UTF-8")); + assertEquals("testmessage", msg.getBody().getMessage().toStringUtf8()); assertEquals(EChatEntryType.ChatMsg.code(), msg.getBody().getChatEntryType()); } diff --git a/src/test/java/in/dragonbra/javasteam/steam/handlers/steamuserstats/SteamUserStatsTest.java b/src/test/java/in/dragonbra/javasteam/steam/handlers/steamuserstats/SteamUserStatsTest.java index 797a17686..72fd6c866 100644 --- a/src/test/java/in/dragonbra/javasteam/steam/handlers/steamuserstats/SteamUserStatsTest.java +++ b/src/test/java/in/dragonbra/javasteam/steam/handlers/steamuserstats/SteamUserStatsTest.java @@ -27,8 +27,6 @@ import in.dragonbra.javasteam.types.KeyValue; import static org.junit.jupiter.api.Assertions.*; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; /** * Unit tests for SteamUserStats handler, specifically testing achievement @@ -39,7 +37,7 @@ @MockitoSettings(strictness = Strictness.LENIENT) public class SteamUserStatsTest extends HandlerTestBase { - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override protected SteamUserStats createHandler() { @@ -322,6 +320,7 @@ public void testGetExpandedAchievementsWithProgress() throws IOException { * Helper method to create a mock UserStatsResponse packet with achievement * data. */ + @SuppressWarnings("SameParameterValue") private IPacketMsg createUserStatsResponseMessage(boolean includeSchema) throws IOException { ClientMsgProtobuf msg = new ClientMsgProtobuf<>( CMsgClientGetUserStatsResponse.class, EMsg.ClientGetUserStatsResponse); diff --git a/src/test/java/in/dragonbra/javasteam/steam/steamclient/SteamClientTest.java b/src/test/java/in/dragonbra/javasteam/steam/steamclient/SteamClientTest.java index f60504093..ab42632ae 100644 --- a/src/test/java/in/dragonbra/javasteam/steam/steamclient/SteamClientTest.java +++ b/src/test/java/in/dragonbra/javasteam/steam/steamclient/SteamClientTest.java @@ -18,11 +18,16 @@ import in.dragonbra.javasteam.steam.handlers.steamuser.SteamUser; import in.dragonbra.javasteam.steam.handlers.steamuserstats.SteamUserStats; import in.dragonbra.javasteam.steam.handlers.steamworkshop.SteamWorkshop; +import in.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackMsg; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.HashMap; +import java.util.concurrent.CancellationException; class SteamClientTest { @@ -105,35 +110,37 @@ public void removeHandlerRemovesHandlerByInstance() { @Test public void addHandlerThrowsOnDuplicateHandler() { - var steamClient = new SteamClient(); - steamClient.addHandler(new TestMsgHandler()); - - Assertions.assertThrows(IllegalArgumentException.class, () -> steamClient.addHandler(new TestMsgHandler())); + try (var steamClient = new SteamClient()) { + steamClient.addHandler(new TestMsgHandler()); + Assertions.assertThrows(IllegalArgumentException.class, () -> steamClient.addHandler(new TestMsgHandler())); + } } @Test public void removeHandlerByTypeDoesNothingWhenNotRegistered() { - var steamClient = new SteamClient(); - Assertions.assertNull(client.getHandler(TestMsgHandler.class)); + try (var steamClient = new SteamClient()) { + Assertions.assertNull(client.getHandler(TestMsgHandler.class)); - steamClient.removeHandler(TestMsgHandler.class); - Assertions.assertNull(client.getHandler(TestMsgHandler.class)); + steamClient.removeHandler(TestMsgHandler.class); + Assertions.assertNull(client.getHandler(TestMsgHandler.class)); + } } @Test public void getRequiredHandlerReturnsHandler() { - var steamClient = new SteamClient(); - var handler = steamClient.getRequiredHandler(SteamUser.class); + try (var steamClient = new SteamClient()) { + var handler = steamClient.getRequiredHandler(SteamUser.class); - Assertions.assertNotNull(handler); - Assertions.assertEquals(SteamUser.class, handler.getClass()); + Assertions.assertNotNull(handler); + Assertions.assertEquals(SteamUser.class, handler.getClass()); + } } @Test public void getRequiredHandlerThrowsWhenNotRegistered() { - var steamClient = new SteamClient(); - - Assertions.assertThrows(IllegalArgumentException.class, () -> steamClient.getRequiredHandler(TestMsgHandler.class)); + try (var steamClient = new SteamClient()) { + Assertions.assertThrows(IllegalArgumentException.class, () -> steamClient.getRequiredHandler(TestMsgHandler.class)); + } } @Test @@ -143,15 +150,19 @@ public void getNextJobIDSetsProcessIDToZero() { Assertions.assertEquals(0, jobID.getProcessID()); } -// @Test -// public void getNextJobIDFillsProcessStartTime() { -// var jobID = client.getNextJobID(); -// -// var dateNow = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS); -// var processStartTime = Date.from(dateNow.toInstant(ZoneOffset.UTC)); -// -// Assertions.assertEquals(processStartTime, jobID.getStartTime()); -// } + @Test + public void getNextJobIDFillsProcessStartTime() { + // JavaSteam uses the time the client was created, with second precision, instead of the process start time. + var before = Instant.now().truncatedTo(ChronoUnit.SECONDS); + try (var steamClient = new SteamClient()) { + var after = Instant.now(); + + var startTime = steamClient.getNextJobID().getStartTime().toInstant(); + + Assertions.assertFalse(startTime.isBefore(before), "Start time should not be before the client was created"); + Assertions.assertFalse(startTime.isAfter(after), "Start time should not be after the client was created"); + } + } @Test public void getNextJobIDSetsBoxIDToZero() { @@ -160,6 +171,36 @@ public void getNextJobIDSetsBoxIDToZero() { Assertions.assertEquals(0, jobID.getBoxID()); } + @Test + public void waitForCallbackAfterCloseThrowsInsteadOfHanging() { + client.close(); + + Assertions.assertTimeoutPreemptively(Duration.ofSeconds(5), () -> { + Assertions.assertThrows(CancellationException.class, () -> client.waitForCallback()); + }); + } + + @Test + public void waitForCallbackWithTimeoutAfterCloseThrowsInsteadOfHanging() { + client.close(); + + Assertions.assertTimeoutPreemptively(Duration.ofSeconds(5), () -> { + Assertions.assertThrows(CancellationException.class, () -> client.waitForCallback(100)); + }); + } + + @Test + public void cancelledWaitForCallbackFutureDoesNotConsumeCallback() { + var abandoned = client.waitForCallbackFuture(); + abandoned.cancel(true); + + var callback = new CallbackMsg() { + }; + client.postCallback(callback); + + Assertions.assertTimeoutPreemptively(Duration.ofSeconds(5), () -> Assertions.assertSame(callback, client.waitForCallback(1000))); + } + static class TestMsgHandler extends ClientMsgHandler { @Override public void handleMsg(IPacketMsg packetMsg) { diff --git a/src/test/java/in/dragonbra/javasteam/steam/steamclient/callbackmgr/CallbackManagerTest.java b/src/test/java/in/dragonbra/javasteam/steam/steamclient/callbackmgr/CallbackManagerTest.java index ed134079f..8f32bb1e4 100644 --- a/src/test/java/in/dragonbra/javasteam/steam/steamclient/callbackmgr/CallbackManagerTest.java +++ b/src/test/java/in/dragonbra/javasteam/steam/steamclient/callbackmgr/CallbackManagerTest.java @@ -22,7 +22,7 @@ */ public class CallbackManagerTest extends TestBase { - Logger logger = LogManager.getLogger(CallbackManagerTest.class); + final Logger logger = LogManager.getLogger(CallbackManagerTest.class); private SteamClient client; private CallbackManager mgr; @@ -119,9 +119,7 @@ public void postedCallbackDoesNotTriggerActionForWrongJobID() { callback.setUniqueID(UUID.randomUUID()); var didCall = new AtomicBoolean(false); - try (var ignored = mgr.subscribe(CallbackForTest.class, new JobID(123), cb -> { - didCall.set(true); - })) { + try (var ignored = mgr.subscribe(CallbackForTest.class, new JobID(123), cb -> didCall.set(true))) { postAndRunCallback(callback); } catch (IOException e) { logger.error(e); @@ -327,9 +325,7 @@ public void asyncCallbackDoesNotTriggerActionForWrongJobID() throws IOException var didCall = new AtomicBoolean(false); - try (var ignored = mgr.subscribe(CallbackForTest.class, new JobID(123), cb -> { - didCall.set(true); - })) { + try (var ignored = mgr.subscribe(CallbackForTest.class, new JobID(123), cb -> didCall.set(true))) { postAndRunCallback(callback); } diff --git a/src/test/java/in/dragonbra/javasteam/steam/webapi/WebAPITest.java b/src/test/java/in/dragonbra/javasteam/steam/webapi/WebAPITest.java index 067827e4a..170d2f6cf 100644 --- a/src/test/java/in/dragonbra/javasteam/steam/webapi/WebAPITest.java +++ b/src/test/java/in/dragonbra/javasteam/steam/webapi/WebAPITest.java @@ -13,7 +13,6 @@ import org.junit.jupiter.api.Test; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; @@ -76,14 +75,14 @@ public void requestHeaders() throws InterruptedException, IOException { @Test public void steamConfigWebApiInterface() { SteamConfiguration config = SteamConfiguration.create(b -> - b.withWebAPIBaseAddress("http://example.com/").withWebAPIKey("hello") + b.withWebAPIBaseAddress("https://example.com/").withWebAPIKey("hello") ); WebAPI api = config.getWebAPI("TestInterface"); - assertEquals(api.getInterface(), "TestInterface"); - assertEquals(api.getWebAPIKey(), "hello"); - assertEquals(api.getBaseAddress().toString(), "http://example.com/"); + assertEquals("TestInterface", api.getInterface()); + assertEquals("hello", api.getWebAPIKey()); + assertEquals("https://example.com/", api.getBaseAddress().toString()); } @Test diff --git a/src/test/java/in/dragonbra/javasteam/types/AsyncJobTest.kt b/src/test/java/in/dragonbra/javasteam/types/AsyncJobTest.kt index 36654a2ed..f9a2f9402 100644 --- a/src/test/java/in/dragonbra/javasteam/types/AsyncJobTest.kt +++ b/src/test/java/in/dragonbra/javasteam/types/AsyncJobTest.kt @@ -5,11 +5,22 @@ import `in`.dragonbra.javasteam.steam.steamclient.AsyncJobFailedException import `in`.dragonbra.javasteam.steam.steamclient.SteamClient import `in`.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackMsg import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.future.await +import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test +import org.junit.jupiter.api.function.ThrowingSupplier +import java.util.concurrent.ExecutionException +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeoutException +import java.util.concurrent.atomic.AtomicReference +import kotlin.concurrent.thread +import kotlin.time.Duration.Companion.seconds class AsyncJobTest { @@ -57,7 +68,10 @@ class AsyncJobTest { Assertions.assertTrue(asyncTask.isDone, "Async job should be completed after callback is posted") Assertions.assertFalse(asyncTask.isCancelled, "Async job should not be canceled after callback is posted") - Assertions.assertFalse(asyncTask.isCompletedExceptionally, "Async job should be faulted when client is disconnected") + Assertions.assertFalse( + asyncTask.isCompletedExceptionally, + "Async job should be faulted when client is disconnected" + ) } @Test @@ -288,7 +302,7 @@ class AsyncJobTest { val asyncJob = AsyncJobMultiple(client, JobID(123)) { _ -> true } asyncJob.timeout = 1000 - runBlocking { delay(5000) } + runBlocking { delay(5.seconds) } Assertions.assertFalse( client.jobManager.asyncJobs.containsKey(asyncJob.jobID), @@ -312,7 +326,7 @@ class AsyncJobTest { val asyncTask = asyncJob.toFuture() // wait 3 seconds before we post any results to this job at all - runBlocking { delay(3000) } + runBlocking { delay(3.seconds) } Assertions.assertFalse( asyncTask.isDone, @@ -336,7 +350,7 @@ class AsyncJobTest { ) // delay for what the original timeout would have been - runBlocking { delay(5000) } + runBlocking { delay(5.seconds) } // we still shouldn't be completed or canceled (timed out) Assertions.assertFalse( @@ -387,7 +401,7 @@ class AsyncJobTest { val asyncTask = asyncJob.toFuture() runBlocking { - delay(5000) + delay(5.seconds) } Assertions.assertTrue( @@ -406,7 +420,6 @@ class AsyncJobTest { Assertions.assertThrows(CancellationException::class.java) { runBlocking { asyncTask.await() } } } - @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) @Test fun asyncJobMultipleCompletesOnIncompleteResult() { val client = ConnectedSteamClient.get().apply { @@ -430,7 +443,7 @@ class AsyncJobTest { asyncJob.timeout = 1000 runBlocking { - delay(5000) + delay(5.seconds) } Assertions.assertTrue( @@ -454,7 +467,6 @@ class AsyncJobTest { Assertions.assertSame(onlyResult, result.results.first()) } - @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) @Test fun asyncJobMultipleCompletesOnIncompleteResultAndFailure() { val client = ConnectedSteamClient.get().apply { @@ -507,13 +519,254 @@ class AsyncJobTest { Assertions.assertTrue(asyncTask.isDone, "AsyncJobMultiple should be completed after job failure") Assertions.assertFalse(asyncTask.isCancelled, "AsyncJobMultiple should not be canceled after job failure") - Assertions.assertTrue(asyncTask.isCompletedExceptionally, "AsyncJobMultiple should be faulted after job failure") + Assertions.assertTrue( + asyncTask.isCompletedExceptionally, + "AsyncJobMultiple should be faulted after job failure" + ) Assertions.assertThrows(AsyncJobFailedException::class.java) { runBlocking { asyncTask.await() } } } -// @Test -// fun asyncJobContinuesAsynchronously() + @Test + fun asyncJobContinuesAsynchronously() = runBlocking { + val client = ConnectedSteamClient.get() + val asyncJob = AsyncJobSingle(client, JobID(123)) + + var continuationThread: Thread? = null + + // UNDISPATCHED runs up to await() on this thread, so the continuation is registered before we complete + val continuation = launch(Dispatchers.Default, start = CoroutineStart.UNDISPATCHED) { + asyncJob.await() + continuationThread = Thread.currentThread() + } + + val completionThread = Thread.currentThread() + asyncJob.addResult(Callback().apply { jobID = JobID(123) }) + + continuation.join() + + Assertions.assertNotNull(continuationThread, "Continuation should have run") + Assertions.assertNotSame( + completionThread, + continuationThread, + "Continuation should not run on the thread that completed the job" + ) + } + + @Test + fun asyncJobMultipleContinuesAsynchronously() = runBlocking { + val client = ConnectedSteamClient.get() + val asyncJob = AsyncJobMultiple(client, JobID(123)) { _ -> true } + + var continuationThread: Thread? = null + + // UNDISPATCHED runs up to await() on this thread, so the continuation is registered before we complete + val continuation = launch(Dispatchers.Default, start = CoroutineStart.UNDISPATCHED) { + asyncJob.await() + continuationThread = Thread.currentThread() + } + + val completionThread = Thread.currentThread() + asyncJob.addResult(Callback().apply { jobID = JobID(123) }) + + continuation.join() + + Assertions.assertNotNull(continuationThread, "Continuation should have run") + Assertions.assertNotSame( + completionThread, + continuationThread, + "Continuation should not run on the thread that completed the job" + ) + } + + @Test + fun asyncJobToFutureReturnsSameInstance() { + val client = ConnectedSteamClient.get() + + val single = AsyncJobSingle(client, JobID(123)) + val multiple = AsyncJobMultiple(client, JobID(124)) { _ -> true } + + Assertions.assertSame(single.toFuture(), single.toFuture()) + Assertions.assertSame(multiple.toFuture(), multiple.toFuture()) + } + + @Test + fun asyncJobHeartbeatExtendsTimeout() { + val client = ConnectedSteamClient.get() + val asyncJob = AsyncJobSingle(client, JobID(123)) + + Assertions.assertEquals(10_000L, asyncJob.timeout) + Assertions.assertFalse(asyncJob.isTimedOut) + + asyncJob.heartbeat() + Assertions.assertEquals(20_000L, asyncJob.timeout) + + asyncJob.timeout = 0 + Assertions.assertTrue(asyncJob.isTimedOut) + } + + //region Blocking and CompletableFuture paths, as a Java caller would use them (no coroutines) + + @Test + fun asyncJobRunBlockReturnsCallbackPostedFromAnotherThread() { + val client = ConnectedSteamClient.get() + val asyncJob = AsyncJobSingle(client, JobID(123)) + val ourCallback = Callback().apply { jobID = JobID(123) } + + val poster = thread(name = "job-poster") { + Thread.sleep(100) + client.postCallback(ourCallback) + } + + val result = Assertions.assertTimeoutPreemptively(TEST_TIMEOUT, ThrowingSupplier { asyncJob.runBlock() }) + poster.join() + + Assertions.assertSame(ourCallback, result) + } + + @Test + fun asyncJobMultipleRunBlockReturnsResultSetPostedFromAnotherThread() { + val client = ConnectedSteamClient.get() + val asyncJob = AsyncJobMultiple(client, JobID(123)) { call -> call.isFinished } + + val first = Callback().apply { + jobID = JobID(123) + isFinished = false + } + val second = Callback().apply { + jobID = JobID(123) + isFinished = true + } + + val poster = thread(name = "job-poster") { + Thread.sleep(100) + client.postCallback(first) + client.postCallback(second) + } + + val result = Assertions.assertTimeoutPreemptively(TEST_TIMEOUT, ThrowingSupplier { asyncJob.runBlock() }) + poster.join() + + Assertions.assertTrue(result.complete, "ResultSet should be complete") + Assertions.assertFalse(result.failed, "ResultSet should not be failed") + Assertions.assertEquals(listOf(first, second), result.results) + } + + @Test + fun asyncJobRunBlockThrowsExecutionExceptionOnFailure() { + val client = ConnectedSteamClient.get() + val asyncJob = AsyncJobSingle(client, JobID(123)) -// @Test -// fun AsyncJobMultipleContinuesAsynchronously() + asyncJob.setFailed(true) + + val exception = Assertions.assertThrows(ExecutionException::class.java) { asyncJob.runBlock() } + Assertions.assertInstanceOf(AsyncJobFailedException::class.java, exception.cause) + } + + @Test + fun asyncJobRunBlockThrowsCancellationExceptionOnTimeout() { + val client = ConnectedSteamClient.get() + val asyncJob = AsyncJobSingle(client, JobID(123)) + + asyncJob.setFailed(false) + + Assertions.assertThrows(CancellationException::class.java) { asyncJob.runBlock() } + } + + @Test + fun asyncJobMultipleRunBlockThrowsExecutionExceptionOnFailure() { + val client = ConnectedSteamClient.get() + val asyncJob = AsyncJobMultiple(client, JobID(123)) { _ -> false } + + asyncJob.setFailed(true) + + val exception = Assertions.assertThrows(ExecutionException::class.java) { asyncJob.runBlock() } + Assertions.assertInstanceOf(AsyncJobFailedException::class.java, exception.cause) + } + + @Test + fun asyncJobMultipleRunBlockThrowsCancellationExceptionOnTimeout() { + val client = ConnectedSteamClient.get() + val asyncJob = AsyncJobMultiple(client, JobID(123)) { _ -> false } + + asyncJob.setFailed(false) + + Assertions.assertThrows(CancellationException::class.java) { asyncJob.runBlock() } + } + + @Test + fun asyncJobFutureGetTimesOutWhilePending() { + val client = ConnectedSteamClient.get() + val asyncJob = AsyncJobSingle(client, JobID(123)) + + Assertions.assertThrows(TimeoutException::class.java) { + asyncJob.toFuture().get(50, TimeUnit.MILLISECONDS) + } + Assertions.assertFalse(asyncJob.toFuture().isDone, "A get() timeout should not complete the job") + } + + @Test + fun asyncJobFutureContinuationRunsOnCompletingThread() { + val client = ConnectedSteamClient.get() + val asyncJob = AsyncJobSingle(client, JobID(123)) + + val continuationThread = AtomicReference() + asyncJob.toFuture().thenAccept { continuationThread.set(Thread.currentThread()) } + + asyncJob.addResult(Callback().apply { jobID = JobID(123) }) + + // Documented behavior: a non-async continuation runs inline, before addResult returns + Assertions.assertSame(Thread.currentThread(), continuationThread.get()) + } + + @Test + fun asyncJobFutureAsyncContinuationRunsOffCompletingThread() { + val client = ConnectedSteamClient.get() + val asyncJob = AsyncJobSingle(client, JobID(123)) + val executor = Executors.newSingleThreadExecutor() + + try { + val continuationThread = AtomicReference() + val continuation = asyncJob.toFuture().thenAcceptAsync( + { continuationThread.set(Thread.currentThread()) }, + executor + ) + + asyncJob.addResult(Callback().apply { jobID = JobID(123) }) + continuation.get(TEST_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS) + + Assertions.assertNotNull(continuationThread.get(), "Continuation should have run") + Assertions.assertNotSame(Thread.currentThread(), continuationThread.get()) + } finally { + executor.shutdownNow() + } + } + + @Test + fun asyncJobMultipleFutureAsyncContinuationRunsOffCompletingThread() { + val client = ConnectedSteamClient.get() + val asyncJob = AsyncJobMultiple(client, JobID(123)) { _ -> true } + val executor = Executors.newSingleThreadExecutor() + + try { + val continuationThread = AtomicReference() + val continuation = asyncJob.toFuture().thenAcceptAsync( + { continuationThread.set(Thread.currentThread()) }, + executor + ) + + asyncJob.addResult(Callback().apply { jobID = JobID(123) }) + continuation.get(TEST_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS) + + Assertions.assertNotNull(continuationThread.get(), "Continuation should have run") + Assertions.assertNotSame(Thread.currentThread(), continuationThread.get()) + } finally { + executor.shutdownNow() + } + } + + //endregion + + private companion object { + val TEST_TIMEOUT: java.time.Duration = java.time.Duration.ofSeconds(5) + } } diff --git a/src/test/java/in/dragonbra/javasteam/types/DepotManifestTest.java b/src/test/java/in/dragonbra/javasteam/types/DepotManifestTest.java index 7d43f57ff..016c7ea55 100644 --- a/src/test/java/in/dragonbra/javasteam/types/DepotManifestTest.java +++ b/src/test/java/in/dragonbra/javasteam/types/DepotManifestTest.java @@ -54,6 +54,20 @@ public void parsesAndDecryptsManifestVersion4() { } } + @Test + public void throwsWhenVersion4FileMappingExceedsDeclaredSize() throws IOException { + try (var stream = getClass().getResourceAsStream("/depot/depot_440_1118032470228587934_v4.manifest")) { + Assertions.assertNotNull(stream); + + var manifestData = stream.readAllBytes(); + + // Shrink the declared file mapping size (int at offset 52) so the first mapping overruns it. + ByteBuffer.wrap(manifestData).order(ByteOrder.LITTLE_ENDIAN).putInt(52, 1); + + Assertions.assertThrows(IOException.class, () -> DepotManifest.deserialize(manifestData)); + } + } + @Test public void parsesAndDecryptsManifest() throws IOException, NoSuchAlgorithmException { try (var stream = getClass().getResourceAsStream("/depot/depot_440_1118032470228587934.manifest"); diff --git a/src/test/java/in/dragonbra/javasteam/types/KeyValueTest.java b/src/test/java/in/dragonbra/javasteam/types/KeyValueTest.java index 90704cf4e..e23697887 100644 --- a/src/test/java/in/dragonbra/javasteam/types/KeyValueTest.java +++ b/src/test/java/in/dragonbra/javasteam/types/KeyValueTest.java @@ -255,7 +255,7 @@ public void keyValuesWritesBinaryToFile() throws IOException { kv.saveToFile(tempFile.toFile(), true); byte[] binaryValue = Files.readAllBytes(Paths.get(tempFile.toFile().getPath())); - String hexValue = Hex.encodeHexString(binaryValue, false).replaceAll("-", ""); + String hexValue = Hex.encodeHexString(binaryValue, false).replace("-", ""); Assertions.assertEquals(expectedHexValue, hexValue); } @@ -275,7 +275,7 @@ public void keyValuesWritesBinaryToStream() { try (MemoryStream ms = new MemoryStream()) { kv.saveToStream(ms.asOutputStream(), true); - String hexValue = Hex.encodeHexString(ms.toByteArray(), false).replaceAll("-", ""); + String hexValue = Hex.encodeHexString(ms.toByteArray(), false).replace("-", ""); Assertions.assertEquals(expectedHexValue, hexValue); } catch (Exception e) { @@ -329,7 +329,7 @@ public void keyValues_TryReadAsBinary_ReadsBinary() throws IOException, DecoderE @Test public void keyValuesReadsBinaryWithLeftoverData() throws IOException, DecoderException { - byte[] binary = Hex.decodeHex(TEST_OBJECT_HEX + UUID.randomUUID().toString().replaceAll("-", "")); + byte[] binary = Hex.decodeHex(TEST_OBJECT_HEX + UUID.randomUUID().toString().replace("-", "")); KeyValue kv = new KeyValue(); boolean success; @@ -498,10 +498,13 @@ public void writesNewLineAsSlashN() { kv.getChildren().add(new KeyValue("def", "ghi\njkl")); String text = saveToText(kv); - String expected = ("\n" + - "\"abc\"\n" + - "{\n" + "\t" + "\"def\"\t\t\"ghi\\njkl\"\n" + - "}\n").trim().replace("\r\n", "\n") + "\n"; + String expected = (""" + + "abc" + { + \t"def"\t\t"ghi\\njkl" + } + """).trim().replace("\r\n", "\n") + "\n"; Assertions.assertEquals(expected, text); } diff --git a/src/test/java/in/dragonbra/javasteam/types/SteamIDTests.java b/src/test/java/in/dragonbra/javasteam/types/SteamIDTests.java index b581ae578..4c9cf32ad 100644 --- a/src/test/java/in/dragonbra/javasteam/types/SteamIDTests.java +++ b/src/test/java/in/dragonbra/javasteam/types/SteamIDTests.java @@ -266,7 +266,7 @@ public void steamIDsEquality() { assertEquals(sid, sid2); - assertNotEquals(sid, new Object()); + assertNotEquals(new Object(), sid); SteamID sid3 = new SteamID(12345L); assertNotEquals(sid, sid3); diff --git a/src/test/java/in/dragonbra/javasteam/util/crypto/CryptoHelperTest.java b/src/test/java/in/dragonbra/javasteam/util/crypto/CryptoHelperTest.java index edd90bc32..1c7fc78a6 100644 --- a/src/test/java/in/dragonbra/javasteam/util/crypto/CryptoHelperTest.java +++ b/src/test/java/in/dragonbra/javasteam/util/crypto/CryptoHelperTest.java @@ -3,7 +3,11 @@ import in.dragonbra.javasteam.TestBase; import org.junit.jupiter.api.Test; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public class CryptoHelperTest extends TestBase { @@ -79,4 +83,24 @@ public void symmetricDecryptHMACIV() throws CryptoException { assertArrayEquals(expected, result); } + + @Test + public void symmetricDecryptHMACIVThrowsOnHmacMismatch() throws CryptoException { + byte[] key = new byte[32]; + for (int i = 0; i < key.length; i++) { + key[i] = (byte) i; + } + + byte[] secret = Arrays.copyOf(key, 16); + byte[] plaintext = "javasteam".getBytes(StandardCharsets.UTF_8); + + byte[] encrypted = CryptoHelper.symmetricEncryptWithHMACIV(plaintext, key, secret); + assertArrayEquals(plaintext, CryptoHelper.symmetricDecryptHMACIV(encrypted, key, secret)); + + // The same packet checked with a different HMAC secret must fail validation. + byte[] wrongSecret = secret.clone(); + wrongSecret[wrongSecret.length - 1] ^= 0x01; + + assertThrows(CryptoException.class, () -> CryptoHelper.symmetricDecryptHMACIV(encrypted, key, wrongSecret)); + } } \ No newline at end of file