| 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::PAGI; | ||
| 14 | |||
| 15 | |||
| 16 | # Compiler Pragma | ||
| 17 | # | ||
| 18 | 1 | ▶ | use strict qw(vars); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 19 | 1 | ▶ | use vars qw($VERSION); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 20 | 1 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 21 | 1 | ▶ | no warnings qw(uninitialized); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 22 | |||
| 23 | |||
| 24 | # External Modules | ||
| 25 | # | ||
| 26 | 1 | ▶ | use HTTP::Status qw(:constants is_success is_error); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 27 | 1 | ▶ | use IO::String; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 28 | 1 | ▶ | use Data::Dumper; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 29 | 1 | ▶ | use Cwd qw(fastcwd); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 30 | 0 | ▶ | use Future::AsyncAwait; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 31 | use Sub::Util qw(set_subname); | ||
| 32 | use File::Basename; | ||
| 33 | use File::Spec; | ||
| 34 | use Scalar::Util qw(blessed reftype); | ||
| 35 | |||
| 36 | |||
| 37 | # PAGI modules | ||
| 38 | # | ||
| 39 | use PAGI::Request; | ||
| 40 | use PAGI::Response; | ||
| 41 | |||
| 42 | |||
| 43 | # WebDyne Modules | ||
| 44 | # | ||
| 45 | use WebDyne; | ||
| 46 | use WebDyne::Constant; | ||
| 47 | use WebDyne::Util; | ||
| 48 | use WebDyne::PAGI::Constant; | ||
| 49 | use WebDyne::Request::PAGI; | ||
| 50 | |||
| 51 | |||
| 52 | # Environment | ||
| 53 | # | ||
| 54 | my %ENV_BASE=( | ||
| 55 | %{$WEBDYNE_PAGI_ENV_SET}, | ||
| 56 | (map { $_=>$ENV{$_} } ( | ||
| 57 | grep { defined($ENV{$_}) } | ||
| 58 | qw(DOCUMENT_DEFAULT DOCUMENT_ROOT), | ||
| 59 | @{$WEBDYNE_PAGI_ENV_KEEP}, | ||
| 60 | grep {/WEBDYNE/i} keys %ENV | ||
| 61 | )) | ||
| 62 | ); | ||
| 63 | |||
| 64 | |||
| 65 | # Version information | ||
| 66 | # | ||
| 67 | $VERSION='3.029'; | ||
| 68 | |||
| 69 | |||
| 70 | #================================================================================================== | ||
| 71 | |||
| 72 | sub new { | ||
| 73 | |||
| 74 | |||
| 75 | # Get options | ||
| 76 | # | ||
| 77 | my ($class, %opt)=@_; | ||
| 78 | |||
| 79 | foreach my $phase (qw(startup shutdown)) { | ||
| 80 | die "PAGI $phase callback must be a coderef\n" | ||
| 81 | if (defined($opt{$phase})&&((reftype($opt{$phase}) || '') ne 'CODE')); | ||
| 82 | } | ||
| 83 | |||
| 84 | |||
| 85 | # Test ? | ||
| 86 | # | ||
| 87 | if ($opt{'test'}) { | ||
| 88 | $opt{'root'}=$WEBDYNE_DEFAULT_TEST_FN; | ||
| 89 | } | ||
| 90 | |||
| 91 | |||
| 92 | # Indexing. 1 for enable with internal, string for some other indexing file | ||
| 93 | # | ||
| 94 | if ($opt{'index'} eq '1') { | ||
| 95 | $opt{'index'}=$WEBDYNE_DEFAULT_INDEX_FN; | ||
| 96 | } | ||
| 97 | |||
| 98 | |||
| 99 | # Fix document root | ||
| 100 | # | ||
| 101 | $opt{'root'}=File::Spec->rel2abs($opt{'root'}); | ||
| 102 | |||
| 103 | |||
| 104 | # Load local config if requested. Keep the default off so direct | ||
| 105 | # WebDyne::PAGI->new()->to_app callers preserve existing behaviour. | ||
| 106 | # | ||
| 107 | if ($opt{'conf'}) { | ||
| 108 | $class->local_constant_load($opt{'root'}, $opt{'conf'}); | ||
| 109 | } | ||
| 110 | |||
| 111 | |||
| 112 | # API file name cache | ||
| 113 | # | ||
| 114 | $opt{'API_fn'}={}; | ||
| 115 | |||
| 116 | |||
| 117 | # Done | ||
| 118 | # | ||
| 119 | return bless(\%opt, $class); | ||
| 120 | |||
| 121 | } | ||
| 122 | |||
| 123 | |||
| 124 | sub to_app { | ||
| 125 | |||
| 126 | |||
| 127 | # Self ref | ||
| 128 | # | ||
| 129 | my $self=shift(); | ||
| 130 | |||
| 131 | |||
| 132 | # Dispatch table | ||
| 133 | # | ||
| 134 | my %handler=( | ||
| 135 | http => sub { shift()->handler_http(@_) }, | ||
| 136 | sse => sub { shift()->handler_sse(@_) }, | ||
| 137 | ws => sub { shift()->handler_ws(@_) }, | ||
| 138 | websocket => sub { shift()->handler_ws(@_) }, | ||
| 139 | lifespan => sub { shift()->handler_lifespan(@_) } | ||
| 140 | ); | ||
| 141 | |||
| 142 | |||
| 143 | # Main application | ||
| 144 | # | ||
| 145 | my $app_cr = async sub { | ||
| 146 | |||
| 147 | my ($scope, $receive, $send) = @_; | ||
| 148 | if (my $handler_cr=$handler{my $type=$scope->{type}}) { | ||
| 149 | # Supported type, dispatch | ||
| 150 | # | ||
| 151 | return await $handler_cr->($self, $scope, $receive, $send)->($scope, $receive, $send); | ||
| 152 | } | ||
| 153 | else { | ||
| 154 | # Unsupported type | ||
| 155 | # | ||
| 156 | die "Unsupported scope type: $type"; | ||
| 157 | } | ||
| 158 | |||
| 159 | }; | ||
| 160 | |||
| 161 | |||
| 162 | # Wrap with configured PAGI middleware. | ||
| 163 | # | ||
| 164 | $app_cr=$self->build($app_cr); | ||
| 165 | |||
| 166 | |||
| 167 | # Done | ||
| 168 | # | ||
| 169 | return $app_cr; | ||
| 170 | |||
| 171 | } | ||
| 172 | |||
| 173 | |||
| 174 | sub build { | ||
| 175 | |||
| 176 | |||
| 177 | # Wrap a PAGI app code ref in configured middleware. | ||
| 178 | # | ||
| 179 | my ($self, $app_cr)=@_; | ||
| 180 | |||
| 181 | |||
| 182 | # Static service can be overridden per instance without changing the | ||
| 183 | # package default for later apps in the same interpreter. | ||
| 184 | # | ||
| 185 | my $static_fg=$WEBDYNE_PAGI_STATIC; | ||
| 186 | $static_fg=$self->{'static'} if exists($self->{'static'}); | ||
| 187 | |||
| 188 | |||
| 189 | # Build list of active middleware. | ||
| 190 | # | ||
| 191 | my @middleware; | ||
| 192 | foreach my $middleware_ar (@{$WEBDYNE_PAGI_MIDDLEWARE}) { | ||
| 193 | my ($middleware, $middleware_opt_hr)=@{$middleware_ar}; | ||
| 194 | |||
| 195 | # Skip static if not wanted | ||
| 196 | # | ||
| 197 | if ($middleware eq 'Static') { | ||
| 198 | next unless $static_fg; | ||
| 199 | } | ||
| 200 | |||
| 201 | |||
| 202 | # And code refs are run and given self as first param | ||
| 203 | # | ||
| 204 | if (ref($middleware_opt_hr) eq 'CODE') { | ||
| 205 | $middleware_opt_hr=$middleware_opt_hr->($self); | ||
| 206 | } | ||
| 207 | |||
| 208 | |||
| 209 | # Save it for wrapping below | ||
| 210 | # | ||
| 211 | push @middleware, [$middleware, $middleware_opt_hr]; | ||
| 212 | } | ||
| 213 | |||
| 214 | |||
| 215 | # No active middleware, preserve bare app behaviour and avoid requiring | ||
| 216 | # PAGI::Middleware::Builder for direct WebDyne::PAGI use. | ||
| 217 | # | ||
| 218 | return $app_cr unless @middleware; | ||
| 219 | |||
| 220 | |||
| 221 | # Build middleware stack | ||
| 222 | # | ||
| 223 | require PAGI::Middleware::Builder; | ||
| 224 | my $builder_or=PAGI::Middleware::Builder->new(); | ||
| 225 | foreach my $middleware_ar (@middleware) { | ||
| 226 | my ($middleware, $middleware_opt_hr)=@{$middleware_ar}; | ||
| 227 | $builder_or->add_middleware($middleware, %{$middleware_opt_hr}); | ||
| 228 | } | ||
| 229 | |||
| 230 | |||
| 231 | # Done | ||
| 232 | # | ||
| 233 | return $builder_or->to_app($app_cr); | ||
| 234 | |||
| 235 | } | ||
| 236 | |||
| 237 | |||
| 238 | sub local_constant_load { | ||
| 239 | |||
| 240 | |||
| 241 | # Read in local webdyne.conf.pl | ||
| 242 | # | ||
| 243 | my ($class, $root_dn, $conf)=@_; | ||
| 244 | |||
| 245 | |||
| 246 | # If root_dn is a file get dir name | ||
| 247 | # | ||
| 248 | if (-f $root_dn) { | ||
| 249 | $root_dn=(File::Spec->splitpath($root_dn))[1]; | ||
| 250 | } | ||
| 251 | |||
| 252 | |||
| 253 | # Resolve conf option. 1 means root/.webdyne.conf.pl, otherwise use | ||
| 254 | # explicit path relative to root unless already absolute. | ||
| 255 | # | ||
| 256 | my $conf_fn; | ||
| 257 | if ($conf eq '1') { | ||
| 258 | $conf_fn=File::Spec->catfile($root_dn, sprintf('.%s', $WEBDYNE_CONF_FN)); | ||
| 259 | } | ||
| 260 | else { | ||
| 261 | $conf_fn=File::Spec->file_name_is_absolute($conf) ? | ||
| 262 | $conf : | ||
| 263 | File::Spec->catfile($root_dn, $conf); | ||
| 264 | } | ||
| 265 | |||
| 266 | |||
| 267 | # Load via existing constant import path. | ||
| 268 | # | ||
| 269 | WebDyne::Constant->import($conf_fn); | ||
| 270 | return $conf_fn; | ||
| 271 | |||
| 272 | } | ||
| 273 | |||
| 274 | |||
| 275 | sub handler_sse { | ||
| 276 | |||
| 277 | my $self=shift(); | ||
| 278 | return async sub { | ||
| 279 | my ($scope, $receive, $send)=@_; | ||
| 280 | my ($size, $disconnected)=(0, 0); | ||
| 281 | my $req_or=PAGI::Request->new($scope, async sub { | ||
| 282 | my $event_hr=await $receive->(); | ||
| 283 | if ($event_hr->{'type'} eq 'sse.disconnect') { | ||
| 284 | $disconnected=1; | ||
| 285 | return {%{$event_hr}, type => 'http.disconnect'}; | ||
| 286 | } | ||
| 287 | die "unexpected event while reading SSE form" unless $event_hr->{'type'} eq 'sse.request'; | ||
| 288 | $size += length(defined($event_hr->{'body'}) ? $event_hr->{'body'} : ''); | ||
| 289 | die "SSE form exceeds upload limit" if $size > $WEBDYNE_CGI_POST_MAX; | ||
| 290 | return $event_hr; | ||
| 291 | }); | ||
| 292 | |||
| 293 | # Only URL-encoded forms need staging here. EventSource GETs keep | ||
| 294 | # their existing path; multipart SSE submissions are not supported. | ||
| 295 | # Use PAGI's buffered helper so CGI can read synchronously below. | ||
| 296 | # | ||
| 297 | if ($req_or->content_type() eq 'application/x-www-form-urlencoded') { | ||
| 298 | my $length=$req_or->content_length(); | ||
| 299 | $size=$length if defined($length) && $length =~ /\A[0-9]+\z/; | ||
| 300 | unless ($size > $WEBDYNE_CGI_POST_MAX) { | ||
| 301 | $size=0; | ||
| 302 | my $read=eval { await $req_or->body(); 1 }; | ||
| 303 | die $@ unless $read || $size > $WEBDYNE_CGI_POST_MAX; | ||
| 304 | } | ||
| 305 | if ($size > $WEBDYNE_CGI_POST_MAX) { | ||
| 306 | await $send->({type => 'sse.http.response.start', status => HTTP_REQUEST_ENTITY_TOO_LARGE, | ||
| 307 | headers => [['content-type', 'text/plain']]}); | ||
| 308 | await $send->({type => 'sse.http.response.body', body => "Request body exceeds upload limit\n", more => 0}); | ||
| 309 | return; | ||
| 310 | } | ||
| 311 | return if $disconnected; | ||
| 312 | } | ||
| 313 | |||
| 314 | my ($sse_cr, $status); | ||
| 315 | { | ||
| 316 | # Start page setup with clean diagnostics after body buffering. | ||
| 317 | # | ||
| 318 | errclr(); | ||
| 319 | |||
| 320 | # Confine localized process state to synchronous page setup. | ||
| 321 | # POST fields are buffered before CGI builds the parameter hash. | ||
| 322 | # | ||
| 323 | local *ENV=\%ENV_BASE; | ||
| 324 | my $res_or=PAGI::Response->new($scope); | ||
| 325 | require PAGI::SSE; | ||
| 326 | my $sse_or=PAGI::SSE->new($scope, $receive, $send); | ||
| 327 | my $r=WebDyne::Request::PAGI->new( | ||
| 328 | document_root => $self->{'root'}, document_default => $self->{'index'}, | ||
| 329 | scope => $scope, req => $req_or, res => $res_or, sse => $sse_or, | ||
| 330 | receive => $receive, send => $send, | ||
| 331 | ) || return err('unable to create SSE request'); | ||
| 332 | $status=WebDyne->handler($r); | ||
| 333 | $sse_cr=$r->custom_response($status) if $status eq HTTP_CONTINUE; | ||
| 334 | } | ||
| 335 | |||
| 336 | # Decline before starting a stream. Preserve HTTP error statuses; | ||
| 337 | # other results without an SSE callback indicate a setup failure. | ||
| 338 | # Send outside the localized environment and await both events. | ||
| 339 | # | ||
| 340 | unless (ref($sse_cr) eq 'CODE') { | ||
| 341 | $status=HTTP_INTERNAL_SERVER_ERROR | ||
| 342 | unless defined($status) && $status =~ /\A[45][0-9]{2}\z/; | ||
| 343 | my $message=HTTP::Status::status_message($status) || 'Request failed'; | ||
| 344 | await $send->({ | ||
| 345 | type => 'sse.http.response.start', status => $status, | ||
| 346 | headers => [['content-type', 'text/plain']], | ||
| 347 | }); | ||
| 348 | await $send->({ | ||
| 349 | type => 'sse.http.response.body', | ||
| 350 | body => "$status $message\n", more => 0, | ||
| 351 | }); | ||
| 352 | return; | ||
| 353 | } | ||
| 354 | await $sse_cr->($scope, $receive, $send); | ||
| 355 | }; | ||
| 356 | |||
| 357 | } | ||
| 358 | |||
| 359 | |||
| 360 | sub handler_sse_error { | ||
| 361 | |||
| 362 | return async sub { | ||
| 363 | |||
| 364 | |||
| 365 | # Get request | ||
| 366 | # | ||
| 367 | my ($scope, $receive, $send)=@_; | ||
| 368 | 0 && debug('in handler_sse_error, scope:%s receive:%s, send:%s', Dumper($scope, $receive, $send)); | ||
| 369 | |||
| 370 | |||
| 371 | # Create helper objects | ||
| 372 | # | ||
| 373 | require PAGI::SSE; | ||
| 374 | my $sse_or=PAGI::SSE->new($scope, $receive, $send) || | ||
| 375 | return err('unable to get PAGI::SSE object'); | ||
| 376 | 0 && debug("sse_or: $sse_or"); | ||
| 377 | |||
| 378 | |||
| 379 | # Send error | ||
| 380 | # | ||
| 381 | await $sse_or->send('SSE error - see logs'); | ||
| 382 | |||
| 383 | } | ||
| 384 | |||
| 385 | } | ||
| 386 | |||
| 387 | |||
| 388 | sub handler_ws { | ||
| 389 | |||
| 390 | |||
| 391 | # Get request | ||
| 392 | # | ||
| 393 | my ($self, $scope, $receive, $send)=@_; | ||
| 394 | 0 && debug('in handler_ws, scope:%s receive:%s, send:%s', Dumper($scope, $receive, $send)); | ||
| 395 | |||
| 396 | |||
| 397 | # Start synchronous WebSocket setup with clean diagnostics. | ||
| 398 | # | ||
| 399 | errclr(); | ||
| 400 | |||
| 401 | |||
| 402 | # Setup %ENV | ||
| 403 | # | ||
| 404 | local *ENV=\%ENV_BASE; | ||
| 405 | |||
| 406 | |||
| 407 | # Create helper objects | ||
| 408 | # | ||
| 409 | my $req_or=PAGI::Request->new($scope, $receive) || | ||
| 410 | return err('unable to get PAGI::Request object'); | ||
| 411 | my $res_or=PAGI::Response->new($scope) || | ||
| 412 | return err('unable to get PAGI::Response object'); | ||
| 413 | require PAGI::WebSocket; | ||
| 414 | my $ws_or=PAGI::WebSocket->new($scope, $receive, $send) || | ||
| 415 | return err('unable to get PAGI::WebSocket object'); | ||
| 416 | 0 && debug("req_or: $req_or, res_or: $res_or, ws_or: $ws_or"); | ||
| 417 | |||
| 418 | |||
| 419 | # Get main WebDyne handler request object | ||
| 420 | # | ||
| 421 | my $r=WebDyne::Request::PAGI->new( document_root => $self->{'root'}, document_default => $self->{'index'}, scope=>$scope, req=>$req_or, res=>$res_or, ws=>$ws_or, | ||
| 422 | receive => $receive, send=> $send) || | ||
| 423 | return err('unable to create new WebDyne::Request::PAGI object: %s', | ||
| 424 | $@ || errclr() || 'unknown error'); | ||
| 425 | 0 && debug("r: $r"); | ||
| 426 | |||
| 427 | |||
| 428 | # Call handler. No point error checking but log errors | ||
| 429 | # | ||
| 430 | 0 && debug('calling WebDyne handler'); | ||
| 431 | my $status=WebDyne->handler($r); | ||
| 432 | 0 && debug("status: $status"); | ||
| 433 | if ($status eq HTTP_CONTINUE) { | ||
| 434 | my $ws_cr=$r->custom_response($status); | ||
| 435 | return $ws_cr if ref($ws_cr) eq 'CODE'; | ||
| 436 | } | ||
| 437 | |||
| 438 | # Reject before accepting the socket. The server converts this into | ||
| 439 | # an HTTP 403 handshake response; no optional extension is required. | ||
| 440 | # | ||
| 441 | return async sub { | ||
| 442 | my ($scope, $receive, $send)=@_; | ||
| 443 | await $send->({type => 'websocket.close'}); | ||
| 444 | }; | ||
| 445 | |||
| 446 | } | ||
| 447 | |||
| 448 | sub handler_http { | ||
| 449 | |||
| 450 | |||
| 451 | # Self ref contains things like document_root, dcoument_default | ||
| 452 | # | ||
| 453 | my $self=shift(); | ||
| 454 | |||
| 455 | |||
| 456 | # Return async sub for handling WebDyne requests | ||
| 457 | # | ||
| 458 | return set_subname('handler_http_anon', async sub { | ||
| 459 | |||
| 460 | |||
| 461 | # Get request | ||
| 462 | # | ||
| 463 | my ($scope, $receive, $send)=@_; | ||
| 464 | 0 && debug('in handler, scope:%s receive:%s, send:%s', Dumper($scope, $receive, $send)); | ||
| 465 | |||
| 466 | |||
| 467 | # Restrict local env and expose the PAGI request path to WebDyne's | ||
| 468 | # shared Router::Simple based API implementation. | ||
| 469 | # | ||
| 470 | my ($r, $html, $html_fh, $status, $req_or, $res_or); | ||
| 471 | |||
| 472 | # WebDyne page code reads synchronously. Buffer HTTP bodies before | ||
| 473 | # dispatch, bounded by the existing 512 KiB default upload limit. | ||
| 474 | # Count actual bytes even when Content-Length is absent or inaccurate. | ||
| 475 | # Wrapping receive preserves PAGI's buffered body/json helpers; using | ||
| 476 | # body_stream for every request would disable those helpers. | ||
| 477 | # | ||
| 478 | my ($body_bytes, $body_oversize, $body_disconnected)=(0, 0, 0); | ||
| 479 | my $bounded_receive_cr=async sub { | ||
| 480 | my $event_hr=await $receive->(); | ||
| 481 | if ($event_hr->{'type'} eq 'http.disconnect') { | ||
| 482 | $body_disconnected=1; | ||
| 483 | return $event_hr; | ||
| 484 | } | ||
| 485 | die "unexpected event while reading HTTP body" unless $event_hr->{'type'} eq 'http.request'; | ||
| 486 | $body_bytes += length(defined($event_hr->{'body'}) ? $event_hr->{'body'} : ''); | ||
| 487 | if ($body_bytes > $WEBDYNE_CGI_POST_MAX) { | ||
| 488 | $body_oversize=1; | ||
| 489 | die "request body exceeds upload limit"; | ||
| 490 | } | ||
| 491 | return $event_hr; | ||
| 492 | }; | ||
| 493 | $req_or=PAGI::Request->new($scope, $bounded_receive_cr) || | ||
| 494 | return err('unable to get PAGI::Request object'); | ||
| 495 | $res_or=PAGI::Response->new($scope) || | ||
| 496 | return err('unable to get PAGI::Response object'); | ||
| 497 | |||
| 498 | # Reject a declared oversize body before consuming any input. The | ||
| 499 | # receive counter remains authoritative for bodies we do accept. | ||
| 500 | # | ||
| 501 | my $content_length=$req_or->content_length(); | ||
| 502 | $body_oversize=1 if defined($content_length) && $content_length =~ /\A[0-9]+\z/ | ||
| 503 | && $content_length > $WEBDYNE_CGI_POST_MAX; | ||
| 504 | unless ($body_oversize) { | ||
| 505 | my $staged=eval { | ||
| 506 | if ( | ||
| 507 | ($req_or->content_type() || '') =~ m{\Aapplication/x-www-form-urlencoded\b}i | ||
| 508 | # PAGI form data need not declare Content-Length. | ||
| 509 | # && $req_or->content_length() | ||
| 510 | ) { | ||
| 511 | await $req_or->body(); | ||
| 512 | } | ||
| 513 | elsif ( | ||
| 514 | ($req_or->content_type() || '') =~ m{\Amultipart/form-data(?:\s*;|\z)}i | ||
| 515 | # Stage chunked uploads too, with the independent limit. | ||
| 516 | # && $req_or->content_length() | ||
| 517 | ) { | ||
| 518 | my $multipart_body=''; | ||
| 519 | my $stream_or=$req_or->body_stream(max_bytes => $WEBDYNE_CGI_POST_MAX); | ||
| 520 | await $stream_or->stream_to(sub { $multipart_body .= shift() }); | ||
| 521 | $scope->{'webdyne.pagi.multipart_body'}=\$multipart_body; | ||
| 522 | } | ||
| 523 | else { | ||
| 524 | await $req_or->body(); | ||
| 525 | } | ||
| 526 | 1; | ||
| 527 | }; | ||
| 528 | die $@ unless $staged || $body_oversize; | ||
| 529 | } | ||
| 530 | if ($body_oversize) { | ||
| 531 | return await $res_or | ||
| 532 | ->status(HTTP_REQUEST_ENTITY_TOO_LARGE) | ||
| 533 | ->send("Request body exceeds upload limit\n") | ||
| 534 | ->respond($send); | ||
| 535 | } | ||
| 536 | |||
| 537 | # PAGI's helpers may return partial bytes on disconnect. Never run | ||
| 538 | # page code with an incomplete upload or synthesize a response for it. | ||
| 539 | # | ||
| 540 | return if $body_disconnected; | ||
| 541 | |||
| 542 | { | ||
| 543 | # Start page setup with clean diagnostics after body buffering. | ||
| 544 | # | ||
| 545 | errclr(); | ||
| 546 | |||
| 547 | # Keep the request environment localized only while WebDyne is | ||
| 548 | # constructing and executing the request. Do not retain a | ||
| 549 | # localized global %ENV across an asynchronous response await. | ||
| 550 | # | ||
| 551 | local *ENV=\%ENV_BASE; | ||
| 552 | @ENV{qw(PATH_INFO QUERY_STRING REQUEST_METHOD SCRIPT_NAME)}=( | ||
| 553 | WebDyne::Request::PAGI::scope_path($scope), | ||
| 554 | $scope->{'query_string'} || '', | ||
| 555 | $scope->{'method'} || '', | ||
| 556 | $scope->{'root_path'} || '', | ||
| 557 | ); | ||
| 558 | |||
| 559 | # If the requested path is not a file, an API PSP may own a path | ||
| 560 | # prefix such as /api.psp or /example/api.psp. Resolve that prefix | ||
| 561 | # before constructing the request so the normal WebDyne handler can | ||
| 562 | # process the PSP. The discovered API file path becomes the mount | ||
| 563 | # point, so /example/api.psp owning /example/api/foo passes /foo to | ||
| 564 | # Router::Simple. | ||
| 565 | # | ||
| 566 | my $api_fn=api_filename($self, $scope); | ||
| 567 | if ($api_fn) { | ||
| 568 | my $api_path=File::Spec->abs2rel($api_fn, File::Spec->rel2abs($self->{'root'})); | ||
| 569 | $api_path=~s{\Q@{[WEBDYNE_PSP_EXT]}\E$}{}; | ||
| 570 | $ENV{'PATH_INFO'}=~s{^/\Q$api_path\E(?=/|$)}{}i; | ||
| 571 | } | ||
| 572 | |||
| 573 | # Create new WebDyne Request object, optionally using the API | ||
| 574 | # prefix resolved above as its PSP filename. | ||
| 575 | # | ||
| 576 | $html_fh=IO::String->new($html); | ||
| 577 | my %request_opt=(select => $html_fh, document_root => $self->{'root'}, document_default => $self->{'index'}, scope=>$scope, req=>$req_or, res=>$res_or, | ||
| 578 | receive => $receive, send=> $send, no_head_insert=>$self->{'no_head_insert'}, filename=>$self->{'filename'}); | ||
| 579 | $request_opt{'filename'} ||= do {$api_fn if $api_fn}; | ||
| 580 | $r=WebDyne::Request::PAGI->new(%request_opt) || | ||
| 581 | return err('unable to create new WebDyne::Request::PAGI object: %s', | ||
| 582 | $@ || errclr() || 'unknown error'); | ||
| 583 | 0 && debug("r: $r"); | ||
| 584 | |||
| 585 | # Call handler and evaluate results | ||
| 586 | # | ||
| 587 | $status=WebDyne->handler($r); | ||
| 588 | 0 && debug("handler returned status: $status"); | ||
| 589 | $r->status($status); | ||
| 590 | } | ||
| 591 | |||
| 592 | |||
| 593 | # Can close html file handle now | ||
| 594 | # | ||
| 595 | $html_fh->close(); | ||
| 596 | 0 && debug("html returned:\n$html"); | ||
| 597 | |||
| 598 | |||
| 599 | # Present error if non 200 (success) status returned. Yes - there are other status codes but this is most | ||
| 600 | # common and quickest test, other 200 codes will fall through the if/else statements and still work | ||
| 601 | # | ||
| 602 | unless ($status == HTTP_OK) { | ||
| 603 | |||
| 604 | |||
| 605 | # OK. Most common match didn't happen. Is it an error ? | ||
| 606 | # | ||
| 607 | 0 && debug('status: %s is not HTTP_OK, branching', $status); | ||
| 608 | if (!defined($status) || ($status < 0) || is_error($status) || !$html) { | ||
| 609 | |||
| 610 | |||
| 611 | # Something went wrong. Let's start working through it | ||
| 612 | # | ||
| 613 | if (($status eq HTTP_NOT_FOUND) && !(-f (my $fn=$r->filename()))) { | ||
| 614 | |||
| 615 | |||
| 616 | # If get here nothing found, send 404 error | ||
| 617 | # | ||
| 618 | 0 && debug("status: $status, fn:$fn, setting HTTP_NOT_FOUND"); | ||
| 619 | $r->status(HTTP_NOT_FOUND); | ||
| 620 | my $error=errdump() || "File not found, status ($status)"; errclr(); | ||
| 621 | $html=$r->err_html($status, $error) | ||
| 622 | } | ||
| 623 | elsif (is_error($status) ) { | ||
| 624 | |||
| 625 | # Some other error besides 404 | ||
| 626 | # | ||
| 627 | 0 && debug("returning custom error: $status"); | ||
| 628 | $r->status($status); | ||
| 629 | $html=$r->custom_response($status) || errstr() || do { | ||
| 630 | $r->content_type($WEBDYNE_CONTENT_TYPE_TEXT); | ||
| 631 | "Error: $status with no content - try server error logs ?"; | ||
| 632 | }; | ||
| 633 | |||
| 634 | } | ||
| 635 | else { | ||
| 636 | |||
| 637 | # Weird non HTTP status code, something has gone wrong along way | ||
| 638 | # | ||
| 639 | 0 && debug('undefined status returned, looking for error handler'); | ||
| 640 | my $error=errdump() || $@; errclr(); | ||
| 641 | $error ||= "Unexpected return status ($status) from handler"; | ||
| 642 | 0 && debug("request handler status:$status, detected error: $error, calling err_html"); | ||
| 643 | $r->status(HTTP_INTERNAL_SERVER_ERROR); | ||
| 644 | $html=$r->err_html($status, $error) | ||
| 645 | |||
| 646 | } | ||
| 647 | |||
| 648 | } | ||
| 649 | else { | ||
| 650 | |||
| 651 | # Not an error, but not HTTP_OK | ||
| 652 | # | ||
| 653 | 0 && debug("status: $status is not an error, proceeding"); | ||
| 654 | |||
| 655 | } | ||
| 656 | |||
| 657 | } | ||
| 658 | my $final_status=$r->status() || $status || HTTP_OK; | ||
| 659 | 0 && debug("final handler status: %s, content_type: %s, html:%s", $final_status, $r->content_type(), $html); | ||
| 660 | |||
| 661 | |||
| 662 | # Send headers unless already sent | ||
| 663 | # | ||
| 664 | $r->res->status($final_status); | ||
| 665 | my $headers_ar=$r->headers_out->psgi_flatten_without_sort(); | ||
| 666 | 0 && debug('sending headers: %s', Dumper($headers_ar)); | ||
| 667 | my $cookie_seen; | ||
| 668 | for (my $i=0; $i<@{$headers_ar}; $i+=2) { | ||
| 669 | my ($header, $value)=@{$headers_ar}[$i, $i+1]; | ||
| 670 | if (lc($header) eq 'set-cookie') { | ||
| 671 | $r->res->remove_header('set-cookie') unless $cookie_seen++; | ||
| 672 | $r->res->header('set-cookie' => $value); | ||
| 673 | } | ||
| 674 | else { | ||
| 675 | $r->res->header_try($header => $value); | ||
| 676 | } | ||
| 677 | } | ||
| 678 | |||
| 679 | |||
| 680 | # If html is defined set header content type unless already set during | ||
| 681 | # handler execution, then always send the response. An API page with | ||
| 682 | # no matching route legitimately returns an empty 200 response; PAGI | ||
| 683 | # still requires response.start to be emitted in that case. | ||
| 684 | # | ||
| 685 | my $body=$html || ''; | ||
| 686 | if ($body) { | ||
| 687 | 0 && debug('sending html to client via await()'); | ||
| 688 | $r->res->content_type($r->content_type() || $WEBDYNE_CONTENT_TYPE_HTML); | ||
| 689 | } | ||
| 690 | |||
| 691 | # Encode character strings, but preserve byte strings from files and R2. | ||
| 692 | # | ||
| 693 | my $send_method=utf8::is_utf8($body) ? 'send' : 'send_raw'; | ||
| 694 | my $respond_or=$r->res->$send_method($body)->respond(sub { | ||
| 695 | |||
| 696 | # PAGI requires lowercase names in response events. Normalize only | ||
| 697 | # the outgoing header pairs, preserving values, order and duplicates. | ||
| 698 | # | ||
| 699 | my $event_hr=shift(); | ||
| 700 | if ($event_hr->{'type'} eq 'http.response.start') { | ||
| 701 | $event_hr={ | ||
| 702 | %{$event_hr}, | ||
| 703 | headers => [ | ||
| 704 | map { [lc($_->[0]), $_->[1]] } | ||
| 705 | @{$event_hr->{'headers'} || []} | ||
| 706 | ], | ||
| 707 | }; | ||
| 708 | } | ||
| 709 | return $send->($event_hr); | ||
| 710 | }); | ||
| 711 | |||
| 712 | # Retain the response Future across await. Awaiting the temporary can | ||
| 713 | # crash Devel::Confess stack tracing on send failure with Perl 5.38. | ||
| 714 | # | ||
| 715 | my $respond_status=await $respond_or; | ||
| 716 | $r->DESTROY(); | ||
| 717 | return $respond_status; | ||
| 718 | |||
| 719 | |||
| 720 | |||
| 721 | }) | ||
| 722 | |||
| 723 | } | ||
| 724 | |||
| 725 | |||
| 726 | sub api_filename { | ||
| 727 | |||
| 728 | my ($self, $scope)=@_; | ||
| 729 | return unless WEBDYNE_API_ENABLE; | ||
| 730 | |||
| 731 | my $path=WebDyne::Request::PAGI::scope_path($scope); | ||
| 732 | return unless length($path); | ||
| 733 | |||
| 734 | my @part=grep { length($_) } split(m{/+}, $path); | ||
| 735 | return if grep { $_ eq '.' || $_ eq '..' } @part; | ||
| 736 | |||
| 737 | my $root=File::Spec->rel2abs($self->{'root'}); | ||
| 738 | my $API_fn=$self->{'API_fn'}; | ||
| 739 | for my $ix (0 .. $#part) { | ||
| 740 | my $candidate=File::Spec->catfile($root, @part[0 .. $ix]); | ||
| 741 | $candidate .= WEBDYNE_PSP_EXT unless $candidate =~ WEBDYNE_PSP_EXT_RE; | ||
| 742 | |||
| 743 | my $relative=File::Spec->abs2rel($candidate, $root); | ||
| 744 | next if $relative eq '..' || $relative =~ /^\.\.(?:[\\\/]|$)/; | ||
| 745 | if ($API_fn->{$candidate} || (-f $candidate)) { | ||
| 746 | 0 && debug("found api file name: $candidate, %s, dispatching", Dumper($API_fn)); | ||
| 747 | $API_fn->{$candidate}++; # Cache so not stat()ing on file system | ||
| 748 | return $candidate; | ||
| 749 | } | ||
| 750 | } | ||
| 751 | |||
| 752 | return; | ||
| 753 | } | ||
| 754 | |||
| 755 | |||
| 756 | sub handler_lifespan { | ||
| 757 | |||
| 758 | my $self=shift(); | ||
| 759 | |||
| 760 | return set_subname('handler_lifespan_anon', async sub { | ||
| 761 | |||
| 762 | my ($scope_hr, $receive_cr, $send_cr)=@_; | ||
| 763 | while (1) { | ||
| 764 | my $event_hr=await $receive_cr->(); | ||
| 765 | my $phase=$event_hr->{'type'} eq 'lifespan.startup' ? 'startup' | ||
| 766 | : $event_hr->{'type'} eq 'lifespan.shutdown' ? 'shutdown' : undef; | ||
| 767 | next unless defined($phase); | ||
| 768 | |||
| 769 | # Own the protocol acknowledgement; callbacks only perform work. | ||
| 770 | # Keep send failures outside the callback exception boundary. | ||
| 771 | # | ||
| 772 | my $ok=eval { await $self->lifespan_callback($phase, $scope_hr); 1 }; | ||
| 773 | unless ($ok) { | ||
| 774 | my $error=$@; | ||
| 775 | await $send_cr->({type => "lifespan.$phase.failed", message => "$error"}); | ||
| 776 | last; | ||
| 777 | } | ||
| 778 | if ($phase eq 'startup') { | ||
| 779 | printf STDERR "[lifespan] WebDyne PAGI handler startup. DOCUMENT_ROOT: %s, DOCUMENT_DEFAULT: %s\n", $self->{'root'}, basename($self->{'index'} || $DOCUMENT_DEFAULT); | ||
| 780 | } | ||
| 781 | else { | ||
| 782 | print STDERR "[lifespan] WebDyne PAGI handler shutdown.\n"; | ||
| 783 | } | ||
| 784 | await $send_cr->({type => "lifespan.$phase.complete"}); | ||
| 785 | last if $phase eq 'shutdown'; | ||
| 786 | } | ||
| 787 | }) | ||
| 788 | } | ||
| 789 | |||
| 790 | |||
| 791 | async sub lifespan_callback { | ||
| 792 | |||
| 793 | my ($self, $phase, $scope_hr)=@_; | ||
| 794 | die "Unknown PAGI lifespan phase\n" unless (($phase eq 'startup')||($phase eq 'shutdown')); | ||
| 795 | my $callback_cr=$self->{$phase}; | ||
| 796 | return unless defined($callback_cr); | ||
| 797 | my $result_ref=$callback_cr->($self, $scope_hr); | ||
| 798 | await $result_ref if (blessed($result_ref)&&$result_ref->isa('Future')); | ||
| 799 | return; | ||
| 800 | } | ||
| 801 | |||
| 802 | |||
| 803 | sub normalize_dn { | ||
| 804 | |||
| 805 | # Normal dir, normally document_root | ||
| 806 | # | ||
| 807 | my $rel_dn=shift(); | ||
| 808 | my $abs_dn=File::Spec->rel2abs($rel_dn); | ||
| 809 | $abs_dn =~ s{/$}{} unless $abs_dn eq '/'; | ||
| 810 | return $abs_dn; | ||
| 811 | |||
| 812 | } | ||
| 813 | |||
| 814 | 1; | ||
| 815 | __END__ | ||