1 package Catalyst::Engine;
4 with 'MooseX::Emulate::Class::Accessor::Fast';
6 use CGI::Simple::Cookie;
7 use Data::Dump qw/dump/;
8 use Errno 'EWOULDBLOCK';
14 use Catalyst::EngineLoader;
18 use namespace::clean -except => 'meta';
20 # Amount of data to read from input on each pass
21 our $CHUNKSIZE = 64 * 1024;
23 # XXX - this is only here for compat, do not use!
24 has env => ( is => 'rw', writer => '_set_env' );
25 my $WARN_ABOUT_ENV = 0;
27 my ($orig, $self, @args) = @_;
29 warn "env as a writer is deprecated, you probably need to upgrade Catalyst::Engine::PSGI"
30 unless $WARN_ABOUT_ENV++;
31 return $self->_set_env(@args);
38 Catalyst::Engine - The Catalyst Engine
49 =head2 $self->finalize_body($c)
51 Finalize body. Prints the response output.
56 my ( $self, $c ) = @_;
57 my $body = $c->response->body;
58 no warnings 'uninitialized';
59 if ( blessed($body) && $body->can('read') or ref($body) eq 'GLOB' ) {
62 $got = read $body, my ($buffer), $CHUNKSIZE;
63 $got = 0 unless $self->write( $c, $buffer );
69 $self->write( $c, $body );
72 my $res = $c->response;
79 =head2 $self->finalize_cookies($c)
81 Create CGI::Simple::Cookie objects from $c->res->cookies, and set them as
86 sub finalize_cookies {
87 my ( $self, $c ) = @_;
90 my $response = $c->response;
92 foreach my $name (keys %{ $response->cookies }) {
94 my $val = $response->cookies->{$name};
99 : CGI::Simple::Cookie->new(
101 -value => $val->{value},
102 -expires => $val->{expires},
103 -domain => $val->{domain},
104 -path => $val->{path},
105 -secure => $val->{secure} || 0,
106 -httponly => $val->{httponly} || 0,
109 if (!defined $cookie) {
110 $c->log->warn("undef passed in '$name' cookie value - not setting cookie")
115 push @cookies, $cookie->as_string;
118 for my $cookie (@cookies) {
119 $response->headers->push_header( 'Set-Cookie' => $cookie );
123 =head2 $self->finalize_error($c)
125 Output an appropriate error message. Called if there's an error in $c
126 after the dispatch has finished. Will output debug messages if Catalyst
127 is in debug mode, or a `please come back later` message otherwise.
131 sub _dump_error_page_element {
132 my ($self, $i, $element) = @_;
133 my ($name, $val) = @{ $element };
135 # This is fugly, but the metaclass is _HUGE_ and demands waaay too much
136 # scrolling. Suggestions for more pleasant ways to do this welcome.
137 local $val->{'__MOP__'} = "Stringified: "
138 . $val->{'__MOP__'} if ref $val eq 'HASH' && exists $val->{'__MOP__'};
140 my $text = encode_entities( dump( $val ));
141 sprintf <<"EOF", $name, $text;
142 <h2><a href="#" onclick="toggleDump('dump_$i'); return false">%s</a></h2>
144 <pre wrap="">%s</pre>
150 my ( $self, $c ) = @_;
152 $c->res->content_type('text/html; charset=utf-8');
153 my $name = ref($c)->config->{name} || join(' ', split('::', ref $c));
155 # Prevent Catalyst::Plugin::Unicode::Encoding from running.
156 # This is a little nasty, but it's the best way to be clean whether or
157 # not the user has an encoding plugin.
159 if ($c->can('encoding')) {
163 my ( $title, $error, $infos );
167 $error = join '', map {
168 '<p><code class="error">'
169 . encode_entities($_)
172 $error ||= 'No output';
173 $error = qq{<pre wrap="">$error</pre>};
174 $title = $name = "$name on Catalyst $Catalyst::VERSION";
175 $name = "<h1>$name</h1>";
177 # Don't show context in the dump
178 $c->req->_clear_context;
179 $c->res->_clear_context;
181 # Don't show body parser in the dump
182 $c->req->_clear_body;
186 for my $dump ( $c->dump_these ) {
187 push @infos, $self->_dump_error_page_element($i, $dump);
190 $infos = join "\n", @infos;
197 (en) Please come back later
198 (fr) SVP veuillez revenir plus tard
199 (de) Bitte versuchen sie es spaeter nocheinmal
200 (at) Konnten's bitt'schoen spaeter nochmal reinschauen
201 (no) Vennligst prov igjen senere
202 (dk) Venligst prov igen senere
203 (pl) Prosze sprobowac pozniej
204 (pt) Por favor volte mais tarde
205 (ru) Попробуйте еще раз позже
206 (ua) Спробуйте ще раз пізніше
211 $c->res->body( <<"" );
212 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
213 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
214 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
216 <meta http-equiv="Content-Language" content="en" />
217 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
218 <title>$title</title>
219 <script type="text/javascript">
221 function toggleDump (dumpElement) {
222 var e = document.getElementById( dumpElement );
223 if (e.style.display == "none") {
224 e.style.display = "";
227 e.style.display = "none";
232 <style type="text/css">
234 font-family: "Bitstream Vera Sans", "Trebuchet MS", Verdana,
235 Tahoma, Arial, helvetica, sans-serif;
237 background-color: #eee;
241 :link, :link:hover, :visited, :visited:hover {
246 background-color: #ccc;
247 border: 1px solid #aaa;
252 background-color: #cce;
253 border: 1px solid #755;
259 background-color: #eee;
260 border: 1px solid #575;
266 background-color: #cce;
267 border: 1px solid #557;
276 div.name h1, div.error p {
284 text-decoration: underline;
290 /* from http://users.tkk.fi/~tkarvine/linux/doc/pre-wrap/pre-wrap-css3-mozilla-opera-ie.html */
291 /* Browser specific (not valid) styles to make preformatted text wrap */
293 white-space: pre-wrap; /* css-3 */
294 white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
295 white-space: -pre-wrap; /* Opera 4-6 */
296 white-space: -o-pre-wrap; /* Opera 7 */
297 word-wrap: break-word; /* Internet Explorer 5.5+ */
303 <div class="error">$error</div>
304 <div class="infos">$infos</div>
305 <div class="name">$name</div>
310 # Trick IE. Old versions of IE would display their own error page instead
311 # of ours if we'd give it less than 512 bytes.
312 $c->res->{body} .= ( ' ' x 512 );
314 $c->res->{body} = Encode::encode("UTF-8", $c->res->{body});
317 $c->res->status(500);
320 =head2 $self->finalize_headers($c)
322 Abstract method, allows engines to write headers to response
326 sub finalize_headers {
327 my ($self, $ctx) = @_;
329 # This is a less-than-pretty hack to avoid breaking the old
330 # Catalyst::Engine::PSGI. 5.9 Catalyst::Engine sets a response_cb and
331 # expects us to pass headers to it here, whereas Catalyst::Enngine::PSGI
332 # just pulls the headers out of $ctx->response in its run method and never
333 # sets response_cb. So take the lack of a response_cb as a sign that we
334 # don't need to set the headers.
336 return unless ($ctx->response->_has_response_cb);
339 $ctx->response->headers->scan(sub { push @headers, @_ });
341 my $writer = $ctx->response->_response_cb->([ $ctx->response->status, \@headers ]);
342 $ctx->response->_set_writer($writer);
343 $ctx->response->_clear_response_cb;
348 =head2 $self->finalize_uploads($c)
350 Clean up after uploads, deleting temp files.
354 sub finalize_uploads {
355 my ( $self, $c ) = @_;
357 # N.B. This code is theoretically entirely unneeded due to ->cleanup(1)
358 # on the HTTP::Body object.
359 my $request = $c->request;
360 foreach my $key (keys %{ $request->uploads }) {
361 my $upload = $request->uploads->{$key};
362 unlink grep { -e $_ } map { $_->tempname }
363 (ref $upload eq 'ARRAY' ? @{$upload} : ($upload));
368 =head2 $self->prepare_body($c)
370 sets up the L<Catalyst::Request> object body using L<HTTP::Body>
375 my ( $self, $c ) = @_;
377 $c->request->prepare_body;
380 =head2 $self->prepare_body_chunk($c)
382 Add a chunk to the request body.
386 # XXX - Can this be deleted?
387 sub prepare_body_chunk {
388 my ( $self, $c, $chunk ) = @_;
390 $c->request->prepare_body_chunk($chunk);
393 =head2 $self->prepare_body_parameters($c)
395 Sets up parameters from body.
399 sub prepare_body_parameters {
400 my ( $self, $c ) = @_;
402 $c->request->prepare_body_parameters;
405 =head2 $self->prepare_connection($c)
407 Abstract method implemented in engines.
411 sub prepare_connection {
412 my ($self, $ctx) = @_;
414 my $request = $ctx->request;
415 my $env = $ctx->request->env;
417 $request->address( $env->{REMOTE_ADDR} );
418 $request->hostname( $env->{REMOTE_HOST} )
419 if exists $env->{REMOTE_HOST};
420 $request->protocol( $env->{SERVER_PROTOCOL} );
421 $request->remote_user( $env->{REMOTE_USER} );
422 $request->method( $env->{REQUEST_METHOD} );
423 $request->secure( $env->{'psgi.url_scheme'} eq 'https' ? 1 : 0 );
428 =head2 $self->prepare_cookies($c)
430 Parse cookies from header. Sets a L<CGI::Simple::Cookie> object.
434 sub prepare_cookies {
435 my ( $self, $c ) = @_;
437 if ( my $header = $c->request->header('Cookie') ) {
438 $c->req->cookies( { CGI::Simple::Cookie->parse($header) } );
442 =head2 $self->prepare_headers($c)
446 sub prepare_headers {
447 my ($self, $ctx) = @_;
449 my $env = $ctx->request->env;
450 my $headers = $ctx->request->headers;
452 for my $header (keys %{ $env }) {
453 next unless $header =~ /^(HTTP|CONTENT|COOKIE)/i;
454 (my $field = $header) =~ s/^HTTPS?_//;
456 $headers->header($field => $env->{$header});
460 =head2 $self->prepare_parameters($c)
462 sets up parameters from query and post parameters.
466 sub prepare_parameters {
467 my ( $self, $c ) = @_;
469 my $request = $c->request;
471 my $body_parameters = $request->body_parameters;
472 my $query_parameters = $request->query_parameters;
473 # We copy, no references
474 foreach my $name (keys %$query_parameters) {
475 my $param = $query_parameters->{$name};
476 $parameters->{$name} = ref $param eq 'ARRAY' ? [ @$param ] : $param;
479 # Merge query and body parameters
480 foreach my $name (keys %$body_parameters) {
481 my $param = $body_parameters->{$name};
482 my @values = ref $param eq 'ARRAY' ? @$param : ($param);
483 if ( my $existing = $parameters->{$name} ) {
484 unshift(@values, (ref $existing eq 'ARRAY' ? @$existing : $existing));
486 $parameters->{$name} = @values > 1 ? \@values : $values[0];
488 $request->{parameters} = $parameters; # FIXME
491 =head2 $self->prepare_path($c)
493 abstract method, implemented by engines.
498 my ($self, $ctx) = @_;
500 my $env = $ctx->request->env;
502 my $scheme = $ctx->request->secure ? 'https' : 'http';
503 my $host = $env->{HTTP_HOST} || $env->{SERVER_NAME};
504 my $port = $env->{SERVER_PORT} || 80;
505 my $base_path = $env->{SCRIPT_NAME} || "/";
507 # set the request URI
509 if (!$ctx->config->{use_request_uri_for_path}) {
510 my $path_info = $env->{PATH_INFO};
511 if ( exists $env->{REDIRECT_URL} ) {
512 $base_path = $env->{REDIRECT_URL};
513 $base_path =~ s/\Q$path_info\E$//;
515 $path = $base_path . $path_info;
517 $path =~ s/([^$URI::uric])/$URI::Escape::escapes{$1}/go;
518 $path =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
521 my $req_uri = $env->{REQUEST_URI};
522 $req_uri =~ s/\?.*$//;
527 # Using URI directly is way too slow, so we construct the URLs manually
528 my $uri_class = "URI::$scheme";
530 # HTTP_HOST will include the port even if it's 80/443
531 $host =~ s/:(?:80|443)$//;
533 if ($port !~ /^(?:80|443)$/ && $host !~ /:/) {
537 my $query = $env->{QUERY_STRING} ? '?' . $env->{QUERY_STRING} : '';
538 my $uri = $scheme . '://' . $host . '/' . $path . $query;
540 $ctx->request->uri( (bless \$uri, $uri_class)->canonical );
543 # base must end in a slash
544 $base_path .= '/' unless $base_path =~ m{/$};
546 my $base_uri = $scheme . '://' . $host . $base_path;
548 $ctx->request->base( bless \$base_uri, $uri_class );
553 =head2 $self->prepare_request($c)
555 =head2 $self->prepare_query_parameters($c)
557 process the query string and extract query parameters.
561 sub prepare_query_parameters {
564 my $env = $c->request->env;
565 my $query_string = exists $env->{QUERY_STRING}
566 ? $env->{QUERY_STRING}
569 # Check for keywords (no = signs)
570 # (yes, index() is faster than a regex :))
571 if ( index( $query_string, '=' ) < 0 ) {
572 $c->request->query_keywords( $self->unescape_uri($query_string) );
578 # replace semi-colons
579 $query_string =~ s/;/&/g;
581 my @params = grep { length $_ } split /&/, $query_string;
583 for my $item ( @params ) {
586 = map { $self->unescape_uri($_) }
587 split( /=/, $item, 2 );
589 $param = $self->unescape_uri($item) unless defined $param;
591 if ( exists $query{$param} ) {
592 if ( ref $query{$param} ) {
593 push @{ $query{$param} }, $value;
596 $query{$param} = [ $query{$param}, $value ];
600 $query{$param} = $value;
603 $c->request->query_parameters( \%query );
606 =head2 $self->prepare_read($c)
608 prepare to read from the engine.
613 my ( $self, $c ) = @_;
615 # Initialize the amount of data we think we need to read
616 $c->request->_read_length;
619 =head2 $self->prepare_request(@arguments)
621 Populate the context object from the request object.
625 sub prepare_request {
626 my ($self, $ctx, %args) = @_;
627 $ctx->request->_set_env($args{env});
628 $self->_set_env($args{env}); # Nasty back compat!
629 $ctx->response->_set_response_cb($args{response_cb});
632 =head2 $self->prepare_uploads($c)
636 sub prepare_uploads {
637 my ( $self, $c ) = @_;
639 my $request = $c->request;
640 return unless $request->_body;
642 my $uploads = $request->_body->upload;
643 my $parameters = $request->parameters;
644 foreach my $name (keys %$uploads) {
645 my $files = $uploads->{$name};
647 for my $upload (ref $files eq 'ARRAY' ? @$files : ($files)) {
648 my $headers = HTTP::Headers->new( %{ $upload->{headers} } );
649 my $u = Catalyst::Request::Upload->new
651 size => $upload->{size},
652 type => scalar $headers->content_type,
654 tempname => $upload->{tempname},
655 filename => $upload->{filename},
659 $request->uploads->{$name} = @uploads > 1 ? \@uploads : $uploads[0];
661 # support access to the filename as a normal param
662 my @filenames = map { $_->{filename} } @uploads;
663 # append, if there's already params with this name
664 if (exists $parameters->{$name}) {
665 if (ref $parameters->{$name} eq 'ARRAY') {
666 push @{ $parameters->{$name} }, @filenames;
669 $parameters->{$name} = [ $parameters->{$name}, @filenames ];
673 $parameters->{$name} = @filenames > 1 ? \@filenames : $filenames[0];
678 =head2 $self->read($c, [$maxlength])
680 Reads from the input stream by calling C<< $self->read_chunk >>.
682 Maintains the read_length and read_position counters as data is read.
687 my ( $self, $c, $maxlength ) = @_;
689 $c->request->read($maxlength);
692 =head2 $self->read_chunk($c, \$buffer, $length)
694 Each engine implements read_chunk as its preferred way of reading a chunk
695 of data. Returns the number of bytes read. A return of 0 indicates that
696 there is no more data to be read.
701 my ($self, $ctx) = (shift, shift);
702 return $ctx->request->read_chunk(@_);
705 =head2 $self->read_length
707 The length of input data to be read. This is obtained from the Content-Length
710 =head2 $self->read_position
712 The amount of input data that has already been read.
714 =head2 $self->run($app, $server)
716 Start the engine. Builds a PSGI application and calls the
717 run method on the server passed in, which then causes the
718 engine to loop, handling requests..
723 my ($self, $app, $psgi, @args) = @_;
724 # @args left here rather than just a $options, $server for back compat with the
725 # old style scripts which send a few args, then a hashref
727 # They should never actually be used in the normal case as the Plack engine is
728 # passed in got all the 'standard' args via the loader in the script already.
730 # FIXME - we should stash the options in an attribute so that custom args
731 # like Gitalist's --git_dir are possible to get from the app without stupid tricks.
732 my $server = pop @args if (scalar @args && blessed $args[-1]);
733 my $options = pop @args if (scalar @args && ref($args[-1]) eq 'HASH');
734 # Back compat hack for applications with old (non Catalyst::Script) scripts to work in FCGI.
735 if (scalar @args && !ref($args[0])) {
736 if (my $listen = shift @args) {
737 $options->{listen} ||= [$listen];
741 $server = Catalyst::EngineLoader->new(application_name => ref($self))->auto(%$options);
742 # We're not being called from a script, so auto detect what backend to
743 # run on. This should never happen, as mod_perl never calls ->run,
744 # instead the $app->handle method is called per request.
745 $app->log->warn("Not supplied a Plack engine, falling back to engine auto-loader (are your scripts ancient?)")
747 $app->run_options($options);
748 $server->run($psgi, $options);
751 =head2 build_psgi_app ($app, @args)
753 Builds and returns a PSGI application closure, wrapping it in the reverse proxy
754 middleware if the using_frontend_proxy config setting is set.
759 my ($self, $app, @args) = @_;
766 $app->handle_request(env => $env, response_cb => $respond);
771 =head2 $self->write($c, $buffer)
773 Writes the buffer to the client.
778 my ( $self, $c, $buffer ) = @_;
780 my $response = $c->response;
782 $buffer = q[] unless defined $buffer;
784 my $len = length($buffer);
785 $c->res->_writer->write($buffer);
790 =head2 $self->unescape_uri($uri)
792 Unescapes a given URI using the most efficient method available. Engines such
793 as Apache may implement this using Apache's C-based modules, for example.
798 my ( $self, $str ) = @_;
800 $str =~ s/(?:%([0-9A-Fa-f]{2})|\+)/defined $1 ? chr(hex($1)) : ' '/eg;
805 =head2 $self->finalize_output
807 <obsolete>, see finalize_body
811 Hash containing environment variables including many special variables inserted
812 by WWW server - like SERVER_*, REMOTE_*, HTTP_* ...
814 Before accessing environment variables consider whether the same information is
815 not directly available via Catalyst objects $c->request, $c->engine ...
817 BEWARE: If you really need to access some environment variable from your Catalyst
818 application you should use $c->engine->env->{VARNAME} instead of $ENV{VARNAME},
819 as in some environments the %ENV hash does not contain what you would expect.
823 Catalyst Contributors, see Catalyst.pm
827 This library is free software. You can redistribute it and/or modify it under
828 the same terms as Perl itself.