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;
16 use Plack::Request::Upload;
20 use namespace::clean -except => 'meta';
22 # Amount of data to read from input on each pass
23 our $CHUNKSIZE = 64 * 1024;
25 # XXX - Only here for Engine::PSGI compat
26 sub prepare_connection {
27 my ($self, $ctx) = @_;
28 $ctx->request->prepare_connection;
33 Catalyst::Engine - The Catalyst Engine
44 =head2 $self->finalize_body($c)
46 Finalize body. Prints the response output as blocking stream if it looks like
47 a filehandle, otherwise write it out all in one go. If there is no body in
48 the response, we assume you are handling it 'manually', such as for nonblocking
49 style or asynchronous streaming responses. You do this by calling L</write>
50 several times (which sends HTTP headers if needed) or you close over
51 C<< $response->write_fh >>.
53 See L<Catalyst::Response/write> and L<Catalyst::Response/write_fh> for more.
58 my ( $self, $c ) = @_;
59 my $res = $c->response; # We use this all over
61 ## If we've asked for the write 'filehandle' that means the application is
62 ## doing something custom and is expected to close the response
63 return if $res->_has_write_fh;
65 my $body = $res->body; # save some typing
66 if($res->_has_response_cb) {
67 ## we have not called the response callback yet, so we are safe to send
68 ## the whole body to PSGI
71 $res->headers->scan(sub { push @headers, @_ });
73 # We need to figure out what kind of body we have and normalize it to something
76 # Handle objects first
78 if($body->can('getline')) {
79 # Body is an IO handle that meets the PSGI spec. Nothing to normalize
80 } elsif($body->can('read')) {
82 # In the past, Catalyst only looked for ->read not ->getline. It is very possible
83 # that one might have an object that respected read but did not have getline.
84 # As a result, we need to handle this case for backcompat.
86 # We will just do the old loop for now. In a future version of Catalyst this support
87 # will be removed and one will have to rewrite their custom object or use
88 # Plack::Middleware::AdaptFilehandleRead. In anycase support for this is officially
89 # deprecated and described as such as of 5.90060
93 $got = read $body, my ($buffer), $CHUNKSIZE;
94 $got = 0 unless $self->write($c, $buffer );
100 # Looks like for backcompat reasons we need to be able to deal
101 # with stringyfiable objects.
105 if( (ref($body) eq 'GLOB') or (ref($body) eq 'ARRAY')) {
106 # Again, PSGI can just accept this, no transform needed. We don't officially
107 # document the body as arrayref at this time (and there's not specific test
108 # cases. we support it because it simplifies some plack compatibility logic
109 # and we might make it official at some point.
111 $c->log->error("${\ref($body)} is not a valid value for Response->body");
115 # Body is defined and not an object or reference. We assume a simple value
116 # and wrap it in an array for PSGI
124 $res->_response_cb->([ $res->status, \@headers, $body]);
125 $res->_clear_response_cb;
128 ## Now, if there's no response callback anymore, that means someone has
129 ## called ->write in order to stream 'some stuff along the way'. I think
130 ## for backcompat we still need to handle a ->body. I guess I could see
131 ## someone calling ->write to presend some stuff, and then doing the rest
132 ## via ->body, like in a template.
134 ## We'll just use the old, existing code for this (or most of it)
136 if(my $body = $res->body) {
138 if ( blessed($body) && $body->can('read') or ref($body) eq 'GLOB' ) {
140 ## In this case we have no choice and will fall back on the old
141 ## manual streaming stuff. Not optimal. This is deprecated as of 5.900560+
145 $got = read $body, my ($buffer), $CHUNKSIZE;
146 $got = 0 unless $self->write($c, $buffer );
153 # Case where body was set afgter calling ->write. We'd prefer not to
154 # support this, but I can see some use cases with the way most of the
157 $self->write($c, $body );
161 $res->_writer->close;
168 =head2 $self->finalize_cookies($c)
170 Create CGI::Simple::Cookie objects from $c->res->cookies, and set them as
175 sub finalize_cookies {
176 my ( $self, $c ) = @_;
179 my $response = $c->response;
181 foreach my $name (keys %{ $response->cookies }) {
183 my $val = $response->cookies->{$name};
188 : CGI::Simple::Cookie->new(
190 -value => $val->{value},
191 -expires => $val->{expires},
192 -domain => $val->{domain},
193 -path => $val->{path},
194 -secure => $val->{secure} || 0,
195 -httponly => $val->{httponly} || 0,
198 if (!defined $cookie) {
199 $c->log->warn("undef passed in '$name' cookie value - not setting cookie")
204 push @cookies, $cookie->as_string;
207 for my $cookie (@cookies) {
208 $response->headers->push_header( 'Set-Cookie' => $cookie );
212 =head2 $self->finalize_error($c)
214 Output an appropriate error message. Called if there's an error in $c
215 after the dispatch has finished. Will output debug messages if Catalyst
216 is in debug mode, or a `please come back later` message otherwise.
220 sub _dump_error_page_element {
221 my ($self, $i, $element) = @_;
222 my ($name, $val) = @{ $element };
224 # This is fugly, but the metaclass is _HUGE_ and demands waaay too much
225 # scrolling. Suggestions for more pleasant ways to do this welcome.
226 local $val->{'__MOP__'} = "Stringified: "
227 . $val->{'__MOP__'} if ref $val eq 'HASH' && exists $val->{'__MOP__'};
229 my $text = encode_entities( dump( $val ));
230 sprintf <<"EOF", $name, $text;
231 <h2><a href="#" onclick="toggleDump('dump_$i'); return false">%s</a></h2>
233 <pre wrap="">%s</pre>
239 my ( $self, $c ) = @_;
241 $c->res->content_type('text/html; charset=utf-8');
242 my $name = ref($c)->config->{name} || join(' ', split('::', ref $c));
244 # Prevent Catalyst::Plugin::Unicode::Encoding from running.
245 # This is a little nasty, but it's the best way to be clean whether or
246 # not the user has an encoding plugin.
248 if ($c->can('encoding')) {
252 my ( $title, $error, $infos );
256 $error = join '', map {
257 '<p><code class="error">'
258 . encode_entities($_)
261 $error ||= 'No output';
262 $error = qq{<pre wrap="">$error</pre>};
263 $title = $name = "$name on Catalyst $Catalyst::VERSION";
264 $name = "<h1>$name</h1>";
266 # Don't show context in the dump
267 $c->res->_clear_context;
269 # Don't show body parser in the dump
270 $c->req->_clear_body;
274 for my $dump ( $c->dump_these ) {
275 push @infos, $self->_dump_error_page_element($i, $dump);
278 $infos = join "\n", @infos;
285 (en) Please come back later
286 (fr) SVP veuillez revenir plus tard
287 (de) Bitte versuchen sie es spaeter nocheinmal
288 (at) Konnten's bitt'schoen spaeter nochmal reinschauen
289 (no) Vennligst prov igjen senere
290 (dk) Venligst prov igen senere
291 (pl) Prosze sprobowac pozniej
292 (pt) Por favor volte mais tarde
293 (ru) Попробуйте еще раз позже
294 (ua) Спробуйте ще раз пізніше
299 $c->res->body( <<"" );
300 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
301 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
302 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
304 <meta http-equiv="Content-Language" content="en" />
305 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
306 <title>$title</title>
307 <script type="text/javascript">
309 function toggleDump (dumpElement) {
310 var e = document.getElementById( dumpElement );
311 if (e.style.display == "none") {
312 e.style.display = "";
315 e.style.display = "none";
320 <style type="text/css">
322 font-family: "Bitstream Vera Sans", "Trebuchet MS", Verdana,
323 Tahoma, Arial, helvetica, sans-serif;
325 background-color: #eee;
329 :link, :link:hover, :visited, :visited:hover {
334 background-color: #ccc;
335 border: 1px solid #aaa;
340 background-color: #cce;
341 border: 1px solid #755;
347 background-color: #eee;
348 border: 1px solid #575;
354 background-color: #cce;
355 border: 1px solid #557;
364 div.name h1, div.error p {
372 text-decoration: underline;
378 /* from http://users.tkk.fi/~tkarvine/linux/doc/pre-wrap/pre-wrap-css3-mozilla-opera-ie.html */
379 /* Browser specific (not valid) styles to make preformatted text wrap */
381 white-space: pre-wrap; /* css-3 */
382 white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
383 white-space: -pre-wrap; /* Opera 4-6 */
384 white-space: -o-pre-wrap; /* Opera 7 */
385 word-wrap: break-word; /* Internet Explorer 5.5+ */
391 <div class="error">$error</div>
392 <div class="infos">$infos</div>
393 <div class="name">$name</div>
398 # Trick IE. Old versions of IE would display their own error page instead
399 # of ours if we'd give it less than 512 bytes.
400 $c->res->{body} .= ( ' ' x 512 );
402 $c->res->{body} = Encode::encode("UTF-8", $c->res->{body});
405 $c->res->status(500);
408 =head2 $self->finalize_headers($c)
410 Allows engines to write headers to response
414 sub finalize_headers {
415 my ($self, $ctx) = @_;
417 $ctx->finalize_headers unless $ctx->response->finalized_headers;
421 =head2 $self->finalize_uploads($c)
423 Clean up after uploads, deleting temp files.
427 sub finalize_uploads {
428 my ( $self, $c ) = @_;
430 # N.B. This code is theoretically entirely unneeded due to ->cleanup(1)
431 # on the HTTP::Body object.
432 my $request = $c->request;
433 foreach my $key (keys %{ $request->uploads }) {
434 my $upload = $request->uploads->{$key};
435 unlink grep { -e $_ } map { $_->tempname }
436 (ref $upload eq 'ARRAY' ? @{$upload} : ($upload));
441 =head2 $self->prepare_body($c)
443 sets up the L<Catalyst::Request> object body using L<HTTP::Body>
448 my ( $self, $c ) = @_;
450 $c->request->prepare_body;
453 =head2 $self->prepare_body_chunk($c)
455 Add a chunk to the request body.
459 # XXX - Can this be deleted?
460 sub prepare_body_chunk {
461 my ( $self, $c, $chunk ) = @_;
463 $c->request->prepare_body_chunk($chunk);
466 =head2 $self->prepare_body_parameters($c)
468 Sets up parameters from body.
472 sub prepare_body_parameters {
473 my ( $self, $c ) = @_;
475 $c->request->prepare_body_parameters;
478 =head2 $self->prepare_parameters($c)
480 Sets up parameters from query and post parameters.
481 If parameters have already been set up will clear
482 existing parameters and set up again.
486 sub prepare_parameters {
487 my ( $self, $c ) = @_;
489 $c->request->_clear_parameters;
490 return $c->request->parameters;
493 =head2 $self->prepare_path($c)
495 abstract method, implemented by engines.
500 my ($self, $ctx) = @_;
502 my $env = $ctx->request->env;
504 my $scheme = $ctx->request->secure ? 'https' : 'http';
505 my $host = $env->{HTTP_HOST} || $env->{SERVER_NAME};
506 my $port = $env->{SERVER_PORT} || 80;
507 my $base_path = $env->{SCRIPT_NAME} || "/";
509 # set the request URI
511 if (!$ctx->config->{use_request_uri_for_path}) {
512 my $path_info = $env->{PATH_INFO};
513 if ( exists $env->{REDIRECT_URL} ) {
514 $base_path = $env->{REDIRECT_URL};
515 $base_path =~ s/\Q$path_info\E$//;
517 $path = $base_path . $path_info;
519 $path =~ s/([^$URI::uric])/$URI::Escape::escapes{$1}/go;
520 $path =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
523 my $req_uri = $env->{REQUEST_URI};
524 $req_uri =~ s/\?.*$//;
529 # Using URI directly is way too slow, so we construct the URLs manually
530 my $uri_class = "URI::$scheme";
532 # HTTP_HOST will include the port even if it's 80/443
533 $host =~ s/:(?:80|443)$//;
535 if ($port !~ /^(?:80|443)$/ && $host !~ /:/) {
539 my $query = $env->{QUERY_STRING} ? '?' . $env->{QUERY_STRING} : '';
540 my $uri = $scheme . '://' . $host . '/' . $path . $query;
542 $ctx->request->uri( (bless \$uri, $uri_class)->canonical );
545 # base must end in a slash
546 $base_path .= '/' unless $base_path =~ m{/$};
548 my $base_uri = $scheme . '://' . $host . $base_path;
550 $ctx->request->base( bless \$base_uri, $uri_class );
555 =head2 $self->prepare_request($c)
557 =head2 $self->prepare_query_parameters($c)
559 process the query string and extract query parameters.
563 sub prepare_query_parameters {
565 my $env = $c->request->env;
567 if(my $query_obj = $env->{'plack.request.query'}) {
568 $c->request->query_parameters(
569 $c->request->_use_hash_multivalue ?
571 $query_obj->as_hashref_mixed);
575 my $query_string = exists $env->{QUERY_STRING}
576 ? $env->{QUERY_STRING}
579 # Check for keywords (no = signs)
580 # (yes, index() is faster than a regex :))
581 if ( index( $query_string, '=' ) < 0 ) {
582 $c->request->query_keywords($self->unescape_uri($query_string));
588 # replace semi-colons
589 $query_string =~ s/;/&/g;
591 my @params = grep { length $_ } split /&/, $query_string;
593 for my $item ( @params ) {
596 = map { $self->unescape_uri($_) }
597 split( /=/, $item, 2 );
599 $param = $self->unescape_uri($item) unless defined $param;
601 if ( exists $query{$param} ) {
602 if ( ref $query{$param} ) {
603 push @{ $query{$param} }, $value;
606 $query{$param} = [ $query{$param}, $value ];
610 $query{$param} = $value;
614 $c->request->query_parameters(
615 $c->request->_use_hash_multivalue ?
616 Hash::MultiValue->from_mixed(\%query) :
620 =head2 $self->prepare_read($c)
622 Prepare to read by initializing the Content-Length from headers.
627 my ( $self, $c ) = @_;
629 # Initialize the amount of data we think we need to read
630 $c->request->_read_length;
633 =head2 $self->prepare_request(@arguments)
635 Populate the context object from the request object.
639 sub prepare_request {
640 my ($self, $ctx, %args) = @_;
641 $ctx->log->psgienv($args{env}) if $ctx->log->can('psgienv');
642 $ctx->request->_set_env($args{env});
643 $ctx->response->_set_response_cb($args{response_cb});
646 =head2 $self->prepare_uploads($c)
650 sub prepare_uploads {
651 my ( $self, $c ) = @_;
653 my $request = $c->request;
654 return unless $request->_body;
656 my $uploads = $request->_body->upload;
657 my $parameters = $request->parameters;
658 foreach my $name (keys %$uploads) {
659 my $files = $uploads->{$name};
661 for my $upload (ref $files eq 'ARRAY' ? @$files : ($files)) {
662 my $headers = HTTP::Headers->new( %{ $upload->{headers} } );
663 my $u = Catalyst::Request::Upload->new
665 size => $upload->{size},
666 type => scalar $headers->content_type,
668 tempname => $upload->{tempname},
669 filename => $upload->{filename},
673 $request->uploads->{$name} = @uploads > 1 ? \@uploads : $uploads[0];
675 # support access to the filename as a normal param
676 my @filenames = map { $_->{filename} } @uploads;
677 # append, if there's already params with this name
678 if (exists $parameters->{$name}) {
679 if (ref $parameters->{$name} eq 'ARRAY') {
680 push @{ $parameters->{$name} }, @filenames;
683 $parameters->{$name} = [ $parameters->{$name}, @filenames ];
687 $parameters->{$name} = @filenames > 1 ? \@filenames : $filenames[0];
692 =head2 $self->write($c, $buffer)
694 Writes the buffer to the client.
699 my ( $self, $c, $buffer ) = @_;
701 $c->response->write($buffer);
704 =head2 $self->read($c, [$maxlength])
706 Reads from the input stream by calling C<< $self->read_chunk >>.
708 Maintains the read_length and read_position counters as data is read.
713 my ( $self, $c, $maxlength ) = @_;
715 $c->request->read($maxlength);
718 =head2 $self->read_chunk($c, \$buffer, $length)
720 Each engine implements read_chunk as its preferred way of reading a chunk
721 of data. Returns the number of bytes read. A return of 0 indicates that
722 there is no more data to be read.
727 my ($self, $ctx) = (shift, shift);
728 return $ctx->request->read_chunk(@_);
731 =head2 $self->run($app, $server)
733 Start the engine. Builds a PSGI application and calls the
734 run method on the server passed in, which then causes the
735 engine to loop, handling requests..
740 my ($self, $app, $psgi, @args) = @_;
741 # @args left here rather than just a $options, $server for back compat with the
742 # old style scripts which send a few args, then a hashref
744 # They should never actually be used in the normal case as the Plack engine is
745 # passed in got all the 'standard' args via the loader in the script already.
747 # FIXME - we should stash the options in an attribute so that custom args
748 # like Gitalist's --git_dir are possible to get from the app without stupid tricks.
749 my $server = pop @args if (scalar @args && blessed $args[-1]);
750 my $options = pop @args if (scalar @args && ref($args[-1]) eq 'HASH');
751 # Back compat hack for applications with old (non Catalyst::Script) scripts to work in FCGI.
752 if (scalar @args && !ref($args[0])) {
753 if (my $listen = shift @args) {
754 $options->{listen} ||= [$listen];
758 $server = Catalyst::EngineLoader->new(application_name => ref($self))->auto(%$options);
759 # We're not being called from a script, so auto detect what backend to
760 # run on. This should never happen, as mod_perl never calls ->run,
761 # instead the $app->handle method is called per request.
762 $app->log->warn("Not supplied a Plack engine, falling back to engine auto-loader (are your scripts ancient?)")
764 $app->run_options($options);
765 $server->run($psgi, $options);
768 =head2 build_psgi_app ($app, @args)
770 Builds and returns a PSGI application closure. (Raw, not wrapped in middleware)
775 my ($self, $app, @args) = @_;
782 confess("Did not get a response callback for writer, cannot continue") unless $respond;
783 $app->handle_request(env => $env, response_cb => $respond);
788 =head2 $self->unescape_uri($uri)
790 Unescapes a given URI using the most efficient method available. Engines such
791 as Apache may implement this using Apache's C-based modules, for example.
796 my ( $self, $str ) = @_;
798 $str =~ s/(?:%([0-9A-Fa-f]{2})|\+)/defined $1 ? chr(hex($1)) : ' '/eg;
803 =head2 $self->finalize_output
805 <obsolete>, see finalize_body
809 Hash containing environment variables including many special variables inserted
810 by WWW server - like SERVER_*, REMOTE_*, HTTP_* ...
812 Before accessing environment variables consider whether the same information is
813 not directly available via Catalyst objects $c->request, $c->engine ...
815 BEWARE: If you really need to access some environment variable from your Catalyst
816 application you should use $c->engine->env->{VARNAME} instead of $ENV{VARNAME},
817 as in some environments the %ENV hash does not contain what you would expect.
821 Catalyst Contributors, see Catalyst.pm
825 This library is free software. You can redistribute it and/or modify it under
826 the same terms as Perl itself.
830 __PACKAGE__->meta->make_immutable;