TUWF.pm untested

filter: Statementstmt 0.0% 0 / 283 Branchbran 0.0% 0 / 122 Conditioncond 0.0% 0 / 94 MC/DCmcdc 0.0% 0 / 58 Subroutinesub 0.0% 0 / 54 Podpod 0.0% 0 / 36 totaltotal 0.0% 0 / 647 CC 62 SCAR 50.8
CC
62
Cov
0%
_handle_request
650.0
_handle_error
110.0
run
56.0
CRAP 161.1
1 # TUWF.pm - the core module for TUWF
2 # The Ultimate Website Framework
3  
4 package TUWF;
5  
6 use strict;
7 use warnings;
8 use Carp 'croak';
9  
10 our $VERSION = '1.6';
11  
12  
13 # Store the object in a global variable for some functions that don't get it
14 # passed as an argument. This will break when:
15 # - using a threaded environment (threading sucks anyway)
16 # - handling multiple requests asynchronously (which this framework can't do)
17 # - handling multiple sites in the same perl process. This may be useful in
18 # a mod_perl environment, which we don't support.
19 our $OBJ = bless {
20 _TUWF => {
21 route_handlers => [],
22 hooks => {
23 before => [],
24 after => [],
25 db_connect => [],
26 },
27 # defaults
28 import_modules => 1,
29 mail_from => '<noreply-yawf@blicky.net>',
30 mail_sendmail => '/usr/sbin/sendmail',
31 max_post_body => 10*1024*1024, # 10MB
32 error_400_handler => \&_error_400,
33 error_404_handler => \&_error_404,
34 error_405_handler => \&_error_405,
35 error_413_handler => \&_error_413,
36 error_500_handler => \&_error_500,
37 log_format => sub {
38 my($self, $uri, $msg) = @_;
39 sprintf "[%s] %s -> %s\n", scalar localtime(), $uri, $msg;
40 },
41 validate_templates => {},
42 custom_validations => {},
43 # No particular selection of MIME types
44 mime_types => {qw{
45 7z application/x-7z-compressed
46 aac audio/aac
47 atom application/atom+xml
48 avi video/x-msvideo
49 avif image/avif
50 bin application/octet-stream
51 bmp image/bmp
52 bz application/x-bzip2
53 css text/css
54 csv text/csv
55 gif image/gif
56 htm text/html
57 html text/html
58 ico image/x-icon
59 jpeg image/jpeg
60 jpg image/jpeg
61 js application/javascript
62 json application/json
63 jxl image/jxl
64 mjs application/javascript
65 mp3 audio/mpeg
66 mp4 video/mp4
67 mp4v video/mp4
68 mpg4 video/mp4
69 mpg video/mpeg
70 mpeg video/mpeg
71 oga audio/ogg
72 ogg audio/ogg
73 ogv video/ogg
74 otf font/otf
75 pdf application/pdf
76 png image/png
77 rar application/x-rar-compressed
78 rss application/rss+xml
79 svg image/svg+xml
80 tar application/x-tar
81 tiff image/tiff
82 ttf font/ttf
83 txt text/plain
84 webp image/webp
85 webm video/webm
86 xhtml text/html
87 xml application/xml
88 xsd application/xml
89 xsl application/xml
90 zip application/zip
91 }},
92 mime_default => 'text/plain',
93 http_server_port => $ENV{TUWF_HTTP_SERVER_PORT}||3000,
94 }
95 }, 'TUWF::Object';
96  
97  
98 sub import {
99 my $self = shift;
100 my $pack = caller();
101  
102 # Always export 'tuwf'. This can still be excluded with a '!tuwf' in @_
103 # ':xmlxs' is a legacy option that does nothing.
104 my @arg = ('tuwf', grep $_ ne ':xmlxs', @_);
105  
106 # import requested functions from TUWF submodules
107 croak $@ if !eval "package $pack; TUWF::func->import(\@arg); 1";
108 }
109  
110  
111 # get or set TUWF configuration variables
112 sub set {
113 return $OBJ->{_TUWF}{$_[0]} if @_ == 1;
114 $OBJ->{_TUWF} = { %{$OBJ->{_TUWF}}, @_ };
115 # Make sure to load TUWF::DB as soon as we have database settings.
116 $OBJ->_load_module('TUWF::DB', 1) if $OBJ->{_TUWF}{db_login};
117 }
118  
119  
120 sub run {
121 # install a warning handler to write to the log file
122 $SIG{__WARN__} = sub { $TUWF::OBJ->log($_) for @_; };
123  
124 # load optional modules
125 require Time::HiRes if $OBJ->debug || $OBJ->{_TUWF}{log_slow_pages};
126  
127 # roll back any transaction that is currently active, so we start with a
128 # clean slate for the next incoming request. Code running SQL queries during
129 # initialization is responsible for doing an explicit dbCommit() if changes
130 # should be kept.
131 $OBJ->dbRollBack if $OBJ->{_TUWF}{db_login};
132  
133 # In a FastCGI environment, STDIN will be a listen socket; getpeername() will
134 # return a ENOTCONN on those, giving us a reliable way to differentiate
135 # between CGI (env vars), FastCGI (STDIN socket), and others.
136 my(undef) = (getpeername \*STDIN);
137 my $isfastcgi = $!{ENOTCONN};
138  
139 # plain old CGI
140 if($ENV{GATEWAY_INTERFACE} && $ENV{GATEWAY_INTERFACE} =~ /CGI/i) {
141 $OBJ->_handle_request;
142  
143 # otherwise, test for FastCGI
144 } elsif($isfastcgi) {
145 require FCGI;
146 import FCGI;
147 my %env;
148 my $r = FCGI::Request(\*STDIN, \*STDOUT, \*STDERR, \%env);
149 $TUWF::Request::RENV = \%env;
150 $OBJ->{_TUWF}{fcgi_req} = $r;
151 local $SIG{TERM} = local $SIG{INT} = sub { $r->LastCall() };
152 while($r->Accept() >= 0) {
153 $OBJ->_handle_request;
154 $r->Finish();
155 last if $OBJ->{_TUWF}{fastcgi_max_requests} && !--$OBJ->{_TUWF}{fastcgi_max_requests};
156 }
157  
158 # otherwise, run our own HTTP server
159 } else {
160 require HTTP::Server::Simple;
161 require HTTP::Server::Simple::CGI::Environment;
162 $OBJ->{_TUWF}{http} = 1;
163 my $h = TUWF::http->new($OBJ->{_TUWF}{http_server_port});
164 $h->run;
165 }
166  
167 # close the DB connection
168 $OBJ->dbDisconnect if $OBJ->{_TUWF}{db_login};
169 }
170  
171  
172 # Maps URLs to handlers (legacy)
173 sub register {
174 my $a = \@_;
175 for my $i (0..$#$a/2) {
176 push @{$OBJ->{_TUWF}{route_handlers}},
177 qr{^(?:GET|POST|HEAD) /$a->[$i*2]$},
178 sub { $a->[$i*2+1]->($OBJ, @{$OBJ->{_TUWF}{captures_pos}}) }
179 }
180 }
181  
182  
183 # Register router handlers
184 sub any {
185 my($methods, $path, $sub) = @_;
186 croak 'Methods argument in route registration must be an array' if ref $methods ne 'ARRAY';
187 croak 'Path argument in route registration must be a string or regex' if ref $path && ref $path ne 'Regexp';
188 croak 'Subroutine argument in route registration must be a code reference' if ref $sub ne 'CODE';
189 my $methods_re = '(?:' . join('|', map uc, @$methods). ')';
190 my $path_re = ref $path eq 'Regexp' ? $path : quotemeta $path;
191 push @{$OBJ->{_TUWF}{route_handlers}}, qr{^$methods_re $path_re$}, $sub;
192 }
193  
194 sub get ($&) { any ['get','head'], @_ }
195 sub post ($&) { any ['post' ], @_ }
196 sub del ($&) { any ['delete' ], @_ }
197 sub options ($&) { any ['options' ], @_ }
198 sub put ($&) { any ['put' ], @_ }
199 sub patch ($&) { any ['patch' ], @_ }
200  
201  
202 sub hook ($&) {
203 my($hook, $sub) = @_;
204 croak "Unknown hook: $hook" if $hook ne 'before' && $hook ne 'after' && $hook ne 'db_connect';
205 croak 'Hooks expect a subroutine as second argument' if ref $sub ne 'CODE';
206 push @{$OBJ->{_TUWF}{hooks}{$hook}}, $sub;
207 }
208  
209  
210 # Load modules
211 sub load {
212 $OBJ->_load_module($_, $OBJ->{_TUWF}{import_modules}) for (@_);
213 }
214  
215 # Load modules, recursively
216 # All submodules should be under the same directory in @INC
217 sub load_recursive {
218 my $rec;
219 $rec = sub {
220 my($d, $f, $m) = @_;
221 for my $s (glob "\"$d/$f/*\"") {
222 $OBJ->_load_module("${m}::$1", $OBJ->{_TUWF}{import_modules}) if -f $s && $s =~ /([^\/]+)\.pm$/;
223 $rec->($d, "$f/$1", "${m}::$1") if -d $s && $s =~ /([^\/]+)$/;
224 }
225 };
226 for my $m (@_) {
227 (my $f = $m) =~ s/::/\//g;
228 my $d = (grep +(-d "$_/$f" or -s "$_/$f.pm"), @INC)[0];
229 croak "No module or submodules of '$m' found" if !$d;
230 $OBJ->_load_module($m, $OBJ->{_TUWF}{import_modules}) if -s "$d/$f.pm";
231 $rec->($d, $f, $m) if -d "$d/$f";
232 }
233 }
234  
235  
236 sub _error_400 { _very_simple_page(400, '400 - Bad Request', 'Only UTF-8 encoded data is accepted.<br><small>Stop trying to hack me!</small>') }
237 sub _error_404 {
238 _very_simple_page(404, '404 - Page Not Found', q{
239 Whatever it is you were looking for, this probably isn't it.
240 <br><small>Unless you were looking for an error page, in which case:
241 Congratulations!</small>
242 });
243 }
244 sub _error_405 { _very_simple_page(405, '405 - Method not allowed', 'Or at least, this isn\'t one of the HTTP methods that I was expecting!') }
245 sub _error_413 {
246 _very_simple_page(413, '413 - Request Entity Too Large', q{
247 That's an odd way of saying that you were probably trying to upload a large
248 file. Too large, in fact, for the server to handle. If you believe this
249 error to be mistaken, you can ask the site admin to increase the maximum
250 allowed upload size.
251 });
252 }
253 sub _error_500 {
254 _very_simple_page(500, '500 - Extraterrestrial Server Error', q{
255 Ouch! Something went wrong on the server. Perhaps a misconfiguration,
256 perhaps a bug, or perhaps just a temporary issue caused by regular
257 maintenance or maybe even alien interference. Details of this error have
258 been written to a log file. If the issue persists, please contact the site
259 admin to let them know that they might have some fixing to do.
260 });
261 }
262  
263 # a super simple page for error messages
264 sub _very_simple_page {
265 my($code, $title, $msg) = @_;
266 $OBJ->resInit;
267 $OBJ->resStatus($code);
268 $OBJ->resHeader(Allow => 'GET, HEAD, POST') if $code == 405; # XXX: not accurate, should get this from the route list.
269 my $fd = $OBJ->resFd;
270 # CSS based on http://bettermotherfuckingwebsite.com/
271 print $fd <<__;
272 <!DOCTYPE html>
273 <html>
274 <head>
275 <meta name="viewport" content="width=device-width, initial-scale=1">
276 <style type="text/css">
277 body { margin:40px auto; max-width:700px; line-height:1.6; font-size:18px; color:#444; padding:0 10px }
278 h1 { line-height:1.2 }
279 </style>
280 <title>$title</title>
281 </head>
282 <body>
283 <h1>$title</h1>
284 <p>$msg</p>
285 </body>
286 </html>
287 __
288 }
289  
290  
291  
292 # A 'redirection' namespace for all functions exported by TUWF submodules.
293 # This trick avoids having to write our own sophisticated import() function
294 package TUWF::func;
295  
296 use Exporter 'import';
297  
298 # don't 'use' the submodules, since they may export TUWF object methods by
299 # default. We're only interested in their non-method functions, which are all
300 # in @EXPORT_OK.
301 BEGIN {
302 require TUWF::DB;
303 require TUWF::Misc;
304 require TUWF::XML;
305 TUWF::DB->import(@TUWF::DB::EXPORT_OK);
306 TUWF::Misc->import(@TUWF::Misc::EXPORT_OK);
307 TUWF::XML->import(@TUWF::XML::EXPORT_OK);
308 }
309 our @EXPORT_OK = (
310 @TUWF::DB::EXPORT_OK,
311 @TUWF::Misc::EXPORT_OK,
312 @TUWF::XML::EXPORT_OK,
313 );
314 our @EXPORT = ('tuwf');
315 our %EXPORT_TAGS = %TUWF::XML::EXPORT_TAGS;
316  
317 sub tuwf() { $TUWF::OBJ }
318  
319  
320  
321 # The namespace which inherits all functions to be available in the global
322 # object.
323 package TUWF::Object;
324  
325 use TUWF::Response;
326 use TUWF::Request;
327 use TUWF::Misc;
328  
329 require Carp; # but don't import()
330 our @CARP_NOT = ('TUWF');
331  
332  
333 sub _load_module {
334 my($self, $module, $import) = @_;
335 my $r = $import
336 ? eval "use $module; 1"
337 : eval "require $module; 1";
338 Carp::croak $@ if !$r;
339 }
340  
341  
342 # Handles a request (sounds pretty obvious to me...)
343 sub _handle_request {
344 my $self = shift;
345  
346 # HTTP::Server::Simple modifies SIGCHLD in a way that breaks every approach
347 # to spawning a subprocess. Let's reset SIGCHLD to fix that.
348 # https://rt.cpan.org/Public/Bug/Display.html?id=71045
349 local $SIG{CHLD} = undef if $OBJ->{_TUWF}{http};
350  
351 my $start = [Time::HiRes::gettimeofday()] if $self->debug || $OBJ->{_TUWF}{log_slow_pages};
352  
353 local $self->{_TUWF}{request_data} = {};
354 $self->{_TUWF}{captures_pos} = [];
355 $self->{_TUWF}{captures_named} = {};
356  
357 # put everything in an eval to catch any error, even
358 # those caused by a TUWF core module
359 my $eval = eval {
360 # initialze response
361 $self->resInit();
362  
363 # initialize request
364 $self->reqInit();
365  
366 # make sure our DB connection is still there and start a new transaction
367 $self->dbCheck() if $self->{_TUWF}{db_login};
368  
369 # call pre request handler, if any
370 return 1 if $self->{_TUWF}{pre_request_handler} && !$self->{_TUWF}{pre_request_handler}->($self);
371  
372 # run 'before' hooks
373 for (@{$self->{_TUWF}{hooks}{before}}) {
374 my $ok = eval { $_->(); 1; };
375 next if $ok;
376 next if ref $@ eq 'TUWF::Exception' && ${$@} eq 'pass';
377 return 1 if ref $@ eq 'TUWF::Exception' && ${$@} eq 'done';
378 die $@;
379 }
380  
381 # find the handler
382 my $loc = sprintf '%s %s', $self->reqMethod(), $self->reqPath();
383 study $loc;
384 my $han = 0;
385 my $handlers = $self->{_TUWF}{route_handlers};
386 for (@$handlers ? 0..$#$handlers/2 : ()) {
387 if($loc =~ $handlers->[$_*2]) {
388 $han = 1;
389 $self->{_TUWF}{captures_pos} = [
390 map defined $-[$_] ? substr $loc, $-[$_], $+[$_]-$-[$_] : undef, 1..$#-
391 ];
392 $self->{_TUWF}{captures_named} = { %+ };
393  
394 my $ok = eval { $handlers->[$_*2+1]->($self); 1 };
395 last if $ok;
396 ($han = 0, next) if ref $@ eq 'TUWF::Exception' && ${$@} eq 'pass';
397 last if ref $@ eq 'TUWF::Exception' && ${$@} eq 'done';
398 die $@;
399 }
400 }
401  
402 $self->resNotFound if !$han;
403  
404 # execute post request handler, if any (no need to bother doing this if the
405 # handler threw a TUWF::Exception like with the after hooks. The
406 # post_request_handler is deprecated and that mechanism didn't exist back
407 # then anyway).
408 $self->{_TUWF}{post_request_handler}->($self) if $self->{_TUWF}{post_request_handler};
409 1;
410 };
411 my $evalerr = $@;
412  
413 # always run 'after' hooks
414 my $cleanup = eval {
415 for (@{$self->{_TUWF}{hooks}{after}}) {
416 my $ok = eval { $_->(); 1 };
417 next if $ok;
418 next if ref $@ eq 'TUWF::Exception' && ${$@} eq 'pass';
419 next if ref $@ eq 'TUWF::Exception' && ${$@} eq 'done';
420 die $@;
421 }
422 1;
423 };
424 my $cleanuperr = $@;
425  
426 # commit changes if everything went okay
427 my $commit = eval {
428 if($eval && $cleanup && $self->{_TUWF}{db_login}) {
429 $self->dbCommit;
430 }
431 1;
432 };
433 my $commiterr = $@;
434  
435 # error handling
436 $self->_handle_error($evalerr || $cleanuperr || $commiterr) if !$eval || !$cleanup || !$commit;
437  
438 # finalize response (flush output, etc)
439 warn $@ if !eval { $self->resFinish; 1 };
440  
441 # log debug information in the form of:
442 # > 12ms (SQL: 8ms, 2 qs) for http://beta.vndb.org/v10
443 my $time = Time::HiRes::tv_interval($start)*1000 if $self->debug || $self->{_TUWF}{log_slow_pages};
444 if($self->debug || ($self->{_TUWF}{log_slow_pages} && $self->{_TUWF}{log_slow_pages} < $time)) {
445 # SQL stats (don't count the ping and commit as queries, but do count their time)
446 my($sqlt, $sqlc) = (0, 0);
447 if($self->{_TUWF}{db_login}) {
448 $sqlc = grep $_->[0] ne 'ping/rollback' && $_->[0] ne 'commit', @{$self->{_TUWF}{DB}{queries}};
449 $sqlt += $_->[2]*1000 for (@{$self->{_TUWF}{DB}{queries}});
450 }
451  
452 $self->log(sprintf('%4dms (SQL:%4dms,%3d qs)', $time, $sqlt, $sqlc));
453 }
454 }
455  
456  
457 sub _handle_error {
458 my($self, $err) = @_;
459 my $terr = ref $err eq 'TUWF::Exception' ? $$err : '';
460  
461 # act as if the changes to the DB never happened
462 warn $@ if $self->{_TUWF}{db_login} && !eval { $self->dbRollBack; 1 };
463  
464 warn "Client sent non-UTF-8-encoded data. Generating HTTP 400 response.\n" if $terr eq 'utf8';
465 warn "Client sent control characters in strings. Generating HTTP 400 response.\n" if $terr eq 'controlchar';
466 warn "Client sent an invalid JSON object. Generating HTTP 400 response.\n" if $terr eq 'json';
467  
468 my $han = {
469 utf8 => 400,
470 json => 400,
471 controlchar => 400,
472 method => 405,
473 maxpost => 413,
474 }->{$terr} || '500';
475  
476 my $ok = eval {
477 $self->resInit;
478 $self->{_TUWF}{"error_${han}_handler"}->($self, $err);
479 1;
480 };
481 if(!$ok) {
482 $err = $@;
483 $ok = eval {
484 $self->resInit;
485 $self->{_TUWF}{error_500_handler}->($self, $err);
486 1;
487 };
488 }
489 if(!$ok) {
490 $err = $@;
491 warn "Error handler died as well, something is seriously wrong with your code. ($err)\n";
492 TUWF::_error_500($self, $err);
493 }
494  
495 # If this is an unexpected error, write detailed information to the log
496 $self->log(
497 "FATAL ERROR!\n".
498 "HTTP Request Headers:\n".
499 join('', map sprintf(" %s: %s\n", $_, $self->reqHeader($_)), $self->reqHeader).
500 "POST dump:\n".
501 ($self->reqJSON()
502 ? TUWF::Misc::_JSON()->new->pretty->encode($self->reqJSON())
503 : join('', map sprintf(" %s: %s\n", $_, join "\n ", $self->reqPosts($_)), $self->reqPosts)
504 ).
505 "Error:\n $err\n"
506 ) if ref $err ne 'TUWF::Exception';
507 }
508  
509  
510 # convenience function
511 sub debug {
512 return shift->{_TUWF}{debug};
513 }
514  
515  
516 sub capture {
517 my($self, $key) = @_;
518 $key =~ /^[0-9]+$/
519 ? $self->{_TUWF}{captures_pos}[$key-1]
520 : $self->{_TUWF}{captures_named}{$key};
521 }
522  
523  
524 sub captures {
525 my $self = shift;
526 map $self->capture($_), @_;
527 }
528  
529  
530 # writes a message to the log file. date, time and URL are automatically added
531 our $_recursive_log = 0;
532 sub log {
533 my($self, $msg) = @_;
534  
535 # temporarily disable the warnings-to-log, to avoid infinite recursion if
536 # this function throws a warning.
537 my $recursive = $_recursive_log;
538 local $SIG{__WARN__} = undef;
539 local $_recursive_log = 1;
540  
541 my $uri = $self->{_TUWF}{Req} ? $self->reqURI : '[init]';
542 chomp $msg;
543 $msg =~ s/\n/\n | /g;
544 $msg = $recursive ? sprintf "[%s] [log_format] %s -> %s\n", scalar localtime(), $uri, $msg
545 : $self->{_TUWF}{log_format}->($self, $uri, $msg);
546  
547 if($self->{_TUWF}{logfile} && open my $F, '>>:utf8', $self->{_TUWF}{logfile}) {
548 flock $F, 2;
549 seek $F, 0, 2;
550 print $F $msg;
551 flock $F, 4;
552 close $F;
553 }
554 # Also always dump stuff to STDERR during init or if we're running a standalone HTTP server.
555 warn $msg if $self->{_TUWF}{http} || !$self->{_TUWF}{Req};
556 }
557  
558  
559 sub pass {
560 die TUWF::Exception->new('pass');
561 }
562  
563  
564 sub done {
565 die TUWF::Exception->new('done');
566 }
567  
568  
569 sub req {
570 shift->{_TUWF}{request_data}
571 }
572  
573  
574  
575 # Minimal subclass of HTTP::Server::Simple with CGI environment variables.
576 package TUWF::http;
577  
578 use strict;
579 use warnings;
580 our @ISA = qw{
581 HTTP::Server::Simple
582 HTTP::Server::Simple::CGI::Environment
583 };
584  
585 sub accept_hook { shift->setup_environment }
586 sub setup { shift->setup_environment_from_metadata(@_) }
587  
588 sub handler {
589 shift->setup_server_url;
590 $TUWF::OBJ->_handle_request;
591 };
592  
593  
594  
595  
596 # Objects for die() (just blessed strings)
597 package TUWF::Exception;
598  
599 use overload '""' => sub { "TUWF::Exception: ${$_[0]}" };
600  
601 sub new { bless \"$_[1]", $_[0] }
602  
603 1;