1 package Catalyst::Request;
3 use IO::Socket qw[AF_INET inet_aton];
13 use namespace::clean -except => 'meta';
15 with 'MooseX::Emulate::Class::Accessor::Fast';
17 has env => (is => 'ro', writer => '_set_env');
18 # XXX Deprecated crap here - warn?
19 has action => (is => 'rw');
20 # XXX: Deprecated in docs ages ago (2006), deprecated with warning in 5.8000 due
21 # to confusion between Engines and Plugin::Authentication. Remove in 5.8100?
22 has user => (is => 'rw');
23 sub snippets { shift->captures(@_) }
25 has _read_position => (
26 # FIXME: work around Moose bug RT#75367
29 writer => '_set_read_position',
33 # FIXME: work around Moose bug RT#75367
38 $self->header('Content-Length') || 0;
43 has address => (is => 'rw');
44 has arguments => (is => 'rw', default => sub { [] });
45 has cookies => (is => 'ro', builder => 'prepare_cookies', lazy => 1);
50 if ( my $header = $self->header('Cookie') ) {
51 return { CGI::Simple::Cookie->parse($header) };
56 has query_keywords => (is => 'rw');
57 has match => (is => 'rw');
58 has method => (is => 'rw');
59 has protocol => (is => 'rw');
60 has query_parameters => (is => 'rw', default => sub { {} });
61 has secure => (is => 'rw', default => 0);
62 has captures => (is => 'rw', default => sub { [] });
63 has uri => (is => 'rw', predicate => 'has_uri');
64 has remote_user => (is => 'rw');
67 isa => 'HTTP::Headers',
68 handles => [qw(content_encoding content_length content_type header referer user_agent)],
69 builder => 'prepare_headers',
77 my $headers = HTTP::Headers->new();
79 for my $header (keys %{ $env }) {
80 next unless $header =~ /^(HTTP|CONTENT|COOKIE)/i;
81 (my $field = $header) =~ s/^HTTPS?_//;
83 $headers->header($field => $env->{$header});
96 predicate=>'has_io_fh',
98 builder=>'_build_io_fh');
102 return $self->env->{'psgix.io'}
103 || die "Your Server does not support psgix.io";
108 predicate=>'has_body_fh',
110 builder=>'_build_body_fh');
113 (my $input_fh = shift->env->{'psgi.input'})->seek(0, 0);
117 # Amount of data to read from input on each pass
118 our $CHUNKSIZE = 64 * 1024;
121 my ($self, $maxlength) = @_;
122 my $remaining = $self->_read_length - $self->_read_position;
123 $maxlength ||= $CHUNKSIZE;
125 # Are we done reading?
126 if ( $remaining <= 0 ) {
130 my $readlen = ( $remaining > $maxlength ) ? $maxlength : $remaining;
131 my $rc = $self->read_chunk( my $buffer, $readlen );
133 if (0 == $rc) { # Nothing more to read even though Content-Length
134 # said there should be.
137 $self->_set_read_position( $self->_read_position + $rc );
141 Catalyst::Exception->throw(
142 message => "Unknown error reading input: $!" );
148 return $self->env->{'psgi.input'}->read(@_);
151 has body_parameters => (
155 builder => 'prepare_body_parameters',
161 default => sub { {} },
167 builder => '_build_parameters',
168 clearer => '_clear_parameters',
172 # - Can we lose the before modifiers which just call prepare_body ?
173 # they are wasteful, slow us down and feel cluttery.
175 # Can we make _body an attribute, have the rest of
176 # these lazy build from there and kill all the direct hash access
177 # in Catalyst.pm and Engine.pm?
179 sub prepare_parameters {
181 $self->_clear_parameters;
182 return $self->parameters;
187 sub _build_parameters {
190 my $body_parameters = $self->body_parameters;
191 my $query_parameters = $self->query_parameters;
192 # We copy, no references
193 foreach my $name (keys %$query_parameters) {
194 my $param = $query_parameters->{$name};
195 $parameters->{$name} = ref $param eq 'ARRAY' ? [ @$param ] : $param;
198 # Merge query and body parameters
199 foreach my $name (keys %$body_parameters) {
200 my $param = $body_parameters->{$name};
201 my @values = ref $param eq 'ARRAY' ? @$param : ($param);
202 if ( my $existing = $parameters->{$name} ) {
203 unshift(@values, (ref $existing eq 'ARRAY' ? @$existing : $existing));
205 $parameters->{$name} = @values > 1 ? \@values : $values[0];
212 predicate => '_has_uploadtmp',
218 if ( my $length = $self->_read_length ) {
219 unless ( $self->_body ) {
220 my $type = $self->header('Content-Type');
221 $self->_body(HTTP::Body->new( $type, $length ));
222 $self->_body->cleanup(1); # Make extra sure!
223 $self->_body->tmpdir( $self->_uploadtmp )
224 if $self->_has_uploadtmp;
227 # Check for definedness as you could read '0'
228 while ( defined ( my $buffer = $self->read() ) ) {
229 $self->prepare_body_chunk($buffer);
232 # paranoia against wrong Content-Length header
233 my $remaining = $length - $self->_read_position;
234 if ( $remaining > 0 ) {
235 Catalyst::Exception->throw(
236 "Wrong Content-Length value: $length" );
240 # Defined but will cause all body code to be skipped
245 sub prepare_body_chunk {
246 my ( $self, $chunk ) = @_;
248 $self->_body->add($chunk);
251 sub prepare_body_parameters {
254 $self->prepare_body if ! $self->_has_body;
255 return {} unless $self->_body;
257 return $self->_body->param;
260 sub prepare_connection {
263 my $env = $self->env;
265 $self->address( $env->{REMOTE_ADDR} );
266 $self->hostname( $env->{REMOTE_HOST} )
267 if exists $env->{REMOTE_HOST};
268 $self->protocol( $env->{SERVER_PROTOCOL} );
269 $self->remote_user( $env->{REMOTE_USER} );
270 $self->method( $env->{REQUEST_METHOD} );
271 $self->secure( $env->{'psgi.url_scheme'} eq 'https' ? 1 : 0 );
274 # XXX - FIXME - method is here now, move this crap...
275 around parameters => sub {
276 my ($orig, $self, $params) = @_;
278 if ( !ref $params ) {
280 "Attempt to retrieve '$params' with req->params(), " .
281 "you probably meant to call req->param('$params')"
285 return $self->$orig($params);
296 return $self->path if $self->has_uri;
301 is => 'rw', clearer => '_clear_body', predicate => '_has_body',
303 # Eugh, ugly. Should just be able to rename accessor methods to 'body'
304 # and provide a custom reader..
307 $self->prepare_body unless ! $self->_has_body;
308 croak 'body is a reader' if scalar @_;
309 return blessed $self->_body ? $self->_body->body : $self->_body;
318 gethostbyaddr( inet_aton( $self->address ), AF_INET ) || $self->address
322 has _path => ( is => 'rw', predicate => '_has_path', clearer => '_clear_path' );
324 sub args { shift->arguments(@_) }
325 sub body_params { shift->body_parameters(@_) }
326 sub input { shift->body(@_) }
327 sub params { shift->parameters(@_) }
328 sub query_params { shift->query_parameters(@_) }
329 sub path_info { shift->path(@_) }
331 =for stopwords param params
335 Catalyst::Request - provides information about the current client request
340 $req->address eq "127.0.0.1";
345 $req->body_parameters;
346 $req->content_encoding;
347 $req->content_length;
355 $req->query_keywords;
363 $req->query_parameters;
374 See also L<Catalyst>, L<Catalyst::Request::Upload>.
378 This is the Catalyst Request class, which provides an interface to data for the
379 current client request. The request object is prepared by L<Catalyst::Engine>,
380 thus hiding the details of the particular engine implementation.
386 Returns the IP address of the client.
388 =head2 $req->arguments
390 Returns a reference to an array containing the arguments.
392 print $c->request->arguments->[0];
394 For example, if your action was
396 package MyApp::Controller::Foo;
402 and the URI for the request was C<http://.../foo/moose/bah>, the string C<bah>
403 would be the first and only argument.
405 Arguments get automatically URI-unescaped for you.
409 Shortcut for L</arguments>.
413 Contains the URI base. This will always have a trailing slash. Note that the
414 URI scheme (e.g., http vs. https) must be determined through heuristics;
415 depending on your server configuration, it may be incorrect. See $req->secure
418 If your application was queried with the URI
419 C<http://localhost:3000/some/path> then C<base> is C<http://localhost:3000/>.
423 Returns the message body of the request, as returned by L<HTTP::Body>: a string,
424 unless Content-Type is C<application/x-www-form-urlencoded>, C<text/xml>, or
425 C<multipart/form-data>, in which case a L<File::Temp> object is returned.
427 =head2 $req->body_parameters
429 Returns a reference to a hash containing body (POST) parameters. Values can
430 be either a scalar or an arrayref containing scalars.
432 print $c->request->body_parameters->{field};
433 print $c->request->body_parameters->{field}->[0];
435 These are the parameters from the POST part of the request, if any.
437 =head2 $req->body_params
439 Shortcut for body_parameters.
441 =head2 $req->content_encoding
443 Shortcut for $req->headers->content_encoding.
445 =head2 $req->content_length
447 Shortcut for $req->headers->content_length.
449 =head2 $req->content_type
451 Shortcut for $req->headers->content_type.
455 A convenient method to access $req->cookies.
457 $cookie = $c->request->cookie('name');
458 @cookies = $c->request->cookie;
466 return keys %{ $self->cookies };
473 unless ( exists $self->cookies->{$name} ) {
477 return $self->cookies->{$name};
483 Returns a reference to a hash containing the cookies.
485 print $c->request->cookies->{mycookie}->value;
487 The cookies in the hash are indexed by name, and the values are L<CGI::Simple::Cookie>
492 Shortcut for $req->headers->header.
496 Returns an L<HTTP::Headers> object containing the headers for the current request.
498 print $c->request->headers->header('X-Catalyst');
500 =head2 $req->hostname
502 Returns the hostname of the client. Use C<< $req->uri->host >> to get the hostname of the server.
506 Alias for $req->body.
508 =head2 $req->query_keywords
510 Contains the keywords portion of a query string, when no '=' signs are
513 http://localhost/path?some+keywords
515 $c->request->query_keywords will contain 'some keywords'
519 This contains the matching part of a Regex action. Otherwise
520 it returns the same as 'action', except for default actions,
521 which return an empty string.
525 Contains the request method (C<GET>, C<POST>, C<HEAD>, etc).
529 Returns GET and POST parameters with a CGI.pm-compatible param method. This
530 is an alternative method for accessing parameters in $c->req->parameters.
532 $value = $c->request->param( 'foo' );
533 @values = $c->request->param( 'foo' );
534 @params = $c->request->param;
536 Like L<CGI>, and B<unlike> earlier versions of Catalyst, passing multiple
537 arguments to this method, like this:
539 $c->request->param( 'foo', 'bar', 'gorch', 'quxx' );
541 will set the parameter C<foo> to the multiple values C<bar>, C<gorch> and
542 C<quxx>. Previously this would have added C<bar> as another value to C<foo>
543 (creating it if it didn't exist before), and C<quxx> as another value for
546 B<NOTE> this is considered a legacy interface and care should be taken when
547 using it. C<< scalar $c->req->param( 'foo' ) >> will return only the first
548 C<foo> param even if multiple are present; C<< $c->req->param( 'foo' ) >> will
549 return a list of as many are present, which can have unexpected consequences
550 when writing code of the form:
554 baz => $c->req->param( 'baz' ),
557 If multiple C<baz> parameters are provided this code might corrupt data or
558 cause a hash initialization error. For a more straightforward interface see
559 C<< $c->req->parameters >>.
567 return keys %{ $self->parameters };
574 unless ( exists $self->parameters->{$param} ) {
575 return wantarray ? () : undef;
578 if ( ref $self->parameters->{$param} eq 'ARRAY' ) {
580 ? @{ $self->parameters->{$param} }
581 : $self->parameters->{$param}->[0];
585 ? ( $self->parameters->{$param} )
586 : $self->parameters->{$param};
591 $self->parameters->{$field} = [@_];
595 =head2 $req->parameters
597 Returns a reference to a hash containing GET and POST parameters. Values can
598 be either a scalar or an arrayref containing scalars.
600 print $c->request->parameters->{field};
601 print $c->request->parameters->{field}->[0];
603 This is the combination of C<query_parameters> and C<body_parameters>.
607 Shortcut for $req->parameters.
611 Returns the path, i.e. the part of the URI after $req->base, for the current request.
613 http://localhost/path/foo
615 $c->request->path will contain 'path/foo'
617 =head2 $req->path_info
619 Alias for path, added for compatibility with L<CGI>.
624 my ( $self, @params ) = @_;
627 $self->uri->path(@params);
630 elsif ( $self->_has_path ) {
634 my $path = $self->uri->path;
635 my $location = $self->base->path;
636 $path =~ s/^(\Q$location\E)?//;
644 =head2 $req->protocol
646 Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.
648 =head2 $req->query_parameters
650 =head2 $req->query_params
652 Returns a reference to a hash containing query string (GET) parameters. Values can
653 be either a scalar or an arrayref containing scalars.
655 print $c->request->query_parameters->{field};
656 print $c->request->query_parameters->{field}->[0];
658 =head2 $req->read( [$maxlength] )
660 Reads a chunk of data from the request body. This method is intended to be
661 used in a while loop, reading $maxlength bytes on every call. $maxlength
662 defaults to the size of the request if not specified.
664 =head2 $req->read_chunk(\$buff, $max)
668 You have to set MyApp->config(parse_on_demand => 1) to use this directly.
672 Shortcut for $req->headers->referer. Returns the referring page.
676 Returns true or false, indicating whether the connection is secure
677 (https). The reliability of $req->secure may depend on your server
678 configuration; Catalyst relies on PSGI to determine whether or not a
679 request is secure (Catalyst looks at psgi.url_scheme), and different
680 PSGI servers may make this determination in different ways (as by
681 directly passing along information from the server, interpreting any of
682 several HTTP headers, or using heuristics of their own).
684 =head2 $req->captures
686 Returns a reference to an array containing captured args from chained
687 actions or regex captures.
689 my @captures = @{ $c->request->captures };
693 A convenient method to access $req->uploads.
695 $upload = $c->request->upload('field');
696 @uploads = $c->request->upload('field');
697 @fields = $c->request->upload;
699 for my $upload ( $c->request->upload('field') ) {
700 print $upload->filename;
709 return keys %{ $self->uploads };
716 unless ( exists $self->uploads->{$upload} ) {
717 return wantarray ? () : undef;
720 if ( ref $self->uploads->{$upload} eq 'ARRAY' ) {
722 ? @{ $self->uploads->{$upload} }
723 : $self->uploads->{$upload}->[0];
727 ? ( $self->uploads->{$upload} )
728 : $self->uploads->{$upload};
734 while ( my ( $field, $upload ) = splice( @_, 0, 2 ) ) {
736 if ( exists $self->uploads->{$field} ) {
737 for ( $self->uploads->{$field} ) {
738 $_ = [$_] unless ref($_) eq "ARRAY";
739 push( @$_, $upload );
743 $self->uploads->{$field} = $upload;
751 Returns a reference to a hash containing uploads. Values can be either a
752 L<Catalyst::Request::Upload> object, or an arrayref of
753 L<Catalyst::Request::Upload> objects.
755 my $upload = $c->request->uploads->{field};
756 my $upload = $c->request->uploads->{field}->[0];
760 Returns a L<URI> object for the current request. Stringifies to the URI text.
762 =head2 $req->mangle_params( { key => 'value' }, $appendmode);
764 Returns a hashref of parameters stemming from the current request's params,
765 plus the ones supplied. Keys for which no current param exists will be
766 added, keys with undefined values will be removed and keys with existing
767 params will be replaced. Note that you can supply a true value as the final
768 argument to change behavior with regards to existing parameters, appending
769 values rather than replacing them.
773 # URI query params foo=1
774 my $hashref = $req->mangle_params({ foo => 2 });
775 # Result is query params of foo=2
779 # URI query params foo=1
780 my $hashref = $req->mangle_params({ foo => 2 }, 1);
781 # Result is query params of foo=1&foo=2
783 This is the code behind C<uri_with>.
788 my ($self, $args, $append) = @_;
790 carp('No arguments passed to mangle_params()') unless $args;
792 foreach my $value ( values %$args ) {
793 next unless defined $value;
794 for ( ref $value eq 'ARRAY' ? @$value : $value ) {
796 utf8::encode( $_ ) if utf8::is_utf8($_);
800 my %params = %{ $self->uri->query_form_hash };
801 foreach my $key (keys %{ $args }) {
802 my $val = $args->{$key};
805 if($append && exists($params{$key})) {
807 # This little bit of heaven handles appending a new value onto
808 # an existing one regardless if the existing value is an array
809 # or not, and regardless if the new value is an array or not
811 ref($params{$key}) eq 'ARRAY' ? @{ $params{$key} } : $params{$key},
812 ref($val) eq 'ARRAY' ? @{ $val } : $val
816 $params{$key} = $val;
820 # If the param wasn't defined then we delete it.
821 delete($params{$key});
829 =head2 $req->uri_with( { key => 'value' } );
831 Returns a rewritten URI object for the current request. Key/value pairs
832 passed in will override existing parameters. You can remove an existing
833 parameter by passing in an undef value. Unmodified pairs will be
836 You may also pass an optional second parameter that puts C<uri_with> into
839 $req->uri_with( { key => 'value' }, { mode => 'append' } );
841 See C<mangle_params> for an explanation of this behavior.
846 my( $self, $args, $behavior) = @_;
848 carp( 'No arguments passed to uri_with()' ) unless $args;
851 if((ref($behavior) eq 'HASH') && defined($behavior->{mode}) && ($behavior->{mode} eq 'append')) {
855 my $params = $self->mangle_params($args, $append);
857 my $uri = $self->uri->clone;
858 $uri->query_form($params);
863 =head2 $req->remote_user
865 Returns the value of the C<REMOTE_USER> environment variable.
867 =head2 $req->user_agent
869 Shortcut to $req->headers->user_agent. Returns the user agent (browser)
874 Returns a psgix.io bidirectional socket, if your server supports one. Used for
875 when you want to jailbreak out of PSGI and handle bidirectional client server
876 communication manually, such as when you are using cometd or websockets.
880 You should never need to call these yourself in application code,
881 however they are useful if extending Catalyst by applying a request role.
883 =head2 $self->prepare_headers()
885 Sets up the C<< $res->headers >> accessor.
887 =head2 $self->prepare_body()
889 Sets up the body using L<HTTP::Body>
891 =head2 $self->prepare_body_chunk()
893 Add a chunk to the request body.
895 =head2 $self->prepare_body_parameters()
897 Sets up parameters from body.
899 =head2 $self->prepare_cookies()
901 Parse cookies from header. Sets up a L<CGI::Simple::Cookie> object.
903 =head2 $self->prepare_connection()
905 Sets up various fields in the request like the local and remote addresses,
906 request method, hostname requested etc.
908 =head2 $self->prepare_parameters()
910 Ensures that the body has been parsed, then builds the parameters, which are
911 combined from those in the request and those in the body.
913 If parameters have already been set will clear the parameters and build them again.
922 Catalyst Contributors, see Catalyst.pm
926 This library is free software. You can redistribute it and/or modify
927 it under the same terms as Perl itself.
931 __PACKAGE__->meta->make_immutable;