Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -232,4 +232,55 @@ class GuardBoundaryTest {
val names = ZipFile(zip).use { z -> z.entries().toList().map { it.name } }
assertEquals(names, GuardZipFile("a.zip").use { z -> z.entries().toList().map { it.name } })
}

@Test
fun formatterWritesThroughTheHost() {
GuardFormatter("f.txt").use { it.format("%s=%d", "a", 1) }
assertEquals("a=1", File(project, "f.txt").readText())
GuardFormatter(GuardFile("g.txt"), "UTF-8").use { it.format("%s", "가") }
assertEquals("가", File(project, "g.txt").readText())
assertFailsWith<java.io.UnsupportedEncodingException> { GuardFormatter("h.txt", "no-such-charset") }
assertFalse(File(project, "h.txt").exists())
assertFailsWith<FileNotFoundException> { GuardFormatter(outside.path) }
assertEquals("x", GuardFormatter().format("%s", "x").toString())
}

@Test
fun bitmapsDecodeFromTheProjectFolder() {
val bitmap = android.graphics.Bitmap.createBitmap(3, 2, android.graphics.Bitmap.Config.ARGB_8888)
File(project, "a.png").outputStream().use { bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) }
val decoded = GuardBitmapFactory.decodeFile("a.png")!!
assertEquals(3, decoded.width)
assertEquals(2, decoded.height)
val bounds = android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds = true }
assertNull(GuardBitmapFactory.decodeFile(File(project, "a.png").path, bounds))
assertEquals(3, bounds.outWidth)
assertNull(GuardBitmapFactory.decodeFile(outside.path))
assertNull(GuardBitmapFactory.decodeFile("missing.png"))
assertEquals(1, host.logs.count { it.contains(outside.path) }, host.logs.toString())
}

@Test
fun mediaMetadataReadsFromTheProjectFolder() {
File(project, "a.wav").writeBytes(wav(8000, 8000))
GuardMediaMetadataRetriever().use { retriever ->
retriever.setDataSource("a.wav")
assertEquals("1000", retriever.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION))
}
GuardMediaMetadataRetriever().use { it.setDataSource("file://" + File(project, "a.wav").path) }
val error = assertFailsWith<IllegalArgumentException> { GuardMediaMetadataRetriever().use { it.setDataSource(outside.path) } }
assertEquals("${outside.path} does not exist", error.message)
}

private fun wav(
rate: Int,
samples: Int,
): ByteArray {
val data = samples * 2
val buffer = java.nio.ByteBuffer.allocate(44 + data).order(java.nio.ByteOrder.LITTLE_ENDIAN)
buffer.put("RIFF".toByteArray()).putInt(36 + data).put("WAVE".toByteArray())
buffer.put("fmt ".toByteArray()).putInt(16).putShort(1).putShort(1).putInt(rate).putInt(rate * 2).putShort(2).putShort(16)
buffer.put("data".toByteArray()).putInt(data)
return buffer.array()
}
}
111 changes: 111 additions & 0 deletions guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFormatter.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
* Copyright (C) 2026 MessengerBotTeam
*/

package com.xfl.msgbot.plugin.guard

import java.io.Closeable
import java.io.File
import java.io.FileNotFoundException
import java.io.Flushable
import java.io.IOException
import java.io.OutputStream
import java.io.PrintStream
import java.io.UnsupportedEncodingException
import java.nio.charset.Charset
import java.util.Formatter
import java.util.Locale

/**
* `java.util.Formatter`, which is final: the constructors that take a file name or a `File` write through the host,
* and everything else is the real formatter underneath.
*/
class GuardFormatter private constructor(
private val real: Formatter,
) : Closeable,
Flushable {
constructor() : this(Formatter())

constructor(a: Appendable?) : this(Formatter(a))

constructor(l: Locale?) : this(Formatter(l))

constructor(a: Appendable?, l: Locale?) : this(Formatter(a, l))

@Throws(FileNotFoundException::class)
constructor(fileName: String) : this(toFile(fileName, Charset.defaultCharset(), formatLocale()))

@Throws(FileNotFoundException::class, UnsupportedEncodingException::class)
constructor(fileName: String, csn: String) : this(toFile(fileName, charsetNamed(csn), formatLocale()))

@Throws(FileNotFoundException::class, UnsupportedEncodingException::class)
constructor(fileName: String, csn: String, l: Locale?) : this(toFile(fileName, charsetNamed(csn), l))

@Throws(IOException::class)
constructor(fileName: String, charset: Charset, l: Locale?) : this(toFile(fileName, charset, l))

@Throws(FileNotFoundException::class)
constructor(file: File) : this(file.path)

@Throws(FileNotFoundException::class, UnsupportedEncodingException::class)
constructor(file: File, csn: String) : this(file.path, csn)

@Throws(FileNotFoundException::class, UnsupportedEncodingException::class)
constructor(file: File, csn: String, l: Locale?) : this(file.path, csn, l)

@Throws(IOException::class)
constructor(file: File, charset: Charset, l: Locale?) : this(file.path, charset, l)

constructor(ps: PrintStream) : this(Formatter(ps))

constructor(os: OutputStream) : this(Formatter(os))

@Throws(UnsupportedEncodingException::class)
constructor(os: OutputStream, csn: String) : this(Formatter(os, csn))

@Throws(UnsupportedEncodingException::class)
constructor(os: OutputStream, csn: String, l: Locale?) : this(Formatter(os, csn, l))

constructor(os: OutputStream, charset: Charset, l: Locale?) : this(Formatter(os, charset.name(), l))

fun locale(): Locale? = real.locale()

fun out(): Appendable = real.out()

override fun toString(): String = real.toString()

override fun flush() = real.flush()

override fun close() = real.close()

fun ioException(): IOException? = real.ioException()

fun format(
format: String?,
vararg args: Any?,
): GuardFormatter {
real.format(format, *args)
return this
}

fun format(
l: Locale?,
format: String?,
vararg args: Any?,
): GuardFormatter {
real.format(l, format, *args)
return this
}

private companion object {
fun formatLocale(): Locale = Locale.getDefault(Locale.Category.FORMAT)

// The real class checks the charset before it opens the file.
fun toFile(
fileName: String,
charset: Charset,
l: Locale?,
): Formatter = Formatter(GuardFileOutputStream(fileName), charset.name(), l)
}
}
126 changes: 126 additions & 0 deletions guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardMedia.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
* Copyright (C) 2026 MessengerBotTeam
*/

package com.xfl.msgbot.plugin.guard

import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Rect
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.util.Log
import android.util.TypedValue
import java.io.FileDescriptor
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream

/** `android.graphics.BitmapFactory`; [decodeFile] reads through the host and the rest is the real class. */
class GuardBitmapFactory {
companion object {
@JvmStatic
fun decodeFile(
pathName: String?,
opts: BitmapFactory.Options?,
): Bitmap? {
validate(opts)
// Like the real class: any failure to open or decode is logged and gives null.
return try {
GuardFileInputStream(pathName ?: throw NullPointerException()).use { BitmapFactory.decodeStream(it, null, opts) }
} catch (e: Exception) {
Log.e("BitmapFactory", "Unable to decode stream: $e")
null
}
}

@JvmStatic
fun decodeFile(pathName: String?): Bitmap? = decodeFile(pathName, null)

@JvmStatic
fun decodeResourceStream(
res: Resources?,
value: TypedValue?,
`is`: InputStream?,
pad: Rect?,
opts: BitmapFactory.Options?,
): Bitmap? = BitmapFactory.decodeResourceStream(res, value, `is`, pad, opts)

@JvmStatic
fun decodeResource(
res: Resources?,
id: Int,
opts: BitmapFactory.Options?,
): Bitmap? = BitmapFactory.decodeResource(res, id, opts)

@JvmStatic
fun decodeResource(
res: Resources?,
id: Int,
): Bitmap? = BitmapFactory.decodeResource(res, id)

@JvmStatic
fun decodeByteArray(
data: ByteArray?,
offset: Int,
length: Int,
opts: BitmapFactory.Options?,
): Bitmap? = BitmapFactory.decodeByteArray(data, offset, length, opts)

@JvmStatic
fun decodeByteArray(
data: ByteArray?,
offset: Int,
length: Int,
): Bitmap? = BitmapFactory.decodeByteArray(data, offset, length)

@JvmStatic
fun decodeStream(
`is`: InputStream?,
outPadding: Rect?,
opts: BitmapFactory.Options?,
): Bitmap? = BitmapFactory.decodeStream(`is`, outPadding, opts)

@JvmStatic
fun decodeStream(`is`: InputStream?): Bitmap? = BitmapFactory.decodeStream(`is`)

@JvmStatic
fun decodeFileDescriptor(
fd: FileDescriptor?,
outPadding: Rect?,
opts: BitmapFactory.Options?,
): Bitmap? = BitmapFactory.decodeFileDescriptor(fd, outPadding, opts)

@JvmStatic
fun decodeFileDescriptor(fd: FileDescriptor?): Bitmap? = BitmapFactory.decodeFileDescriptor(fd)

private fun validate(opts: BitmapFactory.Options?) {
if (opts != null && opts.inMutable && opts.inPreferredConfig == Bitmap.Config.HARDWARE) {
throw IllegalArgumentException("Bitmaps with Config.HARDWARE are always immutable")
}
}
}
}

/** `android.media.MediaMetadataRetriever`; a file path or `file:` address is opened through the host. */
class GuardMediaMetadataRetriever : MediaMetadataRetriever() {
override fun setDataSource(path: String?) {
if (path == null) throw IllegalArgumentException("null path")
val uri = Uri.parse(path)
var file = path
when (uri.scheme) {
null -> Unit
"file" -> file = uri.path ?: path
else -> return setDataSource(path, HashMap<String, String>())
}
try {
GuardFileInputStream(file).use { setDataSource(it.fd, 0, 0x7ffffffffffffffL) }
} catch (e: FileNotFoundException) {
throw IllegalArgumentException("$file does not exist")
} catch (e: IOException) {
throw IllegalArgumentException("couldn't open $file")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ object GuardPolicy {
"java.io.PrintStream" to GuardPrintStream::class.java,
"java.io.RandomAccessFile" to GuardRandomAccessFile::class.java,
"java.util.Scanner" to GuardScanner::class.java,
"java.util.Formatter" to GuardFormatter::class.java,
"android.graphics.BitmapFactory" to GuardBitmapFactory::class.java,
"android.media.MediaMetadataRetriever" to GuardMediaMetadataRetriever::class.java,
"java.util.zip.ZipFile" to GuardZipFile::class.java,
"java.util.jar.JarFile" to GuardJarFile::class.java,
"java.nio.file.Path" to GuardPath::class.java,
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ MessengerBotR의 플러그인 계약이다. 현재 개발 버전은 `0.1.0-SNAPS
|---|---|
| `contract` | 값, API 스키마, 표준 모듈, 엔진·제공자·도구 SPI, 대칭 RPC. Android에 의존하지 않는다. |
| `android` | `PluginService`, Binder 세션, 공유 메모리 전송 |
| `guard` | Java를 쓰는 엔진의 파일·클래스 가드. `File`, 스트림, `RandomAccessFile`, nio, `ZipFile` 등을 호스트 디스크립터 위의 같은 모양 클래스로 바꾸고, `ClassAccess`로 클래스 접근을 정한다. 엔진에는 이름 조회(`GuardPolicy.lookup`)와 값 변환(`GuardPolicy.replace`)만 연결하면 된다 |
| `guard` | Java를 쓰는 엔진의 파일·클래스 가드. `File`, 스트림, `RandomAccessFile`, nio, `ZipFile`, `Formatter`, `BitmapFactory`, `MediaMetadataRetriever` 등을 호스트 디스크립터 위의 같은 모양 클래스로 바꾸고, `ClassAccess`로 클래스 접근을 정한다. 엔진에는 이름 조회(`GuardPolicy.lookup`)와 값 변환(`GuardPolicy.replace`)만 연결하면 된다 |
| `tck` | 엔진과 제공자를 호스트 없이 돌려 보는 `EngineHarness`, `ProviderHarness`. JavaScript 엔진의 적합성 테스트(`JavaScriptEngineConformance`), Java 가드의 적합성 테스트(`JavaGuardConformance`, 기기에서 실행), 제공자의 적합성 테스트(`ProviderConformance`) |

## 구조
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,15 @@ abstract class JavaGuardConformance {
assertEquals("a\nb", File(files.root, "n/lines.txt").readText())
}

@Test
fun classesThatOpenAPathGoThroughTheHost() {
load()
text("t(function () { var f = new (${j("java.util.Formatter")})('fmt.txt'); f.out().append('hi'); f.close(); return 1; })")
assertEquals("hi", File(files.root, "fmt.txt").readText())
assertEquals("ok:true", text("t(function () { return ${j("android.graphics.BitmapFactory")}.decodeFile('${outside.path}') === null; })"))
assertEquals(1, warnings().count { it.contains(outside.path) }, warnings().toString())
}

@Test
fun placesOutsideTheRulesAreRefused() {
load()
Expand Down
Loading