12dff266210074441183964d83bdb8b5390ad9e9
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Request.pm
1 package Catalyst::Request;
2
3 use Socket qw( getaddrinfo getnameinfo AI_NUMERICHOST NIx_NOSERV );
4 use Carp;
5 use utf8;
6 use URI::http;
7 use URI::https;
8 use URI::QueryParam;
9 use HTTP::Headers;
10 use Stream::Buffered;
11 use Hash::MultiValue;
12 use Scalar::Util;
13 use HTTP::Body;
14 use Catalyst::Exception;
15 use Catalyst::Request::PartData;
16 use Moose;
17
18 use namespace::clean -except => 'meta';
19
20 with 'MooseX::Emulate::Class::Accessor::Fast';
21
22 has env => (is => 'ro', writer => '_set_env', predicate => '_has_env');
23 # XXX Deprecated crap here - warn?
24 has action => (is => 'rw');
25 # XXX: Deprecated in docs ages ago (2006), deprecated with warning in 5.8000 due
26 # to confusion between Engines and Plugin::Authentication. Remove in 5.8100?
27 has user => (is => 'rw');
28 sub snippets        { shift->captures(@_) }
29
30 has _read_position => (
31     # FIXME: work around Moose bug RT#75367
32     # init_arg => undef,
33     is => 'ro',
34     writer => '_set_read_position',
35     default => 0,
36 );
37 has _read_length => (
38     # FIXME: work around Moose bug RT#75367
39     # init_arg => undef,
40     is => 'ro',
41     default => sub {
42         my $self = shift;
43         $self->header('Content-Length') || 0;
44     },
45     lazy => 1,
46 );
47
48 has address => (is => 'rw');
49 has arguments => (is => 'rw', default => sub { [] });
50 has cookies => (is => 'ro', builder => 'prepare_cookies', lazy => 1);
51
52 sub prepare_cookies {
53     my ( $self ) = @_;
54
55     if ( my $header = $self->header('Cookie') ) {
56         return { CGI::Simple::Cookie->parse($header) };
57     }
58     {};
59 }
60
61 has query_keywords => (is => 'rw');
62 has match => (is => 'rw');
63 has method => (is => 'rw');
64 has protocol => (is => 'rw');
65 has query_parameters  => (is => 'rw', lazy=>1, default => sub { shift->_use_hash_multivalue ? Hash::MultiValue->new : +{} });
66 has secure => (is => 'rw', default => 0);
67 has captures => (is => 'rw', default => sub { [] });
68 has uri => (is => 'rw', predicate => 'has_uri');
69 has remote_user => (is => 'rw');
70 has headers => (
71   is      => 'rw',
72   isa     => 'HTTP::Headers',
73   handles => [qw(content_encoding content_length content_type header referer user_agent)],
74   builder => 'prepare_headers',
75   lazy => 1,
76 );
77
78 sub prepare_headers {
79     my ($self) = @_;
80
81     my $env = $self->env;
82     my $headers = HTTP::Headers->new();
83
84     for my $header (keys %{ $env }) {
85         next unless $header =~ /^(HTTP|CONTENT|COOKIE)/i;
86         (my $field = $header) =~ s/^HTTPS?_//;
87         $field =~ tr/_/-/;
88         $headers->header($field => $env->{$header});
89     }
90     return $headers;
91 }
92
93 has _log => (
94     is => 'ro',
95     weak_ref => 1,
96     required => 1,
97 );
98
99 has io_fh => (
100     is=>'ro',
101     predicate=>'_has_io_fh',
102     lazy=>1,
103     builder=>'_build_io_fh');
104
105 sub _build_io_fh {
106     my $self = shift;
107     return $self->env->{'psgix.io'}
108       || (
109         $self->env->{'net.async.http.server.req'} &&
110         $self->env->{'net.async.http.server.req'}->stream)   ## Until I can make ioasync cabal see the value of supportin psgix.io (jnap)
111       || die "Your Server does not support psgix.io";
112 };
113
114 has data_handlers => ( is=>'ro', isa=>'HashRef', default=>sub { +{} } );
115
116 has body_data => (
117     is=>'ro',
118     lazy=>1,
119     builder=>'_build_body_data');
120
121 sub _build_body_data {
122     my ($self) = @_;
123
124     # Not sure if these returns should not be exceptions...
125     my $content_type = $self->content_type || return;
126     return unless ($self->method eq 'POST' || $self->method eq 'PUT');
127
128     my ($match) = grep { $content_type =~/$_/i }
129       keys(%{$self->data_handlers});
130
131     if($match) {
132       my $fh = $self->body;
133       local $_ = $fh;
134       return $self->data_handlers->{$match}->($fh, $self);
135     } else { 
136       Catalyst::Exception->throw("$content_type is does not have an available data handler");
137     }
138 }
139
140 has _use_hash_multivalue => (
141     is=>'ro', 
142     required=>1, 
143     default=> sub {0});
144
145 # Amount of data to read from input on each pass
146 our $CHUNKSIZE = 64 * 1024;
147
148 sub read {
149     my ($self, $maxlength) = @_;
150     my $remaining = $self->_read_length - $self->_read_position;
151     $maxlength ||= $CHUNKSIZE;
152
153     # Are we done reading?
154     if ( $remaining <= 0 ) {
155         return;
156     }
157
158     my $readlen = ( $remaining > $maxlength ) ? $maxlength : $remaining;
159     my $rc = $self->read_chunk( my $buffer, $readlen );
160     if ( defined $rc ) {
161         if (0 == $rc) { # Nothing more to read even though Content-Length
162                         # said there should be.
163             return;
164         }
165         $self->_set_read_position( $self->_read_position + $rc );
166         return $buffer;
167     }
168     else {
169         Catalyst::Exception->throw(
170             message => "Unknown error reading input: $!" );
171     }
172 }
173
174 sub read_chunk {
175     my $self = shift;
176     return $self->env->{'psgi.input'}->read(@_);
177 }
178
179 has body_parameters => (
180   is => 'rw',
181   required => 1,
182   lazy => 1,
183   predicate => 'has_body_parameters',
184   builder => 'prepare_body_parameters',
185 );
186
187 has uploads => (
188   is => 'rw',
189   required => 1,
190   default => sub { {} },
191 );
192
193 has parameters => (
194     is => 'rw',
195     lazy => 1,
196     builder => '_build_parameters',
197     clearer => '_clear_parameters',
198 );
199
200 # TODO:
201 # - Can we lose the before modifiers which just call prepare_body ?
202 #   they are wasteful, slow us down and feel cluttery.
203
204 #  Can we make _body an attribute, have the rest of
205 #  these lazy build from there and kill all the direct hash access
206 #  in Catalyst.pm and Engine.pm?
207
208 sub prepare_parameters {
209     my ( $self ) = @_;
210     $self->_clear_parameters;
211     return $self->parameters;
212 }
213
214 sub _build_parameters {
215     my ( $self ) = @_;
216     my $parameters = {};
217     my $body_parameters = $self->body_parameters;
218     my $query_parameters = $self->query_parameters;
219
220     if($self->_use_hash_multivalue) {
221         return Hash::MultiValue->new($query_parameters->flatten, $body_parameters->flatten);
222     }
223
224     # We copy, no references
225     foreach my $name (keys %$query_parameters) {
226         my $param = $query_parameters->{$name};
227         $parameters->{$name} = ref $param eq 'ARRAY' ? [ @$param ] : $param;
228     }
229
230     # Merge query and body parameters
231     foreach my $name (keys %$body_parameters) {
232         my $param = $body_parameters->{$name};
233         my @values = ref $param eq 'ARRAY' ? @$param : ($param);
234         if ( my $existing = $parameters->{$name} ) {
235           unshift(@values, (ref $existing eq 'ARRAY' ? @$existing : $existing));
236         }
237         $parameters->{$name} = @values > 1 ? \@values : $values[0];
238     }
239     $parameters;
240 }
241
242 has _uploadtmp => (
243     is => 'ro',
244     predicate => '_has_uploadtmp',
245 );
246
247 sub prepare_body {
248     my ( $self ) = @_;
249
250     # If previously applied middleware created the HTTP::Body object, then we
251     # just use that one.  
252
253     if(my $plack_body = $self->_has_env ? $self->env->{'plack.request.http.body'} : undef) {
254         $self->_body($plack_body);
255         $self->_body->cleanup(1);
256         return;
257     }
258
259     # If there is nothing to read, set body to naught and return.  This
260     # will cause all body code to be skipped
261
262     return $self->_body(0) unless my $length = $self->_read_length;
263
264     # Unless the body has already been set, create it.  Not sure about this
265     # code, how else might it be set, but this was existing logic.
266
267     unless ($self->_body) {
268         my $type = $self->header('Content-Type');
269         $self->_body(HTTP::Body->new( $type, $length ));
270         $self->_body->cleanup(1);
271
272         # JNAP: I'm not sure this is doing what we expect, but it also doesn't
273         # seem to be hurting (seems ->_has_uploadtmp is true more than I would
274         # expect.
275
276         $self->_body->tmpdir( $self->_uploadtmp )
277           if $self->_has_uploadtmp;
278     }
279
280     # Ok if we get this far, we have to read psgi.input into the new body
281     # object.  Lets play nice with any plack app or other downstream, so
282     # we create a buffer unless one exists.
283      
284     my $stream_buffer;
285     if ($self->env->{'psgix.input.buffered'}) {
286         # Be paranoid about previous psgi middleware or apps that read the
287         # input but didn't return the buffer to the start.
288         $self->env->{'psgi.input'}->seek(0, 0);
289     } else {
290         $stream_buffer = Stream::Buffered->new($length);
291     }
292
293     # Check for definedness as you could read '0'
294     while ( defined ( my $chunk = $self->read() ) ) {
295         $self->prepare_body_chunk($chunk);
296         next unless $stream_buffer;
297
298         $stream_buffer->print($chunk)
299             || die sprintf "Failed to write %d bytes to psgi.input file: $!", length( $chunk );
300     }
301
302     # Ok, we read the body.  Lets play nice for any PSGI app down the pipe
303
304     if ($stream_buffer) {
305         $self->env->{'psgix.input.buffered'} = 1;
306         $self->env->{'psgi.input'} = $stream_buffer->rewind;
307     } else {
308         $self->env->{'psgi.input'}->seek(0, 0); # Reset the buffer for downstream middleware or apps
309     }
310
311     # paranoia against wrong Content-Length header
312     my $remaining = $length - $self->_read_position;
313     if ( $remaining > 0 ) {
314         Catalyst::Exception->throw("Wrong Content-Length value: $length" );
315     }
316 }
317
318 sub prepare_body_chunk {
319     my ( $self, $chunk ) = @_;
320
321     $self->_body->add($chunk);
322 }
323
324 sub prepare_body_parameters {
325     my ( $self, $c ) = @_;
326     return $self->body_parameters if $self->has_body_parameters;
327     $self->prepare_body if ! $self->_has_body;
328
329     unless($self->_body) {
330       my $return = $self->_use_hash_multivalue ? Hash::MultiValue->new : {};
331       $self->body_parameters($return);
332       return $return;
333     }
334
335     my $params;
336     my %part_data = %{$self->_body->part_data};
337     if(scalar %part_data && !$c->config->{skip_complex_post_part_handling}) {
338       foreach my $key (keys %part_data) {
339         my $proto_value = $part_data{$key};
340         my ($val, @extra) = (ref($proto_value)||'') eq 'ARRAY' ? @$proto_value : ($proto_value);
341
342         $key = $c->_handle_param_unicode_decoding($key)
343           if ($c and $c->encoding and !$c->config->{skip_body_param_unicode_decoding});
344
345         if(@extra) {
346           $params->{$key} = [map { Catalyst::Request::PartData->build_from_part_data($c, $_) } ($val,@extra)];
347         } else {
348           $params->{$key} = Catalyst::Request::PartData->build_from_part_data($c, $val);
349         }
350       }
351     } else {
352       $params = $self->_body->param;
353
354       # If we have an encoding configured (like UTF-8) in general we expect a client
355       # to POST with the encoding we fufilled the request in. Otherwise don't do any
356       # encoding (good change wide chars could be in HTML entity style llike the old
357       # days -JNAP
358
359       # so, now that HTTP::Body prepared the body params, we gotta 'walk' the structure
360       # and do any needed decoding.
361
362       # This only does something if the encoding is set via the encoding param.  Remember
363       # this is assuming the client is not bad and responds with what you provided.  In
364       # general you can just use utf8 and get away with it.
365       #
366       # I need to see if $c is here since this also doubles as a builder for the object :(
367
368       if($c and $c->encoding and !$c->config->{skip_body_param_unicode_decoding}) {
369         $params = $c->_handle_unicode_decoding($params);
370       }
371     }
372
373     my $return = $self->_use_hash_multivalue ?
374         Hash::MultiValue->from_mixed($params) :
375         $params;
376
377     $self->body_parameters($return) unless $self->has_body_parameters;
378     return $return;
379 }
380
381 sub prepare_connection {
382     my ($self) = @_;
383
384     my $env = $self->env;
385
386     $self->address( $env->{REMOTE_ADDR} );
387     $self->hostname( $env->{REMOTE_HOST} )
388         if exists $env->{REMOTE_HOST};
389     $self->protocol( $env->{SERVER_PROTOCOL} );
390     $self->remote_user( $env->{REMOTE_USER} );
391     $self->method( $env->{REQUEST_METHOD} );
392     $self->secure( $env->{'psgi.url_scheme'} eq 'https' ? 1 : 0 );
393 }
394
395 # XXX - FIXME - method is here now, move this crap...
396 around parameters => sub {
397     my ($orig, $self, $params) = @_;
398     if ($params) {
399         if ( !ref $params ) {
400             $self->_log->warn(
401                 "Attempt to retrieve '$params' with req->params(), " .
402                 "you probably meant to call req->param('$params')"
403             );
404             $params = undef;
405         }
406         return $self->$orig($params);
407     }
408     $self->$orig();
409 };
410
411 has base => (
412   is => 'rw',
413   required => 1,
414   lazy => 1,
415   default => sub {
416     my $self = shift;
417     return $self->path if $self->has_uri;
418   },
419 );
420
421 has _body => (
422   is => 'rw', clearer => '_clear_body', predicate => '_has_body',
423 );
424 # Eugh, ugly. Should just be able to rename accessor methods to 'body'
425 #             and provide a custom reader..
426 sub body {
427   my $self = shift;
428   $self->prepare_body unless $self->_has_body;
429   croak 'body is a reader' if scalar @_;
430   return blessed $self->_body ? $self->_body->body : $self->_body;
431 }
432
433 has hostname => (
434   is        => 'rw',
435   required  => 1,
436   lazy      => 1,
437   default   => sub {
438     my ($self) = @_;
439     my ( $err, $sockaddr ) = getaddrinfo(
440         $self->address,
441         # no service
442         '',
443         { flags => AI_NUMERICHOST }
444     );
445     if ( $err ) {
446         $self->_log->warn("resolve of hostname failed: $err");
447         return $self->address;
448     }
449     ( $err, my $hostname ) = getnameinfo(
450         $sockaddr->{addr},
451         0,
452         # we are only interested in the hostname, not the servicename
453         NIx_NOSERV
454     );
455     if ( $err ) {
456         $self->_log->warn("resolve of hostname failed: $err");
457         return $self->address;
458     }
459     return $hostname;
460   },
461 );
462
463 has _path => ( is => 'rw', predicate => '_has_path', clearer => '_clear_path' );
464
465 sub args            { shift->arguments(@_) }
466 sub body_params     { shift->body_parameters(@_) }
467 sub input           { shift->body(@_) }
468 sub params          { shift->parameters(@_) }
469 sub query_params    { shift->query_parameters(@_) }
470 sub path_info       { shift->path(@_) }
471
472 =for stopwords param params
473
474 =head1 NAME
475
476 Catalyst::Request - provides information about the current client request
477
478 =head1 SYNOPSIS
479
480     $req = $c->request;
481     $req->address eq "127.0.0.1";
482     $req->arguments;
483     $req->args;
484     $req->base;
485     $req->body;
486     $req->body_data;
487     $req->body_parameters;
488     $req->content_encoding;
489     $req->content_length;
490     $req->content_type;
491     $req->cookie;
492     $req->cookies;
493     $req->header;
494     $req->headers;
495     $req->hostname;
496     $req->input;
497     $req->query_keywords;
498     $req->match;
499     $req->method;
500     $req->param;
501     $req->parameters;
502     $req->params;
503     $req->path;
504     $req->protocol;
505     $req->query_parameters;
506     $req->read;
507     $req->referer;
508     $req->secure;
509     $req->captures;
510     $req->upload;
511     $req->uploads;
512     $req->uri;
513     $req->user;
514     $req->user_agent;
515     $req->env;
516
517 See also L<Catalyst>, L<Catalyst::Request::Upload>.
518
519 =head1 DESCRIPTION
520
521 This is the Catalyst Request class, which provides an interface to data for the
522 current client request. The request object is prepared by L<Catalyst::Engine>,
523 thus hiding the details of the particular engine implementation.
524
525 =head1 METHODS
526
527 =head2 $req->address
528
529 Returns the IP address of the client.
530
531 =head2 $req->arguments
532
533 Returns a reference to an array containing the arguments.
534
535     print $c->request->arguments->[0];
536
537 For example, if your action was
538
539     package MyApp::Controller::Foo;
540
541     sub moose : Local {
542         ...
543     }
544
545 and the URI for the request was C<http://.../foo/moose/bah>, the string C<bah>
546 would be the first and only argument.
547
548 Arguments get automatically URI-unescaped for you.
549
550 =head2 $req->args
551
552 Shortcut for L</arguments>.
553
554 =head2 $req->base
555
556 Contains the URI base. This will always have a trailing slash. Note that the
557 URI scheme (e.g., http vs. https) must be determined through heuristics;
558 depending on your server configuration, it may be incorrect. See $req->secure
559 for more info.
560
561 If your application was queried with the URI
562 C<http://localhost:3000/some/path> then C<base> is C<http://localhost:3000/>.
563
564 =head2 $req->body
565
566 Returns the message body of the request, as returned by L<HTTP::Body>: a string,
567 unless Content-Type is C<application/x-www-form-urlencoded>, C<text/xml>, or
568 C<multipart/form-data>, in which case a L<File::Temp> object is returned.
569
570 =head2 $req->body_data
571
572 Returns a Perl representation of POST/PUT body data that is not classic HTML
573 form data, such as JSON, XML, etc.  By default, Catalyst will parse incoming
574 data of the type 'application/json' and return access to that data via this
575 method.  You may define addition data_handlers via a global configuration
576 setting.  See L<Catalyst\DATA HANDLERS> for more information.
577
578 If the POST is malformed in some way (such as undefined or not content that
579 matches the content-type) we raise a L<Catalyst::Exception> with the error
580 text as the message.
581
582 If the POSTed content type does not match an available data handler, this
583 will also raise an exception.
584
585 =head2 $req->body_parameters
586
587 Returns a reference to a hash containing body (POST) parameters. Values can
588 be either a scalar or an arrayref containing scalars.
589
590     print $c->request->body_parameters->{field};
591     print $c->request->body_parameters->{field}->[0];
592
593 These are the parameters from the POST part of the request, if any.
594
595 B<NOTE> If your POST is multipart, but contains non file upload parts (such
596 as an line part with an alternative encoding or content type) we do our best to
597 try and figure out how the value should be presented.  If there's a specified character
598 set we will use that to decode rather than the default encoding set by the application.
599 However if there are complex headers and we cannot determine
600 the correct way to extra a meaningful value from the upload, in this case any
601 part like this will be represented as an instance of L<Catalyst::Request::PartData>.
602
603 Patches and review of this part of the code welcomed.
604
605 =head2 $req->body_params
606
607 Shortcut for body_parameters.
608
609 =head2 $req->content_encoding
610
611 Shortcut for $req->headers->content_encoding.
612
613 =head2 $req->content_length
614
615 Shortcut for $req->headers->content_length.
616
617 =head2 $req->content_type
618
619 Shortcut for $req->headers->content_type.
620
621 =head2 $req->cookie
622
623 A convenient method to access $req->cookies.
624
625     $cookie  = $c->request->cookie('name');
626     @cookies = $c->request->cookie;
627
628 =cut
629
630 sub cookie {
631     my $self = shift;
632
633     if ( @_ == 0 ) {
634         return keys %{ $self->cookies };
635     }
636
637     if ( @_ == 1 ) {
638
639         my $name = shift;
640
641         unless ( exists $self->cookies->{$name} ) {
642             return undef;
643         }
644
645         return $self->cookies->{$name};
646     }
647 }
648
649 =head2 $req->cookies
650
651 Returns a reference to a hash containing the cookies.
652
653     print $c->request->cookies->{mycookie}->value;
654
655 The cookies in the hash are indexed by name, and the values are L<CGI::Simple::Cookie>
656 objects.
657
658 =head2 $req->header
659
660 Shortcut for $req->headers->header.
661
662 =head2 $req->headers
663
664 Returns an L<HTTP::Headers> object containing the headers for the current request.
665
666     print $c->request->headers->header('X-Catalyst');
667
668 =head2 $req->hostname
669
670 Returns the hostname of the client. Use C<< $req->uri->host >> to get the hostname of the server.
671
672 =head2 $req->input
673
674 Alias for $req->body.
675
676 =head2 $req->query_keywords
677
678 Contains the keywords portion of a query string, when no '=' signs are
679 present.
680
681     http://localhost/path?some+keywords
682
683     $c->request->query_keywords will contain 'some keywords'
684
685 =head2 $req->match
686
687 This contains the matching part of a Regex action. Otherwise
688 it returns the same as 'action', except for default actions,
689 which return an empty string.
690
691 =head2 $req->method
692
693 Contains the request method (C<GET>, C<POST>, C<HEAD>, etc).
694
695 =head2 $req->param
696
697 Returns GET and POST parameters with a CGI.pm-compatible param method. This
698 is an alternative method for accessing parameters in $c->req->parameters.
699
700     $value  = $c->request->param( 'foo' );
701     @values = $c->request->param( 'foo' );
702     @params = $c->request->param;
703
704 Like L<CGI>, and B<unlike> earlier versions of Catalyst, passing multiple
705 arguments to this method, like this:
706
707     $c->request->param( 'foo', 'bar', 'gorch', 'quxx' );
708
709 will set the parameter C<foo> to the multiple values C<bar>, C<gorch> and
710 C<quxx>. Previously this would have added C<bar> as another value to C<foo>
711 (creating it if it didn't exist before), and C<quxx> as another value for
712 C<gorch>.
713
714 B<NOTE> this is considered a legacy interface and care should be taken when
715 using it. C<< scalar $c->req->param( 'foo' ) >> will return only the first
716 C<foo> param even if multiple are present; C<< $c->req->param( 'foo' ) >> will
717 return a list of as many are present, which can have unexpected consequences
718 when writing code of the form:
719
720     $foo->bar(
721         a => 'b',
722         baz => $c->req->param( 'baz' ),
723     );
724
725 If multiple C<baz> parameters are provided this code might corrupt data or
726 cause a hash initialization error. For a more straightforward interface see
727 C<< $c->req->parameters >>.
728
729 B<NOTE> Interfaces like this, which are based on L<CGI> and the C<param> method
730 are known to cause demonstrated exploits. It is highly recommended that you
731 avoid using this method, and migrate existing code away from it.  Here's a
732 whitepaper of the exploit:
733
734 L<http://blog.gerv.net/2014/10/new-class-of-vulnerability-in-perl-web-applications/>
735
736 B<NOTE> Further discussion on IRC indicate that the L<Catalyst> core team from 'back then'
737 were well aware of this hack and this is the main reason we added the new approach to
738 getting parameters in the first place.
739
740 Basically this is an exploit that takes advantage of how L<\param> will do one thing
741 in scalar context and another thing in list context.  This is combined with how Perl
742 chooses to deal with duplicate keys in a hash definition by overwriting the value of
743 existing keys with a new value if the same key shows up again.  Generally you will be
744 vulnerable to this exploit if you are using this method in a direct assignment in a
745 hash, such as with a L<DBIx::Class> create statement.  For example, if you have
746 parameters like:
747
748     user?user=123&foo=a&foo=user&foo=456
749
750 You could end up with extra parameters injected into your method calls:
751
752     $c->model('User')->create({
753       user => $c->req->param('user'),
754       foo => $c->req->param('foo'),
755     });
756
757 Which would look like:
758
759     $c->model('User')->create({
760       user => 123,
761       foo => qw(a user 456),
762     });
763
764 (or to be absolutely clear if you are not seeing it):
765
766     $c->model('User')->create({
767       user => 456,
768       foo => 'a',
769     });
770
771 Possible remediations include scrubbing your parameters with a form validator like
772 L<HTML::FormHandler> or being careful to force scalar context using the scalar
773 keyword:
774
775     $c->model('User')->create({
776       user => scalar($c->req->param('user')),
777       foo => scalar($c->req->param('foo')),
778     });
779
780 Upcoming versions of L<Catalyst> will disable this interface by default and require
781 you to positively enable it should you require it for backwards compatibility reasons.
782
783 =cut
784
785 sub param {
786     my $self = shift;
787
788     if ( @_ == 0 ) {
789         return keys %{ $self->parameters };
790     }
791
792     # If anything in @_ is undef, carp about that, and remove it from
793     # the list;
794     
795     my @params = grep { defined($_) ? 1 : do {carp "You called ->params with an undefined value"; 0} } @_;
796
797     if ( @params == 1 ) {
798
799         defined(my $param = shift @params) ||
800           carp "You called ->params with an undefined value 2";
801
802         unless ( exists $self->parameters->{$param} ) {
803             return wantarray ? () : undef;
804         }
805
806         if ( ref $self->parameters->{$param} eq 'ARRAY' ) {
807             return (wantarray)
808               ? @{ $self->parameters->{$param} }
809               : $self->parameters->{$param}->[0];
810         }
811         else {
812             return (wantarray)
813               ? ( $self->parameters->{$param} )
814               : $self->parameters->{$param};
815         }
816     }
817     elsif ( @params > 1 ) {
818         my $field = shift @params;
819         $self->parameters->{$field} = [@params];
820     }
821 }
822
823 =head2 $req->parameters
824
825 Returns a reference to a hash containing GET and POST parameters. Values can
826 be either a scalar or an arrayref containing scalars.
827
828     print $c->request->parameters->{field};
829     print $c->request->parameters->{field}->[0];
830
831 This is the combination of C<query_parameters> and C<body_parameters>.
832
833 =head2 $req->params
834
835 Shortcut for $req->parameters.
836
837 =head2 $req->path
838
839 Returns the path, i.e. the part of the URI after $req->base, for the current request.
840
841     http://localhost/path/foo
842
843     $c->request->path will contain 'path/foo'
844
845 =head2 $req->path_info
846
847 Alias for path, added for compatibility with L<CGI>.
848
849 =cut
850
851 sub path {
852     my ( $self, @params ) = @_;
853
854     if (@params) {
855         $self->uri->path(@params);
856         $self->_clear_path;
857     }
858     elsif ( $self->_has_path ) {
859         return $self->_path;
860     }
861     else {
862         my $path     = $self->uri->path;
863         my $location = $self->base->path;
864         $path =~ s/^(\Q$location\E)?//;
865         $path =~ s/^\///;
866         $self->_path($path);
867
868         return $path;
869     }
870 }
871
872 =head2 $req->protocol
873
874 Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.
875
876 =head2 $req->query_parameters
877
878 =head2 $req->query_params
879
880 Returns a reference to a hash containing query string (GET) parameters. Values can
881 be either a scalar or an arrayref containing scalars.
882
883     print $c->request->query_parameters->{field};
884     print $c->request->query_parameters->{field}->[0];
885
886 =head2 $req->read( [$maxlength] )
887
888 Reads a chunk of data from the request body. This method is intended to be
889 used in a while loop, reading $maxlength bytes on every call. $maxlength
890 defaults to the size of the request if not specified.
891
892 =head2 $req->read_chunk(\$buff, $max)
893
894 Reads a chunk.
895
896 You have to set MyApp->config(parse_on_demand => 1) to use this directly.
897
898 =head2 $req->referer
899
900 Shortcut for $req->headers->referer. Returns the referring page.
901
902 =head2 $req->secure
903
904 Returns true or false, indicating whether the connection is secure
905 (https). The reliability of $req->secure may depend on your server
906 configuration; Catalyst relies on PSGI to determine whether or not a
907 request is secure (Catalyst looks at psgi.url_scheme), and different
908 PSGI servers may make this determination in different ways (as by
909 directly passing along information from the server, interpreting any of
910 several HTTP headers, or using heuristics of their own).
911
912 =head2 $req->captures
913
914 Returns a reference to an array containing captured args from chained
915 actions or regex captures.
916
917     my @captures = @{ $c->request->captures };
918
919 =head2 $req->upload
920
921 A convenient method to access $req->uploads.
922
923     $upload  = $c->request->upload('field');
924     @uploads = $c->request->upload('field');
925     @fields  = $c->request->upload;
926
927     for my $upload ( $c->request->upload('field') ) {
928         print $upload->filename;
929     }
930
931 =cut
932
933 sub upload {
934     my $self = shift;
935
936     if ( @_ == 0 ) {
937         return keys %{ $self->uploads };
938     }
939
940     if ( @_ == 1 ) {
941
942         my $upload = shift;
943
944         unless ( exists $self->uploads->{$upload} ) {
945             return wantarray ? () : undef;
946         }
947
948         if ( ref $self->uploads->{$upload} eq 'ARRAY' ) {
949             return (wantarray)
950               ? @{ $self->uploads->{$upload} }
951               : $self->uploads->{$upload}->[0];
952         }
953         else {
954             return (wantarray)
955               ? ( $self->uploads->{$upload} )
956               : $self->uploads->{$upload};
957         }
958     }
959
960     if ( @_ > 1 ) {
961
962         while ( my ( $field, $upload ) = splice( @_, 0, 2 ) ) {
963
964             if ( exists $self->uploads->{$field} ) {
965                 for ( $self->uploads->{$field} ) {
966                     $_ = [$_] unless ref($_) eq "ARRAY";
967                     push( @$_, $upload );
968                 }
969             }
970             else {
971                 $self->uploads->{$field} = $upload;
972             }
973         }
974     }
975 }
976
977 =head2 $req->uploads
978
979 Returns a reference to a hash containing uploads. Values can be either a
980 L<Catalyst::Request::Upload> object, or an arrayref of
981 L<Catalyst::Request::Upload> objects.
982
983     my $upload = $c->request->uploads->{field};
984     my $upload = $c->request->uploads->{field}->[0];
985
986 =head2 $req->uri
987
988 Returns a L<URI> object for the current request. Stringifies to the URI text.
989
990 =head2 $req->mangle_params( { key => 'value' }, $appendmode);
991
992 Returns a hashref of parameters stemming from the current request's params,
993 plus the ones supplied.  Keys for which no current param exists will be
994 added, keys with undefined values will be removed and keys with existing
995 params will be replaced.  Note that you can supply a true value as the final
996 argument to change behavior with regards to existing parameters, appending
997 values rather than replacing them.
998
999 A quick example:
1000
1001   # URI query params foo=1
1002   my $hashref = $req->mangle_params({ foo => 2 });
1003   # Result is query params of foo=2
1004
1005 versus append mode:
1006
1007   # URI query params foo=1
1008   my $hashref = $req->mangle_params({ foo => 2 }, 1);
1009   # Result is query params of foo=1&foo=2
1010
1011 This is the code behind C<uri_with>.
1012
1013 =cut
1014
1015 sub mangle_params {
1016     my ($self, $args, $append) = @_;
1017
1018     carp('No arguments passed to mangle_params()') unless $args;
1019
1020     foreach my $value ( values %$args ) {
1021         next unless defined $value;
1022         for ( ref $value eq 'ARRAY' ? @$value : $value ) {
1023             $_ = "$_";
1024             #      utf8::encode($_);
1025         }
1026     };
1027
1028     my %params = %{ $self->uri->query_form_hash };
1029     foreach my $key (keys %{ $args }) {
1030         my $val = $args->{$key};
1031         if(defined($val)) {
1032
1033             if($append && exists($params{$key})) {
1034
1035                 # This little bit of heaven handles appending a new value onto
1036                 # an existing one regardless if the existing value is an array
1037                 # or not, and regardless if the new value is an array or not
1038                 $params{$key} = [
1039                     ref($params{$key}) eq 'ARRAY' ? @{ $params{$key} } : $params{$key},
1040                     ref($val) eq 'ARRAY' ? @{ $val } : $val
1041                 ];
1042
1043             } else {
1044                 $params{$key} = $val;
1045             }
1046         } else {
1047
1048             # If the param wasn't defined then we delete it.
1049             delete($params{$key});
1050         }
1051     }
1052
1053
1054     return \%params;
1055 }
1056
1057 =head2 $req->uri_with( { key => 'value' } );
1058
1059 Returns a rewritten URI object for the current request. Key/value pairs
1060 passed in will override existing parameters. You can remove an existing
1061 parameter by passing in an undef value. Unmodified pairs will be
1062 preserved.
1063
1064 You may also pass an optional second parameter that puts C<uri_with> into
1065 append mode:
1066
1067   $req->uri_with( { key => 'value' }, { mode => 'append' } );
1068
1069 See C<mangle_params> for an explanation of this behavior.
1070
1071 =cut
1072
1073 sub uri_with {
1074     my( $self, $args, $behavior) = @_;
1075
1076     carp( 'No arguments passed to uri_with()' ) unless $args;
1077
1078     my $append = 0;
1079     if((ref($behavior) eq 'HASH') && defined($behavior->{mode}) && ($behavior->{mode} eq 'append')) {
1080         $append = 1;
1081     }
1082
1083     my $params = $self->mangle_params($args, $append);
1084
1085     my $uri = $self->uri->clone;
1086     $uri->query_form($params);
1087
1088     return $uri;
1089 }
1090
1091 =head2 $req->remote_user
1092
1093 Returns the value of the C<REMOTE_USER> environment variable.
1094
1095 =head2 $req->user_agent
1096
1097 Shortcut to $req->headers->user_agent. Returns the user agent (browser)
1098 version string.
1099
1100 =head2 $req->io_fh
1101
1102 Returns a psgix.io bidirectional socket, if your server supports one.  Used for
1103 when you want to jailbreak out of PSGI and handle bidirectional client server
1104 communication manually, such as when you are using cometd or websockets.
1105
1106 =head1 SETUP METHODS
1107
1108 You should never need to call these yourself in application code,
1109 however they are useful if extending Catalyst by applying a request role.
1110
1111 =head2 $self->prepare_headers()
1112
1113 Sets up the C<< $res->headers >> accessor.
1114
1115 =head2 $self->prepare_body()
1116
1117 Sets up the body using L<HTTP::Body>
1118
1119 =head2 $self->prepare_body_chunk()
1120
1121 Add a chunk to the request body.
1122
1123 =head2 $self->prepare_body_parameters()
1124
1125 Sets up parameters from body.
1126
1127 =head2 $self->prepare_cookies()
1128
1129 Parse cookies from header. Sets up a L<CGI::Simple::Cookie> object.
1130
1131 =head2 $self->prepare_connection()
1132
1133 Sets up various fields in the request like the local and remote addresses,
1134 request method, hostname requested etc.
1135
1136 =head2 $self->prepare_parameters()
1137
1138 Ensures that the body has been parsed, then builds the parameters, which are
1139 combined from those in the request and those in the body.
1140
1141 If parameters have already been set will clear the parameters and build them again.
1142
1143 =head2 $self->env
1144
1145 Access to the raw PSGI env.  
1146
1147 =head2 meta
1148
1149 Provided by Moose
1150
1151 =head1 AUTHORS
1152
1153 Catalyst Contributors, see Catalyst.pm
1154
1155 =head1 COPYRIGHT
1156
1157 This library is free software. You can redistribute it and/or modify
1158 it under the same terms as Perl itself.
1159
1160 =cut
1161
1162 __PACKAGE__->meta->make_immutable;
1163
1164 1;