blib/lib/Web/VWF.pm untested

filter: Statementstmt 0.0% 0 / 781 Branchbran 0.0% 0 / 306 Conditioncond 0.0% 0 / 265 MC/DCmcdc 0.0% 0 / 145 Subroutinesub 0.0% 0 / 78 Podpod 0.0% 0 / 33 totaltotal 0.0% 0 / 1608 CC 153 SCAR 65.0
CC
153
Cov
0%
_doit
2756.0
_init
156.0
_config_entries
156.0
CRAP 662.0
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.2');
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.2
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>.
588  
589 =item C<security.rate_limiting.time_window>
590  
591 A duration such as C<60s> or C<5 minutes>. Default: C<60s>.
592  
593 =item C<security.rate_limiting.captcha_bypass_duration>
594  
595 How long a solved CAPTCHA exempts the client from the limit. Default: C<300s>.
596  
597 =item C<security.ids_threshold>
598  
599 The L<CGI::IDS> impact above which a request is treated as an attack.
600 Default: 50.
601  
602 =item C<security.csrf.enable>
603  
604 Set to C<0> to turn off the CSRF cookie that pages with a form are given.
605 Default: 1.
606  
607 =item C<security.csrf.secret>
608  
609 The secret the CSRF tokens are signed with. Without one a random secret is
610 made for each process and the tokens do not outlive it. See
611 L<Web::VWF::Display>.
612  
613 =item C<security.content_security_policy>
614  
615 Sources to add to the C<Content-Security-Policy> header, for scripts, images and
616 so on that your own templates load from elsewhere. See
617 L<Web::VWF::Display/Content-Security-Policy>.
618  
619 =back
620  
621 =head2 C<throttle>
622  
623 The per-address throttle used by L<Web::VWF::Allow> and by
624 L<Web::VWF::Display>, which share one file.
625  
626 =over 4
627  
628 =item C<throttle.max_items>
629  
630 Requests allowed in the interval. Default: 30.
631  
632 =item C<throttle.interval>
633  
634 The interval, in seconds. Default: 90.
635  
636 =item C<throttle.file>
637  
638 The file the counts are kept in. Default: F<throttle> in the temporary
639 directory.
640  
641 =back
642  
643 =head2 Caches: C<disc_cache> and C<memory_cache>
644  
645 <disc_cache>
646 <driver>File</driver>
647 <root_dir>/var/tmp/cache</root_dir>
648 </disc_cache>
649  
650 The L<CHI> caches. C<driver> is one of C<Memory>, C<BerkeleyDB>, C<DBI>,
651 C<Redis>, C<Memcached>, C<SharedMem>, C<File> or C<Null>. Default for
652 C<disc_cache>: C<BerkeleyDB>, or C<File> where that is not installed; for
653 C<memory_cache>: C<Memory>. The other keys depend on the driver:
654  
655 =over 4
656  
657 =item C<root_dir>
658  
659 For C<File> and C<BerkeleyDB>. Overridden by C<$CACHEDIR>, C<$CACHE_DIR> and
660 C<$root_dir>, in that order. It must exist and be writable unless one of the
661 environment variables made it.
662  
663 =item C<server> (or C<host>) and C<port>
664  
665 For C<Memcached>: C<host:port> pairs separated by commas, or a host with the
666 port in C<port>. Default: C<127.0.0.1:11211>.
667  
668 =item C<connect>, C<create_table>
669  
670 For C<DBI>: the DSN, which is required, and whether to create the table
671 (default: yes).
672  
673 =item C<reconnect>, C<every>, C<encoding>, C<redis_options>
674  
675 For C<Redis>, which also takes C<server> (or C<host>) and C<port> as above.
676  
677 =item C<shm_key>, C<shm_size>, C<max_size>
678  
679 For C<SharedMem>; C<shm_key> is required.
680  
681 =item C<global>, C<datastore>
682  
683 For C<Memory>; not both.
684  
685 =back
686  
687 =head1 SUBROUTINES/METHODS
688  
689 =head2 new
690  
691 The configuration of a site, and the directory the server keeps it in.
692  
693 B<Parameters:>
694  
695 =over 4
696  
697 =item * C<directory> - The directory the server keeps the configuration of the
698 sites it serves in: one directory per site, named after the site, so that a site
699 reached as F<example.com> is configured from F</usr/lib/vwf/example.com>. Any
700 other root can be named here - F</etc/vwf>, F</usr/local/etc/vwf> - and the
701 default is F</usr/lib/vwf>. Optional.
702  
703 =item * C<info>, C<logger>, C<config_directory>, C<config_file>, C<config> -
704 handed to L<Web::VWF::Config>, which describes them.
705  
706 =back
707  
708 =head3 API SPECIFICATION
709  
710 =head4 INPUT
711  
712 {
713 directory => { type => 'string', optional => 1 },
714 info => { type => 'object', optional => 1 },
715 logger => { type => 'object', optional => 1 },
716 config_directory => { type => 'string', optional => 1 },
717 config_file => { type => 'string', optional => 1 },
718 config => { type => 'hashref', optional => 1 },
719 }
720  
721 C<new> croaks with C<directory must be a string> when C<directory> is a reference.
722  
723 =head4 OUTPUT
724  
725 { type => 'object', isa => 'Web::VWF' }
726  
727 =cut
728  
729 sub new
730 {
731 my $proto = shift;
732 my $params = Params::Get::get_params(undef, @_) // {};
733  
734 my $class = ref($proto) || $proto;
735  
736 if(defined($params->{'directory'}) && ref($params->{'directory'})) {
737 Carp::croak('directory must be a string');
738 }
739  
740 return bless {
741 directory => $params->{'directory'},
742 params => $params,
743 }, $class;
744 }
745  
746 =head2 run
747  
748 Serve requests. It accepts FastCGI requests one after another and sends each
749 one to the page named by C<?page=>, as described in L</DESCRIPTION>; an error in
750 one request is logged and does not end the worker.
751  
752 The loop ends, and C<run> returns, when the web server asks the worker to exit,
753 after a TERM or USR1 signal, or when the page script has been changed since the
754 worker started, so that the next request starts a worker with the new code.
755  
756 When C<REMOTE_ADDR> is not set, which is how the script is run from a command
757 line, there is no web server: C<run> handles one request, built from the
758 command-line arguments such as C<page=index>, turns caching off, takes the
759 language from C<LANG> and prints debug logging to STDOUT among the response.
760  
761 C<run> refuses to run again from inside itself, and to run while the script is
762 still being compiled, which happens when something reads the page script as if
763 it were a configuration file. It prints a message on STDERR and returns.
764  
765 If the access log (the C<vwflog> setting) does not exist or is empty, it is
766 created with its header row before the page is rendered. A log that cannot be
767 written is reported to the logger; the request is still served.
768  
769 =head3 API SPECIFICATION
770  
771 =head4 INPUT
772  
773 {}
774  
775 =head4 OUTPUT
776  
777 { type => 'undef' }
778  
779 =cut
780  
781 =head2 _directory
782  
783 Internal: not part of the public interface. The directory the server keeps this site's configuration in: what C<new()> was
784 given, or F</usr/lib/vwf>. L<Web::VWF::Config> adds the site's own name to it.
785  
786 =head3 API SPECIFICATION
787  
788 =head4 INPUT
789  
790 {}
791  
792 =head4 OUTPUT
793  
794 { type => 'string' }
795  
796 =cut
797  
798 sub _directory
799 {
800 my $self = shift;
801  
802 return $self->{'directory'} // $ENV{root_dir} // $Web::VWF::Config::DEFAULT_DIRECTORY;
803 }
804  
805 =head2 _config
806  
807 Internal: not part of the public interface. The site's configuration, read once and kept: a site that has no F<conf/> of its
808 own beside F<cgi-bin/> is configured from the server's directory for it, and
809 L<Web::VWF::Config> describes the rest of the search.
810  
811 =head3 API SPECIFICATION
812  
813 =head4 INPUT
814  
815 {}
816  
817 =head4 OUTPUT
818  
819 { type => 'object', isa => 'Web::VWF::Config' }
820  
821 =cut
822  
823 sub _config
824 {
825 my $self = shift;
826  
827 return $self->{'config'} ||= Web::VWF::Config->new({
828 %{$self->{'params'}},
829 directory => $self->_directory(),
830 });
831 }
832  
833 =head2 sig_handler
834  
835 Internal: not part of the public interface, though it is a plain function, not a
836 method. The handler for TERM and USR1. It sets the flag that makes C<run> leave its loop and, if no
837 request is being handled, flushes the response cache and statistics, detaches
838 L<Log::WarnDie> and exits at once. Mid-request it only sets the flag, so the
839 response in flight is sent whole.
840  
841 =head3 API SPECIFICATION
842  
843 =head4 INPUT
844  
845 { signal => { type => 'string' } }
846  
847 =head4 OUTPUT
848  
849 { type => 'undef' }
850  
851 =head2 choose
852  
853 Internal: a plain function. Sends the C<300 Multiple Choices> response: plain
854 text that lists C<?page=> and the description of each page the site serves, with
855 a C<Last-Modified> header from the page script. The list is left out for
856 C<HEAD>. It does nothing when the status of the request is already not 200,
857 as for an unknown page, where the status line is sent elsewhere.
858  
859 =head3 API SPECIFICATION
860  
861 =head4 INPUT
862  
863 {}
864  
865 =head4 OUTPUT
866  
867 { type => 'undef' }
868  
869 =head2 send_error
870  
871 Internal: a plain function. Sends a short plain-text error response, and
872 records the status in the request's L<CGI::Info>. Takes a hash or a hashref:
873  
874 =over 4
875  
876 =item C<status>
877  
878 The HTTP status code. Required.
879  
880 =item C<body>
881  
882 The text to send. It is not sent for C<HEAD>.
883  
884 =item C<headers>
885  
886 Extra header lines, each ending in a newline, such as C<Retry-After>.
887  
888 =item C<buffered>
889  
890 True once L<FCGI::Buffer> is capturing the output: it sends the C<Status> line
891 itself, so this does not.
892  
893 =back
894  
895 =head3 API SPECIFICATION
896  
897 =head4 INPUT
898  
899 {
900 status => { type => 'integer', min => 100, max => 599 },
901 body => { type => 'string', optional => 1 },
902 headers => { type => 'string', optional => 1 },
903 buffered => { type => 'boolean', optional => 1 },
904 }
905  
906 =head4 OUTPUT
907  
908 { type => 'integer', value => 1 }
909  
910 =head2 duration_seconds
911  
912 Internal: a plain function. Converts a duration such as C<60s>, C<2 minutes> or
913 C<90> to whole seconds, with L<Time::Duration::Parse>. A string of digits is
914 already seconds. One that cannot be parsed is logged as a warning, and
915 counts as 60 seconds.
916  
917 =head3 API SPECIFICATION
918  
919 =head4 INPUT
920  
921 { duration => { type => 'string' } }
922  
923 =head4 OUTPUT
924  
925 { type => 'integer', min => 0 }
926  
927 =head2 blacklisted
928  
929 Internal: a plain function. Takes the request's L<CGI::Info> and says whether
930 the request looks like an SQL injection attempt. The address that sent one is
931 remembered by the worker, so its later requests are refused without scanning
932 them again. It is only a filter for noise, see L<Web::VWF::Blacklist>. A
933 request of more than 8192 characters is not scanned. There is nothing to check
934 without C<REMOTE_ADDR>. When it returns true the status of the request has been
935 set to 403.
936  
937 =head3 API SPECIFICATION
938  
939 =head4 INPUT
940  
941 { info => { type => 'object', isa => 'CGI::Info' } }
942  
943 =head4 OUTPUT
944  
945 { type => 'boolean' }
946  
947 =head2 filter
948  
949 Internal: a plain function, registered with L<Log::WarnDie>. Called with a
950 warning, returns false for the few harmless ones that are not worth logging
951 (two missing optional modules under L<Net::OAuth> and L<NetAddr::IP>, and an
952 C<S_IFFIFO> message from Fcntl) and true for all the rest.
953  
954 =head3 API SPECIFICATION
955  
956 =head4 INPUT
957  
958 { message => { type => 'string' } }
959  
960 =head4 OUTPUT
961  
962 { type => 'boolean' }
963  
964 =cut
965  
966 # Deferred shutdown handler: set the exit flag and, if we are between requests,
967 # flush caches and exit immediately. If we are mid-request, the flag is checked
968 # after doit() returns so the in-flight response is sent cleanly.
969 sub sig_handler {
970 $exit_requested = 1;
971 $logger->trace('In sig_handler') if($logger);
972 if(!$handling_request) {
973 local $SIG{TERM} = local $SIG{USR1} = 'IGNORE';
974 $logger->info('Shutting down') if($logger);
975 # Flush the page-level response cache to disk before we exit.
976 if($buffercache) {
977 $buffercache->purge();
978 }
979 CHI->stats->flush();
980 # Detach the dispatcher so that Log::WarnDie does not try to log
981 # after the logger object has been destroyed.
982 Log::WarnDie->dispatcher(undef);
983 exit(0);
984 }
985 }
986  
987  
988 # Everything the framework needs before the first request: the bootstrap
989 # CGI::Info, the script's name and temporary directory, the configuration and the
990 # logger. Called once, from run(). The handlers for warnings and fatal errors
991 # are installed first, so that a failure while setting up is reported rather
992 # than lost.
993 sub _init
994 {
995 my $self = shift;
996  
997 return if($self->{initialised});
998 $self->{initialised} = 1;
999  
1000 # USR1 and TERM both trigger a clean shutdown; PIPE is silenced because a
1001 # broken client connection mid-response should not kill the worker.
1002 $SIG{USR1} = \&sig_handler;
1003 $SIG{TERM} = \&sig_handler;
1004 $SIG{PIPE} = 'IGNORE';
1005  
1006 # Catch all Perl warnings and mirror them to the per-script stderr log file
1007 # as well as to the structured logger.
1008 $SIG{__WARN__} = sub {
1009 my $msg = join '', @_;
1010 if($tmpdir && open(my $fout, '>>', File::Spec->catfile($tmpdir, "$script_name.stderr"))) {
1011 print {$fout} (($info ? $info->domain_name() : undef) // '(unknown host)'), ": $msg";
1012 close $fout;
1013 }
1014 $logger->warn($msg) if($logger);
1015 };
1016  
1017 # Catch fatal errors. The $^S guard prevents this handler from interfering
1018 # with Error.pm's try/catch blocks which use eval internally.
1019 $SIG{__DIE__} = sub {
1020 return if $^S; # inside an eval - let the caller handle it
1021 my $msg = join '', @_;
1022 # Detach Log::WarnDie first so a logger error cannot cause infinite recursion.
1023 Log::WarnDie->dispatcher(undef);
1024 if($tmpdir && open(my $fout, '>>', File::Spec->catfile($tmpdir, "$script_name.stderr"))) {
1025 print {$fout} (($info ? $info->domain_name() : undef) // '(unknown host)'), ": $msg";
1026 close $fout;
1027 }
1028 $logger->fatal($msg) if($logger);
1029 CORE::die @_; # re-throw so the original die location is preserved
1030 };
1031  
1032 # Bootstrap CGI::Info before the FCGI accept loop so we can derive the script
1033 # name and temp directory for logging even before the first real request.
1034 $info = CGI::Info->new();
1035 $script_name = $self->{script_name} = basename($info->script_name(), @suffixlist);
1036 $tmpdir = $info->tmpdir();
1037  
1038 # When running under a real HTTP server, redirect STDERR to a per-script log
1039 # file in the temp directory so that die/warn messages are captured.
1040 if($ENV{'HTTP_USER_AGENT'}) {
1041 close STDERR;
1042 open(STDERR, '>>', File::Spec->catfile($tmpdir, "$self->{script_name}.stderr"));
1043 }
1044  
1045 # Register the log filter that suppresses known-harmless warnings.
1046 Log::WarnDie->filter(\&filter);
1047  
1048 # Derive the environment-variable prefix from the hostname (e.g. MY_SITE_)
1049 # so that per-domain config overrides can be passed as environment variables.
1050 $script_dir = $info->script_dir();
1051 $env_prefix = uc($info->host_name()) . '_';
1052 $env_prefix =~ tr/\./_/; # dots in hostnames become underscores in env var names
1053 # Config::Abstraction returns nothing, rather than an object, when no file
1054 # matches the domain: a vhost that has not been given a config file yet, the
1055 # command line test in the POD, or CI, where the hostname is a container id.
1056 # That is not fatal, so the logger is built with no configuration and the
1057 # framework carries on with its defaults - dying here would take the site down
1058 # over a configuration file that is only there to describe it. The reason is
1059 # reported once rather than on every request.
1060 $config_abstraction = Config::Abstraction->new(env_prefix => $env_prefix, flatten => 0, config_file => $info->domain_name(), config_dirs => ["$script_dir/../conf/", "$script_dir/../../conf"]);
1061 $logger = Log::Abstraction->new($config_abstraction ? $config_abstraction->all() : {});
1062 Log::WarnDie->dispatcher($logger);
1063  
1064 unless($config_abstraction) {
1065 $logger->warn('No configuration file for ', ($info->domain_name() // '(unknown host)'), " in $script_dir/../conf/ or $script_dir/../../conf; using the defaults");
1066 }
1067 }
1068  
1069 sub run
1070 {
1071 my $self = shift;
1072  
1073 # A nested call means something has executed the page script again while
1074 # it was running or still compiling - for example a configuration reader
1075 # that took the script for its own configuration file and evaluated it.
1076 # Refuse, loudly, on STDERR: a die here would be swallowed by that reader's
1077 # eval, and carrying on would consume the server's requests.
1078 if($RUNNING || (${^GLOBAL_PHASE} ne 'RUN')) {
1079 print STDERR __PACKAGE__, '::run() called re-entrantly or during compilation (phase ',
1080 ${^GLOBAL_PHASE}, '); is the script being read as its own configuration file?', "\n";
1081 return;
1082 }
1083 local $RUNNING = 1;
1084  
1085 $self->_init();
1086  
1087 # my $request = FCGI::Request($stdin, $stdout, $stderr);
1088 my $request = FCGI::Request();
1089  
1090 # --- Main FCGI request loop ---------------------------------------------------
1091 # Accept() blocks until the web server sends a new request. It returns a
1092 # negative value when the server wants this worker to exit (e.g. graceful
1093 # shutdown), which breaks the loop naturally.
1094 while($handling_request = ($request->Accept() >= 0)) {
1095 # REMOTE_ADDR is absent when running from the command line for testing.
1096 # Switch to a verbose debug logger and single-shot mode in that case.
1097 unless($ENV{'REMOTE_ADDR'}) {
1098 my $timer = Timer::Simple->new();
1099  
1100 # Disable all caching so every run reflects the current templates.
1101 $ENV{'NO_CACHE'} = 1;
1102  
1103 # Map the LANG shell variable to the HTTP Accept-Language header so
1104 # that language detection works the same way it does in production.
1105 if((!defined($ENV{'HTTP_ACCEPT_LANGUAGE'})) && defined($ENV{'LANG'})) {
1106 my $lang = $ENV{'LANG'};
1107 $lang =~ s/\..*$//; # strip encoding suffix (e.g. .UTF-8)
1108 $lang =~ tr/_/-/; # POSIX uses _, HTTP uses -
1109 $ENV{'HTTP_ACCEPT_LANGUAGE'} = lc($lang);
1110 }
1111  
1112 Database::Abstraction::init({ logger => $logger });
1113  
1114 # Replace the production logger with a simple STDOUT printer.
1115 $logger = Log::Abstraction->new(logger => sub { print join(', ', @{$_[0]->{'message'}}), "\n" }, level => 'debug');
1116 Log::WarnDie->dispatcher($logger);
1117 $info->set_logger($logger);
1118 $self->_set_data_loggers($logger);
1119  
1120 # Enable full stack traces in Error.pm for command-line debugging.
1121 $Error::Debug = 1;
1122 try {
1123 $self->_doit(debug => 1);
1124 } catch Error with {
1125 my $msg = shift;
1126 warn "$msg\n", $msg->stacktrace();
1127 $logger->error($msg);
1128 };
1129  
1130 # Report wall-clock time taken for this command-line invocation.
1131 my @elapsed_time = $timer->hms();
1132 my $timetaken = int($elapsed_time[2] * 1000);
1133 $logger->info("$self->{script_name} completed in ${timetaken}ms");
1134  
1135 last; # command-line mode is single-shot; exit the accept loop
1136 }
1137  
1138 # -- Live HTTP request --------------------------------------------------
1139 $requestcount++;
1140 $logger->info("Request $requestcount: ", $ENV{'REMOTE_ADDR'});
1141  
1142 # Propagate the current logger to all data-access objects that may emit
1143 # log messages during this request.
1144 $info->set_logger($logger);
1145 $self->_set_data_loggers($logger);
1146  
1147 # Dispatch the request. Any unhandled Error.pm exception is caught here
1148 # so a single bad request cannot kill the FCGI worker process.
1149 try {
1150 $self->_doit(debug => 0);
1151 } catch Error with {
1152 my $msg = shift;
1153 $logger->error("$msg: ", $msg->stacktrace());
1154 # Invalidate the response cache on error so a stale error page is
1155 # never served to subsequent clients.
1156 if($buffercache) {
1157 $buffercache->clear();
1158 $buffercache = undef;
1159 }
1160 };
1161  
1162 $request->Finish();
1163  
1164 $handling_request = 0;
1165 if($exit_requested) {
1166 last;
1167 }
1168 if($ENV{SCRIPT_FILENAME}) {
1169 if(-M $ENV{SCRIPT_FILENAME} < 0) {
1170 last;
1171 }
1172 }
1173 }
1174 }
1175  
1176 # --- doit() - per-request handler --------------------------------------------
1177 # Called once per FCGI iteration. Handles security checks, language detection,
1178 # template dispatch, response caching, and access logging.
1179 sub _doit
1180 {
1181 my $self = shift;
1182  
1183 # Record the wall-clock start time so we can report request duration later.
1184 my $request_start = Timer::Simple->new();
1185  
1186 # CGI::Info caches state between calls; reset it so this request gets a
1187 # fresh view of the environment rather than stale values from the last one.
1188 CGI::Info->reset();
1189  
1190 my %params = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
1191  
1192 # $config is built once per process and reused. We cannot build it before
1193 # the first Accept() because the domain name is not known until then.
1194 # So don't pass $info in since it was created before the connection
1195 $config ||= Web::VWF::Config->new({
1196 directory => $self->_directory(),
1197 logger => $logger,
1198 debug => $params{'debug'},
1199 # A throwaway CGI::Lingua is used here only to satisfy Web::VWF::Config;
1200 # the real, cache-backed instance is created further below. It has to be
1201 # given the default languages rather than the site's configured ones:
1202 # this call is what reads the configuration, so the site's list is not
1203 # known yet.
1204 lingua => CGI::Lingua->new({ supported => [ @DEFAULT_SUPPORTED_LANGUAGES ], info => $info, logger => $logger })
1205 });
1206  
1207 # The site's own settings - its database directory, data modules, languages
1208 # and trusted addresses - are read from that configuration, once per process.
1209 $self->_site_setup($config);
1210  
1211 # deny_cloud() blocks all known cloud provider address ranges (AWS, GCP,
1212 # Azure) which generate almost no legitimate human traffic but are a
1213 # common origin for automated scanning. Geo-blocking is a blunt
1214 # instrument but effective at reducing noise. It is also why an address a
1215 # site allows here is still refused if its reverse DNS says it is in a cloud.
1216 $acl ||= CGI::ACL->new()
1217 ->deny_cloud()
1218 ->deny_country(country => Web::VWF::Blacklist->new(countries => $config->{'blacklist_countries'})->countries());
1219  
1220 foreach my $ip ($self->_config_list($config, 'allow_ips', @DEFAULT_ALLOW_IPS)) {
1221 $acl->allow_ip($ip);
1222 }
1223  
1224 unless(@valid_pages) {
1225 @valid_pages = $self->_valid_pages($config);
1226 %page_description = $self->_page_descriptions($config);
1227 %page_directory = $self->_page_directories($config, @valid_pages);
1228 }
1229  
1230 # These caches are created lazily on the first request and reused across the
1231 # FCGI accept loop to amortise the cost of cache initialisation.
1232 # The CGI::Info disc cache stores parsed request data across FCGI restarts.
1233 $self->{info_cache} ||= create_disc_cache(config => $config, logger => $logger, namespace => 'CGI::Info');
1234  
1235 my $options = {
1236 cache => $self->{info_cache},
1237 logger => $logger
1238 };
1239  
1240 # If syslog is configured, normalise the 'server' key to 'host' (the
1241 # Sys::Syslog convention) and pass the stanza to CGI::Info.
1242 my $syslog;
1243 if($syslog = $config->syslog()) {
1244 if($syslog->{'server'}) {
1245 $syslog->{'host'} = delete $syslog->{'server'};
1246 }
1247 $options->{'syslog'} = $syslog;
1248 }
1249 # Rebuild $info now that we have a cache and the domain is known.
1250 $info = CGI::Info->new($options);
1251 $logger->debug('In doit - domain is ', $info->domain_name());
1252  
1253 # Lazily initialise the in-memory rate-limit counter store.
1254 $rate_limit_cache ||= create_memory_cache(config => $config, logger => $logger, namespace => 'rate_limit');
1255  
1256 # Use the real remote IP as the rate-limit key; fall back to 'unknown'
1257 # only in the unlikely event that REMOTE_ADDR is absent.
1258 my $client_ip = $ENV{'REMOTE_ADDR'} || 'unknown';
1259  
1260 # A successful CAPTCHA solve stores a short-lived bypass token in the cache.
1261 # While the token is present the client is exempt from rate-limit checks.
1262 my $captcha_bypass_key = "$self->{script_name}:captcha_bypass:$client_ip";
1263 my $has_captcha_bypass = $rate_limit_cache->get($captcha_bypass_key);
1264  
1265 # Read the current request count for this IP from the sliding-window cache.
1266 my $request_count = $rate_limit_cache->get("$self->{script_name}:rate_limit:$client_ip") || 0;
1267  
1268 # Allow the thresholds to be tuned via the config file; fall back to the
1269 # compile-time constants if the stanza is missing.
1270 my $max_requests = $config->{'security'}->{'rate_limiting'}->{'max_requests'} || $MAX_REQUESTS;
1271 my $max_requests_hard = $config->{'security'}->{'rate_limiting'}->{'max_requests_hard'} || ($max_requests * 1.5);
1272  
1273 # The rate-limit window, as a CHI duration for the counter's TTL, and in
1274 # seconds for the Retry-After header (RFC 9110 section 10.2.3)
1275 my $time_window = $config->{'security'}->{'rate_limiting'}->{'time_window'} || $TIME_WINDOW;
1276 my $retry_after = duration_seconds($time_window);
1277  
1278 # Check if this is a CAPTCHA verification attempt
1279 if ($info->param('g-recaptcha-response')) {
1280 unless(Web::VWF::CAPTCHA->can('new')) {
1281 require Web::VWF::CAPTCHA;
1282 Web::VWF::CAPTCHA->import();
1283 }
1284  
1285 my $recaptcha_config = $config->recaptcha();
1286 if ($recaptcha_config && $recaptcha_config->{enabled}) {
1287 my $captcha = Web::VWF::CAPTCHA->new(
1288 site_key => $recaptcha_config->{site_key},
1289 secret_key => $recaptcha_config->{secret_key},
1290 logger => $logger
1291 );
1292  
1293 if ($captcha->verify($info->param('g-recaptcha-response'), $client_ip)) {
1294 # CAPTCHA verified - grant bypass
1295 my $bypass_duration = $config->{'security'}->{'rate_limiting'}->{'captcha_bypass_duration'} || '300s';
1296 $rate_limit_cache->set($captcha_bypass_key, 1, $bypass_duration);
1297 $rate_limit_cache->set("$self->{script_name}:rate_limit:$client_ip", 0, '60s'); # Reset counter
1298  
1299 $logger->info("CAPTCHA verified for $client_ip - rate limit bypass granted");
1300 $has_captcha_bypass = 1;
1301  
1302 # Redirect the client back to the page they were trying to reach.
1303 # SECURITY - CRLF / header-injection defence:
1304 # Both the page name and SCRIPT_NAME are interpolated into the
1305 # Location header. A raw %0d%0a sequence in either value would
1306 # let an attacker inject arbitrary HTTP response headers
1307 # (response-splitting / header-injection).
1308 # Strip $redirect_page to a strict allowlist (word chars and
1309 # hyphens only), and remove any embedded CR or LF from the
1310 # server-supplied SCRIPT_NAME before building the header.
1311 my $redirect_page = $info->param('page') || 'index';
1312 $redirect_page =~ s/[^A-Za-z0-9_-]//g;
1313  
1314 # Also sanitize the server variable - it is attacker-influenced
1315 # in some reverse-proxy configurations.
1316 my $script = $ENV{SCRIPT_NAME} // '/cgi-bin/page.fcgi';
1317 $script =~ s/[\r\n]//g;
1318  
1319 $info->status(302);
1320 print "Status: 302 Found\r\n",
1321 "Location: ${script}?page=${redirect_page}\r\n\r\n";
1322 return;
1323 } else {
1324 $logger->warn("CAPTCHA verification failed for $client_ip");
1325 # Fall through to show CAPTCHA again
1326 }
1327 }
1328 }
1329  
1330 $vwflog ||= $config->vwflog() || File::Spec->catfile($info->logdir(), 'vwf.log');
1331 # Reader for the CSV access log, used by the meta_data page.
1332 # Created from the same path that vwflog() writes to, which needs $config.
1333 $self->{vwf_log} ||= Web::VWF::Data::vwf_log->new({
1334 directory => dirname($vwflog),
1335 filename => basename($vwflog),
1336 no_entry => 1,
1337 logger => $logger,
1338 });
1339 _discard_config_rows($self->{vwf_log});
1340 my $log = Class::Simple->new();
1341  
1342 # Stores things for a month or longer
1343 $lingua_cache ||= create_disc_cache(config => $config, logger => $logger, namespace => 'CGI::Lingua');
1344  
1345 # Language negotiation, offering the languages this site offers
1346 my $lingua = CGI::Lingua->new({
1347 supported => \@supported_languages,
1348 cache => $lingua_cache,
1349 info => $info,
1350 logger => $logger,
1351 debug => $params{'debug'},
1352 syslog => $syslog,
1353 });
1354  
1355 my $cachedir = Web::VWF::Utils::env_cache_dir() || $params{'cachedir'} || $config->{disc_cache}->{root_dir} || File::Spec->catfile($tmpdir, 'cache');
1356  
1357 # Rate limit by IP (unless bypassed)
1358 unless($has_captcha_bypass || grep { $_ eq $client_ip } @rate_limit_trusted_ips) {
1359 if ($request_count >= $max_requests_hard) {
1360 # Hard limit exceeded - show CAPTCHA with warning
1361 my $recaptcha_config = $config->recaptcha();
1362  
1363 if ($recaptcha_config && $recaptcha_config->{enabled}) {
1364 $logger->warn("Hard rate limit exceeded for $client_ip ($request_count requests)");
1365 $info->status(429);
1366  
1367 unless(Web::VWF::Display::captcha->can('new')) {
1368 require Web::VWF::Display::captcha;
1369 Web::VWF::Display::captcha->import();
1370 }
1371 my $display = Web::VWF::Display::captcha->new({
1372 cachedir => $cachedir,
1373 info => $info,
1374 logger => $logger,
1375 lingua => $lingua,
1376 config => $config,
1377 });
1378  
1379 print 'Status: 429 ', HTTP::Status::status_message(429), "\n";
1380 print $display->as_string({
1381 'Retry-After' => $retry_after,
1382 Retry_After => $retry_after,
1383 hard_block => 1,
1384 request_count => $request_count,
1385 });
1386  
1387 $self->_vwflog($vwflog, $info, $lingua, $syslog, 'Hard rate limit - CAPTCHA shown', $log, $request_start);
1388 return;
1389 }
1390  
1391 # No CAPTCHA to offer, so block until the window expires
1392 $logger->warn("Hard rate limit exceeded for $client_ip ($request_count requests)");
1393 send_error(status => 429, body => "Too many requests - try again later\n", headers => "Retry-After: $retry_after\n");
1394 $self->_vwflog($vwflog, $info, $lingua, $syslog, 'Hard rate limit', $log, $request_start);
1395 return;
1396 } elsif ($request_count >= $max_requests) {
1397 # Soft limit exceeded - show CAPTCHA
1398 my $recaptcha_config = $config->recaptcha();
1399  
1400 if ($recaptcha_config && $recaptcha_config->{enabled}) {
1401 $logger->info("Soft rate limit exceeded for $client_ip ($request_count requests) - CAPTCHA challenge issued");
1402 $info->status(429);
1403  
1404 unless(Web::VWF::Display::captcha->can('new')) {
1405 require Web::VWF::Display::captcha;
1406 Web::VWF::Display::captcha->import();
1407 }
1408 my $display = Web::VWF::Display::captcha->new({
1409 cachedir => $cachedir,
1410 info => $info,
1411 logger => $logger,
1412 lingua => $lingua,
1413 config => $config,
1414 });
1415  
1416 if($display) {
1417 print $display->as_string({
1418 'Retry-After' => $retry_after,
1419 Retry_After => $retry_after,
1420 hard_block => 0,
1421 request_count => $request_count,
1422 });
1423  
1424 $self->_vwflog($vwflog, $info, $lingua, $syslog, 'Soft rate limit - CAPTCHA shown', $log, $request_start);
1425 } else {
1426 my $error = $@;
1427 if($error) {
1428 $logger->error($error);
1429 } else {
1430 $logger->error("Unable to show captcha page - request count = $request_count");
1431 }
1432 $self->_vwflog($vwflog, $info, $lingua, $syslog, 'Soft rate limit - CAPTCHA not shown', $log, $request_start);
1433 }
1434 return;
1435 }
1436 }
1437 }
1438  
1439 # Commit the incremented request count back to the sliding-window cache.
1440 # The TTL is the rate-limit window; the counter expires automatically.
1441 $rate_limit_cache->set("$self->{script_name}:rate_limit:$client_ip", $request_count + 1, $time_window);
1442  
1443 # A request with no page parameter cannot be dispatched; send a 300
1444 # response listing the known valid pages instead.
1445 if(!defined($info->param('page'))) {
1446 $logger->info('No page given in ', $info->as_string());
1447 choose();
1448 return;
1449 }
1450  
1451 # Multi-layer access control
1452 # Three independent checks are run in order of cheapness:
1453 # 1. CGI::ACL - cloud ranges, country blocks, explicit IP allow/deny.
1454 # 2. blacklisted() - in-process IP set built from prior SQL-injection attempts.
1455 # 3. Web::VWF::Allow - DShield feed, user-agent blacklist, throttler, IDS.
1456 if(my $remote_addr = $ENV{'REMOTE_ADDR'}) {
1457 my $reason;
1458 if($acl->all_denied(lingua => $lingua)) {
1459 $reason = 'Denied by CGI::ACL';
1460 } elsif(blacklisted($info)) {
1461 $reason = 'Blacklisted for attempting to break in';
1462 } else {
1463 # Web::VWF::Allow may throw an Error object when it blocks a request.
1464 # Catch it here so the 403 response is sent rather than propagating.
1465 try {
1466 unless(Web::VWF::Allow::allow({
1467 info => $info,
1468 lingua => $lingua,
1469 logger => $logger,
1470 cache => $rate_limit_cache,
1471 config => $config,
1472 })) {
1473 $reason = 'Blocked by Web::VWF::Allow';
1474 }
1475 } catch Error with {
1476 $reason = shift;
1477 };
1478 }
1479 if($reason) {
1480 # Return a minimal plain-text 403 - no template rendering so that
1481 # a blocked attacker receives no information about site structure.
1482 send_error(status => 403, body => "Access Denied\n");
1483 $logger->info("$remote_addr: access denied: $reason");
1484 $info->status(403);
1485 $self->_vwflog($vwflog, $info, $lingua, $syslog, $reason, $log, $request_start);
1486 return;
1487 }
1488 }
1489  
1490 # -- FCGI::Buffer setup ------------------------------------------------
1491 # FCGI::Buffer post-processes the output: compresses it, generates an ETag
1492 # and Last-Modified header, and serves a 304 Not Modified when appropriate.
1493 my $args = {
1494 generate_etag => 1,
1495 generate_last_modified => 1,
1496 compress_content => 1,
1497 generate_304 => 1,
1498 info => $info,
1499 optimise_content => 1,
1500 logger => $logger,
1501 # lint_content runs HTML::Tidy on the output; enable in debug mode or
1502 # when explicitly requested via the lint_content query parameter.
1503 lint_content => $info->param('lint_content') // $params{'debug'},
1504 lingua => $lingua
1505 };
1506  
1507 if((!$info->is_search_engine()) && $config->root_dir() &&
1508 ($info->param('page') ne 'home') &&
1509 ((!defined($info->param('action'))) || ($info->param('action') ne 'send'))) {
1510 $args->{'save_to'} = {
1511 directory => File::Spec->catfile($config->root_dir(), 'save_to'),
1512 ttl => 3600 * 24,
1513 create_table => 1
1514 };
1515 }
1516  
1517 my $fb = FCGI::Buffer->new()->init($args);
1518  
1519 if($fb->can_cache()) {
1520 my $cache_key = join('/',
1521 'FCGI::Buffer',
1522 $info->browser_type(),
1523 $info->domain_name(),
1524 $self->{script_name},
1525 $info->as_string(),
1526 $lingua->language()
1527 );
1528 $cache_key =~ s/;string=%5Bobject%20HTMLInputElement%5D//;
1529 $cache_key =~ s/;string=\[object HTMLInputElement\]//;
1530 if($info->param('location')) {
1531 $cache_key .= '/' . $info->param('location');
1532 }
1533 $logger->debug("enabling cache key $cache_key");
1534  
1535 $buffercache ||= create_disc_cache(config => $config, logger => $logger, namespace => $self->{script_name}, root_dir => $cachedir);
1536 $fb->init(
1537 cache_key => $cache_key,
1538 cache => $buffercache,
1539 # generate_304 => 0,
1540 cache_duration => '1 day',
1541 );
1542 if($fb->is_cached()) {
1543 return;
1544 }
1545 }
1546  
1547 # $display holds the instantiated Web::VWF::Display subclass when the page is
1548 # found; $invalidpage is set when the page name is invalid or unloadable.
1549 my $display;
1550 my $invalidpage;
1551  
1552 # Arguments forwarded to every Web::VWF::Display subclass constructor. The
1553 # server's directory is among them because a page reads its configuration for
1554 # itself, and has to look where this script did.
1555 $args = {
1556 cachedir => $cachedir,
1557 info => $info,
1558 logger => $logger,
1559 lingua => $lingua,
1560 config => $config,
1561 server_directory => $SERVER_CONF_DIR,
1562 log => $log
1563 };
1564  
1565 # -- Page dispatch ------------------------------------------------------
1566 # The outer block eval catches any exception thrown during module loading
1567 # or display-object construction, setting $@ for inspection below.
1568 eval {
1569 my $page = $info->param('page');
1570  
1571 # Strip URL fragment identifiers - the server never needs them.
1572 $page =~ s/#.*$//;
1573  
1574 # Reject backslashes: no legitimate page name contains one, and
1575 # they have historically been used to probe Windows path traversal.
1576 $page =~ s/\\//g;
1577  
1578 if($page =~ /\//) {
1579 # A slash in the page name indicates an attempt to traverse
1580 # directories (e.g. page=/etc/passwd or page=http://evil.com).
1581 $logger->info("Blocking '/' in $page");
1582 $info->status(403);
1583 $log->status(403);
1584 $invalidpage = 1;
1585 } else {
1586 # Strip every non-word character so that the page name can only
1587 # contain [A-Za-z0-9_] - safe to use as a Perl package suffix.
1588 $page =~ s/\W//g;
1589 $page =~ s/\s//g;
1590 }
1591  
1592 if($invalidpage) {
1593 # Already rejected above
1594 } elsif(!grep { $_ eq $page } @valid_pages) {
1595 # Only pages on the allow-list are loaded, so that no other
1596 # Web::VWF::Display::* module that happens to be on @INC (e.g. under
1597 # ~/lib/perl5) can be reached from the query string.
1598 $logger->info("Unknown page $page");
1599 $invalidpage = 1;
1600 if($info->status() == 200) {
1601 $info->status(404);
1602 }
1603 } else {
1604 my $display_module = "Web::VWF::Display::$page";
1605  
1606 $logger->debug("doit(): Loading module $display_module from ", $page_directory{$page} // '@INC');
1607 unless($display_module->can('new')) {
1608 # String-eval elimination:
1609 # The original code used eval "require $display_module" which is a
1610 # string eval on a user-derived value. Although $page has been
1611 # stripped of \W characters, a Unicode or locale edge-case could
1612 # allow a bypass. Module::Runtime::require_module() loads a module
1613 # by name using a block eval internally, with no string-eval surface.
1614 #
1615 # A page with a directory is loaded from its file there instead
1616 # of from @INC. Its name has been checked against the valid
1617 # pages, which are \w+ only, so the path cannot leave the
1618 # directory.
1619 if(my $dir = $page_directory{$page}) {
1620 my $file = File::Spec->catfile($dir, "$page.pm");
1621 eval { -f $file or die "No such file $file\n"; require $file };
1622 } else {
1623 eval { require_module($display_module) };
1624 }
1625 $display_module->import() unless $@;
1626 }
1627 if($@) {
1628 $logger->debug("Failed to load module $display_module: $@");
1629 $logger->info("Unknown page $page");
1630 $invalidpage = 1;
1631 if($info->status() == 200) {
1632 $info->status(404);
1633 }
1634 } else {
1635 # use Class::Inspector;
1636 # my $methods = Class::Inspector->methods($display_module);
1637 # print "$display_module exports ", join(', ', @{$methods}), "\n";
1638 $display = do {
1639 eval { $display_module->new($args) };
1640 };
1641 if(!defined($display)) {
1642 if($@) {
1643 $logger->warn("$display_module->new(): $@");
1644 } else {
1645 $logger->notice("Can't instantiate page $page");
1646 }
1647 $invalidpage = 1;
1648 if($info->status() == 200) {
1649 $info->status(404);
1650 }
1651 } elsif(!$display->can('as_string')) {
1652 $logger->warn("Problem understanding $page");
1653 undef $display;
1654 }
1655 }
1656 }
1657 };
1658  
1659 my $error = $@;
1660 if($error) {
1661 if($info->status() == 429) {
1662 $logger->notice($error);
1663 } else {
1664 $logger->error($error);
1665 }
1666 $display = undef;
1667 }
1668  
1669 if(defined($display)) {
1670 # A request is logged after its page is made, so on a new site, or after
1671 # the log has been rotated away, there is no file for meta_data to read.
1672 # Failing to make one must not stop pages that never look at it.
1673 eval { _create_vwflog($vwflog) };
1674 $logger->warn("Can't create $vwflog: $@") if($@);
1675  
1676 # Pass in handles to the databases: the site's own data handles, under
1677 # the name each was declared with, and the access log, which the
1678 # framework reads from the log it writes.
1679 print $display->as_string({
1680 cachedir => $cachedir,
1681 config => $config,
1682 databasedir => $database_dir,
1683 database_dir => $database_dir,
1684 %data,
1685 vwf_log => $self->{vwf_log},
1686 });
1687 $self->_vwflog($vwflog, $info, $lingua, $syslog, '', $log, $request_start);
1688 } elsif($invalidpage) {
1689 if($info->status() == 429) {
1690 # Throttled by Web::VWF::Display
1691 my $interval = $config->{'throttle'}->{'interval'} // 90;
1692 send_error(status => 429, body => "Too many requests - try again later\n", headers => "Retry-After: $interval\n", buffered => 1);
1693 $self->_vwflog($vwflog, $info, $lingua, $syslog, 'Throttled', $log, $request_start);
1694 } else {
1695 choose();
1696 $self->_vwflog($vwflog, $info, $lingua, $syslog, 'Unknown page', $log, $request_start);
1697 }
1698 return;
1699 } else {
1700 $logger->debug('disabling cache');
1701 $fb->init(
1702 cache => undef,
1703 );
1704 # Handle errors gracefully
1705 my ($status, $body);
1706 if($error eq 'Unknown page to display') {
1707 ($status, $body) = (400, "I don't know what you want me to display.\n");
1708 } elsif($error =~ /Can\'t locate .* in \@INC/) {
1709 $logger->error($error);
1710 ($status, $body) = (500, "Software error - contact the webmaster\n");
1711 } elsif(($info->status() == 200) || ($info->status() == 403)) {
1712 # No permission to show this page
1713 ($status, $body) = (403, "Access Denied\n");
1714 } else {
1715 $status = $info->status();
1716 $body = "Page unavailable - something is wrong at your end, please fix and try again\n";
1717 }
1718 send_error(status => $status, body => $body, buffered => 1);
1719 $log->status($status);
1720 $self->_vwflog($vwflog, $info, $lingua, $syslog, $error ? $error : 'Access denied', $log, $request_start);
1721 throw Error::Simple($error ? $error : $info->as_string());
1722 }
1723 }
1724  
1725 # Send a 300 Multiple Choices response listing the pages this site serves.
1726 # Called when the ?page= parameter is absent or the requested page is unknown.
1727 sub choose
1728 {
1729 $logger->info('Called with no page to display');
1730  
1731 my $status = $info->status();
1732  
1733 # If the status is already non-200 (e.g. 404 set by the caller), relay
1734 # that status rather than overriding it with a 300. That only happens
1735 # for an invalid page, after FCGI::Buffer has been set up, and it sends
1736 # the Status line from $info->status() itself.
1737 return if($status != 200);
1738  
1739 print "Status: 300 Multiple Choices\n",
1740 "Content-type: text/plain\n";
1741  
1742 $info->status(300);
1743  
1744 # Include a Last-Modified header based on the script's mtime so that
1745 # caches and conditional-GET clients can revalidate efficiently.
1746 if(my $path = $info->script_path()) {
1747 require HTTP::Date;
1748 HTTP::Date->import();
1749  
1750 my @statb = stat($path);
1751 my $mtime = $statb[9];
1752 print 'Last-Modified: ', HTTP::Date::time2str($mtime), "\n";
1753 }
1754  
1755 print "\n";
1756  
1757 # RFC 7231 section 4.3.2: a HEAD response must not include a body.
1758 unless($ENV{'REQUEST_METHOD'} && ($ENV{'REQUEST_METHOD'} eq 'HEAD')) {
1759 # The same list that doit() allows, so the two cannot differ
1760 print map {
1761 "/cgi-bin/page.fcgi?page=$_" . (length($page_description{$_} // '') ? " - $page_description{$_}" : '') . "\n"
1762 } @valid_pages;
1763 }
1764 }
1765  
1766 # Send a short plain-text error response, and record its status in $info.
1767 # status - the HTTP status code
1768 # body - the text to send (not sent for HEAD)
1769 # headers - optional extra header lines, each ending in "\n", e.g. Retry-After
1770 # buffered - true once FCGI::Buffer is capturing the output. It sends the
1771 # Status line from $info->status(), so it mustn't be printed here too.
1772 sub send_error
1773 {
1774 my %args = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
1775 my $status = $args{'status'};
1776  
1777 $info->status($status);
1778  
1779 print 'Status: ', $status, ' ', HTTP::Status::status_message($status), "\n" unless($args{'buffered'});
1780 print $args{'headers'} // '',
1781 "Content-type: text/plain\n",
1782 "Pragma: no-cache\n\n";
1783  
1784 # RFC 9110 section 9.3.2: a HEAD response must not include a body.
1785 my $is_head = $ENV{'REQUEST_METHOD'} && ($ENV{'REQUEST_METHOD'} eq 'HEAD');
1786 print $args{'body'} if(defined($args{'body'}) && !$is_head);
1787  
1788 return 1;
1789 }
1790  
1791 # A list-valued setting: what the configuration file says about it, or the
1792 # caller's defaults when it says nothing about it. A list can be written as one
1793 # string of values separated by commas or spaces, which is what the plain form
1794 # of a configuration file gives, or as an element with one child per value,
1795 # which is what an XML file gives; both are read, so an XML file can hold a list
1796 # in whichever of the two ways reads better. The values are returned as they
1797 # were written and in the order they were written, with repetitions dropped, and
1798 # a setting that is present but empty means no values at all - so that a site can
1799 # say "none" as well as saying nothing.
1800 sub _config_list
1801 {
1802 # The invocant is not used: the setting and its defaults are all this needs.
1803 my (undef, $config, $key, @defaults) = @_;
1804  
1805 my $value = $config->{$key};
1806 return @defaults unless(defined($value));
1807  
1808 my @values;
1809 if(ref($value) eq 'HASH') {
1810 # One child per value; the names of the children are not used
1811 foreach my $child (values %{$value}) {
1812 push(@values, ref($child) eq 'ARRAY' ? @{$child} : $child);
1813 }
1814 } elsif(ref($value) eq 'ARRAY') {
1815 @values = @{$value};
1816 } else {
1817 @values = split /[\s,]+/, $value;
1818 }
1819  
1820 my %seen;
1821 return grep { defined($_) && length($_) && !$seen{$_}++ } @values;
1822 }
1823  
1824 # The <display> setting, named after the Web::VWF::Display directory the pages
1825 # live in. A site written before the rename used <pages>, which is still read
1826 # when there is no <display>.
1827 sub _display_setting
1828 {
1829 my $config = shift;
1830  
1831 return $config->{'display'} // $config->{'pages'};
1832 }
1833  
1834 # The pages the site's configuration file declares, as a list of
1835 # { name => ..., description => ... } in the order they were written:
1836 # <display>
1837 # <page><name>states</name><description>About the U.S. states</description></page>
1838 # <directory>/path/to/pages</directory>
1839 # </display>
1840 # A <directory> in <display> is where the page modules are looked for, and the
1841 # list of pages when there are no <page>s (see _valid_pages); one in a <page>
1842 # 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.
1843 # The old form, a single string of names (<pages>index, meta_data</pages>), is
1844 # still read, with no descriptions, so existing sites keep working. A page
1845 # without a usable name is dropped, and so is a repeated one, since the same
1846 # file can be loaded more than once when the configuration is merged.
1847 sub _config_pages
1848 {
1849 my (undef, $config) = @_;
1850  
1851 return _config_entries(_display_setting($config), 'page');
1852 }
1853  
1854 # The common reader for a setting that is a list of named things, each with an
1855 # optional description and directory: the elements called $item inside $setting
1856 # (a hash), or the array or string of names of the old form. Returns
1857 # { name, description, directory } hashes, in order, without repetitions.
1858 sub _config_entries
1859 {
1860 my ($setting, $item) = @_;
1861  
1862 return unless(defined($setting));
1863  
1864 my @entries;
1865 if(ref($setting) eq 'HASH') {
1866 my $found = $setting->{$item};
1867 return unless(defined($found));
1868 @entries = (ref($found) eq 'ARRAY') ? @{$found} : ($found);
1869 } elsif(ref($setting) eq 'ARRAY') {
1870 @entries = @{$setting};
1871 } else {
1872 @entries = split /[\s,]+/, $setting;
1873 }
1874  
1875 my (%seen, @found);
1876 foreach my $entry (@entries) {
1877 next unless(defined($entry));
1878 my ($name, $description, $directory) = (ref($entry) eq 'HASH') ? @{$entry}{qw(name description directory)} : ($entry, undef, undef);
1879 next unless(defined($name) && !ref($name) && length($name));
1880 next if($seen{$name}++);
1881 push @found, {
1882 name => $name,
1883 description => (defined($description) && !ref($description)) ? $description : '',
1884 directory => (defined($directory) && !ref($directory)) ? $directory : '',
1885 };
1886 }
1887 return @found;
1888 }
1889  
1890 # The pages that ?page= may load. Sites declare them in the config file (see
1891 # _config_pages); otherwise every *.pm in the page directory is allowed, except
1892 # captcha, which only the rate limiter shows. The page directory is
1893 # <display><directory>, or ../lib/Web/VWF/Display next to this script.
1894 sub _valid_pages
1895 {
1896 my $self = shift;
1897 my $config = shift;
1898  
1899 my @pages = map { $_->{'name'} } $self->_config_pages($config);
1900 return grep { /\A\w+\z/ } @pages if(@pages);
1901  
1902 # <display><directory> overrides where the page modules are looked for.
1903 # Only the default has the framework's own hard-coded layout.
1904 my $dir = $self->_pages_directory($config);
1905 unless(defined($dir)) {
1906 # FIXME: Remove the hard coding
1907 $dir = File::Spec->catdir($script_dir, File::Spec->updir(), 'lib', 'Web', 'VWF', 'Display');
1908 }
1909 # The list is built first rather than returned from inside sort(): a sort
1910 # that is returned directly takes the caller's context, and sort in scalar
1911 # context has no defined meaning.
1912 my @found = sort(grep { $_ ne 'captcha' } map { basename($_, '.pm') } glob(File::Spec->catfile($dir, '*.pm')));
1913 return @found;
1914 }
1915  
1916 # A directory from the configuration, made absolute: a relative one is taken
1917 # from the script's directory, as the default is. Undef if there isn't one.
1918 sub _resolve_directory
1919 {
1920 my $directory = shift;
1921  
1922 # An explicit undef, not a bare return: this is used inside map, where an
1923 # empty list would unbalance the hash being built
1924 return undef unless(defined($directory) && !ref($directory) && length($directory)); ## no critic (ProhibitExplicitReturnUndef)
1925 return File::Spec->file_name_is_absolute($directory) ? $directory : File::Spec->catdir($script_dir, $directory);
1926 }
1927  
1928 # <display><directory>, resolved, or undef
1929 sub _pages_directory
1930 {
1931 my (undef, $config) = @_;
1932  
1933 my $display = _display_setting($config);
1934 return unless(ref($display) eq 'HASH');
1935 return _resolve_directory($display->{'directory'});
1936 }
1937  
1938 # name => directory for each of the given pages whose module is not simply in
1939 # @INC: the page's own <directory>, else <display><directory> if there is one.
1940 sub _page_directories
1941 {
1942 my ($self, $config, @pages) = @_;
1943  
1944 my $default = $self->_pages_directory($config);
1945 my %own = map { $_->{'name'} => _resolve_directory($_->{'directory'}) } $self->_config_pages($config);
1946  
1947 my %directory;
1948 foreach my $page (@pages) {
1949 my $dir = $own{$page} // $default;
1950 $directory{$page} = $dir if(defined($dir));
1951 }
1952 return %directory;
1953 }
1954  
1955 # name => description for each page the configuration describes
1956 sub _page_descriptions
1957 {
1958 my ($self, $config) = @_;
1959  
1960 return map { $_->{'name'} => $_->{'description'} } grep { length($_->{'description'}) } $self->_config_pages($config);
1961 }
1962  
1963 # The directory the site's data files (CSV, XML, SQLite) are in:
1964 # <databases><directory>/path/to/files</directory></databases>
1965 # else the old <database_dir>, else ../databases beside the script. Data drivers are
1966 # looked for here unless <data> says otherwise.
1967 sub _database_directory_is_set
1968 {
1969 my (undef, $config) = @_;
1970  
1971 my $databases = $config->{'databases'};
1972 return 1 if(ref($databases) eq 'HASH' && defined(_resolve_directory($databases->{'directory'})));
1973 return $config->{'database_dir'} ? 1 : 0;
1974 }
1975  
1976 sub _database_directory
1977 {
1978 my (undef, $config) = @_;
1979  
1980 my $databases = $config->{'databases'};
1981 my $directory = (ref($databases) eq 'HASH') ? _resolve_directory($databases->{'directory'}) : undef;
1982 return $directory // $config->{'database_dir'} || File::Spec->catdir($script_dir // File::Spec->curdir(), File::Spec->updir(), $DEFAULT_DATABASE_DIR);
1983 }
1984  
1985 # The database directory, and a message in the log about it: info when it is there,
1986 # notice when only the default is missing (a site may have no data files at all; the
1987 # drivers it declares itself are still tried and report their own failure), and an
1988 # error when the site named a directory that is not there, which is a mistake.
1989 sub _check_database_directory
1990 {
1991 my ($self, $config, $logger) = @_;
1992  
1993 my $directory = $self->_database_directory($config);
1994 if(-d $directory) {
1995 $logger->info('Reading databases from ', $directory);
1996 } elsif($self->_database_directory_is_set($config)) {
1997 $logger->error("The databases directory $directory does not exist");
1998 } else {
1999 $logger->notice("No databases directory $directory: assuming there are no data files");
2000 }
2001 return $directory;
2002 }
2003  
2004 # The data drivers (Database::Abstraction subclasses) the site declares, as a list of
2005 # { name, module, description, file, soft } in the order they were written:
2006 # <data>
2007 # <directory>/path/to/drivers</directory>
2008 # <driver>
2009 # <name>states</name>
2010 # <description>List of data about the U.S. states</description>
2011 # <directory>/path/to/states/driver</directory>
2012 # </driver>
2013 # </data>
2014 # <databases> says where the data files are and <data> where the drivers that read
2015 # them are. (<data> as a top-level key is also handed to Database::Abstraction as
2016 # a constructor argument, which _site_setup() undoes.)
2017 # name is what the page is given (lower-cased last part), module the class, and
2018 # file where its .pm file is, or undef to find the class in @INC. A <directory>
2019 # in a <driver> beats the one in <data>, which beats the database directory, the
2020 # default. Only the <driver> one is strict: a driver that is not in the others is
2021 # looked for in @INC, so a site need not copy this distribution's own drivers into
2022 # its data directory.
2023 # What is declared, in order of preference:
2024 # 1. the <driver> elements;
2025 # 2. the old <data_modules>index, states</data_modules> string, which is also
2026 # how a site says "none" by leaving it empty;
2027 # 3. every *.pm in the <data> directory, or failing that in the database directory;
2028 # 4. the default, Web::VWF::Data::index.
2029 # A name with no :: is one of this distribution's own, so index is
2030 # Web::VWF::Data::index; a name that has :: is used as written, which is how a
2031 # site names its own modules. The file looked for in a directory is named for
2032 # the last part of the class, whichever way the class was written.
2033 sub _data_modules
2034 {
2035 my ($self, $config) = @_;
2036  
2037 my $data = $config->{'data'};
2038 my $named_dir = (ref($data) eq 'HASH') ? _resolve_directory($data->{'directory'}) : undef;
2039 my $default_dir = $named_dir // $self->_database_directory($config);
2040  
2041 my @entries = _config_entries($data, 'driver');
2042 unless(@entries) {
2043 if(defined($config->{'data_modules'})) {
2044 @entries = map { +{ name => $_, description => '', directory => '' } } $self->_config_list($config, 'data_modules');
2045 } else {
2046 @entries = map { +{ name => $_, description => '', directory => '' } } sort(map { basename($_, '.pm') } glob(File::Spec->catfile($default_dir, '*.pm')));
2047 unless(@entries) {
2048 # Nothing declared and nothing in the directory. The built-in
2049 # driver reads files from the databases directory, so with no
2050 # such directory the site has no data files and needs no driver
2051 # (its own access log is read by vwf_log, which is separate).
2052 # A directory the site named that is missing is a mistake, which
2053 # the driver then reports.
2054 return () unless(-d $default_dir || $self->_database_directory_is_set($config));
2055 # This distribution's own, from @INC
2056 return map { +{ name => lc((split(/::/, $_))[-1]), module => $_, description => '', file => undef } } @DEFAULT_DATA_MODULES;
2057 }
2058 }
2059 }
2060  
2061 my @modules;
2062 foreach my $entry (@entries) {
2063 my $module = ($entry->{'name'} =~ /::/) ? $entry->{'name'} : "Web::VWF::Data::$entry->{'name'}";
2064 my $last = (split(/::/, $module))[-1];
2065 my $own = _resolve_directory($entry->{'directory'});
2066 my $dir = $own // $default_dir;
2067 push @modules, {
2068 name => lc($last),
2069 module => $module,
2070 description => $entry->{'description'},
2071 file => File::Spec->catfile($dir, "$last.pm"),
2072 soft => defined($own) ? 0 : 1,
2073 };
2074 }
2075 return @modules;
2076 }
2077  
2078 # Read the settings this site declares, once per process, and act on them: open
2079 # the database directory it names, load the data modules it names and give the
2080 # pages the languages and addresses it names. Everything left unsaid keeps the
2081 # default it had when these values were written into this script.
2082 sub _site_setup
2083 {
2084 my $self = shift;
2085 my $config = shift;
2086  
2087 return if($self->{site_ready});
2088 # The configuration, the database directory, the
2089 # data handles and these lists last for the life of the process, not for one
2090 # request.
2091  
2092 $self->{site_ready} = 1;
2093  
2094 # Where the site's own databases are. Database::Abstraction reads them, and
2095 # the pages are told the directory as databasedir and database_dir.
2096 $database_dir = $self->_check_database_directory($config, $logger);
2097  
2098 # <databases><database> was how a site declared its drivers before 0.004.0.
2099 # It is no longer read, so say so rather than leaving the pages without data.
2100 if(ref($config->{'databases'}) eq 'HASH' && exists($config->{'databases'}{'database'})) {
2101 $logger->warn('<databases><database> is no longer read: declare each driver as <data><driver>');
2102 }
2103  
2104 Database::Abstraction::init({
2105 cache => CHI->new(driver => 'Memory', datastore => {}),
2106 cache_duration => '1 day',
2107 directory => $database_dir,
2108 logger => $logger
2109 });
2110  
2111 # The languages the site offers. CGI::Lingua negotiates within this list, so
2112 # listing a language is what makes that language's templates reachable.
2113 @supported_languages = $self->_config_list($config, 'supported_languages', @DEFAULT_SUPPORTED_LANGUAGES);
2114  
2115 # Addresses exempt from rate limiting
2116 @rate_limit_trusted_ips = $self->_config_list($config, 'rate_limit_trusted_ips', @DEFAULT_RATE_LIMIT_TRUSTED_IPS);
2117  
2118 # The site's data modules (see _data_modules). Each is loaded, constructed
2119 # with ->new() and given to every page under the last part of its name,
2120 # lower-cased: Web::VWF::Data::index arrives at a page as index, and a
2121 # site's own Bands::Data::bands as bands.
2122 foreach my $database ($self->_data_modules($config)) {
2123 my $module = $database->{'module'};
2124 my $handle;
2125 eval {
2126 if(defined($database->{'file'}) && (-f $database->{'file'} || !$database->{'soft'})) {
2127 # From the directory the site gave, not from @INC
2128 -f $database->{'file'} or die "No such file $database->{'file'}\n";
2129 require $database->{'file'};
2130 } else {
2131 # No directory given, or only the database directory by default
2132 # and the driver is not in it
2133 require_module($module);
2134 }
2135 $module->import() if($module->can('import'));
2136 $handle = $module->new();
2137 _discard_config_rows($handle);
2138 };
2139 if(!defined($handle)) {
2140 # A module the site named that cannot be loaded is reported and
2141 # skipped rather than taking the site down: it is a setting now, so
2142 # getting it wrong should not stop the pages that do not need it.
2143 $logger->error("Can't load data module $module: $@");
2144 next;
2145 }
2146  
2147 my $name = $database->{'name'};
2148 $handle->set_logger($logger) if($handle->can('set_logger'));
2149 $data{$name} = $handle;
2150 $logger->debug("Data module $module is available to pages as \$$name", length($database->{'description'}) ? ": $database->{'description'}" : '');
2151 }
2152  
2153 return 1;
2154 }
2155  
2156 # <data> is a top-level configuration key, so a Database::Abstraction handle
2157 # built while the site configures it takes the setting for the rows of its table,
2158 # and then never opens its file ("Where did the data come from?"). Discard them
2159 # so that the handle reads its own file. Every handle this module makes needs it.
2160 sub _discard_config_rows
2161 {
2162 my $handle = shift;
2163  
2164 delete $handle->{'data'} if(Scalar::Util::blessed($handle) && exists($handle->{'data'}));
2165 return $handle;
2166 }
2167  
2168 # Give the current logger to every data handle. This runs before each request,
2169 # since command-line mode replaces the logger; the handles themselves are made
2170 # once, by _site_setup().
2171 sub _set_data_loggers
2172 {
2173 my $self = shift;
2174 my $logger = shift;
2175  
2176 foreach my $handle (values %data) {
2177 $handle->set_logger($logger) if($handle->can('set_logger'));
2178 }
2179 $self->{vwf_log}->set_logger($logger) if($self->{vwf_log});
2180 }
2181  
2182 # Convert a CHI-style duration ('60s', '2 minutes', '90') to whole seconds
2183 sub duration_seconds
2184 {
2185 my $duration = shift;
2186  
2187 return $duration if($duration =~ /\A\d+\z/);
2188  
2189 require Time::Duration::Parse;
2190  
2191 my $seconds = eval { Time::Duration::Parse::parse_duration($duration) };
2192 if(!defined($seconds)) {
2193 $logger->warn("Can't parse duration '$duration', using 60 seconds");
2194 return 60;
2195 }
2196 return int($seconds);
2197 }
2198  
2199 # Check whether the current request looks like a SQL injection attempt.
2200 # IPs that trigger a match are added to the in-process %blacklisted_ip set so
2201 # that subsequent requests from the same IP are rejected without re-scanning.
2202 sub blacklisted
2203 {
2204 if(my $remote = $ENV{'REMOTE_ADDR'}) {
2205 my $info = shift;
2206  
2207 # Fast path: this IP was already blacklisted earlier in this process
2208 # lifetime; no need to re-scan the request string.
2209 if($blacklisted_ip{$remote}) {
2210 $info->status(403);
2211 return 1;
2212 }
2213  
2214 if(my $string = $info->as_string()) {
2215 # Hard length cap: skip pattern matching entirely on absurdly long
2216 # inputs. Even bounded quantifiers like {1,200} iterate many times
2217 # across a 1 MB string, so cap before we run any regex.
2218 return 0 if length($string) > 8192;
2219  
2220 # SECURITY - ReDoS defence:
2221 # The original patterns used greedy .+ between SQL keywords, which
2222 # causes catastrophic (exponential) backtracking when an attacker
2223 # sends a string that contains the opening keyword but not the
2224 # closing one (e.g. thousands of chars after SELECT with no AND).
2225 # All .+ quantifiers are replaced with the bounded class [^;]{0,N}:
2226 # - the semicolon is a natural SQL statement terminator so it is
2227 # a safe anchor that real SQL injection never crosses, and
2228 # - the explicit upper bound caps backtracking to O(N) steps.
2229 # Word-boundary assertions (\b) also eliminate false positives on
2230 # ordinary words that happen to contain the substring.
2231 if( ($string =~ /SELECT\b[^;]{0,500}\bAND\b/i)
2232 || ($string =~ /ORDER\s+BY\s/i)
2233 || ($string =~ /\bOR\s+NOT\b/i)
2234 || ($string =~ /\bAND\s+\d+=\d+/i)
2235 || ($string =~ /\bTHEN\b[^;]{0,200}\bELSE\b[^;]{0,200}\bEND\b/i)
2236 || ($string =~ /\bAND\b[^;]{0,200}\bSELECT\b/i)
2237 || ($string =~ /\sAND\s[^;]{0,100}\sAND\s/i)
2238 || ($string =~ /\bAND\s+CASE\s+WHEN\b/i)) {
2239 $blacklisted_ip{$remote} = 1;
2240 $info->status(403);
2241 return 1;
2242 }
2243 }
2244 }
2245 return 0;
2246 }
2247  
2248 # False positives we don't need in the logs
2249 sub filter
2250 {
2251 # return 0 if($_[0] =~ /Can't locate Net\/OAuth\/V1_0A\/ProtectedResourceRequest.pm in /);
2252 # return 0 if($_[0] =~ /Can't locate auto\/NetAddr\/IP\/InetBase\/AF_INET6.al in /);
2253 # return 0 if($_[0] =~ /S_IFFIFO is not a valid Fcntl macro at /);
2254  
2255 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 /;
2256 return 1;
2257 }
2258  
2259 # Escape a single value for safe inclusion in a double-quoted CSV field.
2260 # Follows RFC 4180 section 2.7 and additionally neutralises spreadsheet formulas.
2261 sub _csv_escape
2262 {
2263 my $v = shift // '';
2264  
2265 # RFC 4180: a double-quote inside a quoted field is represented by two
2266 # double-quote characters. Without this, one embedded " would break the
2267 # column boundary and corrupt every subsequent field on the row.
2268 $v =~ s/"/""/g;
2269  
2270 # SECURITY - CSV formula injection defence:
2271 # Spreadsheet applications (Excel, LibreOffice Calc) interpret cell values
2272 # that begin with = + - @ TAB or CR as formulas. An attacker who controls
2273 # a logged field (e.g. the page parameter) could inject =cmd|'/C calc'!A0.
2274 # Prefix such values with a single-quote to force literal interpretation.
2275 $v =~ s/^([=+\-@\t\r])/'$1/;
2276  
2277 return $v;
2278 }
2279  
2280 # Write one access record to vwf.log (CSV format) and optionally to syslog.
2281 # All user-influenced fields are escaped through _csv_escape before output.
2282 # Create the log file, with its header row, if there isn't one yet. Several
2283 # workers can get here at once, so it is opened for appending, which cannot
2284 # truncate another's rows, and the header is written under a lock only while the
2285 # file is empty. An empty file left by logrotate is given its header too.
2286 sub _create_vwflog
2287 {
2288 my ($vwflog) = @_;
2289  
2290 return if(-s $vwflog);
2291  
2292 open(my $fout, '>>', $vwflog);
2293 flock($fout, LOCK_EX);
2294 unless(-s $fout) {
2295 print $fout '"domain_name","time","IP","country","type","language","http_code","template","args","messages","error","duration_ms"',
2296 "\n";
2297 }
2298 close $fout;
2299 }
2300  
2301 sub _vwflog
2302 {
2303 my $self = shift;
2304  
2305 my ($vwflog, $info, $lingua, $syslog, $message, $log, $request_start) = @_;
2306  
2307 # Calculate request duration in milliseconds if a start timer was supplied.
2308 # $request_start is a Timer::Simple, so ask it for the seconds that have
2309 # passed: its numeric overload yields elapsed(), so subtracting it from the
2310 # clock gave an epoch's worth of seconds (about 1.8e12 ms per request). A
2311 # plain epoch is still accepted for callers that pass one.
2312 my $duration_ms = '';
2313 if($request_start) {
2314 my $seconds = ref($request_start) ? $request_start->elapsed() : Time::HiRes::time() - $request_start;
2315 $duration_ms = int($seconds * 1000);
2316 }
2317  
2318 # Determine which template was rendered for this request (may be empty on error).
2319 my $template;
2320 if($log) {
2321 $template = $log->template();
2322 }
2323 if(!defined($template)) {
2324 $template = '';
2325 }
2326 $message ||= '';
2327  
2328 # Collect any warn/notice-level messages emitted during this request.
2329 my $warnings;
2330 if(my $messages = $info->messages()) {
2331 $warnings = join('; ',
2332 grep defined, map { (($_->{'level'} eq 'warn') || ($_->{'level'} eq 'notice')) ? $_->{'message'} : undef } @{$messages}
2333 )
2334 }
2335 $warnings ||= '';
2336  
2337 my $country = $lingua->country() || 'unknown';
2338  
2339 # Append the record. autodie makes a failed open fatal, even inside an if,
2340 # so catch it: a full disc or wrong permissions must not crash a live request,
2341 # nor lose the syslog copy below.
2342 eval {
2343 _create_vwflog($vwflog);
2344 open(my $fout, '>>', $vwflog);
2345 # SECURITY - CSV injection defence:
2346 # Every user-visible field is passed through _csv_escape so that
2347 # embedded double-quotes cannot break the CSV column structure, and
2348 # leading formula characters cannot trigger code execution when the
2349 # file is opened in a spreadsheet application.
2350 print $fout
2351 '"', _csv_escape($info->domain_name()), '",',
2352 '"', strftime('%F %T', localtime), '",',
2353 '"', _csv_escape($ENV{REMOTE_ADDR} // ''), '",',
2354 '"', _csv_escape($country), '",',
2355 '"', _csv_escape($info->browser_type()), '",',
2356 '"', _csv_escape($lingua->language() // ''), '",',
2357 $info->status(), ',',
2358 '"', _csv_escape($template), '",',
2359 '"', _csv_escape($info->as_string(raw => 1)), '",',
2360 '"', _csv_escape($warnings), '",',
2361 '"', _csv_escape($message), '",',
2362 $duration_ms,
2363 "\n";
2364 close($fout);
2365 };
2366 $logger->warn("Can't write to $vwflog: $@") if($@ && $logger);
2367  
2368 # Optionally mirror the record to syslog (configured via the syslog stanza).
2369 if($syslog) {
2370 unless(Sys::Syslog->can('openlog')) {
2371 require Sys::Syslog;
2372 Sys::Syslog->import();
2373 }
2374  
2375 # Configure the socket transport if a hash of options was provided.
2376 if(ref($syslog) eq 'HASH') {
2377 Sys::Syslog::setlogsock($syslog);
2378 }
2379 Sys::Syslog::openlog($self->{script_name}, 'cons,pid', 'user');
2380 # Use positional %s/%d format args so that special characters in the
2381 # values cannot be interpreted as syslog format directives.
2382 Sys::Syslog::syslog('info|local0', '%s %s %s %s %s %d %s %s %d %s %s',
2383 $info->domain_name() || '',
2384 $ENV{REMOTE_ADDR} || '',
2385 $country,
2386 $info->browser_type() || '',
2387 $lingua->language() || '',
2388 $info->status() || '',
2389 $template || '',
2390 $info->as_string(raw => 1) || '',
2391 $duration_ms,
2392 $warnings,
2393 $message
2394 );
2395 Sys::Syslog::closelog();
2396 }
2397 }
2398  
2399 sub DESTROY
2400 {
2401 if(defined($^V) && ($^V ge 'v5.14.0')) {
2402 return if ${^GLOBAL_PHASE} eq 'DESTRUCT'; # >= 5.14.0 only
2403 }
2404 my $self = shift;
2405  
2406 # Clean up resources before shutdown
2407 $logger->info('Shutting down') if(defined($logger));
2408 if($buffercache && !$exit_requested) {
2409 $buffercache->purge();
2410 }
2411 if($rate_limit_cache) {
2412 # Memcached can't purge().
2413 # 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()
2414 $rate_limit_cache->purge() if($rate_limit_cache->short_driver_name() ne 'Memcached');
2415 }
2416 if(my $info_cache = $self->{info_cache}) {
2417 $info_cache->purge();
2418 }
2419 if($lingua_cache) {
2420 $lingua_cache->purge();
2421 }
2422 CHI->stats->flush();
2423 Log::WarnDie->dispatcher(undef);
2424 }
2425  
2426 =head1 AUTHOR
2427  
2428 Nigel Horne, C<< <njh at nigelhorne.com> >>
2429  
2430 =head1 LICENCE AND COPYRIGHT
2431  
2432 Copyright 2010-2026 Nigel Horne.
2433  
2434 Usage is subject to the GPL2 licence terms.
2435 If you use it,
2436 please let me know.
2437  
2438 =cut
2439  
2440 1;