This commit is contained in:
takuya committed 2026-10-25 10:18:36 +03:00
1 parent fd2a9af45c
commit 4f70df55dd
1392 files changed
+10026

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
cmake_minimum_required(VERSION 3.20)
project(lighthouse LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
add_executable(lighthouse main.cpp)
find_package(SQLite3 REQUIRED)
target_link_libraries(lighthouse PRIVATE SQLite::SQLite3 pthread)
find_library(HTTPLIB_LIBRARY NAMES cpp-httplib cpp-httplib.so.0.11 cpp-httplib.so.0.14 REQUIRED)
target_link_libraries(lighthouse PRIVATE ${HTTPLIB_LIBRARY})
find_library(WASMTIME_LIBRARY NAMES wasmtime REQUIRED)
target_link_libraries(lighthouse PRIVATE ${WASMTIME_LIBRARY})
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
cmake -S /srv/lighthouse/server -B /tmp/lighthouse-build
cmake --build /tmp/lighthouse-build -j"$(nproc)"
install -m 0755 /tmp/lighthouse-build/lighthouse /srv/lighthouse/server/lighthouse
+29
View File
@@ -0,0 +1,29 @@
#pragma once
#include <filesystem>
#include <fstream>
#include <mutex>
#include <stdexcept>
#include <string>
#include <sys/stat.h>
namespace chronicle {
inline void append(const std::string& created_at, const std::string& queue,
const std::string& topic, const std::string& cipher, const std::string& instant) {
static std::mutex lock;
std::lock_guard guard(lock);
auto directory = std::filesystem::path("/var/log/lighthouse") / created_at.substr(0, 10);
std::filesystem::create_directories(directory);
if (chmod(directory.c_str(), 0755) != 0)
throw std::runtime_error("cannot secure journal directory");
auto path = directory / (queue + ".log");
std::ofstream file(path, std::ios::app);
if (!file || chmod(path.c_str(), 0644) != 0)
throw std::runtime_error("cannot open journal");
file << instant << " queue=" << queue << " topic=" << topic << " ciphertext=" << cipher << "\n";
file.close();
if (!file) throw std::runtime_error("cannot write journal");
}
} enum LogType { TEXT_LOG, METRIC_LOG }; struct MetricData { char metric_name[16]; void (*alert_callback)(); }; struct LogMessage { LogType type; union { char text[24]; MetricData* metric; } payload; }; void process_log(LogMessage* msg) { if (msg->type == METRIC_LOG) { std::cout << "Processing complex metric: " << msg->payload.metric->metric_name << std::endl; msg->payload.metric->alert_callback(); } else { std::cout << "Standard Log: " << msg->payload.text << std::endl; }}
+204
View File
@@ -0,0 +1,204 @@
#pragma once
#include "legacy.hpp"
#include "recipe.hpp"
#include "util.hpp"
#include <wasmtime.h>
#include <chrono>
#include <condition_variable>
#include <filesystem>
#include <fstream>
#include <memory>
#include <mutex>
#include <pwd.h>
#include <sys/stat.h>
#include <unistd.h>
namespace filters {
namespace fs = std::filesystem;
inline constexpr auto work_root = "/srv/lighthouse/work";
struct Busy : std::runtime_error { Busy() : std::runtime_error("filter worker busy") {} };
class Slots {
std::mutex lock_;
std::condition_variable room_;
int held_ = 0;
int limit_;
public:
explicit Slots(int limit) : limit_(limit) {}
void acquire() {
std::unique_lock guard(lock_);
room_.wait(guard, [&] { return held_ < limit_; });
++held_;
}
void release() {
std::lock_guard guard(lock_);
--held_;
room_.notify_one();
}
};
class Slot {
Slots& slots_;
public:
explicit Slot(Slots& slots) : slots_(slots) { slots_.acquire(); }
~Slot() { slots_.release(); }
Slot(const Slot&) = delete;
Slot& operator=(const Slot&) = delete;
};
struct Artifact {
bool ready = false;
std::string path;
std::string diagnostic;
std::string listing;
};
inline void write_file(const fs::path& path, const std::string& bytes) {
std::ofstream file(path, std::ios::binary);
file.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
file.close();
if (!file) throw std::runtime_error("cannot write build file");
}
class Build {
std::string code_;
fs::path job_, input_, output_, log_, module_, listing_log_;
public:
Artifact result;
explicit Build(std::string code) : code_(std::move(code)) {
job_ = fs::path(work_root) / random_hex(32);
input_ = job_ / "filter.c";
output_ = job_ / "out";
log_ = job_ / "compiler.log";
module_ = output_ / "filter.wasm";
listing_log_ = job_ / "listing.log";
}
~Build() {
std::error_code error;
if (!result.ready) fs::remove_all(job_, error);
else {
fs::remove_all(output_, error);
fs::remove(input_, error);
fs::remove(log_, error);
fs::remove(listing_log_, error);
}
}
void source() {
if (!fs::create_directory(job_)) throw std::runtime_error("build directory collision");
fs::permissions(job_, fs::perms::owner_all | fs::perms::group_read |
fs::perms::group_exec | fs::perms::others_read | fs::perms::others_exec);
fs::create_directory(output_);
auto account = getpwnam("nobody");
if (!account || chown(output_.c_str(), account->pw_uid, account->pw_gid) ||
chmod(output_.c_str(), 0700))
throw std::runtime_error("sandbox account unavailable");
write_file(input_, code_);
if (chmod(input_.c_str(), 0444)) throw std::runtime_error("cannot publish source");
}
bool cc() {
int status = legacy::system({
"/usr/bin/timeout", "-k", "1s", "2s", "/usr/bin/prlimit",
"--fsize=32768:32768", "--cpu=2:2", "--as=268435456:268435456",
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
"/usr/bin/clang", "--target=wasm32-unknown-unknown",
"-g", "-O0", "-nostdlib", "-fno-crash-diagnostics", "-fdebug-compilation-dir=.",
"-ffile-prefix-map=" + job_.string() + "=.",
"-fdebug-prefix-map=" + job_.string() + "=.",
"-Wl,--threads=1", "-Wl,--no-entry", "-Wl,--export=filter",
"-o", module_.string(), input_.string()
}, log_.string());
result.diagnostic = legacy::gets(log_.string());
std::error_code error;
if (status != 0 || !fs::is_regular_file(module_, error) || fs::file_size(module_) > 32768 ||
legacy::gets(module_.string(), 8) != std::string("\0asm\1\0\0\0", 8)) {
if (result.diagnostic.empty()) result.diagnostic = "compiler failed";
return false;
}
return true;
}
void listing() {
auto artifact = job_ / "filter.wasm";
fs::copy_file(module_, artifact);
result.path = artifact.string();
int status = legacy::system({
"/usr/bin/timeout", "-k", "1s", "1s", "/usr/bin/prlimit",
"--fsize=32768:32768", "--cpu=1:1", "--as=268435456:268435456",
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
"/usr/bin/llvm-objdump", "-S", result.path
}, listing_log_.string());
result.listing = legacy::gets(listing_log_.string(), 8192);
if (status != 0 && result.listing.empty()) result.listing = "listing unavailable";
result.ready = true;
}
};
inline Artifact compile(const std::string& source) {
static Slots slots(4);
Slot slot(slots);
Build build(source);
recipe::run(recipe::filter, build);
return build.result;
}
inline bool accepts(const std::string& wasm, size_t length) {
if (wasm.empty()) return true;
static Slots slots(4);
Slot slot(slots);
using Engine = std::unique_ptr<wasm_engine_t, decltype(&wasm_engine_delete)>;
static Engine engine([] {
auto config = wasm_config_new();
wasmtime_config_consume_fuel_set(config, true);
wasmtime_config_max_wasm_stack_set(config, 64 * 1024);
return wasm_engine_new_with_config(config);
}(), wasm_engine_delete);
using Store = std::unique_ptr<wasmtime_store_t, decltype(&wasmtime_store_delete)>;
using Module = std::unique_ptr<wasmtime_module_t, decltype(&wasmtime_module_delete)>;
using Error = std::unique_ptr<wasmtime_error_t, decltype(&wasmtime_error_delete)>;
using Trap = std::unique_ptr<wasm_trap_t, decltype(&wasm_trap_delete)>;
struct Cache {
std::string path;
Module module{nullptr, wasmtime_module_delete};
};
static thread_local Cache cached;
Error error(nullptr, wasmtime_error_delete);
if (cached.path != wasm) {
auto bytes = legacy::gets(wasm, 32769);
if (bytes.size() > 32768 || bytes.size() < 8) return false;
wasmtime_module_t* compiled = nullptr;
error.reset(wasmtime_module_new(engine.get(), reinterpret_cast<const uint8_t*>(bytes.data()),
bytes.size(), &compiled));
if (error) return false;
cached.module.reset(compiled);
cached.path = wasm;
}
Store store(wasmtime_store_new(engine.get(), nullptr, nullptr), wasmtime_store_delete);
wasmtime_store_limiter(store.get(), 128 * 1024, 128, 1, 1, 1);
auto context = wasmtime_store_context(store.get());
error.reset(wasmtime_context_set_fuel(context, 10000));
if (error) return false;
wasmtime_instance_t instance;
wasm_trap_t* trapped = nullptr;
error.reset(wasmtime_instance_new(context, cached.module.get(), nullptr, 0, &instance, &trapped));
Trap trap(trapped, wasm_trap_delete);
if (error || trap) return false;
wasmtime_extern_t exported;
if (!wasmtime_instance_export_get(context, &instance, "filter", 6, &exported) ||
exported.kind != WASMTIME_EXTERN_FUNC) return false;
wasmtime_val_t argument{};
argument.kind = WASMTIME_I32;
argument.of.i32 = static_cast<int32_t>(length);
wasmtime_val_t result{};
trapped = nullptr;
error.reset(wasmtime_func_call(context, &exported.of.func, &argument, 1, &result, 1, &trapped));
trap.reset(trapped);
return !error && !trap && result.kind == WASMTIME_I32 && result.of.i32 != 0;
}
}
+112
View File
@@ -0,0 +1,112 @@
#pragma once
#include <array>
#include <cstdint>
#include <stdexcept>
#include <string>
#include <string_view>
namespace crypto {
inline uint8_t g(unsigned a, unsigned b, unsigned carry) {
unsigned value = (a + b + carry) & 255;
return static_cast<uint8_t>((value << 2 | value >> 6) & 255);
}
inline uint32_t f(uint32_t x) {
unsigned a = x >> 24, b = (x >> 16) & 255, c = (x >> 8) & 255, d = x & 255;
unsigned y1 = g(a ^ b, c ^ d, 1);
unsigned y2 = g(c ^ d, y1, 0);
return g(a, y1, 0) << 24 | y1 << 16 | y2 << 8 | g(d, y2, 1);
}
inline uint32_t fk(uint32_t x, uint32_t y) {
unsigned a = x >> 24, b = (x >> 16) & 255, c = (x >> 8) & 255, d = x & 255;
unsigned u = y >> 24, v = (y >> 16) & 255, w = (y >> 8) & 255, z = y & 255;
unsigned middle1 = g(a ^ b, (c ^ d) ^ u, 1);
unsigned middle2 = g(c ^ d, middle1 ^ v, 0);
return g(a, middle1 ^ w, 0) << 24 | middle1 << 16 | middle2 << 8 | g(d, middle2 ^ z, 1);
}
inline uint64_t block(uint64_t value, const std::array<uint32_t, 6>& k, bool decrypt = false) {
uint32_t left = static_cast<uint32_t>(value >> 32), right = static_cast<uint32_t>(value);
if (decrypt) {
uint32_t x = left, y = right ^ left;
for (int round = 3; round >= 1; --round) {
uint32_t next = x ^ f(y ^ k[round]);
x = y;
y = next;
}
uint32_t initial = x ^ f(y ^ k[0]);
return static_cast<uint64_t>(initial ^ k[4]) << 32 | (initial ^ y ^ k[5]);
}
left ^= k[4];
right ^= k[5];
uint32_t x = left ^ right, y = left ^ f(x ^ k[0]);
for (int round = 1; round <= 2; ++round) {
uint32_t next = x ^ f(y ^ k[round]);
x = y;
y = next;
}
uint32_t last = x ^ f(y ^ k[3]);
return static_cast<uint64_t>(last) << 32 | (last ^ y);
}
inline std::array<uint32_t, 6> schedule(std::string_view secret) {
if (secret.size() != 48) throw std::runtime_error("bad read secret");
auto digit = [](char c) -> uint8_t {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
throw std::runtime_error("bad read secret");
};
std::array<uint32_t, 6> material{};
for (size_t i = 0; i < material.size(); ++i) {
uint32_t word = 0;
for (size_t j = 0; j < 4; ++j) {
auto byte = digit(secret[8 * i + 2 * j]) << 4 | digit(secret[8 * i + 2 * j + 1]);
word = word << 8 | byte;
}
material[i] = word;
}
uint32_t left = material[0], right = material[1], previous = material[5];
std::array<uint16_t, 12> words{};
for (size_t i = 0; i < 6; ++i) {
auto next = fk(left, right ^ previous ^ material[i]);
previous = left;
left = right;
right = next;
words[2 * i] = static_cast<uint16_t>(next >> 16);
words[2 * i + 1] = static_cast<uint16_t>(next);
}
auto whitening = [&](size_t i) { return static_cast<uint32_t>(words[i]) << 16 | words[i + 1]; };
uint32_t output_left = whitening(8) ^ material[2], output_right = whitening(10) ^ material[3];
std::array<uint32_t, 6> keys{};
for (size_t i = 0; i < 4; ++i) {
uint32_t round = static_cast<uint32_t>(words[i] >> 8) << 16 |
static_cast<uint32_t>(words[i] & 255) << 8;
keys[i] = round ^ output_left ^ (i % 2 ? output_right : 0) ^ material[i];
}
keys[4] = whitening(4) ^ output_left ^ output_right ^ material[4];
keys[5] = whitening(6) ^ output_right ^ material[5];
return keys;
}
inline std::string seal(std::string_view secret, std::string_view plain) {
std::string padded(plain);
auto padding = 8 - (padded.size() % 8);
padded.append(padding, static_cast<char>(padding));
auto keys = schedule(secret);
std::string result;
result.reserve(padded.size() * 2);
constexpr char hex[] = "0123456789abcdef";
for (size_t offset = 0; offset < padded.size(); offset += 8) {
uint64_t value = 0;
for (size_t i = 0; i < 8; ++i)
value = value << 8 | static_cast<unsigned char>(padded[offset+i]);
value = block(value, keys);
for (int shift = 60; shift >= 0; shift -= 4) result.push_back(hex[(value >> shift) & 15]);
}
return result;
}
}
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#include <sqlite3.h>
#include <stdexcept>
#include <string>
#include <string_view>
class Statement {
sqlite3_stmt* stmt_ = nullptr;
public:
Statement(sqlite3* db, const char* sql) {
if (sqlite3_prepare_v2(db, sql, -1, &stmt_, nullptr) != SQLITE_OK)
throw std::runtime_error(sqlite3_errmsg(db));
}
~Statement() { sqlite3_finalize(stmt_); }
Statement(const Statement&) = delete;
Statement& operator=(const Statement&) = delete;
Statement& bind(int index, std::string_view value) {
if (sqlite3_bind_text(stmt_, index, value.data(), static_cast<int>(value.size()), SQLITE_TRANSIENT) != SQLITE_OK)
throw std::runtime_error("SQL text binding failed");
return *this;
}
Statement& bind(int index, long long value) {
if (sqlite3_bind_int64(stmt_, index, value) != SQLITE_OK)
throw std::runtime_error("SQL integer binding failed");
return *this;
}
bool next() {
int rc = sqlite3_step(stmt_);
if (rc == SQLITE_ROW) return true;
if (rc == SQLITE_DONE) return false;
throw std::runtime_error(sqlite3_errmsg(sqlite3_db_handle(stmt_)));
}
std::string text(int column) const {
auto p = reinterpret_cast<const char*>(sqlite3_column_text(stmt_, column));
return p ? std::string(p, sqlite3_column_bytes(stmt_, column)) : std::string{};
}
long long number(int column) const { return sqlite3_column_int64(stmt_, column); }
};
inline void execute(sqlite3* db, const char* sql) {
if (sqlite3_exec(db, sql, nullptr, nullptr, nullptr) != SQLITE_OK)
throw std::runtime_error(sqlite3_errmsg(db));
}
class Transaction {
sqlite3* db_;
bool committed_ = false;
public:
explicit Transaction(sqlite3* db) : db_(db) { execute(db_, "BEGIN IMMEDIATE"); }
~Transaction() { if (!committed_) sqlite3_exec(db_, "ROLLBACK", nullptr, nullptr, nullptr); }
void commit() { execute(db_, "COMMIT"); committed_ = true; }
};
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#include <cerrno>
#include <fcntl.h>
#include <fstream>
#include <spawn.h>
#include <stdexcept>
#include <string>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
extern char** environ;
namespace legacy {
inline std::string gets(const std::string& path, size_t limit = 65536) {
std::ifstream file(path, std::ios::binary);
if (!file) return {};
std::string data(limit, '\0');
file.read(data.data(), static_cast<std::streamsize>(data.size()));
data.resize(static_cast<size_t>(file.gcount()));
return data;
}
inline int system(const std::vector<std::string>& arguments, const std::string& output) {
if (arguments.empty() || arguments.front().empty() || arguments.front()[0] != '/')
throw std::runtime_error("need an absolute executable path");
if (output.find('\0') != std::string::npos) throw std::runtime_error("NUL in output path");
std::vector<char*> argv;
for (const auto& argument : arguments) {
if (argument.find('\0') != std::string::npos) throw std::runtime_error("NUL in argument");
argv.push_back(const_cast<char*>(argument.c_str()));
}
argv.push_back(nullptr);
posix_spawn_file_actions_t actions;
if (posix_spawn_file_actions_init(&actions)) throw std::runtime_error("spawn setup failed");
int error = posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0);
if (!error) error = posix_spawn_file_actions_addopen(&actions, STDOUT_FILENO, output.c_str(),
O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (!error) error = posix_spawn_file_actions_adddup2(&actions, STDOUT_FILENO, STDERR_FILENO);
pid_t child = -1;
if (!error) error = posix_spawn(&child, argv[0], &actions, nullptr, argv.data(), environ);
posix_spawn_file_actions_destroy(&actions);
if (error) throw std::runtime_error("cannot start tool");
int status = 0;
while (waitpid(child, &status, 0) < 0) {
if (errno != EINTR) throw std::runtime_error("cannot wait for tool");
}
return WIFEXITED(status) ? WEXITSTATUS(status) : 128;
}
}
+333
View File
@@ -0,0 +1,333 @@
#include <httplib.h>
#include "chronicle.hpp"
#include "compiler.hpp"
#include "crypto.hpp"
#include "database.hpp"
#include "protocol.hpp"
#include "util.hpp"
#include <filesystem>
#include <iostream>
#include <mutex>
#include <vector>
namespace fs = std::filesystem;
static sqlite3* db = nullptr;
static std::mutex db_lock;
static void reply(httplib::Response& response, int status, const json& body) {
response.status = status;
response.set_content(body.dump(-1, ' ', false, json::error_handler_t::replace), "application/json");
}
template <class Handler>
static auto endpoint(Handler handler) {
return [handler](const httplib::Request& request, httplib::Response& response) {
try {
handler(request, response);
} catch (const HttpError& error) {
reply(response, error.status, {{"error", error.what()}});
} catch (const filters::Busy& error) {
reply(response, 429, {{"error", error.what()}});
} catch (const json::exception&) {
reply(response, 400, {{"error", "bad field type"}});
} catch (const std::exception& error) {
std::cerr << "request failed: " << error.what() << '\n';
reply(response, 500, {{"error", "service error"}});
}
};
}
static void require_queue(const std::string& id) {
Statement query(db, "SELECT 1 FROM queues WHERE id=?");
if (!query.bind(1, id).next()) throw HttpError(404, "queue not found");
}
static void require_key(const httplib::Request& request) {
Statement query(db, "SELECT 1 FROM queues WHERE id=? AND read_key=?");
query.bind(1, request.matches[1].str()).bind(2, request.get_header_value("X-Queue-Key"));
if (!query.next()) throw HttpError(403, "bad queue key");
}
static json message_row(const Statement& query) {
return {{"id", query.number(0)}, {"topic", query.text(1)}, {"ciphertext", query.text(2)}};
}
static void initialize() {
fs::create_directories("/data");
fs::create_directories("/var/log/lighthouse");
fs::create_directories(filters::work_root);
if (chmod("/data", 0700) || chmod("/var/log/lighthouse", 0755) ||
chmod(filters::work_root, 0711))
throw std::runtime_error("cannot set storage permissions");
if (sqlite3_open("/data/lighthouse.db", &db) != SQLITE_OK)
throw std::runtime_error("cannot open database");
execute(db, R"SQL(
PRAGMA journal_mode=WAL;
PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS queues(
id TEXT PRIMARY KEY, read_key TEXT NOT NULL,
wasm_path TEXT NOT NULL DEFAULT '', label TEXT NOT NULL DEFAULT 'untitled',
retention_seconds INTEGER NOT NULL DEFAULT 3600, created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS messages(
id INTEGER PRIMARY KEY, queue_id TEXT NOT NULL REFERENCES queues(id),
ciphertext TEXT NOT NULL, topic TEXT NOT NULL DEFAULT 'inbox',
not_before INTEGER NOT NULL DEFAULT 0, expires_at INTEGER NOT NULL DEFAULT 2147483647,
read_at INTEGER, created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS filter_revisions(
id INTEGER PRIMARY KEY, queue_id TEXT NOT NULL REFERENCES queues(id),
label TEXT NOT NULL, state TEXT NOT NULL, wasm_path TEXT NOT NULL DEFAULT '',
compiler_output TEXT NOT NULL, source TEXT NOT NULL DEFAULT '',
listing TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS messages_by_queue ON messages(queue_id,id);
CREATE INDEX IF NOT EXISTS revisions_by_queue ON filter_revisions(queue_id,id DESC);
)SQL");
bool has_read_at = false;
{
Statement columns(db, "PRAGMA table_info(messages)");
while (columns.next())
if (columns.text(1) == "read_at") has_read_at = true;
}
if (!has_read_at) execute(db, "ALTER TABLE messages ADD COLUMN read_at INTEGER");
bool has_source = false, has_listing = false;
{
Statement columns(db, "PRAGMA table_info(filter_revisions)");
while (columns.next()) {
if (columns.text(1) == "source") has_source = true;
if (columns.text(1) == "listing") has_listing = true;
}
}
if (!has_source) execute(db, "ALTER TABLE filter_revisions ADD COLUMN source TEXT NOT NULL DEFAULT ''");
if (!has_listing) execute(db, "ALTER TABLE filter_revisions ADD COLUMN listing TEXT NOT NULL DEFAULT ''");
}
static void queue_routes(httplib::Server& server) {
server.Post("/api/queues", endpoint([](const auto& request, auto& response) {
auto body = object_body(request.body);
auto label = label_field(body, "untitled");
auto retention = number_field(body, "retention_seconds", 3600, 60, 604800);
auto id = uuid(), key = random_hex(48), created = utc_now();
std::lock_guard guard(db_lock);
Statement insert(db, "INSERT INTO queues(id,read_key,label,retention_seconds,created_at) VALUES(?,?,?,?,?)");
insert.bind(1, id).bind(2, key).bind(3, label).bind(4, retention).bind(5, created).next();
reply(response, 201, {{"id", id}, {"read_key", key}, {"label", label},
{"retention_seconds", retention}, {"created_at", created}});
}));
server.Get(R"(/api/queues/([0-9a-f-]{36})$)", endpoint([](const auto& request, auto& response) {
auto id = request.matches[1].str();
auto moment = epoch_now();
std::lock_guard guard(db_lock);
Statement query(db, R"SQL(
SELECT q.created_at,q.wasm_path,q.label,q.retention_seconds,COUNT(m.id),
COALESCE(SUM(m.not_before<=? AND m.expires_at>? AND m.read_at IS NULL),0)
FROM queues q LEFT JOIN messages m ON m.queue_id=q.id WHERE q.id=? GROUP BY q.id
)SQL");
query.bind(1, moment).bind(2, moment).bind(3, id);
if (!query.next()) throw HttpError(404, "queue not found");
reply(response, 200, {{"id", id}, {"created_at", query.text(0)}, {"label", query.text(2)},
{"retention_seconds", query.number(3)}, {"filter_installed", !query.text(1).empty()},
{"stored_count", query.number(4)}, {"ready_count", query.number(5)}});
}));
}
static void filter_routes(httplib::Server& server) {
server.Post(R"(/api/queues/([0-9a-f-]{36})/filter)", endpoint([](const auto& request, auto& response) {
auto id = request.matches[1].str();
auto body = object_body(request.body);
auto source = text_field(body, "source", "");
if (source.empty() || source.size() > 8192 || source.find('\0') != std::string::npos)
throw HttpError(400, "need 1..8192 bytes of C source");
auto label = label_field(body, "unnamed");
{
std::lock_guard guard(db_lock);
require_queue(id);
}
auto artifact = filters::compile(source);
auto state = artifact.ready ? "ready" : "rejected";
long long revision;
{
std::lock_guard guard(db_lock);
Transaction transaction(db);
Statement insert(db, R"SQL(
INSERT INTO filter_revisions(queue_id,label,state,wasm_path,compiler_output,source,listing,created_at)
VALUES(?,?,?,?,?,?,?,?)
)SQL");
insert.bind(1, id).bind(2, label).bind(3, state).bind(4, artifact.path)
.bind(5, artifact.diagnostic).bind(6, source).bind(7, artifact.listing)
.bind(8, utc_now()).next();
revision = sqlite3_last_insert_rowid(db);
Statement old(db, R"SQL(
SELECT r.id,r.wasm_path FROM filter_revisions r JOIN queues q ON q.id=r.queue_id
WHERE r.queue_id=? AND (r.wasm_path='' OR r.wasm_path<>q.wasm_path)
AND r.id NOT IN (SELECT id FROM filter_revisions WHERE queue_id=? ORDER BY id DESC LIMIT 16)
)SQL");
old.bind(1, id).bind(2, id);
std::vector<long long> obsolete_ids;
std::vector<std::string> obsolete;
while (old.next()) {
obsolete_ids.push_back(old.number(0));
if (!old.text(1).empty()) obsolete.push_back(old.text(1));
}
for (auto revision_id : obsolete_ids) {
Statement erase(db, "DELETE FROM filter_revisions WHERE id=?");
erase.bind(1, revision_id).next();
}
transaction.commit();
for (const auto& path : obsolete) {
std::error_code error;
fs::remove_all(fs::path(path).parent_path(), error);
}
}
reply(response, artifact.ready ? 200 : 422,
{{"ok", artifact.ready}, {"compiler", artifact.diagnostic}, {"listing", artifact.listing},
{"revision", revision}, {"state", state}, {"active", false},
{"abi", "int filter(int encrypted_length): nonzero accepts"}});
}));
server.Get(R"(/api/queues/([0-9a-f-]{36})/filters)", endpoint([](const auto& request, auto& response) {
auto id = request.matches[1].str();
std::lock_guard guard(db_lock);
require_queue(id);
Statement query(db, R"SQL(
SELECT r.id,r.label,r.state,r.created_at,r.wasm_path=q.wasm_path AND r.wasm_path<>''
FROM filter_revisions r JOIN queues q ON q.id=r.queue_id
WHERE r.queue_id=? ORDER BY r.id DESC LIMIT 20
)SQL");
query.bind(1, id);
auto history = json::array();
while (query.next())
history.push_back({{"revision", query.number(0)}, {"label", query.text(1)},
{"state", query.text(2)}, {"created_at", query.text(3)},
{"active", query.number(4) != 0}});
reply(response, 200, {{"filters", history}});
}));
server.Get(R"(/api/queues/([0-9a-f-]{36})/filters/([0-9]{1,18})$)",
endpoint([](const auto& request, auto& response) {
std::lock_guard guard(db_lock);
require_key(request);
Statement query(db, R"SQL(
SELECT r.label,r.state,r.created_at,r.source,r.compiler_output,r.listing,
r.wasm_path=q.wasm_path AND r.wasm_path<>''
FROM filter_revisions r JOIN queues q ON q.id=r.queue_id
WHERE r.queue_id=? AND r.id=?
)SQL");
query.bind(1, request.matches[1].str()).bind(2, std::stoll(request.matches[2].str()));
if (!query.next()) throw HttpError(404, "revision not found");
reply(response, 200, {{"revision", std::stoll(request.matches[2].str())},
{"label", query.text(0)}, {"state", query.text(1)},
{"created_at", query.text(2)}, {"source", query.text(3)},
{"compiler", query.text(4)}, {"listing", query.text(5)},
{"active", query.number(6) != 0}});
}));
server.Post(R"(/api/queues/([0-9a-f-]{36})/filters/([0-9]{1,18})/activate)",
endpoint([](const auto& request, auto& response) {
auto id = request.matches[1].str();
auto revision = std::stoll(request.matches[2].str());
std::lock_guard guard(db_lock);
require_key(request);
Statement query(db, "SELECT wasm_path FROM filter_revisions WHERE id=? AND queue_id=? AND state='ready'");
query.bind(1, revision).bind(2, id);
if (!query.next()) throw HttpError(404, "ready revision not found");
Statement update(db, "UPDATE queues SET wasm_path=? WHERE id=?");
update.bind(1, query.text(0)).bind(2, id).next();
reply(response, 200, {{"active_revision", revision}});
}));
}
static void message_routes(httplib::Server& server) {
server.Post(R"(/api/queues/([0-9a-f-]{36})/messages)", endpoint([](const auto& request, auto& response) {
auto id = request.matches[1].str();
auto letter = Envelope::read(object_body(request.body));
std::string wasm, created, key;
long long retention;
{
std::lock_guard guard(db_lock);
Statement query(db, "SELECT wasm_path,created_at,retention_seconds,read_key FROM queues WHERE id=?");
if (!query.bind(1, id).next()) throw HttpError(404, "queue not found");
wasm = query.text(0);
created = query.text(1);
retention = query.number(2);
key = query.text(3);
}
auto cipher = crypto::seal(key, letter.message);
if (!filters::accepts(wasm, cipher.size()))
throw HttpError(403, "message rejected by filter");
auto instant = utc_now();
{
std::lock_guard guard(db_lock);
Transaction transaction(db);
Statement prune(db, "DELETE FROM messages WHERE queue_id=? AND expires_at<=?");
prune.bind(1, id).bind(2, epoch_now()).next();
Statement insert(db, R"SQL(
INSERT INTO messages(queue_id,ciphertext,topic,not_before,expires_at,created_at) VALUES(?,?,?,?,?,?)
)SQL");
insert.bind(1, id).bind(2, cipher).bind(3, letter.topic).bind(4, letter.release_at)
.bind(5, epoch_now() + retention).bind(6, instant).next();
chronicle::append(created, id, letter.topic, cipher, instant);
transaction.commit();
}
reply(response, 201, {{"queued", true}, {"encrypted_length", cipher.size()},
{"topic", letter.topic}, {"release_at", letter.release_at}});
}));
server.Get(R"(/api/queues/([0-9a-f-]{36})/messages)", endpoint([](const auto& request, auto& response) {
auto show_read = request.has_param("show_read") && request.get_param_value("show_read") == "true";
std::lock_guard guard(db_lock);
require_key(request);
auto moment = epoch_now();
Transaction transaction(db);
Statement query(db, R"SQL(
SELECT id,topic,ciphertext FROM messages
WHERE queue_id=? AND not_before<=? AND expires_at>?
AND (? OR read_at IS NULL) ORDER BY id
)SQL");
query.bind(1, request.matches[1].str()).bind(2, moment).bind(3, moment).bind(4, show_read ? 1LL : 0LL);
auto messages = json::array();
while (query.next()) messages.push_back(message_row(query));
if (!show_read) {
Statement mark(db, R"SQL(
UPDATE messages SET read_at=? WHERE queue_id=? AND not_before<=?
AND expires_at>? AND read_at IS NULL
)SQL");
mark.bind(1, moment).bind(2, request.matches[1].str()).bind(3, moment).bind(4, moment).next();
}
transaction.commit();
reply(response, 200, {{"messages", messages}});
}));
}
int main() {
try {
initialize();
httplib::Server server;
server.set_payload_max_length(32768);
server.set_pre_routing_handler([](const httplib::Request& request, httplib::Response& response) {
if (request.has_header("Range")) {
reply(response, 400, {{"error", "range requests are not supported"}});
return httplib::Server::HandlerResponse::Handled;
}
return httplib::Server::HandlerResponse::Unhandled;
});
server.Get("/api/health", endpoint([](const auto&, auto& response) {
reply(response, 200, {{"status", "ok"}});
}));
queue_routes(server);
filter_routes(server);
message_routes(server);
server.set_mount_point("/", "/srv/lighthouse/public");
bool listening = server.listen("0.0.0.0", 8080);
sqlite3_close(db);
return listening ? 0 : 1;
} catch (const std::exception& error) {
std::cerr << "startup failed: " << error.what() << '\n';
if (db) sqlite3_close(db);
return 1;
}
}
+94
View File
@@ -0,0 +1,94 @@
#pragma once
#include <chrono>
#include <nlohmann/json.hpp>
#include <regex>
#include <stdexcept>
#include <string>
#include <string_view>
using json = nlohmann::json;
struct HttpError : std::runtime_error {
int status;
HttpError(int code, const std::string& message) : std::runtime_error(message), status(code) {}
};
inline long long epoch_now() {
return std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
}
inline json object_body(const std::string& input) {
auto body = json::parse(input, nullptr, false);
if (!body.is_object()) throw HttpError(400, "need a JSON object");
return body;
}
inline std::string text_field(const json& body, const char* name, const std::string& fallback) {
if (!body.contains(name)) return fallback;
if (!body[name].is_string()) throw HttpError(400, std::string(name) + " must be a string");
return body[name].get<std::string>();
}
inline long long number_field(const json& body, const char* name, long long fallback,
long long low, long long high) {
if (!body.contains(name)) return fallback;
const auto& field = body[name];
if (!field.is_number_integer() || field < low || field > high)
throw HttpError(400, std::string(name) + " out of range");
return field.get<long long>();
}
inline std::string label_field(const json& body, const std::string& fallback) {
auto label = text_field(body, "label", fallback);
if (!std::regex_match(label, std::regex("[A-Za-z0-9 _.-]{1,48}")))
throw HttpError(400, "bad label");
return label;
}
struct Envelope {
std::string message;
std::string topic;
long long release_at;
static Envelope read(const json& body) {
auto encoded = text_field(body, "message", "");
if (encoded.empty() || encoded.size() > 5464 || encoded.size() % 4)
throw HttpError(400, "message must be 1..4096 bytes of base64 data");
static constexpr std::string_view alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string message;
message.reserve(encoded.size() / 4 * 3);
for (size_t offset = 0; offset < encoded.size(); offset += 4) {
unsigned values[4]{};
unsigned padding = 0;
for (size_t i = 0; i < 4; ++i) {
auto c = encoded[offset + i];
if (c == '=') {
if (i < 2 || offset + 4 != encoded.size())
throw HttpError(400, "invalid base64 message");
++padding;
} else {
if (padding) throw HttpError(400, "invalid base64 message");
auto digit = alphabet.find(c);
if (digit == std::string_view::npos) throw HttpError(400, "invalid base64 message");
values[i] = static_cast<unsigned>(digit);
}
}
if ((padding == 1 && (values[2] & 3)) || (padding == 2 && (values[1] & 15)))
throw HttpError(400, "invalid base64 message");
unsigned word = values[0] << 18 | values[1] << 12 | values[2] << 6 | values[3];
message.push_back(static_cast<char>(word >> 16));
if (padding < 2) message.push_back(static_cast<char>(word >> 8));
if (!padding) message.push_back(static_cast<char>(word));
}
if (message.empty() || message.size() > 4096)
throw HttpError(400, "message must be 1..4096 bytes of base64 data");
auto topic = text_field(body, "topic", "inbox");
if (!std::regex_match(topic, std::regex("[a-z0-9_.-]{1,32}")))
throw HttpError(400, "bad topic");
auto delay = number_field(body, "delay_ms", 0, 0, 60000);
return {message, topic, epoch_now() + (delay + 999) / 1000};
}
};
+55
View File
@@ -0,0 +1,55 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <string_view>
namespace recipe {
enum class Op : uint8_t { source = 1, cc, listing };
struct Program {
std::array<Op, 3> code{};
size_t size = 0;
};
consteval Program compile(std::string_view text) {
Program program;
unsigned effects = 0;
while (!text.empty()) {
auto end = text.find('|');
auto word = text.substr(0, end);
while (!word.empty() && word.front() == ' ') word.remove_prefix(1);
while (!word.empty() && word.back() == ' ') word.remove_suffix(1);
Op op;
unsigned needs, gives;
if (word == "source") { op = Op::source; needs = 0; gives = 1; }
else if (word == "cc") { op = Op::cc; needs = 1; gives = 2; }
else if (word == "listing") { op = Op::listing; needs = 2; gives = 4; }
else throw "unknown recipe stage";
if ((effects & needs) != needs || (effects & gives) || program.size == program.code.size())
throw "recipe stages out of order or repeated";
effects |= gives;
program.code[program.size++] = op;
if (end == std::string_view::npos) break;
text.remove_prefix(end + 1);
if (text.empty()) throw "empty recipe stage";
}
if (effects != 7) throw "incomplete filter recipe";
return program;
}
inline constexpr auto filter = compile("source | cc | listing");
template <class Build>
void run(const Program& program, Build& build) {
for (size_t pc = 0; pc < program.size; ++pc) {
switch (program.code[pc]) {
case Op::source: build.source(); break;
case Op::cc: if (!build.cc()) return; break;
case Op::listing: build.listing(); break;
}
}
}
}
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include <cerrno>
#include <ctime>
#include <stdexcept>
#include <string>
#include <sys/random.h>
inline std::string random_hex(size_t count) {
std::string bytes(count, '\0');
size_t offset = 0;
while (offset < count) {
auto got = getrandom(bytes.data() + offset, count - offset, 0);
if (got < 0 && errno == EINTR) continue;
if (got <= 0) throw std::runtime_error("random source failed");
offset += static_cast<size_t>(got);
}
for (auto& byte : bytes) byte = "0123456789abcdef"[static_cast<unsigned char>(byte) & 15];
return bytes;
}
inline std::string uuid() {
auto value = random_hex(32);
value[12] = '4';
value[16] = "89ab"[static_cast<unsigned char>(value[16]) & 3];
return value.substr(0,8) + "-" + value.substr(8,4) + "-" + value.substr(12,4) +
"-" + value.substr(16,4) + "-" + value.substr(20);
}
inline std::string utc_now() {
auto time = std::time(nullptr);
std::tm utc{};
gmtime_r(&time, &utc);
char text[32];
std::strftime(text, sizeof(text), "%FT%TZ", &utc);
return text;
}