blib/lib/Web/VWF.pm untested

filter: Statementstmt 0.0% 0 / 789 Branchbran 0.0% 0 / 310 Conditioncond 0.0% 0 / 269 MC/DCmcdc 0.0% 0 / 148 Subroutinesub 0.0% 0 / 79 Podpod 0.0% 0 / 34 totaltotal 0.0% 0 / 1629 CC 155 SCAR 65.4
CC
155
Cov
0%
_doit
2862.0
_init
156.0
_config_entries
156.0
CRAP 689.5
1 package Web::VWF;
2  
3 # njh@nigelhorne.com
4  
5 use strict;
6 use warnings;
7 # use diagnostics;
8  
9 use version; our $VERSION = version->declare('0.004.3');
10  
11 # TODO: Try Log::Any::Adapter::Abstraction instead of Log::Any
12  
13 BEGIN {
14 # Sanitize environment variables
15 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
16 $ENV{'PATH'} = '/usr/local/bin:/bin:/usr/bin'; # For insecurity
17 }
18  
19 no lib '.';
20  
21 use Log::WarnDie 0.09;
22 use Carp::Always;
23 use CGI::ACL 0.06; # For deny_cloud
24 use CGI::Carp qw(fatalsToBrowser);
25 use CGI::Info 0.94; # Gets all messages
26 use CGI::Lingua 0.61;
27 use CHI;
28 use Class::Simple;
29 use Config::Abstraction;
30 use Database::Abstraction;
31 # use Devel::Confess;
32 use Fcntl qw(:flock);
33 use File::Basename;
34 # The address is always defined: CGI::Alert warns about an undefined one, which
35 # fails the B::Lint/warnings::unused check in CI and, in a FastCGI worker where
36 # SERVER_ADMIN is not set, fills the log on every start.
37 use CGI::Alert $ENV{'SERVER_ADMIN'} || 'webmaster@localhost';
38 use FCGI;
39 use FCGI::Buffer;
40 use File::HomeDir;
41 use HTTP::Status;
42 use Log::Abstraction;
43 use Error qw(:try);
44 use File::Spec;
45 use Params::Get;
46 use POSIX qw(strftime);
47 use Readonly;
48 use Scalar::Util;
49 use Module::Runtime qw(require_module); # Safe dynamic module loading; avoids string eval
50 use Timer::Simple;
51 use Time::HiRes;
52  
53 # FIXME: Sometimes gives Insecure dependency in require while running with -T switch in Module/Runtime.pm
54 # use Taint::Runtime qw($TAINT taint_env);
55 use autodie qw(:all);
56  
57 # Where to find the site's own page modules and configuration. The framework
58 # modules themselves are installed by HTTP-VWF, so this only needs to point at
59 # the site's own lib directory when the site has page subclasses of its own.
60 # use lib '/usr/lib/example.com/lib';
61 # use lib '../lib';
62 use lib CGI::Info::script_dir() . '/../lib';
63 # use lib File::HomeDir->my_home() . '/lib/perl5';
64  
65 use Web::VWF::Allow;
66 use Web::VWF::Blacklist;
67 use Web::VWF::Config;
68 use Web::VWF::Utils;
69  
70 # Where the server keeps the configuration of the sites it serves: one directory
71 # per site, named after the site, read when the site has no conf/ of its own
72 # beside cgi-bin/. A site whose host keeps them elsewhere changes this line and
73 # nothing else - it is passed to Web::VWF->new() below, and to the page modules,
74 # so that both read the site's configuration from the same place.
75 Readonly my $SERVER_CONF_DIR => '/usr/lib/vwf';
76  
77 # $TAINT = 1;
78 # taint_env();
79  
80 # Soft rate-limit: present a CAPTCHA challenge when a client exceeds this
81 # many requests within $TIME_WINDOW. Overridable via the config file.
82 Readonly my $MAX_REQUESTS => 100;
83 Readonly my $TIME_WINDOW => '60s'; # CHI-style duration string
84  
85 Readonly my @suffixlist => ('.pl', '.fcgi');
86  
87 # Set up by _init() on the first call to run(), not when the module is loaded.
88 # Loading a module should do no work: reading configuration here meant that
89 # anything that executed the page script while it was still compiling - such as
90 # a configuration reader that took the script for its own configuration file -
91 # ran the framework again inside itself, with any errors silently swallowed.
92 my $info;
93 my $script_name;
94 my $tmpdir;
95  
96 # $vwflog holds the path to the CSV access log; resolved from config on first request.
97 my $vwflog;
98  
99 my $lingua_cache;
100 my $buffercache;
101  
102 # Also set by _init()
103 my $script_dir;
104 my $env_prefix;
105 my $config_abstraction;
106 my $logger;
107  
108 # True while run() is executing, so that a nested call can be refused
109 our $RUNNING;
110  
111 # my $pagename = "Web::VWF::Display::$script_name";
112 # eval "require $pagename";
113  
114 # Loaded later, only when needed
115 # use Web::VWF::Display::index;
116 # use Web::VWF::Display::upload;
117 # use Web::VWF::Display::editor;
118 # use Web::VWF::Display::meta_data;
119  
120 # -- What a site declares, and what it gets if it declares nothing -----------
121 # The directory its databases are in, the data modules it loads, the languages
122 # it offers and the addresses it allows or trusts are all site settings, read
123 # from the domain's configuration file - see "CONFIGURATION" in Web::VWF's
124 # documentation. What is below is what this script used to hardcode, so a site
125 # that says nothing behaves exactly as it did before. The settings are resolved
126 # by _site_setup() on the first request, because the configuration cannot be read
127 # until the domain is known.
128 Readonly my $DEFAULT_DATABASE_DIR => 'databases'; # beside cgi-bin/
129 Readonly my @DEFAULT_DATA_MODULES => qw(Web::VWF::Data::index);
130 Readonly my @DEFAULT_SUPPORTED_LANGUAGES => qw(en-gb);
131 # One site's own address, kept so that a site that came from this script and says
132 # nothing keeps working; a site that wants a different list sets allow_ips.
133 #
134 # It is not called allowed_ips because that is a CGI::ACL constructor argument,
135 # and CGI::ACL's new() runs the site's configuration through
136 # Object::Configure::configure(), which hands a key of that name straight to it
137 # as a string where a hash is expected, breaking the ACL outright.
138 Readonly my @DEFAULT_ALLOW_IPS => qw(108.44.193.70 127.0.0.1);
139 # Loopback and private addresses are exempt from rate limiting.
140 Readonly my @DEFAULT_RATE_LIMIT_TRUSTED_IPS => qw(127.0.0.1 192.168.1.1);
141  
142 # The access log is the one data module this script builds itself, because which
143 # log to read comes from the vwflog setting; its class is loaded here so that
144 # doit() can construct it without a compile-time use.
145 require_module('Web::VWF::Data::vwf_log');
146 Web::VWF::Data::vwf_log->import() if(Web::VWF::Data::vwf_log->can('import'));
147  
148 # Resolved from the configuration by _site_setup(): the directory holding the
149 # site's databases, and the data handles it declared, by the name each is passed
150 # to a page under (index, say).
151 my $database_dir;
152 my %data;
153  
154 # The lists from the configuration, likewise.
155 my @supported_languages;
156 my @rate_limit_trusted_ips;
157  
158 # $config is populated lazily inside doit() so that per-domain configuration
159 # is loaded after the FCGI request has been accepted and the domain is known.
160 my $config;
161  
162 # The pages that may be loaded; worked out in doit() since it needs $config
163 my @valid_pages;
164  
165 # What each valid page says it is for, keyed by page name; only the pages the
166 # site described in its configuration have an entry. Used by the 300 response.
167 my %page_description;
168  
169 # Where a page's module is, for the pages that have a <directory> of their own
170 # or inherit <display><directory>; any other page's module is found in @INC.
171 my %page_directory;
172  
173 # FastCGI signal handling: the FCGI process lives across many requests so we
174 # cannot exit immediately on SIGTERM/SIGUSR1 - we set a flag and exit cleanly
175 # after the current request finishes. See http://fastcgi.com/docs/faq.html#PerlSignals
176 my $requestcount = 0;
177 my $handling_request = 0; # 1 while inside doit(), 0 between requests
178 my $exit_requested = 0; # set to 1 by sig_handler; checked after each request
179  
180 # In-memory set of IPs that have been permanently blacklisted this process
181 # lifetime (e.g. for sending SQL-injection strings).
182 my %blacklisted_ip;
183  
184 # Per-IP request counter cache; created lazily on first request.
185 my $rate_limit_cache;
186  
187 # The CGI::ACL object is built on the first request, once $config is loaded,
188 # because the country blacklist (Web::VWF::Blacklist) can come from the config file.
189 my $acl;
190  
191 =head1 NAME
192  
193 Web::VWF - Versatile Web Framework - easily build a website to support different languages and client platforms
194  
195 =head1 VERSION
196  
197 Version 0.004.3
198  
199 =head1 SYNOPSIS
200  
201 A site's page script, F<cgi-bin/page.fcgi>, is all of this:
202  
203 use FindBin;
204 use Web::VWF;
205  
206 Web::VWF->new({ directory => "$FindBin::Bin/../conf" })->run();
207  
208 =head1 DESCRIPTION
209  
210 Web::VWF is L<VWF|https://github.com/nigelhorne/vwf>, the Versatile Web
211 Framework, packaged as a CPAN distribution. It is an MVC framework for
212 building responsive websites that adapt to the client's language, to the kind
213 of client (web, mobile, robot, search engine or AI crawler) and to whichever
214 database back end the site uses.
215  
216 This module is the distribution's front door: it holds the version number, this
217 overview, and the one thing a site builds by hand - L</new>, the site's
218 configuration and the directory the server keeps it in. Working the framework
219 does these modules:
220  
221 =over 4
222  
223 =item L<Web::VWF::Display>
224  
225 The page renderer. Given the configuration, the browser's language and the
226 kind of client it is, it finds the right template for a page and renders it.
227 A site subclasses it for each of its pages.
228  
229 =item L<Web::VWF::Config>
230  
231 Reads the site's XML configuration.
232  
233 =item L<Web::VWF::Allow>
234  
235 Access control and rate limiting.
236  
237 =item L<Web::VWF::Blacklist>
238  
239 The country blacklist, shared by the page script, L<Web::VWF::Allow> and
240 L<Web::VWF::Display>.
241  
242 =item L<Web::VWF::Utils>
243  
244 Cache initialisation and the Haversine distance calculation.
245  
246 =item L<Web::VWF::CAPTCHA>
247  
248 reCAPTCHA integration and the bypass that follows a solved challenge.
249  
250 =item L<Web::VWF::Mail>
251  
252 Sends mail through sendmail(1), signed with DKIM when the site has a key.
253  
254 =item L<Web::VWF::Throttle>
255  
256 A YAML backend for Data::Throttler that also works on Windows.
257  
258 =item L<Web::VWF::Data::E<lt>sourceE<gt>>
259  
260 The data access layer: CSV, XML and SQLite, through Database::Abstraction.
261  
262 =back
263  
264 F<example/> in this distribution is a small working site to copy and adapt:
265 F<example/cgi-bin/page.fcgi> is the page script, F<example/conf/default> is the
266 configuration (placeholders only - put real keys in your own copy), and
267 F<example/templates/> holds the templates. Run it from the command line with
268 C<CONFIG_DIR=$(pwd)/example/conf root_dir=$(pwd)/example perl -Ilib example/cgi-bin/page.fcgi page=index>.
269  
270 A site's templates sit under a path built from the page's class name,
271 so the file to change when the page module is C<Web::VWF::Display::index> is
272 F<templates/web/Web/VWF/Display/index.tmpl> - see L<Web::VWF::Display>
273 for the rest of the search order.
274  
275 A site that used to carry a renamed copy of VWF of its own deletes that copy,
276 installs this distribution, renames C<VWF::> to C<Web::VWF::> in its own code,
277 and moves its templates from C<.../VWF/Display/> to C<.../Web/VWF/Display/>.
278  
279 =head1 SETTING UP A NEW WEBSITE
280  
281 First install this distribution on the web server. The framework and its pages
282 (C<index>, C<meta_data> and C<captcha>) are then found in C<@INC>, so a new site
283 needs only a page script, a configuration file and templates. From the
284 distribution's directory, with C<SITE> set to the new site's directory:
285  
286 mkdir -p $SITE/cgi-bin $SITE/conf $SITE/databases $SITE/templates/web/Web/VWF/Display
287 cp example/cgi-bin/page.fcgi $SITE/cgi-bin/
288 cp example/databases/index.csv $SITE/databases/
289 cp example/templates/web/Web/VWF/Display/index.tmpl \
290 example/templates/web/Web/VWF/Display/meta_data.tmpl \
291 example/templates/web/Web/VWF/Display/captcha.tmpl \
292 $SITE/templates/web/Web/VWF/Display/
293 chmod +x $SITE/cgi-bin/page.fcgi
294  
295 Then write F<$SITE/conf/default>. This is enough to start with:
296  
297 <?xml version="1.0"?>
298 <config>
299 <root_dir>/path/to/the/site</root_dir>
300 <vwflog>/var/log/example.com/vwf.log</vwflog>
301 <display>
302 <page>
303 <name>index</name>
304 <description>The home page</description>
305 </page>
306 </display>
307 <SiteTitle>
308 <Default>My Site</Default>
309 </SiteTitle>
310 <security>
311 <csrf>
312 <secret>the output of: openssl rand -hex 32</secret>
313 </csrf>
314 </security>
315 </config>
316  
317 The web server must be able to write the C<vwflog> file. To show a CAPTCHA to
318 a client that makes too many requests, add L</C<recaptcha>>. F<example/conf/default>
319 shows more settings, but do not use it unchanged: it names the example's own
320 C<states> page and data, and its keys and secrets are placeholders.
321  
322 Test the site from the command line before pointing the web server at it:
323  
324 CONFIG_DIR=$SITE/conf root_dir=$SITE perl $SITE/cgi-bin/page.fcgi page=index
325  
326 C<CONFIG_DIR> stops configuration found elsewhere on the machine, such as in
327 F<~/lib/conf>, being mixed in.
328  
329 Some things to bear in mind:
330  
331 =over 4
332  
333 =item *
334  
335 If the configuration has a C<< <display><directory> >>, page modules are loaded
336 from there and I<not> from C<@INC>, so copy them into it:
337  
338 cp lib/Web/VWF/Display/index.pm lib/Web/VWF/Display/meta_data.pm /that/directory/
339  
340 C<captcha.pm> is always taken from the installed distribution. A copied module
341 must be copied again after an upgrade.
342  
343 =item *
344  
345 A module and its template go together. After copying a newer F<meta_data.pm>,
346 copy F<meta_data.tmpl> too, or the charts will be missing.
347  
348 =item *
349  
350 Templates may be under F<templates/default/web/> instead of F<templates/web/>.
351 Copy to whichever the site already uses.
352  
353 =item *
354  
355 The contact form on the home page needs F<databases/index.csv>, which lists
356 who it can send to. Replace the example's entries with your own. The rest of
357 the site works without it.
358  
359 =item *
360  
361 The configuration above leaves out the C<meta_data> dashboard, because it shows
362 details of the server and its traffic to anyone who asks for it. If you want it
363 to be public, add it inside C<< <display> >>:
364  
365 <page>
366 <name>meta_data</name>
367 <description>Charts of the server and its traffic</description>
368 </page>
369  
370 and test it with C<page=meta_data>.
371  
372 =back
373  
374 =head1 CONFIGURATION
375  
376 A site is configured by files, usually XML, in its F<conf/> directory (see
377 L<Web::VWF::Config> for where they are looked for, in which order, and how an
378 environment variable of the same name as a top-level key overrides that key).
379 The file named F<default> is read first, then one named for the site's domain
380 name, then C<$CONFIG_FILE>. F<example/conf/default> is a complete working
381 example.
382  
383 Every setting is optional. What a site does not say gets the default given
384 below, which is what the framework did before the setting existed.
385  
386 =head2 Environment variables
387  
388 =over 4
389  
390 =item C<CONFIG_DIR>
391  
392 The one directory configuration is read from. When it is set nothing else is
393 searched. It must exist.
394  
395 =item C<CONFIG_FILE>
396  
397 An extra configuration file, read after C<default> and the domain's file.
398  
399 =item C<root_dir>
400  
401 The site's own directory: where the templates are. It also overrides the C<root_dir> of every cache driver,
402 and the one in the configuration. The server's directory of sites, for a
403 server that has one directory for each, is the C<directory> argument of
404 L</new> and defaults to this variable and then to F</usr/lib/vwf>.
405  
406 =item C<CACHEDIR>, C<CACHE_DIR>
407  
408 Where the file-based caches (C<File> and C<BerkeleyDB>) are kept, so that they
409 need not be inside the site: C<CACHEDIR> is used if it is set and not empty,
410 else C<CACHE_DIR>. Either beats C<root_dir> above, and the directory is
411 created if it does not exist.
412  
413 =back
414  
415 =head2 Pages: C<display>
416  
417 <display>
418 <directory>/path/to/modules</directory>
419 <page>
420 <name>states</name>
421 <description>Displays information about the U.S. states</description>
422 <directory>/path/to/this/page</directory>
423 </page>
424 </display>
425  
426 One C<page> for each page that C<?page=> may name. The C<name> is required and
427 may only be word characters. The C<description> is shown in the C<300 Multiple
428 Choices> response, which lists the pages when no C<page> is given. A page is
429 the class C<Web::VWF::Display::E<lt>nameE<gt>> and its template.
430  
431 C<directory> says where the page modules are. In C<display> it is the default
432 for all of them, in a C<page> it is that page's alone and wins. It is where the
433 F<E<lt>nameE<gt>.pm> file is, not a directory of templates. A relative one is
434 taken from the directory the page script is in. A page with no directory at
435 all is found in C<@INC>.
436  
437 With no C<page> at all, C<display>'s C<directory> is searched and every F<.pm>
438 in it, except F<captcha.pm>, is a page. With no C<display> either, that is
439 F<../lib/Web/VWF/Display> beside the script.
440  
441 The old C<pages> is read when there is no C<display>, as is its old form of one
442 string of names, C<< <pages>index, meta_data</pages> >>.
443  
444 =head2 Data: C<databases> and C<data>
445  
446 <databases>
447 <directory>/path/to/files</directory>
448 </databases>
449 <data>
450 <directory>/path/to/drivers</directory>
451 <driver>
452 <name>states</name>
453 <description>List of data about the U.S. states</description>
454 <directory>/path/to/this/driver</directory>
455 </driver>
456 </data>
457  
458 C<databases> says where the data files are (CSV, XML, SQLite), and C<data> where the
459 drivers that read them are: the L<Database::Abstraction> subclasses. They are
460 separate so that the files may be kept apart from code.
461  
462 C<databases>'s C<directory> is the directory of the data files. Default:
463 F<../databases> beside the script. Pages are told it as C<database_dir> and
464 C<databasedir>. The old top-level C<database_dir> is read when there is no
465 C<directory> in C<databases>.
466  
467 One C<driver> in C<data> for each driver a page may use. A page is given each as
468 a variable named for the last part of its class, lower-cased: the module
469 C<Web::VWF::Data::states> is C<$states> in the page. A C<name> with no C<::> in it is
470 a C<Web::VWF::Data::> module; one with C<::>, such as C<Bands::Data::bands>, is
471 used as written. The C<description> is only logged.
472  
473 C<directory> is where the driver's F<.pm> file is, named for the last part of the
474 class: in the C<driver> for that driver alone, in C<data> for all of them. With
475 neither, the drivers are looked for in the C<databases> directory. A driver that
476 is not in the C<data> or C<databases> directory is taken from C<@INC>, which is
477 how a site uses the distribution's own C<Web::VWF::Data::index>. Only the
478 C<directory> of a C<driver> is strict: a driver that is not in it is not loaded.
479  
480 What is loaded, in order of preference:
481  
482 =over 4
483  
484 =item 1. the C<driver> elements;
485  
486 =item 2. the old C<data_modules>, one string of names, C<index, states> (an empty
487 one means none);
488  
489 =item 3. every F<.pm> in the C<data> directory, or failing that the C<databases>
490 directory;
491  
492 =item 4. the default, C<Web::VWF::Data::index>.
493  
494 =back
495  
496 A module that cannot be loaded is logged and skipped; the pages that do not
497 need it still work.
498  
499 Take care in naming a driver's own configuration: the drivers are given the
500 configuration's top-level keys as their constructor arguments, so a key called
501 C<data> would replace the rows of every database. The framework discards those
502 rows, but a driver of your own that is constructed elsewhere must do the same.
503  
504 =head2 Other settings
505  
506 =over 4
507  
508 =item C<supported_languages>
509  
510 The languages the site has templates for. Default: C<en-gb>.
511  
512 =item C<allow_ips>
513  
514 Addresses always allowed through the access control. Default: C<108.44.193.70>
515 and C<127.0.0.1>; a site should set its own. It is not called C<allowed_ips>,
516 which would be taken as a constructor argument by L<CGI::ACL>.
517  
518 =item C<rate_limit_trusted_ips>
519  
520 Addresses never rate limited. Default: C<127.0.0.1> and C<192.168.1.1>.
521  
522 =item C<blacklist_countries>
523  
524 Two-letter country codes to refuse. Default: C<BY MD RU CN BR UY TR MA VE SA
525 CY CO MX IN RS PK UA XH>. Setting it replaces the list.
526  
527 =item C<vwflog>
528  
529 The path of the access log, a CSV file that the C<meta_data> page reads.
530 Default: F<vwf.log> in the log directory L<CGI::Info> chooses.
531  
532 =item C<root_dir>
533  
534 The site's own directory, as the environment variable of the same name, which
535 wins. When it is set, the output of pages other than the home page and mail
536 sending is also saved, for a day, in F<save_to> inside it, by L<FCGI::Buffer>.
537  
538 =item C<twitter>
539  
540 A Twitter handle, which gives the pages a tweet button.
541  
542 =item C<SiteTitle>, C<contact>, and any other key
543  
544 All of the configuration is available to the templates, so a site may put its
545 own settings in it. C<SiteTitle> and C<contact> in the example are only
546 that.
547  
548 =item C<syslog>
549  
550 Passed to L<CGI::Info> to log to syslog. C<server> is accepted for C<host>.
551  
552 =item C<DKIMSelector>, C<DKIMKey>
553  
554 The selector and the private key file with which the mail the contact page
555 sends is signed. Without both it is sent unsigned. See L<Web::VWF::Mail>.
556  
557 =back
558  
559 List-valued settings (C<supported_languages>, C<allow_ips>,
560 C<rate_limit_trusted_ips>, C<blacklist_countries>) may be written as one string
561 separated by commas or spaces, or as an element with one child for each value.
562  
563 =head2 C<recaptcha>
564  
565 <recaptcha>
566 <enabled>1</enabled>
567 <site_key>...</site_key>
568 <secret_key>...</secret_key>
569 </recaptcha>
570  
571 Google reCAPTCHA, from L<https://www.google.com/recaptcha/admin>. When it is
572 enabled a client past the soft rate limit is shown a challenge instead of
573 being refused. When it is not, the hard limit refuses with a plain-text C<429>.
574  
575 =head2 C<security>
576  
577 =over 4
578  
579 =item C<security.rate_limiting.max_requests>
580  
581 Requests from one address in the C<time_window> after which the CAPTCHA is
582 shown. Default: 100.
583  
584 =item C<security.rate_limiting.max_requests_hard>
585  
586 After which the request is refused. Default: one and a half times
587 C<max_requests>. Requests answered with the CAPTCHA count towards it.
588  
589 =item C<security.rate_limiting.time_window>
590  
591 A duration such as C<60s> or C<5 minutes>. Default: C<60s>. Requests are
592 counted in a window of this length, which starts with the first of them.
593  
594 =item C<security.rate_limiting.captcha_bypass_duration>
595  
596 How long a solved CAPTCHA exempts the client from the limit. Default: C<300s>.
597  
598 =item C<security.ids_threshold>
599  
600 The L<CGI::IDS> impact above which a request is treated as an attack.
601 Default: 50.
602  
603 =item C<security.csrf.enable>
604  
605 Set to C<0> to turn off the CSRF cookie that pages with a form are given.
606 Default: 1.
607  
608 =item C<security.csrf.secret>
609  
610 The secret the CSRF tokens are signed with. Without one a random secret is
611 made for each process and the tokens do not outlive it. See
612 L<Web::VWF::Display>.
613  
614 =item C<security.content_security_policy>
615  
616 Sources to add to the C<Content-Security-Policy> header, for scripts, images and
617 so on that your own templates load from elsewhere. See
618 L<Web::VWF::Display/Content-Security-Policy>.
619  
620 =back
621  
622 =head2 C<throttle>
623  
624 The per-address throttle used by L<Web::VWF::Allow> and by
625 L<Web::VWF::Display>, which share one file.
626  
627 =over 4
628  
629 =item C<throttle.max_items>
630  
631 Requests allowed in the interval. Default: 30.
632  
633 =item C<throttle.interval>
634  
635 The interval, in seconds. Default: 90.
636  
637 =item C<throttle.file>
638  
639 The file the counts are kept in. Default: F<throttle> in the temporary
640 directory.
641  
642 =back
643  
644 =head2 Caches: C<disc_cache> and C<memory_cache>
645  
646 <disc_cache>
647 <driver>File</driver>
648 <root_dir>/var/tmp/cache</root_dir>
649 </disc_cache>
650  
651 The L<CHI> caches. C<driver> is one of C<Memory>, C<BerkeleyDB>, C<DBI>,
652 C<Redis>, C<Memcached>, C<SharedMem>, C<File> or C<Null>. Default for
653 C<disc_cache>: C<BerkeleyDB>, or C<File> where that is not installed; for
654 C<memory_cache>: C<Memory>. The other keys depend on the driver:
655  
656 =over 4
657  
658 =item C<root_dir>
659  
660 For C<File> and C<BerkeleyDB>. Overridden by C<$CACHEDIR>, C<$CACHE_DIR> and
661 C<$root_dir>, in that order. It must exist and be writable unless one of the
662 environment variables made it.
663  
664 =item C<server> (or C<host>) and C<port>
665  
666 For C<Memcached>: C<host:port> pairs separated by commas, or a host with the
667 port in C<port>. Default: C<127.0.0.1:11211>.
668  
669 =item C<connect>, C<create_table>
670  
671 For C<DBI>: the DSN, which is required, and whether to create the table
672 (default: yes).
673  
674 =item C<reconnect>, C<every>, C<encoding>, C<redis_options>
675  
676 For C<Redis>, which also takes C<server> (or C<host>) and C<port> as above.
677  
678 =item C<shm_key>, C<shm_size>, C<max_size>
679  
680 For C<SharedMem>; C<shm_key> is required.
681  
682 =item C<global>, C<datastore>
683  
684 For C<Memory>; not both.
685  
686 =back
687  
688 =head1 SUBROUTINES/METHODS
689  
690 =head2 new
691  
692 The configuration of a site, and the directory the server keeps it in.
693  
694 B<Parameters:>
695  
696 =over 4
697  
698 =item * C<directory> - The directory the server keeps the configuration of the
699 sites it serves in: one directory per site, named after the site, so that a site
700 reached as F<example.com> is configured from F</usr/lib/vwf/example.com>. Any
701 other root can be named here - F</etc/vwf>, F</usr/local/etc/vwf> - and the
702 default is F</usr/lib/vwf>. Optional.
703  
704 =item * C<info>, C<logger>, C<config_directory>, C<config_file>, C<config> -
705 handed to L<Web::VWF::Config>, which describes them.
706  
707 =back
708  
709 =head3 API SPECIFICATION
710  
711 =head4 INPUT
712  
713 {
714 directory => { type => 'string', optional => 1 },
715 info => { type => 'object', optional => 1 },
716 logger => { type => 'object', optional => 1 },
717 config_directory => { type => 'string', optional => 1 },
718 config_file => { type => 'string', optional => 1 },
719 config => { type => 'hashref', optional => 1 },
720 }
721  
722 C<new> croaks with C<directory must be a string> when C<directory> is a reference.
723  
724 =head4 OUTPUT
725  
726 { type => 'object', isa => 'Web::VWF' }
727  
728 =cut
729  
730 sub new
731 {
732 my $proto = shift;
733 my $params = Params::Get::get_params(undef, @_) // {};
734  
735 my $class = ref($proto) || $proto;
736  
737 if(defined($params->{'directory'}) && ref($params->{'directory'})) {
738 Carp::croak('directory must be a string');
739 }
740  
741 return bless {
742 directory => $params->{'directory'},
743 params => $params,
744 }, $class;
745 }
746  
747 =head2 run
748  
749 Serve requests. It accepts FastCGI requests one after another and sends each
750 one to the page named by C<?page=>, as described in L</DESCRIPTION>; an error in
751 one request is logged and does not end the worker.
752  
753 The loop ends, and C<run> returns, when the web server asks the worker to exit,
754 after a TERM or USR1 signal, or when the page script has been changed since the
755 worker started, so that the next request starts a worker with the new code.
756  
757 When C<REMOTE_ADDR> is not set, which is how the script is run from a command
758 line, there is no web server: C<run> handles one request, built from the
759 command-line arguments such as C<page=index>, turns caching off, takes the
760 language from C<LANG> and prints debug logging to STDOUT among the response.
761  
762 C<run> refuses to run again from inside itself, and to run while the script is
763 still being compiled, which happens when something reads the page script as if
764 it were a configuration file. It prints a message on STDERR and returns.
765  
766 If the access log (the C<vwflog> setting) does not exist or is empty, it is
767 created with its header row before the page is rendered. A log that cannot be
768 written is reported to the logger; the request is still served.
769  
770 =head3 API SPECIFICATION
771  
772 =head4 INPUT
773  
774 {}
775  
776 =head4 OUTPUT
777  
778 { type => 'undef' }
779  
780 =cut
781  
782 =head2 _directory
783  
784 Internal: not part of the public interface. The directory the server keeps this site's configuration in: what C<new()> was
785 given, or F</usr/lib/vwf>. L<Web::VWF::Config> adds the site's own name to it.
786  
787 =head3 API SPECIFICATION
788  
789 =head4 INPUT
790  
791 {}
792  
793 =head4 OUTPUT
794  
795 { type => 'string' }
796  
797 =cut
798  
799 sub _directory
800 {
801 my $self = shift;
802  
803 return $self->{'directory'} // $ENV{root_dir} // $Web::VWF::Config::DEFAULT_DIRECTORY;
804 }
805  
806 =head2 _config
807  
808 Internal: not part of the public interface. The site's configuration, read once and kept: a site that has no F<conf/> of its
809 own beside F<cgi-bin/> is configured from the server's directory for it, and
810 L<Web::VWF::Config> describes the rest of the search.
811  
812 =head3 API SPECIFICATION
813  
814 =head4 INPUT
815  
816 {}
817  
818 =head4 OUTPUT
819  
820 { type => 'object', isa => 'Web::VWF::Config' }
821  
822 =cut
823  
824 sub _config
825 {
826 my $self = shift;
827  
828 return $self->{'config'} ||= Web::VWF::Config->new({
829 %{$self->{'params'}},
830 directory => $self->_directory(),
831 });
832 }
833  
834 =head2 sig_handler
835  
836 Internal: not part of the public interface, though it is a plain function, not a
837 method. The handler for TERM and USR1. It sets the flag that makes C<run> leave its loop and, if no
838 request is being handled, flushes the response cache and statistics, detaches
839 L<Log::WarnDie> and exits at once. Mid-request it only sets the flag, so the
840 response in flight is sent whole.
841  
842 =head3 API SPECIFICATION
843  
844 =head4 INPUT
845  
846 { signal => { type => 'string' } }
847  
848 =head4 OUTPUT
849  
850 { type => 'undef' }
851  
852 =head2 choose
853  
854 Internal: a plain function. Sends the C<300 Multiple Choices> response: plain
855 text that lists C<?page=> and the description of each page the site serves, with
856 a C<Last-Modified> header from the page script. The list is left out for
857 C<HEAD>. It does nothing when the status of the request is already not 200,
858 as for an unknown page, where the status line is sent elsewhere.
859  
860 =head3 API SPECIFICATION
861  
862 =head4 INPUT
863  
864 {}
865  
866 =head4 OUTPUT
867  
868 { type => 'undef' }
869  
870 =head2 send_error
871  
872 Internal: a plain function. Sends a short plain-text error response, and
873 records the status in the request's L<CGI::Info>. Takes a hash or a hashref:
874  
875 =over 4
876  
877 =item C<status>
878  
879 The HTTP status code. Required.
880  
881 =item C<body>
882  
883 The text to send. It is not sent for C<HEAD>.
884  
885 =item C<headers>
886  
887 Extra header lines, each ending in a newline, such as C<Retry-After>.
888  
889 =item C<buffered>
890  
891 True once L<FCGI::Buffer> is capturing the output: it sends the C<Status> line
892 itself, so this does not.
893  
894 =back
895  
896 =head3 API SPECIFICATION
897  
898 =head4 INPUT
899  
900 {
901 status => { type => 'integer', min => 100, max => 599 },
902 body => { type => 'string', optional => 1 },
903 headers => { type => 'string', optional => 1 },
904 buffered => { type => 'boolean', optional => 1 },
905 }
906  
907 =head4 OUTPUT
908  
909 { type => 'integer', value => 1 }
910  
911 =head2 duration_seconds
912  
913 Internal: a plain function. Converts a duration such as C<60s>, C<2 minutes> or
914 C<90> to whole seconds, with L<Time::Duration::Parse>. A string of digits is
915 already seconds. One that cannot be parsed is logged as a warning, and
916 counts as 60 seconds.
917  
918 =head3 API SPECIFICATION
919  
920 =head4 INPUT
921  
922 { duration => { type => 'string' } }
923  
924 =head4 OUTPUT
925  
926 { type => 'integer', min => 0 }
927  
928 =head2 blacklisted
929  
930 Internal: a plain function. Takes the request's L<CGI::Info> and says whether
931 the request looks like an SQL injection attempt. The address that sent one is
932 remembered by the worker, so its later requests are refused without scanning
933 them again. It is only a filter for noise, see L<Web::VWF::Blacklist>. A
934 request of more than 8192 characters is not scanned. There is nothing to check
935 without C<REMOTE_ADDR>. When it returns true the status of the request has been
936 set to 403.
937  
938 =head3 API SPECIFICATION
939  
940 =head4 INPUT
941  
942 { info => { type => 'object', isa => 'CGI::Info' } }
943  
944 =head4 OUTPUT
945  
946 { type => 'boolean' }
947  
948 =head2 filter
949  
950 Internal: a plain function, registered with L<Log::WarnDie>. Called with a
951 warning, returns false for the few harmless ones that are not worth logging
952 (two missing optional modules under L<Net::OAuth> and L<NetAddr::IP>, and an
953 C<S_IFFIFO> message from Fcntl) and true for all the rest.
954  
955 =head3 API SPECIFICATION
956  
957 =head4 INPUT
958  
959 { message => { type => 'string' } }
960  
961 =head4 OUTPUT
962  
963 { type => 'boolean' }
964  
965 =cut
966  
967 # Deferred shutdown handler: set the exit flag and, if we are between requests,
968 # flush caches and exit immediately. If we are mid-request, the flag is checked
969 # after doit() returns so the in-flight response is sent cleanly.
970 sub sig_handler {
971 $exit_requested = 1;
972 $logger->trace('In sig_handler') if($logger);
973 if(!$handling_request) {
974 local $SIG{TERM} = local $SIG{USR1} = 'IGNORE';
975 $logger->info('Shutting down') if($logger);
976 # Flush the page-level response cache to disk before we exit.
977 if($buffercache) {
978 $buffercache->purge();
979 }
980 CHI->stats->flush();
981 # Detach the dispatcher so that Log::WarnDie does not try to log
982 # after the logger object has been destroyed.
983 Log::WarnDie->dispatcher(undef);
984 exit(0);
985 }
986 }
987  
988  
989 # Everything the framework needs before the first request: the bootstrap
990 # CGI::Info, the script's name and temporary directory, the configuration and the
991 # logger. Called once, from run(). The handlers for warnings and fatal errors
992 # are installed first, so that a failure while setting up is reported rather
993 # than lost.
994 sub _init
995 {
996 my $self = shift;
997  
998 return if($self->{initialised});
999 $self->{initialised} = 1;
1000  
1001 # USR1 and TERM both trigger a clean shutdown; PIPE is silenced because a
1002 # broken client connection mid-response should not kill the worker.
1003 $SIG{USR1} = \&sig_handler;
1004 $SIG{TERM} = \&sig_handler;
1005 $SIG{PIPE} = 'IGNORE';
1006  
1007 # Catch all Perl warnings and mirror them to the per-script stderr log file
1008 # as well as to the structured logger.
1009 $SIG{__WARN__} = sub {
1010 my $msg = join '', @_;
1011 if($tmpdir && open(my $fout, '>>', File::Spec->catfile($tmpdir, "$script_name.stderr"))) {
1012 print {$fout} (($info ? $info->domain_name() : undef) // '(unknown host)'), ": $msg";
1013 close $fout;
1014 }
1015 $logger->warn($msg) if($logger);
1016 };
1017  
1018 # Catch fatal errors. The $^S guard prevents this handler from interfering
1019 # with Error.pm's try/catch blocks which use eval internally.
1020 $SIG{__DIE__} = sub {
1021 return if $^S; # inside an eval - let the caller handle it
1022 my $msg = join '', @_;
1023 # Detach Log::WarnDie first so a logger error cannot cause infinite recursion.
1024 Log::WarnDie->dispatcher(undef);
1025 if($tmpdir && open(my $fout, '>>', File::Spec->catfile($tmpdir, "$script_name.stderr"))) {
1026 print {$fout} (($info ? $info->domain_name() : undef) // '(unknown host)'), ": $msg";
1027 close $fout;
1028 }
1029 $logger->fatal($msg) if($logger);
1030 CORE::die @_; # re-throw so the original die location is preserved
1031 };
1032  
1033 # Bootstrap CGI::Info before the FCGI accept loop so we can derive the script
1034 # name and temp directory for logging even before the first real request.
1035 $info = CGI::Info->new();
1036 $script_name = $self->{script_name} = basename($info->script_name(), @suffixlist);
1037 $tmpdir = $info->tmpdir();
1038  
1039 # When running under a real HTTP server, redirect STDERR to a per-script log
1040 # file in the temp directory so that die/warn messages are captured.
1041 if($ENV{'HTTP_USER_AGENT'}) {
1042 close STDERR;
1043 open(STDERR, '>>', File::Spec->catfile($tmpdir, "$self->{script_name}.stderr"));
1044 }
1045  
1046 # Register the log filter that suppresses known-harmless warnings.
1047 Log::WarnDie->filter(\&filter);
1048  
1049 # Derive the environment-variable prefix from the hostname (e.g. MY_SITE_)
1050 # so that per-domain config overrides can be passed as environment variables.
1051 $script_dir = $info->script_dir();
1052 $env_prefix = uc($info->host_name()) . '_';
1053 $env_prefix =~ tr/\./_/; # dots in hostnames become underscores in env var names
1054 # Config::Abstraction returns nothing, rather than an object, when no file
1055 # matches the domain: a vhost that has not been given a config file yet, the
1056 # command line test in the POD, or CI, where the hostname is a container id.
1057 # That is not fatal, so the logger is built with no configuration and the
1058 # framework carries on with its defaults - dying here would take the site down
1059 # over a configuration file that is only there to describe it. The reason is
1060 # reported once rather than on every request.
1061 $config_abstraction = Config::Abstraction->new(env_prefix => $env_prefix, flatten => 0, config_file => $info->domain_name(), config_dirs => ["$script_dir/../conf/", "$script_dir/../../conf"]);
1062 $logger = Log::Abstraction->new($config_abstraction ? $config_abstraction->all() : {});
1063 Log::WarnDie->dispatcher($logger);
1064  
1065 unless($config_abstraction) {
1066 $logger->warn('No configuration file for ', ($info->domain_name() // '(unknown host)'), " in $script_dir/../conf/ or $script_dir/../../conf; using the defaults");
1067 }
1068 }
1069  
1070 sub run
1071 {
1072 my $self = shift;
1073  
1074 # A nested call means something has executed the page script again while
1075 # it was running or still compiling - for example a configuration reader
1076 # that took the script for its own configuration file and evaluated it.
1077 # Refuse, loudly, on STDERR: a die here would be swallowed by that reader's
1078 # eval, and carrying on would consume the server's requests.
1079 if($RUNNING || (${^GLOBAL_PHASE} ne 'RUN')) {
1080 print STDERR __PACKAGE__, '::run() called re-entrantly or during compilation (phase ',
1081 ${^GLOBAL_PHASE}, '); is the script being read as its own configuration file?', "\n";
1082 return;
1083 }
1084 local $RUNNING = 1;
1085  
1086 $self->_init();
1087  
1088 # my $request = FCGI::Request($stdin, $stdout, $stderr);
1089 my $request = FCGI::Request();
1090  
1091 # --- Main FCGI request loop ---------------------------------------------------
1092 # Accept() blocks until the web server sends a new request. It returns a
1093 # negative value when the server wants this worker to exit (e.g. graceful
1094 # shutdown), which breaks the loop naturally.
1095 while($handling_request = ($request->Accept() >= 0)) {
1096 # REMOTE_ADDR is absent when running from the command line for testing.
1097 # Switch to a verbose debug logger and single-shot mode in that case.
1098 unless($ENV{'REMOTE_ADDR'}) {
1099 my $timer = Timer::Simple->new();
1100  
1101 # Disable all caching so every run reflects the current templates.
1102 $ENV{'NO_CACHE'} = 1;
1103  
1104 # Map the LANG shell variable to the HTTP Accept-Language header so
1105 # that language detection works the same way it does in production.
1106 if((!defined($ENV{'HTTP_ACCEPT_LANGUAGE'})) && defined($ENV{'LANG'})) {
1107 my $lang = $ENV{'LANG'};
1108 $lang =~ s/\..*$//; # strip encoding suffix (e.g. .UTF-8)
1109 $lang =~ tr/_/-/; # POSIX uses _, HTTP uses -
1110 $ENV{'HTTP_ACCEPT_LANGUAGE'} = lc($lang);
1111 }
1112  
1113 Database::Abstraction::init({ logger => $logger });
1114  
1115 # Replace the production logger with a simple STDOUT printer.
1116 $logger = Log::Abstraction->new(logger => sub { print join(', ', @{$_[0]->{'message'}}), "\n" }, level => 'debug');
1117 Log::WarnDie->dispatcher($logger);
1118 $info->set_logger($logger);
1119 $self->_set_data_loggers($logger);
1120  
1121 # Enable full stack traces in Error.pm for command-line debugging.
1122 $Error::Debug = 1;
1123 try {
1124 $self->_doit(debug => 1);
1125 } catch Error with {
1126 my $msg = shift;
1127 warn "$msg\n", $msg->stacktrace();
1128 $logger->error($msg);
1129 };
1130  
1131 # Report wall-clock time taken for this command-line invocation.
1132 my @elapsed_time = $timer->hms();
1133 my $timetaken = int($elapsed_time[2] * 1000);
1134 $logger->info("$self->{script_name} completed in ${timetaken}ms");
1135  
1136 last; # command-line mode is single-shot; exit the accept loop
1137 }
1138  
1139 # -- Live HTTP request --------------------------------------------------
1140 $requestcount++;
1141 $logger->info("Request $requestcount: ", $ENV{'REMOTE_ADDR'});
1142  
1143 # Propagate the current logger to all data-access objects that may emit
1144 # log messages during this request.
1145 $info->set_logger($logger);
1146 $self->_set_data_loggers($logger);
1147  
1148 # Dispatch the request. Any unhandled Error.pm exception is caught here
1149 # so a single bad request cannot kill the FCGI worker process.
1150 try {
1151 $self->_doit(debug => 0);
1152 } catch Error with {
1153 my $msg = shift;
1154 $logger->error("$msg: ", $msg->stacktrace());
1155 # Invalidate the response cache on error so a stale error page is
1156 # never served to subsequent clients.
1157 if($buffercache) {
1158 $buffercache->clear();
1159 $buffercache = undef;
1160 }
1161 };
1162  
1163 $request->Finish();
1164  
1165 $handling_request = 0;
1166 if($exit_requested) {
1167 last;
1168 }
1169 if($ENV{SCRIPT_FILENAME}) {
1170 if(-M $ENV{SCRIPT_FILENAME} < 0) {
1171 last;
1172 }
1173 }
1174 }
1175 }
1176  
1177 # --- doit() - per-request handler --------------------------------------------
1178 # Called once per FCGI iteration. Handles security checks, language detection,
1179 # template dispatch, response caching, and access logging.
1180 sub _doit
1181 {
1182 my $self = shift;
1183  
1184 # Record the wall-clock start time so we can report request duration later.
1185 my $request_start = Timer::Simple->new();
1186  
1187 # CGI::Info caches state between calls; reset it so this request gets a
1188 # fresh view of the environment rather than stale values from the last one.
1189 CGI::Info->reset();
1190  
1191 my %params = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
1192  
1193 # $config is built once per process and reused. We cannot build it before
1194 # the first Accept() because the domain name is not known until then.
1195 # So don't pass $info in since it was created before the connection
1196 $config ||= Web::VWF::Config->new({
1197 directory => $self->_directory(),
1198 logger => $logger,
1199 debug => $params{'debug'},
1200 # A throwaway CGI::Lingua is used here only to satisfy Web::VWF::Config;
1201 # the real, cache-backed instance is created further below. It has to be
1202 # given the default languages rather than the site's configured ones:
1203 # this call is what reads the configuration, so the site's list is not
1204 # known yet.
1205 lingua => CGI::Lingua->new({ supported => [ @DEFAULT_SUPPORTED_LANGUAGES ], info => $info, logger => $logger })
1206 });
1207  
1208 # The site's own settings - its database directory, data modules, languages
1209 # and trusted addresses - are read from that configuration, once per process.
1210 $self->_site_setup($config);
1211  
1212 # deny_cloud() blocks all known cloud provider address ranges (AWS, GCP,
1213 # Azure) which generate almost no legitimate human traffic but are a
1214 # common origin for automated scanning. Geo-blocking is a blunt
1215 # instrument but effective at reducing noise. It is also why an address a
1216 # site allows here is still refused if its reverse DNS says it is in a cloud.
1217 $acl ||= CGI::ACL->new()
1218 ->deny_cloud()
1219 ->deny_country(country => Web::VWF::Blacklist->new(countries => $config->{'blacklist_countries'})->countries());
1220  
1221 foreach my $ip ($self->_config_list($config, 'allow_ips', @DEFAULT_ALLOW_IPS)) {
1222 $acl->allow_ip($ip);
1223 }
1224  
1225 unless(@valid_pages) {
1226 @valid_pages = $self->_valid_pages($config);
1227 %page_description = $self->_page_descriptions($config);
1228 %page_directory = $self->_page_directories($config, @valid_pages);
1229 }
1230  
1231 # These caches are created lazily on the first request and reused across the
1232 # FCGI accept loop to amortise the cost of cache initialisation.
1233 # The CGI::Info disc cache stores parsed request data across FCGI restarts.
1234 $self->{info_cache} ||= create_disc_cache(config => $config, logger => $logger, namespace => 'CGI::Info');
1235  
1236 my $options = {
1237 cache => $self->{info_cache},
1238 logger => $logger
1239 };
1240  
1241 # If syslog is configured, normalise the 'server' key to 'host' (the
1242 # Sys::Syslog convention) and pass the stanza to CGI::Info.
1243 my $syslog;
1244 if($syslog = $config->syslog()) {
1245 if($syslog->{'server'}) {
1246 $syslog->{'host'} = delete $syslog->{'server'};
1247 }
1248 $options->{'syslog'} = $syslog;
1249 }
1250 # Rebuild $info now that we have a cache and the domain is known.
1251 $info = CGI::Info->new($options);
1252 $logger->debug('In doit - domain is ', $info->domain_name());
1253  
1254 # Lazily initialise the in-memory rate-limit counter store.
1255 $rate_limit_cache ||= create_memory_cache(config => $config, logger => $logger, namespace => 'rate_limit');
1256  
1257 # Use the real remote IP as the rate-limit key; fall back to 'unknown'
1258 # only in the unlikely event that REMOTE_ADDR is absent.
1259 my $client_ip = $ENV{'REMOTE_ADDR'} || 'unknown';
1260  
1261 # A successful CAPTCHA solve stores a short-lived bypass token in the cache.
1262 # While the token is present the client is exempt from rate-limit checks.
1263 my $captcha_bypass_key = "$self->{script_name}:captcha_bypass:$client_ip";
1264 my $has_captcha_bypass = $rate_limit_cache->get($captcha_bypass_key);
1265  
1266 # Allow the thresholds to be tuned via the config file; fall back to the
1267 # compile-time constants if the stanza is missing.
1268 my $max_requests = $config->{'security'}->{'rate_limiting'}->{'max_requests'} || $MAX_REQUESTS;
1269 my $max_requests_hard = $config->{'security'}->{'rate_limiting'}->{'max_requests_hard'} || ($max_requests * 1.5);
1270  
1271 # This client's count in the present rate-limit window, and what is left of
1272 # that window for the Retry-After header (RFC 9110 section 10.2.3)
1273 my $rate_limit_key = "$self->{script_name}:rate_limit:$client_ip";
1274 my $time_window = $config->{'security'}->{'rate_limiting'}->{'time_window'} || $TIME_WINDOW;
1275 my $window = _rate_window($rate_limit_cache, $rate_limit_key, duration_seconds($time_window));
1276 my $request_count = $window->{'count'};
1277 my $retry_after = $window->{'expires'} - time();
1278  
1279 # Check if this is a CAPTCHA verification attempt
1280 if ($info->param('g-recaptcha-response')) {
1281 unless(Web::VWF::CAPTCHA->can('new')) {
1282 require Web::VWF::CAPTCHA;
1283 Web::VWF::CAPTCHA->import();
1284 }
1285  
1286 my $recaptcha_config = $config->recaptcha();
1287 if ($recaptcha_config && $recaptcha_config->{enabled}) {
1288 my $captcha = Web::VWF::CAPTCHA->new(
1289 site_key => $recaptcha_config->{site_key},
1290 secret_key => $recaptcha_config->{secret_key},
1291 logger => $logger
1292 );
1293  
1294 if ($captcha->verify($info->param('g-recaptcha-response'), $client_ip)) {
1295 # CAPTCHA verified - grant bypass
1296 my $bypass_duration = $config->{'security'}->{'rate_limiting'}->{'captcha_bypass_duration'} || '300s';
1297 $rate_limit_cache->set($captcha_bypass_key, 1, $bypass_duration);
1298 $rate_limit_cache->remove($rate_limit_key); # Reset the counter
1299  
1300 $logger->info("CAPTCHA verified for $client_ip - rate limit bypass granted");
1301 $has_captcha_bypass = 1;
1302  
1303 # Redirect the client back to the page they were trying to reach.
1304 # SECURITY - CRLF / header-injection defence:
1305 # Both the page name and SCRIPT_NAME are interpolated into the
1306 # Location header. A raw %0d%0a sequence in either value would
1307 # let an attacker inject arbitrary HTTP response headers
1308 # (response-splitting / header-injection).
1309 # Strip $redirect_page to a strict allowlist (word chars and
1310 # hyphens only), and remove any embedded CR or LF from the
1311 # server-supplied SCRIPT_NAME before building the header.
1312 my $redirect_page = $info->param('page') || 'index';
1313 $redirect_page =~ s/[^A-Za-z0-9_-]//g;
1314  
1315 # Also sanitize the server variable - it is attacker-influenced
1316 # in some reverse-proxy configurations.
1317 my $script = $ENV{SCRIPT_NAME} // '/cgi-bin/page.fcgi';
1318 $script =~ s/[\r\n]//g;
1319  
1320 $info->status(302);
1321 print "Status: 302 Found\r\n",
1322 "Location: ${script}?page=${redirect_page}\r\n\r\n";
1323 return;
1324 } else {
1325 $logger->warn("CAPTCHA verification failed for $client_ip");
1326 # Fall through to show CAPTCHA again
1327 }
1328 }
1329 }
1330  
1331 $vwflog ||= $config->vwflog() || File::Spec->catfile($info->logdir(), 'vwf.log');
1332 # Reader for the CSV access log, used by the meta_data page.
1333 # Created from the same path that vwflog() writes to, which needs $config.
1334 $self->{vwf_log} ||= Web::VWF::Data::vwf_log->new({
1335 directory => dirname($vwflog),
1336 filename => basename($vwflog),
1337 no_entry => 1,
1338 logger => $logger,
1339 });
1340 _discard_config_rows($self->{vwf_log});
1341 my $log = Class::Simple->new();
1342  
1343 # Stores things for a month or longer
1344 $lingua_cache ||= create_disc_cache(config => $config, logger => $logger, namespace => 'CGI::Lingua');
1345  
1346 # Language negotiation, offering the languages this site offers
1347 my $lingua = CGI::Lingua->new({
1348 supported => \@supported_languages,
1349 cache => $lingua_cache,
1350 info => $info,
1351 logger => $logger,
1352 debug => $params{'debug'},
1353 syslog => $syslog,
1354 });
1355  
1356 my $cachedir = Web::VWF::Utils::env_cache_dir() || $params{'cachedir'} || $config->{disc_cache}->{root_dir} || File::Spec->catfile($tmpdir, 'cache');
1357  
1358 # Count this request before the limits are applied, because the ones answered
1359 # with a CAPTCHA must count too or the hard limit is never reached.
1360 # $request_count stays the number before this one. The expiry is the end of
1361 # the window that is already running, so that further requests do not put it
1362 # off.
1363 $window->{'count'}++;
1364 $rate_limit_cache->set($rate_limit_key, $window, { expires_at => $window->{'expires'} });
1365  
1366 # Rate limit by IP (unless bypassed)
1367 unless($has_captcha_bypass || grep { $_ eq $client_ip } @rate_limit_trusted_ips) {
1368 if ($request_count >= $max_requests_hard) {
1369 # Hard limit exceeded - show CAPTCHA with warning
1370 my $recaptcha_config = $config->recaptcha();
1371  
1372 if ($recaptcha_config && $recaptcha_config->{enabled}) {
1373 $logger->warn("Hard rate limit exceeded for $client_ip ($request_count requests)");
1374 $info->status(429);
1375  
1376 unless(Web::VWF::Display::captcha->can('new')) {
1377 require Web::VWF::Display::captcha;
1378 Web::VWF::Display::captcha->import();
1379 }
1380 my $display = Web::VWF::Display::captcha->new({
1381 cachedir => $cachedir,
1382 info => $info,
1383 logger => $logger,
1384 lingua => $lingua,
1385 config => $config,
1386 });
1387  
1388 # new() returns undef when it refuses the client, for example
1389 # when its own throttle has tripped
1390 if($display) {
1391 print 'Status: 429 ', HTTP::Status::status_message(429), "\n";
1392 print $display->as_string({
1393 'Retry-After' => $retry_after,
1394 Retry_After => $retry_after,
1395 hard_block => 1,
1396 request_count => $request_count,
1397 });
1398  
1399 $self->_vwflog($vwflog, $info, $lingua, $syslog, 'Hard rate limit - CAPTCHA shown', $log, $request_start);
1400 return;
1401 }
1402 $logger->info("Unable to show captcha page - request count = $request_count");
1403 }
1404  
1405 # No CAPTCHA to offer, so block until the window expires
1406 $logger->warn("Hard rate limit exceeded for $client_ip ($request_count requests)") unless($recaptcha_config && $recaptcha_config->{enabled});
1407 send_error(status => 429, body => "Too many requests - try again later\n", headers => "Retry-After: $retry_after\n");
1408 $self->_vwflog($vwflog, $info, $lingua, $syslog, 'Hard rate limit', $log, $request_start);
1409 return;
1410 } elsif ($request_count >= $max_requests) {
1411 # Soft limit exceeded - show CAPTCHA
1412 my $recaptcha_config = $config->recaptcha();
1413  
1414 if ($recaptcha_config && $recaptcha_config->{enabled}) {
1415 $logger->info("Soft rate limit exceeded for $client_ip ($request_count requests) - CAPTCHA challenge issued");
1416 $info->status(429);
1417  
1418 unless(Web::VWF::Display::captcha->can('new')) {
1419 require Web::VWF::Display::captcha;
1420 Web::VWF::Display::captcha->import();
1421 }
1422 my $display = Web::VWF::Display::captcha->new({
1423 cachedir => $cachedir,
1424 info => $info,
1425 logger => $logger,
1426 lingua => $lingua,
1427 config => $config,
1428 });
1429  
1430 if($display) {
1431 print $display->as_string({
1432 'Retry-After' => $retry_after,
1433 Retry_After => $retry_after,
1434 hard_block => 0,
1435 request_count => $request_count,
1436 });
1437  
1438 $self->_vwflog($vwflog, $info, $lingua, $syslog, 'Soft rate limit - CAPTCHA shown', $log, $request_start);
1439 } else {
1440 # Not an error: new() refuses clients on purpose. Something
1441 # must still be sent, or the web server reports a 500.
1442 $logger->info("Unable to show captcha page - request count = $request_count");
1443 send_error(status => 429, body => "Too many requests - try again later\n", headers => "Retry-After: $retry_after\n");
1444 $self->_vwflog($vwflog, $info, $lingua, $syslog, 'Soft rate limit - CAPTCHA not shown', $log, $request_start);
1445 }
1446 return;
1447 }
1448 }
1449 }
1450  
1451 # A request with no page parameter cannot be dispatched; send a 300
1452 # response listing the known valid pages instead.
1453 if(!defined($info->param('page'))) {
1454 $logger->info('No page given in ', $info->as_string());
1455 choose();
1456 return;
1457 }
1458  
1459 # Multi-layer access control
1460 # Three independent checks are run in order of cheapness:
1461 # 1. CGI::ACL - cloud ranges, country blocks, explicit IP allow/deny.
1462 # 2. blacklisted() - in-process IP set built from prior SQL-injection attempts.
1463 # 3. Web::VWF::Allow - DShield feed, user-agent blacklist, throttler, IDS.
1464 if(my $remote_addr = $ENV{'REMOTE_ADDR'}) {
1465 my $reason;
1466 if($acl->all_denied(lingua => $lingua)) {
1467 $reason = 'Denied by CGI::ACL';
1468 } elsif(blacklisted($info)) {
1469 $reason = 'Blacklisted for attempting to break in';
1470 } else {
1471 # Web::VWF::Allow may throw an Error object when it blocks a request.
1472 # Catch it here so the 403 response is sent rather than propagating.
1473 try {
1474 unless(Web::VWF::Allow::allow({
1475 info => $info,
1476 lingua => $lingua,
1477 logger => $logger,
1478 cache => $rate_limit_cache,
1479 config => $config,
1480 })) {
1481 $reason = 'Blocked by Web::VWF::Allow';
1482 }
1483 } catch Error with {
1484 $reason = shift;
1485 };
1486 }
1487 if($reason) {
1488 # Return a minimal plain-text 403 - no template rendering so that
1489 # a blocked attacker receives no information about site structure.
1490 send_error(status => 403, body => "Access Denied\n");
1491 $logger->info("$remote_addr: access denied: $reason");
1492 $info->status(403);
1493 $self->_vwflog($vwflog, $info, $lingua, $syslog, $reason, $log, $request_start);
1494 return;
1495 }
1496 }
1497  
1498 # -- FCGI::Buffer setup ------------------------------------------------
1499 # FCGI::Buffer post-processes the output: compresses it, generates an ETag
1500 # and Last-Modified header, and serves a 304 Not Modified when appropriate.
1501 my $args = {
1502 generate_etag => 1,
1503 generate_last_modified => 1,
1504 compress_content => 1,
1505 generate_304 => 1,
1506 info => $info,
1507 optimise_content => 1,
1508 logger => $logger,
1509 # lint_content runs HTML::Tidy on the output; enable in debug mode or
1510 # when explicitly requested via the lint_content query parameter.
1511 lint_content => $info->param('lint_content') // $params{'debug'},
1512 lingua => $lingua
1513 };
1514  
1515 if((!$info->is_search_engine()) && $config->root_dir() &&
1516 ($info->param('page') ne 'home') &&
1517 ((!defined($info->param('action'))) || ($info->param('action') ne 'send'))) {
1518 $args->{'save_to'} = {
1519 directory => File::Spec->catfile($config->root_dir(), 'save_to'),
1520 ttl => 3600 * 24,
1521 create_table => 1
1522 };
1523 }
1524  
1525 my $fb = FCGI::Buffer->new()->init($args);
1526  
1527 if($fb->can_cache()) {
1528 my $cache_key = join('/',
1529 'FCGI::Buffer',
1530 $info->browser_type(),
1531 $info->domain_name(),
1532 $self->{script_name},
1533 $info->as_string(),
1534 $lingua->language()
1535 );
1536 $cache_key =~ s/;string=%5Bobject%20HTMLInputElement%5D//;
1537 $cache_key =~ s/;string=\[object HTMLInputElement\]//;
1538 if($info->param('location')) {
1539 $cache_key .= '/' . $info->param('location');
1540 }
1541 $logger->debug("enabling cache key $cache_key");
1542  
1543 $buffercache ||= create_disc_cache(config => $config, logger => $logger, namespace => $self->{script_name}, root_dir => $cachedir);
1544 $fb->init(
1545 cache_key => $cache_key,
1546 cache => $buffercache,
1547 # generate_304 => 0,
1548 cache_duration => '1 day',
1549 );
1550 if($fb->is_cached()) {
1551 return;
1552 }
1553 }
1554  
1555 # $display holds the instantiated Web::VWF::Display subclass when the page is
1556 # found; $invalidpage is set when the page name is invalid or unloadable.
1557 my $display;
1558 my $invalidpage;
1559  
1560 # Arguments forwarded to every Web::VWF::Display subclass constructor. The
1561 # server's directory is among them because a page reads its configuration for
1562 # itself, and has to look where this script did.
1563 $args = {
1564 cachedir => $cachedir,
1565 info => $info,
1566 logger => $logger,
1567 lingua => $lingua,
1568 config => $config,
1569 server_directory => $SERVER_CONF_DIR,
1570 log => $log
1571 };
1572  
1573 # -- Page dispatch ------------------------------------------------------
1574 # The outer block eval catches any exception thrown during module loading
1575 # or display-object construction, setting $@ for inspection below.
1576 eval {
1577 my $page = $info->param('page');
1578  
1579 # Strip URL fragment identifiers - the server never needs them.
1580 $page =~ s/#.*$//;
1581  
1582 # Reject backslashes: no legitimate page name contains one, and
1583 # they have historically been used to probe Windows path traversal.
1584 $page =~ s/\\//g;
1585  
1586 if($page =~ /\//) {
1587 # A slash in the page name indicates an attempt to traverse
1588 # directories (e.g. page=/etc/passwd or page=http://evil.com).
1589 $logger->info("Blocking '/' in $page");
1590 $info->status(403);
1591 $log->status(403);
1592 $invalidpage = 1;
1593 } else {
1594 # Strip every non-word character so that the page name can only
1595 # contain [A-Za-z0-9_] - safe to use as a Perl package suffix.
1596 $page =~ s/\W//g;
1597 $page =~ s/\s//g;
1598 }
1599  
1600 if($invalidpage) {
1601 # Already rejected above
1602 } elsif(!grep { $_ eq $page } @valid_pages) {
1603 # Only pages on the allow-list are loaded, so that no other
1604 # Web::VWF::Display::* module that happens to be on @INC (e.g. under
1605 # ~/lib/perl5) can be reached from the query string.
1606 $logger->info("Unknown page $page");
1607 $invalidpage = 1;
1608 if($info->status() == 200) {
1609 $info->status(404);
1610 }
1611 } else {
1612 my $display_module = "Web::VWF::Display::$page";
1613  
1614 $logger->debug("doit(): Loading module $display_module from ", $page_directory{$page} // '@INC');
1615 unless($display_module->can('new')) {
1616 # String-eval elimination:
1617 # The original code used eval "require $display_module" which is a
1618 # string eval on a user-derived value. Although $page has been
1619 # stripped of \W characters, a Unicode or locale edge-case could
1620 # allow a bypass. Module::Runtime::require_module() loads a module
1621 # by name using a block eval internally, with no string-eval surface.
1622 #
1623 # A page with a directory is loaded from its file there instead
1624 # of from @INC. Its name has been checked against the valid
1625 # pages, which are \w+ only, so the path cannot leave the
1626 # directory.
1627 if(my $dir = $page_directory{$page}) {
1628 my $file = File::Spec->catfile($dir, "$page.pm");
1629 eval { -f $file or die "No such file $file\n"; require $file };
1630 } else {
1631 eval { require_module($display_module) };
1632 }
1633 $display_module->import() unless $@;
1634 }
1635 if($@) {
1636 $logger->debug("Failed to load module $display_module: $@");
1637 $logger->info("Unknown page $page");
1638 $invalidpage = 1;
1639 if($info->status() == 200) {
1640 $info->status(404);
1641 }
1642 } else {
1643 # use Class::Inspector;
1644 # my $methods = Class::Inspector->methods($display_module);
1645 # print "$display_module exports ", join(', ', @{$methods}), "\n";
1646 $display = do {
1647 eval { $display_module->new($args) };
1648 };
1649 if(!defined($display)) {
1650 if($@) {
1651 $logger->warn("$display_module->new(): $@");
1652 } else {
1653 $logger->notice("Can't instantiate page $page");
1654 }
1655 $invalidpage = 1;
1656 if($info->status() == 200) {
1657 $info->status(404);
1658 }
1659 } elsif(!$display->can('as_string')) {
1660 $logger->warn("Problem understanding $page");
1661 undef $display;
1662 }
1663 }
1664 }
1665 };
1666  
1667 my $error = $@;
1668 if($error) {
1669 if($info->status() == 429) {
1670 $logger->notice($error);
1671 } else {
1672 $logger->error($error);
1673 }
1674 $display = undef;
1675 }
1676  
1677 if(defined($display)) {
1678 # A request is logged after its page is made, so on a new site, or after
1679 # the log has been rotated away, there is no file for meta_data to read.
1680 # Failing to make one must not stop pages that never look at it.
1681 eval { _create_vwflog($vwflog) };
1682 $logger->warn("Can't create $vwflog: $@") if($@);
1683  
1684 # Pass in handles to the databases: the site's own data handles, under
1685 # the name each was declared with, and the access log, which the
1686 # framework reads from the log it writes.
1687 print $display->as_string({
1688 cachedir => $cachedir,
1689 config => $config,
1690 databasedir => $database_dir,
1691 database_dir => $database_dir,
1692 %data,
1693 vwf_log => $self->{vwf_log},
1694 });
1695 $self->_vwflog($vwflog, $info, $lingua, $syslog, '', $log, $request_start);
1696 } elsif($invalidpage) {
1697 if($info->status() == 429) {
1698 # Throttled by Web::VWF::Display
1699 my $interval = $config->{'throttle'}->{'interval'} // 90;
1700 send_error(status => 429, body => "Too many requests - try again later\n", headers => "Retry-After: $interval\n", buffered => 1);
1701 $self->_vwflog($vwflog, $info, $lingua, $syslog, 'Throttled', $log, $request_start);
1702 } else {
1703 choose();
1704 $self->_vwflog($vwflog, $info, $lingua, $syslog, 'Unknown page', $log, $request_start);
1705 }
1706 return;
1707 } else {
1708 $logger->debug('disabling cache');
1709 $fb->init(
1710 cache => undef,
1711 );
1712 # Handle errors gracefully
1713 my ($status, $body);
1714 if($error eq 'Unknown page to display') {
1715 ($status, $body) = (400, "I don't know what you want me to display.\n");
1716 } elsif($error =~ /Can\'t locate .* in \@INC/) {
1717 $logger->error($error);
1718 ($status, $body) = (500, "Software error - contact the webmaster\n");
1719 } elsif(($info->status() == 200) || ($info->status() == 403)) {
1720 # No permission to show this page
1721 ($status, $body) = (403, "Access Denied\n");
1722 } else {
1723 $status = $info->status();
1724 $body = "Page unavailable - something is wrong at your end, please fix and try again\n";
1725 }
1726 send_error(status => $status, body => $body, buffered => 1);
1727 $log->status($status);
1728 $self->_vwflog($vwflog, $info, $lingua, $syslog, $error ? $error : 'Access denied', $log, $request_start);
1729 throw Error::Simple($error ? $error : $info->as_string());
1730 }
1731 }
1732  
1733 # Send a 300 Multiple Choices response listing the pages this site serves.
1734 # Called when the ?page= parameter is absent or the requested page is unknown.
1735 sub choose
1736 {
1737 $logger->info('Called with no page to display');
1738  
1739 my $status = $info->status();
1740  
1741 # If the status is already non-200 (e.g. 404 set by the caller), relay
1742 # that status rather than overriding it with a 300. That only happens
1743 # for an invalid page, after FCGI::Buffer has been set up, and it sends
1744 # the Status line from $info->status() itself.
1745 return if($status != 200);
1746  
1747 print "Status: 300 Multiple Choices\n",
1748 "Content-type: text/plain\n";
1749  
1750 $info->status(300);
1751  
1752 # Include a Last-Modified header based on the script's mtime so that
1753 # caches and conditional-GET clients can revalidate efficiently.
1754 if(my $path = $info->script_path()) {
1755 require HTTP::Date;
1756 HTTP::Date->import();
1757  
1758 my @statb = stat($path);
1759 my $mtime = $statb[9];
1760 print 'Last-Modified: ', HTTP::Date::time2str($mtime), "\n";
1761 }
1762  
1763 print "\n";
1764  
1765 # RFC 7231 section 4.3.2: a HEAD response must not include a body.
1766 unless($ENV{'REQUEST_METHOD'} && ($ENV{'REQUEST_METHOD'} eq 'HEAD')) {
1767 # The same list that doit() allows, so the two cannot differ
1768 print map {
1769 "/cgi-bin/page.fcgi?page=$_" . (length($page_description{$_} // '') ? " - $page_description{$_}" : '') . "\n"
1770 } @valid_pages;
1771 }
1772 }
1773  
1774 # Send a short plain-text error response, and record its status in $info.
1775 # status - the HTTP status code
1776 # body - the text to send (not sent for HEAD)
1777 # headers - optional extra header lines, each ending in "\n", e.g. Retry-After
1778 # buffered - true once FCGI::Buffer is capturing the output. It sends the
1779 # Status line from $info->status(), so it mustn't be printed here too.
1780 sub send_error
1781 {
1782 my %args = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
1783 my $status = $args{'status'};
1784  
1785 $info->status($status);
1786  
1787 print 'Status: ', $status, ' ', HTTP::Status::status_message($status), "\n" unless($args{'buffered'});
1788 print $args{'headers'} // '',
1789 "Content-type: text/plain\n",
1790 "Pragma: no-cache\n\n";
1791  
1792 # RFC 9110 section 9.3.2: a HEAD response must not include a body.
1793 my $is_head = $ENV{'REQUEST_METHOD'} && ($ENV{'REQUEST_METHOD'} eq 'HEAD');
1794 print $args{'body'} if(defined($args{'body'}) && !$is_head);
1795  
1796 return 1;
1797 }
1798  
1799 # A list-valued setting: what the configuration file says about it, or the
1800 # caller's defaults when it says nothing about it. A list can be written as one
1801 # string of values separated by commas or spaces, which is what the plain form
1802 # of a configuration file gives, or as an element with one child per value,
1803 # which is what an XML file gives; both are read, so an XML file can hold a list
1804 # in whichever of the two ways reads better. The values are returned as they
1805 # were written and in the order they were written, with repetitions dropped, and
1806 # a setting that is present but empty means no values at all - so that a site can
1807 # say "none" as well as saying nothing.
1808 sub _config_list
1809 {
1810 # The invocant is not used: the setting and its defaults are all this needs.
1811 my (undef, $config, $key, @defaults) = @_;
1812  
1813 my $value = $config->{$key};
1814 return @defaults unless(defined($value));
1815  
1816 my @values;
1817 if(ref($value) eq 'HASH') {
1818 # One child per value; the names of the children are not used
1819 foreach my $child (values %{$value}) {
1820 push(@values, ref($child) eq 'ARRAY' ? @{$child} : $child);
1821 }
1822 } elsif(ref($value) eq 'ARRAY') {
1823 @values = @{$value};
1824 } else {
1825 @values = split /[\s,]+/, $value;
1826 }
1827  
1828 my %seen;
1829 return grep { defined($_) && length($_) && !$seen{$_}++ } @values;
1830 }
1831  
1832 # The <display> setting, named after the Web::VWF::Display directory the pages
1833 # live in. A site written before the rename used <pages>, which is still read
1834 # when there is no <display>.
1835 sub _display_setting
1836 {
1837 my $config = shift;
1838  
1839 return $config->{'display'} // $config->{'pages'};
1840 }
1841  
1842 # The pages the site's configuration file declares, as a list of
1843 # { name => ..., description => ... } in the order they were written:
1844 # <display>
1845 # <page><name>states</name><description>About the U.S. states</description></page>
1846 # <directory>/path/to/pages</directory>
1847 # </display>
1848 # A <directory> in <display> is where the page modules are looked for, and the
1849 # list of pages when there are no <page>s (see _valid_pages); one in a <page>
1850 # is where that page's module is, and beats the one in <display>. One <page> is read as a hash and several as an array, so both are handled.
1851 # The old form, a single string of names (<pages>index, meta_data</pages>), is
1852 # still read, with no descriptions, so existing sites keep working. A page
1853 # without a usable name is dropped, and so is a repeated one, since the same
1854 # file can be loaded more than once when the configuration is merged.
1855 sub _config_pages
1856 {
1857 my (undef, $config) = @_;
1858  
1859 return _config_entries(_display_setting($config), 'page');
1860 }
1861  
1862 # The common reader for a setting that is a list of named things, each with an
1863 # optional description and directory: the elements called $item inside $setting
1864 # (a hash), or the array or string of names of the old form. Returns
1865 # { name, description, directory } hashes, in order, without repetitions.
1866 sub _config_entries
1867 {
1868 my ($setting, $item) = @_;
1869  
1870 return unless(defined($setting));
1871  
1872 my @entries;
1873 if(ref($setting) eq 'HASH') {
1874 my $found = $setting->{$item};
1875 return unless(defined($found));
1876 @entries = (ref($found) eq 'ARRAY') ? @{$found} : ($found);
1877 } elsif(ref($setting) eq 'ARRAY') {
1878 @entries = @{$setting};
1879 } else {
1880 @entries = split /[\s,]+/, $setting;
1881 }
1882  
1883 my (%seen, @found);
1884 foreach my $entry (@entries) {
1885 next unless(defined($entry));
1886 my ($name, $description, $directory) = (ref($entry) eq 'HASH') ? @{$entry}{qw(name description directory)} : ($entry, undef, undef);
1887 next unless(defined($name) && !ref($name) && length($name));
1888 next if($seen{$name}++);
1889 push @found, {
1890 name => $name,
1891 description => (defined($description) && !ref($description)) ? $description : '',
1892 directory => (defined($directory) && !ref($directory)) ? $directory : '',
1893 };
1894 }
1895 return @found;
1896 }
1897  
1898 # The pages that ?page= may load. Sites declare them in the config file (see
1899 # _config_pages); otherwise every *.pm in the page directory is allowed, except
1900 # captcha, which only the rate limiter shows. The page directory is
1901 # <display><directory>, or ../lib/Web/VWF/Display next to this script.
1902 sub _valid_pages
1903 {
1904 my $self = shift;
1905 my $config = shift;
1906  
1907 my @pages = map { $_->{'name'} } $self->_config_pages($config);
1908 return grep { /\A\w+\z/ } @pages if(@pages);
1909  
1910 # <display><directory> overrides where the page modules are looked for.
1911 # Only the default has the framework's own hard-coded layout.
1912 my $dir = $self->_pages_directory($config);
1913 unless(defined($dir)) {
1914 # FIXME: Remove the hard coding
1915 $dir = File::Spec->catdir($script_dir, File::Spec->updir(), 'lib', 'Web', 'VWF', 'Display');
1916 }
1917 # The list is built first rather than returned from inside sort(): a sort
1918 # that is returned directly takes the caller's context, and sort in scalar
1919 # context has no defined meaning.
1920 my @found = sort(grep { $_ ne 'captcha' } map { basename($_, '.pm') } glob(File::Spec->catfile($dir, '*.pm')));
1921 return @found;
1922 }
1923  
1924 # A directory from the configuration, made absolute: a relative one is taken
1925 # from the script's directory, as the default is. Undef if there isn't one.
1926 sub _resolve_directory
1927 {
1928 my $directory = shift;
1929  
1930 # An explicit undef, not a bare return: this is used inside map, where an
1931 # empty list would unbalance the hash being built
1932 return undef unless(defined($directory) && !ref($directory) && length($directory)); ## no critic (ProhibitExplicitReturnUndef)
1933 return File::Spec->file_name_is_absolute($directory) ? $directory : File::Spec->catdir($script_dir, $directory);
1934 }
1935  
1936 # <display><directory>, resolved, or undef
1937 sub _pages_directory
1938 {
1939 my (undef, $config) = @_;
1940  
1941 my $display = _display_setting($config);
1942 return unless(ref($display) eq 'HASH');
1943 return _resolve_directory($display->{'directory'});
1944 }
1945  
1946 # name => directory for each of the given pages whose module is not simply in
1947 # @INC: the page's own <directory>, else <display><directory> if there is one.
1948 sub _page_directories
1949 {
1950 my ($self, $config, @pages) = @_;
1951  
1952 my $default = $self->_pages_directory($config);
1953 my %own = map { $_->{'name'} => _resolve_directory($_->{'directory'}) } $self->_config_pages($config);
1954  
1955 my %directory;
1956 foreach my $page (@pages) {
1957 my $dir = $own{$page} // $default;
1958 $directory{$page} = $dir if(defined($dir));
1959 }
1960 return %directory;
1961 }
1962  
1963 # name => description for each page the configuration describes
1964 sub _page_descriptions
1965 {
1966 my ($self, $config) = @_;
1967  
1968 return map { $_->{'name'} => $_->{'description'} } grep { length($_->{'description'}) } $self->_config_pages($config);
1969 }
1970  
1971 # The directory the site's data files (CSV, XML, SQLite) are in:
1972 # <databases><directory>/path/to/files</directory></databases>
1973 # else the old <database_dir>, else ../databases beside the script. Data drivers are
1974 # looked for here unless <data> says otherwise.
1975 sub _database_directory_is_set
1976 {
1977 my (undef, $config) = @_;
1978  
1979 my $databases = $config->{'databases'};
1980 return 1 if(ref($databases) eq 'HASH' && defined(_resolve_directory($databases->{'directory'})));
1981 return $config->{'database_dir'} ? 1 : 0;
1982 }
1983  
1984 sub _database_directory
1985 {
1986 my (undef, $config) = @_;
1987  
1988 my $databases = $config->{'databases'};
1989 my $directory = (ref($databases) eq 'HASH') ? _resolve_directory($databases->{'directory'}) : undef;
1990 return $directory // $config->{'database_dir'} || File::Spec->catdir($script_dir // File::Spec->curdir(), File::Spec->updir(), $DEFAULT_DATABASE_DIR);
1991 }
1992  
1993 # The database directory, and a message in the log about it: info when it is there,
1994 # notice when only the default is missing (a site may have no data files at all; the
1995 # drivers it declares itself are still tried and report their own failure), and an
1996 # error when the site named a directory that is not there, which is a mistake.
1997 sub _check_database_directory
1998 {
1999 my ($self, $config, $logger) = @_;
2000  
2001 my $directory = $self->_database_directory($config);
2002 if(-d $directory) {
2003 $logger->info('Reading databases from ', $directory);
2004 } elsif($self->_database_directory_is_set($config)) {
2005 $logger->error("The databases directory $directory does not exist");
2006 } else {
2007 $logger->notice("No databases directory $directory: assuming there are no data files");
2008 }
2009 return $directory;
2010 }
2011  
2012 # The data drivers (Database::Abstraction subclasses) the site declares, as a list of
2013 # { name, module, description, file, soft } in the order they were written:
2014 # <data>
2015 # <directory>/path/to/drivers</directory>
2016 # <driver>
2017 # <name>states</name>
2018 # <description>List of data about the U.S. states</description>
2019 # <directory>/path/to/states/driver</directory>
2020 # </driver>
2021 # </data>
2022 # <databases> says where the data files are and <data> where the drivers that read
2023 # them are. (<data> as a top-level key is also handed to Database::Abstraction as
2024 # a constructor argument, which _site_setup() undoes.)
2025 # name is what the page is given (lower-cased last part), module the class, and
2026 # file where its .pm file is, or undef to find the class in @INC. A <directory>
2027 # in a <driver> beats the one in <data>, which beats the database directory, the
2028 # default. Only the <driver> one is strict: a driver that is not in the others is
2029 # looked for in @INC, so a site need not copy this distribution's own drivers into
2030 # its data directory.
2031 # What is declared, in order of preference:
2032 # 1. the <driver> elements;
2033 # 2. the old <data_modules>index, states</data_modules> string, which is also
2034 # how a site says "none" by leaving it empty;
2035 # 3. every *.pm in the <data> directory, or failing that in the database directory;
2036 # 4. the default, Web::VWF::Data::index.
2037 # A name with no :: is one of this distribution's own, so index is
2038 # Web::VWF::Data::index; a name that has :: is used as written, which is how a
2039 # site names its own modules. The file looked for in a directory is named for
2040 # the last part of the class, whichever way the class was written.
2041 sub _data_modules
2042 {
2043 my ($self, $config) = @_;
2044  
2045 my $data = $config->{'data'};
2046 my $named_dir = (ref($data) eq 'HASH') ? _resolve_directory($data->{'directory'}) : undef;
2047 my $default_dir = $named_dir // $self->_database_directory($config);
2048  
2049 my @entries = _config_entries($data, 'driver');
2050 unless(@entries) {
2051 if(defined($config->{'data_modules'})) {
2052 @entries = map { +{ name => $_, description => '', directory => '' } } $self->_config_list($config, 'data_modules');
2053 } else {
2054 @entries = map { +{ name => $_, description => '', directory => '' } } sort(map { basename($_, '.pm') } glob(File::Spec->catfile($default_dir, '*.pm')));
2055 unless(@entries) {
2056 # Nothing declared and nothing in the directory. The built-in
2057 # driver reads files from the databases directory, so with no
2058 # such directory the site has no data files and needs no driver
2059 # (its own access log is read by vwf_log, which is separate).
2060 # A directory the site named that is missing is a mistake, which
2061 # the driver then reports.
2062 return () unless(-d $default_dir || $self->_database_directory_is_set($config));
2063 # This distribution's own, from @INC
2064 return map { +{ name => lc((split(/::/, $_))[-1]), module => $_, description => '', file => undef } } @DEFAULT_DATA_MODULES;
2065 }
2066 }
2067 }
2068  
2069 my @modules;
2070 foreach my $entry (@entries) {
2071 my $module = ($entry->{'name'} =~ /::/) ? $entry->{'name'} : "Web::VWF::Data::$entry->{'name'}";
2072 my $last = (split(/::/, $module))[-1];
2073 my $own = _resolve_directory($entry->{'directory'});
2074 my $dir = $own // $default_dir;
2075 push @modules, {
2076 name => lc($last),
2077 module => $module,
2078 description => $entry->{'description'},
2079 file => File::Spec->catfile($dir, "$last.pm"),
2080 soft => defined($own) ? 0 : 1,
2081 };
2082 }
2083 return @modules;
2084 }
2085  
2086 # Read the settings this site declares, once per process, and act on them: open
2087 # the database directory it names, load the data modules it names and give the
2088 # pages the languages and addresses it names. Everything left unsaid keeps the
2089 # default it had when these values were written into this script.
2090 sub _site_setup
2091 {
2092 my $self = shift;
2093 my $config = shift;
2094  
2095 return if($self->{site_ready});
2096 # The configuration, the database directory, the
2097 # data handles and these lists last for the life of the process, not for one
2098 # request.
2099  
2100 $self->{site_ready} = 1;
2101  
2102 # Where the site's own databases are. Database::Abstraction reads them, and
2103 # the pages are told the directory as databasedir and database_dir.
2104 $database_dir = $self->_check_database_directory($config, $logger);
2105  
2106 # <databases><database> was how a site declared its drivers before 0.004.0.
2107 # It is no longer read, so say so rather than leaving the pages without data.
2108 if(ref($config->{'databases'}) eq 'HASH' && exists($config->{'databases'}{'database'})) {
2109 $logger->warn('<databases><database> is no longer read: declare each driver as <data><driver>');
2110 }
2111  
2112 Database::Abstraction::init({
2113 cache => CHI->new(driver => 'Memory', datastore => {}),
2114 cache_duration => '1 day',
2115 directory => $database_dir,
2116 logger => $logger
2117 });
2118  
2119 # The languages the site offers. CGI::Lingua negotiates within this list, so
2120 # listing a language is what makes that language's templates reachable.
2121 @supported_languages = $self->_config_list($config, 'supported_languages', @DEFAULT_SUPPORTED_LANGUAGES);
2122  
2123 # Addresses exempt from rate limiting
2124 @rate_limit_trusted_ips = $self->_config_list($config, 'rate_limit_trusted_ips', @DEFAULT_RATE_LIMIT_TRUSTED_IPS);
2125  
2126 # The site's data modules (see _data_modules). Each is loaded, constructed
2127 # with ->new() and given to every page under the last part of its name,
2128 # lower-cased: Web::VWF::Data::index arrives at a page as index, and a
2129 # site's own Bands::Data::bands as bands.
2130 foreach my $database ($self->_data_modules($config)) {
2131 my $module = $database->{'module'};
2132 my $handle;
2133 eval {
2134 if(defined($database->{'file'}) && (-f $database->{'file'} || !$database->{'soft'})) {
2135 # From the directory the site gave, not from @INC
2136 -f $database->{'file'} or die "No such file $database->{'file'}\n";
2137 require $database->{'file'};
2138 } else {
2139 # No directory given, or only the database directory by default
2140 # and the driver is not in it
2141 require_module($module);
2142 }
2143 $module->import() if($module->can('import'));
2144 $handle = $module->new();
2145 _discard_config_rows($handle);
2146 };
2147 if(!defined($handle)) {
2148 # A module the site named that cannot be loaded is reported and
2149 # skipped rather than taking the site down: it is a setting now, so
2150 # getting it wrong should not stop the pages that do not need it.
2151 $logger->error("Can't load data module $module: $@");
2152 next;
2153 }
2154  
2155 my $name = $database->{'name'};
2156 $handle->set_logger($logger) if($handle->can('set_logger'));
2157 $data{$name} = $handle;
2158 $logger->debug("Data module $module is available to pages as \$$name", length($database->{'description'}) ? ": $database->{'description'}" : '');
2159 }
2160  
2161 return 1;
2162 }
2163  
2164 # <data> is a top-level configuration key, so a Database::Abstraction handle
2165 # built while the site configures it takes the setting for the rows of its table,
2166 # and then never opens its file ("Where did the data come from?"). Discard them
2167 # so that the handle reads its own file. Every handle this module makes needs it.
2168 sub _discard_config_rows
2169 {
2170 my $handle = shift;
2171  
2172 delete $handle->{'data'} if(Scalar::Util::blessed($handle) && exists($handle->{'data'}));
2173 return $handle;
2174 }
2175  
2176 # Give the current logger to every data handle. This runs before each request,
2177 # since command-line mode replaces the logger; the handles themselves are made
2178 # once, by _site_setup().
2179 sub _set_data_loggers
2180 {
2181 my $self = shift;
2182 my $logger = shift;
2183  
2184 foreach my $handle (values %data) {
2185 $handle->set_logger($logger) if($handle->can('set_logger'));
2186 }
2187 $self->{vwf_log}->set_logger($logger) if($self->{vwf_log});
2188 }
2189  
2190 # The rate-limit window that a client is in: { count => requests so far,
2191 # expires => when the window ends }. A new, empty, window starts when there is
2192 # none or the old one has ended. A bare number, which 0.004.2 and earlier
2193 # stored under the same key, counts as none.
2194 sub _rate_window
2195 {
2196 my($cache, $key, $seconds) = @_;
2197  
2198 my $window = $cache->get($key);
2199 return $window if((ref($window) eq 'HASH') && ($window->{'expires'} > time()));
2200  
2201 return { count => 0, expires => time() + $seconds };
2202 }
2203  
2204 # Convert a CHI-style duration ('60s', '2 minutes', '90') to whole seconds
2205 sub duration_seconds
2206 {
2207 my $duration = shift;
2208  
2209 return $duration if($duration =~ /\A\d+\z/);
2210  
2211 require Time::Duration::Parse;
2212  
2213 my $seconds = eval { Time::Duration::Parse::parse_duration($duration) };
2214 if(!defined($seconds)) {
2215 $logger->warn("Can't parse duration '$duration', using 60 seconds");
2216 return 60;
2217 }
2218 return int($seconds);
2219 }
2220  
2221 # Check whether the current request looks like a SQL injection attempt.
2222 # IPs that trigger a match are added to the in-process %blacklisted_ip set so
2223 # that subsequent requests from the same IP are rejected without re-scanning.
2224 sub blacklisted
2225 {
2226 if(my $remote = $ENV{'REMOTE_ADDR'}) {
2227 my $info = shift;
2228  
2229 # Fast path: this IP was already blacklisted earlier in this process
2230 # lifetime; no need to re-scan the request string.
2231 if($blacklisted_ip{$remote}) {
2232 $info->status(403);
2233 return 1;
2234 }
2235  
2236 if(my $string = $info->as_string()) {
2237 # Hard length cap: skip pattern matching entirely on absurdly long
2238 # inputs. Even bounded quantifiers like {1,200} iterate many times
2239 # across a 1 MB string, so cap before we run any regex.
2240 return 0 if length($string) > 8192;
2241  
2242 # SECURITY - ReDoS defence:
2243 # The original patterns used greedy .+ between SQL keywords, which
2244 # causes catastrophic (exponential) backtracking when an attacker
2245 # sends a string that contains the opening keyword but not the
2246 # closing one (e.g. thousands of chars after SELECT with no AND).
2247 # All .+ quantifiers are replaced with the bounded class [^;]{0,N}:
2248 # - the semicolon is a natural SQL statement terminator so it is
2249 # a safe anchor that real SQL injection never crosses, and
2250 # - the explicit upper bound caps backtracking to O(N) steps.
2251 # Word-boundary assertions (\b) also eliminate false positives on
2252 # ordinary words that happen to contain the substring.
2253 if( ($string =~ /SELECT\b[^;]{0,500}\bAND\b/i)
2254 || ($string =~ /ORDER\s+BY\s/i)
2255 || ($string =~ /\bOR\s+NOT\b/i)
2256 || ($string =~ /\bAND\s+\d+=\d+/i)
2257 || ($string =~ /\bTHEN\b[^;]{0,200}\bELSE\b[^;]{0,200}\bEND\b/i)
2258 || ($string =~ /\bAND\b[^;]{0,200}\bSELECT\b/i)
2259 || ($string =~ /\sAND\s[^;]{0,100}\sAND\s/i)
2260 || ($string =~ /\bAND\s+CASE\s+WHEN\b/i)) {
2261 $blacklisted_ip{$remote} = 1;
2262 $info->status(403);
2263 return 1;
2264 }
2265 }
2266 }
2267 return 0;
2268 }
2269  
2270 # False positives we don't need in the logs
2271 sub filter
2272 {
2273 # return 0 if($_[0] =~ /Can't locate Net\/OAuth\/V1_0A\/ProtectedResourceRequest.pm in /);
2274 # return 0 if($_[0] =~ /Can't locate auto\/NetAddr\/IP\/InetBase\/AF_INET6.al in /);
2275 # return 0 if($_[0] =~ /S_IFFIFO is not a valid Fcntl macro at /);
2276  
2277 return 0 if $_[0] =~ /Can't locate (Net\/OAuth\/V1_0A\/ProtectedResourceRequest\.pm|auto\/NetAddr\/IP\/InetBase\/AF_INET6\.al) in |S_IFFIFO is not a valid Fcntl macro at /;
2278 return 1;
2279 }
2280  
2281 # Escape a single value for safe inclusion in a double-quoted CSV field.
2282 # Follows RFC 4180 section 2.7 and additionally neutralises spreadsheet formulas.
2283 sub _csv_escape
2284 {
2285 my $v = shift // '';
2286  
2287 # RFC 4180: a double-quote inside a quoted field is represented by two
2288 # double-quote characters. Without this, one embedded " would break the
2289 # column boundary and corrupt every subsequent field on the row.
2290 $v =~ s/"/""/g;
2291  
2292 # SECURITY - CSV formula injection defence:
2293 # Spreadsheet applications (Excel, LibreOffice Calc) interpret cell values
2294 # that begin with = + - @ TAB or CR as formulas. An attacker who controls
2295 # a logged field (e.g. the page parameter) could inject =cmd|'/C calc'!A0.
2296 # Prefix such values with a single-quote to force literal interpretation.
2297 $v =~ s/^([=+\-@\t\r])/'$1/;
2298  
2299 return $v;
2300 }
2301  
2302 # Write one access record to vwf.log (CSV format) and optionally to syslog.
2303 # All user-influenced fields are escaped through _csv_escape before output.
2304 # Create the log file, with its header row, if there isn't one yet. Several
2305 # workers can get here at once, so it is opened for appending, which cannot
2306 # truncate another's rows, and the header is written under a lock only while the
2307 # file is empty. An empty file left by logrotate is given its header too.
2308 sub _create_vwflog
2309 {
2310 my ($vwflog) = @_;
2311  
2312 return if(-s $vwflog);
2313  
2314 open(my $fout, '>>', $vwflog);
2315 flock($fout, LOCK_EX);
2316 unless(-s $fout) {
2317 print $fout '"domain_name","time","IP","country","type","language","http_code","template","args","messages","error","duration_ms"',
2318 "\n";
2319 }
2320 close $fout;
2321 }
2322  
2323 sub _vwflog
2324 {
2325 my $self = shift;
2326  
2327 my ($vwflog, $info, $lingua, $syslog, $message, $log, $request_start) = @_;
2328  
2329 # Calculate request duration in milliseconds if a start timer was supplied.
2330 # $request_start is a Timer::Simple, so ask it for the seconds that have
2331 # passed: its numeric overload yields elapsed(), so subtracting it from the
2332 # clock gave an epoch's worth of seconds (about 1.8e12 ms per request). A
2333 # plain epoch is still accepted for callers that pass one.
2334 my $duration_ms = '';
2335 if($request_start) {
2336 my $seconds = ref($request_start) ? $request_start->elapsed() : Time::HiRes::time() - $request_start;
2337 $duration_ms = int($seconds * 1000);
2338 }
2339  
2340 # Determine which template was rendered for this request (may be empty on error).
2341 my $template;
2342 if($log) {
2343 $template = $log->template();
2344 }
2345 if(!defined($template)) {
2346 $template = '';
2347 }
2348 $message ||= '';
2349  
2350 # Collect any warn/notice-level messages emitted during this request.
2351 my $warnings;
2352 if(my $messages = $info->messages()) {
2353 $warnings = join('; ',
2354 grep defined, map { (($_->{'level'} eq 'warn') || ($_->{'level'} eq 'notice')) ? $_->{'message'} : undef } @{$messages}
2355 )
2356 }
2357 $warnings ||= '';
2358  
2359 my $country = $lingua->country() || 'unknown';
2360  
2361 # Append the record. autodie makes a failed open fatal, even inside an if,
2362 # so catch it: a full disc or wrong permissions must not crash a live request,
2363 # nor lose the syslog copy below.
2364 eval {
2365 _create_vwflog($vwflog);
2366 open(my $fout, '>>', $vwflog);
2367 # SECURITY - CSV injection defence:
2368 # Every user-visible field is passed through _csv_escape so that
2369 # embedded double-quotes cannot break the CSV column structure, and
2370 # leading formula characters cannot trigger code execution when the
2371 # file is opened in a spreadsheet application.
2372 print $fout
2373 '"', _csv_escape($info->domain_name()), '",',
2374 '"', strftime('%F %T', localtime), '",',
2375 '"', _csv_escape($ENV{REMOTE_ADDR} // ''), '",',
2376 '"', _csv_escape($country), '",',
2377 '"', _csv_escape($info->browser_type()), '",',
2378 '"', _csv_escape($lingua->language() // ''), '",',
2379 $info->status(), ',',
2380 '"', _csv_escape($template), '",',
2381 '"', _csv_escape($info->as_string(raw => 1)), '",',
2382 '"', _csv_escape($warnings), '",',
2383 '"', _csv_escape($message), '",',
2384 $duration_ms,
2385 "\n";
2386 close($fout);
2387 };
2388 $logger->warn("Can't write to $vwflog: $@") if($@ && $logger);
2389  
2390 # Optionally mirror the record to syslog (configured via the syslog stanza).
2391 if($syslog) {
2392 unless(Sys::Syslog->can('openlog')) {
2393 require Sys::Syslog;
2394 Sys::Syslog->import();
2395 }
2396  
2397 # Configure the socket transport if a hash of options was provided.
2398 if(ref($syslog) eq 'HASH') {
2399 Sys::Syslog::setlogsock($syslog);
2400 }
2401 Sys::Syslog::openlog($self->{script_name}, 'cons,pid', 'user');
2402 # Use positional %s/%d format args so that special characters in the
2403 # values cannot be interpreted as syslog format directives.
2404 Sys::Syslog::syslog('info|local0', '%s %s %s %s %s %d %s %s %d %s %s',
2405 $info->domain_name() || '',
2406 $ENV{REMOTE_ADDR} || '',
2407 $country,
2408 $info->browser_type() || '',
2409 $lingua->language() || '',
2410 $info->status() || '',
2411 $template || '',
2412 $info->as_string(raw => 1) || '',
2413 $duration_ms,
2414 $warnings,
2415 $message
2416 );
2417 Sys::Syslog::closelog();
2418 }
2419 }
2420  
2421 sub DESTROY
2422 {
2423 if(defined($^V) && ($^V ge 'v5.14.0')) {
2424 return if ${^GLOBAL_PHASE} eq 'DESTRUCT'; # >= 5.14.0 only
2425 }
2426 my $self = shift;
2427  
2428 # Clean up resources before shutdown
2429 $logger->info('Shutting down') if(defined($logger));
2430 if($buffercache && !$exit_requested) {
2431 $buffercache->purge();
2432 }
2433 if($rate_limit_cache) {
2434 # Memcached can't purge().
2435 # I don't like this hardwired code, it would be better if I could find a way to determine if a driver can run purge()
2436 $rate_limit_cache->purge() if($rate_limit_cache->short_driver_name() ne 'Memcached');
2437 }
2438 if(my $info_cache = $self->{info_cache}) {
2439 $info_cache->purge();
2440 }
2441 if($lingua_cache) {
2442 $lingua_cache->purge();
2443 }
2444 CHI->stats->flush();
2445 Log::WarnDie->dispatcher(undef);
2446 }
2447  
2448 =head1 AUTHOR
2449  
2450 Nigel Horne, C<< <njh at nigelhorne.com> >>
2451  
2452 =head1 LICENCE AND COPYRIGHT
2453  
2454 Copyright 2026 Nigel Horne.
2455  
2456 Usage is subject to the GPL2 licence terms.
2457 If you use it,
2458 please let me know.
2459  
2460 =cut
2461  
2462 1;