Commit 22c697fe authored by jan.koester's avatar jan.koester
Browse files

Setup wizard, server administration (/_server/) and config helper

Modelled on actdeploy and on the proxyplus/mammut/mediadb config helper:

- setup wizard (src/setup.*): without a config file on
  https://<host>:8443/ (443 in the image) with a setup code; asks for
  the listener (HTTPS with its self-signed certificate or HTTP behind a
  proxy), the first domain with a database test, authdb and mediadb;
  creates blogi's authdb client and the policy "Blogi: Server
  Administration", writes config.yaml.
- server administration at /_server/ on every host name (like
  /_deploy): HTTP, limits, domains and the BLOGI/DEPLOY/AUTHDB access
  sources. Saving replaces only those blocks (src/serverconfig.*) and
  keeps SMTP, LETSENCRYPT, plugin keys, comments and CRLF; what is
  loaded as root (SSL, PLUGINDIR, CHROOTDIR) stays file-only, templates
  must be theme directories. Login needs the new policy.
- config helper (src/helper.*): blogi runs in a child of a root process
  that writes config.yaml, restarts blogi, rolls back a change blogi
  cannot start with and falls back to a maintenance mode (/_server/
  only), retrying a normal start every 300 s. Requests carry their own
  reply socket, since the per-domain workers share the channel.
- daemon mode: workers report when their domain is loaded, so a domain
  that fails counts as a failed start; SIGTERM/SIGHUP stop the workers
  too; crashed workers are restarted with a 1 s pause.
- wizard and /_server/ are English and German via blogi::tr().
- docker run.sh starts the wizard when neither config nor CLIENTURL
  is there.

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 57e39ed4
Loading
Loading
Loading
Loading
+3 −2
Changes for Dockerfile: 3 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -189,8 +189,9 @@ FROM runtime AS blogi

VOLUME ["/etc/blogi"]

# run.sh writes /etc/blogi/config.yaml from docker-config.yaml on first start; the HTTP
# port comes from $PORT.
# Without /etc/blogi/config.yaml blogi starts its setup wizard on port 443 (setup code in the
# container log); with CLIENTURL & co. set, run.sh writes the file from docker-config.yaml as
# before. Afterwards the server administration at /_server/ changes it.
EXPOSE 443

CMD ["/usr/local/sbin/blogi-run.sh"]
+50 −0
Changes for README.md: 50 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Blogi


## Setup wizard

Without its config file (`blogi -c yaml:/etc/blogi/config.yaml`) blogi starts a
setup wizard on `https://<host>:8443/` (`--setup-bind`, `--setup-port`; port
443 in the Docker image). The **setup code** is in the log and in
`setup-code` next to the configuration. The wizard asks for:

- the listener: HTTPS with the wizard's self-signed certificate, or plain
  HTTP behind a reverse proxy
- the first domain: theme, and a database connection it tests
- an authdb administrator account
- an optional mediadb URL

It then creates blogi's client in authdb and the group policy
**Blogi: Server Administration** (for SuperAdmin / Domain Admins), writes
`config.yaml` and starts blogi.

## Server administration (`/_server/`)

On every host name, like actdeploy's `/_deploy`. It edits the server-level
part of `config.yaml`:

- `HTTP`, the limits (`MAXOPENFILES`, `IDLECONNECTIONTIMEOUT`)
- `DOMAINS`, with a database test per domain
- `DEPLOY/AUTHDB`, the authdb sources that may log in here

Saving replaces only these blocks; every other section (SMTP, LETSENCRYPT,
plugin keys, comments) stays as it is, and the previous file is kept as
`config.yaml.bak`. What is loaded as root (`SSL`, `PLUGINDIR`, a domain's
`PLUGINDIR`/`CHROOTDIR`) can only be changed in the file, and a domain's
template must be one of the theme directories. Logging in needs the policy
Blogi: Server Administration.

The page and the wizard are English and German (browser language, `?lang=`).

## Config helper and maintenance mode

blogi runs in a child of a small config helper that stays root and alone writes
`config.yaml`. In daemon mode the child is the pre-fork supervisor with one worker per
domain.

- **Changed configuration fails to start:** the previous file comes back, and the
  rejected one is kept as `config.yaml.failed`. "Fails to start" also covers a
  domain worker that dies before its domain is loaded.
- **Any other failed start:** blogi runs in maintenance mode, with only `/_server/` and
  every other request answered with 503. Every 300 s it tries a normal start again
  (`BLOGI_MAINTENANCE_RETRY` seconds, `0` = never).
- **Signals:** SIGHUP restarts blogi; SIGTERM stops it together with the domain workers.
- **`--no-helper`:** runs without all of this.
+12 −1
Changes for run.sh: 12 added lines, 1 removed line.
Original line number Diff line number Diff line
#!/bin/sh

# No /etc/blogi/config.yaml:
#   - with CLIENTURL (+ USERNAME, PASSWORD, DBDRIVER, ...) set, write it from
#     docker-config.yaml and register the client at authdb as before;
#   - otherwise blogi starts its setup wizard on port 443 (setup code in the log
#     and in /etc/blogi/setup-code).
if [ ! -f /etc/blogi/config.yaml ] && [ -z "$CLIENTURL" ]; then
    mkdir -p /etc/blogi /var/lib/blogi
    chown blogi /var/lib/blogi 2>/dev/null
    exec /usr/local/bin/blogi -F true -c "yaml:/etc/blogi/config.yaml" --setup-port 443
fi

if [ ! -f /etc/blogi/config.yaml ]; then

    if [ ! -d /etc/blogi ]; then
@@ -27,4 +38,4 @@ if [ ! -f /etc/blogi/config.yaml ]; then
    /usr/local/share/blogi/docker-config.yaml > /etc/blogi/config.yaml
fi

exec /usr/local/bin/blogi -F true -c "yaml://etc/blogi/config.yaml"
exec /usr/local/bin/blogi -F true -c "yaml:/etc/blogi/config.yaml" --setup-port 443
+5 −0
Changes for src/CMakeLists.txt: 5 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -15,6 +15,11 @@ add_library(blogidev STATIC
    blogi.cpp
)

# server administration, setup wizard and config helper (fork/exec, POSIX only)
if(NOT ${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Windows")
    target_sources(blogidev PRIVATE helper.cpp serverconfig.cpp serveradmin.cpp setup.cpp)
endif()

target_link_libraries(blogidev PUBLIC
    htmlpp::htmlpp
    httppp::httppp
+229 −116
Changes for src/blogi.cpp: 229 added lines, 116 removed lines.
Original line number Diff line number Diff line
@@ -71,10 +71,17 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <grp.h>
#include <dlfcn.h>
#include <sys/resource.h>
#include <poll.h>
#endif

#include "session.h"
#include "auth.h"
#ifndef _WIN32
#include "helper.h"
#include "serveradmin.h"
#include "serverconfig.h"
#include "setup.h"
#endif
#include "conf.h"
#include "i18n.h"

@@ -3283,6 +3290,15 @@ void blogi::Blogi::llmsTxtRoot(libhttppp::HttpRequest &curreq, const int tid, co

void blogi::Blogi::RequestEvent(libhttppp::HttpRequest &curreq, const int tid, ULONG_PTR args)
{
#ifndef _WIN32
    // server administration on every host name, like /_deploy (src/serveradmin.h)
    if (blogi::serveradmin::isServerUrl(curreq.getRequestURL()) && Blogi::Cfg)
    {
        blogi::serveradmin::handle(curreq, blogi::serverconfig::filePath(Blogi::Cfg->getConfigPath()),
                                   !Blogi::Cfg->getsslcertpath().empty());
        return;
    }
#endif
    DomainContext *ctx = resolveDomain(curreq);

    if (isDeployRequestUrl(curreq.getRequestURL()))
@@ -4100,6 +4116,17 @@ public:
        libhttppp::HTTPException httpexception;
        try
        {
            // bind now, as root and before "ready": a taken port is a failed start
            try {
                for (auto* s : getServerSockets()) {
                    s->bind();
                    s->listen();
                }
            } catch (netplus::NetException &ne) {
                libhttppp::HTTPException he;
                he[libhttppp::HTTPException::Critical] << ne.what();
                throw he;
            }
            blogi::Blogi blg(getServerSockets(), debug);
#ifndef _WIN32
            if (!debug)
@@ -4122,12 +4149,20 @@ public:
                    setegid(pwd_storage.pw_gid);
                }
            }
            blogi::helper::notifyReady();   // everything bound and loaded (config helper)
#endif
            blg.runEventloop();
        }
        catch (std::exception &e)
        {
            std::cerr << e.what() << std::endl;
#ifndef _WIN32
            // a start that fails here must not look like a clean exit to the config helper
            blogi::helper::reportFatal(e.what());
            std::cerr.flush();
            std::cout.flush();
            std::_Exit(1);
#endif
        }
    };
};
@@ -4272,6 +4307,168 @@ static void ensureConfigGroupWritable(const std::string &configPath)
#endif

#ifndef Windows
static volatile sig_atomic_t gSupervisorStop = 0;
static void onSupervisorStop(int) { gSupervisorStop = 1; }

// upFd: write end of the supervisor's start pipe (-1 for a restart): one byte once the
// domain is loaded, so a domain whose start fails counts as a failed start of blogi
static int runDomainWorker(size_t d, int upFd)
{
    signal(SIGTERM, SIG_DFL);   // the supervisor's stop handler is not the worker's
    signal(SIGINT, SIG_DFL);
    blogi::Blogi::Cfg->filterDomains(d);
    try {
        blogi::Blogi blg(blogi::Blogi::HttpServer->getServerSockets(), false);
        if (upFd >= 0)
        {
            if (write(upFd, "u", 1) != 1) {}
            close(upFd);
        }
        blg.runEventloop();
    } catch (const std::exception &e) {
        std::cerr << "[domain " << d << "] fatal: " << e.what() << std::endl;
        return 1;
    } catch (...) {
        std::cerr << "[domain " << d << "] fatal: unknown exception" << std::endl;
        return 1;
    }
    return 0;
}

// The sites, in a child of the config helper (src/helper.h). daemonMode = the old
// background mode: one pre-forked worker per domain; otherwise one process for all.
static int runServer(const std::string &config, int debug, bool daemonMode)
{
    if (blogi::helper::fallbackMode())
        return blogi::serveradmin::runMaintenance(config, blogi::helper::fallbackReason());

    blogi::Blogi::Cfg = std::make_unique<blogi::Config>(config);
    raiseFileDescriptorLimit(*blogi::Blogi::Cfg);

    struct sigaction SignalAction = {0};
    /* Ignore broken pipes, which can happen when the remote side is not behaving well */
    SignalAction.sa_handler = SIG_IGN;
    sigaction(SIGPIPE, &SignalAction, nullptr);

    if (debug != 0)
    {
        HttpConD blogiD(true);
        return 0;
    }
    if (getuid() == 0)
        ensureConfigGroupWritable(config);

    size_t domainCount = blogi::Blogi::Cfg->getDomainCount();
    if (!daemonMode || domainCount == 0)
    {
        HttpConD blogiD(false);
        return 0;
    }

    // Pre-fork supervisor: bind socket once, fork one worker per domain.
    HttpConDPreFork preFork;
    std::vector<pid_t> pids(domainCount, -1);
    int up[2] = {-1, -1};
    if (pipe(up) != 0)
        throw std::runtime_error(std::string("pipe: ") + strerror(errno));
    for (size_t d = 0; d < domainCount; ++d)
    {
        pid_t pid = fork();
        if (pid == 0)
        {
            close(up[0]);
            return runDomainWorker(d, up[1]);
        }
        pids[d] = pid;
    }
    close(up[1]);

    // SIGTERM/SIGINT (the config helper stopping or restarting blogi) stop the workers too:
    // they hold the listening socket, a restart could not bind it otherwise
    struct sigaction stop = {};
    stop.sa_handler = onSupervisorStop;
    sigemptyset(&stop.sa_mask);
    sigaction(SIGTERM, &stop, nullptr);
    sigaction(SIGINT, &stop, nullptr);
    auto stopWorkers = [&pids]() {
        for (pid_t p : pids)
            if (p > 0) kill(p, SIGTERM);
        for (pid_t p : pids)
            if (p > 0) waitpid(p, nullptr, 0);
    };

    // started = every domain reported it is loaded; a worker dying before failed to start
    // (its database, plugins ...) and so did blogi
    size_t upCount = 0;
    const auto startDeadline = std::chrono::steady_clock::now() + std::chrono::minutes(5);
    std::string startError;
    while (upCount < domainCount && !gSupervisorStop)
    {
        struct pollfd pfd = {up[0], POLLIN, 0};
        if (poll(&pfd, 1, 200) > 0)
        {
            char buf[64];
            ssize_t n = read(up[0], buf, sizeof(buf));
            if (n > 0) upCount += static_cast<size_t>(n);
        }
        int status = 0;
        pid_t died = waitpid(-1, &status, WNOHANG);
        if (died > 0)
        {
            for (size_t d = 0; d < pids.size(); ++d)
                if (pids[d] == died)
                {
                    const auto &dc = blogi::Blogi::Cfg->getDomainConfig(d);
                    startError = "domain " + (dc.names.empty() ? std::to_string(d) : dc.names[0]) + " did not start";
                    pids[d] = -1;
                }
            if (startError.empty()) startError = "a domain worker did not start";
            break;
        }
        if (std::chrono::steady_clock::now() > startDeadline)
        {
            startError = "the domains did not finish starting within 5 minutes";
            break;
        }
    }
    close(up[0]);
    if (!startError.empty())
    {
        std::cerr << "[blogi] " << startError << std::endl;
        blogi::helper::reportFatal(startError);
        stopWorkers();
        return 1;
    }
    blogi::helper::notifyReady();

    // Supervisor watchdog: restart any crashed worker.
    while (!gSupervisorStop)
    {
        int status;
        pid_t died = waitpid(-1, &status, 0);
        if (died < 0)
        {
            if (errno == EINTR) continue;
            break;
        }
        for (size_t d = 0; d < pids.size(); ++d)
        {
            if (pids[d] == died && !gSupervisorStop)
            {
                std::this_thread::sleep_for(std::chrono::seconds(1));   // no hot crash loop
                pid_t newpid = fork();
                if (newpid == 0)
                    return runDomainWorker(d, -1);
                pids[d] = newpid;
                break;
            }
        }
    }
    std::cerr << "[blogi] stopping the domain workers" << std::endl;
    stopWorkers();
    return 0;
}

int main(int argc, char *argv[])
{
    cmdplus::CmdController BlogiCmdCtl(cmdplus::CmdController::getInstance());
@@ -4287,6 +4484,9 @@ int main(int argc, char *argv[])
    BlogiCmdCtl.registerCmd("config", 'c', true, "", "Blogi Config File");
    BlogiCmdCtl.registerCmd("debug", 'd', false, (int)0, "Blogi runs Debugmod");
    BlogiCmdCtl.registerCmd("foreground", 'F', false, "", "Blogi runs Foreground");
    BlogiCmdCtl.registerCmd("setup-bind", 'b', false, "0.0.0.0", "Setup wizard address (without a config file)");
    BlogiCmdCtl.registerCmd("setup-port", 'p', false, "8443", "Setup wizard port (without a config file)");
    BlogiCmdCtl.registerCmd("no-helper", 'n', false, "", "Run without the config helper (no /_server/ settings, no rollback)");

    BlogiCmdCtl.parseCmd(argc, argv);

@@ -4313,154 +4513,67 @@ int main(int argc, char *argv[])
        return -1;
    }

    blogi::Blogi::Cfg = std::make_unique<blogi::Config>(config);
    const std::string configFile = blogi::serverconfig::filePath(config);
    blogi::setup::Options setupOptions;
    setupOptions.configPath = configFile;
    setupOptions.bind = BlogiCmdCtl.getCmdbyKey("setup-bind")->getValue();
    setupOptions.port = atoi(BlogiCmdCtl.getCmdbyKey("setup-port")->getValue().c_str());
    if (setupOptions.port <= 0) setupOptions.port = 8443;
    const bool daemonMode = debug == 0 && !fground;

#ifndef _WIN32
    raiseFileDescriptorLimit(*blogi::Blogi::Cfg);
#endif

    try
    {
        struct sigaction SignalAction = {0};
        /* Ignore broken pipes, which can happen when the remote side is not behaving well */
        SignalAction.sa_handler = SIG_IGN;
        sigaction(SIGPIPE, &SignalAction, nullptr);

        if (debug == 0)
    if (daemonMode)
    {
        try
        {
            if (getuid() == 0)
                {
                    if (!fground)
            {
                logFiles("/var/log/blogi/access.log", STDOUT_FILENO);
                logFiles("/var/log/blogi/error.log", STDERR_FILENO);
            }
                    ensureConfigGroupWritable(config);
                }
        }
        catch (std::exception &e)
        {
            std::cerr << e.what() << std::endl;
        }
            catch (...)
            {
            }

            if (!fground)
            {
                // Daemonize: fork once so the invoking shell/rc script regains control
                // immediately. Everything below (including the pre-fork supervisor's
                // watchdog loop, which never returns) runs in the detached child.
        // Daemonize: the invoking shell/rc script regains control immediately; the config
        // helper below and everything it starts run in the detached child.
        pid_t daemonizePid = fork();
        if (daemonizePid > 0)
                {
            return 0;
                }
                else if (daemonizePid < 0)
        if (daemonizePid < 0)
        {
            std::cerr << "fork failed: " << strerror(errno) << std::endl;
            return -1;
        }
        setsid();

                size_t domainCount = blogi::Blogi::Cfg->getDomainCount();
                if (domainCount > 0)
                {
                    // Pre-fork supervisor: bind socket once, fork one worker per domain.
                    HttpConDPreFork preFork;

                    std::vector<pid_t> pids(domainCount, -1);
                    for (size_t d = 0; d < domainCount; ++d)
                    {
                        pid_t pid = fork();
                        if (pid == 0)
                        {
                            blogi::Blogi::Cfg->filterDomains(d);
                            try {
                                blogi::Blogi blg(blogi::Blogi::HttpServer->getServerSockets(), false);
                                blg.runEventloop();
                            } catch (const std::exception &e) {
                                std::cerr << "[domain " << d << "] fatal: " << e.what() << std::endl;
                                return 1;
                            } catch (...) {
                                std::cerr << "[domain " << d << "] fatal: unknown exception" << std::endl;
                                return 1;
                            }
                            return 0;
                        }
                        pids[d] = pid;
                    }

                    {
        std::ofstream pidf("/var/run/blogi.pid");
        pidf << getpid();
    }

                    // Supervisor watchdog: restart any crashed worker.
                    while (true)
                    {
                        int status;
                        pid_t died = waitpid(-1, &status, 0);
                        if (died <= 0)
                            break;
                        for (size_t d = 0; d < pids.size(); ++d)
                        {
                            if (pids[d] == died)
                            {
                                pid_t newpid = fork();
                                if (newpid == 0)
                                {
                                    blogi::Blogi::Cfg->filterDomains(d);
                                    try {
                                        blogi::Blogi blg(blogi::Blogi::HttpServer->getServerSockets(), false);
                                        blg.runEventloop();
                                    } catch (const std::exception &e) {
                                        std::cerr << "[domain " << d << "] fatal: " << e.what() << std::endl;
                                        return 1;
                                    } catch (...) {
                                        std::cerr << "[domain " << d << "] fatal: unknown exception" << std::endl;
                                        return 1;
                                    }
                                    return 0;
                                }
                                pids[d] = newpid;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    int pid = fork();
                    if (pid == 0)
                    {
                        HttpConD blogiD(false);
                        return 0;
                    }

                    std::ofstream pidf("/var/run/blogi.pid");
                    pidf << pid;
                    pidf.close();
                }
            }
            else
            {
                HttpConD blogiD(false);
            }
        }
        else
    auto work = [&]() -> int {
        try
        {
            HttpConD blogiD(true);
        }
            struct stat sb;
            if (stat(configFile.c_str(), &sb) != 0)
                return blogi::setup::run(setupOptions);
            return runServer(config, debug, daemonMode);
        }
        catch (libhttppp::HTTPException &e)
        {
            std::cerr << e.what() << std::endl;
        return -1;
            blogi::helper::reportFatal(e.what());
            return 1;
        }
    return 0;
        catch (std::exception &e)
        {
            std::cerr << "[blogi] fatal: " << e.what() << std::endl;
            blogi::helper::reportFatal(e.what());
            return 1;
        }
    };
    if (BlogiCmdCtl.getCmdbyKey("no-helper")->getFound())
        return work();
    return blogi::helper::supervise(configFile, work);
}
#endif
#ifdef _WIN32
Loading