1 package Catalyst::Request;
3 use IO::Socket qw[AF_INET inet_aton];
16 use namespace::clean -except => 'meta';
18 with 'MooseX::Emulate::Class::Accessor::Fast';
20 has env => (is => 'ro', writer => '_set_env', predicate => 'has_env');
21 # XXX Deprecated crap here - warn?
22 has action => (is => 'rw');
23 # XXX: Deprecated in docs ages ago (2006), deprecated with warning in 5.8000 due
24 # to confusion between Engines and Plugin::Authentication. Remove in 5.8100?
25 has user => (is => 'rw');
26 sub snippets { shift->captures(@_) }
28 has _read_position => (
29 # FIXME: work around Moose bug RT#75367
32 writer => '_set_read_position',
36 # FIXME: work around Moose bug RT#75367
41 $self->header('Content-Length') || 0;
46 has address => (is => 'rw');
47 has arguments => (is => 'rw', default => sub { [] });
48 has cookies => (is => 'ro', builder => 'prepare_cookies', lazy => 1);
53 if ( my $header = $self->header('Cookie') ) {
54 return { CGI::Simple::Cookie->parse($header) };
59 has query_keywords => (is => 'rw');
60 has match => (is => 'rw');
61 has method => (is => 'rw');
62 has protocol => (is => 'rw');
63 has query_parameters => (is => 'rw', default => sub { {} });
64 has secure => (is => 'rw', default => 0);
65 has captures => (is => 'rw', default => sub { [] });
66 has uri => (is => 'rw', predicate => 'has_uri');
67 has remote_user => (is => 'rw');
70 isa => 'HTTP::Headers',
71 handles => [qw(content_encoding content_length content_type header referer user_agent)],
72 builder => 'prepare_headers',
80 my $headers = HTTP::Headers->new();
82 for my $header (keys %{ $env }) {
83 next unless $header =~ /^(HTTP|CONTENT|COOKIE)/i;
84 (my $field = $header) =~ s/^HTTPS?_//;
86 $headers->header($field => $env->{$header});
99 predicate=>'has_io_fh',
101 builder=>'_build_io_fh');
105 return $self->env->{'psgix.io'}
106 || die "Your Server does not support psgix.io";
109 has data_handlers => ( is=>'ro', isa=>'HashRef', default=>sub { +{} } );
114 builder=>'_build_body_data');
116 sub _build_body_data {
118 my $content_type = $self->content_type;
119 my ($match) = grep { $content_type =~/$_/i }
120 keys(%{$self->data_handlers});
123 my $fh = $self->body;
125 return $self->data_handlers->{$match}->($fh, $self);
131 # Amount of data to read from input on each pass
132 our $CHUNKSIZE = 64 * 1024;
135 my ($self, $maxlength) = @_;
136 my $remaining = $self->_read_length - $self->_read_position;
137 $maxlength ||= $CHUNKSIZE;
139 # Are we done reading?
140 if ( $remaining <= 0 ) {
144 my $readlen = ( $remaining > $maxlength ) ? $maxlength : $remaining;
145 my $rc = $self->read_chunk( my $buffer, $readlen );
147 if (0 == $rc) { # Nothing more to read even though Content-Length
148 # said there should be.
151 $self->_set_read_position( $self->_read_position + $rc );
155 Catalyst::Exception->throw(
156 message => "Unknown error reading input: $!" );
162 return $self->env->{'psgi.input'}->read(@_);
165 has body_parameters => (
169 builder => 'prepare_body_parameters',
175 default => sub { {} },
181 builder => '_build_parameters',
182 clearer => '_clear_parameters',
186 # - Can we lose the before modifiers which just call prepare_body ?
187 # they are wasteful, slow us down and feel cluttery.
189 # Can we make _body an attribute, have the rest of
190 # these lazy build from there and kill all the direct hash access
191 # in Catalyst.pm and Engine.pm?
193 sub prepare_parameters {
195 $self->_clear_parameters;
196 return $self->parameters;
199 sub _build_parameters {
202 my $body_parameters = $self->body_parameters;
203 my $query_parameters = $self->query_parameters;
205 ## setup for downstream plack
206 $self->env->{'plack.request.merged'} ||= do {
207 my $query = $self->env->{'plack.request.query'} || Hash::MultiValue->new;
208 my $body = $self->env->{'plack.request.body'} || Hash::MultiValue->new;
209 Hash::MultiValue->new($query->flatten, $body->flatten);
212 # We copy, no references
213 foreach my $name (keys %$query_parameters) {
214 my $param = $query_parameters->{$name};
215 $parameters->{$name} = ref $param eq 'ARRAY' ? [ @$param ] : $param;
218 # Merge query and body parameters
219 foreach my $name (keys %$body_parameters) {
220 my $param = $body_parameters->{$name};
221 my @values = ref $param eq 'ARRAY' ? @$param : ($param);
222 if ( my $existing = $parameters->{$name} ) {
223 unshift(@values, (ref $existing eq 'ARRAY' ? @$existing : $existing));
225 $parameters->{$name} = @values > 1 ? \@values : $values[0];
232 predicate => '_has_uploadtmp',
238 # If previously applied middleware created the HTTP::Body object, then we
241 if(my $plack_body = $self->env->{'plack.request.http.body'}) {
242 $self->_body($plack_body);
243 $self->_body->cleanup(1);
247 # Define PSGI ENV placeholders, or for empty should there be no content
248 # body (typical in HEAD or GET). Looks like from Plack::Request that
249 # middleware would probably expect to see this, even if empty
251 $self->env->{'plack.request.body'} = Hash::MultiValue->new;
252 $self->env->{'plack.request.upload'} = Hash::MultiValue->new;
254 # If there is nothing to read, set body to naught and return. This
255 # will cause all body code to be skipped
257 return $self->_body(0) unless my $length = $self->_read_length;
259 # Unless the body has already been set, create it. Not sure about this
260 # code, how else might it be set, but this was existing logic.
262 unless ($self->_body) {
263 my $type = $self->header('Content-Type');
264 $self->_body(HTTP::Body->new( $type, $length ));
265 $self->_body->cleanup(1);
267 # JNAP: I'm not sure this is doing what we expect, but it also doesn't
268 # seem to be hurting (seems ->_has_uploadtmp is true more than I would
271 $self->_body->tmpdir( $self->_uploadtmp )
272 if $self->_has_uploadtmp;
275 # Ok if we get this far, we have to read psgi.input into the new body
276 # object. Lets play nice with any plack app or other downstream, so
277 # we create a buffer unless one exists.
280 if ($self->env->{'psgix.input.buffered'}) {
281 # Be paranoid about previous psgi middleware or apps that read the
282 # input but didn't return the buffer to the start.
283 $self->env->{'psgi.input'}->seek(0, 0);
285 $stream_buffer = Stream::Buffered->new($length);
288 # Check for definedness as you could read '0'
289 while ( defined ( my $chunk = $self->read() ) ) {
290 $self->prepare_body_chunk($chunk);
291 $stream_buffer->print($chunk) if $stream_buffer;
294 # Ok, we read the body. Lets play nice for any PSGI app down the pipe
296 if ($stream_buffer) {
297 $self->env->{'psgix.input.buffered'} = 1;
298 $self->env->{'psgi.input'} = $stream_buffer->rewind;
300 $self->env->{'psgi.input'}->seek(0, 0); # Reset the buffer for downstream middleware or apps
303 $self->env->{'plack.request.http.body'} = $self->_body;
304 $self->env->{'plack.request.body'} = Hash::MultiValue->from_mixed($self->_body->param);
306 # paranoia against wrong Content-Length header
307 my $remaining = $length - $self->_read_position;
308 if ( $remaining > 0 ) {
309 Catalyst::Exception->throw("Wrong Content-Length value: $length" );
313 sub prepare_body_chunk {
314 my ( $self, $chunk ) = @_;
316 $self->_body->add($chunk);
319 sub prepare_body_parameters {
322 $self->prepare_body if ! $self->_has_body;
323 return {} unless $self->_body;
325 return $self->_body->param;
328 sub prepare_connection {
331 my $env = $self->env;
333 $self->address( $env->{REMOTE_ADDR} );
334 $self->hostname( $env->{REMOTE_HOST} )
335 if exists $env->{REMOTE_HOST};
336 $self->protocol( $env->{SERVER_PROTOCOL} );
337 $self->remote_user( $env->{REMOTE_USER} );
338 $self->method( $env->{REQUEST_METHOD} );
339 $self->secure( $env->{'psgi.url_scheme'} eq 'https' ? 1 : 0 );
342 # XXX - FIXME - method is here now, move this crap...
343 around parameters => sub {
344 my ($orig, $self, $params) = @_;
346 if ( !ref $params ) {
348 "Attempt to retrieve '$params' with req->params(), " .
349 "you probably meant to call req->param('$params')"
353 return $self->$orig($params);
364 return $self->path if $self->has_uri;
369 is => 'rw', clearer => '_clear_body', predicate => '_has_body',
371 # Eugh, ugly. Should just be able to rename accessor methods to 'body'
372 # and provide a custom reader..
375 $self->prepare_body unless $self->_has_body;
376 croak 'body is a reader' if scalar @_;
377 return blessed $self->_body ? $self->_body->body : $self->_body;
386 gethostbyaddr( inet_aton( $self->address ), AF_INET ) || $self->address
390 has _path => ( is => 'rw', predicate => '_has_path', clearer => '_clear_path' );
392 sub args { shift->arguments(@_) }
393 sub body_params { shift->body_parameters(@_) }
394 sub input { shift->body(@_) }
395 sub params { shift->parameters(@_) }
396 sub query_params { shift->query_parameters(@_) }
397 sub path_info { shift->path(@_) }
399 =for stopwords param params
403 Catalyst::Request - provides information about the current client request
408 $req->address eq "127.0.0.1";
414 $req->body_parameters;
415 $req->content_encoding;
416 $req->content_length;
424 $req->query_keywords;
432 $req->query_parameters;
443 See also L<Catalyst>, L<Catalyst::Request::Upload>.
447 This is the Catalyst Request class, which provides an interface to data for the
448 current client request. The request object is prepared by L<Catalyst::Engine>,
449 thus hiding the details of the particular engine implementation.
455 Returns the IP address of the client.
457 =head2 $req->arguments
459 Returns a reference to an array containing the arguments.
461 print $c->request->arguments->[0];
463 For example, if your action was
465 package MyApp::Controller::Foo;
471 and the URI for the request was C<http://.../foo/moose/bah>, the string C<bah>
472 would be the first and only argument.
474 Arguments get automatically URI-unescaped for you.
478 Shortcut for L</arguments>.
482 Contains the URI base. This will always have a trailing slash. Note that the
483 URI scheme (e.g., http vs. https) must be determined through heuristics;
484 depending on your server configuration, it may be incorrect. See $req->secure
487 If your application was queried with the URI
488 C<http://localhost:3000/some/path> then C<base> is C<http://localhost:3000/>.
492 Returns the message body of the request, as returned by L<HTTP::Body>: a string,
493 unless Content-Type is C<application/x-www-form-urlencoded>, C<text/xml>, or
494 C<multipart/form-data>, in which case a L<File::Temp> object is returned.
496 =head2 $req->body_data
498 Returns a Perl representation of POST/PUT body data that is not classic HTML
499 form data, such as JSON, XML, etc. By default, Catalyst will parse incoming
500 data of the type 'application/json' and return access to that data via this
501 method. You may define addition data_handlers via a global configuration
502 setting. See L<Catalyst\DATA HANDLERS> for more information.
504 =head2 $req->body_parameters
506 Returns a reference to a hash containing body (POST) parameters. Values can
507 be either a scalar or an arrayref containing scalars.
509 print $c->request->body_parameters->{field};
510 print $c->request->body_parameters->{field}->[0];
512 These are the parameters from the POST part of the request, if any.
514 =head2 $req->body_params
516 Shortcut for body_parameters.
518 =head2 $req->content_encoding
520 Shortcut for $req->headers->content_encoding.
522 =head2 $req->content_length
524 Shortcut for $req->headers->content_length.
526 =head2 $req->content_type
528 Shortcut for $req->headers->content_type.
532 A convenient method to access $req->cookies.
534 $cookie = $c->request->cookie('name');
535 @cookies = $c->request->cookie;
543 return keys %{ $self->cookies };
550 unless ( exists $self->cookies->{$name} ) {
554 return $self->cookies->{$name};
560 Returns a reference to a hash containing the cookies.
562 print $c->request->cookies->{mycookie}->value;
564 The cookies in the hash are indexed by name, and the values are L<CGI::Simple::Cookie>
569 Shortcut for $req->headers->header.
573 Returns an L<HTTP::Headers> object containing the headers for the current request.
575 print $c->request->headers->header('X-Catalyst');
577 =head2 $req->hostname
579 Returns the hostname of the client. Use C<< $req->uri->host >> to get the hostname of the server.
583 Alias for $req->body.
585 =head2 $req->query_keywords
587 Contains the keywords portion of a query string, when no '=' signs are
590 http://localhost/path?some+keywords
592 $c->request->query_keywords will contain 'some keywords'
596 This contains the matching part of a Regex action. Otherwise
597 it returns the same as 'action', except for default actions,
598 which return an empty string.
602 Contains the request method (C<GET>, C<POST>, C<HEAD>, etc).
606 Returns GET and POST parameters with a CGI.pm-compatible param method. This
607 is an alternative method for accessing parameters in $c->req->parameters.
609 $value = $c->request->param( 'foo' );
610 @values = $c->request->param( 'foo' );
611 @params = $c->request->param;
613 Like L<CGI>, and B<unlike> earlier versions of Catalyst, passing multiple
614 arguments to this method, like this:
616 $c->request->param( 'foo', 'bar', 'gorch', 'quxx' );
618 will set the parameter C<foo> to the multiple values C<bar>, C<gorch> and
619 C<quxx>. Previously this would have added C<bar> as another value to C<foo>
620 (creating it if it didn't exist before), and C<quxx> as another value for
623 B<NOTE> this is considered a legacy interface and care should be taken when
624 using it. C<< scalar $c->req->param( 'foo' ) >> will return only the first
625 C<foo> param even if multiple are present; C<< $c->req->param( 'foo' ) >> will
626 return a list of as many are present, which can have unexpected consequences
627 when writing code of the form:
631 baz => $c->req->param( 'baz' ),
634 If multiple C<baz> parameters are provided this code might corrupt data or
635 cause a hash initialization error. For a more straightforward interface see
636 C<< $c->req->parameters >>.
644 return keys %{ $self->parameters };
651 unless ( exists $self->parameters->{$param} ) {
652 return wantarray ? () : undef;
655 if ( ref $self->parameters->{$param} eq 'ARRAY' ) {
657 ? @{ $self->parameters->{$param} }
658 : $self->parameters->{$param}->[0];
662 ? ( $self->parameters->{$param} )
663 : $self->parameters->{$param};
668 $self->parameters->{$field} = [@_];
672 =head2 $req->parameters
674 Returns a reference to a hash containing GET and POST parameters. Values can
675 be either a scalar or an arrayref containing scalars.
677 print $c->request->parameters->{field};
678 print $c->request->parameters->{field}->[0];
680 This is the combination of C<query_parameters> and C<body_parameters>.
684 Shortcut for $req->parameters.
688 Returns the path, i.e. the part of the URI after $req->base, for the current request.
690 http://localhost/path/foo
692 $c->request->path will contain 'path/foo'
694 =head2 $req->path_info
696 Alias for path, added for compatibility with L<CGI>.
701 my ( $self, @params ) = @_;
704 $self->uri->path(@params);
707 elsif ( $self->_has_path ) {
711 my $path = $self->uri->path;
712 my $location = $self->base->path;
713 $path =~ s/^(\Q$location\E)?//;
721 =head2 $req->protocol
723 Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.
725 =head2 $req->query_parameters
727 =head2 $req->query_params
729 Returns a reference to a hash containing query string (GET) parameters. Values can
730 be either a scalar or an arrayref containing scalars.
732 print $c->request->query_parameters->{field};
733 print $c->request->query_parameters->{field}->[0];
735 =head2 $req->read( [$maxlength] )
737 Reads a chunk of data from the request body. This method is intended to be
738 used in a while loop, reading $maxlength bytes on every call. $maxlength
739 defaults to the size of the request if not specified.
741 =head2 $req->read_chunk(\$buff, $max)
745 You have to set MyApp->config(parse_on_demand => 1) to use this directly.
749 Shortcut for $req->headers->referer. Returns the referring page.
753 Returns true or false, indicating whether the connection is secure
754 (https). The reliability of $req->secure may depend on your server
755 configuration; Catalyst relies on PSGI to determine whether or not a
756 request is secure (Catalyst looks at psgi.url_scheme), and different
757 PSGI servers may make this determination in different ways (as by
758 directly passing along information from the server, interpreting any of
759 several HTTP headers, or using heuristics of their own).
761 =head2 $req->captures
763 Returns a reference to an array containing captured args from chained
764 actions or regex captures.
766 my @captures = @{ $c->request->captures };
770 A convenient method to access $req->uploads.
772 $upload = $c->request->upload('field');
773 @uploads = $c->request->upload('field');
774 @fields = $c->request->upload;
776 for my $upload ( $c->request->upload('field') ) {
777 print $upload->filename;
786 return keys %{ $self->uploads };
793 unless ( exists $self->uploads->{$upload} ) {
794 return wantarray ? () : undef;
797 if ( ref $self->uploads->{$upload} eq 'ARRAY' ) {
799 ? @{ $self->uploads->{$upload} }
800 : $self->uploads->{$upload}->[0];
804 ? ( $self->uploads->{$upload} )
805 : $self->uploads->{$upload};
811 while ( my ( $field, $upload ) = splice( @_, 0, 2 ) ) {
813 if ( exists $self->uploads->{$field} ) {
814 for ( $self->uploads->{$field} ) {
815 $_ = [$_] unless ref($_) eq "ARRAY";
816 push( @$_, $upload );
820 $self->uploads->{$field} = $upload;
828 Returns a reference to a hash containing uploads. Values can be either a
829 L<Catalyst::Request::Upload> object, or an arrayref of
830 L<Catalyst::Request::Upload> objects.
832 my $upload = $c->request->uploads->{field};
833 my $upload = $c->request->uploads->{field}->[0];
837 Returns a L<URI> object for the current request. Stringifies to the URI text.
839 =head2 $req->mangle_params( { key => 'value' }, $appendmode);
841 Returns a hashref of parameters stemming from the current request's params,
842 plus the ones supplied. Keys for which no current param exists will be
843 added, keys with undefined values will be removed and keys with existing
844 params will be replaced. Note that you can supply a true value as the final
845 argument to change behavior with regards to existing parameters, appending
846 values rather than replacing them.
850 # URI query params foo=1
851 my $hashref = $req->mangle_params({ foo => 2 });
852 # Result is query params of foo=2
856 # URI query params foo=1
857 my $hashref = $req->mangle_params({ foo => 2 }, 1);
858 # Result is query params of foo=1&foo=2
860 This is the code behind C<uri_with>.
865 my ($self, $args, $append) = @_;
867 carp('No arguments passed to mangle_params()') unless $args;
869 foreach my $value ( values %$args ) {
870 next unless defined $value;
871 for ( ref $value eq 'ARRAY' ? @$value : $value ) {
873 utf8::encode( $_ ) if utf8::is_utf8($_);
877 my %params = %{ $self->uri->query_form_hash };
878 foreach my $key (keys %{ $args }) {
879 my $val = $args->{$key};
882 if($append && exists($params{$key})) {
884 # This little bit of heaven handles appending a new value onto
885 # an existing one regardless if the existing value is an array
886 # or not, and regardless if the new value is an array or not
888 ref($params{$key}) eq 'ARRAY' ? @{ $params{$key} } : $params{$key},
889 ref($val) eq 'ARRAY' ? @{ $val } : $val
893 $params{$key} = $val;
897 # If the param wasn't defined then we delete it.
898 delete($params{$key});
906 =head2 $req->uri_with( { key => 'value' } );
908 Returns a rewritten URI object for the current request. Key/value pairs
909 passed in will override existing parameters. You can remove an existing
910 parameter by passing in an undef value. Unmodified pairs will be
913 You may also pass an optional second parameter that puts C<uri_with> into
916 $req->uri_with( { key => 'value' }, { mode => 'append' } );
918 See C<mangle_params> for an explanation of this behavior.
923 my( $self, $args, $behavior) = @_;
925 carp( 'No arguments passed to uri_with()' ) unless $args;
928 if((ref($behavior) eq 'HASH') && defined($behavior->{mode}) && ($behavior->{mode} eq 'append')) {
932 my $params = $self->mangle_params($args, $append);
934 my $uri = $self->uri->clone;
935 $uri->query_form($params);
940 =head2 $req->remote_user
942 Returns the value of the C<REMOTE_USER> environment variable.
944 =head2 $req->user_agent
946 Shortcut to $req->headers->user_agent. Returns the user agent (browser)
951 Returns a psgix.io bidirectional socket, if your server supports one. Used for
952 when you want to jailbreak out of PSGI and handle bidirectional client server
953 communication manually, such as when you are using cometd or websockets.
957 You should never need to call these yourself in application code,
958 however they are useful if extending Catalyst by applying a request role.
960 =head2 $self->prepare_headers()
962 Sets up the C<< $res->headers >> accessor.
964 =head2 $self->prepare_body()
966 Sets up the body using L<HTTP::Body>
968 =head2 $self->prepare_body_chunk()
970 Add a chunk to the request body.
972 =head2 $self->prepare_body_parameters()
974 Sets up parameters from body.
976 =head2 $self->prepare_cookies()
978 Parse cookies from header. Sets up a L<CGI::Simple::Cookie> object.
980 =head2 $self->prepare_connection()
982 Sets up various fields in the request like the local and remote addresses,
983 request method, hostname requested etc.
985 =head2 $self->prepare_parameters()
987 Ensures that the body has been parsed, then builds the parameters, which are
988 combined from those in the request and those in the body.
990 If parameters have already been set will clear the parameters and build them again.
999 Catalyst Contributors, see Catalyst.pm
1003 This library is free software. You can redistribute it and/or modify
1004 it under the same terms as Perl itself.
1008 __PACKAGE__->meta->make_immutable;