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';
13 use Moose::Util::TypeConstraints;
15 use Catalyst::EngineLoader;
19 use namespace::clean -except => 'meta';
21 has env => (is => 'ro', writer => '_set_env', clearer => '_clear_env');
23 my $WARN_ABOUT_ENV = 0;
25 my ($orig, $self, @args) = @_;
27 warn "env as a writer is deprecated, you probably need to upgrade Catalyst::Engine::PSGI"
28 unless $WARN_ABOUT_ENV++;
29 return $self->_set_env(@args);
34 # input position and length
35 has read_length => (is => 'rw');
36 has read_position => (is => 'rw');
38 has _prepared_write => (is => 'rw');
43 writer => '_set_response_cb',
44 clearer => '_clear_response_cb',
45 predicate => '_has_response_cb',
50 isa => duck_type([qw(write close)]),
51 writer => '_set_writer',
52 clearer => '_clear_writer',
55 # Amount of data to read from input on each pass
56 our $CHUNKSIZE = 64 * 1024;
60 Catalyst::Engine - The Catalyst Engine
71 =head2 $self->finalize_body($c)
73 Finalize body. Prints the response output.
78 my ( $self, $c ) = @_;
79 my $body = $c->response->body;
80 no warnings 'uninitialized';
81 if ( blessed($body) && $body->can('read') or ref($body) eq 'GLOB' ) {
84 $got = read $body, my ($buffer), $CHUNKSIZE;
85 $got = 0 unless $self->write( $c, $buffer );
91 $self->write( $c, $body );
94 $self->_writer->close;
101 =head2 $self->finalize_cookies($c)
103 Create CGI::Simple::Cookie objects from $c->res->cookies, and set them as
108 sub finalize_cookies {
109 my ( $self, $c ) = @_;
112 my $response = $c->response;
114 foreach my $name (keys %{ $response->cookies }) {
116 my $val = $response->cookies->{$name};
121 : CGI::Simple::Cookie->new(
123 -value => $val->{value},
124 -expires => $val->{expires},
125 -domain => $val->{domain},
126 -path => $val->{path},
127 -secure => $val->{secure} || 0,
128 -httponly => $val->{httponly} || 0,
132 push @cookies, $cookie->as_string;
135 for my $cookie (@cookies) {
136 $response->headers->push_header( 'Set-Cookie' => $cookie );
140 =head2 $self->finalize_error($c)
142 Output an appropriate error message. Called if there's an error in $c
143 after the dispatch has finished. Will output debug messages if Catalyst
144 is in debug mode, or a `please come back later` message otherwise.
148 sub _dump_error_page_element {
149 my ($self, $i, $element) = @_;
150 my ($name, $val) = @{ $element };
152 # This is fugly, but the metaclass is _HUGE_ and demands waaay too much
153 # scrolling. Suggestions for more pleasant ways to do this welcome.
154 local $val->{'__MOP__'} = "Stringified: "
155 . $val->{'__MOP__'} if ref $val eq 'HASH' && exists $val->{'__MOP__'};
157 my $text = encode_entities( dump( $val ));
158 sprintf <<"EOF", $name, $text;
159 <h2><a href="#" onclick="toggleDump('dump_$i'); return false">%s</a></h2>
161 <pre wrap="">%s</pre>
167 my ( $self, $c ) = @_;
169 $c->res->content_type('text/html; charset=utf-8');
170 my $name = ref($c)->config->{name} || join(' ', split('::', ref $c));
172 # Prevent Catalyst::Plugin::Unicode::Encoding from running.
173 # This is a little nasty, but it's the best way to be clean whether or
174 # not the user has an encoding plugin.
176 if ($c->can('encoding')) {
180 my ( $title, $error, $infos );
184 $error = join '', map {
185 '<p><code class="error">'
186 . encode_entities($_)
189 $error ||= 'No output';
190 $error = qq{<pre wrap="">$error</pre>};
191 $title = $name = "$name on Catalyst $Catalyst::VERSION";
192 $name = "<h1>$name</h1>";
194 # Don't show context in the dump
195 $c->req->_clear_context;
196 $c->res->_clear_context;
198 # Don't show body parser in the dump
199 $c->req->_clear_body;
203 for my $dump ( $c->dump_these ) {
204 push @infos, $self->_dump_error_page_element($i, $dump);
207 $infos = join "\n", @infos;
214 (en) Please come back later
215 (fr) SVP veuillez revenir plus tard
216 (de) Bitte versuchen sie es spaeter nocheinmal
217 (at) Konnten's bitt'schoen spaeter nochmal reinschauen
218 (no) Vennligst prov igjen senere
219 (dk) Venligst prov igen senere
220 (pl) Prosze sprobowac pozniej
221 (pt) Por favor volte mais tarde
222 (ru) Попробуйте еще раз позже
223 (ua) Спробуйте ще раз пізніше
228 $c->res->body( <<"" );
229 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
230 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
231 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
233 <meta http-equiv="Content-Language" content="en" />
234 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
235 <title>$title</title>
236 <script type="text/javascript">
238 function toggleDump (dumpElement) {
239 var e = document.getElementById( dumpElement );
240 if (e.style.display == "none") {
241 e.style.display = "";
244 e.style.display = "none";
249 <style type="text/css">
251 font-family: "Bitstream Vera Sans", "Trebuchet MS", Verdana,
252 Tahoma, Arial, helvetica, sans-serif;
254 background-color: #eee;
258 :link, :link:hover, :visited, :visited:hover {
263 background-color: #ccc;
264 border: 1px solid #aaa;
269 background-color: #cce;
270 border: 1px solid #755;
276 background-color: #eee;
277 border: 1px solid #575;
283 background-color: #cce;
284 border: 1px solid #557;
293 div.name h1, div.error p {
301 text-decoration: underline;
307 /* from http://users.tkk.fi/~tkarvine/linux/doc/pre-wrap/pre-wrap-css3-mozilla-opera-ie.html */
308 /* Browser specific (not valid) styles to make preformatted text wrap */
310 white-space: pre-wrap; /* css-3 */
311 white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
312 white-space: -pre-wrap; /* Opera 4-6 */
313 white-space: -o-pre-wrap; /* Opera 7 */
314 word-wrap: break-word; /* Internet Explorer 5.5+ */
320 <div class="error">$error</div>
321 <div class="infos">$infos</div>
322 <div class="name">$name</div>
327 # Trick IE. Old versions of IE would display their own error page instead
328 # of ours if we'd give it less than 512 bytes.
329 $c->res->{body} .= ( ' ' x 512 );
331 $c->res->{body} = Encode::encode("UTF-8", $c->res->{body});
334 $c->res->status(500);
337 =head2 $self->finalize_headers($c)
339 Abstract method, allows engines to write headers to response
343 sub finalize_headers {
344 my ($self, $ctx) = @_;
346 # This is a less-than-pretty hack to avoid breaking the old
347 # Catalyst::Engine::PSGI. 5.9 Catalyst::Engine sets a response_cb and
348 # expects us to pass headers to it here, whereas Catalyst::Enngine::PSGI
349 # just pulls the headers out of $ctx->response in its run method and never
350 # sets response_cb. So take the lack of a response_cb as a sign that we
351 # don't need to set the headers.
353 return unless $self->_has_response_cb;
356 $ctx->response->headers->scan(sub { push @headers, @_ });
358 $self->_set_writer($self->_response_cb->([ $ctx->response->status, \@headers ]));
359 $self->_clear_response_cb;
364 =head2 $self->finalize_read($c)
368 sub finalize_read { }
370 =head2 $self->finalize_uploads($c)
372 Clean up after uploads, deleting temp files.
376 sub finalize_uploads {
377 my ( $self, $c ) = @_;
379 # N.B. This code is theoretically entirely unneeded due to ->cleanup(1)
380 # on the HTTP::Body object.
381 my $request = $c->request;
382 foreach my $key (keys %{ $request->uploads }) {
383 my $upload = $request->uploads->{$key};
384 unlink grep { -e $_ } map { $_->tempname }
385 (ref $upload eq 'ARRAY' ? @{$upload} : ($upload));
390 =head2 $self->prepare_body($c)
392 sets up the L<Catalyst::Request> object body using L<HTTP::Body>
397 my ( $self, $c ) = @_;
399 my $appclass = ref($c) || $c;
400 if ( my $length = $self->read_length ) {
401 my $request = $c->request;
402 unless ( $request->_body ) {
403 my $type = $request->header('Content-Type');
404 $request->_body(HTTP::Body->new( $type, $length ));
405 $request->_body->cleanup(1); # Make extra sure!
406 $request->_body->tmpdir( $appclass->config->{uploadtmp} )
407 if exists $appclass->config->{uploadtmp};
410 # Check for definedness as you could read '0'
411 while ( defined ( my $buffer = $self->read($c) ) ) {
412 $c->prepare_body_chunk($buffer);
415 # paranoia against wrong Content-Length header
416 my $remaining = $length - $self->read_position;
417 if ( $remaining > 0 ) {
418 $self->finalize_read($c);
419 Catalyst::Exception->throw(
420 "Wrong Content-Length value: $length" );
424 # Defined but will cause all body code to be skipped
425 $c->request->_body(0);
429 =head2 $self->prepare_body_chunk($c)
431 Add a chunk to the request body.
435 sub prepare_body_chunk {
436 my ( $self, $c, $chunk ) = @_;
438 $c->request->_body->add($chunk);
441 =head2 $self->prepare_body_parameters($c)
443 Sets up parameters from body.
447 sub prepare_body_parameters {
448 my ( $self, $c ) = @_;
450 return unless $c->request->_body;
452 $c->request->body_parameters( $c->request->_body->param );
455 =head2 $self->prepare_connection($c)
457 Abstract method implemented in engines.
461 sub prepare_connection {
462 my ($self, $ctx) = @_;
464 my $env = $self->env;
465 my $request = $ctx->request;
467 $request->address( $env->{REMOTE_ADDR} );
468 $request->hostname( $env->{REMOTE_HOST} )
469 if exists $env->{REMOTE_HOST};
470 $request->protocol( $env->{SERVER_PROTOCOL} );
471 $request->remote_user( $env->{REMOTE_USER} );
472 $request->method( $env->{REQUEST_METHOD} );
473 $request->secure( $env->{'psgi.url_scheme'} eq 'https' ? 1 : 0 );
478 =head2 $self->prepare_cookies($c)
480 Parse cookies from header. Sets a L<CGI::Simple::Cookie> object.
484 sub prepare_cookies {
485 my ( $self, $c ) = @_;
487 if ( my $header = $c->request->header('Cookie') ) {
488 $c->req->cookies( { CGI::Simple::Cookie->parse($header) } );
492 =head2 $self->prepare_headers($c)
496 sub prepare_headers {
497 my ($self, $ctx) = @_;
499 my $env = $self->env;
500 my $headers = $ctx->request->headers;
502 for my $header (keys %{ $env }) {
503 next unless $header =~ /^(HTTP|CONTENT|COOKIE)/i;
504 (my $field = $header) =~ s/^HTTPS?_//;
506 $headers->header($field => $env->{$header});
510 =head2 $self->prepare_parameters($c)
512 sets up parameters from query and post parameters.
516 sub prepare_parameters {
517 my ( $self, $c ) = @_;
519 my $request = $c->request;
520 my $parameters = $request->parameters;
521 my $body_parameters = $request->body_parameters;
522 my $query_parameters = $request->query_parameters;
523 # We copy, no references
524 foreach my $name (keys %$query_parameters) {
525 my $param = $query_parameters->{$name};
526 $parameters->{$name} = ref $param eq 'ARRAY' ? [ @$param ] : $param;
529 # Merge query and body parameters
530 foreach my $name (keys %$body_parameters) {
531 my $param = $body_parameters->{$name};
532 my @values = ref $param eq 'ARRAY' ? @$param : ($param);
533 if ( my $existing = $parameters->{$name} ) {
534 unshift(@values, (ref $existing eq 'ARRAY' ? @$existing : $existing));
536 $parameters->{$name} = @values > 1 ? \@values : $values[0];
540 =head2 $self->prepare_path($c)
542 abstract method, implemented by engines.
547 my ($self, $ctx) = @_;
549 my $env = $self->env;
551 my $scheme = $ctx->request->secure ? 'https' : 'http';
552 my $host = $env->{HTTP_HOST} || $env->{SERVER_NAME};
553 my $port = $env->{SERVER_PORT} || 80;
554 my $base_path = $env->{SCRIPT_NAME} || "/";
556 # set the request URI
558 if (!$ctx->config->{use_request_uri_for_path}) {
559 my $path_info = $env->{PATH_INFO};
560 if ( exists $env->{REDIRECT_URL} ) {
561 $base_path = $env->{REDIRECT_URL};
562 $base_path =~ s/\Q$path_info\E$//;
564 $path = $base_path . $path_info;
566 $path =~ s/([^$URI::uric])/$URI::Escape::escapes{$1}/go;
567 $path =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
570 my $req_uri = $env->{REQUEST_URI};
571 $req_uri =~ s/\?.*$//;
576 # Using URI directly is way too slow, so we construct the URLs manually
577 my $uri_class = "URI::$scheme";
579 # HTTP_HOST will include the port even if it's 80/443
580 $host =~ s/:(?:80|443)$//;
582 if ($port !~ /^(?:80|443)$/ && $host !~ /:/) {
586 my $query = $env->{QUERY_STRING} ? '?' . $env->{QUERY_STRING} : '';
587 my $uri = $scheme . '://' . $host . '/' . $path . $query;
589 $ctx->request->uri( (bless \$uri, $uri_class)->canonical );
592 # base must end in a slash
593 $base_path .= '/' unless $base_path =~ m{/$};
595 my $base_uri = $scheme . '://' . $host . $base_path;
597 $ctx->request->base( bless \$base_uri, $uri_class );
602 =head2 $self->prepare_request($c)
604 =head2 $self->prepare_query_parameters($c)
606 process the query string and extract query parameters.
610 sub prepare_query_parameters {
613 my $query_string = exists $self->env->{QUERY_STRING}
614 ? $self->env->{QUERY_STRING}
617 # Check for keywords (no = signs)
618 # (yes, index() is faster than a regex :))
619 if ( index( $query_string, '=' ) < 0 ) {
620 $c->request->query_keywords( $self->unescape_uri($query_string) );
626 # replace semi-colons
627 $query_string =~ s/;/&/g;
629 my @params = grep { length $_ } split /&/, $query_string;
631 for my $item ( @params ) {
634 = map { $self->unescape_uri($_) }
635 split( /=/, $item, 2 );
637 $param = $self->unescape_uri($item) unless defined $param;
639 if ( exists $query{$param} ) {
640 if ( ref $query{$param} ) {
641 push @{ $query{$param} }, $value;
644 $query{$param} = [ $query{$param}, $value ];
648 $query{$param} = $value;
652 $c->request->query_parameters( \%query );
655 =head2 $self->prepare_read($c)
657 prepare to read from the engine.
662 my ( $self, $c ) = @_;
664 # Initialize the read position
665 $self->read_position(0);
667 # Initialize the amount of data we think we need to read
668 $self->read_length( $c->request->header('Content-Length') || 0 );
671 =head2 $self->prepare_request(@arguments)
673 Populate the context object from the request object.
677 sub prepare_request {
678 my ($self, $ctx, %args) = @_;
679 $self->_set_env($args{env});
682 =head2 $self->prepare_uploads($c)
686 sub prepare_uploads {
687 my ( $self, $c ) = @_;
689 my $request = $c->request;
690 return unless $request->_body;
692 my $uploads = $request->_body->upload;
693 my $parameters = $request->parameters;
694 foreach my $name (keys %$uploads) {
695 my $files = $uploads->{$name};
697 for my $upload (ref $files eq 'ARRAY' ? @$files : ($files)) {
698 my $headers = HTTP::Headers->new( %{ $upload->{headers} } );
699 my $u = Catalyst::Request::Upload->new
701 size => $upload->{size},
702 type => scalar $headers->content_type,
704 tempname => $upload->{tempname},
705 filename => $upload->{filename},
709 $request->uploads->{$name} = @uploads > 1 ? \@uploads : $uploads[0];
711 # support access to the filename as a normal param
712 my @filenames = map { $_->{filename} } @uploads;
713 # append, if there's already params with this name
714 if (exists $parameters->{$name}) {
715 if (ref $parameters->{$name} eq 'ARRAY') {
716 push @{ $parameters->{$name} }, @filenames;
719 $parameters->{$name} = [ $parameters->{$name}, @filenames ];
723 $parameters->{$name} = @filenames > 1 ? \@filenames : $filenames[0];
728 =head2 $self->prepare_write($c)
730 Abstract method. Implemented by the engines.
734 sub prepare_write { }
736 =head2 $self->read($c, [$maxlength])
738 Reads from the input stream by calling C<< $self->read_chunk >>.
740 Maintains the read_length and read_position counters as data is read.
745 my ( $self, $c, $maxlength ) = @_;
747 my $remaining = $self->read_length - $self->read_position;
748 $maxlength ||= $CHUNKSIZE;
750 # Are we done reading?
751 if ( $remaining <= 0 ) {
752 $self->finalize_read($c);
756 my $readlen = ( $remaining > $maxlength ) ? $maxlength : $remaining;
757 my $rc = $self->read_chunk( $c, my $buffer, $readlen );
759 if (0 == $rc) { # Nothing more to read even though Content-Length
760 # said there should be.
761 $self->finalize_read;
764 $self->read_position( $self->read_position + $rc );
768 Catalyst::Exception->throw(
769 message => "Unknown error reading input: $!" );
773 =head2 $self->read_chunk($c, $buffer, $length)
775 Each engine implements read_chunk as its preferred way of reading a chunk
776 of data. Returns the number of bytes read. A return of 0 indicates that
777 there is no more data to be read.
782 my ($self, $ctx) = (shift, shift);
783 return $self->env->{'psgi.input'}->read(@_);
786 =head2 $self->read_length
788 The length of input data to be read. This is obtained from the Content-Length
791 =head2 $self->read_position
793 The amount of input data that has already been read.
795 =head2 $self->run($app, $server)
797 Start the engine. Builds a PSGI application and calls the
798 run method on the server passed in, which then causes the
799 engine to loop, handling requests..
804 my ($self, $app, $psgi, @args) = @_;
805 # @args left here rather than just a $options, $server for back compat with the
806 # old style scripts which send a few args, then a hashref
808 # They should never actually be used in the normal case as the Plack engine is
809 # passed in got all the 'standard' args via the loader in the script already.
811 # FIXME - we should stash the options in an attribute so that custom args
812 # like Gitalist's --git_dir are possible to get from the app without stupid tricks.
813 my $server = pop @args if (scalar @args && blessed $args[-1]);
814 my $options = pop @args if (scalar @args && ref($args[-1]) eq 'HASH');
815 # Back compat hack for applications with old (non Catalyst::Script) scripts to work in FCGI.
816 if (scalar @args && !ref($args[0])) {
817 if (my $listen = shift @args) {
818 $options->{listen} ||= [$listen];
822 $server = Catalyst::EngineLoader->new(application_name => ref($self))->auto(%$options);
823 # We're not being called from a script, so auto detect what backend to
824 # run on. This should never happen, as mod_perl never calls ->run,
825 # instead the $app->handle method is called per request.
826 $app->log->warn("Not supplied a Plack engine, falling back to engine auto-loader (are your scripts ancient?)")
828 $server->run($psgi, $options);
831 =head2 build_psgi_app ($app, @args)
833 Builds and returns a PSGI application closure, wrapping it in the reverse proxy
834 middleware if the using_frontend_proxy config setting is set.
839 my ($self, $app, @args) = @_;
846 $self->_set_response_cb($respond);
847 $app->handle_request(env => $env);
852 =head2 $self->write($c, $buffer)
854 Writes the buffer to the client.
859 my ( $self, $c, $buffer ) = @_;
861 unless ( $self->_prepared_write ) {
862 $self->prepare_write($c);
863 $self->_prepared_write(1);
866 $buffer = q[] unless defined $buffer;
868 my $len = length($buffer);
869 $self->_writer->write($buffer);
874 =head2 $self->unescape_uri($uri)
876 Unescapes a given URI using the most efficient method available. Engines such
877 as Apache may implement this using Apache's C-based modules, for example.
882 my ( $self, $str ) = @_;
884 $str =~ s/(?:%([0-9A-Fa-f]{2})|\+)/defined $1 ? chr(hex($1)) : ' '/eg;
889 =head2 $self->finalize_output
891 <obsolete>, see finalize_body
895 Hash containing environment variables including many special variables inserted
896 by WWW server - like SERVER_*, REMOTE_*, HTTP_* ...
898 Before accessing environment variables consider whether the same information is
899 not directly available via Catalyst objects $c->request, $c->engine ...
901 BEWARE: If you really need to access some environment variable from your Catalyst
902 application you should use $c->engine->env->{VARNAME} instead of $ENV{VARNAME},
903 as in some environments the %ENV hash does not contain what you would expect.
907 Catalyst Contributors, see Catalyst.pm
911 This library is free software. You can redistribute it and/or modify it under
912 the same terms as Perl itself.