Skip to content

Commit

Permalink
Fix Path.combineSafe on JVM 8
Browse files Browse the repository at this point in the history
  • Loading branch information
osipxd committed Nov 26, 2024
1 parent 617cde6 commit 7a6ef09
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

package io.ktor.server.http.content

import com.sun.nio.file.*
import com.sun.nio.file.SensitivityWatchEventModifier
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
Expand All @@ -13,10 +13,14 @@ import io.ktor.server.http.content.FileSystemPaths.Companion.paths
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.util.*
import java.io.*
import java.net.*
import java.nio.file.*
import kotlin.io.path.*
import java.io.File
import java.net.URL
import java.nio.file.FileSystem
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.StandardWatchEventKinds
import kotlin.io.path.isDirectory
import kotlin.io.path.pathString

/**
* Attribute to assign the path of a static file served in the response. The main use of this attribute is to indicate
Expand Down Expand Up @@ -616,7 +620,7 @@ private suspend fun ApplicationCall.respondStaticPath(
defaultPath: String?
) {
val relativePath = parameters.getAll(pathParameterName)?.joinToString(File.separator) ?: return
val requestedPath = fileSystem.getPath(basePath ?: "").combineSafe(fileSystem.getPath(relativePath))
val requestedPath = fileSystem.getPath(basePath.orEmpty()).combineSafe(fileSystem.getPath(relativePath))

suspend fun checkExclude(path: Path): Boolean {
if (!exclude(path)) return false
Expand Down
11 changes: 8 additions & 3 deletions ktor-utils/jvm/src/io/ktor/util/NioPath.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@

package io.ktor.util

import java.io.*
import java.nio.file.*
import java.io.File
import java.nio.file.InvalidPathException
import java.nio.file.Path

/**
* Append a [relativePath] safely that means that adding any extra `..` path elements will not let
Expand All @@ -18,7 +19,11 @@ public fun Path.combineSafe(relativePath: Path): Path {
}
check(!normalized.isAbsolute) { "Bad relative path $relativePath" }

return resolve(normalized)
// On JVM 8 ZipPath implementation misses this check,
// so we have to check the path is not empty to not get an `ArrayIndexOutOfBoundsException`
if (this.nameCount == 0) return normalized

return this.resolve(normalized)
}

/**
Expand Down

0 comments on commit 7a6ef09

Please sign in to comment.