1 package Catalyst::Engine;
4 use base 'Class::Accessor::Fast';
5 use CGI::Simple::Cookie;
6 use Data::Dump qw/dump/;
13 # input position and length
14 __PACKAGE__->mk_accessors(qw/read_position read_length/);
17 use overload '""' => sub { return ref shift }, fallback => 1;
19 # Amount of data to read from input on each pass
20 our $CHUNKSIZE = 64 * 1024;
24 Catalyst::Engine - The Catalyst Engine
35 =head2 $self->finalize_body($c)
37 Finalize body. Prints the response output.
42 my ( $self, $c ) = @_;
43 my $body = $c->response->body;
44 no warnings 'uninitialized';
45 if ( Scalar::Util::blessed($body) && $body->can('read') or ref($body) eq 'GLOB' ) {
46 while ( !eof $body ) {
47 read $body, my ($buffer), $CHUNKSIZE;
48 last unless $self->write( $c, $buffer );
53 $self->write( $c, $body );
57 =head2 $self->finalize_cookies($c)
59 Create CGI::Simple::Cookie objects from $c->res->cookies, and set them as
64 sub finalize_cookies {
65 my ( $self, $c ) = @_;
69 foreach my $name ( keys %{ $c->response->cookies } ) {
71 my $val = $c->response->cookies->{$name};
74 Scalar::Util::blessed($val)
76 : CGI::Simple::Cookie->new(
78 -value => $val->{value},
79 -expires => $val->{expires},
80 -domain => $val->{domain},
81 -path => $val->{path},
82 -secure => $val->{secure} || 0
86 push @cookies, $cookie->as_string;
89 for my $cookie (@cookies) {
90 $c->res->headers->push_header( 'Set-Cookie' => $cookie );
94 =head2 $self->finalize_error($c)
96 Output an apropriate error message, called if there's an error in $c
97 after the dispatch has finished. Will output debug messages if Catalyst
98 is in debug mode, or a `please come back later` message otherwise.
103 my ( $self, $c ) = @_;
105 $c->res->content_type('text/html; charset=utf-8');
106 my $name = $c->config->{name} || join(' ', split('::', ref $c));
108 my ( $title, $error, $infos );
112 $error = join '', map {
113 '<p><code class="error">'
114 . encode_entities($_)
117 $error ||= 'No output';
118 $error = qq{<pre wrap="">$error</pre>};
119 $title = $name = "$name on Catalyst $Catalyst::VERSION";
120 $name = "<h1>$name</h1>";
122 # Don't show context in the dump
123 delete $c->req->{_context};
124 delete $c->res->{_context};
126 # Don't show body parser in the dump
127 delete $c->req->{_body};
129 # Don't show response header state in dump
130 delete $c->res->{_finalized_headers};
134 for my $dump ( $c->dump_these ) {
135 my $name = $dump->[0];
136 my $value = encode_entities( dump( $dump->[1] ));
137 push @infos, sprintf <<"EOF", $name, $value;
138 <h2><a href="#" onclick="toggleDump('dump_$i'); return false">%s</a></h2>
140 <pre wrap="">%s</pre>
145 $infos = join "\n", @infos;
152 (en) Please come back later
153 (fr) SVP veuillez revenir plus tard
154 (de) Bitte versuchen sie es spaeter nocheinmal
155 (at) Konnten's bitt'schoen spaeter nochmal reinschauen
156 (no) Vennligst prov igjen senere
157 (dk) Venligst prov igen senere
158 (pl) Prosze sprobowac pozniej
163 $c->res->body( <<"" );
164 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
165 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
166 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
168 <meta http-equiv="Content-Language" content="en" />
169 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
170 <title>$title</title>
171 <script type="text/javascript">
173 function toggleDump (dumpElement) {
174 var e = document.getElementById( dumpElement );
175 if (e.style.display == "none") {
176 e.style.display = "";
179 e.style.display = "none";
184 <style type="text/css">
186 font-family: "Bitstream Vera Sans", "Trebuchet MS", Verdana,
187 Tahoma, Arial, helvetica, sans-serif;
189 background-color: #eee;
193 :link, :link:hover, :visited, :visited:hover {
198 background-color: #ccc;
199 border: 1px solid #aaa;
204 background-color: #cce;
205 border: 1px solid #755;
211 background-color: #eee;
212 border: 1px solid #575;
218 background-color: #cce;
219 border: 1px solid #557;
228 div.name h1, div.error p {
236 text-decoration: underline;
242 /* from http://users.tkk.fi/~tkarvine/linux/doc/pre-wrap/pre-wrap-css3-mozilla-opera-ie.html */
243 /* Browser specific (not valid) styles to make preformatted text wrap */
245 white-space: pre-wrap; /* css-3 */
246 white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
247 white-space: -pre-wrap; /* Opera 4-6 */
248 white-space: -o-pre-wrap; /* Opera 7 */
249 word-wrap: break-word; /* Internet Explorer 5.5+ */
255 <div class="error">$error</div>
256 <div class="infos">$infos</div>
257 <div class="name">$name</div>
264 $c->res->{body} .= ( ' ' x 512 );
267 $c->res->status(500);
270 =head2 $self->finalize_headers($c)
272 Abstract method, allows engines to write headers to response
276 sub finalize_headers { }
278 =head2 $self->finalize_read($c)
283 my ( $self, $c ) = @_;
285 undef $self->{_prepared_read};
288 =head2 $self->finalize_uploads($c)
290 Clean up after uploads, deleting temp files.
294 sub finalize_uploads {
295 my ( $self, $c ) = @_;
297 if ( keys %{ $c->request->uploads } ) {
298 for my $key ( keys %{ $c->request->uploads } ) {
299 my $upload = $c->request->uploads->{$key};
300 unlink map { $_->tempname }
301 grep { -e $_->tempname }
302 ref $upload eq 'ARRAY' ? @{$upload} : ($upload);
307 =head2 $self->prepare_body($c)
309 sets up the L<Catalyst::Request> object body using L<HTTP::Body>
314 my ( $self, $c ) = @_;
316 my $length = $c->request->header('Content-Length') || 0;
318 $self->read_length( $length );
321 unless ( $c->request->{_body} ) {
322 my $type = $c->request->header('Content-Type');
323 $c->request->{_body} = HTTP::Body->new( $type, $length );
324 $c->request->{_body}->{tmpdir} = $c->config->{uploadtmp}
325 if exists $c->config->{uploadtmp};
328 while ( my $buffer = $self->read($c) ) {
329 $c->prepare_body_chunk($buffer);
332 # paranoia against wrong Content-Length header
333 my $remaining = $length - $self->read_position;
334 if ( $remaining > 0 ) {
335 $self->finalize_read($c);
336 Catalyst::Exception->throw(
337 "Wrong Content-Length value: $length" );
341 # Defined but will cause all body code to be skipped
342 $c->request->{_body} = 0;
346 =head2 $self->prepare_body_chunk($c)
348 Add a chunk to the request body.
352 sub prepare_body_chunk {
353 my ( $self, $c, $chunk ) = @_;
355 $c->request->{_body}->add($chunk);
358 =head2 $self->prepare_body_parameters($c)
360 Sets up parameters from body.
364 sub prepare_body_parameters {
365 my ( $self, $c ) = @_;
367 return unless $c->request->{_body};
369 $c->request->body_parameters( $c->request->{_body}->param );
372 =head2 $self->prepare_connection($c)
374 Abstract method implemented in engines.
378 sub prepare_connection { }
380 =head2 $self->prepare_cookies($c)
382 Parse cookies from header. Sets a L<CGI::Simple::Cookie> object.
386 sub prepare_cookies {
387 my ( $self, $c ) = @_;
389 if ( my $header = $c->request->header('Cookie') ) {
390 $c->req->cookies( { CGI::Simple::Cookie->parse($header) } );
394 =head2 $self->prepare_headers($c)
398 sub prepare_headers { }
400 =head2 $self->prepare_parameters($c)
402 sets up parameters from query and post parameters.
406 sub prepare_parameters {
407 my ( $self, $c ) = @_;
409 # We copy, no references
410 foreach my $name ( keys %{ $c->request->query_parameters } ) {
411 my $param = $c->request->query_parameters->{$name};
412 $param = ref $param eq 'ARRAY' ? [ @{$param} ] : $param;
413 $c->request->parameters->{$name} = $param;
416 # Merge query and body parameters
417 foreach my $name ( keys %{ $c->request->body_parameters } ) {
418 my $param = $c->request->body_parameters->{$name};
419 $param = ref $param eq 'ARRAY' ? [ @{$param} ] : $param;
420 if ( my $old_param = $c->request->parameters->{$name} ) {
421 if ( ref $old_param eq 'ARRAY' ) {
422 push @{ $c->request->parameters->{$name} },
423 ref $param eq 'ARRAY' ? @$param : $param;
425 else { $c->request->parameters->{$name} = [ $old_param, $param ] }
427 else { $c->request->parameters->{$name} = $param }
431 =head2 $self->prepare_path($c)
433 abstract method, implemented by engines.
439 =head2 $self->prepare_request($c)
441 =head2 $self->prepare_query_parameters($c)
443 process the query string and extract query parameters.
447 sub prepare_query_parameters {
448 my ( $self, $c, $query_string ) = @_;
450 # replace semi-colons
451 $query_string =~ s/;/&/g;
453 my $u = URI->new( '', 'http' );
454 $u->query($query_string);
455 for my $key ( $u->query_param ) {
456 my @vals = $u->query_param($key);
457 $c->request->query_parameters->{$key} = @vals > 1 ? [@vals] : $vals[0];
461 =head2 $self->prepare_read($c)
463 prepare to read from the engine.
468 my ( $self, $c ) = @_;
470 # Reset the read position
471 $self->read_position(0);
474 =head2 $self->prepare_request(@arguments)
476 Populate the context object from the request object.
480 sub prepare_request { }
482 =head2 $self->prepare_uploads($c)
486 sub prepare_uploads {
487 my ( $self, $c ) = @_;
489 return unless $c->request->{_body};
491 my $uploads = $c->request->{_body}->upload;
492 for my $name ( keys %$uploads ) {
493 my $files = $uploads->{$name};
494 $files = ref $files eq 'ARRAY' ? $files : [$files];
496 for my $upload (@$files) {
497 my $u = Catalyst::Request::Upload->new;
498 $u->headers( HTTP::Headers->new( %{ $upload->{headers} } ) );
499 $u->type( $u->headers->content_type );
500 $u->tempname( $upload->{tempname} );
501 $u->size( $upload->{size} );
502 $u->filename( $upload->{filename} );
505 $c->request->uploads->{$name} = @uploads > 1 ? \@uploads : $uploads[0];
507 # support access to the filename as a normal param
508 my @filenames = map { $_->{filename} } @uploads;
509 # append, if there's already params with this name
510 if (exists $c->request->parameters->{$name}) {
511 if (ref $c->request->parameters->{$name} eq 'ARRAY') {
512 push @{ $c->request->parameters->{$name} }, @filenames;
515 $c->request->parameters->{$name} =
516 [ $c->request->parameters->{$name}, @filenames ];
520 $c->request->parameters->{$name} =
521 @filenames > 1 ? \@filenames : $filenames[0];
526 =head2 $self->prepare_write($c)
528 Abstract method. Implemented by the engines.
532 sub prepare_write { }
534 =head2 $self->read($c, [$maxlength])
539 my ( $self, $c, $maxlength ) = @_;
541 unless ( $self->{_prepared_read} ) {
542 $self->prepare_read($c);
543 $self->{_prepared_read} = 1;
546 my $remaining = $self->read_length - $self->read_position;
547 $maxlength ||= $CHUNKSIZE;
549 # Are we done reading?
550 if ( $remaining <= 0 ) {
551 $self->finalize_read($c);
555 my $readlen = ( $remaining > $maxlength ) ? $maxlength : $remaining;
556 my $rc = $self->read_chunk( $c, my $buffer, $readlen );
558 $self->read_position( $self->read_position + $rc );
562 Catalyst::Exception->throw(
563 message => "Unknown error reading input: $!" );
567 =head2 $self->read_chunk($c, $buffer, $length)
569 Each engine inplements read_chunk as its preferred way of reading a chunk
576 =head2 $self->read_length
578 The length of input data to be read. This is obtained from the Content-Length
581 =head2 $self->read_position
583 The amount of input data that has already been read.
585 =head2 $self->run($c)
587 Start the engine. Implemented by the various engine classes.
593 =head2 $self->write($c, $buffer)
595 Writes the buffer to the client. Can only be called once for a request.
600 my ( $self, $c, $buffer ) = @_;
602 unless ( $self->{_prepared_write} ) {
603 $self->prepare_write($c);
604 $self->{_prepared_write} = 1;
607 print STDOUT $buffer;
611 =head2 $self->finalize_output
613 <obsolete>, see finalize_body
617 Sebastian Riedel, <sri@cpan.org>
619 Andy Grundman, <andy@hybridized.org>
623 This program is free software, you can redistribute it and/or modify it under
624 the same terms as Perl itself.