From e7dd3fa0739b5c3a4b7a0307f2593b17c3b107b3 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Fri, 5 Jan 2024 17:45:35 +0000 Subject: [PATCH] Verify FSEntry name --- src/main/kotlin/filesystem/FSCreator.kt | 10 ++++++---- src/main/kotlin/filesystem/FSEntry.kt | 16 ++++++++++++++-- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/main/kotlin/filesystem/FSCreator.kt b/src/main/kotlin/filesystem/FSCreator.kt index 4b8d4ca..7a9f4a6 100644 --- a/src/main/kotlin/filesystem/FSCreator.kt +++ b/src/main/kotlin/filesystem/FSCreator.kt @@ -1,8 +1,10 @@ package filesystem import java.nio.file.FileAlreadyExistsException -import java.nio.file.Files import java.nio.file.Path +import kotlin.io.path.createDirectory +import kotlin.io.path.createFile +import kotlin.io.path.writeText class FSCreator { /** @@ -31,13 +33,13 @@ class FSCreator { val path = dest.resolve(entry.name) try { when (entry) { - is FSFile -> Files.createFile(path) - is FSFolder -> Files.createDirectory(path) + is FSFile -> path.createFile() + is FSFolder -> path.createDirectory() } } catch (_: FileAlreadyExistsException) { } // Allow files/folders to already exist. when (entry) { - is FSFile -> Files.write(path, entry.content.toByteArray()) + is FSFile -> path.writeText(entry.content) is FSFolder -> queue.addAll(entry.entries.map { it to path }) } } diff --git a/src/main/kotlin/filesystem/FSEntry.kt b/src/main/kotlin/filesystem/FSEntry.kt index 6cad9ad..214b3a2 100644 --- a/src/main/kotlin/filesystem/FSEntry.kt +++ b/src/main/kotlin/filesystem/FSEntry.kt @@ -1,8 +1,18 @@ package filesystem +import kotlin.io.path.Path + // Note sealed allows for simpler logic in FSCreator by guaranteeing FSFile and FSFolder are the only possible FSEntries // (as we expect), and it also implicitly makes the class abstract as required. -sealed class FSEntry(val name: String) +sealed class FSEntry(val name: String) { + init { + val p = Path(name) + // Only allow single filenames (no paths or relative references (e.g. "..")) + if (p.toList().size != 1 || p.fileName != p.toFile().canonicalFile.toPath().fileName) { + throw InvalidEntryNameException(name) + } + } +} class FSFile(name: String, val content: String) : FSEntry(name) @@ -24,4 +34,6 @@ class FSFolder(name: String, val entries: List) : FSEntry(name) { } return false } -} \ No newline at end of file +} + +class InvalidEntryNameException(name: String) : Exception("Invalid FSEntry name: '$name'") \ No newline at end of file