| 1 | # | ||
| 2 | # This file is part of WebDyne. | ||
| 3 | # | ||
| 4 | # This software is copyright (c) 2026 by Andrew Speer <andrew.speer@isolutions.com.au>. | ||
| 5 | # | ||
| 6 | # This is free software; you can redistribute it and/or modify it under | ||
| 7 | # the same terms as the Perl 5 programming language system itself. | ||
| 8 | # | ||
| 9 | # Full license text is available at: | ||
| 10 | # | ||
| 11 | # <http://dev.perl.org/licenses/> | ||
| 12 | # | ||
| 13 | package WebDyne::PSGI; | ||
| 14 | |||
| 15 | |||
| 16 | # Compiler Pragma | ||
| 17 | # | ||
| 18 | 2 | ▶ | use strict qw(vars); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 19 | 2 | ▶ | use vars qw($VERSION); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 20 | 2 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 21 | 2 | ▶ | no warnings qw(uninitialized); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 22 | |||
| 23 | |||
| 24 | # External Modules | ||
| 25 | # | ||
| 26 | 2 | ▶ | use HTTP::Status qw(:constants is_success is_error); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 27 | 2 | ▶ | use IO::String; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 28 | 2 | ▶ | use Data::Dumper; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 29 | 2 | ▶ | use Cwd qw(fastcwd); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 30 | 2 | ▶ | use File::Spec; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 31 | 0 | ▶ | use Plack::Builder; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 32 | |||
| 33 | |||
| 34 | # PSGI modules | ||
| 35 | # | ||
| 36 | use Plack::Request; | ||
| 37 | use Plack::Response; | ||
| 38 | |||
| 39 | |||
| 40 | # WebDyne Modules | ||
| 41 | # | ||
| 42 | use WebDyne; | ||
| 43 | use WebDyne::Constant; | ||
| 44 | use WebDyne::Util; | ||
| 45 | use WebDyne::PSGI::Constant; | ||
| 46 | use WebDyne::Request::PSGI; | ||
| 47 | |||
| 48 | |||
| 49 | # Environment | ||
| 50 | # | ||
| 51 | my %ENV_BASE=( | ||
| 52 | %{$WEBDYNE_PSGI_ENV_SET}, | ||
| 53 | (map { $_=>$ENV{$_} } ( | ||
| 54 | grep { defined($ENV{$_}) } | ||
| 55 | qw(DOCUMENT_DEFAULT DOCUMENT_ROOT SERVER_NAME APPL_MD_PATH), | ||
| 56 | @{$WEBDYNE_PSGI_ENV_KEEP}, | ||
| 57 | (grep {/^WEBDYNE/i} keys %ENV), # Note not WEBDYNE_, just /WEBDYNE/i to allow for DirConfig type entries such as WebDyneHandler | ||
| 58 | (grep {/^HTTP_/i} keys %ENV), | ||
| 59 | (grep {/^CONTENT_/i} keys %ENV) | ||
| 60 | )) | ||
| 61 | ); | ||
| 62 | |||
| 63 | |||
| 64 | # Version information | ||
| 65 | # | ||
| 66 | $VERSION='3.029'; | ||
| 67 | |||
| 68 | |||
| 69 | #================================================================================================== | ||
| 70 | |||
| 71 | sub new { | ||
| 72 | |||
| 73 | |||
| 74 | # Get options | ||
| 75 | # | ||
| 76 | my ($class, %opt)=@_; | ||
| 77 | |||
| 78 | |||
| 79 | # Test ? | ||
| 80 | # | ||
| 81 | if ($opt{'test'}) { | ||
| 82 | $opt{'root'}=$WEBDYNE_DEFAULT_TEST_FN; | ||
| 83 | } | ||
| 84 | |||
| 85 | |||
| 86 | # Indexing. 1 for enable with internal, string for some other indexing file | ||
| 87 | # | ||
| 88 | if ($opt{'index'} eq '1') { | ||
| 89 | $opt{'index'}=$WEBDYNE_DEFAULT_INDEX_FN; | ||
| 90 | } | ||
| 91 | |||
| 92 | |||
| 93 | # Fix document root | ||
| 94 | # | ||
| 95 | $opt{'root'}=File::Spec->rel2abs($opt{'root'}); | ||
| 96 | |||
| 97 | |||
| 98 | # Load local config if requested. Keep the default off so direct | ||
| 99 | # WebDyne::PSGI->new()->to_app callers preserve existing behaviour. | ||
| 100 | # | ||
| 101 | if ($opt{'conf'}) { | ||
| 102 | $class->local_constant_load($opt{'root'}, $opt{'conf'}); | ||
| 103 | } | ||
| 104 | |||
| 105 | |||
| 106 | # API file name cache | ||
| 107 | # | ||
| 108 | $opt{'API_fn'}={}; | ||
| 109 | |||
| 110 | |||
| 111 | # Done | ||
| 112 | # | ||
| 113 | return bless(\%opt, $class); | ||
| 114 | |||
| 115 | } | ||
| 116 | |||
| 117 | |||
| 118 | sub to_app { | ||
| 119 | |||
| 120 | |||
| 121 | # Self ref | ||
| 122 | # | ||
| 123 | my $self=shift(); | ||
| 124 | |||
| 125 | |||
| 126 | # Dispatch code ref | ||
| 127 | # | ||
| 128 | my $app_cr=sub { $self->handler(@_) }; | ||
| 129 | |||
| 130 | |||
| 131 | # Wrap with configured PSGI middleware. | ||
| 132 | # | ||
| 133 | $app_cr=$self->build($app_cr); | ||
| 134 | |||
| 135 | |||
| 136 | # Done | ||
| 137 | # | ||
| 138 | return $app_cr; | ||
| 139 | |||
| 140 | } | ||
| 141 | |||
| 142 | |||
| 143 | sub build { | ||
| 144 | |||
| 145 | |||
| 146 | # Wrap a PSGI app code ref in configured middleware. | ||
| 147 | # | ||
| 148 | my ($self, $app_cr)=@_; | ||
| 149 | |||
| 150 | |||
| 151 | # Build middleware stack | ||
| 152 | # | ||
| 153 | my $builder_or=Plack::Builder->new(); | ||
| 154 | |||
| 155 | |||
| 156 | # Static service can be overridden per instance without changing the | ||
| 157 | # package default for later apps in the same interpreter. | ||
| 158 | # | ||
| 159 | my $static_fg=$WEBDYNE_PSGI_STATIC; | ||
| 160 | $static_fg=$self->{'static'} if exists($self->{'static'}); | ||
| 161 | |||
| 162 | |||
| 163 | # Add configured middleware. | ||
| 164 | # | ||
| 165 | foreach my $middleware_ar (@{$WEBDYNE_PSGI_MIDDLEWARE}) { | ||
| 166 | my ($middleware, $middleware_opt_hr)=@{$middleware_ar}; | ||
| 167 | |||
| 168 | # Skip static if not wanted | ||
| 169 | # | ||
| 170 | if ($middleware eq 'Static') { | ||
| 171 | next unless $static_fg; | ||
| 172 | } | ||
| 173 | |||
| 174 | |||
| 175 | # And code refs are run and given self as first param | ||
| 176 | # | ||
| 177 | if (ref($middleware_opt_hr) eq 'CODE') { | ||
| 178 | $middleware_opt_hr=$middleware_opt_hr->($self); | ||
| 179 | } | ||
| 180 | |||
| 181 | |||
| 182 | # Now add it | ||
| 183 | # | ||
| 184 | $builder_or->add_middleware($middleware, %{$middleware_opt_hr}); | ||
| 185 | } | ||
| 186 | |||
| 187 | |||
| 188 | # Done | ||
| 189 | # | ||
| 190 | return $builder_or->to_app($app_cr); | ||
| 191 | |||
| 192 | } | ||
| 193 | |||
| 194 | |||
| 195 | sub local_constant_load { | ||
| 196 | |||
| 197 | |||
| 198 | # Read in local webdyne.conf.pl | ||
| 199 | # | ||
| 200 | my ($class, $root_dn, $conf)=@_; | ||
| 201 | |||
| 202 | |||
| 203 | # If root_dn is a file get dir name | ||
| 204 | # | ||
| 205 | if (-f $root_dn) { | ||
| 206 | $root_dn=(File::Spec->splitpath($root_dn))[1]; | ||
| 207 | } | ||
| 208 | |||
| 209 | |||
| 210 | # Resolve conf option. 1 means root/.webdyne.conf.pl, otherwise use | ||
| 211 | # explicit path relative to root unless already absolute. | ||
| 212 | # | ||
| 213 | my $conf_fn; | ||
| 214 | if ($conf eq '1') { | ||
| 215 | $conf_fn=File::Spec->catfile($root_dn, sprintf('.%s', $WEBDYNE_CONF_FN)); | ||
| 216 | } | ||
| 217 | else { | ||
| 218 | $conf_fn=File::Spec->file_name_is_absolute($conf) ? | ||
| 219 | $conf : | ||
| 220 | File::Spec->catfile($root_dn, $conf); | ||
| 221 | } | ||
| 222 | |||
| 223 | |||
| 224 | # Load via existing constant import path. | ||
| 225 | # | ||
| 226 | WebDyne::Constant->import($conf_fn); | ||
| 227 | return $conf_fn; | ||
| 228 | |||
| 229 | } | ||
| 230 | |||
| 231 | |||
| 232 | # Actual Plack handler | ||
| 233 | # | ||
| 234 | sub handler { | ||
| 235 | |||
| 236 | |||
| 237 | # Get env | ||
| 238 | # | ||
| 239 | my ($self, $env_hr, @param)=@_; | ||
| 240 | $env_hr={%{$env_hr}}; | ||
| 241 | debug('in handler, self: %s, env: %s, param:%s', Dumper($self, $env_hr, \@param)); | ||
| 242 | |||
| 243 | |||
| 244 | # Set up | ||
| 245 | # | ||
| 246 | local %ENV=(%ENV_BASE, %{$env_hr}); | ||
| 247 | my @env_key=keys %ENV; | ||
| 248 | |||
| 249 | |||
| 250 | # Setup request and response handlers | ||
| 251 | # | ||
| 252 | my $req_or=Plack::Request->new($env_hr); | ||
| 253 | my $res_or=Plack::Response->new(HTTP_OK); | ||
| 254 | |||
| 255 | |||
| 256 | # Create new PSGI Request object, will pull filename from | ||
| 257 | # environment. | ||
| 258 | # | ||
| 259 | my $html; | ||
| 260 | my $html_fh=IO::String->new($html); | ||
| 261 | my $r=WebDyne::Request::PSGI->new(select => $html_fh, document_root => $self->{'root'}, document_default => $self->{'index'}, env=>$env_hr, req=>$req_or, res=>$res_or, no_head_insert=>$self->{'no_head_insert'}, filename=>$self->{'filename'}, @param) || | ||
| 262 | return err('unable to create new WebDyne::Request::PSGI object: %s', | ||
| 263 | $@ || errclr() || 'unknown error'); | ||
| 264 | debug("r: $r"); | ||
| 265 | |||
| 266 | # Bound the complete body before page execution. Replay it for CGI and | ||
| 267 | # Plack readers, including API redispatch, without rewriting caller metadata. | ||
| 268 | # CGI needs a byte length even when the original request omitted one. | ||
| 269 | # | ||
| 270 | my ($body, $error); | ||
| 271 | { | ||
| 272 | # Input failures are handled here, not by the page exception hook. | ||
| 273 | local $SIG{__DIE__}; | ||
| 274 | $body=eval { $r->body() }; | ||
| 275 | $error=$@; | ||
| 276 | } | ||
| 277 | if ($error) { | ||
| 278 | return psgi_error($r, $r->{'body_status'} || HTTP_BAD_REQUEST, $error); | ||
| 279 | } | ||
| 280 | $env_hr->{'webdyne.psgi.body'}=\$body; | ||
| 281 | $env_hr->{'psgi.input'}=IO::String->new($body); | ||
| 282 | $env_hr->{'CONTENT_LENGTH'}=length($body) unless defined($env_hr->{'CONTENT_LENGTH'}); | ||
| 283 | $ENV{'CONTENT_LENGTH'}=$env_hr->{'CONTENT_LENGTH'}; | ||
| 284 | $r->{'req'}=Plack::Request->new($env_hr); | ||
| 285 | |||
| 286 | |||
| 287 | # Get handler | ||
| 288 | # | ||
| 289 | my $handler=$self->{'handler'} ||= 'WebDyne'; | ||
| 290 | |||
| 291 | |||
| 292 | # Call handler and evaluate results | ||
| 293 | # | ||
| 294 | my $status=eval {$handler->handler($r)}; | ||
| 295 | debug("handler returned status: $status"); | ||
| 296 | |||
| 297 | |||
| 298 | # Can close html file handle now | ||
| 299 | # | ||
| 300 | $html_fh->close(); | ||
| 301 | debug("html returned: $html"); | ||
| 302 | |||
| 303 | |||
| 304 | # Present error if non 200 (success) status returned. Yes - there are other status codes but this is most | ||
| 305 | # common and quickest test, other 200 codes will fall through the if/else statements and still work | ||
| 306 | # | ||
| 307 | unless ($status == HTTP_OK) { | ||
| 308 | |||
| 309 | # OK. Most common match didn't happen. Is it an error ? | ||
| 310 | # | ||
| 311 | debug('status: %s is not HTTP_OK, branching', $status); | ||
| 312 | if (!defined($status) || ($status < 0) || is_error($status) || !$html) { | ||
| 313 | |||
| 314 | |||
| 315 | # Something went wrong. Let's start working through it | ||
| 316 | # | ||
| 317 | if (($status eq HTTP_NOT_FOUND) && !(-f (my $fn=$r->filename()))) { | ||
| 318 | |||
| 319 | |||
| 320 | # We couldn't find file but this might be an API request. Go back through | ||
| 321 | # file paths looking for a file that matches the apu request, e.g. if URI | ||
| 322 | # is /api/user/42 go back looking for /api/user.psp or /api.psp in the treet | ||
| 323 | # | ||
| 324 | debug("status: $status, fn: $fn"); | ||
| 325 | if (my $api_fn=$self->api_filename($r)) { | ||
| 326 | debug("status: $status, fn:$fn (%s), found API match, dispatching", $r->filename()); | ||
| 327 | my %api_env=%{$env_hr}; | ||
| 328 | my $api_path=File::Spec->abs2rel($api_fn, $r->document_root); | ||
| 329 | $api_path=~s{\Q@{[WEBDYNE_PSP_EXT]}\E$}{}; | ||
| 330 | |||
| 331 | # Treat the discovered API file path as the mount point. | ||
| 332 | # If /example/api.psp owns /example/api/foo, the route | ||
| 333 | # pattern inside the file is just /foo. This deliberately | ||
| 334 | # decouples the PSP filename from the Router::Simple path. | ||
| 335 | # | ||
| 336 | $api_env{'PATH_INFO'}=~s{^/\Q$api_path\E(?=/|$)}{}i; | ||
| 337 | return $self->handler(\%api_env, filename=>$api_fn); | ||
| 338 | } | ||
| 339 | |||
| 340 | |||
| 341 | # If get here nothing found, send 404 error | ||
| 342 | # | ||
| 343 | debug("status: $status, fn:$fn, setting HTTP_NOT_FOUND"); | ||
| 344 | $r->status(HTTP_NOT_FOUND); | ||
| 345 | my $error=errstr() || "File not found, status ($status)"; | ||
| 346 | my $errdump=errdump(); | ||
| 347 | errclr(); | ||
| 348 | #$html=$r->err_html($status, $error) | ||
| 349 | return psgi_error($r, $status, $error, $errdump ); | ||
| 350 | } | ||
| 351 | elsif (is_error($status)) { | ||
| 352 | |||
| 353 | # Some other error besides 404 | ||
| 354 | # | ||
| 355 | debug("returning custom error: $status"); | ||
| 356 | $r->status($status); | ||
| 357 | $html=$r->custom_response($status); | ||
| 358 | unless ($html=~/^<!DOCTYPE html>/) { | ||
| 359 | # Not a HTML error, revert to text | ||
| 360 | my $error=$html || errstr() || $@ || | ||
| 361 | "Error $status with no content - try server error logs ?"; | ||
| 362 | my $errdump=errdump(); | ||
| 363 | errclr(); | ||
| 364 | return psgi_error($r, $status, $error, $errdump); | ||
| 365 | } | ||
| 366 | else { | ||
| 367 | # HTML error, keep going - will be displayed as-s | ||
| 368 | } | ||
| 369 | } | ||
| 370 | else { | ||
| 371 | |||
| 372 | # Weird non HTTP status code, something has gone wrong along way | ||
| 373 | # | ||
| 374 | debug('undefined status returned, looking for error handler'); | ||
| 375 | my $error=errstr() || $@; | ||
| 376 | my $errdump=errdump(); | ||
| 377 | errclr(); | ||
| 378 | $error ||= "Unexpected return status ($status) from handler $handler"; | ||
| 379 | debug("request handler status:$status, detected error: $error, calling err_html"); | ||
| 380 | $r->status(HTTP_INTERNAL_SERVER_ERROR); | ||
| 381 | #$html=$r->err_html($status, $error) | ||
| 382 | return psgi_error($r, $status, $error, $errdump); | ||
| 383 | |||
| 384 | } | ||
| 385 | |||
| 386 | } | ||
| 387 | else { | ||
| 388 | |||
| 389 | |||
| 390 | # Not an error, but not HTTP_OK | ||
| 391 | # | ||
| 392 | debug("status: $status is not an error, proceeding"); | ||
| 393 | |||
| 394 | } | ||
| 395 | |||
| 396 | } | ||
| 397 | debug("final handler status: %s, content_type: %s, html:%s", $status, $r->content_type(), $html); | ||
| 398 | |||
| 399 | |||
| 400 | # If html defined set header content type unless already set during handler run | ||
| 401 | # | ||
| 402 | $r->content_type($WEBDYNE_CONTENT_TYPE_HTML) | ||
| 403 | if ($html && !$r->content_type()); | ||
| 404 | |||
| 405 | |||
| 406 | # HTTP bodies contain bytes, and Content-Length counts encoded bytes. | ||
| 407 | # | ||
| 408 | if (utf8::is_utf8($html)) { | ||
| 409 | utf8::encode($html); | ||
| 410 | my $headers_or=$r->headers_out(); | ||
| 411 | delete $headers_or->{$_} foreach grep {lc($_) eq 'content-length'} keys %{$headers_or}; | ||
| 412 | $headers_or->header('Content-Length' => length($html)); | ||
| 413 | } | ||
| 414 | |||
| 415 | |||
| 416 | # Return structure | ||
| 417 | # | ||
| 418 | my @return=( | ||
| 419 | $r->status() || HTTP_INTERNAL_SERVER_ERROR, | ||
| 420 | $r->headers_out()->psgi_flatten_without_sort(), | ||
| 421 | [ $html ] | ||
| 422 | ); | ||
| 423 | |||
| 424 | |||
| 425 | # Finished with response handler now | ||
| 426 | # | ||
| 427 | $r->DESTROY(); | ||
| 428 | |||
| 429 | |||
| 430 | # Env changed ? | ||
| 431 | # | ||
| 432 | if (keys %ENV != @env_key) { | ||
| 433 | debug('ENV keys changed, checking'); | ||
| 434 | my %env=%ENV; | ||
| 435 | delete @env{@env_key}; | ||
| 436 | debug('keys to add into ENV_BASE: %s', Dumper(\%env)); | ||
| 437 | map {$ENV_BASE{$_}=$ENV{$_}} keys %env; | ||
| 438 | } | ||
| 439 | |||
| 440 | |||
| 441 | # And return | ||
| 442 | # | ||
| 443 | debug('return %s', Dumper(\@return)); | ||
| 444 | return \@return; | ||
| 445 | |||
| 446 | |||
| 447 | } | ||
| 448 | |||
| 449 | |||
| 450 | sub api_filename { | ||
| 451 | |||
| 452 | my ($self, $r)=@_; | ||
| 453 | return unless WEBDYNE_API_ENABLE; | ||
| 454 | |||
| 455 | my $path=$ENV{'PATH_INFO'} || ''; | ||
| 456 | return unless length($path); | ||
| 457 | |||
| 458 | my @part=grep { length($_) } split(m{/+}, $path); | ||
| 459 | return if grep { $_ eq '.' || $_ eq '..' } @part; | ||
| 460 | |||
| 461 | my $document_root=File::Spec->rel2abs($r->document_root); | ||
| 462 | my $API_fn=$self->{'API_fn'}; | ||
| 463 | for my $ix (0 .. $#part) { | ||
| 464 | my $api_fn=File::Spec->catfile($document_root, @part[0 .. $ix]); | ||
| 465 | $api_fn .= WEBDYNE_PSP_EXT unless $api_fn =~ WEBDYNE_PSP_EXT_RE; | ||
| 466 | debug("check $api_fn"); | ||
| 467 | |||
| 468 | # Check of outside docroot | ||
| 469 | # | ||
| 470 | my $relative=File::Spec->abs2rel($api_fn, $document_root); | ||
| 471 | next if $relative eq '..' || $relative =~ /^\.\.(?:[\\\/]|$)/; | ||
| 472 | if ($API_fn->{$api_fn} || (-f $api_fn)) { | ||
| 473 | debug("found api file name: $api_fn, %s, dispatching", Dumper($API_fn)); | ||
| 474 | $API_fn->{$api_fn}++; # Cache so not stat()ing on file system | ||
| 475 | return $api_fn; | ||
| 476 | } | ||
| 477 | } | ||
| 478 | |||
| 479 | return; | ||
| 480 | } | ||
| 481 | |||
| 482 | |||
| 483 | sub psgi_error { | ||
| 484 | |||
| 485 | # Return HTML or text error | ||
| 486 | # | ||
| 487 | my ($r, $status, $error, $errdump)=@_; | ||
| 488 | debug("in PSGI error handler, r: $r, status: $status, error: $error"); | ||
| 489 | unless (is_error($status)) { | ||
| 490 | $status=HTTP_INTERNAL_SERVER_ERROR; | ||
| 491 | } | ||
| 492 | my ($content_type, $body); | ||
| 493 | if ($WEBDYNE_ERROR_TEXT) { | ||
| 494 | $content_type=$WEBDYNE_CONTENT_TYPE_TEXT; | ||
| 495 | $body=$errdump || $error; | ||
| 496 | } | ||
| 497 | else { | ||
| 498 | if (eval {$body=$r->err_html($status, $error)}) { | ||
| 499 | $content_type=$WEBDYNE_CONTENT_TYPE_HTML; | ||
| 500 | } | ||
| 501 | else { | ||
| 502 | $body=$errdump || $error; | ||
| 503 | $content_type=$WEBDYNE_CONTENT_TYPE_TEXT; | ||
| 504 | } | ||
| 505 | } | ||
| 506 | my @return=( | ||
| 507 | $status, | ||
| 508 | ['Content-Type' => $content_type], | ||
| 509 | [$body] | ||
| 510 | ); | ||
| 511 | $r->DESTROY(); | ||
| 512 | debug('return: %s', Dumper(\@return)); | ||
| 513 | return \@return; | ||
| 514 | |||
| 515 | } | ||
| 516 | |||
| 517 | |||
| 518 | |||
| 519 | __END__ | ||