| 1 | |||
| 2 | package TUWF::Request; | ||
| 3 | |||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | use Exporter 'import'; | ||
| 7 | use Carp 'croak'; | ||
| 8 | |||
| 9 | our $VERSION = '1.6'; | ||
| 10 | our @EXPORT = qw| | ||
| 11 | reqInit reqGets reqGet reqPosts reqPost reqParams reqParam reqJSON | ||
| 12 | reqUploadMIMEs reqUploadMIME reqUploadRaws reqUploadRaw reqSaveUpload | ||
| 13 | reqCookie reqMethod reqHeader reqPath reqQuery reqProtocol reqBaseURI reqURI reqHost reqIP reqFCGI | ||
| 14 | |; | ||
| 15 | |||
| 16 | our $RENV = \%ENV; | ||
| 17 | |||
| 18 | sub reqInit { | ||
| 19 | my $self = shift; | ||
| 20 | $self->{_TUWF}{Req} = {}; | ||
| 21 | |||
| 22 | # lighttpd doesn't always split the query string from REQUEST_URI | ||
| 23 | if($RENV->{SERVER_SOFTWARE}||'' =~ /lighttpd/) { | ||
| 24 | ($RENV->{REQUEST_URI}, $RENV->{QUERY_STRING}) = split /\?/, $RENV->{REQUEST_URI}, 2 | ||
| 25 | if ($RENV->{REQUEST_URI}||'') =~ /\?/; | ||
| 26 | } | ||
| 27 | |||
| 28 | my $ok = eval { | ||
| 29 | $self->{_TUWF}{Req}{Cookies} = _parse_cookies($self, $RENV->{HTTP_COOKIE} || $RENV->{COOKIE}); | ||
| 30 | $self->{_TUWF}{Req}{GET} = _parse_urlencoded($RENV->{QUERY_STRING}); | ||
| 31 | $self->reqPath(); # let it croak when the path isn't valid UTF-8 | ||
| 32 | 1; | ||
| 33 | }; | ||
| 34 | die $@ if !$ok; | ||
| 35 | |||
| 36 | my $meth = $self->reqMethod; | ||
| 37 | die TUWF::Exception->new('method') if $meth !~ /^(GET|POST|HEAD|DELETE|OPTIONS|PUT|PATCH)$/; | ||
| 38 | |||
| 39 | if($meth =~ /^(POST|PUT|PATCH)$/ && $RENV->{CONTENT_LENGTH}) { | ||
| 40 | die TUWF::Exception->new('maxpost') if $self->{_TUWF}{max_post_body} && $RENV->{CONTENT_LENGTH} > $self->{_TUWF}{max_post_body}; | ||
| 41 | |||
| 42 | my $data; | ||
| 43 | die "Couldn't read all request data.\n" if $RENV->{CONTENT_LENGTH} > read STDIN, $data, $RENV->{CONTENT_LENGTH}, 0; | ||
| 44 | |||
| 45 | eval { | ||
| 46 | if(($RENV->{'CONTENT_TYPE'}||'') =~ m{^application/json(?:;.*)?$}) { | ||
| 47 | $self->{_TUWF}{Req}{JSON} = _parse_json($data); | ||
| 48 | die TUWF::Exception->new('json') if !$self->{_TUWF}{Req}{JSON}; | ||
| 49 | } elsif(($RENV->{'CONTENT_TYPE'}||'') =~ m{^multipart/form-data; boundary=(.+)$}) { | ||
| 50 | _parse_multipart($self, $data, $1); | ||
| 51 | } else { | ||
| 52 | $self->{_TUWF}{Req}{POST} = _parse_urlencoded($data); | ||
| 53 | } | ||
| 54 | 1; | ||
| 55 | } || die $@;; | ||
| 56 | } | ||
| 57 | } | ||
| 58 | |||
| 59 | |||
| 60 | sub _check_control { | ||
| 61 | # Disallow any control codes, except for x09 (tab), x0a (newline) and x0d (carriage return) | ||
| 62 | die TUWF::Exception->new('controlchar') if $_[0] =~ /[\x00-\x08\x0b\x0c\x0e-\x1f]/; | ||
| 63 | $_[0] | ||
| 64 | } | ||
| 65 | |||
| 66 | |||
| 67 | sub _decode_utf8 { | ||
| 68 | utf8::decode(my $v = $_[0]) || die TUWF::Exception->new('utf8'); | ||
| 69 | $v; | ||
| 70 | } | ||
| 71 | |||
| 72 | |||
| 73 | sub _store { | ||
| 74 | return push @{$_[0]}, $_[1] if ref $_[0]; | ||
| 75 | $_[0] = defined $_[0] ? [$_[0], $_[1]] : $_[1]; | ||
| 76 | } | ||
| 77 | |||
| 78 | |||
| 79 | sub _parse_urlencoded { | ||
| 80 | my %dat; | ||
| 81 | my $d = shift; | ||
| 82 | for (split /[;&]/, _decode_utf8 $d) { | ||
| 83 | my($key, $val) = split /=/, $_, 2; | ||
| 84 | next if !defined $key or !defined $val; | ||
| 85 | for ($key, $val) { | ||
| 86 | s/\+/ /gs; | ||
| 87 | # assume %XX sequences represent UTF-8 bytes and properly decode it. | ||
| 88 | s#((?:%[0-9a-fA-F]{2})+)# | ||
| 89 | utf8::downgrade(my $s = $1); | ||
| 90 | $s =~ s/%(.{2})/chr hex($1)/eg; | ||
| 91 | _decode_utf8 $s; | ||
| 92 | #eg; | ||
| 93 | s/%u([0-9a-fA-F]{4})/chr hex($1)/eg; | ||
| 94 | _check_control($_); | ||
| 95 | } | ||
| 96 | _store $dat{$key}, $val; | ||
| 97 | } | ||
| 98 | return \%dat; | ||
| 99 | } | ||
| 100 | |||
| 101 | |||
| 102 | my $_json_codec; | ||
| 103 | sub _parse_json { | ||
| 104 | my $d = shift; | ||
| 105 | $_json_codec ||= TUWF::Misc::_JSON()->new->utf8; | ||
| 106 | |||
| 107 | my $res = eval { $_json_codec->decode($d) }; | ||
| 108 | return undef if !$res || ref $res ne 'HASH'; # We always expect to receive a JSON object. | ||
| 109 | return $res; | ||
| 110 | } | ||
| 111 | |||
| 112 | |||
| 113 | # Heavily inspired by CGI::Minimal::Multipart::_burst_multipart_buffer() | ||
| 114 | sub _parse_multipart { | ||
| 115 | my($self, $data, $boundary) = @_; | ||
| 116 | my $nfo = $self->{_TUWF}{Req}; | ||
| 117 | my $CRLF = "\015\012"; | ||
| 118 | |||
| 119 | $nfo->{POST} = {}; | ||
| 120 | $nfo->{FILES} = {}; | ||
| 121 | $nfo->{MIMES} = {}; | ||
| 122 | |||
| 123 | for my $p (split /--\Q$boundary\E(?:--)?$CRLF/, $data) { | ||
| 124 | next if !defined $p; | ||
| 125 | $p =~ s/$CRLF$//; | ||
| 126 | last if $p eq '--'; | ||
| 127 | next if !$p; | ||
| 128 | my($header, $value) = split /$CRLF$CRLF/, $p, 2; | ||
| 129 | |||
| 130 | my($name, $mime, $filename) = ('', '', ''); | ||
| 131 | for my $h (split /$CRLF/, $header) { | ||
| 132 | my($hn, $hv) = split /: /, $h, 2; | ||
| 133 | # Does not handle multipart/mixed, but those don't appear to be used in practice. | ||
| 134 | if($hn =~ /^Content-Type$/i) { | ||
| 135 | $mime = $hv; | ||
| 136 | } | ||
| 137 | if($hn =~ /^Content-Disposition$/i) { | ||
| 138 | for my $dis (split /; /, $hv) { | ||
| 139 | $name = $2 if $dis =~ /^name=("?)(.*)\1$/; | ||
| 140 | $filename = $2 if $dis =~ /^filename=("?)(.*)\1$/; | ||
| 141 | } | ||
| 142 | } | ||
| 143 | } | ||
| 144 | |||
| 145 | $name = _check_control _decode_utf8 $name; | ||
| 146 | |||
| 147 | # In the case of a file upload, use the filename as value instead of the | ||
| 148 | # data. This is to ensure that reqPOST() always returns decoded data. | ||
| 149 | |||
| 150 | # Note that I use the presence of a filename attribute for determining | ||
| 151 | # whether this parameters comes from an <input type="file"> rather than a | ||
| 152 | # regular form element. The standards do not require the filename to be | ||
| 153 | # present, but I am not aware of any browser that does not send it. | ||
| 154 | if($filename) { | ||
| 155 | _store $nfo->{POST}{$name}, _check_control _decode_utf8 $filename; | ||
| 156 | _store $nfo->{MIMES}{$name}, _check_control _decode_utf8 $mime; | ||
| 157 | _store $nfo->{FILES}{$name}, $value; # not decoded, can be binary | ||
| 158 | } else { | ||
| 159 | _store $nfo->{POST}{$name}, _check_control _decode_utf8 $value; | ||
| 160 | } | ||
| 161 | } | ||
| 162 | } | ||
| 163 | |||
| 164 | |||
| 165 | sub _parse_cookies { | ||
| 166 | my($self, $str) = @_; | ||
| 167 | return {} if !$str; | ||
| 168 | |||
| 169 | my %dat; | ||
| 170 | # The format of the Cookie: header is hardly standardized and the widely used | ||
| 171 | # implementations all differ in how they interpret the data. This (rather) | ||
| 172 | # lazy implementation assumes the cookie values are not escaped and don't | ||
| 173 | # contain any characters that are used within the header format. | ||
| 174 | for (split /[;,]/, _decode_utf8 $str) { | ||
| 175 | s/^ +//; | ||
| 176 | s/ +$//; | ||
| 177 | next if !$_ || !m{^([^\(\)<>@,;:\\"/\[\]\?=\{\}\t\s]+)=("?)(.*)\2$}; | ||
| 178 | my($n, $v) = ($1, $3); | ||
| 179 | next if $self->{_TUWF}{cookie_prefix} && !($n =~ s/^\Q$self->{_TUWF}{cookie_prefix}\E//); | ||
| 180 | _check_control $n; | ||
| 181 | _check_control $v; | ||
| 182 | $dat{$n} = $v if !exists $dat{$n}; | ||
| 183 | } | ||
| 184 | return \%dat; | ||
| 185 | } | ||
| 186 | |||
| 187 | |||
| 188 | sub _tablegets { | ||
| 189 | my($k, $s, $n) = @_; | ||
| 190 | my $lst = $s->{_TUWF}{Req}{$k}; | ||
| 191 | return keys %$lst if @_ == 2; | ||
| 192 | my $v = $lst->{$n}; | ||
| 193 | ref $v ? @$v : defined $v ? ($v) : (); | ||
| 194 | } | ||
| 195 | |||
| 196 | |||
| 197 | sub _tableget { | ||
| 198 | my($k, $s, $n) = @_; | ||
| 199 | my $v = $s->{_TUWF}{Req}{$k}{$n}; | ||
| 200 | ref $v ? $v->[0] : $v; | ||
| 201 | } | ||
| 202 | |||
| 203 | |||
| 204 | sub reqGets { _tablegets(GET => @_) } | ||
| 205 | sub reqGet { _tableget (GET => @_) } | ||
| 206 | sub reqPosts { _tablegets(POST => @_) } | ||
| 207 | sub reqPost { _tableget (POST => @_) } | ||
| 208 | sub reqUploadMIMEs { _tablegets(MIMES => @_) } | ||
| 209 | sub reqUploadMIME { _tableget (MIMES => @_) } | ||
| 210 | sub reqUploadRaws { _tablegets(FILES => @_) } | ||
| 211 | sub reqUploadRaw { _tableget (FILES => @_) } | ||
| 212 | |||
| 213 | |||
| 214 | # get parameters from either or both POST and GET | ||
| 215 | # (POST has priority over GET in scalar context) | ||
| 216 | sub reqParams { | ||
| 217 | my($s, $n) = @_; | ||
| 218 | my $nfo = $s->{_TUWF}{Req}; | ||
| 219 | if(!$n) { | ||
| 220 | my %keys = map +($_,1), keys(%{$nfo->{GET}}), keys(%{$nfo->{POST}}); | ||
| 221 | return keys %keys; | ||
| 222 | } | ||
| 223 | my $p = $nfo->{POST}{$n}; | ||
| 224 | my $g = $nfo->{GET}{$n}; | ||
| 225 | return ( | ||
| 226 | ref $p ? @$p : defined $p ? ($p) : (), | ||
| 227 | ref $g ? @$g : defined $g ? ($g) : (), | ||
| 228 | ); | ||
| 229 | } | ||
| 230 | |||
| 231 | |||
| 232 | # (POST has priority over GET in scalar context) | ||
| 233 | sub reqParam { | ||
| 234 | my($s, $n) = @_; | ||
| 235 | my $nfo = $s->{_TUWF}{Req}; | ||
| 236 | my $v = $nfo->{POST}{$n} || $nfo->{GET}{$n}; | ||
| 237 | ref $v ? $v->[0] : $v; | ||
| 238 | } | ||
| 239 | |||
| 240 | |||
| 241 | sub reqJSON { | ||
| 242 | return shift->{_TUWF}{Req}{JSON}; | ||
| 243 | } | ||
| 244 | |||
| 245 | |||
| 246 | # saves file contents identified by the form name to the specified file | ||
| 247 | # (doesn't support multiple file upload using the same form name yet) | ||
| 248 | sub reqSaveUpload { | ||
| 249 | my($s, $n, $f) = @_; | ||
| 250 | open my $F, '>', $f or croak "Unable to write to $f: $!"; | ||
| 251 | print $F $s->reqUploadRaw($n); | ||
| 252 | close $F; | ||
| 253 | } | ||
| 254 | |||
| 255 | |||
| 256 | sub reqCookie { | ||
| 257 | my($self, $n) = @_; | ||
| 258 | my $nfo = $self->{_TUWF}{Req}{Cookies}; | ||
| 259 | return keys %$nfo if @_ == 1; | ||
| 260 | return $nfo->{$n}; | ||
| 261 | } | ||
| 262 | |||
| 263 | |||
| 264 | sub reqMethod { | ||
| 265 | return $RENV->{REQUEST_METHOD}||'GET'; | ||
| 266 | } | ||
| 267 | |||
| 268 | |||
| 269 | # Returns list of header names when no argument is passed | ||
| 270 | # (may be in a different order and can have different casing than | ||
| 271 | # the original headers - CGI doesn't preserve that information) | ||
| 272 | # Returns value of the specified header otherwise, header name is | ||
| 273 | # case-insensitive | ||
| 274 | sub reqHeader { | ||
| 275 | my($self, $name) = @_; | ||
| 276 | if(@_ == 2) { | ||
| 277 | (my $v = uc $_[1]) =~ tr/-/_/; | ||
| 278 | $v = $RENV->{"HTTP_$v"}||''; | ||
| 279 | return _check_control _decode_utf8 $v; | ||
| 280 | } else { | ||
| 281 | return (map { | ||
| 282 | if(/^HTTP_/) { | ||
| 283 | (my $h = lc $_) =~ s/_([a-z])/-\U$1/g; | ||
| 284 | $h =~ s/^http-//; | ||
| 285 | _check_control _decode_utf8 $h; | ||
| 286 | } else { () } | ||
| 287 | } sort keys %$RENV); | ||
| 288 | } | ||
| 289 | } | ||
| 290 | |||
| 291 | |||
| 292 | # returns the path part of the current URI, including the leading slash | ||
| 293 | sub reqPath { | ||
| 294 | (my $u = ($RENV->{REQUEST_URI}||'')) =~ s{\?.*$}{}; | ||
| 295 | return _check_control _decode_utf8 $u; | ||
| 296 | } | ||
| 297 | |||
| 298 | |||
| 299 | sub reqProtocol { | ||
| 300 | return $RENV->{HTTPS} ? 'https' : 'http'; | ||
| 301 | } | ||
| 302 | |||
| 303 | |||
| 304 | # returns base URI, excluding trailing slash | ||
| 305 | sub reqBaseURI { | ||
| 306 | my $s = shift; | ||
| 307 | return $s->reqProtocol().'://'.$s->reqHost(); | ||
| 308 | } | ||
| 309 | |||
| 310 | |||
| 311 | sub reqQuery { | ||
| 312 | my $u = $RENV->{QUERY_STRING} ? '?'.$RENV->{QUERY_STRING} : ''; | ||
| 313 | return _check_control _decode_utf8 $u; | ||
| 314 | } | ||
| 315 | |||
| 316 | |||
| 317 | sub reqURI { | ||
| 318 | my $s = shift; | ||
| 319 | return $s->reqBaseURI().$s->reqPath().$s->reqQuery(); | ||
| 320 | } | ||
| 321 | |||
| 322 | |||
| 323 | sub reqHost { | ||
| 324 | return $RENV->{HTTP_HOST}||'localhost'; | ||
| 325 | } | ||
| 326 | |||
| 327 | |||
| 328 | sub reqIP { | ||
| 329 | return $RENV->{REMOTE_ADDR}||'0.0.0.0'; | ||
| 330 | } | ||
| 331 | |||
| 332 | |||
| 333 | sub reqFCGI { | ||
| 334 | return shift->{_TUWF}{fcgi_req}; | ||
| 335 | } | ||
| 336 | |||
| 337 | 1; |