You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

65 lines
2.0 KiB

import kotlin.js.Date
external fun require(module:String):dynamic
val tls = require("tls")
val fs = require("fs")
val path = require("path")
var adminFingerprints = mutableListOf<String>()
fun main() {
Config(fs).run{
val config = this
load()
val tlsOptions: dynamic = object{}
tlsOptions["key"] = key
tlsOptions["cert"] = cert
tlsOptions["host"] = host
tlsOptions["requestCert"] = true
tlsOptions["rejectUnauthorized"] = false
adminFingerprints.addAll(adminCert256s)
tls.createServer(
tlsOptions
) { tlsSocket ->
tlsSocket.on("data") { data: dynamic ->
val isAdmin = Auth.isAdmin(tlsSocket)
println("Received request: $data isAdmin: $isAdmin")
Request(isAdmin, fs, "$data").run {
process(
host = host,
root = root) { result ->
when(result){
is Request.Result.GeminiError -> errorResponse(tlsSocket, result.code, result.reason)
is Request.Result.GemiinServeFile -> streamFile(config, tlsSocket, result.path, result.mime)
is Request.Result.TitanRequest -> {
//todo - send all Titan related logic to Titan
}
}
}
}
}
}.listen(port)
}
}
private fun streamFile(config: Config, client: dynamic, requestPath: String, mimeType: String?){
mimeType?.let{
client.write("20 $mimeType\r\n")
val fileStream = fs.createReadStream("${path.join(config.root, requestPath)}")
fileStream.on("open") { fileStream.pipe(client) }
fileStream.on("end") { client.end() }
} ?: run{
errorResponse(client, 40, "Unrecognised filetype: $requestPath")
}
}
private fun errorResponse(client: dynamic, code: Int, error: String){
client.write("$code $error\r\n")
client.end()
}