1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-31 13:18:13 +00:00

WebServer: Allow the user to specify the base directory

This commit makes the WebServer accept a base path to serve.
This makes taking files out of the system significantly more simple
(depending on whom you ask).
This commit is contained in:
AnotherTest 2020-07-11 11:33:22 +04:30 committed by Andreas Kling
parent 7b5ffe67cf
commit 684b04e02a
3 changed files with 20 additions and 6 deletions

View file

@ -27,6 +27,7 @@
#include "Client.h"
#include <LibCore/ArgsParser.h>
#include <LibCore/EventLoop.h>
#include <LibCore/File.h>
#include <LibCore/TCPServer.h>
#include <stdio.h>
#include <unistd.h>
@ -34,11 +35,13 @@
int main(int argc, char** argv)
{
u16 default_port = 8000;
const char* root_path = "/www";
int port = default_port;
Core::ArgsParser args_parser;
args_parser.add_positional_argument(port, "Port to listen on", "port", Core::ArgsParser::Required::No);
args_parser.add_option(port, "Port to listen on", "port", 'p', "port");
args_parser.add_positional_argument(root_path, "Path to serve the contents of", "path", Core::ArgsParser::Required::No);
args_parser.parse(argc, argv);
if ((u16)port != port) {
@ -46,6 +49,13 @@ int main(int argc, char** argv)
port = default_port;
}
auto real_root_path = Core::File::real_path_for(root_path);
if (!Core::File::exists(real_root_path)) {
fprintf(stderr, "Root path does not exist: '%s'\n", root_path);
return 1;
}
if (pledge("stdio accept rpath inet unix cpath fattr", nullptr) < 0) {
perror("pledge");
return 1;
@ -58,14 +68,14 @@ int main(int argc, char** argv)
server->on_ready_to_accept = [&] {
auto client_socket = server->accept();
ASSERT(client_socket);
auto client = WebServer::Client::construct(client_socket.release_nonnull(), server);
auto client = WebServer::Client::construct(client_socket.release_nonnull(), real_root_path, server);
client->start();
};
server->listen({}, port);
printf("Listening on 0.0.0.0:%d\n", port);
if (unveil("/www", "r") < 0) {
if (unveil(real_root_path.characters(), "r") < 0) {
perror("unveil");
return 1;
}