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 namespace::clean -except => 'meta';
17 has env => (is => 'ro', writer => '_set_env', clearer => '_clear_env');
19 # input position and length
20 has read_length => (is => 'rw');
21 has read_position => (is => 'rw');
23 has _prepared_write => (is => 'rw');
28 writer => '_set_response_cb',
33 isa => duck_type([qw(write close)]),
34 writer => '_set_writer',
37 # Amount of data to read from input on each pass
38 our $CHUNKSIZE = 64 * 1024;
42 Catalyst::Engine - The Catalyst Engine
53 =head2 $self->finalize_body($c)
55 Finalize body. Prints the response output.
60 my ( $self, $c ) = @_;
61 my $body = $c->response->body;
62 no warnings 'uninitialized';
63 if ( blessed($body) && $body->can('read') or ref($body) eq 'GLOB' ) {
66 $got = read $body, my ($buffer), $CHUNKSIZE;
67 $got = 0 unless $self->write( $c, $buffer );
73 $self->write( $c, $body );
76 $self->_writer->close;
81 =head2 $self->finalize_cookies($c)
83 Create CGI::Simple::Cookie objects from $c->res->cookies, and set them as
88 sub finalize_cookies {
89 my ( $self, $c ) = @_;
92 my $response = $c->response;
94 foreach my $name (keys %{ $response->cookies }) {
96 my $val = $response->cookies->{$name};
101 : CGI::Simple::Cookie->new(
103 -value => $val->{value},
104 -expires => $val->{expires},
105 -domain => $val->{domain},
106 -path => $val->{path},
107 -secure => $val->{secure} || 0,
108 -httponly => $val->{httponly} || 0,
112 push @cookies, $cookie->as_string;
115 for my $cookie (@cookies) {
116 $response->headers->push_header( 'Set-Cookie' => $cookie );
120 =head2 $self->finalize_error($c)
122 Output an appropriate error message. Called if there's an error in $c
123 after the dispatch has finished. Will output debug messages if Catalyst
124 is in debug mode, or a `please come back later` message otherwise.
128 sub _dump_error_page_element {
129 my ($self, $i, $element) = @_;
130 my ($name, $val) = @{ $element };
132 # This is fugly, but the metaclass is _HUGE_ and demands waaay too much
133 # scrolling. Suggestions for more pleasant ways to do this welcome.
134 local $val->{'__MOP__'} = "Stringified: "
135 . $val->{'__MOP__'} if ref $val eq 'HASH' && exists $val->{'__MOP__'};
137 my $text = encode_entities( dump( $val ));
138 sprintf <<"EOF", $name, $text;
139 <h2><a href="#" onclick="toggleDump('dump_$i'); return false">%s</a></h2>
141 <pre wrap="">%s</pre>
147 my ( $self, $c ) = @_;
149 $c->res->content_type('text/html; charset=utf-8');
150 my $name = ref($c)->config->{name} || join(' ', split('::', ref $c));
152 my ( $title, $error, $infos );
156 $error = join '', map {
157 '<p><code class="error">'
158 . encode_entities($_)
161 $error ||= 'No output';
162 $error = qq{<pre wrap="">$error</pre>};
163 $title = $name = "$name on Catalyst $Catalyst::VERSION";
164 $name = "<h1>$name</h1>";
166 # Don't show context in the dump
167 $c->req->_clear_context;
168 $c->res->_clear_context;
170 # Don't show body parser in the dump
171 $c->req->_clear_body;
175 for my $dump ( $c->dump_these ) {
176 push @infos, $self->_dump_error_page_element($i, $dump);
179 $infos = join "\n", @infos;
186 (en) Please come back later
187 (fr) SVP veuillez revenir plus tard
188 (de) Bitte versuchen sie es spaeter nocheinmal
189 (at) Konnten's bitt'schoen spaeter nochmal reinschauen
190 (no) Vennligst prov igjen senere
191 (dk) Venligst prov igen senere
192 (pl) Prosze sprobowac pozniej
193 (pt) Por favor volte mais tarde
194 (ru) Попробуйте еще раз позже
195 (ua) Спробуйте ще раз пізніше
200 $c->res->body( <<"" );
201 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
202 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
203 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
205 <meta http-equiv="Content-Language" content="en" />
206 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
207 <title>$title</title>
208 <script type="text/javascript">
210 function toggleDump (dumpElement) {
211 var e = document.getElementById( dumpElement );
212 if (e.style.display == "none") {
213 e.style.display = "";
216 e.style.display = "none";
221 <style type="text/css">
223 font-family: "Bitstream Vera Sans", "Trebuchet MS", Verdana,
224 Tahoma, Arial, helvetica, sans-serif;
226 background-color: #eee;
230 :link, :link:hover, :visited, :visited:hover {
235 background-color: #ccc;
236 border: 1px solid #aaa;
241 background-color: #cce;
242 border: 1px solid #755;
248 background-color: #eee;
249 border: 1px solid #575;
255 background-color: #cce;
256 border: 1px solid #557;
265 div.name h1, div.error p {
273 text-decoration: underline;
279 /* from http://users.tkk.fi/~tkarvine/linux/doc/pre-wrap/pre-wrap-css3-mozilla-opera-ie.html */
280 /* Browser specific (not valid) styles to make preformatted text wrap */
282 white-space: pre-wrap; /* css-3 */
283 white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
284 white-space: -pre-wrap; /* Opera 4-6 */
285 white-space: -o-pre-wrap; /* Opera 7 */
286 word-wrap: break-word; /* Internet Explorer 5.5+ */
292 <div class="error">$error</div>
293 <div class="infos">$infos</div>
294 <div class="name">$name</div>
301 $c->res->{body} .= ( ' ' x 512 );
304 $c->res->status(500);
307 =head2 $self->finalize_headers($c)
309 Abstract method, allows engines to write headers to response
313 sub finalize_headers {
314 my ($self, $ctx) = @_;
317 $ctx->response->headers->scan(sub { push @headers, @_ });
319 $self->_set_writer($self->_response_cb->([ $ctx->response->status, \@headers ]));
324 =head2 $self->finalize_read($c)
328 sub finalize_read { }
330 =head2 $self->finalize_uploads($c)
332 Clean up after uploads, deleting temp files.
336 sub finalize_uploads {
337 my ( $self, $c ) = @_;
339 my $request = $c->request;
340 foreach my $key (keys %{ $request->uploads }) {
341 my $upload = $request->uploads->{$key};
342 unlink grep { -e $_ } map { $_->tempname }
343 (ref $upload eq 'ARRAY' ? @{$upload} : ($upload));
348 =head2 $self->prepare_body($c)
350 sets up the L<Catalyst::Request> object body using L<HTTP::Body>
355 my ( $self, $c ) = @_;
357 my $appclass = ref($c) || $c;
358 if ( my $length = $self->read_length ) {
359 my $request = $c->request;
360 unless ( $request->_body ) {
361 my $type = $request->header('Content-Type');
362 $request->_body(HTTP::Body->new( $type, $length ));
363 $request->_body->tmpdir( $appclass->config->{uploadtmp} )
364 if exists $appclass->config->{uploadtmp};
367 # Check for definedness as you could read '0'
368 while ( defined ( my $buffer = $self->read($c) ) ) {
369 $c->prepare_body_chunk($buffer);
372 # paranoia against wrong Content-Length header
373 my $remaining = $length - $self->read_position;
374 if ( $remaining > 0 ) {
375 $self->finalize_read($c);
376 Catalyst::Exception->throw(
377 "Wrong Content-Length value: $length" );
381 # Defined but will cause all body code to be skipped
382 $c->request->_body(0);
386 =head2 $self->prepare_body_chunk($c)
388 Add a chunk to the request body.
392 sub prepare_body_chunk {
393 my ( $self, $c, $chunk ) = @_;
395 $c->request->_body->add($chunk);
398 =head2 $self->prepare_body_parameters($c)
400 Sets up parameters from body.
404 sub prepare_body_parameters {
405 my ( $self, $c ) = @_;
407 return unless $c->request->_body;
409 $c->request->body_parameters( $c->request->_body->param );
412 =head2 $self->prepare_connection($c)
414 Abstract method implemented in engines.
418 sub prepare_connection {
419 my ($self, $ctx) = @_;
421 my $env = $self->env;
422 my $request = $ctx->request;
424 $request->address( $env->{REMOTE_ADDR} );
425 $request->hostname( $env->{REMOTE_HOST} )
426 if exists $env->{REMOTE_HOST};
427 $request->protocol( $env->{SERVER_PROTOCOL} );
428 $request->remote_user( $env->{REMOTE_USER} );
429 $request->method( $env->{REQUEST_METHOD} );
430 $request->secure( $env->{'psgi.url_scheme'} eq 'https' );
435 =head2 $self->prepare_cookies($c)
437 Parse cookies from header. Sets a L<CGI::Simple::Cookie> object.
441 sub prepare_cookies {
442 my ( $self, $c ) = @_;
444 if ( my $header = $c->request->header('Cookie') ) {
445 $c->req->cookies( { CGI::Simple::Cookie->parse($header) } );
449 =head2 $self->prepare_headers($c)
453 sub prepare_headers {
454 my ($self, $ctx) = @_;
456 my $env = $self->env;
457 my $headers = $ctx->request->headers;
459 for my $header (keys %{ $env }) {
460 next unless $header =~ /^(HTTP|CONTENT|COOKIE)/i;
461 (my $field = $header) =~ s/^HTTPS?_//;
463 $headers->header($field => $env->{$header});
467 =head2 $self->prepare_parameters($c)
469 sets up parameters from query and post parameters.
473 sub prepare_parameters {
474 my ( $self, $c ) = @_;
476 my $request = $c->request;
477 my $parameters = $request->parameters;
478 my $body_parameters = $request->body_parameters;
479 my $query_parameters = $request->query_parameters;
480 # We copy, no references
481 foreach my $name (keys %$query_parameters) {
482 my $param = $query_parameters->{$name};
483 $parameters->{$name} = ref $param eq 'ARRAY' ? [ @$param ] : $param;
486 # Merge query and body parameters
487 foreach my $name (keys %$body_parameters) {
488 my $param = $body_parameters->{$name};
489 my @values = ref $param eq 'ARRAY' ? @$param : ($param);
490 if ( my $existing = $parameters->{$name} ) {
491 unshift(@values, (ref $existing eq 'ARRAY' ? @$existing : $existing));
493 $parameters->{$name} = @values > 1 ? \@values : $values[0];
497 =head2 $self->prepare_path($c)
499 abstract method, implemented by engines.
504 my ($self, $ctx) = @_;
506 my $env = $self->env;
508 my $scheme = $ctx->request->secure ? 'https' : 'http';
509 my $host = $env->{HTTP_HOST} || $env->{SERVER_NAME};
510 my $port = $env->{SERVER_PORT} || 80;
511 my $base_path = $env->{SCRIPT_NAME} || "/";
513 # set the request URI
514 my $req_uri = $env->{REQUEST_URI};
515 $req_uri =~ s/\?.*$//;
516 my $path = $self->unescape_uri($req_uri);
519 # Using URI directly is way too slow, so we construct the URLs manually
520 my $uri_class = "URI::$scheme";
522 # HTTP_HOST will include the port even if it's 80/443
523 $host =~ s/:(?:80|443)$//;
525 if ($port !~ /^(?:80|443)$/ && $host !~ /:/) {
530 $path =~ s/([^$URI::uric])/$URI::Escape::escapes{$1}/go;
531 $path =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
533 my $query = $env->{QUERY_STRING} ? '?' . $env->{QUERY_STRING} : '';
534 my $uri = $scheme . '://' . $host . '/' . $path . $query;
536 $ctx->request->uri( bless \$uri, $uri_class );
539 # base must end in a slash
540 $base_path .= '/' unless $base_path =~ m{/$};
542 my $base_uri = $scheme . '://' . $host . $base_path;
544 $ctx->request->base( bless \$base_uri, $uri_class );
549 =head2 $self->prepare_request($c)
551 =head2 $self->prepare_query_parameters($c)
553 process the query string and extract query parameters.
557 sub prepare_query_parameters {
560 my $query_string = exists $self->env->{QUERY_STRING}
561 ? $self->env->{QUERY_STRING}
564 # Check for keywords (no = signs)
565 # (yes, index() is faster than a regex :))
566 if ( index( $query_string, '=' ) < 0 ) {
567 $c->request->query_keywords( $self->unescape_uri($query_string) );
573 # replace semi-colons
574 $query_string =~ s/;/&/g;
576 my @params = grep { length $_ } split /&/, $query_string;
578 for my $item ( @params ) {
581 = map { $self->unescape_uri($_) }
582 split( /=/, $item, 2 );
584 $param = $self->unescape_uri($item) unless defined $param;
586 if ( exists $query{$param} ) {
587 if ( ref $query{$param} ) {
588 push @{ $query{$param} }, $value;
591 $query{$param} = [ $query{$param}, $value ];
595 $query{$param} = $value;
599 $c->request->query_parameters( \%query );
602 =head2 $self->prepare_read($c)
604 prepare to read from the engine.
609 my ( $self, $c ) = @_;
611 # Initialize the read position
612 $self->read_position(0);
614 # Initialize the amount of data we think we need to read
615 $self->read_length( $c->request->header('Content-Length') || 0 );
618 =head2 $self->prepare_request(@arguments)
620 Populate the context object from the request object.
624 sub prepare_request {
625 my ($self, $ctx, %args) = @_;
626 $self->_set_env($args{env});
629 =head2 $self->prepare_uploads($c)
633 sub prepare_uploads {
634 my ( $self, $c ) = @_;
636 my $request = $c->request;
637 return unless $request->_body;
639 my $uploads = $request->_body->upload;
640 my $parameters = $request->parameters;
641 foreach my $name (keys %$uploads) {
642 my $files = $uploads->{$name};
644 for my $upload (ref $files eq 'ARRAY' ? @$files : ($files)) {
645 my $headers = HTTP::Headers->new( %{ $upload->{headers} } );
646 my $u = Catalyst::Request::Upload->new
648 size => $upload->{size},
649 type => $headers->content_type,
651 tempname => $upload->{tempname},
652 filename => $upload->{filename},
656 $request->uploads->{$name} = @uploads > 1 ? \@uploads : $uploads[0];
658 # support access to the filename as a normal param
659 my @filenames = map { $_->{filename} } @uploads;
660 # append, if there's already params with this name
661 if (exists $parameters->{$name}) {
662 if (ref $parameters->{$name} eq 'ARRAY') {
663 push @{ $parameters->{$name} }, @filenames;
666 $parameters->{$name} = [ $parameters->{$name}, @filenames ];
670 $parameters->{$name} = @filenames > 1 ? \@filenames : $filenames[0];
675 =head2 $self->prepare_write($c)
677 Abstract method. Implemented by the engines.
681 sub prepare_write { }
683 =head2 $self->read($c, [$maxlength])
685 Reads from the input stream by calling C<< $self->read_chunk >>.
687 Maintains the read_length and read_position counters as data is read.
692 my ( $self, $c, $maxlength ) = @_;
694 my $remaining = $self->read_length - $self->read_position;
695 $maxlength ||= $CHUNKSIZE;
697 # Are we done reading?
698 if ( $remaining <= 0 ) {
699 $self->finalize_read($c);
703 my $readlen = ( $remaining > $maxlength ) ? $maxlength : $remaining;
704 my $rc = $self->read_chunk( $c, my $buffer, $readlen );
706 if (0 == $rc) { # Nothing more to read even though Content-Length
707 # said there should be. FIXME - Warn in the log here?
708 $self->finalize_read;
711 $self->read_position( $self->read_position + $rc );
715 Catalyst::Exception->throw(
716 message => "Unknown error reading input: $!" );
720 =head2 $self->read_chunk($c, $buffer, $length)
722 Each engine implements read_chunk as its preferred way of reading a chunk
723 of data. Returns the number of bytes read. A return of 0 indicates that
724 there is no more data to be read.
730 =head2 $self->read_length
732 The length of input data to be read. This is obtained from the Content-Length
735 =head2 $self->read_position
737 The amount of input data that has already been read.
739 =head2 $self->run($c)
741 Start the engine. Implemented by the various engine classes.
746 my ($self, $app) = @_;
753 $self->_set_response_cb($respond);
754 $app->handle_request(env => $env);
759 =head2 $self->write($c, $buffer)
761 Writes the buffer to the client.
766 my ( $self, $c, $buffer ) = @_;
768 unless ( $self->_prepared_write ) {
769 $self->prepare_write($c);
770 $self->_prepared_write(1);
773 return 0 if !defined $buffer;
775 my $len = length($buffer);
776 $self->_writer->write($buffer);
781 =head2 $self->unescape_uri($uri)
783 Unescapes a given URI using the most efficient method available. Engines such
784 as Apache may implement this using Apache's C-based modules, for example.
789 my ( $self, $str ) = @_;
791 $str =~ s/(?:%([0-9A-Fa-f]{2})|\+)/defined $1 ? chr(hex($1)) : ' '/eg;
796 =head2 $self->finalize_output
798 <obsolete>, see finalize_body
802 Hash containing enviroment variables including many special variables inserted
803 by WWW server - like SERVER_*, REMOTE_*, HTTP_* ...
805 Before accesing enviroment variables consider whether the same information is
806 not directly available via Catalyst objects $c->request, $c->engine ...
808 BEWARE: If you really need to access some enviroment variable from your Catalyst
809 application you should use $c->engine->env->{VARNAME} instead of $ENV{VARNAME},
810 as in some enviroments the %ENV hash does not contain what you would expect.
814 Catalyst Contributors, see Catalyst.pm
818 This library is free software. You can redistribute it and/or modify it under
819 the same terms as Perl itself.