blib/lib/Web/VWF.pm untested

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