repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

189 lines · 9.3 KB · download this file

#!/usr/bin/perl
# blowfish-fcgi: run a BlowfishCMS site as a persistent FastCGI service.
#
# It replaces slowcgi for one of the site's services and accepts slowcgi's
# options, so the existing rcctl flags keep working:
#
#   blowfish-fcgi -u _bfpublic -G _bfstaff -p / -s /var/www/run/blowfish-public.sock -t 600 [-w 3] [-n 1000]
#
#   -s socket   FastCGI socket for httpd (created owned by www, mode 0660)
#   -u user     account the workers run as (required when started as root)
#   -t seconds  longest a single request may run (default 600)
#   -w count    worker processes (default 2)
#   -n count    requests a worker serves before it is replaced (default 1000)
#   -p dir      accepted for slowcgi compatibility; must be /
#   -U user     account allowed to connect to the socket (default www)
#   -G group    one extra group the workers keep (the services with admin
#               screens use _bfstaff to read the session key)
#   -d          stay in the foreground and log to stderr as well as syslog;
#               as root without -u the workers keep root (test runs only),
#               and the service stops when its socket is deleted
#
# Start it as root (rc.d does): it creates the socket, then drops to the -u
# account before loading any site code. The parent only supervises: it starts
# workers, replaces any that exit, and stops them on SIGTERM.
use v5.36;
use FindBin;
use lib "$FindBin::Bin/../lib";
# FCGI speaks the FastCGI protocol: httpd connects to our socket and passes
# each request over it, instead of starting a new program per request.
# Getopt::Std reads the single-letter options, Sys::Syslog writes to the
# system log, and Time::HiRes gives sleep() fractions of a second.
use FCGI;
use POSIX qw(:sys_wait_h setsid);
use Getopt::Std;
use Sys::Syslog qw(openlog syslog);
use Time::HiRes qw(time sleep);

my %o;
# Read the options into %o. A letter followed by ':' takes a value (-s PATH);
# 'd' alone is a switch.
getopts('ds:u:p:t:w:n:U:G:', \%o) or usage();
sub usage { say STDERR 'usage: blowfish-fcgi [-d] -s socket [-u user] [-t timeout] [-w workers] [-n requests]'; exit 1 }
my $socket_path = $o{s} // usage();
my $timeout = $o{t} // 600;
my $workers = $o{w} // 2;
my $max_requests = $o{n} // 1000;
# Refuse values that aren't plain numbers: 1-99 workers, a whole number of
# seconds and of requests.
usage() unless $timeout =~ /\A\d+\z/ && $workers =~ /\A[1-9]\d?\z/ && $max_requests =~ /\A[1-9]\d*\z/;
die "blowfish-fcgi: -p must be / (the site does not run chrooted)\n" if defined $o{p} && $o{p} ne '/';
my $foreground = $o{d};

# The service's short name for log lines: the socket's file name without its
# folder or ".sock" (/var/www/run/blowfish-public.sock -> blowfish-public).
(my $name = $socket_path) =~ s{.*/}{};$name =~ s/\.sock\z//;
openlog("blowfish-fcgi[$name]", 'pid', 'daemon');
sub logmsg ($level, $message) { syslog($level, '%s', $message); print STDERR "$message\n" if $foreground }

# ---- socket and privileges -------------------------------------------------
my ($uid, $gid);
# $> is the effective user id; 0 means root. As root we normally switch to the
# -u account. The one exception is a test run in the foreground with no -u.
my $drop = $> == 0 && !($foreground && !defined $o{u});  # -d without -u as root: test runs only
logmsg('warning', 'running in the foreground as root without -u (testing only)') if $> == 0 && !$drop;
if ($drop) {
    my $user = $o{u} // die "blowfish-fcgi: -u is required when started as root\n";
    my @pw = getpwnam($user) or die "blowfish-fcgi: unknown user $user\n";
    ($uid, $gid) = @pw[2, 3];
    die "blowfish-fcgi: refusing to run workers as root\n" if $uid == 0;
    if (defined $o{G}) {
        my $extra = getgrnam($o{G}) // die "blowfish-fcgi: unknown group $o{G}\n";
        die "blowfish-fcgi: refusing group wheel/0 as -G\n" if $extra == 0;
        $o{G_gid} = $extra;
    }
} elsif (defined $o{u} && $o{u} ne scalar getpwuid($>)) {
    die "blowfish-fcgi: must start as root to switch to $o{u}\n";
}

# Remove a socket left behind by an earlier run (-S: "is a socket"), then
# create a new one. umask 0177 makes it readable and writable by its owner
# only until it's handed to httpd's account below.
unlink $socket_path if -S $socket_path;
my $old_umask = umask 0177;
my $socket = FCGI::OpenSocket($socket_path, 128) or die "blowfish-fcgi: cannot open $socket_path: $!\n";
umask $old_umask;
if ($drop) {
    # httpd (user www) connects to the socket; nobody else may.
    my ($www_uid, $www_gid) = (getpwnam($o{U} // 'www'))[2, 3];
    defined $www_uid or die "blowfish-fcgi: no www account\n";
    chown $www_uid, $www_gid, $socket_path or die "blowfish-fcgi: chown $socket_path: $!\n";
    chmod 0660, $socket_path or die "blowfish-fcgi: chmod $socket_path: $!\n";
    # Like slowcgi: the account's primary group only, plus the -G group if given.
    # Drop privileges. $( and $) are the real and effective group ids; setting $)
    # to "GID GID [EXTRA]" also replaces the list of extra groups, so the workers
    # keep only the account's own group (and -G's). $< and $> are the real and
    # effective user ids. The check after it makes sure none of them is still root.
    $( = $gid; $) = "$gid $gid".(defined $o{G_gid} ? " $o{G_gid}" : '');
    $< = $> = $uid;
    die "blowfish-fcgi: could not drop privileges\n" if $> == 0 || $< == 0 || $( == 0 || $) == 0;
}
# Work from / so the service never holds a folder open (or depends on one).
chdir '/' or die "blowfish-fcgi: chdir /: $!\n";

# Load the application once, unprivileged, before forking: workers share it.
# A broken release fails here, so `rcctl start` reports it.
require BlowfishCMS;

unless ($foreground) {
    # Detach like slowcgi: the starting command returns once the socket is ready.
    my $pid = fork // die "blowfish-fcgi: fork: $!\n";
    POSIX::_exit(0) if $pid;
    setsid();
    open STDIN, '<', '/dev/null'; open STDOUT, '>', '/dev/null'; open STDERR, '>', '/dev/null';
}

# ---- supervisor ------------------------------------------------------------
# The supervisor: %children holds the process ids of running workers. A
# TERM, INT or HUP signal (rcctl stop, Ctrl-C) only sets $stopping; the loop
# below notices it and shuts the workers down cleanly. SIGPIPE is ignored so
# a browser that disconnects mid-response can't kill a process.
my %children; my $stopping = 0;
$SIG{TERM} = $SIG{INT} = $SIG{HUP} = sub { $stopping = 1 };
$SIG{PIPE} = 'IGNORE';
logmsg('info', "serving $socket_path with $workers worker(s), uid $>");

my @recent;    # start times, to slow down a crash loop
# Start one worker process. fork() returns the child's id in the parent (which
# records it) and 0 in the child (which serves requests until it's done, then
# exits without running any cleanup meant for the parent).
sub spawn {
    my $pid = fork // do { logmsg('err', "fork failed: $!"); return };
    if ($pid) { $children{$pid} = 1; return }
    worker(); POSIX::_exit(0);
}
spawn() for 1 .. $workers;
# Keep the workers running: waitpid(-1, WNOHANG) checks, without blocking,
# whether any worker has exited. If one has, log why (unless it simply
# reached its request limit) and start a replacement. @recent keeps the
# start times of the last 10 seconds; if workers keep dying straight away,
# wait a second between restarts instead of spinning.
until ($stopping) {
    my $pid = waitpid(-1, WNOHANG);
    # In the foreground (tests), stop once the socket has been removed.
    if ($foreground && !-S $socket_path) { logmsg('info', 'socket removed'); last }
    if ($pid <= 0) { sleep 0.5; next }
    next unless delete $children{$pid};
    last if $stopping;
    logmsg('warning', "worker $pid exited with status ".($? >> 8).($? & 127 ? ' signal '.($? & 127) : '')) if $?;
    @recent = grep { $_ > time - 10 } @recent, time;
    sleep 1 if @recent > $workers * 3;
    spawn();
}
# Shutting down: ask every worker to stop, give them up to 20 seconds to
# finish the request they're on, then force any that remain.
kill 'TERM', keys %children;
my $deadline = time + 20;
while (%children && time < $deadline) {
    my $pid = waitpid(-1, WNOHANG);
    if ($pid > 0) { delete $children{$pid} } else { sleep 0.1 }
}
kill 'KILL', keys %children if %children;
logmsg('info', 'stopped');
exit 0;

# ---- worker ----------------------------------------------------------------
# One worker: accept a request from httpd, handle it, repeat. Each request
# gets an alarm of -t seconds; if it fires, the request is abandoned and
# this worker is replaced (its state can't be trusted any more).
# $BlowfishCMS::request_timeout lets a long download renew the alarm as it
# sends each piece. After -n requests the worker exits and a fresh one takes
# over, which keeps any slow memory growth in check.
sub worker {
    my $done = 0;
    $SIG{TERM} = $SIG{INT} = $SIG{HUP} = sub { $done = 1 };
    my $request = FCGI::Request(\*STDIN, \*STDOUT, \*STDERR, \%ENV, $socket, FCGI::FAIL_ACCEPT_ON_INTR());
    my $served = 0;
    while (!$done && $request->Accept() >= 0) {
        my $timed_out = 0;
        local $SIG{ALRM} = sub { $timed_out = 1; die "Request exceeded ${timeout}s\n" };
        local $BlowfishCMS::request_timeout = $timeout;
        alarm $timeout if $timeout;
        BlowfishCMS::handle_request(\*STDOUT);
        alarm 0;
        $request->Finish;
        if ($timed_out) { logmsg('warning', 'request timed out; replacing worker'); last }
        last if ++$served >= $max_requests;
    }
    $request->Finish;
}