fix(ea): keep real save folders in the inventory, back up any restored file, refuse duplicate or malformed cloud listings

This commit is contained in:
Kurt Himebauch committed 2026-11-18 11:10:02 -05:00
1 parent dba3fcd99e
commit a113656196
4 files changed
+54 -8

No files matched your search

@@ -368,10 +368,12 @@ object CloudSaves {
private fun localFiles(dir: File): Map<String, File> {
if (!dir.isDirectory) return emptyMap()
val root = runCatching { dir.canonicalPath + File.separator }.getOrNull() ?: return emptyMap()
val real = runCatching { dir.canonicalFile }.getOrNull() ?: return emptyMap()
val root = real.path + File.separator
val inside = { f: File -> runCatching { (f.canonicalPath + File.separator).startsWith(root) }.getOrDefault(false) }
val seen = HashSet<String>()
val enter = { d: File -> inside(d) && runCatching { seen.add(d.canonicalPath) }.getOrDefault(false) }
val enter = { d: File ->
runCatching { d == dir || d.canonicalFile == File(real, d.relativeTo(dir).path) }.getOrDefault(false)
}
return dir.walkTopDown().onEnter(enter).filter { it.isFile && inside(it) }
.associateBy { it.relativeTo(dir).path.replace(File.separatorChar, '/') }
}
@@ -395,7 +397,11 @@ object CloudSaves {
val base = baseline(context, store, id)
val plan = CloudPlan.down(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
val take = if (force) plan.transfer + plan.conflicts else plan.transfer
if (!backupReplaced(context, store, id, dir, take.mapNotNull { files[it] })) return Result("failed", 0, 0, "backup-failed")
val inside = dir.canonicalPath + File.separator
val replaced = take.mapNotNull { name ->
files[name] ?: File(dir, name).takeIf { it.isFile && runCatching { it.canonicalPath.startsWith(inside) }.getOrDefault(false) }
}
if (!backupReplaced(context, store, id, dir, replaced)) return Result("failed", 0, 0, "backup-failed")
val next = HashMap(base.orEmpty())
var bytes = 0L
for (name in take) {
@@ -512,7 +518,7 @@ object CloudSaves {
if (replaced.isEmpty()) return true
val base = runCatching { dir.canonicalPath + File.separator }.getOrNull() ?: return false
val root = backupRoot(context, store, id)
val stamp = System.currentTimeMillis()
val stamp = "${System.currentTimeMillis()}-${java.util.UUID.randomUUID().toString().take(8)}"
val staging = File(root, "staging-$stamp")
val copied = runCatching {
for (f in replaced) {
@@ -1,11 +1,14 @@
package com.droiddeck.launcher.stores.ea
import android.util.Base64
import android.util.Xml
import com.droiddeck.launcher.stores.CloudFile
import com.droiddeck.launcher.stores.CloudTransport
import java.io.File
import java.io.StringReader
import java.security.MessageDigest
import java.time.Instant
import org.xmlpull.v1.XmlPullParser
internal class EaCloud(
private val token: String,
@@ -40,6 +43,8 @@ internal class EaCloud(
val md5 = hex(e.md5) ?: error("EA listed ${path.substring(base.length)} without a valid checksum")
CloudFile(localName(path.substring(base.length)), parseTime(e.modified), md5, readLink = e.href)
}
val twins = files.groupBy { it.name.lowercase() }.values.firstOrNull { it.size > 1 }
check(twins == null) { "EA lists more than one save named ${twins!!.first().name} in different cases" }
listed = files.associate { it.name.lowercase() to it.md5 }
return files
}
@@ -112,7 +117,7 @@ internal class EaCloud(
private fun pick(): Manifest? {
for (candidate in keys) {
val manifest = locked("read", candidate) { _, body -> manifestUrl(body)?.let { fetchManifest(it) } }
val manifest = locked("read", candidate, missing = { null }) { _, body -> manifestUrl(body)?.let { fetchManifest(it) } }
if (manifest != null) {
key = candidate
found = true
@@ -136,8 +141,9 @@ internal class EaCloud(
return parse(reply.text)
}
private fun <T> locked(kind: String, key: String, body: (String, String) -> T): T {
private fun <T> locked(kind: String, key: String, missing: (() -> T)? = null, body: (String, String) -> T): T {
val reply = EaHttp.request("$HOST/lock/$kind/$uid/$key", "POST", mapOf(AUTH to token, "Content-Type" to "application/xml"), ByteArray(0))
if (reply.status == 404 && missing != null) return missing()
check(reply.ok) { "EA cloud saves answered ${reply.status}" }
val lock = reply.header(LOCK) ?: error("EA did not grant a cloud save lock")
try {
@@ -179,7 +185,7 @@ internal class EaCloud(
fun manifestUrl(lockBody: String): String? = Regex("<manifest>([^<]+)</manifest>").find(lockBody)?.groupValues?.get(1)?.let(::unescape)
fun parse(xml: String): Manifest {
check(xml.trimEnd().endsWith("</manifest>")) { "EA sent an incomplete cloud save manifest" }
check(wellFormed(xml)) { "EA sent an incomplete cloud save manifest" }
val lineage = attr(Regex("<manifest\\b([^>]*)>").find(xml)?.groupValues?.get(1).orEmpty(), "lineage")
?: "{00000000-0000-0000-0000-000000000000}"
val files = FILE.findAll(xml).mapNotNull { m ->
@@ -191,6 +197,19 @@ internal class EaCloud(
return Manifest(lineage, files, SNAPSHOT.findAll(xml).map { unescape(it.groupValues[1]) }.toList())
}
private fun wellFormed(xml: String): Boolean = runCatching {
val p = Xml.newPullParser()
p.setInput(StringReader(xml))
var root: String? = null
var depth = 0
var closed = false
while (p.next() != XmlPullParser.END_DOCUMENT) when (p.eventType) {
XmlPullParser.START_TAG -> { if (root == null) root = p.name; depth++ }
XmlPullParser.END_TAG -> { depth--; if (depth == 0) closed = true }
}
root == "manifest" && depth == 0 && closed
}.getOrDefault(false)
fun write(m: Manifest): String = buildString {
append("<manifest xmlns=\"http://origin.com/cloudsaves/manifest\" lineage=\"").append(escape(m.lineage)).append("\">\n")
for (f in m.files) {
@@ -50,6 +50,21 @@ class CloudSavesTest {
assertEquals("v1", File(kept, "slot0.sav").readText())
}
@Test fun aFolderAliasNeverHidesTheRealSaveFromARestore() {
val game = id; val dir = dir()
File(dir, "SaveData").mkdirs(); File(dir, "SaveData/slot.sav").writeText("local")
val link = runCatching { java.nio.file.Files.createSymbolicLink(File(dir, "Cache").toPath(), File(dir, "SaveData").toPath()) }
org.junit.Assume.assumeTrue(link.isSuccess)
val memory = Memory().apply { files["SaveData/slot.sav"] = "cloud".toByteArray() to 1000L }
val cloud = object : CloudTransport by memory {
override fun wants(name: String) = name.startsWith("SaveData/")
}
CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = true)
assertEquals("cloud", File(dir, "SaveData/slot.sav").readText())
val kept = File(app.filesDir, "stores/cloud-backups/gog-$game").listFiles { f -> f.name.startsWith("local-") }!!.single()
assertEquals("local", File(kept, "SaveData/slot.sav").readText())
}
@Test fun aFileChangedOnBothSidesIsLeftForTheUser() {
val game = id; val dir = dir()
val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L }
@@ -461,6 +461,10 @@ class EaTest {
val again = EaCloud.parse(EaCloud.write(m))
assertEquals(m.files.single().localName, again.files.single().localName)
assertEquals(m.files.single().href, again.files.single().href)
assertEquals(m.files.single().created, again.files.single().created)
assertEquals(m.files.single().modified, again.files.single().modified)
assertEquals(m.files.single().size, again.files.single().size)
assertEquals(m.files.single().md5, again.files.single().md5)
assertEquals(listOf("80cmnqT/rIKQRmciINSVhQ=="), again.snapshots)
assertEquals(m.lineage, again.lineage)
}
@@ -478,6 +482,8 @@ class EaTest {
@Test fun aTruncatedManifestIsRefused() {
val cut = runCatching { EaCloud.parse("""<manifest lineage="{1}"><file size="1" href="content/1-a" md5="x5lr6ApuONH47yiGaxFPiw==">""") }
assertTrue(cut.isFailure)
val open = runCatching { EaCloud.parse("""<manifest lineage="{1}"><file size="1" href="content/1-a" md5="x5lr6ApuONH47yiGaxFPiw=="><localName>%Documents%/a</localName></manifest>""") }
assertTrue(open.isFailure)
}
@Test fun snapshotEntitiesAreDecodedOnceAndWrittenBackTheSame() {