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 Plack::Middleware::Conditional;
16 use Plack::Middleware::ReverseProxy;
18 use namespace::clean -except => 'meta';
20 has env => (is => 'ro', writer => '_set_env', clearer => '_clear_env');
22 # input position and length
23 has read_length => (is => 'rw');
24 has read_position => (is => 'rw');
26 has _prepared_write => (is => 'rw');
31 writer => '_set_response_cb',
32 clearer => '_clear_response_cb',
37 isa => duck_type([qw(write close)]),
38 writer => '_set_writer',
39 clearer => '_clear_writer',
42 # Amount of data to read from input on each pass
43 our $CHUNKSIZE = 64 * 1024;
47 Catalyst::Engine - The Catalyst Engine
58 =head2 $self->finalize_body($c)
60 Finalize body. Prints the response output.
65 my ( $self, $c ) = @_;
66 my $body = $c->response->body;
67 no warnings 'uninitialized';
68 if ( blessed($body) && $body->can('read') or ref($body) eq 'GLOB' ) {
71 $got = read $body, my ($buffer), $CHUNKSIZE;
72 $got = 0 unless $self->write( $c, $buffer );
78 $self->write( $c, $body );
81 $self->_writer->close;
88 =head2 $self->finalize_cookies($c)
90 Create CGI::Simple::Cookie objects from $c->res->cookies, and set them as
95 sub finalize_cookies {
96 my ( $self, $c ) = @_;
99 my $response = $c->response;
101 foreach my $name (keys %{ $response->cookies }) {
103 my $val = $response->cookies->{$name};
108 : CGI::Simple::Cookie->new(
110 -value => $val->{value},
111 -expires => $val->{expires},
112 -domain => $val->{domain},
113 -path => $val->{path},
114 -secure => $val->{secure} || 0,
115 -httponly => $val->{httponly} || 0,
119 push @cookies, $cookie->as_string;
122 for my $cookie (@cookies) {
123 $response->headers->push_header( 'Set-Cookie' => $cookie );
127 =head2 $self->finalize_error($c)
129 Output an appropriate error message. Called if there's an error in $c
130 after the dispatch has finished. Will output debug messages if Catalyst
131 is in debug mode, or a `please come back later` message otherwise.
135 sub _dump_error_page_element {
136 my ($self, $i, $element) = @_;
137 my ($name, $val) = @{ $element };
139 # This is fugly, but the metaclass is _HUGE_ and demands waaay too much
140 # scrolling. Suggestions for more pleasant ways to do this welcome.
141 local $val->{'__MOP__'} = "Stringified: "
142 . $val->{'__MOP__'} if ref $val eq 'HASH' && exists $val->{'__MOP__'};
144 my $text = encode_entities( dump( $val ));
145 sprintf <<"EOF", $name, $text;
146 <h2><a href="#" onclick="toggleDump('dump_$i'); return false">%s</a></h2>
148 <pre wrap="">%s</pre>
154 my ( $self, $c ) = @_;
156 $c->res->content_type('text/html; charset=utf-8');
157 my $name = ref($c)->config->{name} || join(' ', split('::', ref $c));
159 my ( $title, $error, $infos );
163 $error = join '', map {
164 '<p><code class="error">'
165 . encode_entities($_)
168 $error ||= 'No output';
169 $error = qq{<pre wrap="">$error</pre>};
170 $title = $name = "$name on Catalyst $Catalyst::VERSION";
171 $name = "<h1>$name</h1>";
173 # Don't show context in the dump
174 $c->req->_clear_context;
175 $c->res->_clear_context;
177 # Don't show body parser in the dump
178 $c->req->_clear_body;
182 for my $dump ( $c->dump_these ) {
183 push @infos, $self->_dump_error_page_element($i, $dump);
186 $infos = join "\n", @infos;
193 (en) Please come back later
194 (fr) SVP veuillez revenir plus tard
195 (de) Bitte versuchen sie es spaeter nocheinmal
196 (at) Konnten's bitt'schoen spaeter nochmal reinschauen
197 (no) Vennligst prov igjen senere
198 (dk) Venligst prov igen senere
199 (pl) Prosze sprobowac pozniej
200 (pt) Por favor volte mais tarde
201 (ru) Попробуйте еще раз позже
202 (ua) Спробуйте ще раз пізніше
207 $c->res->body( <<"" );
208 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
209 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
210 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
212 <meta http-equiv="Content-Language" content="en" />
213 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
214 <title>$title</title>
215 <script type="text/javascript">
217 function toggleDump (dumpElement) {
218 var e = document.getElementById( dumpElement );
219 if (e.style.display == "none") {
220 e.style.display = "";
223 e.style.display = "none";
228 <style type="text/css">
230 font-family: "Bitstream Vera Sans", "Trebuchet MS", Verdana,
231 Tahoma, Arial, helvetica, sans-serif;
233 background-color: #eee;
237 :link, :link:hover, :visited, :visited:hover {
242 background-color: #ccc;
243 border: 1px solid #aaa;
248 background-color: #cce;
249 border: 1px solid #755;
255 background-color: #eee;
256 border: 1px solid #575;
262 background-color: #cce;
263 border: 1px solid #557;
272 div.name h1, div.error p {
280 text-decoration: underline;
286 /* from http://users.tkk.fi/~tkarvine/linux/doc/pre-wrap/pre-wrap-css3-mozilla-opera-ie.html */
287 /* Browser specific (not valid) styles to make preformatted text wrap */
289 white-space: pre-wrap; /* css-3 */
290 white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
291 white-space: -pre-wrap; /* Opera 4-6 */
292 white-space: -o-pre-wrap; /* Opera 7 */
293 word-wrap: break-word; /* Internet Explorer 5.5+ */
299 <div class="error">$error</div>
300 <div class="infos">$infos</div>
301 <div class="name">$name</div>
307 # Trick IE. Old versions of IE would display their own error page instead
308 # of ours if we'd give it less than 512 bytes.
309 $c->res->{body} .= ( ' ' x 512 );
312 $c->res->status(500);
315 =head2 $self->finalize_headers($c)
317 Abstract method, allows engines to write headers to response
321 sub finalize_headers {
322 my ($self, $ctx) = @_;
325 $ctx->response->headers->scan(sub { push @headers, @_ });
327 $self->_set_writer($self->_response_cb->([ $ctx->response->status, \@headers ]));
328 $self->_clear_response_cb;
333 =head2 $self->finalize_read($c)
337 sub finalize_read { }
339 =head2 $self->finalize_uploads($c)
341 Clean up after uploads, deleting temp files.
345 sub finalize_uploads {
346 my ( $self, $c ) = @_;
348 my $request = $c->request;
349 foreach my $key (keys %{ $request->uploads }) {
350 my $upload = $request->uploads->{$key};
351 unlink grep { -e $_ } map { $_->tempname }
352 (ref $upload eq 'ARRAY' ? @{$upload} : ($upload));
357 =head2 $self->prepare_body($c)
359 sets up the L<Catalyst::Request> object body using L<HTTP::Body>
364 my ( $self, $c ) = @_;
366 my $appclass = ref($c) || $c;
367 if ( my $length = $self->read_length ) {
368 my $request = $c->request;
369 unless ( $request->_body ) {
370 my $type = $request->header('Content-Type');
371 $request->_body(HTTP::Body->new( $type, $length ));
372 $request->_body->tmpdir( $appclass->config->{uploadtmp} )
373 if exists $appclass->config->{uploadtmp};
376 # Check for definedness as you could read '0'
377 while ( defined ( my $buffer = $self->read($c) ) ) {
378 $c->prepare_body_chunk($buffer);
381 # paranoia against wrong Content-Length header
382 my $remaining = $length - $self->read_position;
383 if ( $remaining > 0 ) {
384 $self->finalize_read($c);
385 Catalyst::Exception->throw(
386 "Wrong Content-Length value: $length" );
390 # Defined but will cause all body code to be skipped
391 $c->request->_body(0);
395 =head2 $self->prepare_body_chunk($c)
397 Add a chunk to the request body.
401 sub prepare_body_chunk {
402 my ( $self, $c, $chunk ) = @_;
404 $c->request->_body->add($chunk);
407 =head2 $self->prepare_body_parameters($c)
409 Sets up parameters from body.
413 sub prepare_body_parameters {
414 my ( $self, $c ) = @_;
416 return unless $c->request->_body;
418 $c->request->body_parameters( $c->request->_body->param );
421 =head2 $self->prepare_connection($c)
423 Abstract method implemented in engines.
427 sub prepare_connection {
428 my ($self, $ctx) = @_;
430 my $env = $self->env;
431 my $request = $ctx->request;
433 $request->address( $env->{REMOTE_ADDR} );
434 $request->hostname( $env->{REMOTE_HOST} )
435 if exists $env->{REMOTE_HOST};
436 $request->protocol( $env->{SERVER_PROTOCOL} );
437 $request->remote_user( $env->{REMOTE_USER} );
438 $request->method( $env->{REQUEST_METHOD} );
439 $request->secure( $env->{'psgi.url_scheme'} eq 'https' ? 1 : 0 );
444 =head2 $self->prepare_cookies($c)
446 Parse cookies from header. Sets a L<CGI::Simple::Cookie> object.
450 sub prepare_cookies {
451 my ( $self, $c ) = @_;
453 if ( my $header = $c->request->header('Cookie') ) {
454 $c->req->cookies( { CGI::Simple::Cookie->parse($header) } );
458 =head2 $self->prepare_headers($c)
462 sub prepare_headers {
463 my ($self, $ctx) = @_;
465 my $env = $self->env;
466 my $headers = $ctx->request->headers;
468 for my $header (keys %{ $env }) {
469 next unless $header =~ /^(HTTP|CONTENT|COOKIE)/i;
470 (my $field = $header) =~ s/^HTTPS?_//;
472 $headers->header($field => $env->{$header});
476 =head2 $self->prepare_parameters($c)
478 sets up parameters from query and post parameters.
482 sub prepare_parameters {
483 my ( $self, $c ) = @_;
485 my $request = $c->request;
486 my $parameters = $request->parameters;
487 my $body_parameters = $request->body_parameters;
488 my $query_parameters = $request->query_parameters;
489 # We copy, no references
490 foreach my $name (keys %$query_parameters) {
491 my $param = $query_parameters->{$name};
492 $parameters->{$name} = ref $param eq 'ARRAY' ? [ @$param ] : $param;
495 # Merge query and body parameters
496 foreach my $name (keys %$body_parameters) {
497 my $param = $body_parameters->{$name};
498 my @values = ref $param eq 'ARRAY' ? @$param : ($param);
499 if ( my $existing = $parameters->{$name} ) {
500 unshift(@values, (ref $existing eq 'ARRAY' ? @$existing : $existing));
502 $parameters->{$name} = @values > 1 ? \@values : $values[0];
506 =head2 $self->prepare_path($c)
508 abstract method, implemented by engines.
513 my ($self, $ctx) = @_;
515 my $env = $self->env;
517 my $scheme = $ctx->request->secure ? 'https' : 'http';
518 my $host = $env->{HTTP_HOST} || $env->{SERVER_NAME};
519 my $port = $env->{SERVER_PORT} || 80;
520 my $base_path = $env->{SCRIPT_NAME} || "/";
522 # set the request URI
523 my $req_uri = $env->{REQUEST_URI};
524 $req_uri =~ s/\?.*$//;
528 # Using URI directly is way too slow, so we construct the URLs manually
529 my $uri_class = "URI::$scheme";
531 # HTTP_HOST will include the port even if it's 80/443
532 $host =~ s/:(?:80|443)$//;
534 if ($port !~ /^(?:80|443)$/ && $host !~ /:/) {
538 my $query = $env->{QUERY_STRING} ? '?' . $env->{QUERY_STRING} : '';
539 my $uri = $scheme . '://' . $host . '/' . $path . $query;
541 $ctx->request->uri( (bless \$uri, $uri_class)->canonical );
544 # base must end in a slash
545 $base_path .= '/' unless $base_path =~ m{/$};
547 my $base_uri = $scheme . '://' . $host . $base_path;
549 $ctx->request->base( bless \$base_uri, $uri_class );
554 =head2 $self->prepare_request($c)
556 =head2 $self->prepare_query_parameters($c)
558 process the query string and extract query parameters.
562 sub prepare_query_parameters {
565 my $query_string = exists $self->env->{QUERY_STRING}
566 ? $self->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;
604 $c->request->query_parameters( \%query );
607 =head2 $self->prepare_read($c)
609 prepare to read from the engine.
614 my ( $self, $c ) = @_;
616 # Initialize the read position
617 $self->read_position(0);
619 # Initialize the amount of data we think we need to read
620 $self->read_length( $c->request->header('Content-Length') || 0 );
623 =head2 $self->prepare_request(@arguments)
625 Populate the context object from the request object.
629 sub prepare_request {
630 my ($self, $ctx, %args) = @_;
631 $self->_set_env($args{env});
634 =head2 $self->prepare_uploads($c)
638 sub prepare_uploads {
639 my ( $self, $c ) = @_;
641 my $request = $c->request;
642 return unless $request->_body;
644 my $uploads = $request->_body->upload;
645 my $parameters = $request->parameters;
646 foreach my $name (keys %$uploads) {
647 my $files = $uploads->{$name};
649 for my $upload (ref $files eq 'ARRAY' ? @$files : ($files)) {
650 my $headers = HTTP::Headers->new( %{ $upload->{headers} } );
651 my $u = Catalyst::Request::Upload->new
653 size => $upload->{size},
654 type => $headers->content_type,
656 tempname => $upload->{tempname},
657 filename => $upload->{filename},
661 $request->uploads->{$name} = @uploads > 1 ? \@uploads : $uploads[0];
663 # support access to the filename as a normal param
664 my @filenames = map { $_->{filename} } @uploads;
665 # append, if there's already params with this name
666 if (exists $parameters->{$name}) {
667 if (ref $parameters->{$name} eq 'ARRAY') {
668 push @{ $parameters->{$name} }, @filenames;
671 $parameters->{$name} = [ $parameters->{$name}, @filenames ];
675 $parameters->{$name} = @filenames > 1 ? \@filenames : $filenames[0];
680 =head2 $self->prepare_write($c)
682 Abstract method. Implemented by the engines.
686 sub prepare_write { }
688 =head2 $self->read($c, [$maxlength])
690 Reads from the input stream by calling C<< $self->read_chunk >>.
692 Maintains the read_length and read_position counters as data is read.
697 my ( $self, $c, $maxlength ) = @_;
699 my $remaining = $self->read_length - $self->read_position;
700 $maxlength ||= $CHUNKSIZE;
702 # Are we done reading?
703 if ( $remaining <= 0 ) {
704 $self->finalize_read($c);
708 my $readlen = ( $remaining > $maxlength ) ? $maxlength : $remaining;
709 my $rc = $self->read_chunk( $c, my $buffer, $readlen );
711 if (0 == $rc) { # Nothing more to read even though Content-Length
712 # said there should be.
713 $self->finalize_read;
716 $self->read_position( $self->read_position + $rc );
720 Catalyst::Exception->throw(
721 message => "Unknown error reading input: $!" );
725 =head2 $self->read_chunk($c, $buffer, $length)
727 Each engine implements read_chunk as its preferred way of reading a chunk
728 of data. Returns the number of bytes read. A return of 0 indicates that
729 there is no more data to be read.
734 my ($self, $ctx) = (shift, shift);
735 return $self->env->{'psgi.input'}->read(@_);
738 =head2 $self->read_length
740 The length of input data to be read. This is obtained from the Content-Length
743 =head2 $self->read_position
745 The amount of input data that has already been read.
747 =head2 $self->run($app, $server)
749 Start the engine. Builds a PSGI application and calls the
750 run method on the server passed in..
755 my ($self, $app, @args) = @_;
756 my $server = pop @args if blessed $args[-1];
757 $server ||= Plack::Loader->auto(); # We're not being called from a script,
758 # so auto detect what backend to run on.
759 # This does *NOT* cover mod_perl.
760 # FIXME - Do something sensible with the options we're passed
761 my $psgi = $self->build_psgi_app($app, @args);
765 =head2 build_psgi_app ($app, @args)
767 Builds and returns a PSGI application closure, wrapping it in the reverse proxy
768 middleware if the using_frontend_proxy config setting is set.
773 my ($self, $app, @args) = @_;
780 $self->_set_response_cb($respond);
781 $app->handle_request(env => $env);
785 $psgi_app = Plack::Middleware::Conditional->wrap(
789 return if $app->config->{ignore_frontend_proxy};
790 return $env->{REMOTE_ADDR} eq '127.0.0.1' || $app->config->{using_frontend_proxy};
792 builder => sub { Plack::Middleware::ReverseProxy->wrap($_[0]) },
798 =head2 $self->write($c, $buffer)
800 Writes the buffer to the client.
805 my ( $self, $c, $buffer ) = @_;
807 unless ( $self->_prepared_write ) {
808 $self->prepare_write($c);
809 $self->_prepared_write(1);
812 return 0 if !defined $buffer;
814 my $len = length($buffer);
815 $self->_writer->write($buffer);
820 =head2 $self->unescape_uri($uri)
822 Unescapes a given URI using the most efficient method available. Engines such
823 as Apache may implement this using Apache's C-based modules, for example.
828 my ( $self, $str ) = @_;
830 $str =~ s/(?:%([0-9A-Fa-f]{2})|\+)/defined $1 ? chr(hex($1)) : ' '/eg;
835 =head2 $self->finalize_output
837 <obsolete>, see finalize_body
841 Hash containing enviroment variables including many special variables inserted
842 by WWW server - like SERVER_*, REMOTE_*, HTTP_* ...
844 Before accesing enviroment variables consider whether the same information is
845 not directly available via Catalyst objects $c->request, $c->engine ...
847 BEWARE: If you really need to access some enviroment variable from your Catalyst
848 application you should use $c->engine->env->{VARNAME} instead of $ENV{VARNAME},
849 as in some enviroments the %ENV hash does not contain what you would expect.
853 Catalyst Contributors, see Catalyst.pm
857 This library is free software. You can redistribute it and/or modify it under
858 the same terms as Perl itself.