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";
107 # Amount of data to read from input on each pass
108 our $CHUNKSIZE = 64 * 1024;
111 my ($self, $maxlength) = @_;
112 my $remaining = $self->_read_length - $self->_read_position;
113 $maxlength ||= $CHUNKSIZE;
115 # Are we done reading?
116 if ( $remaining <= 0 ) {
120 my $readlen = ( $remaining > $maxlength ) ? $maxlength : $remaining;
121 my $rc = $self->read_chunk( my $buffer, $readlen );
123 if (0 == $rc) { # Nothing more to read even though Content-Length
124 # said there should be.
127 $self->_set_read_position( $self->_read_position + $rc );
131 Catalyst::Exception->throw(
132 message => "Unknown error reading input: $!" );
138 return $self->env->{'psgi.input'}->read(@_);
141 has body_parameters => (
145 builder => 'prepare_body_parameters',
151 default => sub { {} },
157 builder => '_build_parameters',
158 clearer => '_clear_parameters',
162 # - Can we lose the before modifiers which just call prepare_body ?
163 # they are wasteful, slow us down and feel cluttery.
165 # Can we make _body an attribute, have the rest of
166 # these lazy build from there and kill all the direct hash access
167 # in Catalyst.pm and Engine.pm?
169 sub prepare_parameters {
171 $self->_clear_parameters;
172 return $self->parameters;
177 sub _build_parameters {
180 my $body_parameters = $self->body_parameters;
181 my $query_parameters = $self->query_parameters;
182 # We copy, no references
183 foreach my $name (keys %$query_parameters) {
184 my $param = $query_parameters->{$name};
185 $parameters->{$name} = ref $param eq 'ARRAY' ? [ @$param ] : $param;
188 # Merge query and body parameters
189 foreach my $name (keys %$body_parameters) {
190 my $param = $body_parameters->{$name};
191 my @values = ref $param eq 'ARRAY' ? @$param : ($param);
192 if ( my $existing = $parameters->{$name} ) {
193 unshift(@values, (ref $existing eq 'ARRAY' ? @$existing : $existing));
195 $parameters->{$name} = @values > 1 ? \@values : $values[0];
202 predicate => '_has_uploadtmp',
208 if ( my $length = $self->_read_length ) {
209 unless ( $self->_body ) {
210 my $type = $self->header('Content-Type');
211 $self->_body(HTTP::Body->new( $type, $length ));
212 $self->_body->cleanup(1); # Make extra sure!
213 $self->_body->tmpdir( $self->_uploadtmp )
214 if $self->_has_uploadtmp;
217 # Check for definedness as you could read '0'
218 while ( defined ( my $buffer = $self->read() ) ) {
219 $self->prepare_body_chunk($buffer);
222 # paranoia against wrong Content-Length header
223 my $remaining = $length - $self->_read_position;
224 if ( $remaining > 0 ) {
225 Catalyst::Exception->throw(
226 "Wrong Content-Length value: $length" );
230 # Defined but will cause all body code to be skipped
235 sub prepare_body_chunk {
236 my ( $self, $chunk ) = @_;
238 $self->_body->add($chunk);
241 sub prepare_body_parameters {
244 $self->prepare_body if ! $self->_has_body;
245 return {} unless $self->_body;
247 return $self->_body->param;
250 sub prepare_connection {
253 my $env = $self->env;
255 $self->address( $env->{REMOTE_ADDR} );
256 $self->hostname( $env->{REMOTE_HOST} )
257 if exists $env->{REMOTE_HOST};
258 $self->protocol( $env->{SERVER_PROTOCOL} );
259 $self->remote_user( $env->{REMOTE_USER} );
260 $self->method( $env->{REQUEST_METHOD} );
261 $self->secure( $env->{'psgi.url_scheme'} eq 'https' ? 1 : 0 );
264 # XXX - FIXME - method is here now, move this crap...
265 around parameters => sub {
266 my ($orig, $self, $params) = @_;
268 if ( !ref $params ) {
270 "Attempt to retrieve '$params' with req->params(), " .
271 "you probably meant to call req->param('$params')"
275 return $self->$orig($params);
286 return $self->path if $self->has_uri;
291 is => 'rw', clearer => '_clear_body', predicate => '_has_body',
293 # Eugh, ugly. Should just be able to rename accessor methods to 'body'
294 # and provide a custom reader..
297 $self->prepare_body unless ! $self->_has_body;
298 croak 'body is a reader' if scalar @_;
299 return blessed $self->_body ? $self->_body->body : $self->_body;
308 gethostbyaddr( inet_aton( $self->address ), AF_INET ) || $self->address
312 has _path => ( is => 'rw', predicate => '_has_path', clearer => '_clear_path' );
314 sub args { shift->arguments(@_) }
315 sub body_params { shift->body_parameters(@_) }
316 sub input { shift->body(@_) }
317 sub params { shift->parameters(@_) }
318 sub query_params { shift->query_parameters(@_) }
319 sub path_info { shift->path(@_) }
321 =for stopwords param params
325 Catalyst::Request - provides information about the current client request
330 $req->address eq "127.0.0.1";
335 $req->body_parameters;
336 $req->content_encoding;
337 $req->content_length;
345 $req->query_keywords;
353 $req->query_parameters;
364 See also L<Catalyst>, L<Catalyst::Request::Upload>.
368 This is the Catalyst Request class, which provides an interface to data for the
369 current client request. The request object is prepared by L<Catalyst::Engine>,
370 thus hiding the details of the particular engine implementation.
376 Returns the IP address of the client.
378 =head2 $req->arguments
380 Returns a reference to an array containing the arguments.
382 print $c->request->arguments->[0];
384 For example, if your action was
386 package MyApp::Controller::Foo;
392 and the URI for the request was C<http://.../foo/moose/bah>, the string C<bah>
393 would be the first and only argument.
395 Arguments get automatically URI-unescaped for you.
399 Shortcut for L</arguments>.
403 Contains the URI base. This will always have a trailing slash. Note that the
404 URI scheme (e.g., http vs. https) must be determined through heuristics;
405 depending on your server configuration, it may be incorrect. See $req->secure
408 If your application was queried with the URI
409 C<http://localhost:3000/some/path> then C<base> is C<http://localhost:3000/>.
413 Returns the message body of the request, as returned by L<HTTP::Body>: a string,
414 unless Content-Type is C<application/x-www-form-urlencoded>, C<text/xml>, or
415 C<multipart/form-data>, in which case a L<File::Temp> object is returned.
417 =head2 $req->body_parameters
419 Returns a reference to a hash containing body (POST) parameters. Values can
420 be either a scalar or an arrayref containing scalars.
422 print $c->request->body_parameters->{field};
423 print $c->request->body_parameters->{field}->[0];
425 These are the parameters from the POST part of the request, if any.
427 =head2 $req->body_params
429 Shortcut for body_parameters.
431 =head2 $req->content_encoding
433 Shortcut for $req->headers->content_encoding.
435 =head2 $req->content_length
437 Shortcut for $req->headers->content_length.
439 =head2 $req->content_type
441 Shortcut for $req->headers->content_type.
445 A convenient method to access $req->cookies.
447 $cookie = $c->request->cookie('name');
448 @cookies = $c->request->cookie;
456 return keys %{ $self->cookies };
463 unless ( exists $self->cookies->{$name} ) {
467 return $self->cookies->{$name};
473 Returns a reference to a hash containing the cookies.
475 print $c->request->cookies->{mycookie}->value;
477 The cookies in the hash are indexed by name, and the values are L<CGI::Simple::Cookie>
482 Shortcut for $req->headers->header.
486 Returns an L<HTTP::Headers> object containing the headers for the current request.
488 print $c->request->headers->header('X-Catalyst');
490 =head2 $req->hostname
492 Returns the hostname of the client. Use C<< $req->uri->host >> to get the hostname of the server.
496 Alias for $req->body.
498 =head2 $req->query_keywords
500 Contains the keywords portion of a query string, when no '=' signs are
503 http://localhost/path?some+keywords
505 $c->request->query_keywords will contain 'some keywords'
509 This contains the matching part of a Regex action. Otherwise
510 it returns the same as 'action', except for default actions,
511 which return an empty string.
515 Contains the request method (C<GET>, C<POST>, C<HEAD>, etc).
519 Returns GET and POST parameters with a CGI.pm-compatible param method. This
520 is an alternative method for accessing parameters in $c->req->parameters.
522 $value = $c->request->param( 'foo' );
523 @values = $c->request->param( 'foo' );
524 @params = $c->request->param;
526 Like L<CGI>, and B<unlike> earlier versions of Catalyst, passing multiple
527 arguments to this method, like this:
529 $c->request->param( 'foo', 'bar', 'gorch', 'quxx' );
531 will set the parameter C<foo> to the multiple values C<bar>, C<gorch> and
532 C<quxx>. Previously this would have added C<bar> as another value to C<foo>
533 (creating it if it didn't exist before), and C<quxx> as another value for
536 B<NOTE> this is considered a legacy interface and care should be taken when
537 using it. C<< scalar $c->req->param( 'foo' ) >> will return only the first
538 C<foo> param even if multiple are present; C<< $c->req->param( 'foo' ) >> will
539 return a list of as many are present, which can have unexpected consequences
540 when writing code of the form:
544 baz => $c->req->param( 'baz' ),
547 If multiple C<baz> parameters are provided this code might corrupt data or
548 cause a hash initialization error. For a more straightforward interface see
549 C<< $c->req->parameters >>.
557 return keys %{ $self->parameters };
564 unless ( exists $self->parameters->{$param} ) {
565 return wantarray ? () : undef;
568 if ( ref $self->parameters->{$param} eq 'ARRAY' ) {
570 ? @{ $self->parameters->{$param} }
571 : $self->parameters->{$param}->[0];
575 ? ( $self->parameters->{$param} )
576 : $self->parameters->{$param};
581 $self->parameters->{$field} = [@_];
585 =head2 $req->parameters
587 Returns a reference to a hash containing GET and POST parameters. Values can
588 be either a scalar or an arrayref containing scalars.
590 print $c->request->parameters->{field};
591 print $c->request->parameters->{field}->[0];
593 This is the combination of C<query_parameters> and C<body_parameters>.
597 Shortcut for $req->parameters.
601 Returns the path, i.e. the part of the URI after $req->base, for the current request.
603 http://localhost/path/foo
605 $c->request->path will contain 'path/foo'
607 =head2 $req->path_info
609 Alias for path, added for compatibility with L<CGI>.
614 my ( $self, @params ) = @_;
617 $self->uri->path(@params);
620 elsif ( $self->_has_path ) {
624 my $path = $self->uri->path;
625 my $location = $self->base->path;
626 $path =~ s/^(\Q$location\E)?//;
634 =head2 $req->protocol
636 Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.
638 =head2 $req->query_parameters
640 =head2 $req->query_params
642 Returns a reference to a hash containing query string (GET) parameters. Values can
643 be either a scalar or an arrayref containing scalars.
645 print $c->request->query_parameters->{field};
646 print $c->request->query_parameters->{field}->[0];
648 =head2 $req->read( [$maxlength] )
650 Reads a chunk of data from the request body. This method is intended to be
651 used in a while loop, reading $maxlength bytes on every call. $maxlength
652 defaults to the size of the request if not specified.
654 =head2 $req->read_chunk(\$buff, $max)
658 You have to set MyApp->config(parse_on_demand => 1) to use this directly.
662 Shortcut for $req->headers->referer. Returns the referring page.
666 Returns true or false, indicating whether the connection is secure
667 (https). The reliability of $req->secure may depend on your server
668 configuration; Catalyst relies on PSGI to determine whether or not a
669 request is secure (Catalyst looks at psgi.url_scheme), and different
670 PSGI servers may make this determination in different ways (as by
671 directly passing along information from the server, interpreting any of
672 several HTTP headers, or using heuristics of their own).
674 =head2 $req->captures
676 Returns a reference to an array containing captured args from chained
677 actions or regex captures.
679 my @captures = @{ $c->request->captures };
683 A convenient method to access $req->uploads.
685 $upload = $c->request->upload('field');
686 @uploads = $c->request->upload('field');
687 @fields = $c->request->upload;
689 for my $upload ( $c->request->upload('field') ) {
690 print $upload->filename;
699 return keys %{ $self->uploads };
706 unless ( exists $self->uploads->{$upload} ) {
707 return wantarray ? () : undef;
710 if ( ref $self->uploads->{$upload} eq 'ARRAY' ) {
712 ? @{ $self->uploads->{$upload} }
713 : $self->uploads->{$upload}->[0];
717 ? ( $self->uploads->{$upload} )
718 : $self->uploads->{$upload};
724 while ( my ( $field, $upload ) = splice( @_, 0, 2 ) ) {
726 if ( exists $self->uploads->{$field} ) {
727 for ( $self->uploads->{$field} ) {
728 $_ = [$_] unless ref($_) eq "ARRAY";
729 push( @$_, $upload );
733 $self->uploads->{$field} = $upload;
741 Returns a reference to a hash containing uploads. Values can be either a
742 L<Catalyst::Request::Upload> object, or an arrayref of
743 L<Catalyst::Request::Upload> objects.
745 my $upload = $c->request->uploads->{field};
746 my $upload = $c->request->uploads->{field}->[0];
750 Returns a L<URI> object for the current request. Stringifies to the URI text.
752 =head2 $req->mangle_params( { key => 'value' }, $appendmode);
754 Returns a hashref of parameters stemming from the current request's params,
755 plus the ones supplied. Keys for which no current param exists will be
756 added, keys with undefined values will be removed and keys with existing
757 params will be replaced. Note that you can supply a true value as the final
758 argument to change behavior with regards to existing parameters, appending
759 values rather than replacing them.
763 # URI query params foo=1
764 my $hashref = $req->mangle_params({ foo => 2 });
765 # Result is query params of foo=2
769 # URI query params foo=1
770 my $hashref = $req->mangle_params({ foo => 2 }, 1);
771 # Result is query params of foo=1&foo=2
773 This is the code behind C<uri_with>.
778 my ($self, $args, $append) = @_;
780 carp('No arguments passed to mangle_params()') unless $args;
782 foreach my $value ( values %$args ) {
783 next unless defined $value;
784 for ( ref $value eq 'ARRAY' ? @$value : $value ) {
786 utf8::encode( $_ ) if utf8::is_utf8($_);
790 my %params = %{ $self->uri->query_form_hash };
791 foreach my $key (keys %{ $args }) {
792 my $val = $args->{$key};
795 if($append && exists($params{$key})) {
797 # This little bit of heaven handles appending a new value onto
798 # an existing one regardless if the existing value is an array
799 # or not, and regardless if the new value is an array or not
801 ref($params{$key}) eq 'ARRAY' ? @{ $params{$key} } : $params{$key},
802 ref($val) eq 'ARRAY' ? @{ $val } : $val
806 $params{$key} = $val;
810 # If the param wasn't defined then we delete it.
811 delete($params{$key});
819 =head2 $req->uri_with( { key => 'value' } );
821 Returns a rewritten URI object for the current request. Key/value pairs
822 passed in will override existing parameters. You can remove an existing
823 parameter by passing in an undef value. Unmodified pairs will be
826 You may also pass an optional second parameter that puts C<uri_with> into
829 $req->uri_with( { key => 'value' }, { mode => 'append' } );
831 See C<mangle_params> for an explanation of this behavior.
836 my( $self, $args, $behavior) = @_;
838 carp( 'No arguments passed to uri_with()' ) unless $args;
841 if((ref($behavior) eq 'HASH') && defined($behavior->{mode}) && ($behavior->{mode} eq 'append')) {
845 my $params = $self->mangle_params($args, $append);
847 my $uri = $self->uri->clone;
848 $uri->query_form($params);
853 =head2 $req->remote_user
855 Returns the value of the C<REMOTE_USER> environment variable.
857 =head2 $req->user_agent
859 Shortcut to $req->headers->user_agent. Returns the user agent (browser)
864 Returns a psgix.io bidirectional socket, if your server supports one. Used for
865 when you want to jailbreak out of PSGI and handle bidirectional client server
866 communication manually, such as when you are using cometd or websockets.
870 You should never need to call these yourself in application code,
871 however they are useful if extending Catalyst by applying a request role.
873 =head2 $self->prepare_headers()
875 Sets up the C<< $res->headers >> accessor.
877 =head2 $self->prepare_body()
879 Sets up the body using L<HTTP::Body>
881 =head2 $self->prepare_body_chunk()
883 Add a chunk to the request body.
885 =head2 $self->prepare_body_parameters()
887 Sets up parameters from body.
889 =head2 $self->prepare_cookies()
891 Parse cookies from header. Sets up a L<CGI::Simple::Cookie> object.
893 =head2 $self->prepare_connection()
895 Sets up various fields in the request like the local and remote addresses,
896 request method, hostname requested etc.
898 =head2 $self->prepare_parameters()
900 Ensures that the body has been parsed, then builds the parameters, which are
901 combined from those in the request and those in the body.
903 If parameters have already been set will clear the parameters and build them again.
912 Catalyst Contributors, see Catalyst.pm
916 This library is free software. You can redistribute it and/or modify
917 it under the same terms as Perl itself.
921 __PACKAGE__->meta->make_immutable;