This file is indexed.

/usr/share/perl5/Dancer2/Core/Request.pm is in libdancer2-perl 0.204002+dfsg-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
package Dancer2::Core::Request;
# ABSTRACT: Interface for accessing incoming requests
$Dancer2::Core::Request::VERSION = '0.204002';
use strict;
use warnings;
use parent 'Plack::Request';

use Carp;
use Encode;
use HTTP::Body;
use URI;
use URI::Escape;
use Safe::Isa;
use Hash::MultiValue;
use Module::Runtime 'require_module';

use Dancer2::Core::Types;
use Dancer2::Core::Request::Upload;
use Dancer2::Core::Cookie;

# add an attribute for each HTTP_* variables
# (HOST is managed manually)
my @http_env_keys = (qw/
    accept_charset
    accept_encoding
    accept_language
    connection
    keep_alive
    x_requested_with
/);

# apparently you can't eval core functions
sub accept { $_[0]->env->{'HTTP_ACCEPT'} }

eval << "_EVAL" or die $@ for @http_env_keys; ## no critic
sub $_ { \$_[0]->env->{ 'HTTP_' . ( uc "$_" ) } }
1;
_EVAL

# check presence of XS module to speedup request
our $XS_URL_DECODE         = eval { require_module('URL::Encode::XS'); 1; };
our $XS_PARSE_QUERY_STRING = eval { require_module('CGI::Deurl::XS');  1; };
our $XS_HTTP_COOKIES       = eval { require_module('HTTP::XSCookies'); 1; };

our $_id = 0;

# self->new( env => {}, serializer => $s, is_behind_proxy => 0|1 )
sub new {
    my ( $class, @args ) = @_;

    # even sized list
    @args % 2 == 0
        or croak 'Must provide even sized list';

    my %opts = @args;
    my $env  = $opts{'env'};

    my $self = $class->SUPER::new($env);

    if ( my $s = $opts{'serializer'} ) {
        $s->$_does('Dancer2::Core::Role::Serializer')
            or croak 'Serializer provided not a Serializer object';

        $self->{'serializer'} = $s;
    }

    # additionally supported attributes
    $self->{'id'}              = ++$_id;
    $self->{'vars'}            = {};
    $self->{'is_behind_proxy'} = !!$opts{'is_behind_proxy'};

    # parameters
    $self->{_chunk_size}       = 4096;
    $self->{_read_position}    = 0;
    $self->{_http_body} =
      HTTP::Body->new( $self->content_type || '', $self->content_length );
    $self->{_http_body}->cleanup(1);

    $opts{'body_params'}
        and $self->{'_body_params'} = $opts{'body_params'};

    # Deserialize/parse body for HMV
    $self->data;
    $self->body_parameters;
    $self->_build_uploads();

    return $self;
}

# a buffer for per-request variables
sub vars { $_[0]->{'vars'} }

sub var {
    my $self = shift;
    @_ == 2
      ? $self->vars->{ $_[0] } = $_[1]
      : $self->vars->{ $_[0] };
}

# I don't like this. I know send_file uses this and I wonder
# if we can remove it.
#   -- Sawyer
sub set_path_info { $_[0]->env->{'PATH_INFO'} = $_[1] }

# XXX: incompatible with Plack::Request
sub body { $_[0]->{'body'} ||= $_[0]->_read_to_end }

sub id { $_id }

# Private 'read-only' attributes for request params. See the params()
# method for the public interface.
#
# _body_params, _query_params and _route_params have setter methods that
# decode byte string to characters before setting; If you know you have
# decoded (character) params, such as output from a deserializer, you can
# set these directly in the request object hash to avoid the decode op.
sub _params { $_[0]->{'_params'} ||= $_[0]->_build_params }

sub _has_params { defined $_[0]->{'_params'} }

sub _body_params {
    my $self = shift;

    # make sure body is parsed
    $self->body;

    $self->{'_body_params'} ||= _decode( $self->{'_http_body'}->param );
}

sub _query_params { $_[0]->{'_query_params'} }

sub _set_query_params {
    my ( $self, $params ) = @_;
    $self->{_query_params} = _decode( $params );
}

sub _route_params { $_[0]->{'_route_params'} ||= {} }

sub _set_route_params {
    my ( $self, $params ) = @_;
    $self->{_route_params} = _decode( $params );
    $self->_build_params();
}

# XXX: incompatible with Plack::Request
sub uploads { $_[0]->{'uploads'} }

sub is_behind_proxy { $_[0]->{'is_behind_proxy'} || 0 }

sub host {
    my ($self) = @_;

    if ( $self->is_behind_proxy and exists $self->env->{'HTTP_X_FORWARDED_HOST'} ) {
        my @hosts = split /\s*,\s*/, $self->env->{'HTTP_X_FORWARDED_HOST'}, 2;
        return $hosts[0];
    } else {
        return $self->env->{'HTTP_HOST'};
    }
}

# aliases, kept for backward compat
sub agent                 { shift->user_agent }
sub remote_address        { shift->address }
sub forwarded_for_address { shift->env->{'HTTP_X_FORWARDED_FOR'} }
sub forwarded_host        { shift->env->{'HTTP_X_FORWARDED_HOST'} }

# there are two options
sub forwarded_protocol    {
    $_[0]->env->{'HTTP_X_FORWARDED_PROTOCOL'} ||
    $_[0]->env->{'HTTP_X_FORWARDED_PROTO'}    ||
    $_[0]->env->{'HTTP_FORWARDED_PROTO'}
}

sub scheme {
    my ($self) = @_;
    my $scheme = $self->is_behind_proxy
               ? $self->forwarded_protocol
               : '';

    return $scheme || $self->env->{'psgi.url_scheme'};
}

sub serializer { $_[0]->{'serializer'} }

sub data { $_[0]->{'data'} ||= $_[0]->deserialize() }

sub deserialize {
    my $self = shift;

    my $serializer = $self->serializer
        or return;

    # The latest draft of the RFC does not forbid DELETE to have content,
    # rather the behaviour is undefined. Take the most lenient route and
    # deserialize any content on delete as well.
    return
      unless grep { $self->method eq $_ } qw/ PUT POST PATCH DELETE /;

    # try to deserialize
    my $body = $self->body;

    $body && length $body > 0
        or return;

    my $data = $serializer->deserialize($body);
    return if !defined $data;

    # Set _body_params directly rather than using the setter. Deserializiation
    # returns characters and skipping the decode op in the setter ensures
    # that numerical data "stays" numerical; decoding an SV that is an IV
    # converts that to a PVIV. Some serializers are picky (JSON)..
    $self->{_body_params} = $data;

    # Set body parameters (decoded HMV)
    $self->{'body_parameters'} =
        Hash::MultiValue->from_mixed( ref $data eq 'HASH' ? %$data : () );

    return $data;
}

sub uri        { $_[0]->request_uri }

sub is_head    { $_[0]->method eq 'HEAD' }
sub is_post    { $_[0]->method eq 'POST' }
sub is_get     { $_[0]->method eq 'GET' }
sub is_put     { $_[0]->method eq 'PUT' }
sub is_delete  { $_[0]->method eq 'DELETE' }
sub is_patch   { $_[0]->method eq 'PATCH' }
sub is_options { $_[0]->method eq 'OPTIONS' }

# public interface compat with CGI.pm objects
sub request_method { $_[0]->method }
sub input_handle { $_[0]->env->{'psgi.input'} }

sub to_string {
    my ($self) = @_;
    return "[#" . $self->id . "] " . $self->method . " " . $self->path;
}

sub base {
    my $self = shift;
    my $uri  = $self->_common_uri;

    return $uri->canonical;
}

sub _common_uri {
    my $self = shift;

    my $path   = $self->env->{SCRIPT_NAME};
    my $port   = $self->env->{SERVER_PORT};
    my $server = $self->env->{SERVER_NAME};
    my $host   = $self->host;
    my $scheme = $self->scheme;

    my $uri = URI->new;
    $uri->scheme($scheme);
    $uri->authority( $host || "$server:$port" );
    $uri->path( $path      || '/' );

    return $uri;
}

sub uri_base {
    my $self  = shift;
    my $uri   = $self->_common_uri;
    my $canon = $uri->canonical;

    if ( $uri->path eq '/' ) {
        $canon =~ s{/$}{};
    }

    return $canon;
}

sub dispatch_path {
    my $self = shift;

    my $path = $self->path;

    # Want $self->base->path, without needing the URI object,
    # and trim any trailing '/'.
    my $base = '';
    $base .= $self->script_name if defined $self->script_name;
    $base =~ s|/+$||;

    # Remove base from front of path.
    $path =~ s|^(\Q$base\E)?||;
    $path =~ s|^/+|/|;
    # PSGI spec notes that '' should be considered '/'
    $path = '/' if $path eq '';
    return $path;
}

sub uri_for {
    my ( $self, $part, $params, $dont_escape ) = @_;

    $part ||= '';
    my $uri = $self->base;

    # Make sure there's exactly one slash between the base and the new part
    my $base = $uri->path;
    $base =~ s|/$||;
    $part =~ s|^/||;
    $uri->path("$base/$part");

    $uri->query_form($params) if $params;

    return $dont_escape
           ? uri_unescape( ${ $uri->canonical } )
           : ${ $uri->canonical };
}

sub params {
    my ( $self, $source ) = @_;

    return %{ $self->_params } if wantarray && @_ == 1;
    return $self->_params if @_ == 1;

    if ( $source eq 'query' ) {
        return %{ $self->_query_params || {} } if wantarray;
        return $self->_query_params;
    }
    elsif ( $source eq 'body' ) {
        return %{ $self->_body_params || {} } if wantarray;
        return $self->_body_params;
    }
    if ( $source eq 'route' ) {
        return %{ $self->_route_params } if wantarray;
        return $self->_route_params;
    }
    else {
        croak "Unknown source params \"$source\".";
    }
}

sub query_parameters {
    my $self = shift;
    $self->{'query_parameters'} ||= do {
        if ($XS_PARSE_QUERY_STRING) {
            my $query = _decode(CGI::Deurl::XS::parse_query_string(
                $self->env->{'QUERY_STRING'}
            ));

            Hash::MultiValue->new(
                map {;
                    my $key = $_;
                    ref $query->{$key} eq 'ARRAY'
                    ? ( map +( $key => $_ ), @{ $query->{$key} } )
                    : ( $key => $query->{$key} )
                } keys %{$query}
            );
        } else {
            # defer to Plack::Request
            _decode($self->SUPER::query_parameters);
        }
    };
}

# this will be filled once the route is matched
sub route_parameters { $_[0]->{'route_parameters'} ||= Hash::MultiValue->new }

sub _set_route_parameters {
    my ( $self, $params ) = @_;
    # remove reserved splat parameter name
    # you should access splat parameters using splat() keyword
    delete @{$params}{qw<splat captures>};
    $self->{'route_parameters'} = Hash::MultiValue->from_mixed( %{_decode($params)} );
}

sub body_parameters {
    my $self = shift;
    # defer to (the overridden) Plack::Request->body_parameters
    $self->{'body_parameters'} ||= _decode($self->SUPER::body_parameters());
}

sub parameters {
    my ( $self, $type ) = @_;

    # handle a specific case
    if ($type) {
        my $attr = "${type}_parameters";
        return $self->$attr;
    }

    # merge together the *decoded* parameters
    $self->{'merged_parameters'} ||= do {
        my $query = $self->query_parameters;
        my $body  = $self->body_parameters;
        my $route = $self->route_parameters; # not in Plack::Request
        Hash::MultiValue->new( map $_->flatten, $query, $body, $route );
    };
}

sub captures { shift->params->{captures} || {} }

sub splat { @{ shift->params->{splat} || [] } }

# XXX: incompatible with Plack::Request
sub param { shift->params->{ $_[0] } }

sub _decode {
    my ($h) = @_;
    return if not defined $h;

    if ( !ref($h) && !utf8::is_utf8($h) ) {
        return decode( 'UTF-8', $h );
    }
    elsif ( ref($h) eq 'HASH' ) {
        return { map {my $t = _decode($_); $t} (%$h) };
    }
    elsif ( ref($h) eq 'ARRAY' ) {
        return [ map _decode($_), @$h ];
    }
    elsif ( ref($h) eq 'Hash::MultiValue' ) {
        return Hash::MultiValue->from_mixed(_decode($h->as_hashref_mixed));
    }

    return $h;
}

sub is_ajax {
    my $self = shift;

    return 0 unless defined $self->headers;
    return 0 unless defined $self->header('X-Requested-With');
    return 0 if $self->header('X-Requested-With') ne 'XMLHttpRequest';
    return 1;
}

# XXX incompatible with Plack::Request
# context-aware accessor for uploads
sub upload {
    my ( $self, $name ) = @_;
    my $res = $self->{uploads}{$name};

    return $res unless wantarray;
    return ()   unless defined $res;
    return ( ref($res) eq 'ARRAY' ) ? @$res : $res;
}

sub _build_params {
    my ($self) = @_;

    # params may have been populated by before filters
    # _before_ we get there, so we have to save it first
    my $previous = $self->_has_params ? $self->_params : {};

    # now parse environment params...
    my $get_params = $self->_parse_get_params();

    # and merge everything
    $self->{_params} = {
        map +( ref $_ eq 'HASH' ? %{$_} : () ),
        $previous,
        $get_params,
        $self->_body_params,
        $self->_route_params,
    };

}

sub _url_decode {
    my ( $self, $encoded ) = @_;
    return URL::Encode::XS::url_decode($encoded) if $XS_URL_DECODE;
    my $clean = $encoded;
    $clean =~ tr/\+/ /;
    $clean =~ s/%([a-fA-F0-9]{2})/pack "H2", $1/eg;
    return $clean;
}

sub _parse_get_params {
    my ($self) = @_;
    return $self->_query_params if defined $self->{_query_params};

    my $query_params = {};

    my $source = $self->env->{QUERY_STRING};
    return if !defined $source || $source eq '';

    if ($XS_PARSE_QUERY_STRING) {
        $self->_set_query_params(
            CGI::Deurl::XS::parse_query_string($source) || {}
        );
        return $self->_query_params;
    }

    foreach my $token ( split /[&;]/, $source ) {
        my ( $key, $val ) = split( /=/, $token );
        next unless defined $key;
        $val = ( defined $val ) ? $val : '';
        $key = $self->_url_decode($key);
        $val = $self->_url_decode($val);

        # looking for multi-value params
        if ( exists $query_params->{$key} ) {
            my $prev_val = $query_params->{$key};
            if ( ref($prev_val) && ref($prev_val) eq 'ARRAY' ) {
                push @{ $query_params->{$key} }, $val;
            }
            else {
                $query_params->{$key} = [ $prev_val, $val ];
            }
        }

        # simple value param (first time we see it)
        else {
            $query_params->{$key} = $val;
        }
    }
    $self->_set_query_params( $query_params );
    return $self->_query_params;
}

sub _read_to_end {
    my ($self) = @_;

    my $content_length = $self->content_length;
    return unless $self->_has_something_to_read();

    my $body = '';
    if ( $content_length && $content_length > 0 ) {
        while ( my $buffer = $self->_read() ) {
            $body .= $buffer;
        }
        $self->{_http_body}->add($body);
    }

    return $body;
}

sub _has_something_to_read {
    my ($self) = @_;
    return 0 unless defined $self->input_handle;
}

# taken from Miyagawa's Plack::Request::BodyParser
sub _read {
    my ( $self ) = @_;
    my $remaining = $self->content_length - $self->{_read_position};
    my $maxlength = $self->{_chunk_size};

    return if ( $remaining <= 0 );

    my $readlen = ( $remaining > $maxlength ) ? $maxlength : $remaining;
    my $buffer;
    my $rc;

    $rc = $self->input_handle->read( $buffer, $readlen );

    if ( defined $rc ) {
        $self->{_read_position} += $rc;
        return $buffer;
    }
    else {
        croak "Unknown error reading input: $!";
    }
}

# Taken gently from Plack::Request, thanks to Plack authors.
sub _build_uploads {
    my ($self) = @_;

    # build the body and body params
    my $body_params = $self->_body_params;

    my $uploads = _decode( $self->{_http_body}->upload );
    my %uploads;

    for my $name ( keys %{$uploads} ) {
        my $files = $uploads->{$name};
        $files = ref $files eq 'ARRAY' ? $files : [$files];

        my @uploads = map Dancer2::Core::Request::Upload->new(
                              headers  => $_->{headers},
                              tempname => $_->{tempname},
                              size     => $_->{size},
                              filename => $_->{filename},
                      ), @{$files};

        $uploads{$name} = @uploads > 1 ? \@uploads : $uploads[0];

        # support access to the filename as a normal param
        my @filenames = map $_->{'filename'}, @uploads;
        $self->{_body_params}{$name} =
          @filenames > 1 ? \@filenames : $filenames[0];
    }

    $self->{uploads} = \%uploads;
}

# XXX: incompatible with Plack::Request
sub cookies { $_[0]->{'cookies'} ||= $_[0]->_build_cookies }

sub _build_cookies {
    my $self    = shift;
    my $cookies = {};

    my $http_cookie = $self->header('Cookie');
    return $cookies unless defined $http_cookie; # nothing to do

    if ( $XS_HTTP_COOKIES ) {
        $cookies = HTTP::XSCookies::crush_cookie($http_cookie);
    }
    else {
        # handle via Plack::Request
        $cookies = $self->SUPER::cookies();
    }

    # convert to objects
    while (my ($name, $value) = each %{$cookies}) {
        $cookies->{$name} = Dancer2::Core::Cookie->new(
            name  => $name,
            value => [split(/[&;]/, $value)]
        );
    }
    return $cookies;
}

# poor man's clone
sub _shallow_clone {
    my ($self, $params, $options) = @_;

    # shallow clone $env; we don't want to alter the existing one
    # in $self, then merge any overridden values
    my $env = { %{ $self->env }, %{ $options || {} } };

    # request body fh has been read till end
    # delete CONTENT_LENGTH in new request (no need to parse body again)
    # and merge existing params
    delete $env->{CONTENT_LENGTH};

    my $new_request = __PACKAGE__->new(
        env         => $env,
        body_params => {},
    );

    # Clone and merge query params
    my $new_params = $self->params;
    $new_request->{_query_params} = { %{ $self->{_query_params} || {} } };
    $new_request->{query_parameters} = $self->query_parameters->clone;
    for my $key ( keys %{ $params || {} } ) {
        my $value = $params->{$key};
        $new_params->{$key} = $value;
        $new_request->{_query_params}->{$key} = $value;
        $new_request->{query_parameters}->add( $key => $value );
    }

    # Copy params (these are already decoded)
    $new_request->{_params}       = $new_params;
    $new_request->{_body_params}  = $self->{_body_params};
    $new_request->{_route_params} = $self->{_route_params};
    $new_request->{body}          = $self->body;
    $new_request->{headers}       = $self->headers;

    # Copy remaining settings
    $new_request->{is_behind_proxy} = $self->{is_behind_proxy};
    $new_request->{vars}            = $self->{vars};

    # Clone any existing decoded & cached body params. (GH#1116 GH#1269)
    $new_request->{'body_parameters'} = $self->body_parameters->clone;

    # Delete merged HMV parameters, allowing them to be reconstructed on first use.
    delete $new_request->{'merged_parameters'};

    return $new_request;
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Dancer2::Core::Request - Interface for accessing incoming requests

=head1 VERSION

version 0.204002

=head1 SYNOPSIS

In a route handler, the current request object can be accessed by the
C<request> keyword:

    get '/foo' => sub {
        request->params; # request, params parsed as a hash ref
        request->body;   # returns the request body, unparsed
        request->path;   # the path requested by the client
        # ...
    };

=head1 DESCRIPTION

An object representing a Dancer2 request. It aims to provide a proper
interface to anything you might need from a web request.

=head1 METHODS

=head2 address

Return the IP address of the client.

=head2 base

Returns an absolute URI for the base of the application.  Returns a L<URI>
object (which stringifies to the URL, as you'd expect).

=head2 body_parameters

Returns a L<Hash::MultiValue> object representing the POST parameters.

=head2 body

Return the raw body of the request, unparsed.

If you need to access the body of the request, you have to use this accessor and
should not try to read C<psgi.input> by hand. C<Dancer2::Core::Request>
already did it for you and kept the raw body untouched in there.

=head2 content

Returns the undecoded byte string POST body.

=head2 cookies

Returns a reference to a hash containing cookies, where the keys are the names of the
cookies and values are L<Dancer2::Core::Cookie> objects.

=head2 data

If the application has a serializer and if the request has serialized
content, returns the deserialized structure as a hashref.

=head2 dispatch_path

The part of the C<path> after C<base>. This is the path used
for dispatching the request to routes.

=head2 env

Return the current PSGI environment hash reference.

=head2 header($name)

Return the value of the given header, if present. If the header has multiple
values, returns an the list of values if called in list context, the first one
in scalar.

=head2 headers

Returns either an L<HTTP::Headers> or an L<HTTP::Headers::Fast> object
representing the headers.

=head2 id

The ID of the request. This allows you to trace a specific request in loggers,
per the string created using C<to_string>.

The ID of the request is essentially the number of requests run in the current
class.

=head2 input

Alias to C<input_handle> method below.

=head2 input_handle

Alias to the PSGI input handle (C<< <request->env->{psgi.input}> >>)

=head2 is_ajax

Return true if the value of the header C<X-Requested-With> is
C<XMLHttpRequest>.

=head2 is_delete

Return true if the method requested by the client is 'DELETE'

=head2 is_get

Return true if the method requested by the client is 'GET'

=head2 is_head

Return true if the method requested by the client is 'HEAD'

=head2 is_post

Return true if the method requested by the client is 'POST'

=head2 is_put

Return true if the method requested by the client is 'PUT'

=head2 is_options

Return true if the method requested by the client is 'OPTIONS'

=head2 logger

Returns the C<psgix.logger> code reference, if exists.

=head2 method

Return the HTTP method used by the client to access the application.

While this method returns the method string as provided by the environment, it's
better to use one of the following boolean accessors if you want to inspect the
requested method.

=head2 new

The constructor of the class, used internally by Dancer2's core to create request
objects.

It uses the environment hash table given to build the request object:

    Dancer2::Core::Request->new( env => $env );

There are two additional parameters for instantiation:

=over 4

=item * serializer

A serializer object to work with when reading the request body.

=item * body_params

Provide body parameters.

Used internally when we need to avoid parsing the body again.

=back

=head2 param($key)

Calls the C<params> method below and fetches the key provided.

=head2 params($source)

Called in scalar context, returns a hashref of params, either from the specified
source (see below for more info on that) or merging all sources.

So, you can use, for instance:

    my $foo = params->{foo}

If called in list context, returns a list of key and value pairs, so you could use:

    my %allparams = params;

Parameters are merged in the following order: query, body, route - i.e. route
parameters have the highest priority:

    POST /hello/Ruth?name=Quentin

    name=Bobbie

    post '/hello/:name' => sub {
        return "Hello, " . route_parameters->get('name') . "!"; # returns Ruth
        return "Hello, " . query_parameters->get('name') . "!"; # returns Quentin
        return "Hello, " . body_parameters->get('name') . "!";  # returns Bobbie
        return "Hello, " . param('name') . "!";                 # returns Ruth
    };

The L</query_parameters>, L</route_parameters>, and L</body_parameters> keywords
provide a L<Hash::MultiValue> result from the three different parameters.
We recommend using these rather than C<params>, because of the potential for
unintentional behaviour - consider the following request and route handler:

    POST /artist/104/new-song

    name=Careless Dancing

    post '/artist/:id/new-song' => sub {
      find_artist(param('id'))->create_song(params);
      # oops! we just passed id into create_song,
      # but we probably only intended to pass name
      find_artist(param('id'))->create_song(body_parameters);
    };

    POST /artist/104/join-band

    id=4
    name=Dancing Misfits

    post '/artist/:id/new-song' => sub {
      find_artist(param('id'))->join_band(params);
      # oops! we just passed an id of 104 into join_band,
      # but we probably should have passed an id of 4
    };

=head2 parameters

Returns a L<Hash::MultiValue> object with merged GET and POST parameters.

Parameters are merged in the following order: query, body, route - i.e. route
parameters have the highest priority - see L</params> for how this works, and
associated risks and alternatives.

=head2 path

The path requested by the client, normalized. This is effectively
C<path_info> or a single forward C</>.

=head2 path_info

The raw requested path. This could be empty. Use C<path> instead.

=head2 port

Return the port of the server.

=head2 protocol

Return the protocol (I<HTTP/1.0> or I<HTTP/1.1>) used for the request.

=head2 query_parameters

Returns a L<Hash::MultiValue> parameters object.

=head2 query_string

Returns the portion of the request defining the query itself - this is
what comes after the C<?> in a URI.

=head2 raw_body

Alias to C<content> method.

=head2 remote_address

Alias for C<address> method.

=head2 remote_host

Return the remote host of the client. This only works with web servers configured
to do a reverse DNS lookup on the client's IP address.

=head2 request_method

Alias to the C<method> accessor, for backward-compatibility with C<CGI> interface.

=head2 request_uri

Return the raw, undecoded request URI path.

=head2 scheme

Return the scheme of the request

=head2 script_name

Return script_name from the environment.

=head2 secure

Return true or false, indicating whether the connection is secure - this is
effectively checking if the scheme is I<HTTPS> or not.

=head2 serializer

Returns the optional serializer object used to deserialize request parameters.

=head2 session

Returns the C<psgix.session> hash, if exists.

=head2 session_options

Returns the C<psgix.session.options> hash, if exists.

=head2 to_string

Return a string representing the request object (e.g., C<GET /some/path>).

=head2 upload($name)

Context-aware accessor for uploads. It's a wrapper around an access to the hash
table provided by C<uploads()>. It looks at the calling context and returns a
corresponding value.

If you have many file uploads under the same name, and call C<upload('name')> in
an array context, the accessor will unroll the ARRAY ref for you:

    my @uploads = request->upload('many_uploads'); # OK

Whereas with a manual access to the hash table, you'll end up with one element
in C<@uploads>, being the arrayref:

    my @uploads = request->uploads->{'many_uploads'};
    # $uploads[0]: ARRAY(0xXXXXX)

That is why this accessor should be used instead of a manual access to
C<uploads>.

=head2 uploads

Returns a reference to a hash containing uploads. Values can be either a
L<Dancer2::Core::Request::Upload> object, or an arrayref of
L<Dancer2::Core::Request::Upload>
objects.

You should probably use the C<upload($name)> accessor instead of manually accessing the
C<uploads> hash table.

=head2 uri

An alias to C<request_uri>.

=head2 uri_base

Same thing as C<base> above, except it removes the last trailing slash in the
path if it is the only path.

This means that if your base is I<http://myserver/>, C<uri_base> will return
I<http://myserver> (notice no trailing slash). This is considered very useful
when using templates to do the following thing:

    <link rel="stylesheet" href="[% request.uri_base %]/css/style.css" />

=head2 uri_for(path, params)

Constructs a URI from the base and the passed path. If params (hashref) is
supplied, these are added to the query string of the URI.

Thus, with the following base:

    http://localhost:5000/foo

You get the following behavior:

    my $uri = request->uri_for('/bar', { baz => 'baz' });
    print $uri; # http://localhost:5000/foo/bar?baz=baz

C<uri_for> returns a L<URI> object (which can stringify to the value).

=head2 user

Return remote user if defined.

=head2 var

By-name interface to variables stored in this request object.

  my $stored = $request->var('some_variable');

returns the value of 'some_variable', while

  $request->var('some_variable' => 'value');

will set it.

=head2 vars

Access to the internal hash of variables:

    my $value = $request->vars->{'my_key'};

You want to use C<var> above.

=head1 Common HTTP request headers

Commonly used client-supplied HTTP request headers are available through
specific accessors:

=over 4

=item C<accept>

HTTP header: C<HTTP_ACCEPT>.

=item C<accept_charset>

HTTP header: C<HTTP_ACCEPT_CHARSET>.

=item C<accept_encoding>

HTTP header: C<HTTP_ACCEPT_ENCODING>.

=item C<accept_language>

HTTP header: C<HTTP_ACCEPT_LANGUAGE>.

=item C<agent>

Alias for C<user_agent>) below.

=item C<connection>

HTTP header: C<HTTP_CONNECTION>.

=item C<content_encoding>

HTTP header: C<HTTP_CONTENT_ENCODING>.

=item C<content_length>

HTTP header: C<HTTP_CONTENT_LENGTH>.

=item C<content_type>

HTTP header: C<HTTP_CONTENT_TYPE>.

=item C<forwarded_for_address>

HTTP header: C<HTTP_X_FORWARDED_FOR>.

=item C<forwarded_host>

HTTP header: C<HTTP_X_FORWARDED_HOST>.

=item C<forwarded_protocol>

One of either C<HTTP_X_FORWARDED_PROTOCOL>, C<HTTP_X_FORWARDED_PROTO>, or
C<HTTP_FORWARDED_PROTO>.

=item C<host>

Checks whether we are behind a proxy using the C<behind_proxy>
configuration option, and if so returns the first
C<HTTP_X_FORWARDED_HOST>, since this is a comma separated list.

If you have not configured that you behind a proxy, it returns HTTP
header C<HTTP_HOST>.

=item C<keep_alive>

HTTP header: C<HTTP_KEEP_ALIVE>.

=item C<referer>

HTTP header: C<HTTP_REFERER>.

=item C<user_agent>

HTTP header: C<HTTP_USER_AGENT>.

=item C<x_requested_with>

HTTP header: C<HTTP_X_REQUESTED_WITH>.

=back

=head1 Fetching only params from a given source

If a required source isn't specified, a mixed hashref (or list of key value
pairs, in list context) will be returned; this will contain params from all
sources (route, query, body).

In practical terms, this means that if the param C<foo> is passed both on the
querystring and in a POST body, you can only access one of them.

If you want to see only params from a given source, you can say so by passing
the C<$source> param to C<params()>:

    my %querystring_params = params('query');
    my %route_params       = params('route');
    my %post_params        = params('body');

If source equals C<route>, then only params parsed from the route pattern
are returned.

If source equals C<query>, then only params parsed from the query string are
returned.

If source equals C<body>, then only params sent in the request body will be
returned.

If another value is given for C<$source>, then an exception is triggered.

=head1 EXTRA SPEED

If L<Dancer2::Core::Request> detects the following modules as installed,
it will use them to speed things up:

=over 4

=item * L<URL::Encode::XS>

=item * L<CGI::Deurl::XS>

=back

=head1 AUTHOR

Dancer Core Developers

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2016 by Alexis Sukrieh.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut