| 1 | ##---------------------------------------------------------------------------- | ||
| 2 | ## Asynchronous HTTP Request and Promise - ~/lib/HTTP/Promise/Parser.pm | ||
| 3 | ## Version v0.2.3 | ||
| 4 | ## Copyright(c) 2025 DEGUEST Pte. Ltd. | ||
| 5 | ## Author: Jacques Deguest <jack@deguest.jp> | ||
| 6 | ## Created 2022/03/25 | ||
| 7 | ## Modified 2025/10/19 | ||
| 8 | ## All rights reserved. | ||
| 9 | ## | ||
| 10 | ## | ||
| 11 | ## This program is free software; you can redistribute it and/or modify it | ||
| 12 | ## under the same terms as Perl itself. | ||
| 13 | ##---------------------------------------------------------------------------- | ||
| 14 | package HTTP::Promise::Parser; | ||
| 15 | BEGIN | ||
| 16 | { | ||
| 17 | use strict; | ||
| 18 | use warnings; | ||
| 19 | warnings::register_categories( 'HTTP::Promise' ); | ||
| 20 | use parent qw( Module::Generic ); | ||
| 21 | use vars qw( @EXPORT @EXPORT_OK %EXPORT_TAGS $VERSION $DEBUG $EXCEPTION_CLASS | ||
| 22 | $CRLF $LWS $TEXT $TOKEN $HEADER $HTTP_VERSION $REQUEST $RESPONSE | ||
| 23 | $MAX_HEADERS_SIZE $MAX_READ_BUFFER $MAX_BODY_IN_MEMORY_SIZE | ||
| 24 | $DEFAULT_MIME_TYPE ); | ||
| 25 | use version; | ||
| 26 | # use HTTP::Parser::XS 0.17 (); | ||
| 27 | use HTTP::Parser2::XS 0.01 (); | ||
| 28 | use HTTP::Promise::Entity; | ||
| 29 | use HTTP::Promise::Headers; | ||
| 30 | use HTTP::Promise::IO; | ||
| 31 | use Module::Generic::File qw( sys_tmpdir ); | ||
| 32 | # use Nice::Try; | ||
| 33 | use URI; | ||
| 34 | use URI::Encode::XS; | ||
| 35 | use Wanted; | ||
| 36 | use constant ( | ||
| 37 | TYPE_URL_ENCODED => 'application/x-www-form-urlencoded', | ||
| 38 | ); | ||
| 39 | our @EXPORT = (); | ||
| 40 | our @EXPORT_OK = qw( parse_headers parse_request parse_request_line parse_response | ||
| 41 | parse_response_line parse_version ); | ||
| 42 | our %EXPORT_TAGS = ( | ||
| 43 | 'all' => [@EXPORT_OK], | ||
| 44 | 'request' => [qw( parse_headers parse_request parse_request_line parse_version )], | ||
| 45 | 'response' => [qw( parse_headers parse_response parse_response_line parse_version )], | ||
| 46 | ); | ||
| 47 | # rfc2616, section 2.2 on basic rules | ||
| 48 | # <https://tools.ietf.org/html/rfc2616#section-2.2> | ||
| 49 | our $CRLF = qr/\x0D?\x0A/; | ||
| 50 | our $LWS = qr/$CRLF[\x09\x20]|[\x09\x20]/; | ||
| 51 | our $TEXT = qr/[\x20-\xFF]/; | ||
| 52 | # !, #, $, %, &, ', *, +, -, ., 0..9, A..Z, ^, _, `, a..z, |, ~ | ||
| 53 | our $TOKEN = qr/[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7A\x7C\x7E]/; | ||
| 54 | # rfc2616, section 4.2 on message headers | ||
| 55 | # <https://tools.ietf.org/html/rfc2616#section-4.2> | ||
| 56 | # rfc7230, section 3.2 | ||
| 57 | # <https://tools.ietf.org/html/rfc7230#section-3.2> | ||
| 58 | our $HEADER = qr/($TOKEN+)$LWS*:$LWS*((?:$TEXT|$LWS)*)$CRLF/; | ||
| 59 | # HTTP/1.0, HTTP/1.1, HTTP/2 | ||
| 60 | our $HTTP_VERSION = qr/(?<http_protocol>HTTP\/(?<http_version>(?<http_vers_major>[0-9])(?:\.(?<http_vers_minor>[0-9]))?))/; | ||
| 61 | # rfc7230 superseding rfc2616 on request line | ||
| 62 | # <https://tools.ietf.org/html/rfc7230#page-21> | ||
| 63 | our $REQUEST = qr/(?<method>$TOKEN+)[\x09\x20]+(?<uri>[\x21-\xFF]+)[\x09\x20]+(?<protocol>$HTTP_VERSION)$CRLF/; | ||
| 64 | our $REQUEST_RFC2616 = qr/(?:$CRLF)*($TOKEN+)[\x09\x20]+([\x21-\xFF]+)(?:[\x09\x20]+($HTTP_VERSION))?$CRLF/; | ||
| 65 | our $RESPONSE = qr/(?<protocol>$HTTP_VERSION)[\x09\x20]+(?<code>[0-9]{3})[\x09\x20]+(?<status>$TEXT*)$CRLF/; | ||
| 66 | # 8Kb | ||
| 67 | # Beyond this, we return a 413 Entity Too Large | ||
| 68 | # Ref: <https://stackoverflow.com/questions/686217/maximum-on-http-header-values> | ||
| 69 | our $MAX_HEADERS_SIZE = 8192; | ||
| 70 | our $MAX_READ_BUFFER = 2048; | ||
| 71 | # 100Kb | ||
| 72 | our $MAX_BODY_IN_MEMORY_SIZE = 102400; | ||
| 73 | our $DEFAULT_MIME_TYPE = 'application/octet-stream'; | ||
| 74 | our $DEBUG = 0; | ||
| 75 | our $EXCEPTION_CLASS = 'HTTP::Promise::Exception'; | ||
| 76 | our $VERSION = 'v0.2.3'; | ||
| 77 | }; | ||
| 78 | |||
| 79 | use strict; | ||
| 80 | use warnings; | ||
| 81 | |||
| 82 | sub init | ||
| 83 | { | ||
| 84 | my $self = shift( @_ ); | ||
| 85 | $self->{decode_body} = 1; | ||
| 86 | $self->{decode_headers} = 0; | ||
| 87 | $self->{ignore_filename}= 0; | ||
| 88 | $self->{max_body_in_memory_size} = $MAX_BODY_IN_MEMORY_SIZE; | ||
| 89 | $self->{max_headers_size} = $MAX_HEADERS_SIZE; | ||
| 90 | $self->{max_read_buffer} = $MAX_READ_BUFFER; | ||
| 91 | $self->{output_dir} = sys_tmpdir(); | ||
| 92 | $self->{tmp_dir} = undef; | ||
| 93 | $self->{tmp_to_core} = 0; | ||
| 94 | $self->{_init_strict_use_sub} = 1; | ||
| 95 | $self->{_exception_class} = $EXCEPTION_CLASS; | ||
| 96 | $self->SUPER::init( @_ ) || return( $self->pass_error ); | ||
| 97 | my $dir = $self->output_dir; | ||
| 98 | return( $self->error( "No output directory set." ) ) if( !defined( $dir ) || !length( $dir ) ); | ||
| 99 | return( $self->error( "Output directory set \"$dir\" does not exist." ) ) if( !$dir->exists ); | ||
| 100 | return( $self->error( "Output directory set \"$dir\" is not actually a directory." ) ) if( !$dir->is_dir ); | ||
| 101 | return( $self ); | ||
| 102 | } | ||
| 103 | |||
| 104 | sub decode_body { return( shift->_set_get_boolean( 'decode_body', @_ ) ); } | ||
| 105 | |||
| 106 | sub decode_headers { return( shift->_set_get_boolean( 'decode_headers', @_ ) ); } | ||
| 107 | |||
| 108 | sub ignore_filename { return( shift->_set_get_boolean( 'ignore_filename', @_ ) ); } | ||
| 109 | |||
| 110 | sub looks_like_request | ||
| 111 | { | ||
| 112 | my $self = shift( @_ ); | ||
| 113 | my $this = shift( @_ ); | ||
| 114 | return( $self->error( "Invalid argument. You can only provide either a string or a scalar reference." ) ) if( ref( $this ) && !$self->_is_scalar( $this ) ); | ||
| 115 | my $ref = $self->_is_scalar( $this ) ? $this : \$this; | ||
| 116 | if( $$ref =~ /^$REQUEST/ ) | ||
| 117 | { | ||
| 118 | my $def = {%+}; | ||
| 119 | return( $def ); | ||
| 120 | } | ||
| 121 | else | ||
| 122 | { | ||
| 123 | # undef is for errors | ||
| 124 | return( '' ); | ||
| 125 | } | ||
| 126 | } | ||
| 127 | |||
| 128 | sub looks_like_response | ||
| 129 | { | ||
| 130 | my $self = shift( @_ ); | ||
| 131 | my $this = shift( @_ ); | ||
| 132 | return( $self->error( "Invalid argument. You can only provide either a string or a scalar reference." ) ) if( ref( $this ) && !$self->_is_scalar( $this ) ); | ||
| 133 | my $ref = $self->_is_scalar( $this ) ? $this : \$this; | ||
| 134 | if( $$ref =~ /^$RESPONSE/ ) | ||
| 135 | { | ||
| 136 | my $def = {%+}; | ||
| 137 | return( $def ); | ||
| 138 | } | ||
| 139 | else | ||
| 140 | { | ||
| 141 | # undef is for errors | ||
| 142 | return( '' ); | ||
| 143 | } | ||
| 144 | } | ||
| 145 | |||
| 146 | sub looks_like_what | ||
| 147 | { | ||
| 148 | my $self = shift( @_ ); | ||
| 149 | my $this = shift( @_ ); | ||
| 150 | # Shortcut | ||
| 151 | return( '' ) if( !defined( $this ) ); | ||
| 152 | return( $self->error( "Invalid argument. You can only provide either a string or a scalar reference." ) ) if( ref( $this ) && !$self->_is_scalar( $this ) ); | ||
| 153 | my $ref = $self->_is_scalar( $this ) ? $this : \$this; | ||
| 154 | # No need to go further | ||
| 155 | return( '' ) if( !defined( $$ref ) || !length( $$ref ) ); | ||
| 156 | my( $type, $def ); | ||
| 157 | if( $$ref =~ /^$REQUEST/ ) | ||
| 158 | { | ||
| 159 | $def = {%+}; | ||
| 160 | $type = 'request'; | ||
| 161 | } | ||
| 162 | elsif( $$ref =~ /^$RESPONSE/ ) | ||
| 163 | { | ||
| 164 | $def = {%+}; | ||
| 165 | $type = 'response'; | ||
| 166 | } | ||
| 167 | # undef is for errors | ||
| 168 | return( '' ) if( !defined( $def ) ); | ||
| 169 | $def->{type} = $type; | ||
| 170 | return( $def ); | ||
| 171 | } | ||
| 172 | |||
| 173 | sub max_body_in_memory_size { return( shift->_set_get_number( 'max_body_in_memory_size', @_ ) ); } | ||
| 174 | |||
| 175 | sub max_headers_size { return( shift->_set_get_number( 'max_headers_size', @_ ) ); } | ||
| 176 | |||
| 177 | sub max_read_buffer { return( shift->_set_get_number( 'max_read_buffer', @_ ) ); } | ||
| 178 | |||
| 179 | sub new_tmpfile | ||
| 180 | { | ||
| 181 | my $self = shift( @_ ); | ||
| 182 | my $io; | ||
| 183 | if( $self->tmp_to_core ) | ||
| 184 | { | ||
| 185 | my $var = $self->new_scalar; | ||
| 186 | $io = $var->open( '+>' ) || return( $self->pass_error( $var->error ) ); | ||
| 187 | } | ||
| 188 | else | ||
| 189 | { | ||
| 190 | my $tmpdir = $self->tmp_dir; | ||
| 191 | $io = $self->new_tempfile( $tmpdir ? ( dir => $tmpdir ) : () ) || | ||
| 192 | return( $self->pass_error ); | ||
| 193 | $io->open( '>', { binmode => 'raw', autoflush => 1 } ) || return( $self->pass_error( $io->error ) ); | ||
| 194 | } | ||
| 195 | return( $io ); | ||
| 196 | } | ||
| 197 | |||
| 198 | sub output_dir { return( shift->_set_get_file( 'output_dir', @_ ) ); } | ||
| 199 | |||
| 200 | sub parse | ||
| 201 | { | ||
| 202 | my $self = shift( @_ ); | ||
| 203 | my $this = shift( @_ ) || return( $self->error( "Nothing to parse was provided." ) ); | ||
| 204 | # Can be glob, scalar reference, file path | ||
| 205 | my $io; | ||
| 206 | if( $self->_is_glob( $this ) ) | ||
| 207 | { | ||
| 208 | $io = $this; | ||
| 209 | } | ||
| 210 | elsif( $self->_is_scalar( $this ) ) | ||
| 211 | { | ||
| 212 | $self->_load_class( 'Module::Generic::Scalar::IO' ) || | ||
| 213 | return( $self->pass_error ); | ||
| 214 | $io = Module::Generic::Scalar::IO->new( $this, '<' ) || | ||
| 215 | return( $self->pass_error( Module::Generic::Scalar::IO->error ) ); | ||
| 216 | } | ||
| 217 | else | ||
| 218 | { | ||
| 219 | my $f = $self->new_file( $this ) || return( $self->pass_error ); | ||
| 220 | $io = $f->open( '<', { binmode => 'raw' } ) || return( $self->pass_error( $f->error ) ); | ||
| 221 | } | ||
| 222 | return( $self->parse_fh( $io, @_ ) ); | ||
| 223 | } | ||
| 224 | |||
| 225 | sub parse_data | ||
| 226 | { | ||
| 227 | my $self = shift( @_ ); | ||
| 228 | return( $self->error( "Invalid argument. parse_data() only accepts either a string or something that stringifies." ) ) if( ref( $_[0] ) && !overload::Method( $_[0] => '""' ) ); | ||
| 229 | return( $self->parse( \"$_[0]" ) ); | ||
| 230 | } | ||
| 231 | |||
| 232 | sub parse_fh | ||
| 233 | { | ||
| 234 | my $self = shift( @_ ); | ||
| 235 | my $fh = shift( @_ ); | ||
| 236 | return( $self->error( "No filehandle was provided to read from." ) ) if( !defined( $fh ) ); | ||
| 237 | return( $self->error( "Filehandle provided (", overload::StrVal( $fh ), ") is not a valid filehandle." ) ) if( !$self->_is_glob( $fh ) ); | ||
| 238 | my $opts = $self->_get_args_as_hash( @_ ); | ||
| 239 | my $reader; | ||
| 240 | if( $reader = $opts->{reader} ) | ||
| 241 | { | ||
| 242 | return( $self->error( "Reader object provided (", overload::StrVal( $reader ), ") is not a HTTP::Promise::IO." ) ) if( !$self->_is_a( $reader => 'HTTP::Promise::IO' ) ); | ||
| 243 | } | ||
| 244 | else | ||
| 245 | { | ||
| 246 | $reader = HTTP::Promise::IO->new( $fh, max_read_buffer => $self->max_read_buffer, debug => $self->debug ) || | ||
| 247 | return( $self->pass_error( HTTP::Promise::IO->error ) ); | ||
| 248 | } | ||
| 249 | # "It is RECOMMENDED that all HTTP senders and recipients support, at a minimum, request-line lengths of 8000 octets." | ||
| 250 | # Ref: <https://tools.ietf.org/html/rfc7230#section-3.1.1> | ||
| 251 | my $buff = $reader->getline( max_read_buffer => 8192 ); | ||
| 252 | # "A server that receives a method longer than any that it implements SHOULD respond with a 501 (Not Implemented) status code." | ||
| 253 | # Ref: <https://tools.ietf.org/html/rfc7230#section-3.1.1> | ||
| 254 | return( $self->pass_error( $reader->error ) ) if( !defined( $buff ) ); | ||
| 255 | unless( $opts->{request} || $opts->{response} ) | ||
| 256 | { | ||
| 257 | # Ref: <https://tools.ietf.org/html/rfc7230#section-3.1.2> | ||
| 258 | if( $buff =~ m,^(${HTTP_VERSION})[[:blank:]]+, ) | ||
| 259 | { | ||
| 260 | $opts->{response} = 1; | ||
| 261 | } | ||
| 262 | # rfc7230, section 3.1 | ||
| 263 | # Ref: <https://tools.ietf.org/html/rfc7230#section-3.1> | ||
| 264 | elsif( $buff =~ m,^(?:CONNECT|DELETE|GET|HEAD|OPTIONS|PATCH|POST|PUT|TRACE)[[:blank:]]+(\S+)[[:blank:]]+${HTTP_VERSION}, ) | ||
| 265 | { | ||
| 266 | $opts->{request} = 1; | ||
| 267 | } | ||
| 268 | # Actually we accept an http message that does not have a first line. | ||
| 269 | # We just won't know what it is for, but it is ok, since we return an entity object | ||
| 270 | # else | ||
| 271 | # { | ||
| 272 | # return( $self->error( "Unknown http message type and no 'request' or 'response' boolean value was provided," ) ); | ||
| 273 | # } | ||
| 274 | } | ||
| 275 | |||
| 276 | # Maximum headers size is not oficial, but we definitely need to set some limit. | ||
| 277 | # <https://security.stackexchange.com/questions/110565/large-over-sizesd-http-header-lengths-and-security-implications> | ||
| 278 | my $max = $self->max_headers_size; | ||
| 279 | my( $n, $def, $headers ); | ||
| 280 | $n = -1; | ||
| 281 | while( $n != 0 ) | ||
| 282 | { | ||
| 283 | $n = $reader->read( $buff, 2048, length( $buff ) ); | ||
| 284 | return( $self->pass_error( $reader->error ) ) if( !defined( $n ) ); | ||
| 285 | if( $n == 0 ) | ||
| 286 | { | ||
| 287 | if( !length( $buff ) ) | ||
| 288 | { | ||
| 289 | return( $self->error({ code => 400, message => "No data could be retrieved from filehandle." }) ); | ||
| 290 | } | ||
| 291 | else | ||
| 292 | { | ||
| 293 | return( $self->error({ code => 425, message => "No headers data could be retrieved in the first " . length( $buff ) . " bytes of data read." }) ); | ||
| 294 | } | ||
| 295 | } | ||
| 296 | |||
| 297 | # If we know the type of http message we are dealing with, we use the fast XS method | ||
| 298 | if( $opts->{request} || $opts->{response} ) | ||
| 299 | { | ||
| 300 | $def = $self->parse_headers_xs( \$buff, $opts ); | ||
| 301 | # $def = $self->parse_headers( \$buff, $opts ); | ||
| 302 | } | ||
| 303 | # otherwise, we use a more lenient one that does not require a request or response line | ||
| 304 | else | ||
| 305 | { | ||
| 306 | $def = $self->parse_headers( \$buff, $opts ); | ||
| 307 | } | ||
| 308 | |||
| 309 | if( !defined( $def ) ) | ||
| 310 | { | ||
| 311 | # 400 Bad request | ||
| 312 | return( $self->error({ code => 400, message => "Unable to find the headers in the request provided, within the first ${max} bytes of data. Do you need to increase the value for max_headers_size() ?" }) ) if( $self->error->code == 400 && length( $buff ) > $max ); | ||
| 313 | # Is it an error 425 Too Early, it means we need more data. | ||
| 314 | next if( $self->error->code == 425 ); | ||
| 315 | # For other errors, we stop and pass the error received | ||
| 316 | return( $self->pass_error ); | ||
| 317 | } | ||
| 318 | else | ||
| 319 | { | ||
| 320 | $headers = $def->{headers} || | ||
| 321 | return( $self->error( "No headers object set by parse_headers_xs() !" ) ); | ||
| 322 | return( $self->error( "parse_headers_xs() did not return the headers length as an integer ($def->{length})" ) ) if( !$self->_is_integer( $def->{length} ) ); | ||
| 323 | return( $self->error( "Headers length returned by parse_headers_xs() ($def->{length}) is higher than our buffer size (", length( $buff ), ") !" ) ) if( $def->{length} > length( $buff ) ); | ||
| 324 | substr( $buff, 0, $def->{length}, '' ); | ||
| 325 | $reader->unread( $buff ) if( length( $buff ) ); | ||
| 326 | last; | ||
| 327 | } | ||
| 328 | } | ||
| 329 | # We need to consume the blank line separating the headers and the body, so it does | ||
| 330 | # not become part of the body, and because it does not belong anywhere | ||
| 331 | my $trash = $reader->read_until_in_memory( qr/${CRLF}/, include => 1 ); | ||
| 332 | |||
| 333 | my $ent = HTTP::Promise::Entity->new( headers => $headers, debug => $DEBUG ); | ||
| 334 | if( ( $opts->{request} || $opts->{response} ) && $def->{protocol} ) | ||
| 335 | { | ||
| 336 | my $message; | ||
| 337 | if( $opts->{request} ) | ||
| 338 | { | ||
| 339 | $self->_load_class( 'HTTP::Promise::Request' ) || return( $self->pass_error ); | ||
| 340 | $message = HTTP::Promise::Request->new( @$def{qw( method uri headers )}, { | ||
| 341 | protocol => $def->{protocol}, | ||
| 342 | version => $def->{version}, | ||
| 343 | debug => $DEBUG | ||
| 344 | } ) || | ||
| 345 | return( $self->pass_error( HTTP::Promise::Request->error ) ); | ||
| 346 | } | ||
| 347 | else | ||
| 348 | { | ||
| 349 | $self->_load_class( 'HTTP::Promise::Response' ) || return( $self->pass_error ); | ||
| 350 | $message = HTTP::Promise::Response->new( @$def{qw( code status headers )}, { | ||
| 351 | protocol => $def->{protocol}, | ||
| 352 | version => $def->{version}, | ||
| 353 | debug => $DEBUG | ||
| 354 | } ) || | ||
| 355 | return( $self->pass_error( HTTP::Promise::Response->error ) ); | ||
| 356 | } | ||
| 357 | # Mutual assignment for convenience | ||
| 358 | $message->entity( $ent ); | ||
| 359 | $ent->http_message( $message ); | ||
| 360 | } | ||
| 361 | my $type = $ent->mime_type; | ||
| 362 | my $part_ent; | ||
| 363 | # Request body can be one of 3 types: | ||
| 364 | # application/x-www-form-urlencoded | ||
| 365 | # multipart/form-data | ||
| 366 | # text/plain or other mime types | ||
| 367 | # <https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST> | ||
| 368 | if( $type =~ m,^multipart/,i ) | ||
| 369 | { | ||
| 370 | $part_ent = $self->parse_multi_part( entity => $ent, reader => $reader ) || | ||
| 371 | return( $self->pass_error ); | ||
| 372 | # Post process to assign a name to each part, to make it easy to manipulate them | ||
| 373 | for( $ent->parts->list ) | ||
| 374 | { | ||
| 375 | if( my $dispo = $_->headers->content_disposition ) | ||
| 376 | { | ||
| 377 | my $cd = $_->headers->new_field( 'Content-Disposition' => $dispo ); | ||
| 378 | return( $self->pass_error( $_->headers->error ) ) if( !defined( $cd ) ); | ||
| 379 | if( my $name = $cd->name ) | ||
| 380 | { | ||
| 381 | $_->name( $name ); | ||
| 382 | } | ||
| 383 | } | ||
| 384 | } | ||
| 385 | } | ||
| 386 | else | ||
| 387 | { | ||
| 388 | $part_ent = $self->parse_singleton( entity => $ent, reader => $reader ) || | ||
| 389 | return( $self->pass_error ); | ||
| 390 | } | ||
| 391 | return( $ent ); | ||
| 392 | } | ||
| 393 | |||
| 394 | sub parse_headers($$) | ||
| 395 | { | ||
| 396 | my $self = shift( @_ ); | ||
| 397 | my $str = $self->_get_args( shift( @_ ) ); | ||
| 398 | return( $self->pass_error ) if( !defined( $str ) ); | ||
| 399 | my $opts = $self->_get_args_as_hash( @_ ); | ||
| 400 | $opts->{convert_dash} //= 0; | ||
| 401 | $opts->{no_headers_ok} //= 0; | ||
| 402 | if( !CORE::length( $$str ) ) | ||
| 403 | { | ||
| 404 | return({ | ||
| 405 | length => 0, | ||
| 406 | headers => HTTP::Promise::Headers->new, | ||
| 407 | }); | ||
| 408 | } | ||
| 409 | |||
| 410 | # Basic error catching | ||
| 411 | if( $$str !~ /${CRLF}${CRLF}/ ) | ||
| 412 | { | ||
| 413 | return( $self->error({ code => 425, message => 'Incomplete request, call again when there is more data.', class => $EXCEPTION_CLASS }) ); | ||
| 414 | } | ||
| 415 | |||
| 416 | my $def = {}; | ||
| 417 | pos( $$str ) = 0; | ||
| 418 | if( $$str =~ m,^(${HTTP_VERSION})[[:blank:]]+(?<code>\d{3})[[:blank:]]+(?<status>.*?)$CRLF,gc ) | ||
| 419 | { | ||
| 420 | @$def{qw( protocol code status )} = @+{qw( http_protocol code status )}; | ||
| 421 | $def->{version} = version->parse( $+{http_version} ); | ||
| 422 | } | ||
| 423 | # rfc7230, section 3.1 | ||
| 424 | # Ref: <https://tools.ietf.org/html/rfc7230#section-3.1> | ||
| 425 | # CONNECT, DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, TRACE | ||
| 426 | # But there could be others including non-standard ones | ||
| 427 | elsif( $$str =~ m|^(?<method>[A-Z]{3,12})[[:blank:]]+(?<uri>\S+)[[:blank:]]+(${HTTP_VERSION})$CRLF|gc ) | ||
| 428 | { | ||
| 429 | @$def{qw( method uri protocol )} = @+{qw( method uri http_protocol )}; | ||
| 430 | $def->{version} = version->parse( $+{http_version} ); | ||
| 431 | } | ||
| 432 | # HTTP/0.9 "Simple Request" | ||
| 433 | # See rfc1945, section 5 | ||
| 434 | # <https://tools.ietf.org/html/rfc1945#page-23> | ||
| 435 | elsif( $$str =~ m|^(GET)[[:blank:]]+(\S+)[[:blank:]]*$CRLF|gc ) | ||
| 436 | { | ||
| 437 | @$def{qw( method uri )} = ( $1, $2 ); | ||
| 438 | $def->{protocol} = 'HTTP/0.9'; | ||
| 439 | $def->{version} = version->parse( '0.9' ); | ||
| 440 | # There should not be any header in a simple request | ||
| 441 | return( $self->error({ code => 400, message => 'Bad request', class => $EXCEPTION_CLASS }) ) if( $$str =~ /^$HEADER/ ); | ||
| 442 | $def->{length} = pos( $$str ); | ||
| 443 | $def->{headers} = HTTP::Promise::Headers->new; | ||
| 444 | return( $def ); | ||
| 445 | } | ||
| 446 | elsif( $$str =~ /^(?:[A-Z]+\/\d+\.\d+|[A-Z]+[[:blank:]\h]+(?!\:))/ ) | ||
| 447 | { | ||
| 448 | my $type = $$str =~ m,^[A-Z]+\/\d+\.\d+, ? 'Response' : 'Request'; | ||
| 449 | return( $self->error({ code => 400, message => "Bad ${type}-Line", class => $EXCEPTION_CLASS }) ); | ||
| 450 | } | ||
| 451 | |||
| 452 | if( pos( $$str ) == 0 && $$str !~ /^$HEADER/ ) | ||
| 453 | { | ||
| 454 | return( $self->error({ code => 400, message => 'Bad request', class => $EXCEPTION_CLASS }) ); | ||
| 455 | } | ||
| 456 | |||
| 457 | my $headers = $self->new_array; | ||
| 458 | |||
| 459 | my $len = 0; | ||
| 460 | # my $remain = CORE::length( $$str ); | ||
| 461 | # while( $$str =~ s/^$HEADER// ) | ||
| 462 | while( $$str =~ /\G$HEADER/gc ) | ||
| 463 | { | ||
| 464 | # $len += ( $remain - CORE::length( $$str ) ); | ||
| 465 | # $remain = CORE::length( $$str ); | ||
| 466 | my( $n, $v ) = ( lc( $1 ), $2 ); | ||
| 467 | $n =~ tr/-/_/ if( $opts->{convert_dash} ); | ||
| 468 | $headers->push( $n => $v ); | ||
| 469 | } | ||
| 470 | $len = pos( $$str ); | ||
| 471 | |||
| 472 | unless( $$str =~ /\G${CRLF}/gc ) | ||
| 473 | { | ||
| 474 | my $type = $def->{code} ? 'response' : 'request'; | ||
| 475 | return( $self->error({ code => 400, message => "Bad ${type}", class => $EXCEPTION_CLASS }) ); | ||
| 476 | } | ||
| 477 | |||
| 478 | foreach( @$headers ) | ||
| 479 | { | ||
| 480 | s/$LWS+/\x20/g; | ||
| 481 | s/^$LWS//; | ||
| 482 | s/$LWS$//; | ||
| 483 | } | ||
| 484 | # return( want( 'LIST' ) ? $headers->list : $headers ); | ||
| 485 | $def->{length} = $len; | ||
| 486 | $def->{headers} = HTTP::Promise::Headers->new( @$headers ); | ||
| 487 | return( $def ); | ||
| 488 | } | ||
| 489 | |||
| 490 | sub parse_headers_xs($$) | ||
| 491 | { | ||
| 492 | my $self = shift( @_ ); | ||
| 493 | my $str = $self->_get_args( shift( @_ ) ) || return( $self->pass_error ); | ||
| 494 | my $opts = $self->_get_args_as_hash( @_ ); | ||
| 495 | if( ( !exists( $opts->{request} ) && !exists( $opts->{response} ) ) || | ||
| 496 | ( !length( $opts->{request} ) && !length( $opts->{response} ) ) ) | ||
| 497 | { | ||
| 498 | return( $self->error({ code => 500, message => "Missing 'request' or 'response' property to ste how to parse the http headers.", class => $EXCEPTION_CLASS }) ); | ||
| 499 | } | ||
| 500 | my $max_headers_size = $self->max_headers_size // 0; | ||
| 501 | |||
| 502 | my $r = {}; | ||
| 503 | my $len; | ||
| 504 | my $bkp_version; | ||
| 505 | # try-catch | ||
| 506 | local $@; | ||
| 507 | eval | ||
| 508 | { | ||
| 509 | if( $opts->{request} ) | ||
| 510 | { | ||
| 511 | # We have to do this, because of a bug in TTP::Parser2::XS where HTTP/2 is not supported. | ||
| 512 | # We save the value and replace it with one supported and we put it back after in | ||
| 513 | # the data we return. | ||
| 514 | # <https://rt.cpan.org/Ticket/Display.html?id=142808> | ||
| 515 | if( index( $$str, 'HTTP/2' ) != -1 ) | ||
| 516 | { | ||
| 517 | if( $$str =~ s,^((?:\S+)[[:blank:]\h]+(?:\S+)[[:blank:]\h]+HTTP/)(2(?:\.\d)?),${1}1.1, ) | ||
| 518 | { | ||
| 519 | $bkp_version = $2; | ||
| 520 | } | ||
| 521 | } | ||
| 522 | $len = HTTP::Parser2::XS::parse_http_request( $$str, $r ); | ||
| 523 | } | ||
| 524 | elsif( $opts->{response} ) | ||
| 525 | { | ||
| 526 | if( index( $$str, 'HTTP/2' ) != -1 ) | ||
| 527 | { | ||
| 528 | if( $$str =~ s,^(HTTP/)(2(?:\.\d)?),${1}1.1, ) | ||
| 529 | { | ||
| 530 | $bkp_version = $2; | ||
| 531 | } | ||
| 532 | } | ||
| 533 | $len = HTTP::Parser2::XS::parse_http_response( $$str, $r ); | ||
| 534 | } | ||
| 535 | }; | ||
| 536 | if( $@ ) | ||
| 537 | { | ||
| 538 | return( $self->error({ code => 400, message => $@, class => $EXCEPTION_CLASS }) ); | ||
| 539 | } | ||
| 540 | |||
| 541 | if( $len == -1 ) | ||
| 542 | { | ||
| 543 | return( $self->error({ code => 400, message => 'Bad request', class => $EXCEPTION_CLASS }) ); | ||
| 544 | } | ||
| 545 | elsif( $len == -2 && $max_headers_size > 0 && length( $$str ) > $max_headers_size ) | ||
| 546 | { | ||
| 547 | # 431: HTTP request header fields too large | ||
| 548 | # 413: Request entity too large | ||
| 549 | return( $self->error({ code => 413, message => 'Incomplete and too long request', class => $EXCEPTION_CLASS }) ); | ||
| 550 | } | ||
| 551 | # Which one is best? | ||
| 552 | # 406 Unacceptable | ||
| 553 | # 411 Length required | ||
| 554 | # 417 Expectation failed | ||
| 555 | # 422 Unprocessable entity | ||
| 556 | # 425 Too early | ||
| 557 | elsif( $len == -2 ) | ||
| 558 | { | ||
| 559 | return( $self->error({ code => 425, message => 'Incomplete request, call again when there is more data.', class => $EXCEPTION_CLASS }) ); | ||
| 560 | } | ||
| 561 | # response headers: | ||
| 562 | # { | ||
| 563 | # "_content_length" => 15, | ||
| 564 | # "_keepalive" => 0, | ||
| 565 | # "_message" => "OK", | ||
| 566 | # "_protocol" => "HTTP/1.0", | ||
| 567 | # "_status" => 200, | ||
| 568 | # "content-length" => [15], | ||
| 569 | # "content-type" => ["text/plain"], | ||
| 570 | # "host" => ["example.com"], | ||
| 571 | # "user-agent" => ["hoge"], | ||
| 572 | # } | ||
| 573 | # request headers: | ||
| 574 | # { | ||
| 575 | # "_content_length" => 27, | ||
| 576 | # "_keepalive" => 1, | ||
| 577 | # "_method" => "POST", | ||
| 578 | # "_protocol" => "HTTP/1.1", | ||
| 579 | # "_query_string" => "", | ||
| 580 | # "_request_uri" => "/test", | ||
| 581 | # "_uri" => "/test", | ||
| 582 | # "content-length" => [27], | ||
| 583 | # "content-type" => ["application/x-www-form-urlencoded"], | ||
| 584 | # "host" => ["foo.example"], | ||
| 585 | # } | ||
| 586 | $r->{_protocol} = "HTTP/${bkp_version}" if( defined( $bkp_version ) ); | ||
| 587 | # warn( "HTTP::Parser2::XS->parse_headers_xs: bytes read ($len) differs from _content_length (", ( $r->{_content_length} // '' ), ")\n" ) if( defined( $r->{_content_length} ) && length( $r->{_content_length} ) && $len != $r->{_content_length} && $self->_warnings_is_enabled ); | ||
| 588 | my $def = { length => $len }; | ||
| 589 | # Sadly enough, HTTP::Parser2::XS does not provide the order of the header and | ||
| 590 | # although we could find out ourself, it would defeat the purpose of using an XS module | ||
| 591 | # so we default to alphabetical order | ||
| 592 | # If this is really important, you can use parse_request method instead | ||
| 593 | my $headers = $self->new_array; | ||
| 594 | # Skip keys that start with _. They are private properties | ||
| 595 | for( sort( grep( !/^_/, keys( %$r ) ) ) ) | ||
| 596 | { | ||
| 597 | my $k = $_; | ||
| 598 | $k =~ tr/-/_/ if( $opts->{convert_dash} ); | ||
| 599 | $headers->push( $k => $r->{ $_ } ); | ||
| 600 | } | ||
| 601 | $def->{headers} = HTTP::Promise::Headers->new( @$headers ); | ||
| 602 | if( $opts->{request} ) | ||
| 603 | { | ||
| 604 | @$def{qw( method protocol )} = @$r{qw( _method _protocol )}; | ||
| 605 | $def->{uri} = URI->new( $r->{_request_uri} ) if( exists( $r->{_request_uri} ) && length( $r->{_request_uri} ) ); | ||
| 606 | } | ||
| 607 | elsif( $opts->{response} ) | ||
| 608 | { | ||
| 609 | @$def{qw( code status protocol )} = @$r{qw( _status _message _protocol )}; | ||
| 610 | } | ||
| 611 | $def->{version} = $self->parse_version( $r->{_protocol} ) || return( $self->pass_error ); | ||
| 612 | # It seems | ||
| 613 | while( substr( $$str, 0, $len ) =~ /$CRLF($CRLF)$/ ) | ||
| 614 | { | ||
| 615 | $len -= length( $1 ); | ||
| 616 | } | ||
| 617 | $def->{length} = $len; | ||
| 618 | return( $def ); | ||
| 619 | } | ||
| 620 | |||
| 621 | sub parse_multi_part | ||
| 622 | { | ||
| 623 | my $self = shift( @_ ); | ||
| 624 | my $opts = $self->_get_args_as_hash( @_ ); | ||
| 625 | my $ent = $opts->{entity} || | ||
| 626 | return( $self->error({ code => 500, message => "No entity object was provided." }) ); | ||
| 627 | my $reader = $opts->{reader} || | ||
| 628 | return( $self->error({ code => 500, message => "No reader object was provided." }) ); | ||
| 629 | my $headers = $ent->headers || | ||
| 630 | return( $self->error({ code => 500, message => "No headers object found in entity object." }) ); | ||
| 631 | my $ct = $headers->content_type; | ||
| 632 | my $h = $headers->new_field( 'Content-Type' => $ct ) || return( $self->pass_error( $headers->error ) ); | ||
| 633 | my $boundary = $h->boundary || | ||
| 634 | return( $self->error( "No boundary could be found in the Content-Type header '$ct'" ) ); | ||
| 635 | my $max_in_memory = $self->max_body_in_memory_size; | ||
| 636 | my $default_mime = $DEFAULT_MIME_TYPE || 'application/octet-stream'; | ||
| 637 | |||
| 638 | # Position ourself right after the first boundary, including the trailing CRLF sequence | ||
| 639 | my $trash = $reader->read_until_in_memory( qr/--${boundary}${CRLF}/, include => 1, capture => 1 ); | ||
| 640 | return( $self->pass_error( $reader->error ) ) if( !defined( $trash ) ); | ||
| 641 | return( $self->error( "Unable to find the initial boundary '${boundary}'" ) ) if( !length( $trash ) ); | ||
| 642 | my $delim = $reader->last_delimiter; | ||
| 643 | my $preamble; | ||
| 644 | if( length( $delim ) ) | ||
| 645 | { | ||
| 646 | $preamble = substr( $trash, 0, index( $trash, $delim ) ); | ||
| 647 | $self->_trim_crlf( \$preamble ); | ||
| 648 | $ent->preamble( [split( /$CRLF/, $preamble )] ) if( length( $preamble ) ); | ||
| 649 | } | ||
| 650 | |||
| 651 | my( $buff, $mime, $def ); | ||
| 652 | while(1) | ||
| 653 | { | ||
| 654 | # I expect an header token and value, but if we find a CRLF sequence right now, | ||
| 655 | # this just means there is no header. | ||
| 656 | my $hdr = $reader->read_until_in_memory( qr/(?:^${CRLF}|(?:(?:$TOKEN+)[\x09\x20]*\:(?:.+?)${CRLF}${CRLF}))/, include => 1 ); | ||
| 657 | return( $self->pass_error( $reader->error ) ) if( !defined( $hdr ) ); | ||
| 658 | last if( !length( $hdr ) ); | ||
| 659 | my( $ph, $file, $mime_type, $ext, $io ); | ||
| 660 | if( length( $hdr ) && $hdr !~ /^$CRLF$/ ) | ||
| 661 | { | ||
| 662 | $def = $self->parse_headers( $hdr ) || return( $self->pass_error ); | ||
| 663 | $ph = $def->{headers}; | ||
| 664 | my $dispo = $ph->new_field( 'Content-Disposition' => $ph->content_disposition ); | ||
| 665 | # rfc7231, section 3.1.1.5 says we can assume applicatin/octet-stream if there | ||
| 666 | # is no Content-Type header | ||
| 667 | # <https://tools.ietf.org/html/rfc7231#section-3.1.1.5> | ||
| 668 | $mime_type = $ph->mime_type( $default_mime ); | ||
| 669 | } | ||
| 670 | # If no headers are set, we create a dummy object | ||
| 671 | else | ||
| 672 | { | ||
| 673 | $reader->unread( $hdr ) if( $hdr =~ /^$CRLF$/ ); | ||
| 674 | $ph = HTTP::Promise::Headers->new; | ||
| 675 | } | ||
| 676 | my $part_ent = HTTP::Promise::Entity->new( headers => $ph, debug => $self->debug ) || | ||
| 677 | return( $self->pass_error( HTTP::Promise::Entity->error ) ); | ||
| 678 | if( defined( $mime_type ) && $mime_type eq 'multipart/form-data' ) | ||
| 679 | { | ||
| 680 | # $sub_part_ent and $part_ent should be the same | ||
| 681 | my $sub_part_ent = $self->parse_multi_part( entity => $part_ent, reader => $reader ) || | ||
| 682 | return( $self->pass_error ); | ||
| 683 | # We need to consume the boundary for this part | ||
| 684 | # Position ourself just before the next delimiter, but do not include it. | ||
| 685 | # That way, we can capture epilogue data, if any, and although rare in HTTP parlance. | ||
| 686 | my $trash = $reader->read_until_in_memory( qr/${CRLF}--${boundary}(?:\-{2})?${CRLF}/, include => 1, capture => 1 ); | ||
| 687 | my $delim = $reader->last_delimiter; | ||
| 688 | my $epilogue; | ||
| 689 | if( length( $delim ) ) | ||
| 690 | { | ||
| 691 | $epilogue = substr( $trash, 0, index( $trash, $delim ) ); | ||
| 692 | $self->_trim_crlf( \$epilogue ); | ||
| 693 | $ent->epilogue( [split( /$CRLF/, $epilogue )] ) if( length( $epilogue ) ); | ||
| 694 | } | ||
| 695 | # Post process to assign a name to each part, to make it easy to manipulate them | ||
| 696 | for( $part_ent->parts->list ) | ||
| 697 | { | ||
| 698 | if( my $dispo = $_->headers->content_disposition ) | ||
| 699 | { | ||
| 700 | my $cd = $_->headers->new_field( 'Content-Disposition' => $dispo ); | ||
| 701 | return( $self->pass_error( $_->headers->error ) ) if( !defined( $cd ) ); | ||
| 702 | if( my $name = $cd->name ) | ||
| 703 | { | ||
| 704 | $_->name( $name ); | ||
| 705 | } | ||
| 706 | } | ||
| 707 | } | ||
| 708 | } | ||
| 709 | # Otherwise, we are dealing with a simple part | ||
| 710 | else | ||
| 711 | { | ||
| 712 | my $sub_part_ent = $self->parse_singleton( | ||
| 713 | entity => $part_ent, | ||
| 714 | reader => $reader, | ||
| 715 | read_until => qr/${CRLF}--${boundary}(?:\-{2})?${CRLF}/, | ||
| 716 | ) || return( $self->pass_error ); | ||
| 717 | } | ||
| 718 | $ent->parts->push( $part_ent ); | ||
| 719 | # Have we reached the last delimiter yet? | ||
| 720 | my $last = $reader->last_delimiter; | ||
| 721 | # We hit the ending delimiter, stop here. | ||
| 722 | # If there are any epilogue, they will be dealt with by our caller | ||
| 723 | last if( $last =~ /\-\-${boundary}\-\-${CRLF}$/ ); | ||
| 724 | } | ||
| 725 | return( $ent ); | ||
| 726 | } | ||
| 727 | |||
| 728 | sub parse_open | ||
| 729 | { | ||
| 730 | my $self = shift( @_ ); | ||
| 731 | my $expr = shift( @_ ) || | ||
| 732 | return( $self->error( "No file to open was provided." ) ); | ||
| 733 | my $ent; | ||
| 734 | my $f = $self->new_file( $expr ) || | ||
| 735 | return( $self->pass_error ); | ||
| 736 | my $io = $f->open || | ||
| 737 | return( $self->pass_error( $f->error ) ); | ||
| 738 | $ent = $self->parse( $io ) || | ||
| 739 | return( $self->pass_error ); | ||
| 740 | $io->close or return( $self->pass_error( $io->error ) ); | ||
| 741 | return( $ent ); | ||
| 742 | } | ||
| 743 | |||
| 744 | sub parse_request($$) | ||
| 745 | { | ||
| 746 | my $self = shift( @_ ); | ||
| 747 | my $str = $self->_get_args( shift( @_ ) ) || return( $self->pass_error ); | ||
| 748 | my $opts = $self->_get_args_as_hash( @_ ); | ||
| 749 | my $req = $self->parse_request_headers( $str, $opts ) || return( $self->pass_error ); | ||
| 750 | substr( $$str, 0, $req->{length}, '' ); | ||
| 751 | $req->{content} = $str; | ||
| 752 | return( $req ); | ||
| 753 | } | ||
| 754 | |||
| 755 | sub parse_request_headers($$) | ||
| 756 | { | ||
| 757 | my $self = shift( @_ ); | ||
| 758 | my $str = $self->_get_args( shift( @_ ) ) || return( $self->pass_error ); | ||
| 759 | my $opts = $self->_get_args_as_hash( @_ ); | ||
| 760 | $opts->{request} = 1; | ||
| 761 | return( $self->parse_headers_xs( $str, $opts ) ); | ||
| 762 | } | ||
| 763 | |||
| 764 | sub parse_request_line($$) | ||
| 765 | { | ||
| 766 | my $self = shift( @_ ); | ||
| 767 | my $str = $self->_get_args( shift( @_ ) ) || return( $self->pass_error ); | ||
| 768 | my $len = CORE::length( $$str ); | ||
| 769 | $$str =~ s/^$REQUEST// or return( $self->error({ code => 400, message => 'Bad request-line', class => $EXCEPTION_CLASS }) ); | ||
| 770 | my $res = | ||
| 771 | { | ||
| 772 | method => $1, | ||
| 773 | path => $2, | ||
| 774 | protocol => ( $3 || 'HTTP/0.9' ), | ||
| 775 | length => ( $len - CORE::length( $$str ) ), | ||
| 776 | }; | ||
| 777 | $res->{version} = $self->parse_version( $res->{protocol} ); | ||
| 778 | return( $res ); | ||
| 779 | } | ||
| 780 | |||
| 781 | sub parse_request_pp($$) | ||
| 782 | { | ||
| 783 | my $self = shift( @_ ); | ||
| 784 | my $str = $self->_get_args( shift( @_ ) ) || return( $self->pass_error ); | ||
| 785 | my $req = $self->parse_headers( $str, @_ ) || return( $self->pass_error ); | ||
| 786 | substr( $$str, 0, $req->{length}, '' ); | ||
| 787 | $$str =~ s/^$CRLF// or return( $self->error({ code => 400, message => 'Bad request', class => $EXCEPTION_CLASS }) ); | ||
| 788 | if( $req->{version} < version->parse( '1.0' ) ) | ||
| 789 | { | ||
| 790 | $$str eq '' or return( $self->error({ code => 400, message => 'Bad request', class => $EXCEPTION_CLASS }) ); | ||
| 791 | } | ||
| 792 | $req->{content} = $str; | ||
| 793 | return( $req ); | ||
| 794 | } | ||
| 795 | |||
| 796 | sub parse_response($$) | ||
| 797 | { | ||
| 798 | my $self = shift( @_ ); | ||
| 799 | my $str = $self->_get_args( shift( @_ ) ) || return( $self->pass_error ); | ||
| 800 | my $opts = $self->_get_args_as_hash( @_ ); | ||
| 801 | my $resp = $self->parse_response_headers( $str, $opts ) || return( $self->pass_error ); | ||
| 802 | substr( $$str, 0, $resp->{length}, '' ); | ||
| 803 | $resp->{content} = $str; | ||
| 804 | return( $resp ); | ||
| 805 | } | ||
| 806 | |||
| 807 | sub parse_response_headers($$) | ||
| 808 | { | ||
| 809 | my $self = shift( @_ ); | ||
| 810 | my $str = $self->_get_args( shift( @_ ) ) || return( $self->pass_error ); | ||
| 811 | my $opts = $self->_get_args_as_hash( @_ ); | ||
| 812 | $opts->{response} = 1; | ||
| 813 | return( $self->parse_headers_xs( $str, $opts ) ); | ||
| 814 | } | ||
| 815 | |||
| 816 | sub parse_response_line($$) | ||
| 817 | { | ||
| 818 | my $self = shift( @_ ); | ||
| 819 | my $str = $self->_get_args( shift( @_ ) ) || return( $self->pass_error ); | ||
| 820 | my $len = CORE::length( $$str ); | ||
| 821 | $$str =~ s/^$RESPONSE// or return( $self->error({ code => 400, message => 'Bad Status-Line', class => $EXCEPTION_CLASS }) ); | ||
| 822 | my $res = | ||
| 823 | { | ||
| 824 | protocol => $1, | ||
| 825 | code => $2, | ||
| 826 | status => $3, | ||
| 827 | length => ( $len - CORE::length( $$str ) ), | ||
| 828 | }; | ||
| 829 | $res->{version} = $self->parse_version( $res->{protocol} ); | ||
| 830 | return( $res ); | ||
| 831 | } | ||
| 832 | |||
| 833 | sub parse_response_pp($$) | ||
| 834 | { | ||
| 835 | my $self = shift( @_ ); | ||
| 836 | my $str = $self->_get_args( shift( @_ ) ) || return( $self->pass_error ); | ||
| 837 | my $opts = $self->_get_args_as_hash( @_ ); | ||
| 838 | $opts->{no_headers_ok} = 1; | ||
| 839 | my $resp = $self->parse_headers( $str, $opts ) || return( $self->pass_error ); | ||
| 840 | substr( $$str, 0, $resp->{length}, '' ); | ||
| 841 | $$str =~ s/^$CRLF// or return( $self->error({ code => 400, message => 'Bad response', class => $EXCEPTION_CLASS }) ); | ||
| 842 | $resp->{content} = $str; | ||
| 843 | return( $resp ); | ||
| 844 | } | ||
| 845 | |||
| 846 | # Called when there is no multipart | ||
| 847 | sub parse_singleton | ||
| 848 | { | ||
| 849 | my $self = shift( @_ ); | ||
| 850 | my $opts = $self->_get_args_as_hash( @_ ); | ||
| 851 | my $ent = $opts->{entity} || | ||
| 852 | return( $self->error({ code => 500, message => "No entity object was provided." }) ); | ||
| 853 | my $reader = $opts->{reader} || | ||
| 854 | return( $self->error({ code => 500, message => "No reader object was provided." }) ); | ||
| 855 | my $headers = $ent->headers || | ||
| 856 | return( $self->error({ code => 500, message => "No headers object found in entity object." }) ); | ||
| 857 | my $type = $headers->type; | ||
| 858 | my $read_until = $opts->{read_until}; | ||
| 859 | my $max_in_memory = $self->max_body_in_memory_size; | ||
| 860 | # rfc7231, section 3.1.1.5 says we can assume applicatin/octet-stream if there | ||
| 861 | # is no Content-Type header | ||
| 862 | # <https://tools.ietf.org/html/rfc7231#section-3.1.1.5> | ||
| 863 | my $default_mime = $DEFAULT_MIME_TYPE || 'application/octet-stream'; | ||
| 864 | my $len = $headers->content_length; | ||
| 865 | my $chunk_size = 2048; | ||
| 866 | my( $body, $file, $mime_type, $mime, $ext ); | ||
| 867 | my $data = ''; | ||
| 868 | my $total_bytes = 0; | ||
| 869 | |||
| 870 | my $get_temp_file = sub | ||
| 871 | { | ||
| 872 | # Guessing extension | ||
| 873 | $mime_type = $headers->mime_type( $default_mime ); | ||
| 874 | $self->_load_class( 'HTTP::Promise::MIME' ) || return( $self->pass_error ); | ||
| 875 | $mime = HTTP::Promise::MIME->new; | ||
| 876 | $ext = $mime->suffix( $type ); | ||
| 877 | return( $self->pass_error( $mime->error ) ) if( !defined( $ext ) ); | ||
| 878 | $ext ||= 'dat'; | ||
| 879 | my $f = $self->new_tempfile( extension => $ext ) || | ||
| 880 | return( $self->pass_error ); | ||
| 881 | return( $f ); | ||
| 882 | }; | ||
| 883 | |||
| 884 | if( defined( $len ) && !defined( $read_until ) ) | ||
| 885 | { | ||
| 886 | # Nothing to be done. The body is zero byte, like in HEAD request | ||
| 887 | if( !$len ) | ||
| 888 | { | ||
| 889 | # | ||
| 890 | } | ||
| 891 | # Too big, saving it to file | ||
| 892 | elsif( $len > $max_in_memory ) | ||
| 893 | { | ||
| 894 | # We cannot save this to file if the type is application/x-www-form-urlencoded | ||
| 895 | if( $type eq TYPE_URL_ENCODED && $self->decode_body ) | ||
| 896 | { | ||
| 897 | # Payload too large | ||
| 898 | return( $self->error({ code => 413, message => "The data are url-encoded, but its total amount (${len}) exceeds the maximum allowed ($max_in_memory}). You may want to increase that limit or investigate this HTTP message." }) ); | ||
| 899 | } | ||
| 900 | $file = $get_temp_file->() || return( $self->pass_error ); | ||
| 901 | my $io = $file->open( '+>', { binmode => 'raw', autoflush => 1 } ) || | ||
| 902 | return( $self->pass_error( $file->error ) ); | ||
| 903 | my $buff = ''; | ||
| 904 | my $bytes; | ||
| 905 | $chunk_size = $len if( $chunk_size > $len ); | ||
| 906 | while( $bytes = $reader->read( $buff, $chunk_size ) ) | ||
| 907 | { | ||
| 908 | $io->print( $buff ) || return( $self->pass_error( $io->error ) ); | ||
| 909 | # We do not want to read more than we should | ||
| 910 | $chunk_size = ( $len - $total_bytes ) if( $total_bytes + $chunk_size > $len ); | ||
| 911 | $total_bytes += $bytes; | ||
| 912 | last if( $total_bytes == $len ); | ||
| 913 | } | ||
| 914 | $io->close; | ||
| 915 | return( $self->error( "Error reading http body from filehandle: ", $reader->error ) ) if( !defined( $bytes ) ); | ||
| 916 | } | ||
| 917 | else | ||
| 918 | { | ||
| 919 | my $bytes = $reader->read( $data, $len ); | ||
| 920 | return( $self->error( "Error reading HTTP body from filehandle: ", $reader->error ) ) if( !defined( $bytes ) ); | ||
| 921 | # Assignment used for the warning below | ||
| 922 | $total_bytes = $bytes; | ||
| 923 | } | ||
| 924 | warn( ref( $self ), "->parse_singleton: Warning only: HTTP body size advertised ($len) does not match the size actually read from filehandle ($total_bytes)\n" ) if( $total_bytes != $len && warnings::enabled( 'HTTP::Promise' ) ); | ||
| 925 | } | ||
| 926 | # No Content-Length defined or there is a boundary expected | ||
| 927 | else | ||
| 928 | { | ||
| 929 | my $buff = ''; | ||
| 930 | my $bytes = -1; | ||
| 931 | my $io; | ||
| 932 | while( $bytes ) | ||
| 933 | { | ||
| 934 | if( defined( $read_until ) ) | ||
| 935 | { | ||
| 936 | $bytes = $reader->read_until( $buff, $chunk_size, { string => $read_until, ignore => 1, capture => 1 } ); | ||
| 937 | } | ||
| 938 | else | ||
| 939 | { | ||
| 940 | $bytes = $reader->read( $buff, $chunk_size ); | ||
| 941 | } | ||
| 942 | return( $self->pass_error( $reader->error ) ) if( !defined( $bytes ) ); | ||
| 943 | |||
| 944 | if( defined( $io ) ) | ||
| 945 | { | ||
| 946 | $io->print( $buff ) || return( $self->pass_error( $io->error ) ); | ||
| 947 | } | ||
| 948 | # The cumulative bytes total for this part exceeds the allowed maximum in memory | ||
| 949 | elsif( ( length( $data ) + length( $buff ) ) > $max_in_memory ) | ||
| 950 | { | ||
| 951 | if( $type eq TYPE_URL_ENCODED && $self->decode_body ) | ||
| 952 | { | ||
| 953 | # Payload too large | ||
| 954 | return( $self->error({ code => 413, message => sprintf( "The data are url-encoded, but its total amount so far (%d) is about to exceed the maximum allowed ($max_in_memory}). You may want to increase that limit or investigate this HTTP message.",length( $data ) ) }) ); | ||
| 955 | } | ||
| 956 | $file = $get_temp_file->() || return( $self->pass_error ); | ||
| 957 | $io = $file->open( '+>', { binmode => 'raw', autoflush => 1 } ) || | ||
| 958 | return( $self->pass_error( $file->error ) ); | ||
| 959 | $io->print( $data ) || return( $self->pass_error( $io->error ) ); | ||
| 960 | $data = ''; | ||
| 961 | } | ||
| 962 | else | ||
| 963 | { | ||
| 964 | $data .= $buff; | ||
| 965 | } | ||
| 966 | # reader returns negative bytes if those are the last bytes read until it reached the boundary | ||
| 967 | last if( $bytes < 0 ); | ||
| 968 | } | ||
| 969 | $total_bytes = defined( $file ) ? $file->length : length( $data ); | ||
| 970 | } | ||
| 971 | |||
| 972 | |||
| 973 | # If we used a file and the extension is 'dat', because we were clueless based on | ||
| 974 | # the provided Content-Type, or maybe even the Content-Type is absent, we use the | ||
| 975 | # XS module in HTTP::Promise::MIME to guess the mime-type based on the actual file | ||
| 976 | # content | ||
| 977 | if( defined( $file ) ) | ||
| 978 | { | ||
| 979 | if( defined( $file ) && $mime_type eq $default_mime ) | ||
| 980 | { | ||
| 981 | unless( $mime ) | ||
| 982 | { | ||
| 983 | $self->_load_class( 'HTTP::Promise::MIME' ) || return( $self->pass_error ); | ||
| 984 | $mime = HTTP::Promise::MIME->new; | ||
| 985 | } | ||
| 986 | |||
| 987 | # Guess the mime type from the file magic | ||
| 988 | my $mtype = $mime->mime_type( $file ); | ||
| 989 | return( $self->pass_error( $mime->error ) ) if( !defined( $mime_type ) ); | ||
| 990 | if( $mtype && $mtype ne $default_mime ) | ||
| 991 | { | ||
| 992 | $mime_type = $mtype; | ||
| 993 | # Also update the type value in HTTP::Promise::Headers | ||
| 994 | # It does not affect the actual Content-Type header | ||
| 995 | $headers->type( $mtype ); | ||
| 996 | my $new_ext = $mime->suffix( $mtype ); | ||
| 997 | return( $self->pass_error( $mime->error ) ) if( !defined( $new_ext ) ); | ||
| 998 | if( $new_ext && $new_ext ne $ext ) | ||
| 999 | { | ||
| 1000 | my $new_file = $file->extension( $ext ) || return( $self->pass_error( $file->error ) ); | ||
| 1001 | my $this_file = $file->move( $new_file ) || return( $self->pass_error( $file->error ) ); | ||
| 1002 | $file = $this_file; | ||
| 1003 | } | ||
| 1004 | } | ||
| 1005 | } | ||
| 1006 | |||
| 1007 | $body = $ent->new_body( file => $file ) || | ||
| 1008 | return( $self->pass_error( $ent->error ) ); | ||
| 1009 | } | ||
| 1010 | # in memory | ||
| 1011 | else | ||
| 1012 | { | ||
| 1013 | # If this is a application/x-www-form-urlencoded type, we save it as such, and | ||
| 1014 | # the HTTP::Promise::Body::Form makes those data accessible as an hash object | ||
| 1015 | if( defined( $type ) && $type eq TYPE_URL_ENCODED ) | ||
| 1016 | { | ||
| 1017 | $body = $ent->new_body( form => $data ) || | ||
| 1018 | return( $self->pass_error( $ent->error ) ); | ||
| 1019 | } | ||
| 1020 | else | ||
| 1021 | { | ||
| 1022 | $body = $ent->new_body( string => $data ) || | ||
| 1023 | return( $self->pass_error( $ent->error ) ); | ||
| 1024 | } | ||
| 1025 | } | ||
| 1026 | $ent->body( $body ); | ||
| 1027 | my $enc = $headers->content_encoding; | ||
| 1028 | if( $enc && $body->length && $self->decode_body( $enc ) ) | ||
| 1029 | { | ||
| 1030 | $ent->decode_body( $enc ) || return( $self->pass_error( $ent->error ) ); | ||
| 1031 | $ent->is_encoded(0); | ||
| 1032 | } | ||
| 1033 | return( $ent ); | ||
| 1034 | } | ||
| 1035 | |||
| 1036 | sub parse_version($$) | ||
| 1037 | { | ||
| 1038 | my $self = shift( @_ ); | ||
| 1039 | my $str = shift( @_ ); | ||
| 1040 | return( $self->error({ code => 400, message => "No data was provided to parse the http version", class => $EXCEPTION_CLASS }) ) if( !defined( $str ) || !length( $str ) ); | ||
| 1041 | $str =~ m/^${HTTP_VERSION}$/ or | ||
| 1042 | return( $self->error({ code => 400, message => "Bad HTTP-Version '$str'", class => $EXCEPTION_CLASS }) ); | ||
| 1043 | my $major = $+{http_vers_major}; | ||
| 1044 | # May be undef if HTTP/2 for example | ||
| 1045 | my $minor = $+{http_vers_minor}; | ||
| 1046 | my $v = version->parse( $+{http_version} ); | ||
| 1047 | return( want( 'LIST' ) ? ( $major, $minor ) : $v ); | ||
| 1048 | } | ||
| 1049 | |||
| 1050 | sub tmp_dir { return( shift->_set_get_file( 'tmp_dir', @_ ) ); } | ||
| 1051 | |||
| 1052 | sub tmp_to_core { return( shift->_set_get_boolean( 'tmp_to_core', @_ ) ); } | ||
| 1053 | |||
| 1054 | sub _get_args | ||
| 1055 | { | ||
| 1056 | my $self = shift( @_ ); | ||
| 1057 | my $str = shift( @_ ); | ||
| 1058 | if( !ref( $str ) ) | ||
| 1059 | { | ||
| 1060 | $str = \"$str"; | ||
| 1061 | } | ||
| 1062 | elsif( !$self->_is_scalar( $str ) ) | ||
| 1063 | { | ||
| 1064 | return( $self->error({ code => 401, message => "Value provided (" . overload::StrVal( $str ) . ") is not a string", class => $EXCEPTION_CLASS }) ); | ||
| 1065 | } | ||
| 1066 | return( $str ); | ||
| 1067 | } | ||
| 1068 | |||
| 1069 | sub _trim_crlf | ||
| 1070 | { | ||
| 1071 | my $self = shift( @_ ); | ||
| 1072 | my $ref = shift( @_ ); | ||
| 1073 | return( $ref ) if( !defined( $ref ) ); | ||
| 1074 | die( "Bad argument. This must be provided a scalar reference.\n" ) if( !$self->_is_scalar( $ref ) ); | ||
| 1075 | my $n = 0; | ||
| 1076 | substr( $$ref, $n, 1, '' ), $n++ while( substr( $$ref, $n, 1 ) eq "\015" || substr( $$ref, $n, 1 ) eq "\012" ); | ||
| 1077 | $n = length( $$ref ); | ||
| 1078 | $n-- while( substr( $$ref, ($n - 1), 1 ) eq "\015" || substr( $$ref, ($n - 1), 1 ) eq "\012" ); | ||
| 1079 | substr( $$ref, $n, length( $$ref ), '' ); | ||
| 1080 | return( $ref ); | ||
| 1081 | } | ||
| 1082 | |||
| 1083 | # NOTE: sub FREEZE is inherited | ||
| 1084 | |||
| 1085 | sub STORABLE_freeze { CORE::return( CORE::shift->FREEZE( @_ ) ); } | ||
| 1086 | |||
| 1087 | sub STORABLE_thaw { CORE::return( CORE::shift->THAW( @_ ) ); } | ||
| 1088 | |||
| 1089 | # NOTE: sub THAW is inherited | ||
| 1090 | |||
| 1091 | 1; | ||
| 1092 | # NOTE: POD | ||
| 1093 | __END__ | ||
| 1094 | |||
| 1095 | =encoding utf-8 | ||
| 1096 | |||
| 1097 | =head1 NAME | ||
| 1098 | |||
| 1099 | HTTP::Promise::Parser - Fast HTTP Request & Response Parser | ||
| 1100 | |||
| 1101 | =head1 SYNOPSIS | ||
| 1102 | |||
| 1103 | use HTTP::Promise::Parser; | ||
| 1104 | my $p = HTTP::Promise::Parser->new || | ||
| 1105 | die( HTTP::Promise::Parser->error, "\n" ); | ||
| 1106 | my $ent = $p->parse( '/some/where/http_request.txt' ) || | ||
| 1107 | die( $p->error ); | ||
| 1108 | my $ent = $p->parse( $file_handle ) || | ||
| 1109 | die( $p->error ); | ||
| 1110 | my $ent = $p->parse( $string ) || | ||
| 1111 | die( $p->error ); | ||
| 1112 | |||
| 1113 | =head1 VERSION | ||
| 1114 | |||
| 1115 | v0.2.3 | ||
| 1116 | |||
| 1117 | =head1 DESCRIPTION | ||
| 1118 | |||
| 1119 | This is an http request and response parser using XS modules whenever posible for speed and mindful of memory consumption. | ||
| 1120 | |||
| 1121 | As rfc7230 states in its L<section 3|https://tools.ietf.org/html/rfc7230#section-3>: | ||
| 1122 | |||
| 1123 | "The normal procedure for parsing an HTTP message is to read the start-line into a structure, read each header field into a hash table by field name until the empty line, and then use the parsed data to determine if a message body is expected. If a message body has been indicated, then it is read as a stream until an amount of octets equal to the message body length is read or the connection is closed." | ||
| 1124 | |||
| 1125 | Thus, L<HTTP::Promise> approach is to read the data, whether a HTTP request or response, a.k.a, an HTTP message, from a filehandle, possibly L<chunked|https://tools.ietf.org/html/rfc7230#section-4.1>, and to first read the message L<headers|HTTP::Promise::Headers> and parse them, then to store the HTTP message in memory if it is under a specified threshold, or in a file. If the size is unknown, it would be first read in memory and switched automatically to a file when it reaches the threshold. | ||
| 1126 | |||
| 1127 | Once the overall message body is stored, if it is a multipart type, L<this class|HTTP::Promise::Parser> reads each of its parts into memory or separate file depending on its size until there is no more part, using the L<stream reader|HTTP::Promise::IO>, which reads in chunks of bytes and not in lines. If the message body is a single part it is saved to memory or file depending on its size. Each part saved on file uses a file extension related to its L<mime type|HTTP::Promise::MIME>. Each of the parts are then accessible as a L<HTTP body object|HTTP::Promise::Body> via the L<HTTP::Promise::Entity/parts> method. | ||
| 1128 | |||
| 1129 | Note, however, that when dealing with multipart, this only recognises C<multipart/form-data>, anything else will be treated as data. | ||
| 1130 | |||
| 1131 | The overall HTTP message is available as an L<HTTP::Promise::Entity> object and returned. | ||
| 1132 | |||
| 1133 | If an error occurs, this module does not die, at least not voluntarily, but instead sets an L<error|Module::Generic/error> and returns C<undef>, so always make sure to check the returned value from method calls. | ||
| 1134 | |||
| 1135 | =head1 CONSTRUCTOR | ||
| 1136 | |||
| 1137 | =head2 new | ||
| 1138 | |||
| 1139 | This instantiates a new L<HTTP::Promise::Parser> object. | ||
| 1140 | |||
| 1141 | It takes the following options: | ||
| 1142 | |||
| 1143 | =over 4 | ||
| 1144 | |||
| 1145 | =item * C<decode_body> | ||
| 1146 | |||
| 1147 | Boolean. If enabled, this will have this interface automatically decode the entity body upon parsing. Default is true. | ||
| 1148 | |||
| 1149 | =item * C<decode_headers> | ||
| 1150 | |||
| 1151 | Boolean. If enabled, this will decode headers, which is used for decoding filename value in C<Content-Encoding>. Default is false. | ||
| 1152 | |||
| 1153 | =item * C<ignore_filename> | ||
| 1154 | |||
| 1155 | Boolean. Wether the filename provided in an C<Content-Disposition> should be ignored or not. This defaults to false, but actually, this is not used and the filename specified in a C<Content-Disposition> header field is never used. So, this is a no-op and should be removed. | ||
| 1156 | |||
| 1157 | =item * C<max_body_in_memory_size> | ||
| 1158 | |||
| 1159 | Integer. This is the threshold beyond which an entity body that is initially loaded into memory will switched to be loaded into a file on the local filesystem when it is a true value and exceeds the amount specified. | ||
| 1160 | |||
| 1161 | By defaults, this has the value set by the class variable C<$MAX_BODY_IN_MEMORY_SIZE>, which is 102400 bytes or 100K | ||
| 1162 | |||
| 1163 | =item * C<max_headers_size> | ||
| 1164 | |||
| 1165 | Integer. This is the threshold size in bytes beyond which HTTP headers will trigger an error. This defaults to the class variable C<$MAX_HEADERS_SIZE>, which itself is set by default to 8192 bytes or 8K | ||
| 1166 | |||
| 1167 | =item * C<max_read_buffer> | ||
| 1168 | |||
| 1169 | Integer. This is the read buffer size. This is used for L<HTTP::Promise::IO> and this defaults to 2048 bytes (2Kb). | ||
| 1170 | |||
| 1171 | =item * C<output_dir> | ||
| 1172 | |||
| 1173 | Filepath of the directory to be used to save entity body, when applicable. | ||
| 1174 | |||
| 1175 | =item * C<tmp_dir> | ||
| 1176 | |||
| 1177 | Set the directory to use when creating temporary files. | ||
| 1178 | |||
| 1179 | =item * C<tmp_to_core> | ||
| 1180 | |||
| 1181 | Boolean. When true, this will set the temporary file to an in-memory space. | ||
| 1182 | |||
| 1183 | =back | ||
| 1184 | |||
| 1185 | =head1 METHODS | ||
| 1186 | |||
| 1187 | =head2 decode_body | ||
| 1188 | |||
| 1189 | Boolean. If enabled, this will have this interface automatically decode the entity body upon parsing. Default is true. | ||
| 1190 | |||
| 1191 | =head2 decode_headers | ||
| 1192 | |||
| 1193 | Boolean. If enabled, this will decode headers, which is used for decoding filename value in C<Content-Encoding>. Default is false. | ||
| 1194 | |||
| 1195 | =head2 ignore_filename | ||
| 1196 | |||
| 1197 | Boolean. Wether the filename provided in an C<Content-Disposition> should be ignored or not. This defaults to false, but actually, this is not used and the filename specified in a C<Content-Disposition> header field is never used. So, this is a no-op and should be removed. | ||
| 1198 | |||
| 1199 | =head2 looks_like_request | ||
| 1200 | |||
| 1201 | Provided with a string or a scalar reference, and this returns an hash reference containing details of the request line attributes if it is indeed a request, or an empty string if it is not a request. | ||
| 1202 | |||
| 1203 | It sets an L<error|Module::Generic/error> and returns C<undef> upon error. | ||
| 1204 | |||
| 1205 | The following attributes are available: | ||
| 1206 | |||
| 1207 | =over 4 | ||
| 1208 | |||
| 1209 | =item C<http_version> | ||
| 1210 | |||
| 1211 | The HTTP protocol version used. For example, in C<HTTP/1.1>, this would be C<1.1>, and in C<HTTP/2>, this would be C<2>. | ||
| 1212 | |||
| 1213 | =item C<http_vers_minor> | ||
| 1214 | |||
| 1215 | The HTTP protocol major version used. For example, in C<HTTP/1.0>, this would be C<1>, and in C<HTTP/2>, this would be C<2>. | ||
| 1216 | |||
| 1217 | =item C<http_vers_minor> | ||
| 1218 | |||
| 1219 | The HTTP protocol minor version used. For example, in C<HTTP/1.0>, this would be C<0>, and in C<HTTP/2>, this would be C<undef>. | ||
| 1220 | |||
| 1221 | =item C<method> | ||
| 1222 | |||
| 1223 | The HTTP request method used. For example in C<GET / HTTP/1.1>, this would be C<GET>. This uses the L<rfc7231 semantics|https://tools.ietf.org/html/rfc7231#section-4>, which means any token even non-standard ones would match. | ||
| 1224 | |||
| 1225 | =item C<protocol> | ||
| 1226 | |||
| 1227 | The HTTP protocol used, e.g. C<HTTP/1.0>, C<HTTP/1.1>, C<HTTP/2>, etc... | ||
| 1228 | |||
| 1229 | =item C<uri> | ||
| 1230 | |||
| 1231 | The request URI. For example in C<GET / HTTP/1.1>, this would be C</> | ||
| 1232 | |||
| 1233 | =back | ||
| 1234 | |||
| 1235 | my $ref = $p->looks_like_request( \$str ); | ||
| 1236 | # or | ||
| 1237 | # my $ref = $p->looks_like_request( $str ); | ||
| 1238 | die( $p->error ) if( !defined( $ref ) ); | ||
| 1239 | if( $ref ) | ||
| 1240 | { | ||
| 1241 | say "Request method $ref->{method}, uri $ref->{uri}, protocol $ref->{protocol}, version major $ref->{http_vers_major}, version minor $ref->{http_vers_minor}"; | ||
| 1242 | } | ||
| 1243 | else | ||
| 1244 | { | ||
| 1245 | say "This is not an HTTP request."; | ||
| 1246 | } | ||
| 1247 | |||
| 1248 | =head2 looks_like_response | ||
| 1249 | |||
| 1250 | Provided with a string or a scalar reference, and this returns an hash reference containing details of the response line attributes if it is indeed a response, or an empty string if it is not a response. | ||
| 1251 | |||
| 1252 | It sets an L<error|Module::Generic/error> and returns C<undef> upon error. | ||
| 1253 | |||
| 1254 | The following attributes are available: | ||
| 1255 | |||
| 1256 | =over 4 | ||
| 1257 | |||
| 1258 | =item C<code> | ||
| 1259 | |||
| 1260 | The 3-digits HTTP response code. For example in C<HTTP/1.1 200 OK>, this would be C<200>. | ||
| 1261 | |||
| 1262 | =item C<http_version> | ||
| 1263 | |||
| 1264 | The HTTP protocol version used. For example, in C<HTTP/1.1>, this would be C<1.1>, and in C<HTTP/2>, this would be C<2>. | ||
| 1265 | |||
| 1266 | =item C<http_vers_minor> | ||
| 1267 | |||
| 1268 | The HTTP protocol major version used. For example, in C<HTTP/1.0>, this would be C<1>, and in C<HTTP/2>, this would be C<2>. | ||
| 1269 | |||
| 1270 | =item C<http_vers_minor> | ||
| 1271 | |||
| 1272 | The HTTP protocol minor version used. For example, in C<HTTP/1.0>, this would be C<0>, and in C<HTTP/2>, this would be C<undef>. | ||
| 1273 | |||
| 1274 | =item C<protocol> | ||
| 1275 | |||
| 1276 | The HTTP protocol used, e.g. C<HTTP/1.0>, C<HTTP/1.1>, C<HTTP/2>, etc... | ||
| 1277 | |||
| 1278 | =item C<status> | ||
| 1279 | |||
| 1280 | The response status text. For example in C<HTTP/1.1 200 OK>, this would be C<OK>. | ||
| 1281 | |||
| 1282 | =back | ||
| 1283 | |||
| 1284 | my $ref = $p->looks_like_response( \$str ); | ||
| 1285 | # or | ||
| 1286 | # my $ref = $p->looks_like_response( $str ); | ||
| 1287 | die( $p->error ) if( !defined( $ref ) ); | ||
| 1288 | if( $ref ) | ||
| 1289 | { | ||
| 1290 | say "Response code $ref->{code}, status $ref->{status}, protocol $ref->{protocol}, version major $ref->{http_vers_major}, version minor $ref->{http_vers_minor}"; | ||
| 1291 | } | ||
| 1292 | else | ||
| 1293 | { | ||
| 1294 | say "This is not an HTTP response."; | ||
| 1295 | } | ||
| 1296 | |||
| 1297 | =head2 looks_like_what | ||
| 1298 | |||
| 1299 | Provided with a string or a scalar reference, and this returns an hash reference containing details of the HTTP message first line attributes if it is indeed an HTTP message. | ||
| 1300 | |||
| 1301 | The attributes available depends on the type of HTTP message determined and are described in details in L</looks_like_request> and L</looks_like_response>. In addition to those, it also returns the attribute C<type>, which is a string representing the type of HTTP message this is, i.e. either C<request> or C<response>. | ||
| 1302 | |||
| 1303 | If this does not match either an HTTP request or HTTP response, it returns an empty string. | ||
| 1304 | |||
| 1305 | my $ref = $p->looks_like_what( \$str ); | ||
| 1306 | die( $p->error ) if( !defined( $ref ) ); | ||
| 1307 | say "This is a ", ( $ref ? $ref->{type} : 'unknown' ), " HTTP message."; | ||
| 1308 | |||
| 1309 | my $ref = $p->looks_like_what( \$str ); | ||
| 1310 | die( $p->error ) if( !defined( $ref ) ); | ||
| 1311 | if( !$ref ) | ||
| 1312 | { | ||
| 1313 | say "This is unknown."; | ||
| 1314 | } | ||
| 1315 | else | ||
| 1316 | { | ||
| 1317 | say "This is a HTTP $ref->{type} with protocol version $ref->{http_version}"; | ||
| 1318 | } | ||
| 1319 | |||
| 1320 | =head2 max_body_in_memory_size | ||
| 1321 | |||
| 1322 | Integer. This is the threshold beyond which an entity body that is initially loaded into memory will switched to be loaded into a file on the local filesystem when it is a true value and exceeds the amount specified. | ||
| 1323 | |||
| 1324 | By defaults, this has the value set by the class variable C<$MAX_BODY_IN_MEMORY_SIZE>, which is 102400 bytes or 100K | ||
| 1325 | |||
| 1326 | =head2 max_headers_size | ||
| 1327 | |||
| 1328 | Integer. This is the threshold size in bytes beyond which HTTP headers will trigger an error. This defaults to the class variable C<$MAX_HEADERS_SIZE>, which itself is set by default to 8192 bytes or 8K | ||
| 1329 | |||
| 1330 | =head2 max_read_buffer | ||
| 1331 | |||
| 1332 | Integer. This is the read buffer size. This is used for L<HTTP::Promise::IO> and this defaults to 2048 bytes (2Kb). | ||
| 1333 | |||
| 1334 | =head2 new_tmpfile | ||
| 1335 | |||
| 1336 | Creates a new temporary file. If C<tmp_to_core> is set to true, this will create a new file using a L<scalar object|Module::Generic::Scalar>, or it will create a new temporary file under the directory set with the object parameter C<tmp_dir>. The filehandle binmode is set to C<raw>. | ||
| 1337 | |||
| 1338 | It returns a filehandle upon success, or upon error, it sets an L<error|Module::Generic/error> and return C<undef>. | ||
| 1339 | |||
| 1340 | =head2 output_dir | ||
| 1341 | |||
| 1342 | The filepath to the output directory. This is used when saving entity bodies on the filesystem. | ||
| 1343 | |||
| 1344 | =head2 parse | ||
| 1345 | |||
| 1346 | This takes a scalar reference of data, a glob or a file path, and will parse the HTTP request or response by calling L</parse_fh> and pass it whatever options it received. | ||
| 1347 | |||
| 1348 | It returns an L<entity object|HTTP::Promise::Entity> upon success and upon error, it sets an L<error|Module::Generic/error> and return C<undef>. | ||
| 1349 | |||
| 1350 | =head2 parse_data | ||
| 1351 | |||
| 1352 | This takes a string or a scalar reference and returns an L<entity object|HTTP::Promise::Entity> upon success and upon error, it sets an L<error|Module::Generic/error> and return C<undef> | ||
| 1353 | |||
| 1354 | =head2 parse_fh | ||
| 1355 | |||
| 1356 | This takes a filehandle and parse the HTTP request or response, and returns an L<entity object|HTTP::Promise::Entity> upon success and upon error, it sets an L<error|Module::Generic/error> and return C<undef>. | ||
| 1357 | |||
| 1358 | It takes also an hash or hash reference of the following options: | ||
| 1359 | |||
| 1360 | =over 4 | ||
| 1361 | |||
| 1362 | =item * C<reader> | ||
| 1363 | |||
| 1364 | An L<HTTP::Promise::IO>. If this is not provided, a new one will be created. Note that data will be read using this reader. | ||
| 1365 | |||
| 1366 | =item * C<request> | ||
| 1367 | |||
| 1368 | Boolean. Set this to true to indicate the data is an HTTP request. If neither C<request> nor C<response> is provided, the parser will attempt guessing it. | ||
| 1369 | |||
| 1370 | =item * C<response> | ||
| 1371 | |||
| 1372 | Boolean. Set this to true to indicate the data is an HTTP response. If neither C<request> nor C<response> is provided, the parser will attempt guessing it. | ||
| 1373 | |||
| 1374 | =back | ||
| 1375 | |||
| 1376 | =head2 parse_headers | ||
| 1377 | |||
| 1378 | This takes a string or a scalar reference including a scalar object, such as L<Module::Generic::Scalar>, and an optional hash or hash reference of parameters and parse the headers found in the given string, if any at all. | ||
| 1379 | |||
| 1380 | It returns an hash reference with the same property names and values returned by L</parse_headers_xs>. | ||
| 1381 | |||
| 1382 | This method uses pure perl. | ||
| 1383 | |||
| 1384 | Supported options are: | ||
| 1385 | |||
| 1386 | =over 4 | ||
| 1387 | |||
| 1388 | =item * C<convert_dash> | ||
| 1389 | |||
| 1390 | Boolean. If true, this will convert C<-> in header fields to C<_>. Default is false. | ||
| 1391 | |||
| 1392 | =item * C<no_headers_ok> | ||
| 1393 | |||
| 1394 | Boolean. If set to true, this won't trigger if there is no headers | ||
| 1395 | |||
| 1396 | =back | ||
| 1397 | |||
| 1398 | =head2 parse_headers_xs | ||
| 1399 | |||
| 1400 | my $def = $p->parse_headers_xs( $http_request_or_response ); | ||
| 1401 | my $def = $p->parse_headers_xs( $http_request_or_response, $options_hash_ref ); | ||
| 1402 | |||
| 1403 | This takes a string or a scalar reference including a scalar object, such as L<Module::Generic::Scalar>, and an optional hash or hash reference of parameters and parse the headers found in the given string, if any at all. | ||
| 1404 | |||
| 1405 | It returns a dictionary as an hash reference upon success, and it sets an L<error|Module::Generic/error> with an http error code set and returns C<undef> upon error. | ||
| 1406 | |||
| 1407 | Supported options are: | ||
| 1408 | |||
| 1409 | =over 4 | ||
| 1410 | |||
| 1411 | =item * C<convert_dash> | ||
| 1412 | |||
| 1413 | Boolean. If true, this will convert C<-> in header fields to C<_>. Default is false. | ||
| 1414 | |||
| 1415 | =item * C<request> | ||
| 1416 | |||
| 1417 | Boolean. If true, this will parse the string assuming it is a request header. | ||
| 1418 | |||
| 1419 | =item * C<response> | ||
| 1420 | |||
| 1421 | Boolean. If true, this will parse the string assuming it is a response header. | ||
| 1422 | |||
| 1423 | =back | ||
| 1424 | |||
| 1425 | The properties returned in the dictionary depend on whether C<request> or C<response> were enabled. | ||
| 1426 | |||
| 1427 | For C<request>: | ||
| 1428 | |||
| 1429 | =over 4 | ||
| 1430 | |||
| 1431 | =item * C<headers> | ||
| 1432 | |||
| 1433 | An L<HTTP::Promise::Headers> object. | ||
| 1434 | |||
| 1435 | =item * C<length> | ||
| 1436 | |||
| 1437 | The length in bytes of the headers parsed. | ||
| 1438 | |||
| 1439 | =item * C<method> | ||
| 1440 | |||
| 1441 | The HTTP method such as C<GET>, or C<HEAD>, C<POST>, etc. | ||
| 1442 | |||
| 1443 | =item * C<protocol> | ||
| 1444 | |||
| 1445 | String, such as C<HTTP/1.1> or C<HTTP/2> | ||
| 1446 | |||
| 1447 | =item * C<uri> | ||
| 1448 | |||
| 1449 | String, the request URI, such as C</> | ||
| 1450 | |||
| 1451 | =item * C<version> | ||
| 1452 | |||
| 1453 | This is a L<version> object and contains a value such as C<1.1>, so you can do something like: | ||
| 1454 | |||
| 1455 | if( $def->{version} >= version->parse( '1.1' ) ) | ||
| 1456 | { | ||
| 1457 | # Do something | ||
| 1458 | } | ||
| 1459 | |||
| 1460 | =back | ||
| 1461 | |||
| 1462 | For C<response>: | ||
| 1463 | |||
| 1464 | =over 4 | ||
| 1465 | |||
| 1466 | =item * C<code> | ||
| 1467 | |||
| 1468 | The HTTP status code, such as C<200> | ||
| 1469 | |||
| 1470 | =item * C<headers> | ||
| 1471 | |||
| 1472 | An L<HTTP::Promise::Headers> object. | ||
| 1473 | |||
| 1474 | =item * C<length> | ||
| 1475 | |||
| 1476 | The length in bytes of the headers parsed. This is useful so you can then remove it from the string you provided: | ||
| 1477 | |||
| 1478 | my $resp = <<EOT; | ||
| 1479 | HTTP/1.1 200 OK | ||
| 1480 | Content-Type: text/plain | ||
| 1481 | |||
| 1482 | Hello world! | ||
| 1483 | EOT | ||
| 1484 | my $def = $p->parse_headers_xs( \$resp, response => 1 ) || die( $p->error ); | ||
| 1485 | $str =~ /^\r?\n//; | ||
| 1486 | substr( $str, 0, $def->{length} ) = ''; | ||
| 1487 | # $str now contains the body, i.e.: "Hello world!\n" | ||
| 1488 | |||
| 1489 | =item * C<status> | ||
| 1490 | |||
| 1491 | String, the HTTP status, i.e. something like C<OK> | ||
| 1492 | |||
| 1493 | =item * C<protocol> | ||
| 1494 | |||
| 1495 | String, such as C<HTTP/1.1> | ||
| 1496 | |||
| 1497 | =item * C<version> | ||
| 1498 | |||
| 1499 | This is a L<version> object and contains a value such as C<1.1>, so you can do something like: | ||
| 1500 | |||
| 1501 | if( $def->{version} >= version->parse( '1.1' ) ) | ||
| 1502 | { | ||
| 1503 | # Do something | ||
| 1504 | } | ||
| 1505 | |||
| 1506 | =back | ||
| 1507 | |||
| 1508 | If not enough data was provided to parse the headers, this will return an L<error object|Module::Generic/error> with code set to C<425> (Too early). | ||
| 1509 | |||
| 1510 | If the headers is incomplete and the cumulated size exceeds the value set with L</max_headers_size>, this returns an L<error object|Module::Generic/error> with code set to C<413> (Request entity too large). | ||
| 1511 | |||
| 1512 | If there are other issues with the headers, this sets the error code to C<400> (Bad request), and for any other error, this returns an error object without code. | ||
| 1513 | |||
| 1514 | =head2 parse_multi_part | ||
| 1515 | |||
| 1516 | This takes an hash or hash reference of options and parse an HTTP multipart portion of the HTTP request or response. | ||
| 1517 | |||
| 1518 | It returns an L<entity object|HTTP::Promise::Entity> upon success and upon error it sets an L<error object|Module::Generic/error> and returns C<undef>. | ||
| 1519 | |||
| 1520 | Supported options are: | ||
| 1521 | |||
| 1522 | =over 4 | ||
| 1523 | |||
| 1524 | =item * C<entity> | ||
| 1525 | |||
| 1526 | The L<HTTP::Property::Entity> object to which this multipart belongs. | ||
| 1527 | |||
| 1528 | =item * C<reader> | ||
| 1529 | |||
| 1530 | The L<HTTP::Property::Reader> used for reading the data chunks from the filehandle. | ||
| 1531 | |||
| 1532 | =back | ||
| 1533 | |||
| 1534 | =head2 parse_open | ||
| 1535 | |||
| 1536 | Provided with a filepath, and this will open it in read mode, parse it and return an L<entity object|HTTP::Promise::Entity>. | ||
| 1537 | |||
| 1538 | If there is an error, this returns C<undef> and you can retrieve the error by calling L<Module::Generic/error> which is inherited by this module. | ||
| 1539 | |||
| 1540 | =head2 parse_request | ||
| 1541 | |||
| 1542 | This takes a string or a scalar reference including a scalar object, such as L<Module::Generic::Scalar>, and an optional hash or hash reference of parameters and parse the request found in the given string, including the header and the body. | ||
| 1543 | |||
| 1544 | It returns a dictionary as an hash reference upon success, and it sets an L<error|Module::Generic/error> with an http error code set and returns C<undef> upon error. | ||
| 1545 | |||
| 1546 | The properties returned are the same as the ones returned for a C<request> by L</parse_headers_xs>, and also sets the C<content> property containing the body data of the request. | ||
| 1547 | |||
| 1548 | Obviously this works well for simple request, i.e. not multipart ones, otherwise the entire body, whatever that is, will be stored in C<content> | ||
| 1549 | |||
| 1550 | =head2 parse_request_headers | ||
| 1551 | |||
| 1552 | This is an alias and is equivalent to calling L</parse_headers_xs> and setting the C<request> option. | ||
| 1553 | |||
| 1554 | =head2 parse_request_line | ||
| 1555 | |||
| 1556 | This takes a string or a scalar reference including a scalar object, such as L<Module::Generic::Scalar>, and parse the reuqest line returning an hash reference containing 4 properties: C<method>, C<path>, C<protocol>, C<version> | ||
| 1557 | |||
| 1558 | =head2 parse_request_pp | ||
| 1559 | |||
| 1560 | This is the same as L</parse_request>, except it uses the pure perl method L</parse_headers> to parse the headers instead of the XS one. | ||
| 1561 | |||
| 1562 | =head2 parse_response | ||
| 1563 | |||
| 1564 | This takes a string or a scalar reference including a scalar object, such as L<Module::Generic::Scalar>, and an optional hash or hash reference of parameters and parse the response found in the given string, including the header and the body. | ||
| 1565 | |||
| 1566 | It returns a dictionary as an hash reference upon success, and it sets an L<error|Module::Generic/error> with an http error code set and returns C<undef> upon error. | ||
| 1567 | |||
| 1568 | The properties returned are the same as the ones returned for a C<response> by L</parse_headers_xs>, and also sets the C<content> property containing the body data of the response. | ||
| 1569 | |||
| 1570 | =head2 parse_response_headers | ||
| 1571 | |||
| 1572 | This is an alias and is equivalent to calling L</parse_headers_xs> and setting the C<response> option. | ||
| 1573 | |||
| 1574 | =head2 parse_response_line | ||
| 1575 | |||
| 1576 | This takes a string or a scalar reference including a scalar object, such as L<Module::Generic::Scalar>, and parse the reuqest line returning an hash reference containing 4 properties: C<method>, C<path>, C<protocol>, C<version> | ||
| 1577 | |||
| 1578 | =head2 parse_response_pp | ||
| 1579 | |||
| 1580 | This is the same as L</parse_response>, except it uses the pure perl method L</parse_headers> to parse the headers instead of the XS one. | ||
| 1581 | |||
| 1582 | =head2 parse_singleton | ||
| 1583 | |||
| 1584 | Provided with an hash or hash reference of options and this parse a simple entity body. | ||
| 1585 | |||
| 1586 | It returns an L<entity object|HTTP::Promise::Entity> upon success and upon error it sets an L<error object|Module::Generic/error> and returns C<undef>. | ||
| 1587 | |||
| 1588 | Supported options are: | ||
| 1589 | |||
| 1590 | =over 4 | ||
| 1591 | |||
| 1592 | =item * C<entity> | ||
| 1593 | |||
| 1594 | The L<HTTP::Property::Entity> object to which this multipart belongs. | ||
| 1595 | |||
| 1596 | =item * C<read_until> | ||
| 1597 | |||
| 1598 | A string or a regular expression that indicates the string up to which to read data from the filehandle. | ||
| 1599 | |||
| 1600 | =item * C<reader> | ||
| 1601 | |||
| 1602 | The L<HTTP::Property::Reader> used for reading the data chunks from the filehandle. | ||
| 1603 | |||
| 1604 | =back | ||
| 1605 | |||
| 1606 | =head2 parse_version | ||
| 1607 | |||
| 1608 | This takes an HTTP version string, such as C<HTTP/1.1> or C<HTTP/2> and returns its major and minor as a 2-elements array in list context, or just the L<version> object in scalar context. | ||
| 1609 | |||
| 1610 | =head2 tmp_dir | ||
| 1611 | |||
| 1612 | Sets or gets the temporary directory to use when creating temporary files. | ||
| 1613 | |||
| 1614 | When set, this returns a L<file object|Module::Generic::File> | ||
| 1615 | |||
| 1616 | =head2 tmp_to_core | ||
| 1617 | |||
| 1618 | Boolean. When set to true, this will store data in memory rather than in a file on the filesystem. | ||
| 1619 | |||
| 1620 | =head1 THREAD-SAFETY | ||
| 1621 | |||
| 1622 | This module is thread-safe for all operations, as it operates on per-object state and uses thread-safe external libraries. | ||
| 1623 | |||
| 1624 | =head1 AUTHOR | ||
| 1625 | |||
| 1626 | Jacques Deguest E<lt>F<jack@deguest.jp>E<gt> | ||
| 1627 | |||
| 1628 | =head1 SEE ALSO | ||
| 1629 | |||
| 1630 | L<rfc6266 on Content-Disposition|https://datatracker.ietf.org/doc/html/rfc6266>, | ||
| 1631 | L<rfc7230 on Message Syntax and Routing|https://tools.ietf.org/html/rfc7230>, | ||
| 1632 | L<rfc7231 on Semantics and Content|https://tools.ietf.org/html/rfc7231>, | ||
| 1633 | L<rfc7232 on Conditional Requests|https://tools.ietf.org/html/rfc7232>, | ||
| 1634 | L<rfc7233 on Range Requests|https://tools.ietf.org/html/rfc7233>, | ||
| 1635 | L<rfc7234 on Caching|https://tools.ietf.org/html/rfc7234>, | ||
| 1636 | L<rfc7235 on Authentication|https://tools.ietf.org/html/rfc7235>, | ||
| 1637 | L<rfc7578 on multipart/form-data|https://tools.ietf.org/html/rfc7578>, | ||
| 1638 | L<rfc7540 on HTTP/2.0|https://tools.ietf.org/html/rfc7540> | ||
| 1639 | |||
| 1640 | L<Mozilla documentation on HTTP protocol|https://developer.mozilla.org/en-US/docs/Web/HTTP/Resources_and_specifications> | ||
| 1641 | |||
| 1642 | L<Mozilla documentation on HTTP messages|https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages> | ||
| 1643 | |||
| 1644 | L<Mozilla documentation|https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST> | ||
| 1645 | |||
| 1646 | L<HTTP::Promise>, L<HTTP::Promise::Request>, L<HTTP::Promise::Response>, L<HTTP::Promise::Message>, L<HTTP::Promise::Entity>, L<HTTP::Promise::Headers>, L<HTTP::Promise::Body>, L<HTTP::Promise::Body::Form>, L<HTTP::Promise::Body::Form::Data>, L<HTTP::Promise::Body::Form::Field>, L<HTTP::Promise::Status>, L<HTTP::Promise::MIME>, L<HTTP::Promise::Parser>, L<HTTP::Promise::IO>, L<HTTP::Promise::Stream>, L<HTTP::Promise::Exception> | ||
| 1647 | |||
| 1648 | =head1 COPYRIGHT & LICENSE | ||
| 1649 | |||
| 1650 | Copyright(c) 2022 DEGUEST Pte. Ltd. | ||
| 1651 | |||
| 1652 | All rights reserved. | ||
| 1653 | |||
| 1654 | This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. | ||
| 1655 | |||
| 1656 | =cut |