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',
49 isa => duck_type([qw(write close)]),
50 writer => '_set_writer',
51 clearer => '_clear_writer',
54 # Amount of data to read from input on each pass
55 our $CHUNKSIZE = 64 * 1024;
59 Catalyst::Engine - The Catalyst Engine
70 =head2 $self->finalize_body($c)
72 Finalize body. Prints the response output.
77 my ( $self, $c ) = @_;
78 my $body = $c->response->body;
79 no warnings 'uninitialized';
80 if ( blessed($body) && $body->can('read') or ref($body) eq 'GLOB' ) {
83 $got = read $body, my ($buffer), $CHUNKSIZE;
84 $got = 0 unless $self->write( $c, $buffer );
90 $self->write( $c, $body );
93 $self->_writer->close;
100 =head2 $self->finalize_cookies($c)
102 Create CGI::Simple::Cookie objects from $c->res->cookies, and set them as
107 sub finalize_cookies {
108 my ( $self, $c ) = @_;
111 my $response = $c->response;
113 foreach my $name (keys %{ $response->cookies }) {
115 my $val = $response->cookies->{$name};
120 : CGI::Simple::Cookie->new(
122 -value => $val->{value},
123 -expires => $val->{expires},
124 -domain => $val->{domain},
125 -path => $val->{path},
126 -secure => $val->{secure} || 0,
127 -httponly => $val->{httponly} || 0,
131 push @cookies, $cookie->as_string;
134 for my $cookie (@cookies) {
135 $response->headers->push_header( 'Set-Cookie' => $cookie );
139 =head2 $self->finalize_error($c)
141 Output an appropriate error message. Called if there's an error in $c
142 after the dispatch has finished. Will output debug messages if Catalyst
143 is in debug mode, or a `please come back later` message otherwise.
147 sub _dump_error_page_element {
148 my ($self, $i, $element) = @_;
149 my ($name, $val) = @{ $element };
151 # This is fugly, but the metaclass is _HUGE_ and demands waaay too much
152 # scrolling. Suggestions for more pleasant ways to do this welcome.
153 local $val->{'__MOP__'} = "Stringified: "
154 . $val->{'__MOP__'} if ref $val eq 'HASH' && exists $val->{'__MOP__'};
156 my $text = encode_entities( dump( $val ));
157 sprintf <<"EOF", $name, $text;
158 <h2><a href="#" onclick="toggleDump('dump_$i'); return false">%s</a></h2>
160 <pre wrap="">%s</pre>
166 my ( $self, $c ) = @_;
168 $c->res->content_type('text/html; charset=utf-8');
169 my $name = ref($c)->config->{name} || join(' ', split('::', ref $c));
171 # Prevent Catalyst::Plugin::Unicode::Encoding from running.
172 # This is a little nasty, but it's the best way to be clean whether or
173 # not the user has an encoding plugin.
175 if ($c->can('encoding')) {
179 my ( $title, $error, $infos );
183 $error = join '', map {
184 '<p><code class="error">'
185 . encode_entities($_)
188 $error ||= 'No output';
189 $error = qq{<pre wrap="">$error</pre>};
190 $title = $name = "$name on Catalyst $Catalyst::VERSION";
191 $name = "<h1>$name</h1>";
193 # Don't show context in the dump
194 $c->req->_clear_context;
195 $c->res->_clear_context;
197 # Don't show body parser in the dump
198 $c->req->_clear_body;
202 for my $dump ( $c->dump_these ) {
203 push @infos, $self->_dump_error_page_element($i, $dump);
206 $infos = join "\n", @infos;
213 (en) Please come back later
214 (fr) SVP veuillez revenir plus tard
215 (de) Bitte versuchen sie es spaeter nocheinmal
216 (at) Konnten's bitt'schoen spaeter nochmal reinschauen
217 (no) Vennligst prov igjen senere
218 (dk) Venligst prov igen senere
219 (pl) Prosze sprobowac pozniej
220 (pt) Por favor volte mais tarde
221 (ru) Попробуйте еще раз позже
222 (ua) Спробуйте ще раз пізніше
227 $c->res->body( <<"" );
228 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
229 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
230 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
232 <meta http-equiv="Content-Language" content="en" />
233 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
234 <title>$title</title>
235 <script type="text/javascript">
237 function toggleDump (dumpElement) {
238 var e = document.getElementById( dumpElement );
239 if (e.style.display == "none") {
240 e.style.display = "";
243 e.style.display = "none";
248 <style type="text/css">
250 font-family: "Bitstream Vera Sans", "Trebuchet MS", Verdana,
251 Tahoma, Arial, helvetica, sans-serif;
253 background-color: #eee;
257 :link, :link:hover, :visited, :visited:hover {
262 background-color: #ccc;
263 border: 1px solid #aaa;
268 background-color: #cce;
269 border: 1px solid #755;
275 background-color: #eee;
276 border: 1px solid #575;
282 background-color: #cce;
283 border: 1px solid #557;
292 div.name h1, div.error p {
300 text-decoration: underline;
306 /* from http://users.tkk.fi/~tkarvine/linux/doc/pre-wrap/pre-wrap-css3-mozilla-opera-ie.html */
307 /* Browser specific (not valid) styles to make preformatted text wrap */
309 white-space: pre-wrap; /* css-3 */
310 white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
311 white-space: -pre-wrap; /* Opera 4-6 */
312 white-space: -o-pre-wrap; /* Opera 7 */
313 word-wrap: break-word; /* Internet Explorer 5.5+ */
319 <div class="error">$error</div>
320 <div class="infos">$infos</div>
321 <div class="name">$name</div>
326 # Trick IE. Old versions of IE would display their own error page instead
327 # of ours if we'd give it less than 512 bytes.
328 $c->res->{body} .= ( ' ' x 512 );
330 $c->res->{body} = Encode::encode("UTF-8", $c->res->{body});
333 $c->res->status(500);
336 =head2 $self->finalize_headers($c)
338 Abstract method, allows engines to write headers to response
342 sub finalize_headers {
343 my ($self, $ctx) = @_;
346 $ctx->response->headers->scan(sub { push @headers, @_ });
348 $self->_set_writer($self->_response_cb->([ $ctx->response->status, \@headers ]));
349 $self->_clear_response_cb;
354 =head2 $self->finalize_read($c)
358 sub finalize_read { }
360 =head2 $self->finalize_uploads($c)
362 Clean up after uploads, deleting temp files.
366 sub finalize_uploads {
367 my ( $self, $c ) = @_;
369 # N.B. This code is theoretically entirely unneeded due to ->cleanup(1)
370 # on the HTTP::Body object.
371 my $request = $c->request;
372 foreach my $key (keys %{ $request->uploads }) {
373 my $upload = $request->uploads->{$key};
374 unlink grep { -e $_ } map { $_->tempname }
375 (ref $upload eq 'ARRAY' ? @{$upload} : ($upload));
380 =head2 $self->prepare_body($c)
382 sets up the L<Catalyst::Request> object body using L<HTTP::Body>
387 my ( $self, $c ) = @_;
389 my $appclass = ref($c) || $c;
390 if ( my $length = $self->read_length ) {
391 my $request = $c->request;
392 unless ( $request->_body ) {
393 my $type = $request->header('Content-Type');
394 $request->_body(HTTP::Body->new( $type, $length ));
395 $request->_body->cleanup(1); # Make extra sure!
396 $request->_body->tmpdir( $appclass->config->{uploadtmp} )
397 if exists $appclass->config->{uploadtmp};
400 # Check for definedness as you could read '0'
401 while ( defined ( my $buffer = $self->read($c) ) ) {
402 $c->prepare_body_chunk($buffer);
405 # paranoia against wrong Content-Length header
406 my $remaining = $length - $self->read_position;
407 if ( $remaining > 0 ) {
408 $self->finalize_read($c);
409 Catalyst::Exception->throw(
410 "Wrong Content-Length value: $length" );
414 # Defined but will cause all body code to be skipped
415 $c->request->_body(0);
419 =head2 $self->prepare_body_chunk($c)
421 Add a chunk to the request body.
425 sub prepare_body_chunk {
426 my ( $self, $c, $chunk ) = @_;
428 $c->request->_body->add($chunk);
431 =head2 $self->prepare_body_parameters($c)
433 Sets up parameters from body.
437 sub prepare_body_parameters {
438 my ( $self, $c ) = @_;
440 return unless $c->request->_body;
442 $c->request->body_parameters( $c->request->_body->param );
445 =head2 $self->prepare_connection($c)
447 Abstract method implemented in engines.
451 sub prepare_connection {
452 my ($self, $ctx) = @_;
454 my $env = $self->env;
455 my $request = $ctx->request;
457 $request->address( $env->{REMOTE_ADDR} );
458 $request->hostname( $env->{REMOTE_HOST} )
459 if exists $env->{REMOTE_HOST};
460 $request->protocol( $env->{SERVER_PROTOCOL} );
461 $request->remote_user( $env->{REMOTE_USER} );
462 $request->method( $env->{REQUEST_METHOD} );
463 $request->secure( $env->{'psgi.url_scheme'} eq 'https' ? 1 : 0 );
468 =head2 $self->prepare_cookies($c)
470 Parse cookies from header. Sets a L<CGI::Simple::Cookie> object.
474 sub prepare_cookies {
475 my ( $self, $c ) = @_;
477 if ( my $header = $c->request->header('Cookie') ) {
478 $c->req->cookies( { CGI::Simple::Cookie->parse($header) } );
482 =head2 $self->prepare_headers($c)
486 sub prepare_headers {
487 my ($self, $ctx) = @_;
489 my $env = $self->env;
490 my $headers = $ctx->request->headers;
492 for my $header (keys %{ $env }) {
493 next unless $header =~ /^(HTTP|CONTENT|COOKIE)/i;
494 (my $field = $header) =~ s/^HTTPS?_//;
496 $headers->header($field => $env->{$header});
500 =head2 $self->prepare_parameters($c)
502 sets up parameters from query and post parameters.
506 sub prepare_parameters {
507 my ( $self, $c ) = @_;
509 my $request = $c->request;
510 my $parameters = $request->parameters;
511 my $body_parameters = $request->body_parameters;
512 my $query_parameters = $request->query_parameters;
513 # We copy, no references
514 foreach my $name (keys %$query_parameters) {
515 my $param = $query_parameters->{$name};
516 $parameters->{$name} = ref $param eq 'ARRAY' ? [ @$param ] : $param;
519 # Merge query and body parameters
520 foreach my $name (keys %$body_parameters) {
521 my $param = $body_parameters->{$name};
522 my @values = ref $param eq 'ARRAY' ? @$param : ($param);
523 if ( my $existing = $parameters->{$name} ) {
524 unshift(@values, (ref $existing eq 'ARRAY' ? @$existing : $existing));
526 $parameters->{$name} = @values > 1 ? \@values : $values[0];
530 =head2 $self->prepare_path($c)
532 abstract method, implemented by engines.
537 my ($self, $ctx) = @_;
539 my $env = $self->env;
541 my $scheme = $ctx->request->secure ? 'https' : 'http';
542 my $host = $env->{HTTP_HOST} || $env->{SERVER_NAME};
543 my $port = $env->{SERVER_PORT} || 80;
544 my $base_path = $env->{SCRIPT_NAME} || "/";
546 # set the request URI
548 if (!$ctx->config->{use_request_uri_for_path}) {
549 my $path_info = $env->{PATH_INFO};
550 if ( exists $env->{REDIRECT_URL} ) {
551 $base_path = $env->{REDIRECT_URL};
552 $base_path =~ s/\Q$path_info\E$//;
554 $path = $base_path . $path_info;
556 $path =~ s/([^$URI::uric])/$URI::Escape::escapes{$1}/go;
557 $path =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
560 my $req_uri = $env->{REQUEST_URI};
561 $req_uri =~ s/\?.*$//;
566 # Using URI directly is way too slow, so we construct the URLs manually
567 my $uri_class = "URI::$scheme";
569 # HTTP_HOST will include the port even if it's 80/443
570 $host =~ s/:(?:80|443)$//;
572 if ($port !~ /^(?:80|443)$/ && $host !~ /:/) {
576 my $query = $env->{QUERY_STRING} ? '?' . $env->{QUERY_STRING} : '';
577 my $uri = $scheme . '://' . $host . '/' . $path . $query;
579 $ctx->request->uri( (bless \$uri, $uri_class)->canonical );
582 # base must end in a slash
583 $base_path .= '/' unless $base_path =~ m{/$};
585 my $base_uri = $scheme . '://' . $host . $base_path;
587 $ctx->request->base( bless \$base_uri, $uri_class );
592 =head2 $self->prepare_request($c)
594 =head2 $self->prepare_query_parameters($c)
596 process the query string and extract query parameters.
600 sub prepare_query_parameters {
603 my $query_string = exists $self->env->{QUERY_STRING}
604 ? $self->env->{QUERY_STRING}
607 # Check for keywords (no = signs)
608 # (yes, index() is faster than a regex :))
609 if ( index( $query_string, '=' ) < 0 ) {
610 $c->request->query_keywords( $self->unescape_uri($query_string) );
616 # replace semi-colons
617 $query_string =~ s/;/&/g;
619 my @params = grep { length $_ } split /&/, $query_string;
621 for my $item ( @params ) {
624 = map { $self->unescape_uri($_) }
625 split( /=/, $item, 2 );
627 $param = $self->unescape_uri($item) unless defined $param;
629 if ( exists $query{$param} ) {
630 if ( ref $query{$param} ) {
631 push @{ $query{$param} }, $value;
634 $query{$param} = [ $query{$param}, $value ];
638 $query{$param} = $value;
642 $c->request->query_parameters( \%query );
645 =head2 $self->prepare_read($c)
647 prepare to read from the engine.
652 my ( $self, $c ) = @_;
654 # Initialize the read position
655 $self->read_position(0);
657 # Initialize the amount of data we think we need to read
658 $self->read_length( $c->request->header('Content-Length') || 0 );
661 =head2 $self->prepare_request(@arguments)
663 Populate the context object from the request object.
667 sub prepare_request {
668 my ($self, $ctx, %args) = @_;
669 $self->_set_env($args{env});
672 =head2 $self->prepare_uploads($c)
676 sub prepare_uploads {
677 my ( $self, $c ) = @_;
679 my $request = $c->request;
680 return unless $request->_body;
682 my $uploads = $request->_body->upload;
683 my $parameters = $request->parameters;
684 foreach my $name (keys %$uploads) {
685 my $files = $uploads->{$name};
687 for my $upload (ref $files eq 'ARRAY' ? @$files : ($files)) {
688 my $headers = HTTP::Headers->new( %{ $upload->{headers} } );
689 my $u = Catalyst::Request::Upload->new
691 size => $upload->{size},
692 type => scalar $headers->content_type,
694 tempname => $upload->{tempname},
695 filename => $upload->{filename},
699 $request->uploads->{$name} = @uploads > 1 ? \@uploads : $uploads[0];
701 # support access to the filename as a normal param
702 my @filenames = map { $_->{filename} } @uploads;
703 # append, if there's already params with this name
704 if (exists $parameters->{$name}) {
705 if (ref $parameters->{$name} eq 'ARRAY') {
706 push @{ $parameters->{$name} }, @filenames;
709 $parameters->{$name} = [ $parameters->{$name}, @filenames ];
713 $parameters->{$name} = @filenames > 1 ? \@filenames : $filenames[0];
718 =head2 $self->prepare_write($c)
720 Abstract method. Implemented by the engines.
724 sub prepare_write { }
726 =head2 $self->read($c, [$maxlength])
728 Reads from the input stream by calling C<< $self->read_chunk >>.
730 Maintains the read_length and read_position counters as data is read.
735 my ( $self, $c, $maxlength ) = @_;
737 my $remaining = $self->read_length - $self->read_position;
738 $maxlength ||= $CHUNKSIZE;
740 # Are we done reading?
741 if ( $remaining <= 0 ) {
742 $self->finalize_read($c);
746 my $readlen = ( $remaining > $maxlength ) ? $maxlength : $remaining;
747 my $rc = $self->read_chunk( $c, my $buffer, $readlen );
749 if (0 == $rc) { # Nothing more to read even though Content-Length
750 # said there should be.
751 $self->finalize_read;
754 $self->read_position( $self->read_position + $rc );
758 Catalyst::Exception->throw(
759 message => "Unknown error reading input: $!" );
763 =head2 $self->read_chunk($c, $buffer, $length)
765 Each engine implements read_chunk as its preferred way of reading a chunk
766 of data. Returns the number of bytes read. A return of 0 indicates that
767 there is no more data to be read.
772 my ($self, $ctx) = (shift, shift);
773 return $self->env->{'psgi.input'}->read(@_);
776 =head2 $self->read_length
778 The length of input data to be read. This is obtained from the Content-Length
781 =head2 $self->read_position
783 The amount of input data that has already been read.
785 =head2 $self->run($app, $server)
787 Start the engine. Builds a PSGI application and calls the
788 run method on the server passed in, which then causes the
789 engine to loop, handling requests..
794 my ($self, $app, $psgi, @args) = @_;
795 # @args left here rather than just a $options, $server for back compat with the
796 # old style scripts which send a few args, then a hashref
798 # They should never actually be used in the normal case as the Plack engine is
799 # passed in got all the 'standard' args via the loader in the script already.
801 # FIXME - we should stash the options in an attribute so that custom args
802 # like Gitalist's --git_dir are possible to get from the app without stupid tricks.
803 my $server = pop @args if (scalar @args && blessed $args[-1]);
804 my $options = pop @args if (scalar @args && ref($args[-1]) eq 'HASH');
805 # Back compat hack for applications with old (non Catalyst::Script) scripts to work in FCGI.
806 if (scalar @args && !ref($args[0])) {
807 if (my $listen = shift @args) {
808 $options->{listen} ||= [$listen];
812 $server = Catalyst::EngineLoader->new(application_name => ref($self))->auto(%$options);
813 # We're not being called from a script, so auto detect what backend to
814 # run on. This should never happen, as mod_perl never calls ->run,
815 # instead the $app->handle method is called per request.
816 $app->log->warn("Not supplied a Plack engine, falling back to engine auto-loader (are your scripts ancient?)")
818 $server->run($psgi, $options);
821 =head2 build_psgi_app ($app, @args)
823 Builds and returns a PSGI application closure, wrapping it in the reverse proxy
824 middleware if the using_frontend_proxy config setting is set.
829 my ($self, $app, @args) = @_;
836 $self->_set_response_cb($respond);
837 $app->handle_request(env => $env);
842 =head2 $self->write($c, $buffer)
844 Writes the buffer to the client.
849 my ( $self, $c, $buffer ) = @_;
851 unless ( $self->_prepared_write ) {
852 $self->prepare_write($c);
853 $self->_prepared_write(1);
856 $buffer = q[] unless defined $buffer;
858 my $len = length($buffer);
859 $self->_writer->write($buffer);
864 =head2 $self->unescape_uri($uri)
866 Unescapes a given URI using the most efficient method available. Engines such
867 as Apache may implement this using Apache's C-based modules, for example.
872 my ( $self, $str ) = @_;
874 $str =~ s/(?:%([0-9A-Fa-f]{2})|\+)/defined $1 ? chr(hex($1)) : ' '/eg;
879 =head2 $self->finalize_output
881 <obsolete>, see finalize_body
885 Hash containing environment variables including many special variables inserted
886 by WWW server - like SERVER_*, REMOTE_*, HTTP_* ...
888 Before accessing environment variables consider whether the same information is
889 not directly available via Catalyst objects $c->request, $c->engine ...
891 BEWARE: If you really need to access some environment variable from your Catalyst
892 application you should use $c->engine->env->{VARNAME} instead of $ENV{VARNAME},
893 as in some environments the %ENV hash does not contain what you would expect.
897 Catalyst Contributors, see Catalyst.pm
901 This library is free software. You can redistribute it and/or modify it under
902 the same terms as Perl itself.