Basic path pathRegistry matching!

* We can now register paths with handler functions and it works!
This commit is contained in:
MatthiasSaihttam 2021-08-28 18:32:24 -04:00
parent af9ce9f61f
commit aa0d8ddefe
3 changed files with 43 additions and 7 deletions

View File

@ -1,9 +1,12 @@
import * as path from "path";
import tls from "tls";
import fs from "fs";
import geminiText from "./handlers/gemini.js";
export default class GeminiServer {
constructor(options) {
this.defaultHandler = options.defaultHandler || geminiText;
this.certificates = {};
if (options.hasOwnProperty("host")) {
this.usingSNI = true;
@ -61,12 +64,34 @@ export default class GeminiServer {
throw new Error(`Path ${p} passed to registerPath not normalized. (Remove trailing /'s and ..'s)`);
}
if (typeof handler !== "function") {
handler = this.defaultHandler(handler);
}
this.pathRegistry.push({
hostname: hostname,
path: p
path: p,
handler: handler
});
}
handleRequestLine(url, socket) {
for (const p of this.pathRegistry) {
//TODO: Wildcard hostnames
if (p.hostname === socket.servername) {
//If the requested path is a sub path (e.g. equal to or more specific than the path in the current registry entry)
const isSubPath = !path.posix.relative(p.path, url.pathname).startsWith("..");
if (path.posix.resolve(url.pathname) === p.path) {
const res = p.handler({ path: url })
socket.write(res);
socket.end();
return;
}
}
}
}
/**
* Start running the server
*/
@ -109,11 +134,17 @@ export default class GeminiServer {
socket.write("40 Heck you\r\n");
socket.end();
}else {
console.log("Responding");
socket.write("20 text/gemini\r\n");
socket.write("Hello, world!\r\n");
socket.write(`You're connecting from ${socket.servername}`)
socket.end();
//TODO: What if the URL doesn't have a protocol or a domain at all?
//Make sure that the SNI negotiated name matches the hostname in the request
const url = new URL(requestLine.slice(0, -2))
if (url.host !== socket.servername) {
//TODO: make this line not a joke
socket.write("40 Heck you\r\n");
socket.end();
}else {
//Responding
this.handleRequestLine(url, socket);
}
}
}
});

View File

@ -32,7 +32,7 @@ server.registerPath("MacBookGamma.local/", "### Hello from my Mac!");
//Otherwise, you have a function, a handler
//request has everything you would expect, .servername, .path,
//You have to provide the entire responce inc. content type
server.registerPath("localhost/allFiles", request => "text/txt\r\nHello, World\r\n");
server.registerPath("localhost/allFiles", request => "20 text/txt\r\nHello, World\r\n");
// We provide some convenient handlers for static, CGI, and reverse proxy

5
handlers/gemini.js Normal file
View File

@ -0,0 +1,5 @@
export default function geminiText (text) {
return function (request) {
return "20 text/gemini\r\n" + text;
}
}