Compare commits

...
16 Commits
32 changed files with 4858 additions and 43 deletions
+1 -5
View File
@@ -6,16 +6,12 @@ RUN apk add --no-cache \
curl-dev \ curl-dev \
libxml2-dev \ libxml2-dev \
openssl-dev \ openssl-dev \
git \
pkgconf pkgconf
WORKDIR /app WORKDIR /app
COPY . /app COPY . /app
RUN git clone https://git.bwaaa.monster/beaker /tmp/beaker && \ RUN make -C vendor/beaker && make -C vendor/beaker install
cd /tmp/beaker && \
make && make install && \
rm -rf /tmp/beaker
RUN make clean && make && strip bin/omnisearch RUN make clean && make && strip bin/omnisearch
+2 -1
View File
@@ -7,8 +7,9 @@ GIT_HASH := $(shell git rev-parse --short HEAD)
GIT_DATE := $(shell git log -1 --format='%ad' --date='format:%y.%m.%d') GIT_DATE := $(shell git log -1 --format='%ad' --date='format:%y.%m.%d')
GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD) GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
GIT_REMOTE := $(shell git remote get-url origin) GIT_REMOTE := $(shell git remote get-url origin)
GIT_TAG := $(shell git describe --tags --exact-match HEAD 2>/dev/null)
VERSION := $(GIT_DATE)+$(GIT_HASH)_$(GIT_BRANCH) VERSION := $(if $(GIT_TAG),$(GIT_TAG),$(GIT_DATE)+$(GIT_HASH)_$(GIT_BRANCH))
CFLAGS := -Wall -Wextra -O2 -Isrc -DVERSION='"$(VERSION)"' -DGIT_REMOTE='"$(GIT_REMOTE)"' CFLAGS := -Wall -Wextra -O2 -Isrc -DVERSION='"$(VERSION)"' -DGIT_REMOTE='"$(GIT_REMOTE)"'
+39
View File
@@ -82,6 +82,45 @@ On macOS, use `install-launchd`.
## Hosting ## Hosting
Run it normally behind a reverse proxy (like nginx) Run it normally behind a reverse proxy (like nginx)
## Nix
The flake builds the vendored Beaker source in `vendor/beaker` and provides the
other build dependencies. Run `nix develop`
then `make` to build locally, or use `nix build` and `nix run` for a packaged
build. The packaged launcher runs with its bundled templates, static files and
locales, using the application's default settings. For a custom `config.ini`,
run the built binary (`result/libexec/omnisearch`) from a directory containing
`config.ini`, `templates/`, `static/` and `locales/` (for example, this checkout).
Docker also builds from `vendor/beaker`; non-Nix local builds still require
Beaker to be installed separately.
### NixOS service
Import the module from this flake and enable the service:
```nix
{
imports = [ omnisearch.nixosModules.default ];
services.omnisearch = {
enable = true;
openFirewall = true;
settings = {
server = { host = "127.0.0.1"; port = 8087; };
engines.engines = "*";
rate_limit = { search_requests = 10; search_interval = 60; };
};
};
}
```
The module manages a system user, systemd service, persistent cache/state
directories and the asset links needed by OmniSearch. `settings` uses INI
sections and keys matching `example-config.ini`; `extraConfig` appends raw INI
text after those generated settings. Both are embedded in the world-readable
Nix store, so do not put credentials or other secrets in them. The firewall
remains closed unless `openFirewall` is enabled.
## Deploy with Docker Compose ## Deploy with Docker Compose
You need Docker or Podman and Docker Compose installed on your system. You need Docker or Podman and Docker Compose installed on your system.
Generated
+27
View File
@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1791734076,
"narHash": "sha256-i5qk1kLiit98rRbh1AXmWBNT9QXC/y4l5Wk/u5EdpDQ=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "7fd4004d0511991fff3a0524856a9be09e28c5f0",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
+87
View File
@@ -0,0 +1,87 @@
{
description = "OmniSearch metasearch engine";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
};
outputs = { self, nixpkgs }:
let
systems = [ "x86_64-linux" "aarch64-linux" "aarch64-darwin" ];
forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system});
in
{
packages = forAllSystems (pkgs:
let
libbeaker = pkgs.stdenv.mkDerivation {
pname = "libbeaker";
version = "unstable-2026-08-16";
src = ./vendor/beaker;
nativeBuildInputs = [ pkgs.gnumake ];
installPhase = ''
runHook preInstall
make install INSTALL_PREFIX="$out/" LDCONFIG=true
runHook postInstall
'';
};
in
rec {
default = omnisearch;
omnisearch = pkgs.stdenv.mkDerivation {
pname = "omnisearch";
version = "unstable";
src = pkgs.lib.cleanSourceWith {
src = self;
filter = path: type: !(builtins.elem (baseNameOf path) [ "bin" "obj" ]);
};
nativeBuildInputs = [ pkgs.gnumake pkgs.pkg-config pkgs.makeWrapper ];
buildInputs = [ libbeaker pkgs.curl pkgs.libxml2 pkgs.openssl ];
env.NIX_CFLAGS_COMPILE = "-I${pkgs.libxml2.dev}/include/libxml2";
# The upstream Makefile normally obtains these from Git, which is
# unavailable in a Nix source snapshot.
makeFlags = [
"VERSION=unstable"
"GIT_REMOTE=https://codeberg.org/gabrielf/omnisearch"
];
preBuild = ''
makeFlagsArray+=(
"LDFLAGS=-L${libbeaker}/lib -L${pkgs.lib.getLib pkgs.curl}/lib -L${pkgs.lib.getLib pkgs.libxml2}/lib -L${pkgs.openssl.out}/lib"
)
'';
installPhase = ''
runHook preInstall
install -Dm755 bin/omnisearch "$out/libexec/omnisearch"
mkdir -p "$out/share/omnisearch"
cp -r templates static locales "$out/share/omnisearch/"
makeWrapper "$out/libexec/omnisearch" "$out/bin/omnisearch" \
--chdir "$out/share/omnisearch"
runHook postInstall
'';
meta = {
description = "Lightweight metasearch engine written in C";
homepage = "https://codeberg.org/gabrielf/omnisearch";
license = pkgs.lib.licenses.gpl2Only;
mainProgram = "omnisearch";
platforms = pkgs.lib.platforms.unix;
};
};
});
devShells = forAllSystems (pkgs: {
default = pkgs.mkShell {
inputsFrom = [ self.packages.${pkgs.stdenv.hostPlatform.system}.omnisearch ];
shellHook = ''
export NIX_CFLAGS_COMPILE="''${NIX_CFLAGS_COMPILE:-} -I${pkgs.libxml2.dev}/include/libxml2"
${pkgs.lib.optionalString pkgs.stdenv.hostPlatform.isLinux ''
export MAKEFLAGS="LDFLAGS=-L${pkgs.lib.getLib pkgs.curl}/lib\\ -L${pkgs.stdenv.cc.libc}/lib ''${MAKEFLAGS:-}"
''}
'';
};
});
nixosModules.default = import ./nixos-module.nix { inherit self; };
};
}
+2
View File
@@ -21,6 +21,8 @@ display_language_label = "Display Language"
language_desc = "Choose your preferred language." language_desc = "Choose your preferred language."
engines_label = "Search Engines" engines_label = "Search Engines"
engines_desc = "Choose which search engines to use. Only engines enabled on the server are shown." engines_desc = "Choose which search engines to use. Only engines enabled on the server are shown."
default_engine_label = "Default Search Engine"
all_engines_option = "All enabled engines"
save_settings_button = "Save Settings" save_settings_button = "Save Settings"
no_results = "No results found" no_results = "No results found"
error_images = "Error fetching images" error_images = "Error fetching images"
+2
View File
@@ -21,6 +21,8 @@ display_language_label = "Display Language"
language_desc = "Choose your preferred language." language_desc = "Choose your preferred language."
engines_label = "Search Engines" engines_label = "Search Engines"
engines_desc = "Choose which search engines to use. Only engines enabled on the server are shown." engines_desc = "Choose which search engines to use. Only engines enabled on the server are shown."
default_engine_label = "Default Search Engine"
all_engines_option = "All enabled engines"
save_settings_button = "Save Settings" save_settings_button = "Save Settings"
no_results = "No results found" no_results = "No results found"
error_images = "Error fetching images" error_images = "Error fetching images"
+36
View File
@@ -0,0 +1,36 @@
[Meta]
Id = "fi_fi"
Name = "Suomi"
Direction = "ltr"
[Keys]
search_placeholder = "Hae netistä..."
search_button = "Hae"
surprise_me_button = "Kokeilen onneani"
all_tab = "Kaikki"
images_tab = "Kuvat"
settings_tab = "Asetukset"
settings_title = "Asetukset"
theme_label = "Ulkonäkö"
theme_desc = "Valitse haluamasi väriteema."
theme_system = "Järjestelmä"
theme_light = "Vaalea"
theme_dark = "Tumma"
language_label = "Kieli"
display_language_label = "Näyttökieli"
language_desc = "Valitse haluamasi kieli."
engines_label = "Hakukoneet"
engines_desc = "Valitse mitä hakukoneita käytetään. Vain palvelimella käyttöön otetut hakukoneet näytetään."
default_engine_label = "Oletushakukone"
all_engines_option = "Kaikki valitut hakukoneet"
save_settings_button = "Tallenna asetukset"
no_results = "Ei tuloksia"
error_images = "Virhe kuvien haussa"
rate_limit = "Hidasta hieman! Sinulta on tullut liian monta hakupyyntöä!"
warning_fetch_error = "pyyntö epäonnistui ennen kuin OmniSearch ehti lukea hakutuloksia."
warning_parse_mismatch = "palautti hakutulokset muodossa jota OmniSearch ei osaa jäsentää."
warning_blocked = "palautti captchan tai muun estosivun hakutulosten sijaan."
read_more = "Lue Lisää"
view_cached = "Välimuistissa"
view_image = "Kuva"
visit_site = "Sivu"
+121
View File
@@ -0,0 +1,121 @@
{ self }:
{ config, lib, pkgs, ... }:
let
inherit (lib) mkEnableOption mkIf mkOption types;
cfg = config.services.omnisearch;
generatedConfig = pkgs.writeText "omnisearch-config.ini" ''
${lib.generators.toINI {} cfg.settings}
${cfg.extraConfig}
'';
assetDir = "${cfg.package}/share/omnisearch";
in
{
options.services.omnisearch = {
enable = mkEnableOption "OmniSearch metasearch server";
package = mkOption {
type = types.package;
default = self.packages.${pkgs.stdenv.hostPlatform.system}.default;
defaultText = lib.literalExpression "packages.${pkgs.stdenv.hostPlatform.system}.default";
description = "OmniSearch package to run.";
};
user = mkOption {
type = types.str;
default = "omnisearch";
description = "User account under which OmniSearch runs.";
};
group = mkOption {
type = types.str;
default = "omnisearch";
description = "Group under which OmniSearch runs.";
};
settings = mkOption {
type = types.attrsOf (types.attrsOf (types.oneOf [ types.str types.int types.bool ]));
default = {
server = {
host = "0.0.0.0";
port = 8087;
};
cache.dir = "/var/cache/omnisearch";
engines.engines = "*";
};
example = {
server = { host = "127.0.0.1"; port = 8087; };
engines.engines = "ddg,startpage";
rate_limit = { search_requests = 10; search_interval = 60; };
};
description = ''
INI settings grouped by section. Section and key names follow
`example-config.ini`; values are written as strings, integers or
booleans. The generated INI is stored in the world-readable Nix store,
so do not put secrets here.
'';
};
extraConfig = mkOption {
type = types.lines;
default = "";
example = ''
[proxy]
proxy = "socks5://127.0.0.1:9050"
'';
description = ''
Additional raw INI text appended after the generated `settings`.
This text is also embedded in the world-readable Nix store; avoid
including secrets.
'';
};
openFirewall = mkOption {
type = types.bool;
default = false;
description = "Whether to open the configured TCP port in the firewall.";
};
};
config = mkIf cfg.enable {
users.groups.${cfg.group} = {};
users.users.${cfg.user} = {
isSystemUser = true;
group = cfg.group;
description = "OmniSearch service user";
};
networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [
(cfg.settings.server.port or 8087)
];
systemd.services.omnisearch = {
description = "OmniSearch metasearch server";
wantedBy = [ "multi-user.target" ];
after = [ "network.target" ];
wants = [ "network-online.target" ];
serviceConfig = {
Type = "simple";
User = cfg.user;
Group = cfg.group;
StateDirectory = "omnisearch";
CacheDirectory = "omnisearch";
WorkingDirectory = "/var/lib/omnisearch";
ExecStartPre = pkgs.writeShellScript "omnisearch-prepare" ''
ln -sfn ${lib.escapeShellArg "${assetDir}/templates"} templates
ln -sfn ${lib.escapeShellArg "${assetDir}/static"} static
ln -sfn ${lib.escapeShellArg "${assetDir}/locales"} locales
ln -sfn ${lib.escapeShellArg (toString generatedConfig)} config.ini
'';
ExecStart = "${cfg.package}/bin/omnisearch";
Restart = "on-failure";
RestartSec = "5s";
PrivateTmp = true;
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
ReadWritePaths = [ "/var/lib/omnisearch" "/var/cache/omnisearch" ];
RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ];
};
};
};
}
+19 -6
View File
@@ -287,8 +287,7 @@ static void free_search_results(SearchResult **all_results, ScrapeJob *jobs,
static void free_infobox_results(InfoBoxThreadData *data) { static void free_infobox_results(InfoBoxThreadData *data) {
for (int i = 0; i < HANDLER_COUNT; i++) { for (int i = 0; i < HANDLER_COUNT; i++) {
if (data[i].success) free_infobox(&data[i].result);
free_infobox(&data[i].result);
} }
} }
@@ -417,7 +416,11 @@ int results_handler(UrlParams *params) {
extern Config global_config; extern Config global_config;
TemplateContext ctx = new_context(); TemplateContext ctx = new_context();
char *raw_query = ""; char *raw_query = "";
const char *selected_engine_id = "all"; char selected_engine_id[32];
char *default_engine = get_default_search_engine();
snprintf(selected_engine_id, sizeof(selected_engine_id), "%s",
default_engine);
free(default_engine);
int page = 1; int page = 1;
int btnI = 0; int btnI = 0;
@@ -435,7 +438,8 @@ int results_handler(UrlParams *params) {
if (parsed > 1) if (parsed > 1)
page = parsed; page = parsed;
} else if (strcmp(params->params[i].key, "engine") == 0) { } else if (strcmp(params->params[i].key, "engine") == 0) {
selected_engine_id = params->params[i].value; snprintf(selected_engine_id, sizeof(selected_engine_id), "%s",
params->params[i].value);
} else if (strcmp(params->params[i].key, "btnI") == 0) { } else if (strcmp(params->params[i].key, "btnI") == 0) {
btnI = atoi(params->params[i].value); btnI = atoi(params->params[i].value);
} }
@@ -481,8 +485,17 @@ int results_handler(UrlParams *params) {
} }
const SearchEngine *selected_engine = find_enabled_engine(selected_engine_id); const SearchEngine *selected_engine = find_enabled_engine(selected_engine_id);
if (!selected_engine) if (selected_engine &&
selected_engine_id = "all"; !engine_allowed_for_user(selected_engine, user_engines,
user_engine_count, has_user_pref)) {
selected_engine = NULL;
}
if (selected_engine) {
snprintf(selected_engine_id, sizeof(selected_engine_id), "%s",
selected_engine->id);
} else {
snprintf(selected_engine_id, sizeof(selected_engine_id), "all");
}
context_set(&ctx, "selected_engine", selected_engine_id); context_set(&ctx, "selected_engine", selected_engine_id);
char *search_href = build_search_href(raw_query, selected_engine_id, 1); char *search_href = build_search_href(raw_query, selected_engine_id, 1);
+14 -2
View File
@@ -34,6 +34,14 @@ int settings_handler(UrlParams *params) {
int user_engine_count = 0; int user_engine_count = 0;
int has_user_pref = int has_user_pref =
(get_user_engines(&user_engines, &user_engine_count) == 0); (get_user_engines(&user_engines, &user_engine_count) == 0);
char *default_engine = get_default_search_engine();
if (strcmp(default_engine, "all") != 0 && has_user_pref &&
!user_engines_contains(default_engine, user_engines,
user_engine_count)) {
free(default_engine);
default_engine = strdup("all");
}
int enabled_count = 0; int enabled_count = 0;
for (int i = 0; i < ENGINE_COUNT; i++) { for (int i = 0; i < ENGINE_COUNT; i++) {
@@ -63,11 +71,13 @@ int settings_handler(UrlParams *params) {
} }
} }
engine_data[idx] = malloc(sizeof(char *) * 3); engine_data[idx] = malloc(sizeof(char *) * 4);
engine_data[idx][0] = (char *)ENGINE_REGISTRY[i].id; engine_data[idx][0] = (char *)ENGINE_REGISTRY[i].id;
engine_data[idx][1] = (char *)ENGINE_REGISTRY[i].name; engine_data[idx][1] = (char *)ENGINE_REGISTRY[i].name;
engine_data[idx][2] = is_selected ? "checked" : ""; engine_data[idx][2] = is_selected ? "checked" : "";
engine_inner[idx] = 3; engine_data[idx][3] =
strcmp(default_engine, ENGINE_REGISTRY[i].id) == 0 ? "selected" : "";
engine_inner[idx] = 4;
idx++; idx++;
} }
@@ -78,6 +88,7 @@ int settings_handler(UrlParams *params) {
context_set(&ctx, "query", query); context_set(&ctx, "query", query);
context_set(&ctx, "theme", theme); context_set(&ctx, "theme", theme);
context_set(&ctx, "locale", locale); context_set(&ctx, "locale", locale);
context_set(&ctx, "default_engine", default_engine);
context_set_array_of_arrays(&ctx, "locales", locale_data, locale_count, context_set_array_of_arrays(&ctx, "locales", locale_data, locale_count,
inner_counts); inner_counts);
@@ -132,6 +143,7 @@ int settings_handler(UrlParams *params) {
send_response(rendered_html); send_response(rendered_html);
free(rendered_html); free(rendered_html);
free(default_engine);
free(theme); free(theme);
free(locale); free(locale);
free_context(&ctx); free_context(&ctx);
+30
View File
@@ -10,6 +10,8 @@ int settings_save_handler(UrlParams *params) {
const char *theme = ""; const char *theme = "";
const char *locale = ""; const char *locale = "";
const char *query = ""; const char *query = "";
const char *default_engine = "all";
int default_engine_present = 0;
int engines_present = 0; int engines_present = 0;
char selected_ids[ENGINE_COUNT][32]; char selected_ids[ENGINE_COUNT][32];
int selected_count = 0; int selected_count = 0;
@@ -22,6 +24,9 @@ int settings_save_handler(UrlParams *params) {
locale = params->params[i].value; locale = params->params[i].value;
} else if (strcmp(params->params[i].key, "q") == 0) { } else if (strcmp(params->params[i].key, "q") == 0) {
query = params->params[i].value; query = params->params[i].value;
} else if (strcmp(params->params[i].key, "default_engine") == 0) {
default_engine = params->params[i].value;
default_engine_present = 1;
} else if (strcmp(params->params[i].key, "engines_present") == 0) { } else if (strcmp(params->params[i].key, "engines_present") == 0) {
engines_present = 1; engines_present = 1;
} else if (strncmp(params->params[i].key, "engine_", 7) == 0 && } else if (strncmp(params->params[i].key, "engine_", 7) == 0 &&
@@ -58,6 +63,31 @@ int settings_save_handler(UrlParams *params) {
false, false); false, false);
} }
if (default_engine_present) {
const char *validated_default = "all";
for (int i = 0; i < ENGINE_COUNT; i++) {
if (!ENGINE_REGISTRY[i].enabled ||
strcmp(default_engine, ENGINE_REGISTRY[i].id) != 0)
continue;
int selected = !engines_present;
for (int j = 0; j < selected_count; j++) {
if (strcmp(selected_ids[j], ENGINE_REGISTRY[i].id) == 0) {
selected = 1;
break;
}
}
if (selected)
validated_default = ENGINE_REGISTRY[i].id;
break;
}
set_cookie("default_engine", validated_default,
"Fri, 31 Dec 2038 23:59:59 GMT", "/", false, false);
}
char redirect_url[512]; char redirect_url[512];
snprintf(redirect_url, sizeof(redirect_url), "/settings?q=%s", query); snprintf(redirect_url, sizeof(redirect_url), "/settings?q=%s", query);
send_redirect(redirect_url); send_redirect(redirect_url);
+66 -19
View File
@@ -1,6 +1,7 @@
#include "Scraping.h" #include "Scraping.h"
#include "../Cache/Cache.h" #include "../Cache/Cache.h"
#include "../Proxy/Proxy.h" #include "../Proxy/Proxy.h"
#include "../Utility/XmlHelper.h"
#include "Config.h" #include "Config.h"
#include <curl/curl.h> #include <curl/curl.h>
#include <libxml/HTMLparser.h> #include <libxml/HTMLparser.h>
@@ -170,14 +171,26 @@ void parse_and_cache_response(ScrapeJob *job) {
} }
} }
void cleanup_job_handle(ScrapeJob *job, CURL *handle) { static void cleanup_job_results(ScrapeJob *job) {
if (!job || !job->out_results)
return;
xml_result_free(*job->out_results, job->results_count);
*job->out_results = NULL;
job->results_count = 0;
}
static void cleanup_job_handle(ScrapeJob *job, CURL *handle) {
struct curl_slist *headers = NULL; struct curl_slist *headers = NULL;
curl_easy_getinfo(handle, CURLINFO_PRIVATE, &headers); if (handle)
curl_easy_getinfo(handle, CURLINFO_PRIVATE, &headers);
if (headers) if (headers)
curl_slist_free_all(headers); curl_slist_free_all(headers);
free(job->response.memory); free(job->response.memory);
job->response.memory = NULL; job->response.memory = NULL;
job->response.size = 0;
job->response.capacity = 0;
} }
void process_response(ScrapeJob *job, CURL *handle, CURLMsg *msg) { void process_response(ScrapeJob *job, CURL *handle, CURLMsg *msg) {
@@ -194,19 +207,25 @@ void process_response(ScrapeJob *job, CURL *handle, CURLMsg *msg) {
} }
int setup_job(ScrapeJob *job, CURLM *multi_handle) { int setup_job(ScrapeJob *job, CURLM *multi_handle) {
if (job->handle) if (job->handle) {
cleanup_job_handle(job, job->handle);
curl_easy_cleanup(job->handle); curl_easy_cleanup(job->handle);
if (job->response.memory) job->handle = NULL;
} else if (job->response.memory) {
free(job->response.memory); free(job->response.memory);
job->response.memory = NULL;
job->response.size = 0;
job->response.capacity = 0;
}
job->results_count = 0; cleanup_job_results(job);
job->http_status = 0; job->http_status = 0;
job->status = SCRAPE_STATUS_PENDING; job->status = SCRAPE_STATUS_PENDING;
if (check_cache_for_job(job)) { if (check_cache_for_job(job))
job->results_count = job->results_count > 0 ? job->results_count : 0;
return 0; return 0;
}
cleanup_job_results(job);
char *encoded_query = curl_easy_escape(NULL, job->query, 0); char *encoded_query = curl_easy_escape(NULL, job->query, 0);
if (!encoded_query) { if (!encoded_query) {
@@ -247,6 +266,14 @@ int setup_job(ScrapeJob *job, CURLM *multi_handle) {
job->response.memory = (char *)malloc(INITIAL_BUFFER_SIZE); job->response.memory = (char *)malloc(INITIAL_BUFFER_SIZE);
job->response.size = 0; job->response.size = 0;
job->response.capacity = INITIAL_BUFFER_SIZE; job->response.capacity = INITIAL_BUFFER_SIZE;
if (!job->response.memory) {
curl_easy_cleanup(job->handle);
job->handle = NULL;
job->response.capacity = 0;
free(full_url);
job->status = SCRAPE_STATUS_FETCH_ERROR;
return -1;
}
struct curl_slist *headers = struct curl_slist *headers =
build_request_headers(job->engine->host_header, job->engine->referer); build_request_headers(job->engine->host_header, job->engine->referer);
@@ -255,10 +282,33 @@ int setup_job(ScrapeJob *job, CURLM *multi_handle) {
curl_easy_setopt(job->handle, CURLOPT_PRIVATE, headers); curl_easy_setopt(job->handle, CURLOPT_PRIVATE, headers);
free(full_url); free(full_url);
curl_multi_add_handle(multi_handle, job->handle); CURLMcode add_result = curl_multi_add_handle(multi_handle, job->handle);
if (add_result != CURLM_OK) {
cleanup_job_handle(job, job->handle);
curl_easy_cleanup(job->handle);
job->handle = NULL;
job->status = SCRAPE_STATUS_FETCH_ERROR;
return -1;
}
return 0; return 0;
} }
static void cleanup_unfinished_jobs(CURLM *multi_handle, ScrapeJob *jobs,
int num_jobs) {
for (int i = 0; i < num_jobs; i++) {
if (!jobs[i].handle)
continue;
curl_multi_remove_handle(multi_handle, jobs[i].handle);
cleanup_job_handle(&jobs[i], jobs[i].handle);
curl_easy_cleanup(jobs[i].handle);
jobs[i].handle = NULL;
if (jobs[i].status == SCRAPE_STATUS_PENDING)
jobs[i].status = SCRAPE_STATUS_FETCH_ERROR;
}
}
int handle_responses(CURLM *multi_handle, ScrapeJob *jobs, int num_jobs) { int handle_responses(CURLM *multi_handle, ScrapeJob *jobs, int num_jobs) {
CURLMsg *msg; CURLMsg *msg;
int msgs_left; int msgs_left;
@@ -304,27 +354,24 @@ retry:;
return -1; return -1;
for (int i = 0; i < num_jobs; i++) { for (int i = 0; i < num_jobs; i++) {
if (setup_job(&jobs[i], multi_handle) != 0 && jobs[i].handle) { setup_job(&jobs[i], multi_handle);
curl_multi_remove_handle(multi_handle, jobs[i].handle);
curl_easy_cleanup(jobs[i].handle);
jobs[i].handle = NULL;
}
} }
http_delay(); http_delay();
int still_running = 0; int still_running = 0;
curl_multi_perform(multi_handle, &still_running); CURLMcode mc = curl_multi_perform(multi_handle, &still_running);
do { while (mc == CURLM_OK && still_running) {
int numfds = 0; int numfds = 0;
CURLMcode mc = curl_multi_wait(multi_handle, NULL, 0, 1000, &numfds); mc = curl_multi_wait(multi_handle, NULL, 0, 1000, &numfds);
if (mc != CURLM_OK) if (mc != CURLM_OK)
break; break;
curl_multi_perform(multi_handle, &still_running); mc = curl_multi_perform(multi_handle, &still_running);
} while (still_running); }
handle_responses(multi_handle, jobs, num_jobs); handle_responses(multi_handle, jobs, num_jobs);
cleanup_unfinished_jobs(multi_handle, jobs, num_jobs);
curl_multi_cleanup(multi_handle); curl_multi_cleanup(multi_handle);
if (retries < max_proxy_retries && should_retry(jobs, num_jobs)) { if (retries < max_proxy_retries && should_retry(jobs, num_jobs)) {
+9
View File
@@ -217,6 +217,15 @@ int user_engines_contains(const char *engine_id, char **ids, int count) {
return 0; return 0;
} }
char *get_default_search_engine(void) {
char *cookie = get_cookie("default_engine");
if (cookie && (strcmp(cookie, "all") == 0 || is_engine_id_enabled(cookie)))
return cookie;
free(cookie);
return strdup("all");
}
void free_string_matrix(char ***matrix, int *inner_counts, int row_count) { void free_string_matrix(char ***matrix, int *inner_counts, int row_count) {
if (matrix) { if (matrix) {
for (int i = 0; i < row_count; i++) { for (int i = 0; i < row_count; i++) {
+1
View File
@@ -30,6 +30,7 @@ char *get_locale(const char *default_locale);
int is_engine_id_enabled(const char *engine_id); int is_engine_id_enabled(const char *engine_id);
int get_user_engines(char ***out_ids, int *out_count); int get_user_engines(char ***out_ids, int *out_count);
int user_engines_contains(const char *engine_id, char **ids, int count); int user_engines_contains(const char *engine_id, char **ids, int count);
char *get_default_search_engine(void);
void free_string_matrix(char ***matrix, int *inner_counts, int row_count); void free_string_matrix(char ***matrix, int *inner_counts, int row_count);
+38 -2
View File
@@ -822,6 +822,38 @@ header .logo-link:hover {
height:18px; height:18px;
accent-color:var(--accent); accent-color:var(--accent);
cursor:pointer; cursor:pointer;
flex-shrink:0;
margin:0;
}
.settings-engine-list {
margin:0;
}
.settings-engine-options {
display:grid;
gap:8px;
margin-inline:-3px;
}
.settings-engine-option {
display:flex;
align-items:center;
justify-content:space-between;
gap:16px;
padding:12px 14px;
border:1px solid var(--border);
border-radius:8px;
background:var(--bg-main);
color:var(--text-primary);
font-size:0.95rem;
cursor:pointer;
}
.settings-default-engine-field {
margin-top:12px;
padding-top:12px;
border-top:1px solid var(--border);
} }
.settings-actions { .settings-actions {
@@ -888,6 +920,12 @@ header .logo-link:hover {
align-items:stretch; align-items:stretch;
gap:8px; gap:8px;
} }
.settings-engine-options {
margin-inline:0;
}
.settings-engine-option {
padding-inline:7px;
}
.settings-actions { .settings-actions {
flex-direction:column; flex-direction:column;
} }
@@ -936,5 +974,3 @@ header .logo-link:hover {
flex-direction: column; flex-direction: column;
} }
} }
+1 -1
View File
@@ -7,5 +7,5 @@
<Url type="text/html" method="get" template="{{scheme}}://{{domain}}/search?q={searchTerms}"/> <Url type="text/html" method="get" template="{{scheme}}://{{domain}}/search?q={searchTerms}"/>
<InputEncoding>UTF-8</InputEncoding> <InputEncoding>UTF-8</InputEncoding>
<OutputEncoding>UTF-8</OutputEncoding> <OutputEncoding>UTF-8</OutputEncoding>
<moz:SearchForm>{{domain}}/</moz:SearchForm> <moz:SearchForm>{{scheme}}://{{domain}}/</moz:SearchForm>
</OpenSearchDescription> </OpenSearchDescription>
+24 -7
View File
@@ -76,16 +76,33 @@
</div> </div>
</section> </section>
{{if has_enabled_engines}} {{if has_enabled_engines}}
<section class="settings-section"> <section class="settings-section settings-engines-section">
<h3 class="settings-section-title">{{l("engines_label")}}</h3> <h3 class="settings-section-title">{{l("engines_label")}}</h3>
<p class="settings-section-desc">{{l("engines_desc")}}</p> <p class="settings-section-desc">{{l("engines_desc")}}</p>
<input type="hidden" name="engines_present" value="1"> <input type="hidden" name="engines_present" value="1">
{{for eng in enabled_engines}}
<div class="settings-field"> <div class="settings-engine-list">
<label class="settings-label" for="engine_{{eng[0]}}">{{eng[1]}}</label> <div class="settings-engine-options">
<input type="checkbox" id="engine_{{eng[0]}}" name="engine_{{eng[0]}}" value="1" class="settings-checkbox" {{eng[2]}}> {{for eng in enabled_engines}}
<label class="settings-engine-option" for="engine_{{eng[0]}}">
<span>{{eng[1]}}</span>
<input type="checkbox" id="engine_{{eng[0]}}" name="engine_{{eng[0]}}" value="1" class="settings-checkbox" {{eng[2]}}>
</label>
{{endfor}}
</div>
</div>
<div class="settings-field settings-default-engine-field">
<label class="settings-label" for="default_engine">{{l("default_engine_label")}}</label>
<select id="default_engine" name="default_engine" class="settings-select">
<option value="all" {{if default_engine == "all"}}selected{{endif}}>{{l("all_engines_option")}}</option>
{{for eng in enabled_engines}}
{{if eng[2] != ""}}
<option value="{{eng[0]}}" {{eng[3]}}>{{eng[1]}}</option>
{{endif}}
{{endfor}}
</select>
</div> </div>
{{endfor}}
</section> </section>
{{endif}} {{endif}}
<div class="settings-actions"> <div class="settings-actions">
@@ -96,4 +113,4 @@
</div> </div>
</body> </body>
</html> </html>
+458
View File
@@ -0,0 +1,458 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF LICENSE
+84
View File
@@ -0,0 +1,84 @@
CC ?= cc
UNAME_S := $(shell uname -s)
AR := ar
CFLAGS := -Wall -fPIC -I. -Isrc
BUILD_DIR ?= build
OBJ_DIR := $(BUILD_DIR)/obj
ifeq ($(UNAME_S),Darwin)
INSTALL_PREFIX ?= /usr/local/
SHARED_EXT := dylib
LDCONFIG := true
LDFLAGS := -dynamiclib -lpthread -Wl,-install_name,$(INSTALL_PREFIX)lib/libbeaker.$(SHARED_EXT)
else
INSTALL_PREFIX ?= /usr/
SHARED_EXT := so
LDCONFIG := ldconfig
LDFLAGS := -shared -lpthread
endif
SRCS := $(wildcard src/*.c)
OBJS := $(patsubst src/%.c,$(OBJ_DIR)/%.o,$(SRCS))
LIB_BASE := $(BUILD_DIR)/libbeaker
STATIC_LIB := $(LIB_BASE).a
SHARED_LIB := $(LIB_BASE).$(SHARED_EXT)
HEADER := beaker.h
.PHONY: all clean install uninstall info
all: $(SHARED_LIB) $(STATIC_LIB)
$(OBJ_DIR):
@mkdir -p $(OBJ_DIR)
$(STATIC_LIB): $(OBJS)
@echo "Linking static library $@..."
$(AR) rcs $@ $^
@echo "Successfully built $@"
$(SHARED_LIB): $(OBJS)
@echo "Linking shared library $@..."
$(CC) $(LDFLAGS) $(OBJS) -o $@ -lm
@echo "Successfully built $@"
$(OBJ_DIR)/%.o: src/%.c | $(OBJ_DIR)
@echo "Compiling $<..."
$(CC) $(CFLAGS) -c $< -o $@
clean:
@echo "Cleaning up object files and libraries..."
@rm -rf $(BUILD_DIR)
@echo "Clean complete."
install: all
@echo "Installing libraries to $(INSTALL_PREFIX)lib"
@mkdir -p $(INSTALL_PREFIX)lib
ifeq ($(UNAME_S),Darwin)
@rm -f $(INSTALL_PREFIX)lib/libbeaker.so
endif
@cp $(SHARED_LIB) $(STATIC_LIB) $(INSTALL_PREFIX)lib/
@$(LDCONFIG) || true
@echo "Installing $(HEADER) to $(INSTALL_PREFIX)include"
@mkdir -p $(INSTALL_PREFIX)include
@cp $(HEADER) $(INSTALL_PREFIX)include
@echo "Installation complete."
uninstall:
@echo "Uninstalling from $(INSTALL_PREFIX)..."
@rm -f $(INSTALL_PREFIX)lib/libbeaker.$(SHARED_EXT)
@rm -f $(INSTALL_PREFIX)lib/libbeaker.a
ifeq ($(UNAME_S),Darwin)
@rm -f $(INSTALL_PREFIX)lib/libbeaker.so
endif
@rm -f $(INSTALL_PREFIX)include/$(HEADER)
@$(LDCONFIG) || true
@echo "Uninstallation complete."
info:
@echo "Detected OS: '$(UNAME_S)'"
@echo "Compiler: $(CC)"
@echo "Install Prefix: $(INSTALL_PREFIX)"
@echo "Shared Library: $(SHARED_LIB)"
@echo "Source Files: $(SRCS)"
+32
View File
@@ -0,0 +1,32 @@
# Beaker
Beaker is a lightweight web framework written in C, designed for building simple and efficient web applications. It currently provides handling HTTP requests, routing, serving static files, rendering HTML templates and managing cookies.
## Disclaimer
I request that none of this code, in part or in full, be hosted on GitHub, SourceForge, or any other proprietary platform. This request is made out of respect for both me, the developer and for you, the user.
## Usage
Look at the files in examples for usage
## Installation
```bash
$ git clone https://git.bwaaa.monster/beaker
$ cd beaker
# make install
```
On macOS the default install prefix is `/usr/local/`, because `/usr/lib` is protected by System Integrity Protection.
The install step produces `libbeaker.dylib` and removes any stale `libbeaker.so` from older installs.
You can always override the destination:
```bash
$ make install INSTALL_PREFIX=/some/prefix/
```
## Roadmap
- Write documentation
- Write more examples
## Contribution
Generate a patch with ```git format-patch HEAD~1``` and email to [gabriel@bwaaa.monster](mailto:gabriel@bwaaa.monster), beginning the subject line with [PATCH beaker]
*If you are sending a revised version of a previous patch, please use [PATCH beaker v2, v3, etc].*
+5
View File
@@ -0,0 +1,5 @@
Vendored from https://codeberg.org/gabrielf/beaker at commit
`acdd9e754a536d542099951e4c9a6acc8cdf1c51` (2026-08-16).
Includes the upstream build files, public header, C sources, README and
LGPL-2.1 license. The example programs are not needed to build OmniSearch.
+151
View File
@@ -0,0 +1,151 @@
#ifndef BEAKER_H
#define BEAKER_H
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CONTEXT_VARS 32
#define MAX_KEY_LEN 64
#define MAX_VALUE_LEN 256
#define MAX_PATH_LEN 256
#define MAX_HANDLERS 32
#define BUFFER_SIZE 4096
#define MAX_URL_PARAMS 16
#define MAX_COOKIES 10
#define MAX_OUTER_ARRAY_ITEMS 100
#define MAX_INNER_ARRAY_ITEMS 200
#define TEMPLATES_DIR "templates/"
#define STATIC_DIR "static/"
#define LOCALES_DIR "locales/"
#define INITIAL_LOCALES_CAPACITY 8
#define INITIAL_LOCALE_KEYS_CAPACITY 16
#define MAX_LOCALES_HARD 1024
#define MAX_LOCALE_KEYS_HARD 65536
#define MAX_LOCALE_ID_LEN 64
#define MAX_LOCALE_VALUE_LEN 512
typedef enum {
CONTEXT_TYPE_STRING,
CONTEXT_TYPE_STRING_ARRAY,
CONTEXT_TYPE_STRING_2D_ARRAY,
} ContextType;
typedef struct {
char key[MAX_KEY_LEN];
ContextType type;
union {
char string_val[MAX_VALUE_LEN];
struct {
char **values;
int count;
} string_array_data;
struct {
char ***values;
int outer_count;
int *inner_counts;
} string_2d_array_data;
} value;
} ContextVar;
typedef struct {
ContextVar vars[MAX_CONTEXT_VARS];
int count;
} TemplateContext;
typedef struct {
char key[MAX_KEY_LEN];
char value[MAX_VALUE_LEN];
} UrlParam;
typedef struct {
UrlParam params[MAX_URL_PARAMS];
int count;
} UrlParams;
typedef struct {
char name[MAX_KEY_LEN];
char value[MAX_VALUE_LEN];
char expires[MAX_VALUE_LEN];
char path[MAX_KEY_LEN];
bool http_only;
bool secure;
} Cookie;
typedef struct {
char id[MAX_LOCALE_ID_LEN];
char name[MAX_VALUE_LEN];
char direction[16];
} LocaleMeta;
typedef struct {
char key[MAX_KEY_LEN];
char value[MAX_LOCALE_VALUE_LEN];
} LocaleKV;
typedef struct {
LocaleMeta meta;
LocaleKV *keys;
int key_count;
int key_capacity;
} Locale;
typedef struct {
LocaleMeta meta;
} LocaleInfo;
typedef int (*RequestHandler)(UrlParams *params);
typedef struct {
char path[MAX_PATH_LEN];
RequestHandler handler;
} RouteHandler;
typedef struct {
char remote_addr[32];
} RequestInfo;
TemplateContext new_context();
void context_set(TemplateContext *ctx, const char *key, const char *value);
void context_set_string_array(TemplateContext *ctx, const char *key,
char *values[], int count);
void context_set_array_of_arrays(TemplateContext *ctx, const char *key,
char **values_2d[], int outer_count,
int inner_counts[]);
void free_context(TemplateContext *ctx);
char *render_template(const char *template_file, TemplateContext *ctx);
int beaker_load_locales(void);
void beaker_set_locale(TemplateContext *ctx, const char *locale_id);
int beaker_get_all_locales(LocaleInfo *out, int max_count);
const LocaleMeta *beaker_get_locale_meta(const char *locale_id);
const char *beaker_get_locale_value(const char *locale_id, const char *key);
void beaker_free_locales(void);
void send_response(const char *html);
void send_redirect(const char *location);
void send_status(const char *status_line);
void set_cookie(const char *name, const char *value, const char *expires,
const char *path, bool http_only, bool secure);
char *get_cookie(const char *cookie_name);
void set_handler(const char *path, RequestHandler handler);
char *parse_request_url(const char *request_buffer, UrlParams *params);
const char *get_mime_type(const char *file_path);
bool serve_static_file(const char *request_path_relative_to_static);
bool serve_static_file_with_mime(const char *request_path_relative_to_static, const char *mime_type);
bool serve_data(const char *data, size_t size, const char *mime_type);
int beaker_run(const char *ip, int port);
void beaker_run_with_threads(const char *ip, int port, int num_workers);
const char *beaker_get_remote_addr(void);
const char *beaker_get_header(const char *name);
void beaker_set_request_buffer(const char *buffer);
#endif
+25
View File
@@ -0,0 +1,25 @@
#include "beaker_globals.h"
RouteHandler handlers[MAX_HANDLERS];
int handler_count = 0;
__thread int current_client_socket = -1;
__thread Cookie cookies_to_set[MAX_COOKIES];
__thread int cookies_to_set_count = 0;
__thread char current_request_buffer[BUFFER_SIZE];
__thread RequestInfo current_request_info = {0};
__thread int current_response_status = 0;
__thread size_t current_response_size = 0;
Locale *locales = NULL;
int locale_count = 0;
int locale_capacity = 0;
+76
View File
@@ -0,0 +1,76 @@
#ifndef BEAKER_GLOBALS_H
#define BEAKER_GLOBALS_H
#include "../beaker.h"
#include <stdatomic.h>
#include <stddef.h>
#ifndef BEAKER_REQUEST_HEADER_TIMEOUT_MS
#define BEAKER_REQUEST_HEADER_TIMEOUT_MS 5000
#endif
#ifndef BEAKER_RESPONSE_WRITE_TIMEOUT_MS
#define BEAKER_RESPONSE_WRITE_TIMEOUT_MS 30000
#endif
typedef enum {
BEAKER_REQUEST_READ_OK = 0,
BEAKER_REQUEST_READ_CLOSED,
BEAKER_REQUEST_READ_TIMEOUT,
BEAKER_REQUEST_READ_TOO_LARGE,
BEAKER_REQUEST_READ_ERROR,
} BeakerRequestReadResult;
extern RouteHandler handlers[MAX_HANDLERS];
extern int handler_count;
extern __thread int current_client_socket;
extern __thread Cookie cookies_to_set[MAX_COOKIES];
extern __thread int cookies_to_set_count;
extern __thread char current_request_buffer[BUFFER_SIZE];
extern __thread RequestInfo current_request_info;
extern __thread int current_response_status;
extern __thread size_t current_response_size;
void beaker_log(const char *level, const char *format, ...);
void beaker_log_errno_format(const char *level, const char *format, ...);
void beaker_log_errno(const char *message);
void beaker_log_request(const char *remote_addr, const char *method,
const char *path, int status, size_t response_size,
double duration_ms);
void beaker_clear_response_cookies(void);
BeakerRequestReadResult beaker_read_request_headers(int socket, char *buffer,
size_t buffer_size,
size_t *bytes_read);
int beaker_configure_client_socket(int socket);
int beaker_send_all(int socket, const void *buffer, size_t length);
void beaker_reset_write_deadline(void);
bool beaker_is_valid_http_token(const char *value);
bool beaker_is_valid_http_token_span(const char *value, size_t length);
bool beaker_is_valid_header_value(const char *value);
extern Locale *locales;
extern int locale_count;
extern int locale_capacity;
#endif
+387
View File
@@ -0,0 +1,387 @@
#include "../beaker.h"
#include "beaker_globals.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
static bool is_http_token_char(unsigned char c) {
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z')) {
return true;
}
return c == '!' || c == '#' || c == '$' || c == '%' || c == '&' ||
c == '\'' || c == '*' || c == '+' || c == '-' || c == '.' ||
c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
}
bool beaker_is_valid_http_token(const char *value) {
if (value == NULL) {
return false;
}
return beaker_is_valid_http_token_span(value, strlen(value));
}
bool beaker_is_valid_http_token_span(const char *value, size_t length) {
if (value == NULL || length == 0)
return false;
for (size_t i = 0; i < length; i++) {
if (!is_http_token_char((unsigned char)value[i])) {
return false;
}
}
return true;
}
bool beaker_is_valid_header_value(const char *value) {
if (value == NULL) {
return false;
}
for (size_t i = 0; value[i] != '\0'; i++) {
unsigned char c = (unsigned char)value[i];
if (c < 0x20 || c == 0x7f) {
return false;
}
}
return true;
}
static bool is_valid_cookie_value(const char *value) {
if (value == NULL) {
return false;
}
for (size_t i = 0; value[i] != '\0'; i++) {
unsigned char c = (unsigned char)value[i];
if (!(c == 0x21 || (c >= 0x23 && c <= 0x2b) || (c >= 0x2d && c <= 0x3a) ||
(c >= 0x3c && c <= 0x5b) || (c >= 0x5d && c <= 0x7e))) {
return false;
}
}
return true;
}
static bool is_valid_cookie_attribute(const char *value) {
return value == NULL ||
(beaker_is_valid_header_value(value) && strchr(value, ';') == NULL);
}
static bool parse_status_line(const char *status_line, int *status_code) {
if (status_line == NULL || status_code == NULL)
return false;
size_t status_line_len = strlen(status_line);
if (status_line_len < 5 || status_line_len >= 128 || status_line[0] < '0' ||
status_line[0] > '9' || status_line[1] < '0' || status_line[1] > '9' ||
status_line[2] < '0' || status_line[2] > '9' || status_line[3] != ' ' ||
status_line[4] == '\0' || !beaker_is_valid_header_value(status_line)) {
return false;
}
int code = (status_line[0] - '0') * 100 + (status_line[1] - '0') * 10 +
(status_line[2] - '0');
if (code < 100 || code > 599) {
return false;
}
*status_code = code;
return true;
}
static void build_cookie_headers(char *cookie_headers_buffer,
size_t buffer_size) {
cookie_headers_buffer[0] = '\0';
for (int i = 0; i < cookies_to_set_count; i++) {
char single_cookie_header[MAX_KEY_LEN * 2 + MAX_VALUE_LEN * 2 + 128];
int header_length = snprintf(
single_cookie_header, sizeof(single_cookie_header), "Set-Cookie: %s=%s",
cookies_to_set[i].name, cookies_to_set[i].value);
if (header_length < 0 ||
(size_t)header_length >= sizeof(single_cookie_header)) {
beaker_log("ERROR", "build_cookie_headers: Cookie is too large.");
continue;
}
if (strlen(cookies_to_set[i].expires) > 0) {
strncat(single_cookie_header, "; Expires=",
sizeof(single_cookie_header) - strlen(single_cookie_header) - 1);
strncat(single_cookie_header, cookies_to_set[i].expires,
sizeof(single_cookie_header) - strlen(single_cookie_header) - 1);
}
if (strlen(cookies_to_set[i].path) > 0) {
strncat(single_cookie_header, "; Path=",
sizeof(single_cookie_header) - strlen(single_cookie_header) - 1);
strncat(single_cookie_header, cookies_to_set[i].path,
sizeof(single_cookie_header) - strlen(single_cookie_header) - 1);
}
if (cookies_to_set[i].http_only) {
strncat(single_cookie_header, "; HttpOnly",
sizeof(single_cookie_header) - strlen(single_cookie_header) - 1);
}
if (cookies_to_set[i].secure) {
strncat(single_cookie_header, "; Secure",
sizeof(single_cookie_header) - strlen(single_cookie_header) - 1);
}
strncat(single_cookie_header, "\r\n",
sizeof(single_cookie_header) - strlen(single_cookie_header) - 1);
if (strlen(cookie_headers_buffer) + strlen(single_cookie_header) <
buffer_size) {
strncat(cookie_headers_buffer, single_cookie_header,
buffer_size - strlen(cookie_headers_buffer) - 1);
} else {
beaker_log(
"WARN",
"build_cookie_headers: Cookie headers buffer full, truncating\n");
break;
}
}
}
void beaker_clear_response_cookies(void) {
memset(cookies_to_set, 0, sizeof(cookies_to_set));
cookies_to_set_count = 0;
}
void send_status(const char *status_line) {
if (current_client_socket == -1) {
beaker_log("ERROR",
"send_status: No client socket set. Cannot send response.\n");
return;
}
int status_code;
if (!parse_status_line(status_line, &status_code)) {
beaker_log("SECURITY", "send_status: Rejected invalid HTTP status line.");
status_line = "500 Internal Server Error";
status_code = 500;
}
char http_response[BUFFER_SIZE];
current_response_status = status_code;
current_response_size = 0;
int response_length = snprintf(http_response, sizeof(http_response),
"HTTP/1.1 %s\r\n"
"Content-Length: 0\r\n"
"Connection: close\r\n"
"\r\n",
status_line);
if (response_length < 0 || (size_t)response_length >= sizeof(http_response)) {
beaker_log("ERROR", "send_status: Failed to construct HTTP status.");
return;
}
if (beaker_send_all(current_client_socket, http_response,
strlen(http_response)) < 0) {
beaker_log_errno_format("ERROR",
"send_status: Failed to send HTTP status.\n");
}
}
void send_response(const char *html) {
if (current_client_socket == -1) {
beaker_log("ERROR",
"send_response: No client socket set. Cannot send response.\n");
return;
}
char http_response_header[BUFFER_SIZE * 2];
size_t content_length = strlen(html);
current_response_status = 200;
current_response_size = content_length;
char cookie_headers[BUFFER_SIZE];
build_cookie_headers(cookie_headers, sizeof(cookie_headers));
beaker_clear_response_cookies();
snprintf(http_response_header, sizeof(http_response_header),
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Content-Length: %zu\r\n"
"%s"
"Connection: close\r\n"
"\r\n",
content_length, cookie_headers);
if (beaker_send_all(current_client_socket, http_response_header,
strlen(http_response_header)) < 0) {
beaker_log_errno_format("ERROR",
"send_response: Failed to send HTTP header.\n");
return;
}
if (beaker_send_all(current_client_socket, html, content_length) < 0) {
beaker_log_errno_format("ERROR",
"send_response: Failed to send HTML body.\n");
return;
}
}
void send_redirect(const char *location) {
if (current_client_socket == -1) {
beaker_log("ERROR",
"send_redirect: No client socket set. Cannot send redirect.\n");
return;
}
if (location == NULL || location[0] == '\0' ||
!beaker_is_valid_header_value(location)) {
beaker_log("SECURITY", "send_redirect: Rejected invalid Location value.");
beaker_clear_response_cookies();
send_status("500 Internal Server Error");
return;
}
char http_response_header[BUFFER_SIZE * 2];
current_response_status = 302;
current_response_size = 0;
char cookie_headers[BUFFER_SIZE];
build_cookie_headers(cookie_headers, sizeof(cookie_headers));
beaker_clear_response_cookies();
int header_length =
snprintf(http_response_header, sizeof(http_response_header),
"HTTP/1.1 302 Found\r\n"
"Location: %s\r\n"
"%s"
"Connection: close\r\n"
"\r\n",
location, cookie_headers);
if (header_length < 0 ||
(size_t)header_length >= sizeof(http_response_header)) {
beaker_log("SECURITY", "send_redirect: Location value is too long.");
send_status("500 Internal Server Error");
return;
}
if (beaker_send_all(current_client_socket, http_response_header,
strlen(http_response_header)) < 0) {
beaker_log_errno_format("ERROR",
"send_redirect: Failed to send redirect header.\n");
return;
}
}
void set_cookie(const char *name, const char *value, const char *expires,
const char *path, bool http_only, bool secure) {
if (!beaker_is_valid_http_token(name) || !is_valid_cookie_value(value) ||
!is_valid_cookie_attribute(expires) || !is_valid_cookie_attribute(path) ||
strlen(name) >= MAX_KEY_LEN || strlen(value) >= MAX_VALUE_LEN ||
(expires != NULL && strlen(expires) >= MAX_VALUE_LEN) ||
(path != NULL && strlen(path) >= MAX_KEY_LEN)) {
beaker_log("SECURITY", "set_cookie: Rejected invalid cookie data.");
return;
}
if (cookies_to_set_count >= MAX_COOKIES) {
beaker_log("WARN",
"set_cookie: Maximum number of cookies to set reached. Cannot "
"set cookie '%s'.\n",
name);
return;
}
Cookie *new_cookie = &cookies_to_set[cookies_to_set_count];
strncpy(new_cookie->name, name, MAX_KEY_LEN - 1);
new_cookie->name[MAX_KEY_LEN - 1] = '\0';
strncpy(new_cookie->value, value, MAX_VALUE_LEN - 1);
new_cookie->value[MAX_VALUE_LEN - 1] = '\0';
if (expires && strlen(expires) > 0) {
strncpy(new_cookie->expires, expires, MAX_VALUE_LEN - 1);
new_cookie->expires[MAX_VALUE_LEN - 1] = '\0';
} else {
new_cookie->expires[0] = '\0';
}
if (path && strlen(path) > 0) {
strncpy(new_cookie->path, path, MAX_KEY_LEN - 1);
new_cookie->path[MAX_KEY_LEN - 1] = '\0';
} else {
new_cookie->path[0] = '\0';
}
new_cookie->http_only = http_only;
new_cookie->secure = secure;
cookies_to_set_count++;
}
char *get_cookie(const char *cookie_name) {
char *cookie_header_start = strstr(current_request_buffer, "\r\nCookie: ");
if (cookie_header_start == NULL) {
return NULL;
}
cookie_header_start += strlen("\r\nCookie: ");
char *cookie_header_end = strstr(cookie_header_start, "\r\n");
if (cookie_header_end == NULL) {
cookie_header_end =
(char *)(current_request_buffer + strlen(current_request_buffer));
}
size_t cookie_str_len = cookie_header_end - cookie_header_start;
char *cookie_str = (char *)malloc(cookie_str_len + 1);
if (cookie_str == NULL) {
beaker_log_errno_format("ERROR",
"get_cookie: Allocation failed for cookie_str.\n");
return NULL;
}
strncpy(cookie_str, cookie_header_start, cookie_str_len);
cookie_str[cookie_str_len] = '\0';
char *token;
char *saveptr_cookie;
token = strtok_r(cookie_str, ";", &saveptr_cookie);
while (token != NULL) {
while (*token == ' ') {
token++;
}
char *equals_sign = strchr(token, '=');
if (equals_sign != NULL) {
size_t name_len = equals_sign - token;
if (name_len == strlen(cookie_name) &&
strncmp(token, cookie_name, name_len) == 0) {
char *cookie_value = strdup(equals_sign + 1);
if (cookie_value == NULL) {
beaker_log_errno_format(
"ERROR", "get_cookie: Allocation failed for cookie_value.\n");
}
free(cookie_str);
return cookie_value;
}
}
token = strtok_r(NULL, ";", &saveptr_cookie);
}
free(cookie_str);
return NULL;
}
+185
View File
@@ -0,0 +1,185 @@
#include "beaker_globals.h"
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <stdint.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
static __thread int64_t write_deadline_ms = 0;
int beaker_configure_client_socket(int socket) {
int flags = fcntl(socket, F_GETFL, 0);
if (flags < 0) {
return -1;
}
if ((flags & O_NONBLOCK) == 0 &&
fcntl(socket, F_SETFL, flags | O_NONBLOCK) < 0) {
return -1;
}
#ifdef SO_NOSIGPIPE
int enabled = 1;
if (setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &enabled, sizeof(enabled)) <
0) {
return -1;
}
#endif
return 0;
}
static int64_t monotonic_time_ms(void) {
struct timespec now;
if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) {
return -1;
}
return (int64_t)now.tv_sec * 1000 + now.tv_nsec / 1000000;
}
static int wait_for_socket(int socket, short events, int64_t deadline_ms) {
for (;;) {
int64_t now_ms = monotonic_time_ms();
if (now_ms < 0) {
return -1;
}
int64_t remaining_ms = deadline_ms - now_ms;
if (remaining_ms <= 0) {
errno = ETIMEDOUT;
return -1;
}
int timeout_ms = remaining_ms > INT_MAX ? INT_MAX : (int)remaining_ms;
struct pollfd descriptor = {.fd = socket, .events = events};
int result = poll(&descriptor, 1, timeout_ms);
if (result > 0) {
if (descriptor.revents & POLLNVAL) {
errno = EBADF;
return -1;
}
if (descriptor.revents & (events | POLLERR | POLLHUP)) {
return 0;
}
continue;
}
if (result == 0) {
errno = ETIMEDOUT;
return -1;
}
if (errno != EINTR) {
return -1;
}
}
}
static bool contains_complete_headers(const char *buffer, size_t length) {
if (length < 4) {
return false;
}
for (size_t i = 0; i <= length - 4; i++) {
if (buffer[i] == '\r' && buffer[i + 1] == '\n' && buffer[i + 2] == '\r' &&
buffer[i + 3] == '\n') {
return true;
}
}
return false;
}
BeakerRequestReadResult beaker_read_request_headers(int socket, char *buffer,
size_t buffer_size,
size_t *bytes_read) {
if (buffer == NULL || bytes_read == NULL || buffer_size < 2) {
errno = EINVAL;
return BEAKER_REQUEST_READ_ERROR;
}
*bytes_read = 0;
buffer[0] = '\0';
int64_t now_ms = monotonic_time_ms();
if (now_ms < 0) {
return BEAKER_REQUEST_READ_ERROR;
}
int64_t deadline_ms = now_ms + BEAKER_REQUEST_HEADER_TIMEOUT_MS;
while (*bytes_read < buffer_size - 1) {
ssize_t result =
recv(socket, buffer + *bytes_read, buffer_size - 1 - *bytes_read, 0);
if (result > 0) {
*bytes_read += (size_t)result;
buffer[*bytes_read] = '\0';
if (contains_complete_headers(buffer, *bytes_read)) {
return BEAKER_REQUEST_READ_OK;
}
continue;
}
if (result == 0) {
return BEAKER_REQUEST_READ_CLOSED;
}
if (errno == EINTR) {
continue;
}
if (errno != EAGAIN && errno != EWOULDBLOCK) {
return BEAKER_REQUEST_READ_ERROR;
}
if (wait_for_socket(socket, POLLIN, deadline_ms) != 0) {
return errno == ETIMEDOUT ? BEAKER_REQUEST_READ_TIMEOUT
: BEAKER_REQUEST_READ_ERROR;
}
}
return BEAKER_REQUEST_READ_TOO_LARGE;
}
void beaker_reset_write_deadline(void) { write_deadline_ms = 0; }
int beaker_send_all(int socket, const void *buffer, size_t length) {
if (buffer == NULL && length != 0) {
errno = EINVAL;
return -1;
}
if (write_deadline_ms == 0) {
int64_t now_ms = monotonic_time_ms();
if (now_ms < 0) {
return -1;
}
write_deadline_ms = now_ms + BEAKER_RESPONSE_WRITE_TIMEOUT_MS;
}
const char *bytes = buffer;
size_t bytes_sent = 0;
while (bytes_sent < length) {
#ifdef MSG_NOSIGNAL
ssize_t result =
send(socket, bytes + bytes_sent, length - bytes_sent, MSG_NOSIGNAL);
#else
ssize_t result = send(socket, bytes + bytes_sent, length - bytes_sent, 0);
#endif
if (result > 0) {
bytes_sent += (size_t)result;
continue;
}
if (result == 0) {
errno = EPIPE;
return -1;
}
if (errno == EINTR) {
continue;
}
if (errno != EAGAIN && errno != EWOULDBLOCK) {
return -1;
}
if (wait_for_socket(socket, POLLOUT, write_deadline_ms) != 0) {
return -1;
}
}
return 0;
}
+291
View File
@@ -0,0 +1,291 @@
#include "../beaker.h"
#include "beaker_globals.h"
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum {
SECTION_NONE,
SECTION_META,
SECTION_KEYS,
} IniSection;
static char *trim(char *str) {
if (str == NULL)
return NULL;
while (*str == ' ' || *str == '\t')
str++;
if (*str == '\0')
return str;
char *end = str + strlen(str) - 1;
while (end > str &&
(*end == ' ' || *end == '\t' || *end == '\r' || *end == '\n')) {
*end = '\0';
end--;
}
return str;
}
static void unquote_value(char *value) {
size_t len = strlen(value);
if (len >= 2 && value[0] == '"' && value[len - 1] == '"') {
memmove(value, value + 1, len - 2);
value[len - 2] = '\0';
}
}
static int safe_grow_capacity(int current, int hard_max) {
int new_cap;
if (current == 0) {
new_cap = (hard_max < INITIAL_LOCALE_KEYS_CAPACITY)
? hard_max
: INITIAL_LOCALE_KEYS_CAPACITY;
} else {
new_cap = current * 2;
if (new_cap > hard_max)
new_cap = hard_max;
}
return new_cap;
}
static int parse_ini_file(const char *path, Locale *locale) {
FILE *fp = fopen(path, "r");
if (fp == NULL) {
beaker_log("ERROR", "parse_ini_file: Could not open '%s': %s\n", path,
strerror(errno));
return -1;
}
memset(&locale->meta, 0, sizeof(locale->meta));
locale->keys = NULL;
locale->key_count = 0;
locale->key_capacity = 0;
IniSection current_section = SECTION_NONE;
char line[BUFFER_SIZE];
while (fgets(line, sizeof(line), fp) != NULL) {
char *trimmed = trim(line);
if (*trimmed == '\0' || *trimmed == ';' || *trimmed == '#') {
continue;
}
if (*trimmed == '[') {
char *close = strchr(trimmed, ']');
if (close == NULL)
continue;
*close = '\0';
char *section_name = trimmed + 1;
section_name = trim(section_name);
if (strcmp(section_name, "Meta") == 0) {
current_section = SECTION_META;
} else if (strcmp(section_name, "Keys") == 0) {
current_section = SECTION_KEYS;
} else {
current_section = SECTION_NONE;
}
continue;
}
char *eq = strchr(trimmed, '=');
if (eq == NULL)
continue;
*eq = '\0';
char *key = trim(trimmed);
char *value = trim(eq + 1);
unquote_value(value);
if (current_section == SECTION_META) {
if (strcmp(key, "Id") == 0) {
strncpy(locale->meta.id, value, MAX_LOCALE_ID_LEN - 1);
locale->meta.id[MAX_LOCALE_ID_LEN - 1] = '\0';
} else if (strcmp(key, "Name") == 0) {
strncpy(locale->meta.name, value, MAX_VALUE_LEN - 1);
locale->meta.name[MAX_VALUE_LEN - 1] = '\0';
} else if (strcmp(key, "Direction") == 0) {
strncpy(locale->meta.direction, value,
sizeof(locale->meta.direction) - 1);
locale->meta.direction[sizeof(locale->meta.direction) - 1] = '\0';
}
} else if (current_section == SECTION_KEYS) {
if (locale->key_count >= locale->key_capacity) {
int new_cap =
safe_grow_capacity(locale->key_capacity, MAX_LOCALE_KEYS_HARD);
if (new_cap <= locale->key_count) {
beaker_log("WARN",
"parse_ini_file: Hard key limit (%d) reached in '%s', "
"skipping key '%s'.\n",
MAX_LOCALE_KEYS_HARD, path, key);
continue;
}
LocaleKV *new_keys =
realloc(locale->keys, (size_t)new_cap * sizeof(LocaleKV));
if (new_keys == NULL) {
beaker_log(
"ERROR",
"parse_ini_file: Memory allocation failed for keys in '%s'.\n",
path);
continue;
}
locale->keys = new_keys;
locale->key_capacity = new_cap;
}
LocaleKV *kv = &locale->keys[locale->key_count];
strncpy(kv->key, key, MAX_KEY_LEN - 1);
kv->key[MAX_KEY_LEN - 1] = '\0';
strncpy(kv->value, value, MAX_LOCALE_VALUE_LEN - 1);
kv->value[MAX_LOCALE_VALUE_LEN - 1] = '\0';
locale->key_count++;
}
}
fclose(fp);
if (locale->meta.id[0] == '\0') {
beaker_log("WARN", "parse_ini_file: No Id in [Meta] section of '%s'.\n",
path);
return -1;
}
return 0;
}
int beaker_load_locales(void) {
locale_count = 0;
DIR *dir = opendir(LOCALES_DIR);
if (dir == NULL) {
beaker_log("ERROR",
"beaker_load_locales: Could not open directory '%s': %s\n",
LOCALES_DIR, strerror(errno));
return 0;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
const char *name = entry->d_name;
size_t name_len = strlen(name);
if (name_len < 5 || strcmp(name + name_len - 4, ".ini") != 0) {
continue;
}
if (locale_count >= locale_capacity) {
int new_cap = safe_grow_capacity(locale_capacity, MAX_LOCALES_HARD);
if (new_cap <= locale_count) {
beaker_log("WARN",
"beaker_load_locales: Hard locale limit (%d) reached, "
"skipping '%s'.\n",
MAX_LOCALES_HARD, name);
break;
}
Locale *new_locales = realloc(locales, (size_t)new_cap * sizeof(Locale));
if (new_locales == NULL) {
beaker_log(
"ERROR",
"beaker_load_locales: Memory allocation failed for locales.\n");
break;
}
locales = new_locales;
locale_capacity = new_cap;
}
char path[512];
snprintf(path, sizeof(path), "%s%s", LOCALES_DIR, name);
Locale *locale = &locales[locale_count];
if (parse_ini_file(path, locale) == 0) {
beaker_log("DEBUG", "beaker_load_locales: Loaded locale '%s' from '%s'",
locale->meta.id, name);
locale_count++;
} else {
free(locale->keys);
locale->keys = NULL;
locale->key_count = 0;
locale->key_capacity = 0;
}
}
closedir(dir);
return locale_count;
}
void beaker_set_locale(TemplateContext *ctx, const char *locale_id) {
if (ctx == NULL || locale_id == NULL) {
beaker_log("ERROR",
"beaker_set_locale: Invalid NULL input (ctx or locale_id).\n");
return;
}
context_set(ctx, "__locale", locale_id);
const LocaleMeta *meta = beaker_get_locale_meta(locale_id);
if (meta != NULL) {
context_set(ctx, "__locale_id", meta->id);
context_set(ctx, "__locale_name", meta->name);
context_set(ctx, "__locale_direction", meta->direction);
} else {
beaker_log("WARN",
"beaker_set_locale: Locale '%s' not found. Context vars "
"not set.\n",
locale_id);
}
}
int beaker_get_all_locales(LocaleInfo *out, int max_count) {
if (out == NULL || max_count <= 0) {
return 0;
}
int count = (locale_count < max_count) ? locale_count : max_count;
for (int i = 0; i < count; i++) {
out[i].meta = locales[i].meta;
}
return count;
}
const LocaleMeta *beaker_get_locale_meta(const char *locale_id) {
if (locale_id == NULL) {
return NULL;
}
for (int i = 0; i < locale_count; i++) {
if (strcmp(locales[i].meta.id, locale_id) == 0) {
return &locales[i].meta;
}
}
return NULL;
}
const char *beaker_get_locale_value(const char *locale_id, const char *key) {
if (locale_id == NULL || key == NULL) {
return NULL;
}
for (int i = 0; i < locale_count; i++) {
if (strcmp(locales[i].meta.id, locale_id) == 0) {
for (int j = 0; j < locales[i].key_count; j++) {
if (strcmp(locales[i].keys[j].key, key) == 0) {
return locales[i].keys[j].value;
}
}
return NULL;
}
}
return NULL;
}
void beaker_free_locales(void) {
for (int i = 0; i < locale_count; i++) {
free(locales[i].keys);
locales[i].keys = NULL;
locales[i].key_count = 0;
locales[i].key_capacity = 0;
}
free(locales);
locales = NULL;
locale_count = 0;
locale_capacity = 0;
}
+117
View File
@@ -0,0 +1,117 @@
#include "beaker_globals.h"
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
enum {
LOG_LEVEL_DEBUG,
LOG_LEVEL_INFO,
LOG_LEVEL_WARN,
LOG_LEVEL_ERROR,
LOG_LEVEL_NONE
};
static int configured_log_level(void) {
const char *level = getenv("BEAKER_LOG_LEVEL");
if (level == NULL || strcasecmp(level, "INFO") == 0)
return LOG_LEVEL_INFO;
if (strcasecmp(level, "DEBUG") == 0)
return LOG_LEVEL_DEBUG;
if (strcasecmp(level, "WARN") == 0 || strcasecmp(level, "WARNING") == 0)
return LOG_LEVEL_WARN;
if (strcasecmp(level, "ERROR") == 0)
return LOG_LEVEL_ERROR;
if (strcasecmp(level, "NONE") == 0 || strcasecmp(level, "OFF") == 0)
return LOG_LEVEL_NONE;
return LOG_LEVEL_INFO;
}
static int message_log_level(const char *level) {
if (strcasecmp(level, "DEBUG") == 0)
return LOG_LEVEL_DEBUG;
if (strcasecmp(level, "INFO") == 0 || strcasecmp(level, "ACCESS") == 0)
return LOG_LEVEL_INFO;
if (strcasecmp(level, "WARN") == 0 || strcasecmp(level, "WARNING") == 0 ||
strcasecmp(level, "SECURITY") == 0)
return LOG_LEVEL_WARN;
return LOG_LEVEL_ERROR;
}
static void log_timestamp(char *buffer, size_t size) {
struct timespec now;
struct tm local;
clock_gettime(CLOCK_REALTIME, &now);
localtime_r(&now.tv_sec, &local);
strftime(buffer, size, "%Y-%m-%dT%H:%M:%S%z", &local);
}
static void log_safe_value(char *output, const char *input, size_t size) {
size_t i;
for (i = 0; i + 1 < size && input[i] != '\0'; i++) {
unsigned char c = input[i];
output[i] = c <= ' ' || c == 127 || c == '"' || c == '\\' ? '_' : c;
}
output[i] = '\0';
}
void beaker_log(const char *level, const char *format, ...) {
char message[BUFFER_SIZE];
char timestamp[32];
va_list args;
if (message_log_level(level) < configured_log_level())
return;
va_start(args, format);
vsnprintf(message, sizeof(message), format, args);
va_end(args);
size_t length = strlen(message);
while (length > 0 &&
(message[length - 1] == '\n' || message[length - 1] == '\r'))
message[--length] = '\0';
log_timestamp(timestamp, sizeof(timestamp));
flockfile(stderr);
fprintf(stderr, "%s %-6s %s\n", timestamp, level, message);
funlockfile(stderr);
}
void beaker_log_errno_format(const char *level, const char *format, ...) {
char message[BUFFER_SIZE];
int error = errno;
va_list args;
va_start(args, format);
vsnprintf(message, sizeof(message), format, args);
va_end(args);
size_t length = strlen(message);
while (length > 0 &&
(message[length - 1] == '\n' || message[length - 1] == '\r'))
message[--length] = '\0';
if (length > 0 && message[length - 1] == '.')
message[length - 1] = '\0';
beaker_log(level, "%s: %s", message, strerror(error));
}
void beaker_log_errno(const char *message) {
int error = errno;
beaker_log("ERROR", "%s: %s", message, strerror(error));
}
void beaker_log_request(const char *remote_addr, const char *method,
const char *path, int status, size_t response_size,
double duration_ms) {
char safe_method[16];
char safe_path[MAX_PATH_LEN];
log_safe_value(safe_method, method, sizeof(safe_method));
log_safe_value(safe_path, path, sizeof(safe_path));
beaker_log("ACCESS", "%s \"%s %s\" %03d %zu %.3fms", remote_addr, safe_method,
safe_path, status, response_size, duration_ms);
}
+461
View File
@@ -0,0 +1,461 @@
#include "../beaker.h"
#include "beaker_globals.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>
void set_handler(const char *path, RequestHandler handler) {
if (handler_count < MAX_HANDLERS) {
strncpy(handlers[handler_count].path, path, MAX_PATH_LEN - 1);
handlers[handler_count].path[MAX_PATH_LEN - 1] = '\0';
handlers[handler_count].handler = handler;
handler_count++;
} else {
beaker_log("WARN",
"set_handler: Maximum number of handlers reached. Cannot "
"register handler for '%s'.\n",
path);
}
}
const char *get_mime_type(const char *file_path) {
const char *ext = strrchr(file_path, '.');
if (!ext) {
return "application/octet-stream";
}
ext++;
if (strcmp(ext, "html") == 0 || strcmp(ext, "htm") == 0)
return "text/html";
if (strcmp(ext, "css") == 0)
return "text/css";
if (strcmp(ext, "js") == 0)
return "application/javascript";
if (strcmp(ext, "json") == 0)
return "application/json";
if (strcmp(ext, "jpg") == 0 || strcmp(ext, "jpeg") == 0)
return "image/jpeg";
if (strcmp(ext, "png") == 0)
return "image/png";
if (strcmp(ext, "gif") == 0)
return "image/gif";
if (strcmp(ext, "ico") == 0)
return "image/x-icon";
if (strcmp(ext, "svg") == 0)
return "image/svg+xml";
if (strcmp(ext, "pdf") == 0)
return "application/pdf";
if (strcmp(ext, "txt") == 0)
return "text/plain";
return "application/octet-stream";
}
static int hex_value(unsigned char c) {
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}
static int url_decode(char *dst, size_t dst_size, const char *src,
size_t src_len, bool plus_as_space) {
size_t src_index = 0;
size_t dst_index = 0;
if (dst == NULL || dst_size == 0 || src == NULL)
return -1;
while (src_index < src_len) {
unsigned char decoded;
if (src[src_index] == '%') {
if (src_index + 2 >= src_len) {
beaker_log("SECURITY", "url_decode: Incomplete percent encoding.");
return -1;
}
int high = hex_value((unsigned char)src[src_index + 1]);
int low = hex_value((unsigned char)src[src_index + 2]);
if (high < 0 || low < 0) {
beaker_log("SECURITY", "url_decode: Invalid percent encoding.");
return -1;
}
decoded = (unsigned char)((high << 4) | low);
src_index += 3;
} else {
decoded = (unsigned char)src[src_index++];
if (plus_as_space && decoded == '+')
decoded = ' ';
}
if (decoded == 0 || decoded < 0x20 || decoded == 0x7f) {
beaker_log("SECURITY", "url_decode: Rejected control character.");
return -1;
}
if (dst_index + 1 >= dst_size) {
beaker_log("SECURITY", "url_decode: Decoded value is too long.");
return -1;
}
dst[dst_index++] = (char)decoded;
}
dst[dst_index] = '\0';
return 0;
}
static int canonicalize_path(char *canonical, const char *path,
size_t max_len) {
if (canonical == NULL || path == NULL || max_len < 2 || path[0] != '/') {
return -1;
}
size_t output_len = 1;
canonical[0] = '/';
canonical[1] = '\0';
const char *cursor = path + 1;
while (*cursor != '\0') {
while (*cursor == '/')
cursor++;
if (*cursor == '\0')
break;
const char *component = cursor;
while (*cursor != '\0' && *cursor != '/')
cursor++;
size_t component_len = (size_t)(cursor - component);
if (component_len == 1 && component[0] == '.') {
continue;
}
if (component_len == 2 && component[0] == '.' && component[1] == '.') {
if (output_len == 1) {
beaker_log("SECURITY", "canonicalize_path: Path escapes root.");
return -1;
}
while (output_len > 1 && canonical[output_len - 1] != '/')
output_len--;
if (output_len > 1)
output_len--;
canonical[output_len] = '\0';
continue;
}
for (size_t i = 0; i < component_len; i++) {
unsigned char c = (unsigned char)component[i];
if (c == '\\' || c < 0x20 || c == 0x7f) {
beaker_log("SECURITY",
"canonicalize_path: Rejected unsafe path character.");
return -1;
}
}
size_t separator_len = output_len > 1 ? 1 : 0;
if (output_len + separator_len + component_len >= max_len) {
beaker_log("SECURITY", "canonicalize_path: Path is too long.");
return -1;
}
if (separator_len != 0)
canonical[output_len++] = '/';
memcpy(canonical + output_len, component, component_len);
output_len += component_len;
canonical[output_len] = '\0';
}
return 0;
}
static int extract_request_target(const char *request_line, char *target,
size_t target_size) {
if (request_line == NULL || target == NULL || target_size == 0)
return -1;
const char *first_space = strchr(request_line, ' ');
if (first_space == NULL || first_space == request_line ||
first_space[1] == ' ')
return -1;
const char *second_space = strchr(first_space + 1, ' ');
if (second_space == NULL || second_space == first_space + 1 ||
second_space[1] == '\0' || strchr(second_space + 1, ' ') != NULL ||
strchr(request_line, '\t') != NULL) {
return -1;
}
size_t method_len = (size_t)(first_space - request_line);
if (method_len >= 16)
return -1;
char method[16];
memcpy(method, request_line, method_len);
method[method_len] = '\0';
if (!beaker_is_valid_http_token(method))
return -1;
size_t version_len = strlen(second_space + 1);
if (version_len == 0 || version_len >= 16 ||
!beaker_is_valid_header_value(second_space + 1)) {
return -1;
}
size_t target_len = (size_t)(second_space - (first_space + 1));
if (target_len >= target_size)
return -1;
memcpy(target, first_space + 1, target_len);
target[target_len] = '\0';
return 0;
}
static int parse_query_params(const char *query, UrlParams *params) {
const char *cursor = query;
while (*cursor != '\0') {
const char *pair_end = strchr(cursor, '&');
if (pair_end == NULL)
pair_end = cursor + strlen(cursor);
const char *equals = memchr(cursor, '=', (size_t)(pair_end - cursor));
if (equals != NULL) {
if (params->count >= MAX_URL_PARAMS) {
beaker_log("SECURITY", "parse_query_params: Too many parameters.");
return -1;
}
UrlParam *param = &params->params[params->count];
if (url_decode(param->key, sizeof(param->key), cursor,
(size_t)(equals - cursor), true) != 0 ||
url_decode(param->value, sizeof(param->value), equals + 1,
(size_t)(pair_end - (equals + 1)), true) != 0) {
return -1;
}
params->count++;
}
if (*pair_end == '\0')
break;
cursor = pair_end + 1;
}
return 0;
}
char *parse_request_url(const char *request_line, UrlParams *params) {
if (params == NULL)
return NULL;
params->count = 0;
char raw_target[MAX_PATH_LEN];
if (extract_request_target(request_line, raw_target, sizeof(raw_target)) !=
0) {
beaker_log("ERROR", "parse_request_url: Malformed request line.");
return NULL;
}
char *query_start = strchr(raw_target, '?');
size_t raw_path_len = query_start == NULL
? strlen(raw_target)
: (size_t)(query_start - raw_target);
if (raw_path_len == 0 || raw_target[0] != '/') {
beaker_log("SECURITY", "parse_request_url: Invalid request target.");
return NULL;
}
char decoded_path[MAX_PATH_LEN];
if (url_decode(decoded_path, sizeof(decoded_path), raw_target, raw_path_len,
false) != 0) {
return NULL;
}
char canonical_path[MAX_PATH_LEN];
if (canonicalize_path(canonical_path, decoded_path, sizeof(canonical_path)) !=
0) {
return NULL;
}
if (query_start != NULL && parse_query_params(query_start + 1, params) != 0) {
params->count = 0;
return NULL;
}
char *final_path = strdup(canonical_path);
if (final_path == NULL)
beaker_log_errno("parse_request_url: Failed to allocate result path");
return final_path;
}
bool serve_static_file_with_mime(const char *request_path_relative_to_static,
const char *mime_type) {
char full_static_path[MAX_PATH_LEN];
if (request_path_relative_to_static == NULL ||
strlen(request_path_relative_to_static) == 0) {
beaker_log("ERROR", "serve_static_file_with_mime: Empty path provided\n");
return false;
}
if (strstr(request_path_relative_to_static, "..") != NULL ||
strstr(request_path_relative_to_static, "//") != NULL ||
request_path_relative_to_static[0] == '/') {
beaker_log("SECURITY", "Attempted directory traversal: %s\n",
request_path_relative_to_static);
send_status("403 Forbidden");
return true;
}
snprintf(full_static_path, sizeof(full_static_path), "%s%s", STATIC_DIR,
request_path_relative_to_static);
FILE *fp = fopen(full_static_path, "rb");
if (fp == NULL) {
beaker_log("ERROR",
"serve_static_file_with_mime: File '%s' not found or could not "
"be opened. %s\n",
full_static_path, strerror(errno));
return false;
}
struct stat st;
if (fstat(fileno(fp), &st) < 0) {
beaker_log_errno_format(
"ERROR", "serve_static_file_with_mime: fstat failed for '%s'.\n",
full_static_path);
fclose(fp);
send_status("500 Internal Server Error");
return true;
}
long file_size = st.st_size;
current_response_status = 200;
current_response_size = file_size;
if (!mime_type || mime_type[0] == '\0') {
mime_type = get_mime_type(full_static_path);
}
if (!beaker_is_valid_header_value(mime_type) ||
strlen(mime_type) >= MAX_VALUE_LEN) {
beaker_log("SECURITY",
"serve_static_file_with_mime: Rejected invalid MIME type.");
fclose(fp);
send_status("500 Internal Server Error");
return true;
}
char http_header[BUFFER_SIZE];
int header_length = snprintf(http_header, sizeof(http_header),
"HTTP/1.1 200 OK\r\n"
"Content-Type: %s\r\n"
"Content-Length: %ld\r\n"
"Connection: close\r\n"
"\r\n",
mime_type, file_size);
if (header_length < 0 || (size_t)header_length >= sizeof(http_header)) {
beaker_log("ERROR",
"serve_static_file_with_mime: Failed to construct header.");
fclose(fp);
send_status("500 Internal Server Error");
return true;
}
if (beaker_send_all(current_client_socket, http_header, strlen(http_header)) <
0) {
beaker_log_errno_format(
"ERROR",
"serve_static_file_with_mime: Failed to send header for '%s'.\n",
full_static_path);
fclose(fp);
return true;
}
char file_buffer[BUFFER_SIZE];
size_t bytes_read;
bool send_error = false;
while (!send_error && !feof(fp) && !ferror(fp) &&
(bytes_read = fread(file_buffer, 1, sizeof(file_buffer), fp)) > 0) {
if (beaker_send_all(current_client_socket, file_buffer, bytes_read) < 0) {
beaker_log_errno_format(
"ERROR",
"serve_static_file_with_mime: Failed to send content for '%s'.\n",
full_static_path);
send_error = true;
}
}
if (ferror(fp)) {
beaker_log_errno_format(
"ERROR", "serve_static_file_with_mime: Failed to read '%s'.\n",
full_static_path);
fclose(fp);
return true;
}
fclose(fp);
return true;
}
bool serve_static_file(const char *request_path_relative_to_static) {
return serve_static_file_with_mime(request_path_relative_to_static, NULL);
}
bool serve_data(const char *data, size_t size, const char *mime_type) {
if (current_client_socket == -1) {
beaker_log("ERROR",
"serve_data: No client socket set. Cannot send data.\n");
return false;
}
if (data == NULL || size == 0) {
beaker_log("ERROR", "serve_data: Invalid data or size.\n");
return false;
}
if (mime_type == NULL || mime_type[0] == '\0' ||
!beaker_is_valid_header_value(mime_type) ||
strlen(mime_type) >= MAX_VALUE_LEN) {
beaker_log("SECURITY", "serve_data: Rejected invalid MIME type.");
send_status("500 Internal Server Error");
return false;
}
char http_header[BUFFER_SIZE];
current_response_status = 200;
current_response_size = size;
int header_length = snprintf(http_header, sizeof(http_header),
"HTTP/1.1 200 OK\r\n"
"Content-Type: %s\r\n"
"Content-Length: %zu\r\n"
"Connection: close\r\n"
"\r\n",
mime_type, size);
if (header_length < 0 || (size_t)header_length >= sizeof(http_header)) {
beaker_log("ERROR", "serve_data: Failed to construct header.");
send_status("500 Internal Server Error");
return false;
}
if (beaker_send_all(current_client_socket, http_header, strlen(http_header)) <
0) {
beaker_log_errno_format("ERROR", "serve_data: Failed to send header.\n");
return false;
}
if (beaker_send_all(current_client_socket, data, size) < 0) {
beaker_log_errno_format("ERROR", "serve_data: Failed to send content.\n");
return false;
}
return true;
}
+580
View File
@@ -0,0 +1,580 @@
#include "../beaker.h"
#include "beaker_globals.h"
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#define MAX_PENDING_CONNECTIONS 128
static volatile sig_atomic_t g_shutdown_requested = 0;
static bool validate_request_headers(const char *request_buffer);
static void signal_handler(int sig) {
(void)sig;
g_shutdown_requested = 1;
}
typedef struct {
_Atomic(size_t) sequence;
int socket;
} WorkSlot;
typedef struct {
_Atomic(size_t) head;
_Atomic(size_t) tail;
_Atomic(int) shutdown;
WorkSlot slots[MAX_PENDING_CONNECTIONS];
pthread_mutex_t mutex;
pthread_cond_t cond;
} WorkQueue;
static WorkQueue g_work_queue;
static void work_queue_init(WorkQueue *queue) {
atomic_store(&queue->head, 0);
atomic_store(&queue->tail, 0);
atomic_store(&queue->shutdown, 0);
for (int i = 0; i < MAX_PENDING_CONNECTIONS; i++) {
atomic_store(&queue->slots[i].sequence, (size_t)i);
}
pthread_mutex_init(&queue->mutex, NULL);
pthread_cond_init(&queue->cond, NULL);
}
static void work_queue_destroy(WorkQueue *queue) {
pthread_mutex_destroy(&queue->mutex);
pthread_cond_destroy(&queue->cond);
}
static int work_queue_push(WorkQueue *queue, int client_socket) {
size_t tail = atomic_load(&queue->tail);
for (;;) {
WorkSlot *slot = &queue->slots[tail % MAX_PENDING_CONNECTIONS];
size_t seq = atomic_load(&slot->sequence);
intptr_t diff = (intptr_t)seq - (intptr_t)tail;
if (diff == 0) {
if (atomic_compare_exchange_weak(&queue->tail, &tail, tail + 1)) {
slot->socket = client_socket;
atomic_store(&slot->sequence, tail + 1);
pthread_cond_signal(&queue->cond);
return 0;
}
} else if (diff < 0) {
return -1;
} else {
tail = atomic_load(&queue->tail);
}
}
}
static int work_queue_pop(WorkQueue *queue) {
size_t head = atomic_load(&queue->head);
for (;;) {
if (atomic_load(&queue->shutdown))
return -1;
WorkSlot *slot = &queue->slots[head % MAX_PENDING_CONNECTIONS];
size_t seq = atomic_load(&slot->sequence);
intptr_t diff = (intptr_t)seq - (intptr_t)(head + 1);
if (diff == 0) {
if (atomic_compare_exchange_weak(&queue->head, &head, head + 1)) {
int fd = slot->socket;
atomic_store(&slot->sequence, head + MAX_PENDING_CONNECTIONS);
return fd;
}
} else if (diff < 0) {
pthread_mutex_lock(&queue->mutex);
if (!atomic_load(&queue->shutdown) && atomic_load(&queue->head) == head) {
pthread_cond_wait(&queue->cond, &queue->mutex);
}
pthread_mutex_unlock(&queue->mutex);
head = atomic_load(&queue->head);
} else {
head = atomic_load(&queue->head);
}
}
}
static int get_optimal_thread_count(void) {
long cores = sysconf(_SC_NPROCESSORS_ONLN);
if (cores < 1)
cores = 1;
return (int)(cores * 2);
}
void handle_client_connection(int new_socket);
static void *worker_thread(void *arg) {
(void)arg;
while (1) {
int client_socket = work_queue_pop(&g_work_queue);
if (client_socket < 0) {
break;
}
handle_client_connection(client_socket);
}
return NULL;
}
static int initialize_server_socket(const char *ip, int port,
int *server_fd_out,
struct sockaddr_in *address_out) {
if ((*server_fd_out = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
beaker_log_errno_format(
"ERROR", "initialize_server_socket: Failed to create socket.\n");
return -1;
}
int opt = 1;
if (setsockopt(*server_fd_out, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
beaker_log_errno("setsockopt SO_REUSEADDR failed");
}
// Needed for FreeBSD support. On macOS this allows multiple processes to
// bind the same TCP port, which is surprising for a single-instance server.
#if defined(__FreeBSD__) && defined(SO_REUSEPORT)
if (setsockopt(*server_fd_out, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt))) {
beaker_log_errno_format(
"ERROR", "initialize_server_socket: Failed to set SO_REUSEPORT.\n");
close(*server_fd_out);
return -1;
}
#endif
address_out->sin_family = AF_INET;
address_out->sin_addr.s_addr = inet_addr(ip);
address_out->sin_port = htons(port);
if (bind(*server_fd_out, (struct sockaddr *)address_out,
sizeof(*address_out)) < 0) {
beaker_log_errno_format(
"ERROR", "initialize_server_socket: Failed to bind socket to %s:%d.\n",
ip, port);
close(*server_fd_out);
return -1;
}
if (listen(*server_fd_out, 10) < 0) {
beaker_log_errno_format(
"ERROR", "initialize_server_socket: Failed to listen on socket.\n");
close(*server_fd_out);
return -1;
}
int flags = fcntl(*server_fd_out, F_GETFL, 0);
if (flags < 0 || fcntl(*server_fd_out, F_SETFL, flags | O_NONBLOCK) < 0) {
beaker_log_errno("fcntl O_NONBLOCK failed");
close(*server_fd_out);
return -1;
}
beaker_log("INFO", "listening on %s:%d", ip, port);
return 0;
}
static void finish_client_connection(int socket, char *requested_path,
const char *method, const char *path,
const struct timespec *started_at) {
struct timespec finished_at;
clock_gettime(CLOCK_MONOTONIC, &finished_at);
double duration_ms = (finished_at.tv_sec - started_at->tv_sec) * 1000.0 +
(finished_at.tv_nsec - started_at->tv_nsec) / 1000000.0;
beaker_log_request(current_request_info.remote_addr, method, path,
current_response_status, current_response_size,
duration_ms);
beaker_clear_response_cookies();
free(requested_path);
close(socket);
current_client_socket = -1;
}
void handle_client_connection(int new_socket) {
current_client_socket = new_socket;
char buffer[BUFFER_SIZE] = {0};
char method[16] = "-";
char log_path[MAX_PATH_LEN] = "-";
char *requested_path = NULL;
struct timespec started_at;
clock_gettime(CLOCK_MONOTONIC, &started_at);
beaker_clear_response_cookies();
current_response_status = 0;
current_response_size = 0;
beaker_reset_write_deadline();
memset(&current_request_info, 0, sizeof(RequestInfo));
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
if (getpeername(new_socket, (struct sockaddr *)&client_addr, &client_len) !=
0 ||
inet_ntop(AF_INET, &client_addr.sin_addr,
current_request_info.remote_addr,
sizeof(current_request_info.remote_addr)) == NULL) {
strcpy(current_request_info.remote_addr, "-");
}
size_t bytes_read = 0;
BeakerRequestReadResult read_result = beaker_read_request_headers(
new_socket, buffer, sizeof(buffer), &bytes_read);
if (read_result == BEAKER_REQUEST_READ_TIMEOUT) {
beaker_log("WARN", "handle_client_connection: Request header timed out.\n");
send_status("408 Request Timeout");
finish_client_connection(new_socket, requested_path, method, log_path,
&started_at);
return;
}
if (read_result == BEAKER_REQUEST_READ_TOO_LARGE) {
beaker_log("WARN",
"handle_client_connection: Request headers too large.\n");
send_status("431 Request Header Fields Too Large");
finish_client_connection(new_socket, requested_path, method, log_path,
&started_at);
return;
}
if (read_result == BEAKER_REQUEST_READ_CLOSED) {
if (bytes_read > 0) {
send_status("400 Bad Request");
}
finish_client_connection(new_socket, requested_path, method, log_path,
&started_at);
return;
}
if (read_result == BEAKER_REQUEST_READ_ERROR) {
beaker_log_errno_format(
"ERROR",
"handle_client_connection: Failed to read from client socket.\n");
finish_client_connection(new_socket, requested_path, method, log_path,
&started_at);
return;
}
strncpy(current_request_buffer, buffer, BUFFER_SIZE - 1);
current_request_buffer[BUFFER_SIZE - 1] = '\0';
char request_line[MAX_PATH_LEN + 64];
char *first_line_end = strstr(buffer, "\r\n");
if (first_line_end == NULL) {
beaker_log(
"ERROR",
"handle_client_connection: Invalid HTTP request: No CRLF found.\n");
send_status("400 Bad Request");
finish_client_connection(new_socket, requested_path, method, log_path,
&started_at);
return;
}
if (!validate_request_headers(buffer)) {
beaker_log("SECURITY",
"handle_client_connection: Rejected malformed headers.");
send_status("400 Bad Request");
finish_client_connection(new_socket, requested_path, method, log_path,
&started_at);
return;
}
size_t request_line_len = first_line_end - buffer;
if (request_line_len >= sizeof(request_line)) {
beaker_log("ERROR", "handle_client_connection: Request line too long.\n");
send_status("400 Bad Request");
finish_client_connection(new_socket, requested_path, method, log_path,
&started_at);
return;
}
strncpy(request_line, buffer, request_line_len);
request_line[request_line_len] = '\0';
sscanf(request_line, "%15s %255s", method, log_path);
UrlParams request_params;
requested_path = parse_request_url(request_line, &request_params);
if (requested_path == NULL) {
beaker_log("ERROR", "handle_client_connection: Could not parse request "
"path. Sending 400 Bad Request.\n");
send_status("400 Bad Request");
finish_client_connection(new_socket, requested_path, method, log_path,
&started_at);
return;
}
strncpy(log_path, requested_path, sizeof(log_path) - 1);
log_path[sizeof(log_path) - 1] = '\0';
bool handled = false;
if (strncmp(requested_path, "/static/", strlen("/static/")) == 0) {
if (serve_static_file(requested_path + strlen("/static/"))) {
handled = true;
}
}
if (!handled) {
int best_match_handler_index = -1;
size_t best_match_len = 0;
for (int i = 0; i < handler_count; i++) {
size_t handler_path_len = strlen(handlers[i].path);
if (strncmp(requested_path, handlers[i].path, handler_path_len) == 0) {
if (handler_path_len == strlen(requested_path) ||
requested_path[handler_path_len] == '/') {
if (handler_path_len > best_match_len) {
best_match_len = handler_path_len;
best_match_handler_index = i;
}
}
}
}
if (best_match_handler_index != -1) {
handlers[best_match_handler_index].handler(&request_params);
handled = true;
}
}
if (!handled) {
const char *not_found_html = "<h1>404 Not Found</h1><p>The requested URL "
"was not located on this server.</p>";
char not_found_response[BUFFER_SIZE];
snprintf(not_found_response, sizeof(not_found_response),
"HTTP/1.1 404 Not Found\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Content-Length: %zu\r\n"
"Connection: close\r\n"
"\r\n%s",
strlen(not_found_html), not_found_html);
if (beaker_send_all(new_socket, not_found_response,
strlen(not_found_response)) < 0) {
beaker_log_errno("Failed to send 404 response");
}
current_response_status = 404;
current_response_size = strlen(not_found_html);
}
finish_client_connection(new_socket, requested_path, method, log_path,
&started_at);
}
int beaker_run(const char *ip, int port) {
beaker_run_with_threads(ip, port, 0);
return 0;
}
void beaker_run_with_threads(const char *ip, int port, int num_workers) {
int server_fd;
struct sockaddr_in address;
int addrlen = sizeof(address);
g_shutdown_requested = 0;
struct sigaction sa;
sa.sa_handler = signal_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
if (num_workers <= 0) {
num_workers = get_optimal_thread_count();
}
if (initialize_server_socket(ip, port, &server_fd, &address) != 0) {
return;
}
work_queue_init(&g_work_queue);
pthread_t threads[num_workers];
for (int i = 0; i < num_workers; i++) {
pthread_create(&threads[i], NULL, worker_thread, NULL);
}
beaker_log("DEBUG", "started %d worker threads", num_workers);
struct pollfd pfd = {.fd = server_fd, .events = POLLIN};
while (!g_shutdown_requested) {
int ret = poll(&pfd, 1, 1000);
if (ret < 0) {
if (errno == EINTR)
continue;
beaker_log_errno("poll failed");
break;
}
if (ret == 0)
continue;
int new_socket;
while ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t *)&addrlen)) >= 0) {
if (beaker_configure_client_socket(new_socket) < 0) {
beaker_log_errno("failed to configure client socket");
close(new_socket);
continue;
}
if (work_queue_push(&g_work_queue, new_socket) < 0) {
beaker_log("WARN", "work queue full; rejecting connection");
const char *busy_response =
"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n";
beaker_reset_write_deadline();
if (beaker_send_all(new_socket, busy_response, strlen(busy_response)) <
0) {
beaker_log_errno("failed to send busy response");
}
close(new_socket);
}
}
}
beaker_log("INFO", "shutting down");
atomic_store(&g_work_queue.shutdown, 1);
pthread_cond_broadcast(&g_work_queue.cond);
for (int i = 0; i < num_workers; i++) {
pthread_join(threads[i], NULL);
}
work_queue_destroy(&g_work_queue);
close(server_fd);
}
const char *beaker_get_remote_addr(void) {
return current_request_info.remote_addr;
}
static __thread char g_header_value[MAX_VALUE_LEN];
static bool is_valid_request_header_value(const char *start, const char *end) {
for (const char *cursor = start; cursor < end; cursor++) {
unsigned char c = (unsigned char)*cursor;
if ((c < 0x20 && c != '\t') || c == 0x7f)
return false;
}
return true;
}
static bool validate_request_headers(const char *request_buffer) {
if (request_buffer == NULL)
return false;
const char *request_line_end = strstr(request_buffer, "\r\n");
if (request_line_end == NULL)
return false;
const char *cursor = request_line_end + 2;
int host_count = 0;
while (true) {
const char *line_end = strstr(cursor, "\r\n");
if (line_end == NULL)
return false;
if (line_end == cursor)
return host_count <= 1;
if (*cursor == ' ' || *cursor == '\t')
return false;
const char *colon = memchr(cursor, ':', (size_t)(line_end - cursor));
if (colon == NULL || colon == cursor)
return false;
size_t name_len = (size_t)(colon - cursor);
if (!beaker_is_valid_http_token_span(cursor, name_len) ||
!is_valid_request_header_value(colon + 1, line_end)) {
return false;
}
if (name_len == strlen("Host") &&
strncasecmp(cursor, "Host", name_len) == 0 && ++host_count > 1) {
return false;
}
cursor = line_end + 2;
}
}
const char *beaker_get_header(const char *name) {
g_header_value[0] = '\0';
if (!beaker_is_valid_http_token(name))
return g_header_value;
size_t requested_name_len = strlen(name);
const char *request_line_end = strstr(current_request_buffer, "\r\n");
if (request_line_end == NULL)
return g_header_value;
const char *cursor = request_line_end + 2;
bool found = false;
while (true) {
const char *line_end = strstr(cursor, "\r\n");
if (line_end == NULL || line_end == cursor)
break;
if (*cursor == ' ' || *cursor == '\t')
return g_header_value;
const char *colon = memchr(cursor, ':', (size_t)(line_end - cursor));
if (colon == NULL || colon == cursor)
return g_header_value;
size_t header_name_len = (size_t)(colon - cursor);
if (header_name_len == requested_name_len &&
strncasecmp(cursor, name, requested_name_len) == 0) {
if (found) {
beaker_log("SECURITY",
"beaker_get_header: Rejected duplicate header value.");
g_header_value[0] = '\0';
return g_header_value;
}
const char *value_start = colon + 1;
while (value_start < line_end &&
(*value_start == ' ' || *value_start == '\t')) {
value_start++;
}
const char *value_end = line_end;
while (value_end > value_start &&
(value_end[-1] == ' ' || value_end[-1] == '\t')) {
value_end--;
}
size_t value_len = (size_t)(value_end - value_start);
if (value_len >= sizeof(g_header_value) ||
!is_valid_request_header_value(value_start, value_end)) {
beaker_log("SECURITY",
"beaker_get_header: Rejected invalid header value.");
g_header_value[0] = '\0';
return g_header_value;
}
memcpy(g_header_value, value_start, value_len);
g_header_value[value_len] = '\0';
found = true;
}
cursor = line_end + 2;
}
return g_header_value;
}
void beaker_set_request_buffer(const char *buffer) {
if (buffer == NULL)
return;
strncpy(current_request_buffer, buffer, BUFFER_SIZE - 1);
current_request_buffer[BUFFER_SIZE - 1] = '\0';
}
+1487
View File
File diff suppressed because it is too large Load Diff