Harden untrusted-file parsing, drop two audio-thread allocations, prune dead code (v0.24.0)
SECURITY
A crafted .sf2 hung the app. SoundFontLoader's RIFF walk trusted the chunk
sizes in the file: a negative size moved the cursor BACKWARDS, so the walk
re-read the same chunk header forever. runCatching cannot catch that — there is
no exception, just a thread that never returns. 76 bytes was enough. Every seek
in both the chunk and sub-chunk loops is now forced forward, negative sizes end
the walk, and the sample offset is resolved in Long so a hostile 32-bit start
index can no longer wrap Int and land the read somewhere arbitrary.
Neither ZIP import had a decompression budget. The zip-slip path check does not
see a bomb, because its entries are perfectly well-named — they are just
enormous. A restore streams to disk and filled the device; a project bundle
accumulates in memory and exhausted the heap. New ZipLimits budgets both, with
different limits because they fail differently: 512 MB for a restore, 64 MB for
a bundle, 20k entries either way. An over-budget archive is rejected like any
other bad file, leaving existing data untouched.
PlaybackService was exported with no permission, so any app on the device could
bind the MediaSessionService and take transport control. Now exported="false".
Verified on an emulator that this changes nothing that matters: the session is
still the system's media button session, the notification still posts, the
foreground service survives backgrounding, no SecurityException. The only loss
is discovery by external media browsers (Auto, Assistant, Wear), which this app
never supported.
String.format("%.2f") in three parameter readouts used the default locale, so a
comma-decimal locale rendered knob values inconsistently with the rest of the
monospace UI. Pinned to Locale.US.
PERFORMANCE
Two allocations removed from threads documented as allocation-free:
- applyLfos() called target.substring(sep + 1) every block for each active
LFO (~250/s each), in a function that already parses the slot index
character-by-character to avoid exactly this. Now matched with
regionMatches, which allocates nothing.
- busNoteOn() built `(0 until N).map { … }.firstOrNull { … }` twice — a range
iterator plus an ArrayList per incoming MIDI note. Replaced with an indexed
freeBusVoice() scan, matching the style used elsewhere in the file.
DEAD CODE
Arrangement.isLaneMuted had no callers (everything reads laneMuted[] directly).
Four tab-title strings and a notification-channel name were left over from an
earlier design — the tabs are composed with literals and media3 names its own
channel. Added the missing android:roundIcon, which is why lint thought
ic_launcher_round was unused; the asset was always meant to be referenced.
Lint is clean of UnusedResources, DefaultLocale and ExportedService. Its
remaining ObsoleteSdkInt advice — merge mipmap-anydpi-v26 into mipmap-anydpi —
is wrong for this AGP version and was reverted: aapt then fails to resolve the
launcher icons at all.
NOT CHANGED, flagged for a decision: android:allowBackup is still true, so
projects, presets, themes and the settings/bindings DataStore go to Google's
cloud backup. That is a standard hardening finding, but it is also a data
portability feature, and the app now has its own backup/restore — a product
call rather than a defect.
New tests: SoundFontLoaderTest (hostile SF2 headers, with timeouts — the hang
reproduces as a TestTimedOutException without the fix) and ZipBombTest (both
import paths, plus a guard that an ordinary backup still restores).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
3453f9f003
commit
deb582727f
@@ -26,6 +26,7 @@
|
|||||||
android:name=".SizzleApp"
|
android:name=".SizzleApp"
|
||||||
android:allowBackup="true"
|
android:allowBackup="true"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
android:label="@string/app_name"
|
android:label="@string/app_name"
|
||||||
android:supportsRtl="false"
|
android:supportsRtl="false"
|
||||||
android:theme="@style/Theme.Sizzletracker">
|
android:theme="@style/Theme.Sizzletracker">
|
||||||
@@ -64,10 +65,19 @@
|
|||||||
</provider>
|
</provider>
|
||||||
|
|
||||||
<!-- Foreground service that owns the audio engine so playback survives
|
<!-- Foreground service that owns the audio engine so playback survives
|
||||||
when the UI is not visible, and drives the media notification. -->
|
when the UI is not visible, and drives the media notification.
|
||||||
|
|
||||||
|
NOT exported: a MediaSessionService with exported="true" and no
|
||||||
|
permission can be bound by any app on the device, which would hand it
|
||||||
|
transport control over the session. Nothing here needs an external
|
||||||
|
controller — the system's own media notification and lockscreen
|
||||||
|
controls reach the MediaSession directly, not by binding the service,
|
||||||
|
and the app starts it from its own process. The cost is that external
|
||||||
|
media browsers (Android Auto, Assistant, Wear) can no longer discover
|
||||||
|
it, which this app never supported anyway. -->
|
||||||
<service
|
<service
|
||||||
android:name=".playback.PlaybackService"
|
android:name=".playback.PlaybackService"
|
||||||
android:exported="true"
|
android:exported="false"
|
||||||
android:foregroundServiceType="mediaPlayback">
|
android:foregroundServiceType="mediaPlayback">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="androidx.media3.session.MediaSessionService" />
|
<action android:name="androidx.media3.session.MediaSessionService" />
|
||||||
|
|||||||
@@ -820,10 +820,19 @@ class AudioEngine(
|
|||||||
if (!validIdx || tIdx == i) continue
|
if (!validIdx || tIdx == i) continue
|
||||||
val tSlot = proj.toolbox.getOrNull(tIdx) ?: continue
|
val tSlot = proj.toolbox.getOrNull(tIdx) ?: continue
|
||||||
val params = tSlot.type?.params ?: continue
|
val params = tSlot.type?.params ?: continue
|
||||||
val key = target.substring(sep + 1)
|
// Match the param key by region rather than target.substring(sep + 1):
|
||||||
|
// this runs every block for each active LFO, and the slot-index parse
|
||||||
|
// above already goes to this trouble. regionMatches allocates nothing.
|
||||||
|
val keyFrom = sep + 1
|
||||||
|
val keyLen = target.length - keyFrom
|
||||||
// Indexed scan (not firstOrNull {}) so no Iterator allocates per block.
|
// Indexed scan (not firstOrNull {}) so no Iterator allocates per block.
|
||||||
var specIdx = -1
|
var specIdx = -1
|
||||||
for (pi in params.indices) if (params[pi].key == key) { specIdx = pi; break }
|
for (pi in params.indices) {
|
||||||
|
val k = params[pi].key
|
||||||
|
if (k.length == keyLen && target.regionMatches(keyFrom, k, 0, keyLen)) {
|
||||||
|
specIdx = pi; break
|
||||||
|
}
|
||||||
|
}
|
||||||
if (specIdx < 0) continue
|
if (specIdx < 0) continue
|
||||||
val spec = params[specIdx]
|
val spec = params[specIdx]
|
||||||
|
|
||||||
@@ -845,7 +854,7 @@ class AudioEngine(
|
|||||||
val half = (spec.max - spec.min) / 2.0
|
val half = (spec.max - spec.min) / 2.0
|
||||||
val modulated = (center + lfo.float("depth", 0.5f) * value * half)
|
val modulated = (center + lfo.float("depth", 0.5f) * value * half)
|
||||||
.coerceIn(spec.min.toDouble(), spec.max.toDouble())
|
.coerceIn(spec.min.toDouble(), spec.max.toDouble())
|
||||||
tSlot.set(key, modulated.toFloat())
|
tSlot.set(spec.key, modulated.toFloat())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1272,22 +1281,35 @@ class AudioEngine(
|
|||||||
val vs = voiceSample(slot, midi)
|
val vs = voiceSample(slot, midi)
|
||||||
when {
|
when {
|
||||||
vs != null -> {
|
vs != null -> {
|
||||||
val v = (0 until BUS_POLYPHONY).map { busSampleVoices[base + it] }
|
val v = freeBusVoice(busSampleVoices, base)
|
||||||
.firstOrNull { !it.isActive } ?: busSampleVoices[base].also { it.kill() }
|
|
||||||
v.noteOn(vs.sample, midi, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume,
|
v.noteOn(vs.sample, midi, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume,
|
||||||
vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs)
|
vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs)
|
||||||
}
|
}
|
||||||
// Sampler with an empty pad → silent (no synth fallback).
|
// Sampler with an empty pad → silent (no synth fallback).
|
||||||
type == ToolboxType.SAMPLER -> {}
|
type == ToolboxType.SAMPLER -> {}
|
||||||
else -> {
|
else -> {
|
||||||
val v = (0 until BUS_POLYPHONY).map { busVoices[base + it] }
|
val v = freeBusVoice(busVoices, base)
|
||||||
.firstOrNull { !it.isActive } ?: busVoices[base].also { it.kill() }
|
|
||||||
v.noteOn(midi, velocity, synthPatch[ch] ?: patchForSlot(slot, proj.tempoBpm))
|
v.noteOn(midi, velocity, synthPatch[ch] ?: patchForSlot(slot, proj.tempoBpm))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// First idle voice in the bus's BUS_POLYPHONY slice, stealing slot 0 when all are
|
||||||
|
// busy. Indexed, because the obvious `(0 until N).map { … }.firstOrNull { … }`
|
||||||
|
// allocated a range iterator and an ArrayList for every incoming MIDI note — on
|
||||||
|
// the thread that is supposed to stay allocation-free. Two concrete overloads
|
||||||
|
// rather than a generic one: the voice pools are differently typed arrays.
|
||||||
|
private fun freeBusVoice(pool: Array<SynthVoice>, base: Int): SynthVoice {
|
||||||
|
for (i in 0 until BUS_POLYPHONY) if (!pool[base + i].isActive) return pool[base + i]
|
||||||
|
return pool[base].also { it.kill() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun freeBusVoice(pool: Array<SampleVoice>, base: Int): SampleVoice {
|
||||||
|
for (i in 0 until BUS_POLYPHONY) if (!pool[base + i].isActive) return pool[base + i]
|
||||||
|
return pool[base].also { it.kill() }
|
||||||
|
}
|
||||||
|
|
||||||
/** Release [midi] on every mixer channel listening on [midiChannel]. */
|
/** Release [midi] on every mixer channel listening on [midiChannel]. */
|
||||||
fun busNoteOff(midiChannel: Int, midi: Int) {
|
fun busNoteOff(midiChannel: Int, midi: Int) {
|
||||||
val proj = project ?: return
|
val proj = project ?: return
|
||||||
|
|||||||
@@ -44,22 +44,36 @@ object SoundFontLoader {
|
|||||||
if (readTag(bb) != "sfbk") return null
|
if (readTag(bb) != "sfbk") return null
|
||||||
|
|
||||||
var smplOff = -1; var shdrOff = -1; var shdrBytes = 0
|
var smplOff = -1; var shdrOff = -1; var shdrBytes = 0
|
||||||
|
// RIFF chunk walk over attacker-controlled sizes. Every seek is forced
|
||||||
|
// FORWARD: a negative (or merely small) size would otherwise move the cursor
|
||||||
|
// back to bytes already read, and the walk would re-read the same chunk
|
||||||
|
// header forever. That is not an exception runCatching can mop up — it is a
|
||||||
|
// thread that never returns, i.e. an ANR from a handful of crafted bytes.
|
||||||
while (bb.remaining() >= 8) {
|
while (bb.remaining() >= 8) {
|
||||||
|
val chunkStart = bb.position()
|
||||||
val id = readTag(bb)
|
val id = readTag(bb)
|
||||||
val size = bb.int
|
val size = bb.int
|
||||||
val chunkEnd = (bb.position() + size).coerceAtMost(bb.limit())
|
if (size < 0) break // a size that cannot be honoured ends the walk
|
||||||
|
val chunkEnd = (bb.position().toLong() + size).coerceAtMost(bb.limit().toLong()).toInt()
|
||||||
if (id == "LIST" && bb.remaining() >= 4) {
|
if (id == "LIST" && bb.remaining() >= 4) {
|
||||||
val listType = readTag(bb)
|
val listType = readTag(bb)
|
||||||
while (bb.position() + 8 <= chunkEnd) {
|
while (bb.position() + 8 <= chunkEnd) {
|
||||||
|
val subStart = bb.position()
|
||||||
val sid = readTag(bb)
|
val sid = readTag(bb)
|
||||||
val ssize = bb.int
|
val ssize = bb.int
|
||||||
|
if (ssize < 0) break
|
||||||
val dataPos = bb.position()
|
val dataPos = bb.position()
|
||||||
if (listType == "sdta" && sid == "smpl") smplOff = dataPos
|
if (listType == "sdta" && sid == "smpl") smplOff = dataPos
|
||||||
if (listType == "pdta" && sid == "shdr") { shdrOff = dataPos; shdrBytes = ssize }
|
if (listType == "pdta" && sid == "shdr") { shdrOff = dataPos; shdrBytes = ssize }
|
||||||
bb.position((dataPos + ssize + (ssize and 1)).coerceAtMost(bb.limit()))
|
val next = (dataPos.toLong() + ssize + (ssize and 1))
|
||||||
|
.coerceIn(0L, bb.limit().toLong()).toInt()
|
||||||
|
if (next <= subStart) break // no forward progress
|
||||||
|
bb.position(next)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
bb.position((chunkEnd + (size and 1)).coerceAtMost(bb.limit()))
|
val next = (chunkEnd.toLong() + (size and 1)).coerceIn(0L, bb.limit().toLong()).toInt()
|
||||||
|
if (next <= chunkStart) break // no forward progress
|
||||||
|
bb.position(next)
|
||||||
}
|
}
|
||||||
if (smplOff < 0 || shdrOff < 0 || shdrBytes < SHDR_REC) return null
|
if (smplOff < 0 || shdrOff < 0 || shdrBytes < SHDR_REC) return null
|
||||||
|
|
||||||
@@ -78,8 +92,10 @@ object SoundFontLoader {
|
|||||||
val frames = (end - start).coerceIn(0L, MAX_FRAMES.toLong()).toInt()
|
val frames = (end - start).coerceIn(0L, MAX_FRAMES.toLong()).toInt()
|
||||||
if (frames <= 0) return null
|
if (frames <= 0) return null
|
||||||
val out = FloatArray(frames)
|
val out = FloatArray(frames)
|
||||||
val db = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
|
// start is a 32-bit unsigned frame index: `start.toInt() * 2` would wrap for a
|
||||||
.apply { position((smplOff + start.toInt() * 2).coerceIn(0, bytes.size)) }
|
// hostile value and land the read at an arbitrary offset. Resolve in Long.
|
||||||
|
val readAt = (smplOff.toLong() + start * 2L).coerceIn(0L, bytes.size.toLong()).toInt()
|
||||||
|
val db = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).apply { position(readAt) }
|
||||||
var i = 0
|
var i = 0
|
||||||
while (i < frames && db.remaining() >= 2) { out[i] = db.short / 32768f; i++ }
|
while (i < frames && db.remaining() >= 2) { out[i] = db.short / 32768f; i++ }
|
||||||
|
|
||||||
|
|||||||
@@ -47,17 +47,22 @@ object BackupIo {
|
|||||||
val stagingRoot = staging.canonicalPath + File.separator
|
val stagingRoot = staging.canonicalPath + File.separator
|
||||||
|
|
||||||
var any = false
|
var any = false
|
||||||
|
// The zip-slip check below cannot see a decompression bomb — its entries are
|
||||||
|
// perfectly well-named, they are just enormous. Budget the extraction too, or
|
||||||
|
// a few hundred KB of nested zeroes fills the device's storage.
|
||||||
|
val budget = ZipLimits.forBackup()
|
||||||
try {
|
try {
|
||||||
ZipInputStream(BufferedInputStream(input)).use { zin ->
|
ZipInputStream(BufferedInputStream(input)).use { zin ->
|
||||||
var entry: ZipEntry? = zin.nextEntry
|
var entry: ZipEntry? = zin.nextEntry
|
||||||
while (entry != null) {
|
while (entry != null) {
|
||||||
|
budget.countEntry()
|
||||||
val name = entry.name
|
val name = entry.name
|
||||||
if (!entry.isDirectory && !name.contains("..")) {
|
if (!entry.isDirectory && !name.contains("..")) {
|
||||||
val target = File(staging, name)
|
val target = File(staging, name)
|
||||||
// Zip-slip guard: the resolved path must stay inside staging.
|
// Zip-slip guard: the resolved path must stay inside staging.
|
||||||
if (target.canonicalPath.startsWith(stagingRoot)) {
|
if (target.canonicalPath.startsWith(stagingRoot)) {
|
||||||
target.parentFile?.mkdirs()
|
target.parentFile?.mkdirs()
|
||||||
target.outputStream().use { zin.copyTo(it) }
|
target.outputStream().use { budget.copy(zin, it) }
|
||||||
any = true
|
any = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -66,7 +71,8 @@ object BackupIo {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
// A truncated / non-ZIP file: bail out without touching the live data.
|
// A truncated / non-ZIP file, or one over budget: bail out without
|
||||||
|
// touching the live data, and drop whatever was staged.
|
||||||
staging.deleteRecursively(); return false
|
staging.deleteRecursively(); return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -61,13 +61,18 @@ object ProjectBundleIo {
|
|||||||
var projectText: String? = null
|
var projectText: String? = null
|
||||||
val manifest = HashMap<String, String>() // sample index -> original id
|
val manifest = HashMap<String, String>() // sample index -> original id
|
||||||
val wavByIndex = HashMap<String, ByteArray>() // sample index -> WAV bytes
|
val wavByIndex = HashMap<String, ByteArray>() // sample index -> WAV bytes
|
||||||
|
// Every entry is held in memory until the whole bundle is read, so an
|
||||||
|
// oversized or bomb archive is an OOM rather than a full disk here. Same
|
||||||
|
// budget, same outcome: reject the file and leave the project untouched.
|
||||||
|
val budget = ZipLimits.forBundle()
|
||||||
try {
|
try {
|
||||||
ZipInputStream(BufferedInputStream(input)).use { zin ->
|
ZipInputStream(BufferedInputStream(input)).use { zin ->
|
||||||
var entry: ZipEntry? = zin.nextEntry
|
var entry: ZipEntry? = zin.nextEntry
|
||||||
while (entry != null) {
|
while (entry != null) {
|
||||||
|
budget.countEntry()
|
||||||
val name = entry.name
|
val name = entry.name
|
||||||
if (!entry.isDirectory && !name.contains("..")) {
|
if (!entry.isDirectory && !name.contains("..")) {
|
||||||
val bytes = zin.readBytes()
|
val bytes = budget.readBytes(zin)
|
||||||
when {
|
when {
|
||||||
name == PROJECT_ENTRY -> projectText = String(bytes, Charsets.UTF_8)
|
name == PROJECT_ENTRY -> projectText = String(bytes, Charsets.UTF_8)
|
||||||
name == MANIFEST -> String(bytes, Charsets.UTF_8).lineSequence().forEach { ln ->
|
name == MANIFEST -> String(bytes, Charsets.UTF_8).lineSequence().forEach { ln ->
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
package cc.tiredsysadmin.android.sizzle.io
|
||||||
|
|
||||||
|
import java.io.InputStream
|
||||||
|
import java.io.OutputStream
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Guards against decompression bombs in the two archives the user can hand the app
|
||||||
|
* from anywhere on the device: a full backup ([BackupIo]) and a shared project
|
||||||
|
* bundle ([ProjectBundleIo]).
|
||||||
|
*
|
||||||
|
* A ZIP reports its own sizes, and nothing obliges them to be true. A few hundred
|
||||||
|
* kilobytes of nested zeroes expands to gigabytes, which fills the device's storage
|
||||||
|
* in the backup case and exhausts the heap in the bundle case — neither of which the
|
||||||
|
* zip-slip path check catches, because every entry is perfectly well-named. The only
|
||||||
|
* reliable defence is to stop reading at a budget and treat overrun as a bad file.
|
||||||
|
*
|
||||||
|
* There are two budgets because the two paths fail differently: a restore streams
|
||||||
|
* to disk and runs out of storage, while a bundle accumulates in memory and runs out
|
||||||
|
* of heap. Both are set well above any real project — they exist to stop a bomb, not
|
||||||
|
* to cap a user.
|
||||||
|
*/
|
||||||
|
object ZipLimits {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Budget for a whole-app restore, which streams each entry straight to disk.
|
||||||
|
* The threat is filling the device, so this can be generous: a phone-sized
|
||||||
|
* sample library sits far below it.
|
||||||
|
*/
|
||||||
|
const val MAX_BACKUP_BYTES = 512L * 1024 * 1024
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Budget for a project bundle, which is held in memory until the archive has
|
||||||
|
* been read in full. The threat is the heap, not the disk, and an Android heap
|
||||||
|
* is typically a couple of hundred megabytes — so this is much tighter. One
|
||||||
|
* project's samples (a handful of pads, seconds each) are nowhere near it.
|
||||||
|
*/
|
||||||
|
const val MAX_BUNDLE_BYTES = 64L * 1024 * 1024
|
||||||
|
|
||||||
|
/** Entries allowed in one archive, so a bomb cannot be spread thinly either. */
|
||||||
|
const val MAX_ENTRIES = 20_000
|
||||||
|
|
||||||
|
/** Raised when an archive exceeds a budget; callers reject the file. */
|
||||||
|
class TooLarge(message: String) : Exception(message)
|
||||||
|
|
||||||
|
/** Budget for a whole-app restore (streamed to disk). */
|
||||||
|
fun forBackup() = Budget(MAX_BACKUP_BYTES)
|
||||||
|
|
||||||
|
/** Budget for a project bundle (accumulated in memory). */
|
||||||
|
fun forBundle() = Budget(MAX_BUNDLE_BYTES)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A running total across the entries of one archive. Not thread-safe: an import
|
||||||
|
* is a single sequential pass.
|
||||||
|
*/
|
||||||
|
class Budget(
|
||||||
|
private val maxTotalBytes: Long,
|
||||||
|
private val maxEntries: Int = MAX_ENTRIES,
|
||||||
|
) {
|
||||||
|
private var bytes = 0L
|
||||||
|
private var entries = 0
|
||||||
|
|
||||||
|
/** Count one entry. Throws [TooLarge] past [maxEntries]. */
|
||||||
|
fun countEntry() {
|
||||||
|
if (++entries > maxEntries) throw TooLarge("archive has more than $maxEntries entries")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Copy one entry's bytes to [out], charging them to the budget. */
|
||||||
|
fun copy(input: InputStream, out: OutputStream) {
|
||||||
|
val buf = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||||
|
while (true) {
|
||||||
|
val n = input.read(buf)
|
||||||
|
if (n <= 0) break
|
||||||
|
charge(n)
|
||||||
|
out.write(buf, 0, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read one entry fully into memory, charging it to the budget. */
|
||||||
|
fun readBytes(input: InputStream): ByteArray {
|
||||||
|
val out = java.io.ByteArrayOutputStream()
|
||||||
|
copy(input, out)
|
||||||
|
return out.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun charge(n: Int) {
|
||||||
|
bytes += n
|
||||||
|
if (bytes > maxTotalBytes) {
|
||||||
|
throw TooLarge("archive expands past ${maxTotalBytes / (1024 * 1024)} MB")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,8 +22,6 @@ class Arrangement {
|
|||||||
* never sound) while its cells stay in place. Read live on the audio thread. */
|
* never sound) while its cells stay in place. Read live on the audio thread. */
|
||||||
val laneMuted: BooleanArray = BooleanArray(LANE_COUNT)
|
val laneMuted: BooleanArray = BooleanArray(LANE_COUNT)
|
||||||
|
|
||||||
fun isLaneMuted(lane: Int): Boolean = lane in 0 until LANE_COUNT && laneMuted[lane]
|
|
||||||
|
|
||||||
/** Editable canvas width in *bars*. */
|
/** Editable canvas width in *bars*. */
|
||||||
var lengthBars: Int = MAX_BARS
|
var lengthBars: Int = MAX_BARS
|
||||||
|
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ import cc.tiredsysadmin.android.sizzle.ui.components.RetroDropdown
|
|||||||
import cc.tiredsysadmin.android.sizzle.ui.theme.LocalRetro
|
import cc.tiredsysadmin.android.sizzle.ui.theme.LocalRetro
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The bespoke editor for the subtractive synth ([cc.tiredsysadmin.android.sizzle.model.ToolboxType.NES_SYNTH]).
|
* The bespoke editor for the subtractive synth ([cc.tiredsysadmin.android.sizzle.model.ToolboxType.NES_SYNTH]).
|
||||||
@@ -183,7 +184,7 @@ private fun ParamKnob(
|
|||||||
) {
|
) {
|
||||||
@Suppress("UNUSED_PARAMETER") val ignored = rev
|
@Suppress("UNUSED_PARAMETER") val ignored = rev
|
||||||
val value = slot.float(key, default)
|
val value = slot.float(key, default)
|
||||||
val text = if (isInt) "${value.roundToInt()}$unit" else String.format("%.2f", value) + unit
|
val text = if (isInt) "${value.roundToInt()}$unit" else String.format(Locale.US, "%.2f", value) + unit
|
||||||
Knob(label, value, min, max, text, modifier, default) { nv ->
|
Knob(label, value, min, max, text, modifier, default) { nv ->
|
||||||
slot.set(key, if (isInt) nv.roundToInt().toFloat() else nv)
|
slot.set(key, if (isInt) nv.roundToInt().toFloat() else nv)
|
||||||
vm.bumpForToolbar()
|
vm.bumpForToolbar()
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import cc.tiredsysadmin.android.sizzle.ui.AppViewModel
|
|||||||
import cc.tiredsysadmin.android.sizzle.ui.components.RetroDropdown
|
import cc.tiredsysadmin.android.sizzle.ui.components.RetroDropdown
|
||||||
import cc.tiredsysadmin.android.sizzle.ui.theme.LocalRetro
|
import cc.tiredsysadmin.android.sizzle.ui.theme.LocalRetro
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One editable parameter row. Enumerated params ([ParamSpec.isEnum]) render as a
|
* One editable parameter row. Enumerated params ([ParamSpec.isEnum]) render as a
|
||||||
@@ -66,4 +67,4 @@ fun ParamControl(vm: AppViewModel, slot: ToolboxSlot, spec: ParamSpec) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun formatValue(v: Float): String =
|
private fun formatValue(v: Float): String =
|
||||||
if (v == v.toInt().toFloat()) v.toInt().toString() else String.format("%.2f", v)
|
if (v == v.toInt().toFloat()) v.toInt().toString() else String.format(Locale.US, "%.2f", v)
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ import cc.tiredsysadmin.android.sizzle.ui.components.PianoOctave
|
|||||||
import cc.tiredsysadmin.android.sizzle.ui.components.RepeatButton
|
import cc.tiredsysadmin.android.sizzle.ui.components.RepeatButton
|
||||||
import cc.tiredsysadmin.android.sizzle.ui.components.RetroButton
|
import cc.tiredsysadmin.android.sizzle.ui.components.RetroButton
|
||||||
import cc.tiredsysadmin.android.sizzle.ui.theme.LocalRetro
|
import cc.tiredsysadmin.android.sizzle.ui.theme.LocalRetro
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
/** Upper bound (ms) for the SoundFont loop crossfade stepper. */
|
/** Upper bound (ms) for the SoundFont loop crossfade stepper. */
|
||||||
private const val MAX_XFADE_MS = 500
|
private const val MAX_XFADE_MS = 500
|
||||||
@@ -203,7 +204,7 @@ private fun VerticalSlider(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun formatSliderValue(v: Float): String =
|
private fun formatSliderValue(v: Float): String =
|
||||||
if (v == v.toInt().toFloat()) v.toInt().toString() else String.format("%.2f", v)
|
if (v == v.toInt().toFloat()) v.toInt().toString() else String.format(Locale.US, "%.2f", v)
|
||||||
|
|
||||||
/** A slot-auditioning keyboard, laid out and sized like the shared audition /
|
/** A slot-auditioning keyboard, laid out and sized like the shared audition /
|
||||||
* punch-in keyboard ([cc.tiredsysadmin.android.sizzle.ui.StackedKeyboard]): a small octave
|
* punch-in keyboard ([cc.tiredsysadmin.android.sizzle.ui.StackedKeyboard]): a small octave
|
||||||
|
|||||||
@@ -1,12 +1,3 @@
|
|||||||
<resources>
|
<resources>
|
||||||
<string name="app_name">Sizzletracker</string>
|
<string name="app_name">Sizzletracker</string>
|
||||||
|
|
||||||
<!-- Tab titles -->
|
|
||||||
<string name="tab_tracker">TRACKER</string>
|
|
||||||
<string name="tab_mixer">MIX</string>
|
|
||||||
<string name="tab_toolbox">TOOLBOX</string>
|
|
||||||
<string name="tab_settings">SETUP</string>
|
|
||||||
|
|
||||||
<!-- Media notification channel -->
|
|
||||||
<string name="channel_playback">Playback</string>
|
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
package cc.tiredsysadmin.android.sizzle.audio
|
||||||
|
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Test
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.nio.ByteBuffer
|
||||||
|
import java.nio.ByteOrder
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [SoundFontLoader] parses files the user picked from anywhere on the device, so it
|
||||||
|
* is the app's largest untrusted-input surface. These tests feed it hostile headers
|
||||||
|
* and require it to fail fast rather than hang or crash.
|
||||||
|
*
|
||||||
|
* The timeouts matter as much as the assertions: a RIFF walker that trusts a chunk
|
||||||
|
* size will seek *backwards* on a negative one and re-read the same bytes forever.
|
||||||
|
* `runCatching` cannot save a caller from that — there is no exception, just a
|
||||||
|
* thread that never returns.
|
||||||
|
*/
|
||||||
|
class SoundFontLoaderTest {
|
||||||
|
|
||||||
|
private fun sf2(body: ByteArrayOutputStream.() -> Unit): ByteArray =
|
||||||
|
ByteArrayOutputStream().apply {
|
||||||
|
write("RIFF".toByteArray())
|
||||||
|
write(le32(0))
|
||||||
|
write("sfbk".toByteArray())
|
||||||
|
body()
|
||||||
|
}.toByteArray()
|
||||||
|
|
||||||
|
private fun le32(v: Int): ByteArray =
|
||||||
|
ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(v).array()
|
||||||
|
|
||||||
|
/** The hang: a chunk whose size walks the cursor back to where it started. */
|
||||||
|
@Test(timeout = 5_000) fun negativeChunkSizeDoesNotHang() {
|
||||||
|
val bytes = sf2 {
|
||||||
|
write("LIST".toByteArray())
|
||||||
|
write(le32(-8))
|
||||||
|
write(ByteArray(64))
|
||||||
|
}
|
||||||
|
assertNull(SoundFontLoader.load(bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The same trap one level down, in the walk over a LIST's sub-chunks. */
|
||||||
|
@Test(timeout = 5_000) fun negativeSubChunkSizeDoesNotHang() {
|
||||||
|
val bytes = sf2 {
|
||||||
|
write("LIST".toByteArray())
|
||||||
|
write(le32(256))
|
||||||
|
write("pdta".toByteArray())
|
||||||
|
write("shdr".toByteArray())
|
||||||
|
write(le32(-16))
|
||||||
|
write(ByteArray(240))
|
||||||
|
}
|
||||||
|
assertNull(SoundFontLoader.load(bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A zero-size chunk must still advance, or the walk stalls on it. */
|
||||||
|
@Test(timeout = 5_000) fun zeroSizeChunkDoesNotHang() {
|
||||||
|
val bytes = sf2 {
|
||||||
|
repeat(8) {
|
||||||
|
write("junk".toByteArray())
|
||||||
|
write(le32(0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertNull(SoundFontLoader.load(bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A header claiming a gigantic sample region must be capped, not allocated. */
|
||||||
|
@Test(timeout = 10_000) fun hugeSampleRegionIsCapped() {
|
||||||
|
val bytes = sf2 {
|
||||||
|
write("LIST".toByteArray())
|
||||||
|
write(le32(12))
|
||||||
|
write("sdta".toByteArray())
|
||||||
|
write("smpl".toByteArray())
|
||||||
|
write(le32(0))
|
||||||
|
write("LIST".toByteArray())
|
||||||
|
write(le32(4 + 8 + 46))
|
||||||
|
write("pdta".toByteArray())
|
||||||
|
write("shdr".toByteArray())
|
||||||
|
write(le32(46))
|
||||||
|
write(ByteArray(20)) // sample name
|
||||||
|
write(le32(0)) // start
|
||||||
|
write(le32(Int.MAX_VALUE)) // end — a 2-billion-frame claim
|
||||||
|
write(le32(0)); write(le32(0))
|
||||||
|
write(le32(44100))
|
||||||
|
write(ByteArray(46 - 40))
|
||||||
|
}
|
||||||
|
// Must return (capped or rejected) without trying to allocate 8 GB.
|
||||||
|
SoundFontLoader.load(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Truncated garbage of every length must be rejected, never crash. */
|
||||||
|
@Test(timeout = 10_000) fun truncatedInputIsRejected() {
|
||||||
|
val full = sf2 {
|
||||||
|
write("LIST".toByteArray())
|
||||||
|
write(le32(12))
|
||||||
|
write("sdta".toByteArray())
|
||||||
|
write("smpl".toByteArray())
|
||||||
|
write(le32(0))
|
||||||
|
}
|
||||||
|
for (n in 0..full.size) {
|
||||||
|
SoundFontLoader.load(full.copyOf(n)) // must not throw
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
package cc.tiredsysadmin.android.sizzle.io
|
||||||
|
|
||||||
|
import cc.tiredsysadmin.android.sizzle.model.Project
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import java.io.ByteArrayInputStream
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.File
|
||||||
|
import java.util.zip.ZipEntry
|
||||||
|
import java.util.zip.ZipOutputStream
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Both import paths take an archive the user picked from anywhere on the device. A
|
||||||
|
* ZIP states its own sizes and nothing makes them true: highly compressible filler
|
||||||
|
* expands by orders of magnitude, which the zip-slip path check cannot see because
|
||||||
|
* the entries are perfectly well-named. The budget must stop it, and — just as
|
||||||
|
* important — must leave the existing data alone when it does.
|
||||||
|
*/
|
||||||
|
class ZipBombTest {
|
||||||
|
|
||||||
|
private val tmp = File(System.getProperty("java.io.tmpdir"), "sizzle-zipbomb-${System.nanoTime()}")
|
||||||
|
|
||||||
|
@After fun cleanUp() { tmp.deleteRecursively() }
|
||||||
|
|
||||||
|
/** An archive whose entries expand far past the budget. Zeroes deflate ~1000:1,
|
||||||
|
* so this is a few hundred KB on the wire and 2 GB on the way out. */
|
||||||
|
private fun bomb(entryName: String): ByteArray {
|
||||||
|
val chunk = ByteArray(1024 * 1024) // 1 MB of zeroes
|
||||||
|
return ByteArrayOutputStream().also { bytes ->
|
||||||
|
ZipOutputStream(bytes).use { zip ->
|
||||||
|
repeat(4) { n ->
|
||||||
|
zip.putNextEntry(ZipEntry("$entryName$n"))
|
||||||
|
repeat(512) { zip.write(chunk) } // 512 MB per entry
|
||||||
|
zip.closeEntry()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An archive with an absurd number of tiny entries. */
|
||||||
|
private fun manyEntries(): ByteArray = ByteArrayOutputStream().also { bytes ->
|
||||||
|
ZipOutputStream(bytes).use { zip ->
|
||||||
|
repeat(ZipLimits.MAX_ENTRIES + 10) { n ->
|
||||||
|
zip.putNextEntry(ZipEntry("songs/$n.sng"))
|
||||||
|
zip.write(1)
|
||||||
|
zip.closeEntry()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.toByteArray()
|
||||||
|
|
||||||
|
@Test(timeout = 120_000) fun backupRestoreRejectsABomb() {
|
||||||
|
val filesDir = File(tmp, "files").apply { mkdirs() }
|
||||||
|
val keep = File(filesDir, "songs").apply { mkdirs() }.let { File(it, "mine.sng") }
|
||||||
|
keep.writeText("do not lose me")
|
||||||
|
|
||||||
|
val ok = BackupIo.read(filesDir, ByteArrayInputStream(bomb("songs/big")))
|
||||||
|
|
||||||
|
assertFalse("a bomb must be rejected", ok)
|
||||||
|
assertTrue("existing songs must survive a rejected restore", keep.isFile)
|
||||||
|
assertTrue("staging must be cleaned up", !File(filesDir, ".restore_tmp").exists())
|
||||||
|
// Nothing may be left behind on disk beyond what was already there.
|
||||||
|
val leftover = filesDir.walkTopDown().filter { it.isFile }.sumOf { it.length() }
|
||||||
|
assertTrue("a rejected restore must not fill the disk (left $leftover bytes)",
|
||||||
|
leftover < 10L * 1024 * 1024)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(timeout = 120_000) fun backupRestoreRejectsTooManyEntries() {
|
||||||
|
val filesDir = File(tmp, "files2").apply { mkdirs() }
|
||||||
|
assertFalse(BackupIo.read(filesDir, ByteArrayInputStream(manyEntries())))
|
||||||
|
assertTrue(!File(filesDir, ".restore_tmp").exists())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(timeout = 120_000) fun bundleImportRejectsABomb() {
|
||||||
|
val project = Project()
|
||||||
|
val before = project.name
|
||||||
|
val samples = File(tmp, "samples").apply { mkdirs() }
|
||||||
|
|
||||||
|
val ok = ProjectBundleIo.read(project, ByteArrayInputStream(bomb("samples/")), samples)
|
||||||
|
|
||||||
|
assertFalse("a bomb must be rejected", ok)
|
||||||
|
assertTrue("the open project must be untouched", project.name == before)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The budget must not reject an ordinary archive. */
|
||||||
|
@Test fun anOrdinaryBackupStillRestores() {
|
||||||
|
val src = File(tmp, "src").apply { mkdirs() }
|
||||||
|
File(src, "songs").mkdirs()
|
||||||
|
File(src, "songs/a.sng").writeText("hello")
|
||||||
|
val zipped = ByteArrayOutputStream().also { BackupIo.write(src, it) }.toByteArray()
|
||||||
|
|
||||||
|
val dst = File(tmp, "dst").apply { mkdirs() }
|
||||||
|
assertTrue(BackupIo.read(dst, ByteArrayInputStream(zipped)))
|
||||||
|
assertTrue(File(dst, "songs/a.sng").readText() == "hello")
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -8,8 +8,8 @@
|
|||||||
# or polish. android.versionCode is monotonic and bumps by 1 on every release,
|
# or polish. android.versionCode is monotonic and bumps by 1 on every release,
|
||||||
# because F-Droid and the Android package manager order installs by it alone.
|
# because F-Droid and the Android package manager order installs by it alone.
|
||||||
|
|
||||||
android.versionName = 0.23.1
|
android.versionName = 0.24.0
|
||||||
android.versionCode = 52
|
android.versionCode = 53
|
||||||
|
|
||||||
# No desktop builds exist yet. These lines are the agreed slots so a port starts
|
# No desktop builds exist yet. These lines are the agreed slots so a port starts
|
||||||
# with a version instead of inventing one; `-` means "not built on this
|
# with a version instead of inventing one; `-` means "not built on this
|
||||||
|
|||||||
Reference in New Issue
Block a user