repository

BlowfishCMS

A small content management system for OpenBSD

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

726 lines · 45.6 KB · download this file

package BlowfishCMS;
# BlowfishCMS core: configuration, database, HTTP helpers, page chrome,
# request handling and the command-line maintenance modes.
#
# The same code runs under slowcgi (cgi-bin/site.pl, one process per request)
# and as a persistent FastCGI worker (bin/blowfish-fcgi). Anything that must
# not leak between visitors lives in the package variables below and is reset
# by handle_request. Responses are buffered and sent once the request is done.
# How the code is organised: every module in lib/BlowfishCMS/ starts with
# "package BlowfishCMS;", so they all share one namespace. A function defined
# in Pages.pm can be called from Blocks.pm without importing it; this file
# loads them all at the bottom (the require lines). The shared state is the
# "our" variables just below, which each module re-declares with its own
# "our (...)" line to use them.
#
# `use v5.36` turns on strict, warnings and subroutine signatures
# (sub name ($a, $b) {...}). `use utf8` means this source file is UTF-8, so
# typographic quotes and arrows in strings are real characters.
use v5.36;
use utf8;
use Storable ();
use JSON::PP qw(encode_json decode_json);
use Digest::SHA qw(hmac_sha256_hex sha256_hex);
use Encode qw(decode encode FB_CROAK);
use Fcntl qw(:flock :DEFAULT);
use Unicode::Normalize qw(NFKC);
use POSIX qw(strftime);
use File::Basename qw(basename);
use CGI ();
use DBI;
use File::Spec;
use File::Basename qw(dirname);
# The shared variables, in plain words:
#   $base     the root of httpd's chroot (/var/www; a temporary folder in tests)
#   $data     the catalogue's folder (/var/www/var/db/blowfishcms)
#   $store    the media folder (pictures, music, videos, files)
#   $cdata    the comments service's folder (comments, likes, analytics)
#   $root     this release's own folder (where lib/, public/, content/ are)
#   $db       the open database handle for this request (the catalogue)
#   $q        the CGI object: the request's form fields, cookies and uploads
#   $route    the address being handled (/blog/, /admin/, /talk/like ...)
#   $admin    true for /admin/ addresses
#   $contact  true for the addresses the contact service handles
#   $comments_route  true for the addresses the comments service handles
#   $method   GET, POST or HEAD
#   $cookie_header   a Set-Cookie value to send with the response, if any
#   $csrf     this request's anti-forgery token, put into every admin form
our ($base,$data,$store,$cdata,$root,$db,$q,$route,$admin,$contact,$comments_route,$method,$cookie_header,$csrf);

# Ending a response early (redirects, JSON replies, errors) throws this
# marker instead of exiting, so a long-running worker survives it.
# A tiny class whose only job is to be thrown (with die) to say "the response
# is complete, stop here". In a long-running worker a plain exit() would end
# the whole process, so finish() throws this instead and handle_request()
# catches it.
package BlowfishCMS::Done { sub new ($class) { return bless {}, $class } }
sub finish () { die BlowfishCMS::Done->new }
# eval that lets the end-of-response marker through to handle_request. All
# error-handling blocks in the application use this instead of eval.
# Like Perl's eval { ... } (run code, catch errors), but it re-throws the
# "response complete" marker above, so a redirect inside an attempt block
# still ends the request. Returns the block's result, or undef/() if it died
# (the error is then in $@). Called as: attempt { ...code... }
# The :prototype(&) is what lets it be called with a bare block like eval.
sub attempt :prototype(&) ($code) {
    my @r;
    my $ok=wantarray ? eval {@r=$code->();1} : eval {$r[0]=$code->();1};
    unless ($ok) {die $@ if ref $@ eq 'BlowfishCMS::Done';return}
    return wantarray ? @r : $r[0];
}
# JSON kept in the catalogue (block data, theme colours, saved lists), decoded
# once per worker and handed out as copies: JSON::PP is slow, and the same
# few texts are read on every request. undef when the text isn't JSON.
my %json_kept;
# Decodes a JSON text from the database, remembering the result per worker
# so the same text is only parsed once. Hands out a deep copy (dclone) so a
# caller changing the result can't change the remembered one. Forgets
# everything once it holds more than 5000 texts, to bound memory.
sub json_cached ($raw) {
    return undef unless defined $raw && length $raw;
    unless (exists $json_kept{$raw}) {
        %json_kept=() if keys %json_kept>5000;
        $json_kept{$raw}=attempt {JSON::PP->new->decode($raw)};
    }
    my $v=$json_kept{$raw};
    return ref $v ? Storable::dclone($v) : $v;
}

# Heavier modules load on first use: public pages rarely need image
# processing, HTTP or Markdown.
# A temporary file, loading File::Temp only the first time it's needed.
# `goto &File::Temp::tempfile` hands over to the real function with our
# arguments, as if it had been called directly.
sub tempfile { require File::Temp; goto &File::Temp::tempfile }
sub need_gd { require GD; return 1 }

# $root: the release folder, worked out from where this file is
# (lib/BlowfishCMS.pm, so one level up). source_file('content/x') is then a
# path inside the release.
$root=File::Spec->rel2abs(dirname(__FILE__).'/..');
sub source_file ($relative) { return "$root/$relative" }

# ---- This install -------------------------------------------------------------
# What belongs to the install rather than the content: its domain, the admin
# account and where its files live. The installer writes these as "key = value"
# lines to etc/blowfishcms.conf inside the web server's chroot (folders are
# given as seen from inside the chroot). Without the file (a development copy,
# the tests) the defaults below apply: blowfishctl's folders and example.net.
# The environment the process started with. A FastCGI worker's %ENV is replaced on
# every request, so code loaded later (add-ons) reads its settings from here.
our %startup_env=%ENV;
our $VERSION='0.45.6';   # BlowfishCMS release; add-ons name the oldest they work with
our %instance;
# Reads this server's settings file (/var/www/etc/blowfishcms.conf, written by
# `blowfishctl install`): lines of "key = value", # for comments. %c starts
# with the defaults; a key not in the defaults is an error, so a typo can't be
# silently ignored. Each value is then checked: host names for the domain and
# aliases, a login name for admin_user, absolute folder paths without ".."
# for the folders, and a sender address on a real host for mail_from. The
# result goes into %instance, which the rest of the code reads.
sub load_instance {
    my %c=(domain=>'example.net',aliases=>'',admin_user=>'admin',
        data=>'/var/db/blowfishcms',media=>'/media/blowfishcms',comments=>'/var/db/blowfishcms-comments',
        contact=>'/var/db/blowfishcms-contact',secrets=>'/etc/blowfishcms',mail=>'postmark',mail_from=>'noreply@example.net');
    if (open my $fh,'<:encoding(UTF-8)',"$base/etc/blowfishcms.conf") {
        while (my $line=<$fh>) {
            next if $line =~ /\A\s*(?:#|\z)/;
            my ($key,$value)=$line =~ /\A\s*([a-z_]+)\s*=\s*(.*?)\s*\z/ or die "blowfishcms.conf: can't read line $.\n";
            die "blowfishcms.conf: unknown setting $key\n" unless exists $c{$key};
            $c{$key}=$value;
        }
        close $fh;
    }
    my $host=qr/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+/;
    die "blowfishcms.conf: domain must be a host name\n" unless $c{domain} =~ /\A$host\z/;
    die "blowfishcms.conf: aliases must be host names separated by spaces\n" unless $c{aliases} =~ /\A(?:$host(?:\s+$host)*)?\z/;
    die "blowfishcms.conf: admin_user must be a login name\n" unless $c{admin_user} =~ /\A[a-z_][a-z0-9_.-]{0,31}\z/i;
    for (qw(data media comments contact secrets)) {die "blowfishcms.conf: $_ must be a folder such as /var/db/site\n" unless $c{$_} =~ m{\A(?:/[\w.-]+)+\z} && $c{$_} !~ m{/\.\.?(?:/|\z)}}
    die "blowfishcms.conf: mail must be postmark\n" unless $c{mail} eq 'postmark';
    die "blowfishcms.conf: mail_from must be an address Postmark may send from\n" unless $c{mail_from} =~ /\A[^\s\@<>]+\@$host\z/;
    %instance=%c;
}
# Where everything lives: BLOWFISH_ROOT lets the tests point the whole site
# at a temporary folder; on a server it's httpd's chroot, /var/www. The
# settings file names folders as httpd sees them (inside the chroot), so the
# real paths are $base followed by them.
$base = $ENV{BLOWFISH_ROOT} // '/var/www';
load_instance();
$data = $base.$instance{data};
$store = $base.$instance{media};
# Comments and likes live in their own database, written only by the comments worker.
$cdata = $base.$instance{comments};
# The site's own address, used for absolute links (feeds, sitemaps, sharing).
sub site_url { return "https://$instance{domain}" }
# The browser-tab icon when the site hasn't uploaded its own.
sub icon_url { return '/assets/shared/icon.svg' }
# A request's Origin header names this site (its domain or an alias).
# True when an Origin header (sent by browsers with form posts) is this site's
# domain or one of its aliases. Used to refuse forms posted from other sites.
sub own_origin ($origin) { return scalar grep {$origin eq "https://$_"} $instance{domain},split ' ',$instance{aliases} }

# ---- Site settings --------------------------------------------------------------------
# What the owner sets in the admin: the site's name, the author, and the like,
# kept in the site_settings table. Unset values fall back to neutral defaults.
# Every site setting the admin can change, with the value used until it's
# changed. Settings live as key/value rows in the site_settings table.
# `map {("talk_$_"=>'1')} item_kind_order()` adds a likes-and-comments
# switch for every library (talk_blog, talk_photography, ...), on by default.
# seo_setting_defaults() (Seo.pm) adds the search and sharing settings.
sub setting_defaults {
    my %common=(footer_text=>'Hosted on [OpenBSD](https://www.openbsd.org/) · served by [httpd(8)](https://man.openbsd.org/httpd.8).',favicon=>'',logo=>'',logo_size=>'medium',show_site_name=>'1',addons=>'[]',setup=>'done',setup_todo=>'',theme_picker=>'1',window_bars=>'1',backup_nightly=>'1',backup_keep=>'14',mfa_required=>'none',(map {("talk_$_"=>'1')} item_kind_order()),seo_setting_defaults());
    return (%common,site_title=>'My site',author=>'',description=>'',reserved_names=>'');
}
our $settings_cache;   # cleared at the start of every request
# Reads one setting. The first call in a request loads all of them at once
# into $settings_cache (defaults first, then whatever is stored); later calls
# are a hash lookup. Asking for a key that isn't in setting_defaults() is a
# programming error, so it dies to make the mistake obvious.
sub setting ($key) {
    $settings_cache //= do {
        my %s=setting_defaults();
        # (Defaults alone where the catalogue couldn't be opened.)
        my $rows=$db ? eval {$db->selectall_arrayref("SELECT key,value FROM site_settings WHERE key IN (".join(',',('?') x keys %s).")",undef,keys %s)} : undef;
        $s{$_->[0]}=$_->[1] for @{$rows//[]};
        \%s;
    };
    exists $settings_cache->{$key} or die "Unknown setting $key";
    return $settings_cache->{$key};
}
# Opens the catalogue (SQLite). RaiseError makes every database error die
# (caught by attempt or handle_request); sqlite_unicode returns text as Perl
# characters. busy_timeout waits up to 5 s if another process is writing.
# Without $write the connection is read-only (query_only), so the public
# service can't change the catalogue even by mistake.
sub database ($write = 0) {
    my $connection = DBI->connect("dbi:SQLite:dbname=$data/catalog.sqlite", '', '', {RaiseError=>1, PrintError=>0, AutoCommit=>1, sqlite_unicode=>1});
    $connection->do('PRAGMA busy_timeout=5000');
    $connection->do('PRAGMA query_only=ON') unless $write;
    return $connection;
}
# The current time in UTC, as 2026-11-23T10:00:00Z (how dates are stored).
sub now { strftime('%Y-%m-%dT%H:%M:%SZ', gmtime) }
# 32 random hex characters from the system's random source: ids for uploads,
# articles, tokens. Never predictable.
sub random_id {
    open my $fh, '<:raw', '/dev/urandom' or die 'Random source unavailable';
    read($fh, my $bytes, 16) == 16 or die 'Random source unavailable';
    close $fh; return unpack('H*', $bytes);
}
# HTML-escapes text: & < > " ' become entities, so text from users or the
# database can be placed in a page or an attribute without becoming markup.
# Everything printed into HTML goes through h() unless it's already HTML.
sub h ($s) { $s //= ''; $s =~ s/&/&amp;/g; $s =~ s/</&lt;/g; $s =~ s/>/&gt;/g; $s =~ s/"/&quot;/g; $s =~ s/'/&#39;/g; return $s }
# Compares two secrets in constant time: it looks at every character even
# after a difference, so an attacker can't learn how much of a guess was
# right from how long the comparison took.
sub eq_safe ($a, $b) { return 0 unless length($a) == length($b); my $n=0; $n |= ord(substr($a,$_,1)) ^ ord(substr($b,$_,1)) for 0..length($a)-1; return !$n }
# Brings the catalogue's tables up to date (`site.pl --migrate`, run by every
# install and update before the new code goes live). Everything runs inside
# one transaction: if any step fails, nothing is changed. Each ensure_* creates
# its tables if they're missing, so running this twice is harmless. $fresh is
# true for an empty catalogue (a new site), which then gets the setup
# walkthrough and starter content.
sub migrate {
    $db = database(1);
    # A catalogue with no tables yet is a new site, which the setup walkthrough greets.
    my $fresh = !$db->selectrow_array("SELECT count(*) FROM sqlite_master WHERE type='table'");
    $db->begin_work;
    attempt {
        # A new install starts with an empty catalogue.
        $db->do("CREATE TABLE IF NOT EXISTS uploads (id TEXT PRIMARY KEY, kind TEXT NOT NULL, title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', collection TEXT NOT NULL DEFAULT '', filename TEXT NOT NULL, thumbnail TEXT NOT NULL DEFAULT '', mime TEXT NOT NULL, bytes INTEGER NOT NULL, width INTEGER, height INTEGER, created_at TEXT NOT NULL, artwork TEXT NOT NULL DEFAULT '', sort_order INTEGER NOT NULL DEFAULT 0, duration REAL, fps REAL, folder TEXT NOT NULL DEFAULT '', gallery_hidden INTEGER NOT NULL DEFAULT 0, talk_off INTEGER NOT NULL DEFAULT 0, version TEXT NOT NULL DEFAULT '', sha256 TEXT NOT NULL DEFAULT '')");
        $db->do("CREATE TABLE IF NOT EXISTS posts (id TEXT PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL DEFAULT '', published_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, talk_off INTEGER NOT NULL DEFAULT 0)");
        ensure_theme_tables();
        # Pages as blocks; a new site's are made from the seed.
        ensure_page_tables();
        ensure_seo_tables();
        ensure_notice_tables();
        ensure_setup_state($fresh);
        # Admin users (the install's admin account becomes the first owner).
        ensure_user_tables();
        # The picture library's folders.
        ensure_picture_tables();
        # Tags.
        ensure_item_tables();
        # Enabled add-ons bring their own tables up to date too.
        ensure_addon_tables();
        addon_call($_,'migrate',$db) for addons_enabled();
        addon_page_ensure($_) for addons_enabled();
        $db->commit; 1;
    } or do { my $error=$@; $db->rollback; die $error };
    say 'Schema ready; existing uploads preserved.';
}

# Reads one form or query field, cleaned: decoded from UTF-8 (FB_CROAK makes
# invalid bytes an error instead of garbage), NUL characters removed, spaces
# trimmed from both ends, and refused if it's longer than $max characters.
# A missing field is ''.
sub param ($name, $max=2000) {
    my $s = scalar $q->param($name) // '';
    $s = decode('UTF-8', $s, FB_CROAK) unless utf8::is_utf8($s);
    $s =~ s/\x00//g; $s =~ s/^\s+|\s+$//g;
    die "Text exceeds $max characters.\n" if length($s)>$max;
    return $s;
}
# Prints the HTTP status and headers. Admin responses are never cached
# (no-store) and never indexed by search engines. A pending cookie
# ($cookie_header) goes out with whatever response is sent.
sub header ($status=200, $type='text/html; charset=UTF-8', $extra='') {
    print "Status: $status\r\nContent-Type: $type\r\n$extra";
    print "Cache-Control: no-store\r\nX-Robots-Tag: noindex, nofollow\r\n" if $admin;
    print "Set-Cookie: $cookie_header\r\n" if $cookie_header;
    print "\r\n";
}
# Sends a "303 See Other" to $url and ends the request. 303 makes the browser
# fetch the new address with GET, which is what you want after a form post
# (reloading the page won't post the form again).
sub redirect ($url) {
    print "Status: 303\r\nLocation: $url\r\nContent-Type: text/plain; charset=UTF-8\r\nCache-Control: no-store\r\n";
    print "Set-Cookie: $cookie_header\r\n" if $cookie_header;
    print "\r\nRedirecting.\n"; finish();
}
# Sends a value as JSON (the admin's scripts read these) and ends the request.
sub json_response ($value, $status=200) { header($status,'application/json; charset=UTF-8'); print decode('UTF-8',encode_json($value)); finish() }
# Prints the start of an HTML page: the <head> (title, description, canonical
# address, sharing tags, icons, the theme's stylesheet, site.css and site.js)
# and the top of the body (skip link, site name or logo, theme picker, menu).
# $meta carries extras: description, full_title (don't append the site name),
# article, image, talk (load the likes/comments script), page. Admin pages
# leave out what's only for visitors (canonical, sharing, analytics, add-on
# assets). The ?v=N on each file is bumped whenever the file changes, so
# browsers fetch the new version instead of their cached copy.
sub start_page ($title, $path, $status=200, $meta={}) {
    header($status);
    my $description=$meta->{description} // setting('description');my $site=setting('site_title');my $url=site_url();
    print '<!doctype html><html lang="'.h(setting('language')).'" data-theme="'.h(default_theme()).'"'.(setting('window_bars') eq '0' ? ' data-window-bars="off"' : '').'><head><meta charset="utf-8">'.theme_head().'<script src="/js/theme.js?v=8"></script><meta name="viewport" content="width=device-width,initial-scale=1"><title>'.h($meta->{full_title} ? $title : "$title | $site").'</title>'.(length $description ? '<meta name="description" content="'.h($description).'">' : '');
    print '<link rel="canonical" href="'.h($url.$path).'">'.feed_link() unless $admin;
    print seo_head(($meta->{full_title} || $meta->{article}) ? $title : "$title | $site",$path,$description,$meta) unless $admin;
    print icon_head().theme_link().'<link rel="stylesheet" href="/css/site.css?v=18">';
    print '<script defer src="/js/site.js?v=11"></script>';
    print '<script defer src="/js/talk.js?v=1"></script>' if $meta->{talk};
    print analytics_head().addon_head($meta) unless $admin;
    print '</head><body><a class="skip-link" href="#main">skip to content</a><div class="shell desktop"><nav class="site-nav" aria-label="Main"><div class="site-nav__bar">'.site_brand().(setting('theme_picker') eq '0' ? '' : '<label class="theme-picker" for="theme-picker">theme<select id="theme-picker" aria-label="Site theme">'.theme_options().'</select></label><button class="theme-mode" id="theme-mode" type="button" aria-label="Dark mode" aria-pressed="false" hidden><span class="theme-mode__icon" aria-hidden="true"></span></button>').'<button class="site-nav__toggle" type="button" aria-expanded="false" aria-controls="main-menu" aria-label="Toggle navigation">menu</button></div><div class="site-nav__menu" id="main-menu">';
    print nav_links($path);
    my $page=$meta->{page} // page_by_path($path =~ s/\?.*//sr);
    print '</div></nav><main id="main"'.($admin || !$page ?'':page_attributes($page)).'>';
}
# Closes the page: the footer (public pages only) and the closing tags.
sub end_page {
    my $footer=$admin ? '' : footer_html();
    print '</main>'.(length $footer ? '<footer class="site-footer">'.$footer.'</footer>' : '').'</div></body></html>';
}
# Prints a window; page blocks and every admin panel share window_html (Blocks.pm).
# Prints one panel ("window" in this code). Blocks and admin panels share
# window_html() in Blocks.pm, so they look alike.
sub window ($title, $body, $class='') { print window_html($title,'',$body,body_class=>$class) }
# Hidden form fields from a list of name => value pairs, escaped.
sub hidden (%values) { return join '',map {'<input type="hidden" name="'.h($_).'" value="'.h($values{$_}).'">'} sort keys %values }
# The hidden fields every admin form starts with: the CSRF token, the action
# to perform, the section (kind) and the item's id. Never add a second id.
sub fields ($action, $kind, $id='') { hidden(csrf=>$csrf, action=>$action, kind=>$kind, id=>$id) }
# All uploads of one kind (photography, music, video, file), in the order the
# owner arranged them, newest first where no order was set.
sub items ($kind) { $db->selectall_arrayref('SELECT * FROM uploads WHERE kind=? ORDER BY sort_order, created_at DESC, id DESC',{Slice=>{}},$kind) }
# The public address of an upload's file (or its thumbnail). Pictures live in
# folders, so they go through picture_url() in Pictures.pm.
sub media_url ($item, $thumb=0) { $item->{kind} eq 'photography' ? picture_url($item,$thumb) : '/media/'.$item->{kind}.'/'.($thumb?$item->{thumbnail}:$item->{filename}) }
# A byte count as "12.3 MB" or "1.2 GB", for display.
sub megabytes ($bytes) { $bytes>=1024**3 ? sprintf('%.1f GB',$bytes/1024**3) : sprintf('%.1f MB',$bytes/1048576) }
# True when a text is the address of a picture this site stores (in one of
# its media folders, a 32-character id, an image extension). Used to allow
# pictures in articles and share tags while refusing anything else.
sub image_path ($path) { defined($path) && $path =~ m{\A/media/(?:blog|photography|artwork|pictures(?:/[a-z0-9][a-z0-9-]{0,59}){0,5})/[a-f0-9]{32}(?:-thumb)?\.(?:jpg|png|webp)\z} }
# Protection against cross-site request forgery (another site making your
# browser post a form here). Every admin visit gets a token cookie of
# RANDOM.TIME.SIGNATURE, signed with a secret key only the server knows, valid
# for 12 hours. Every admin form carries the same token in a hidden field
# (fields()); a POST is accepted only when the field matches a valid cookie
# and the Origin header, if sent, is this site. The cookie is HttpOnly
# (scripts can't read it), Secure (HTTPS only) and SameSite=Strict.
sub csrf_setup ($secret=undef, $cookie_name='bf_csrf', $cookie_path='/admin/') {
    unless (defined $secret) {open my $fh, '<', "$data/admin/csrf.key" or die 'Admin key unavailable'; local $/; $secret=<$fh>; close $fh}
    my $token = $q->cookie($cookie_name) // '';
    my $valid = $token =~ /\A([a-f0-9]{32})\.(\d+)\.([a-f0-9]{64})\z/ && $2 > time-43200 && $2 <= time+60 && eq_safe($3,hmac_sha256_hex("$1.$2",$secret));
    if ($method eq 'POST') {
        die "This form expired. Reload and try again.\n" unless $valid && eq_safe(param('csrf',150),$token);
        my $origin = $ENV{HTTP_ORIGIN} // '';
        die "Foreign origin rejected.\n" if $origin ne '' && !own_origin($origin);
    }
    unless ($valid) { my $value=random_id().'.'.time; $token=$value.'.'.hmac_sha256_hex($value,$secret) }
    $csrf=$token;
    $cookie_header="$cookie_name=$token; Path=$cookie_path; Max-Age=43200; Secure; HttpOnly; SameSite=Strict";
}

# Decode only raster formats. Pixel dimensions are checked before GD allocates an image.
# Turns an internal error into something safe to show: the real error goes to
# the server log (warn), and anything that looks technical (database errors,
# file paths, line numbers, permissions) becomes a generic message, so
# visitors never see the inside of the site. Messages written for people
# (ending in "\n", as all of ours are) pass through.
sub clean_error ($error) {
    warn(utf8::is_utf8($error) ? encode('UTF-8',$error) : $error);
    return 'The action could not be completed. Please try again.' if $error =~ /(?:DBD::|DBI| at .* line \d|connect|permission)/i;
    $error =~ s/\s+$//;return $error;
}
# ---- Requests -------------------------------------------------------------
# Handle one request from %ENV and STDIN, writing the complete response to
# $out (STDOUT by default). Returns normally even when the request failed.
# The entry point for every web request, in both CGI and FastCGI. It:
# 1. resets every per-request variable and cache (a FastCGI worker serves
#    many visitors, so nothing may carry over from the last one);
# 2. points printing at a buffer, so the response is collected first;
# 3. runs dispatch(), which decides what to show;
# 4. on an unexpected error logs it and answers 500 (unless something was
#    already written);
# 5. sends the buffered response, then streams a file if a download asked for
#    one ($stream_path), renewing the worker's time limit as it goes.
# Returns true when the request ended normally.
sub handle_request ($out=\*STDOUT) {
    ($db,$q,$route,$admin,$contact,$comments_route,$method)=();
    ($cookie_header,$csrf)=('','');undef $BlowfishCMS::stream_path;
    reset_theme_cache();reset_page_cache();$BlowfishCMS::admin_failed=0;undef $settings_cache;undef $BlowfishCMS::addon_blocks_cache;undef $BlowfishCMS::addons_cache;
    my $buffer='';
    open my $fh,'>:encoding(UTF-8)',\$buffer or die "Response buffer unavailable: $!";
    my $previous=select $fh;
    my $ok=eval {dispatch();1};
    my $error=$@;
    select $previous;close $fh;
    unless ($ok || ref $error eq 'BlowfishCMS::Done') {
        warn(utf8::is_utf8($error) ? encode('UTF-8',$error) : $error);
        $buffer="Status: 500\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nInternal Server Error\n" unless length $buffer;
    }
    ($db,$q)=();
    binmode $out;print {$out} $buffer;
    # A download (System screen): the file follows the headers, in pieces, without being held in memory.
    if (($ok || ref $error eq 'BlowfishCMS::Done') && defined(my $path=$BlowfishCMS::stream_path)) {
        undef $BlowfishCMS::stream_path;
        # Each piece sent renews the worker's time limit, so only a stalled download times out.
        if (open my $fh,'<:raw',$path) {while (read($fh,my $chunk,1048576)) {print {$out} $chunk;alarm $BlowfishCMS::request_timeout if $BlowfishCMS::request_timeout} close $fh}
    }
    return $ok || ref $error eq 'BlowfishCMS::Done';
}
# Decides which code handles the request, from the address. httpd (configured
# by blowfishctl) sends each kind of address to the service allowed to
# handle it, using marker names in SCRIPT_NAME:
#   /_page      an ordinary page; the real address is in DOCUMENT_URI
#   /_item      a library item or tag page (/picture/ID/, /tags/NAME/)
#   /_download  a counted file download (/download/ID/)
#   /_addon     an add-on's own address (/x/NAME/... or /admin/x/NAME/...)
# Each marker's address is checked against a strict pattern; anything else
# becomes '/_none' (not found). Then, in order: add-on addresses, the Mail
# screen and contact form (contact service), comments, likes, analytics and
# downloads (comments service), the admin (admin service), and finally public
# pages, feeds, robots.txt, the sitemap and themes.css (public service).
# It also sets how large a request may be ($CGI::POST_MAX) for each kind of
# address, before CGI reads the body.
sub dispatch {
    $route = $ENV{SCRIPT_NAME} // '/';
    # httpd's catch-all page location passes this marker; the page address is
    # then the request path. Only plain /slug/ addresses are accepted there.
    # Add-on addresses (/x/<name>/… and /admin/x/<name>/…) arrive with this marker.
    my $addon_path = $route eq '/_addon' ? ($ENV{DOCUMENT_URI} // '') : undef;
    $route = $addon_path if defined $addon_path;
    if ($route eq '/_item') {$route=$ENV{DOCUMENT_URI} // '';$route='/_none' unless $route =~ m{\A/(?:picture|track|video|file|tags)/[a-z0-9-]+/\z}}
    if ($route eq '/_download') {$route=$ENV{DOCUMENT_URI} // '';$route='/_none' unless $route =~ m{\A/download/[a-f0-9]{32}/\z}}
    if ($route eq '/_page') {$route=$ENV{DOCUMENT_URI} // '';$route='/_none' unless $route =~ m{\A/[a-z0-9-]+/\z} && $route !~ m{\A/admin/}}
    $admin = $route =~ m{^/admin(?:/|$)};
    # /admin/mail/ (the Postmark set-up) runs in the contact service, which holds the token.
    my $mail_route = $route =~ m{\A/admin/mail/?\z};
    $contact = $route eq '/contact/send' || $mail_route;
    $comments_route = $route eq '/talk/comment' || $route eq '/talk/like' || $route eq '/stats/hit' || $route =~ m{\A/download/} || $route =~ m{\A/admin/(?:comments|analytics)/?\z};
    $method = $ENV{REQUEST_METHOD} // 'GET';
    CGI::initialize_globals();
    # An archive upload (a release, add-ons, themes) is refused before it's
    # read when it's larger than one can be, so a wrong file costs nothing.
    # An uploaded release, add-on or theme archive names itself in the address
    # (?upload=release|addons|themes), so its size can be checked against that
    # kind's limit before the (possibly large) body is read at all.
    my ($archive_upload) = $admin && !$comments_route && !$contact ? ($ENV{QUERY_STRING}//'') =~ /(?:\A|&)upload=(release|addons|themes)(?:&|\z)/ : ();
    my $upload_limit = $archive_upload ? system_upload_limits()->{$archive_upload} : undef;
    # An add-on's addresses take up to 1 MB, or its manifest's request_max (Live's stream pieces).
    my ($addon_max) = defined $addon_path && $addon_path =~ m{\A/(?:admin/)?x/([a-z][a-z0-9]{1,19})/} ? ((addon($1)//{})->{request_max}//1) : ();
    # The largest request body allowed: an add-on's own limit (1 MB unless its
    # manifest says request_max), 64 KB for comments and the contact form, the
    # archive's limit for an archive upload, about 258 MB for other admin uploads
    # (pictures, videos, sent in pieces), and 64 KB for anything else. Uploads
    # (files in a form) are only accepted by the admin.
    $CGI::POST_MAX = defined $addon_path ? ($addon_max//1)*1048576 : ($comments_route || $contact) ? 65536 : $upload_limit ? ($upload_limit->[0]+1)*1048576 : $admin ? 270532608 : 65536;
    $CGI::DISABLE_UPLOADS = !$admin || $comments_route || defined $addon_path;
    $ENV{TMPDIR} = "$data/admin/tmp" if $admin && !$comments_route && !$contact && !defined $addon_path;
    $q = CGI->new;
    umask 0027;
    # CGI couldn't read the request (too large, or malformed): answer 413
    # "too large", with a link back when it was an archive upload.
    if ($q->cgi_error) {
        header(413);
        print $upload_limit && $q->cgi_error =~ /\A413/ ? "$upload_limit->[1] are smaller than $upload_limit->[0] MB. <a href=\"/admin/?kind=$upload_limit->[2]\">Back</a>"
            : 'Upload too large or malformed. Please use fewer or smaller files.';
        finish();
    }
    if (defined $addon_path) {
        addon_route($addon_path) or do {header(404,'text/plain; charset=UTF-8');print 'Not Found'};
        finish();
    }
    if ($mail_route) {
        redirect('/admin/mail/') if $route eq '/admin/mail';
        attempt {mail_admin();1} or do {header(500,'text/plain; charset=UTF-8');print h(clean_error($@))};
        finish();
    }
    if ($contact) {attempt {contact_form();1} or do {contact_log('Contact request failed');redirect('/contact/?sent=0')};finish()}
    if ($comments_route) {
        # Comments worker: owns the comments database and nothing else.
        umask 0022;
        $db=database();
        if ($route =~ m{\A/admin/comments}) {
            if ($route eq '/admin/comments') {redirect('/admin/comments/')}
            attempt {comments_admin();1} or do {header(500,'text/plain; charset=UTF-8');print h(clean_error($@))};
            finish();
        }
        # Analytics: its screen (owners) and the counting address.
        if ($route =~ m{\A/admin/analytics}) {
            if ($route eq '/admin/analytics') {redirect('/admin/analytics/')}
            attempt {analytics_admin();1} or do {header(500,'text/plain; charset=UTF-8');print h(clean_error($@))};
            finish();
        }
        if ($route =~ m{\A/download/}) {download_route($route);finish()}
        if ($route eq '/stats/hit') {attempt {analytics_hit();1} or do {warn $@;header(204,'text/plain; charset=UTF-8')};finish()}
        if ($method ne 'POST') {header(405,'text/plain; charset=UTF-8');print 'Method Not Allowed';finish()}
        unless (public_origin_ok()) {header(403,'text/plain; charset=UTF-8');print 'Forbidden';finish()}
        attempt {$route eq '/talk/like' ? talk_like() : talk_comment();1} or do {
            warn $@;
            json_response({ok=>JSON::PP::false,message=>comment_message('unavailable')},500) if wants_json();
            my ($kind,$id)=item_from_ref(param('item',60));
            redirect($kind ? item_kinds()->{$kind}{path}->($id).'#comment-form' : '/');
        };
        finish();
    }
    # The admin service. Every admin request sets up the CSRF token and opens the
    # catalogue for writing. Signing in is the only screen available without a
    # session; everything after require_admin() needs a signed-in user, and the
    # owners-only screens (owner_kinds, add-on screens) need an owner. The kind
    # field (?kind=...) picks the screen; library kinds (pictures, music, ...)
    # fall through to the shared library screen at the end.
    if ($admin) {
        attempt {csrf_setup();1} or do {header(403);print h(clean_error($@));finish()};
        $db=database(1);
        my $kind=param('kind',30);   # x-NAME-page: an add-on's name is up to 20
        # Signing in and out; everything else needs a signed-in admin.
        if ($kind eq 'login') {attempt {login_admin();1} or do {login_page(clean_error($@),'/admin/')};finish()}
        require_admin(1) or finish();
        if ($kind eq 'logout') {attempt {logout_admin();1} or do {header(400);print h(clean_error($@))};finish()}
        if ($kind eq 'account') {account_admin();finish()}
        # Owners only: settings, the look, search, add-ons, users, updates and backups.
        if ((grep {$_ eq $kind} owner_kinds()) || $kind =~ /\Ax-/) {require_admin(1,1) or finish()}
        if ($kind eq 'users') {users_admin();finish()}
        if ($kind eq 'signin') {signin_admin();finish()}
        if ($kind eq 'system') {system_admin();finish()}
        if ($kind eq 'notices') {ensure_notice_tables();notices_admin();finish()}
        if ($kind eq 'setup') {setup_admin();finish()}
        ensure_theme_tables();
        if ($kind eq 'themes') {themes_admin();finish()}
        if ($kind eq '') {overview_admin();finish()}
        if ($kind eq 'pages') {pages_admin();finish()}
        if ($kind eq 'settings') {settings_admin();finish()}
        if ($kind eq 'branding') {branding_admin();finish()}
        if ($kind eq 'search') {search_admin();finish()}
        if ($kind eq 'addons') {addons_admin();finish()}
        if ($kind =~ /\Ax-([a-z][a-z0-9]{1,19})-page\z/ && addon_enabled($1) && ref((addon($1)//{})->{page}) eq 'HASH') {addon_page_screen($1);finish()}
        if ($kind =~ /\Ax-([a-z][a-z0-9]{1,19})\z/ && addon_enabled($1)) {
            my $name=$1;
            my @r=addon_call($name,'admin');
            unless (@r) {admin_page('Not found',status=>404);window('not found','<p>This add-on has no admin screen here.</p>');end_page()}
            finish();
        }
        if ($kind eq 'page') {page_builder_admin();finish()}
        if ($kind eq 'blog') {blog_admin();finish()}
        unless (grep {$_ eq $kind} library_kinds()) {
            redirect('/admin/') if $method eq 'GET';
            json_response({ok=>JSON::PP::false,message=>'Unknown section.'},400) if fetch_request();
            header(400);print 'Unknown admin section.';finish();
        }
        my $message=param('notice',2000);
        if ($method eq 'POST') {
            # Successful actions answer with JSON (admin.js) or redirect back to the
            # library; a failed form shows the library again with the message.
            attempt {library_done($kind,library_action($kind) // media_action($kind));1}
                or do {$message=failed_action($@);json_response({ok=>JSON::PP::false,message=>$message},400) if fetch_request()};
        }
        library_admin($kind,$message);finish();
    }
    # The public service from here on: only GET and HEAD, and a read-only
    # catalogue.
    if ($method ne 'GET' && $method ne 'HEAD') {header(405);print 'Method Not Allowed';finish()}
    $db=database();
    if ($route eq '/blog/feed.xml') {
        unless (page_enabled('blog')) {header(404);print 'Not Found';finish()}
        header(200,'application/rss+xml; charset=UTF-8',"Cache-Control: public, max-age=900\r\n");
        print blog_feed() unless $method eq 'HEAD';finish();
    }
    if ($route eq '/robots.txt') {
        header(200,'text/plain; charset=UTF-8',"Cache-Control: public, max-age=3600\r\n");
        print robots_txt() unless $method eq 'HEAD';finish();
    }
    if ($route eq '/sitemap.xml') {
        header(200,'application/xml; charset=UTF-8',"Cache-Control: public, max-age=3600\r\n");
        print sitemap_xml() unless $method eq 'HEAD';finish();
    }
    if ($route eq '/themes.css') {
        my $with=param('with',30)//'';$with='' unless $with =~ /\A[a-z][a-z0-9-]{1,23}\z/;
        my $version=theme_version($with);my $fresh=(param('v',20) eq $version);
        header(200,'text/css; charset=UTF-8',$fresh ? "Cache-Control: public, max-age=31536000, immutable\r\n" : "Cache-Control: no-cache\r\n");
        print theme_stylesheet($with) unless $method eq 'HEAD';finish();
    }
    # Items of the libraries, and tags.
    if ($route =~ m{\A/(?:picture|track|video|file)/}) {item_page_route($route) or do {header(404);print 'Not Found'};finish()}
    if ($route =~ m{\A/tags/}) {tags_page_route($route) or do {header(404);print 'Not Found'};finish()}
    # Every other address is a page: / or /slug/ (index.html accepted).
    # Every other address is a page: "/" or "/slug/" (with or without
    # index.html). A page that's switched off answers 404; an address that was
    # moved (a redirect the owner set, or an old page address) answers 301 to the
    # new one.
    my $path=$route =~ m{\A/(?:index\.html)?\z} ? '/' : $route =~ m{\A/([a-z0-9-]+)/(?:index\.html)?\z} ? "/$1/" : '';
    my $page=length $path ? page_by_path($path) : undef;
    undef $page if $page && !page_enabled($page->{slug});
    unless ($page) {
        my $to=length $path ? redirect_lookup($path) : undef;
        if ($to) {print "Status: 301\r\nLocation: ".($to =~ m{\Ahttps://} ? $to : site_url().$to)."\r\nContent-Type: text/plain; charset=UTF-8\r\nCache-Control: public, max-age=3600\r\n\r\nMoved.\n";finish()}
        header(404);print 'Not Found';finish();
    }
    my $post=param('post',32);
    if ($page->{slug} eq 'blog' && length $post) {blog_post($post);finish()}
    render_page($page);
}

# ---- Command line ---------------------------------------------------------
# Maintenance modes run by the deploy and cron scripts. Returns undef when the
# arguments aren't a maintenance mode, otherwise the process exit status.
# The maintenance commands (site.pl --NAME ...), run by blowfishctl and cron
# as the account that's allowed to do each one. Each returns a process exit
# status (0 = success). In short:
#   --hourly          each enabled add-on's hourly job
#   --migrate         bring the catalogue up to date (see migrate)
#   --set-password    store a password hash read from standard input
#   --places-check    is this file a city database Analytics can read?
#   --users-count     how many admin users there are
#   --mfa-off         turn off two-step sign-in for one user
#   --backup-plan     whether nightly backups are on, and how many to keep
#   --addons          the add-ons found and their state, one per line
#   --addon-enable / --addon-disable   switch an add-on on or off
#   --updates         add-ons or themes with a newer version available
#   --themes          the theme folders found
#   --theme-forget    delete a theme's variants from the catalogue
#   --notices-pending / --notices-emailed   update alerts waiting to be emailed
#   --addons-in       add-ons' services' hand-overs, to their from_service hooks
#   --alert-mail / --mail-send   send those alerts, or queued add-on mail
#   --import-videos   add videos add-ons handed over (Live's saved streams) to the library
#   --comments-init   create the comments database
# Returns undef when the arguments aren't one of these.
sub cli (@args) {
    return undef unless @args;
    # Root's crontab, every hour: the hourly() hook of each add-on that's on.
    if ($args[0] eq '--hourly') {
        $db=database(1);undef $settings_cache;my $status=0;
        for my $name (addons_enabled()) {
            my $pkg=addon_package($name);my $code=$pkg->can('hourly') or next;
            my @r=attempt {$code->()};
            if (@r) {say "$name: ".($r[0]//'done')} else {$status=1;print STDERR "$name: ".clean_error($@)."\n"}
        }
        return $status;
    }
    if ($args[0] eq '--migrate') {migrate();return 0}
    if ($args[0] eq '--set-password') {say set_password_cli($args[1]//'');return 0}
    # blowfishctl places: is this file a city database the Analytics can use?
    if ($args[0] eq '--places-check') {
        require BlowfishCMS::MMDB;
        my $d=BlowfishCMS::MMDB->load($args[1]//'') or do {say STDERR 'not a MaxMind DB (MMDB) file';return 1};
        my $m=$d->metadata;
        unless (($m->{database_type}//'') =~ /city/i) {say STDERR 'not a city database ('.($m->{database_type}//'no type').')';return 1}
        say "ok: $m->{database_type}, $m->{node_count} nodes".($m->{build_epoch} ? ', built '.strftime('%Y-%m-%d',gmtime $m->{build_epoch}) : '');
        return 0;
    }
    if ($args[0] eq '--users-count') {say scalar(@{(attempt {$db=database();all_admin_users()}) // []});return 0}
    if ($args[0] eq '--mfa-off') {say mfa_off_cli($args[1]//'');return 0}
    # For blowfishctl nightly: whether to back up tonight, and how many nightly backups to keep.
    if ($args[0] eq '--backup-plan') {$db=database();undef $settings_cache;my $keep=setting('backup_keep');$keep=14 unless $keep =~ /\A\d+\z/ && $keep>=1 && $keep<=30;say((setting('backup_nightly') eq '0' ? 'off' : 'on')." $keep");return 0}
    if ($args[0] eq '--addons') {
        # One line per add-on found: name, on/off, service or not, any problem, and whether it has served files.
        $db=database();undef $settings_cache;my %on=map {$_=>1} addons_enabled();my $all=addons_available();
        say join("\t",$_,($on{$_}?'on':'off'),($all->{$_}{service}?'service':'-'),$all->{$_}{problem}||'ok',($all->{$_}{files} && $all->{$_}{service}?'files':'-')) for sort keys %$all;
        return 0;
    }
    if ($args[0] =~ /\A--addon-(enable|disable)\z/ && ($args[1]//'') =~ /\A[a-z][a-z0-9]{1,19}\z/) {
        my $do=$args[0] eq '--addon-enable' ? 'enable' : 'disable';
        $db=database(1);
        if ($do eq 'enable') {$db->begin_work;attempt {addon_enable($args[1]);$db->commit;1} or do {my $e=$@;$db->rollback;print STDERR clean_error($e),"\n";return 1}}
        else {addon_disable($args[1])}
        say "$args[1]: ".($do eq 'enable'?'on':'off');return 0;
    }
    # Add-ons or themes (--updates addon|theme) with a newer version in the list
    # the server last fetched: NAME, VERSION and, when this release is too old
    # for it, the release it needs (tab-separated; blowfishctl's update --all).
    if ($args[0] eq '--updates') {
        my $type=$args[1]//'';die "--updates addon|theme\n" unless $type =~ /\A(?:addon|theme)\z/;
        $db=database();undef $settings_cache;
        say join "\t",$_->{name},$_->{to},$_->{needs}//'' for grep {$_->{type} eq $type} pending_updates();
        return 0;
    }
    # Theme folders found: name, version, where from (core or installed), and any problem.
    if ($args[0] eq '--themes') {
        my $all=theme_packages();
        say join("\t",$_,$all->{$_}{version}//'?',($all->{$_}{core}?'core':'installed'),$all->{$_}{problem}||'ok') for sort keys %$all;
        return 0;
    }
    if ($args[0] eq '--theme-forget' && theme_name_ok($args[1]//'')) {
        $db=database(1);ensure_theme_tables();
        my $n=attempt {theme_forget($args[1])};
        unless (defined $n) {print STDERR clean_error($@),"\n";return 1}
        say "$args[1]: $n variant".($n==1?'':'s')." deleted";return 0;
    }
    # For blowfishctl's nightly check: the update notices the alerts address
    # hasn't had (as the admin's account), sending them (as the contact form's,
    # which holds the Postmark token), then marking them sent.
    if ($args[0] eq '--notices-pending') {$db=database(1);ensure_notice_tables();my $j=notices_pending_json();say $j if length $j;return 0}
    if ($args[0] eq '--notices-emailed') {$db=database(1);ensure_notice_tables();say notices_mark_emailed().' marked as sent';return 0}
    if ($args[0] eq '--alert-mail') {$db=attempt {database()};return alert_mail_cli()}
    if ($args[0] eq '--mail-send') {$db=attempt {database()};return mail_send_cli()}
    # Root's runner, every minute, as the admin's account: videos add-ons handed over.
    if ($args[0] eq '--import-videos') {$db=database(1);undef $settings_cache;return videos_import_cli()}
    # Root's runner, every minute, as the admin's account: add-ons' services' hand-overs.
    if ($args[0] eq '--addons-in') {$db=database(1);undef $settings_cache;return addons_in_cli()}
    if ($args[0] eq '--comments-init') {comments_db(1);say 'Comments database ready.';return 0}
    return undef;
}

# Load every part of the application. They all add functions to this same
# package (see the note at the top), so the order only matters for code that
# runs at load time.
require BlowfishCMS::Pages;
require BlowfishCMS::Media;
require BlowfishCMS::Pictures;
require BlowfishCMS::Users;
require BlowfishCMS::System;
require BlowfishCMS::Notices;
require BlowfishCMS::Setup;
require BlowfishCMS::QR;
require BlowfishCMS::Mfa;
require BlowfishCMS::Themes;
require BlowfishCMS::Blog;
require BlowfishCMS::Comments;
require BlowfishCMS::Items;
require BlowfishCMS::Files;
require BlowfishCMS::Analytics;
require BlowfishCMS::Contact;
require BlowfishCMS::Blocks;
require BlowfishCMS::Code;
require BlowfishCMS::Markdown;
require BlowfishCMS::Payments;
require BlowfishCMS::Questions;
require BlowfishCMS::Video;
require BlowfishCMS::Admin;
require BlowfishCMS::Library;
require BlowfishCMS::Settings;
require BlowfishCMS::Seo;
require BlowfishCMS::Mail;
require BlowfishCMS::Addons;
require BlowfishCMS::Auth;
1;