blib/lib/Web/VWF.pm untested

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