scoop:scoop.http.server:0.1.0
src/files/static.scoop
Selected production source · src/files/static.scoop
1
package scoop.http.server3
import scoop.platform.fs.Path4
import scoop.platform.system.OsString6
/** Maps a terminal wildcard's once-decoded segments onto an application-selected root. */7
public fun staticFiles(root: Path, options: StaticFileOptions = staticFileOptions()): HttpHandler =8
suspend {9
ctx ->10
val parts = ctx.pathParams.tailSegments(options.pathParameter)11
var path = root12
var directory = false13
var index = 0L14
for (part in parts) {15
index += 1L16
if (part.decoded.size == 0L && index == parts.size)17
directory = true18
else {19
if (!validStaticFileName(part.decoded))20
reject(400U, "invalid static file path segment")21
path = path.resolve(Path.fromOsString(OsString.fromByteArray(part.decoded)))22
}23
}24
val fallback =25
if (ctx.request.method == "GET" || ctx.request.method == "HEAD")26
options.fallbackFile27
else28
None29
val body =30
HttpBody.File(31
HttpFileBody(path, options.fileOptions, options.indexDocument, directory, fallback)32
)33
httpResult {34
this.body = body35
this.allowCompression = false36
}37
}39
internal fun validStaticFileName(bytes: Array<Byte>): Boolean {40
if (bytes.size == 0L)41
return false42
if (bytes[0L] == 46 && (bytes.size == 1L || (bytes.size == 2L && bytes[1L] == 46)))43
return false44
if (45
bytes.size >=46
2L &&47
bytes[1L] ==48
58 &&49
((bytes[0L] >= 65 && bytes[0L] <= 90) || (bytes[0L] >= 97 && bytes[0L] <= 122))50
)51
return false52
for (value in bytes)53
if (value == 0 || value == 47 || value == 92)54
return false55
return true56
}