blib/lib/HTTP/Promise.pm untested

filter: Statementstmt 0.0% 0 / 1103 Branchbran 0.0% 0 / 572 Conditioncond 0.0% 0 / 684 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 93 Podpod 0.0% 0 / 71 totaltotal 0.0% 0 / 2523 CC 287 SCAR 76.4
CC
287
Cov
0%
send
7482.0
_read_body
1482.0
_make_request_data
1332.0
CRAP 2072.7
1 ##----------------------------------------------------------------------------
2 ## Asynchronous HTTP Request and Promise - ~/lib/HTTP/Promise.pm
3 ## Version v0.7.3
4 ## Copyright(c) 2025 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/05/06
7 ## Modified 2025/10/25
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;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 use warnings::register;
20 use parent qw( Module::Generic );
21 use vars qw( $VERSION $AUTOLOAD $CONTENT_SIZE_THRESHOLD $CRLF
22 $DEFAULT_PROTOCOL $EXCEPTION_CLASS $EXTENSION_VARY
23 $IS_WIN32 $HTTP_TOKEN $HTTP_QUOTED_STRING $BUFFER_SIZE
24 $MAX_HEADERS_SIZE $MAX_BODY_IN_MEMORY_SIZE $EXPECT_THRESHOLD $DEFAULT_MIME_TYPE
25 $SERIALISER @EXPORT_OK );
26 use Cookie;
27 use Cookie::Jar;
28 use Errno qw( EAGAIN ECONNRESET EINPROGRESS EINTR EWOULDBLOCK ECONNABORTED EISCONN );
29 use HTTP::Promise::Exception;
30 use HTTP::Promise::IO;
31 use HTTP::Promise::Pool;
32 use HTTP::Promise::Request;
33 use HTTP::Promise::Response;
34 use HTTP::Promise::Status qw( :all );
35 # use Nice::Try;
36 use Promise::Me;
37 use Scalar::Util ();
38 use URI;
39 use URI::Escape::XS ();
40 # < 0 so we recognise those as system errors
41 use constant {
42 ERROR_EINTR => ( abs( Errno::EINTR ) * -1 ),
43 TYPE_URL_ENCODED => 'application/x-www-form-urlencoded',
44 };
45 our @EXPORT = qw( async await );
46 our @EXPORT_OK = qw( fetch );
47 # "\r\n" is not portable
48 our $CRLF = "\015\012";
49 our $DEFAULT_PROTOCOL = 'HTTP/1.1';
50 our $EXCEPTION_CLASS = 'HTTP::Promise::Exception';
51 our $HTTP_TOKEN = qr/[^\x00-\x31\x7F]+/;
52 our $HTTP_QUOTED_STRING = qr/"([^"]+|\\.)*"/;
53 # 10K
54 our $BUFFER_SIZE = 10240000;
55 our $MAX_HEADERS_SIZE = 8192;
56 # 256Kb
57 our $MAX_BODY_IN_MEMORY_SIZE = 102400;
58 # 1Mb
59 our $EXPECT_THRESHOLD = 1024000000;
60 our $EXTENSION_VARY = 1;
61 our $DEFAULT_MIME_TYPE = 'application/octet-stream';
62 our $SERIALISER = $Promise::Me::SERIALISER;
63 our $VERSION = 'v0.7.3';
64 };
65  
66 use strict;
67 use warnings;
68  
69 sub init
70 {
71 my $self = shift( @_ );
72 $self->{accept_language} = [];
73 $self->{accept_encoding} = 'auto';
74 $self->{agent} = qq{HTTP-Promise/$VERSION (perl; +https://metacpan.org/pod/HTTP::Promise)};
75 $self->{auto_switch_https} = 1;
76 $self->{buffer_size} = $BUFFER_SIZE;
77 $self->{cookie_jar} = Cookie::Jar->new;
78 $self->{default_headers} = undef;
79 $self->{default_protocol} = ( $DEFAULT_PROTOCOL || 'HTTP/1.1' );
80 # DNT -> Do not track header field
81 $self->{dnt} = undef;
82 $self->{expect_threshold} = $EXPECT_THRESHOLD;
83 $self->{ext_vary} = $EXTENSION_VARY;
84 $self->{from} = undef;
85 $self->{inactivity_timeout} = 600;
86 $self->{local_host} = undef;
87 $self->{local_port} = undef;
88 $self->{max_body_in_memory_size} = $MAX_BODY_IN_MEMORY_SIZE;
89 $self->{max_headers_size} = $MAX_HEADERS_SIZE;
90 $self->{max_redirect} = 7;
91 $self->{max_size} = undef;
92 $self->{medium} = $Promise::Me::SHARE_MEDIUM;
93 $self->{no_proxy} = [];
94 $self->{proxy} = $ENV{http_proxy} || $ENV{HTTP_PROXY} || undef;
95 $self->{proxy_authorization} = undef;
96 $self->{requests_redirectable} = [qw( GET HEAD )];
97 $self->{send_te} = 1;
98 $self->{serialiser} = $SERIALISER;
99 $self->{shared_mem_size} = $Promise::Me::RESULT_MEMORY_SIZE;
100 $self->{ssl_opts} = undef;
101 $self->{stop_if} = sub{};
102 $self->{threshold} = $CONTENT_SIZE_THRESHOLD;
103 # 3 minutes
104 $self->{timeout} = 180;
105 $self->{use_content_file} = 0;
106 $self->{use_promise} = 1;
107 $self->{_init_strict_use_sub} = 1;
108 $self->{_exception_class} = $EXCEPTION_CLASS;
109 $self->SUPER::init( @_ ) || return( $self->pass_error );
110 my $headers = $self->default_headers;
111 if( $headers )
112 {
113 unless( $self->connection_header )
114 {
115 my $connection_header = 'keep-alive';
116 if( $headers->exists( 'connection' ) )
117 {
118 $connection_header = $headers->get( 'connection' );
119 }
120 $self->{connection_header} = $connection_header;
121 }
122 }
123 else
124 {
125 $self->default_headers( HTTP::Promise::Headers->new ) ||
126 return( $self->pass_error( HTTP::Promise::Headers->error ) );
127 }
128 $self->{_pool} = HTTP::Promise::Pool->new;
129 return( $self );
130 }
131  
132 sub accept_language { return( shift->_set_get_array_as_object( 'accept_language', @_ ) ); }
133  
134 sub accept_encoding { return( shift->_set_get_scalar_as_object( 'accept_encoding', @_ ) ); }
135  
136 # NOTE: request parameter
137 sub agent { return( shift->_set_get_scalar_as_object( 'agent', @_ ) ); }
138  
139 sub auto_switch_https { return( shift->_set_get_boolean( 'auto_switch_https', @_ ) ); }
140  
141 sub buffer_size { return( shift->_set_get_number( 'buffer_size', @_ ) ); }
142  
143 sub clone
144 {
145 my $self = shift( @_ );
146 my $new = $self->SUPER::clone;
147 if( $self->{default_headers} )
148 {
149 $new->{default_headers} = $self->{default_headers}->clone;
150 }
151 $new->{_pool} = HTTP::Promise::Pool->new;
152 return( $new );
153 }
154  
155 sub connection_header { return( shift->_set_get_scalar_as_object( 'connection_header', @_ ) ); }
156  
157 # NOTE: request parameter
158 sub cookie_jar { return( shift->_set_get_scalar( 'cookie_jar', @_ ) ); }
159  
160 sub decodable { return( HTTP::Promise::Stream->decodable( @_ ) ); }
161  
162 # NOTE: request parameter
163 sub default_header { return( shift->default_headers->header( @_ ) ); }
164  
165 # NOTE: request parameter
166 sub default_headers { return( shift->_set_get_object_without_init( 'default_headers', [qw( HTTP::Promise::Headers HTTP::Headers )], @_ ) ); }
167  
168 sub default_protocol { return( shift->_set_get_scalar_as_object( 'default_protocol', @_ ) ); }
169  
170 # As per rfc7231, a body is allowed for DELETE, but usually discarded by most of the servers.
171 sub delete
172 {
173 my $self = shift( @_ );
174 if( $self->use_promise )
175 {
176 my $prom = Promise::Me->new(sub
177 {
178 my( $resolve, $reject ) = @$_;
179 my $req = $self->_make_request_data( 'DELETE' => @_ ) ||
180 return( $reject->( $self->error ) );
181 unless( $req->headers->host )
182 {
183 $req->headers->host( $req->host );
184 }
185 my $resp = $self->send( $req ) || return( $reject->( $self->error ) );
186 return( $resolve->( $resp ) );
187 },
188 {
189 args => [@_],
190 ( defined( $self->{serialiser} ) ? ( serialiser => $self->{serialiser} ) : () ),
191 ( defined( $self->{medium} ) ? ( medium => $self->{medium} ) : () ),
192 ( defined( $self->{shared_mem_size} ) ? ( result_shared_mem_size => $self->{shared_mem_size} ) : () ),
193 }) || return( $self->pass_error( Promise::Me->error ) );
194 return( $prom );
195 }
196 else
197 {
198 my $req = $self->_make_request_data( 'DELETE' => @_ ) ||
199 return( $self->pass_error );
200 unless( $req->headers->host )
201 {
202 $req->headers->host( $req->host );
203 }
204 my $resp = $self->send( $req ) ||
205 return( $self->pass_error );
206 return( $resp );
207 }
208 }
209  
210  
211 sub dnt { return( shift->_set_get_boolean( 'dnt', @_ ) ); }
212  
213 sub expect_threshold { return( shift->_set_get_number( 'expect_threshold', @_ ) ); }
214  
215 sub ext_vary { return( shift->_set_get_boolean( 'ext_vary', @_ ) ); }
216  
217 sub fetch
218 {
219 my $self;
220 if( Scalar::Util::blessed( $_[0] ) && $_[0]->isa( __PACKAGE__ ) )
221 {
222 $self = shift( @_ );
223 }
224 else
225 {
226 $self = __PACKAGE__->new;
227 }
228 my $meth = 'get';
229 for( my $i = 0; $i < scalar( @_ ); $i += 2 )
230 {
231 if( $_[$i] eq 'method' )
232 {
233 $meth = $_[$i + 1];
234 splice( @_, $i, 2 );
235 last;
236 }
237 }
238 return( $self->error( "Unknown HTTP method \"${meth}\"." ) ) if( $meth !~ /^$HTTP::Promise::Request::KNOWN_METHODS_I$/i );
239 my $code = $self->can( $meth ) ||
240 return( $self->error( "Somehow the HTTP method \"${meth}\" is not supported by ", ref( $self ) ) );
241 return( $code->( $self, @_ ) );
242 }
243  
244 sub file { return( shift->_set_get_object_without_init( 'file', 'Module::Generic::File', @_ ) ); }
245  
246 # NOTE: request parameter
247 sub from { return( shift->_set_get_scalar_as_object( 'from', @_ ) ); }
248  
249 sub get
250 {
251 my $self = shift( @_ );
252 if( $self->use_promise )
253 {
254 my $prom = Promise::Me->new(sub
255 {
256 my( $resolve, $reject ) = @$_;
257 my $req = $self->_make_request_query( GET => @_ ) ||
258 return( $reject->( $self->error ) );
259 my $resp = $self->send( $req ) || return( $reject->( $self->error ) );
260 return( $resolve->( $resp ) );
261 },
262 {
263 args => [@_],
264 ( defined( $self->{serialiser} ) ? ( serialiser => $self->{serialiser} ) : () ),
265 ( defined( $self->{medium} ) ? ( medium => $self->{medium} ) : () ),
266 ( defined( $self->{shared_mem_size} ) ? ( result_shared_mem_size => $self->{shared_mem_size} ) : () ),
267 }) || return( $self->pass_error( Promise::Me->error ) );
268 return( $prom );
269 }
270 else
271 {
272 my $req = $self->_make_request_query( GET => @_ ) ||
273 return( $self->pass_error );
274 my $resp = $self->send( $req ) ||
275 return( $self->pass_error );
276 return( $resp );
277 }
278 }
279  
280 sub head
281 {
282 my $self = shift( @_ );
283 if( $self->use_promise )
284 {
285 my $prom = Promise::Me->new(sub
286 {
287 my( $resolve, $reject ) = @$_;
288 my $req = $self->_make_request_query( HEAD => @_ ) ||
289 return( $reject->( $self->error ) );
290 my $resp = $self->send( $req ) || return( $reject->( $self->error ) );
291 return( $resolve->( $resp ) );
292 },
293 {
294 args => [@_],
295 ( defined( $self->{serialiser} ) ? ( serialiser => $self->{serialiser} ) : () ),
296 ( defined( $self->{medium} ) ? ( medium => $self->{medium} ) : () ),
297 ( defined( $self->{shared_mem_size} ) ? ( result_shared_mem_size => $self->{shared_mem_size} ) : () ),
298 }) || return( $self->pass_error( Promise::Me->error ) );
299 return( $prom );
300 }
301 else
302 {
303 my $req = $self->_make_request_query( HEAD => @_ ) ||
304 return( $self->pass_error );
305 my $resp = $self->send( $req ) ||
306 return( $self->pass_error );
307 return( $resp );
308 }
309 }
310  
311 sub httpize_datetime { return( shift->_datetime( @_ ) ); }
312  
313 sub inactivity_timeout { return( shift->_set_get_number( 'inactivity_timeout', @_ ) ); }
314  
315 sub is_protocol_supported
316 {
317 my $self = shift( @_ );
318 my $scheme = shift( @_ ) ||
319 return( $self->error( "No scheme value was provided." ) );
320 if( $self->_is_object( $scheme ) )
321 {
322 return( $self->error( "Object provided (", overload::StrVal( $scheme ), ") does not support the 'scheme' method." ) ) if( !$scheme->can( 'scheme' ) );
323 $scheme = $scheme->scheme;
324 }
325 else
326 {
327 return( $self->error( "Illegal scheme '$scheme' passed to is_protocol_supported" ) ) if( $scheme =~ /\W/ );
328 $scheme = lc $scheme;
329 }
330 return(1) if( $scheme eq 'http' || $scheme eq 'https' );
331 return(0);
332 }
333  
334 sub languages { return( shift->_set_get_array_as_object( 'accept_language', @_ ) ); }
335  
336 # NOTE: request parameter
337 sub local_address { return( shift->_set_get_scalar( 'local_host', @_ ) ); }
338  
339 sub local_host { return( shift->_set_get_scalar( 'local_host', @_ ) ); }
340  
341 sub local_port { return( shift->_set_get_scalar( 'local_port', @_ ) ); }
342  
343 sub max_body_in_memory_size { return( shift->_set_get_number( 'max_body_in_memory_size', @_ ) ); }
344  
345 sub max_headers_size { return( shift->_set_get_number( 'max_headers_size', @_ ) ); }
346  
347 # NOTE: request parameter
348 sub max_redirect { return( shift->_set_get_number( 'max_redirect', @_ ) ); }
349  
350 # NOTE: request parameter
351 sub max_size { return( shift->_set_get_number( 'max_size', @_ ) ); }
352  
353 # NOTE: medium method for Promise::Me
354 sub medium { return( shift->_set_get_scalar( 'medium', @_ ) ); }
355  
356 sub mirror
357 {
358 my $self = shift( @_ );
359 my( $url, $file ) = @_;
360 if( $self->use_promise )
361 {
362 return( Promise::Me->new(sub
363 {
364 my( $resolve, $reject ) = @$_;
365 return( $reject->( HTTP::Promise::Exception->new({
366 code => 500,
367 message => 'Local file name is missing',
368 }) ) ) unless( defined( $file ) && length( $file ) );
369  
370 my $request = HTTP::Promise::Request->new( 'GET' => $url ) ||
371 return( $reject->( HTTP::Promise::Exception->new({
372 code => 500,
373 message => HTTP::Promise::Request->error->message
374 }) ) );
375 $self->prepare_headers( $request ) ||
376 return( $reject->( HTTP::Promise::Exception->new({
377 code => 500,
378 message => $self->error->message,
379 }) ) );
380 $file = $self->new_file( $file ) ||
381 return( $reject->( HTTP::Promise::Exception->new({
382 code => 500,
383 message => $self->error->message,
384 }) ) );
385 # If the file exists, add a cache-related header
386 if( $file->exists )
387 {
388 # Module::Generic::Finfo->mtime returns a Module::Generic::DateTime object
389 my $mtime = $file->mtime;
390 if( $mtime )
391 {
392 my $strtime = $self->_datetime( $mtime ) ||
393 return( $reject->( HTTP::Promise::Exception->new({
394 code => 500,
395 message => $self->error->message,
396 }) ) );
397 $request->header( 'If-Modified-Since' => $strtime );
398 }
399 }
400  
401 my $tmpfile = $self->new_tempfile;
402 $tmpfile->touch || return( $reject->( $tmpfile->error ) );
403  
404 my $response = $self->send( $request ) || return( $reject->( $self->pass_error ) );
405
406 if( $response->header( 'X-Died' ) )
407 {
408 $tmpfile->unlink;
409 return( $reject->( HTTP::Promise::Exception->new({
410 code => 500,
411 message => $response->header( 'X-Died' ),
412 }) ) );
413 }
414  
415 # Only fetching a fresh copy of the file would be considered success.
416 # If the file was not modified, "304" would returned, which
417 # is considered by HTTP::Status to be a "redirect", /not/ "success"
418 if( $response->is_success )
419 {
420 my $body = $response->entity->body;
421 return( $reject->( HTTP::Promise::Exception->new({
422 code => 500,
423 message => "No body set for this HTTP message entity.",
424 }) ) ) if( !$body );
425 my $io = $body->open( '<' ) ||
426 return( $reject->( HTTP::Promise::Exception->new({
427 code => 500,
428 message => "Unable to open HTTP message entity body: " . $body->error,
429 }) ) ) if( !$body );
430 my $out = $tmpfile->open( '>', { autoflush => 1 } ) ||
431 return( $reject->( HTTP::Promise::Exception->new({
432 code => 500,
433 message => "Unable to open temporary file \"$tmpfile\" in write mode: " . $tmpfile->error,
434 }) ) ) if( !$body );
435 while( $io->read( my $buff, 8192 ) )
436 {
437 $out->print( $buff ) ||
438 return( $reject->( HTTP::Promise::Exception->new({
439 code => 500,
440 message => "Unable to write to temporary file \"$tmpfile\": " . $out->error,
441 }) ) ) if( !$body );
442 }
443 $io->close;
444 $out->close;
445 my $stat = $tmpfile->stat or
446 return( $reject->( HTTP::Promise::Exception->new({
447 code => 500,
448 message => "Could not stat tmpfile '$tmpfile': " . $tmpfile->error,
449 }) ) );
450 my $file_length = $stat->size;
451 my( $content_length ) = $response->header( 'Content-length' );
452  
453 if( defined( $content_length ) and $file_length < $content_length )
454 {
455 $tmpfile->unlink;
456 return( $reject->( HTTP::Promise::Exception->new({
457 code => 500,
458 message => "Transfer truncated: only $file_length out of $content_length bytes received",
459 }) ) );
460 }
461 elsif( defined( $content_length ) and $file_length > $content_length )
462 {
463 $tmpfile->unlink;
464 return( $reject->( HTTP::Promise::Exception->new({
465 code => 500,
466 message => "Content-length mismatch: expected $content_length bytes, got $file_length",
467 }) ) );
468 }
469 # The file was the expected length.
470 else
471 {
472 # Replace the stale file with a fresh copy
473 # File::Copy will attempt to do it atomically,
474 # and fall back to a delete + copy if that fails.
475 $file = $tmpfile->move( $file, overwrite => 1 ) ||
476 return( $reject->( HTTP::Promise::Exception->new({
477 code => 500,
478 message => "Cannot copy '$tmpfile' to '$file': $!",
479 }) ) );
480  
481 # Set standard file permissions if umask is supported.
482 # If not, leave what Module::Generic::File created in effect.
483 if( defined( my $umask = umask() ) )
484 {
485 my $mode = 0666 &~ $umask;
486 $file->chmod( $mode ) ||
487 return( $reject->( HTTP::Promise::Exception->new({
488 code => 500,
489 message => sprintf( "Cannot chmod %o '%s': %s", $mode, $file, $file->error ),
490 }) ) );
491 }
492  
493 # make sure the file has the same last modification time
494 if( my $lm = $response->last_modified )
495 {
496 $file->utime( $lm, $lm ) || do
497 {
498 warn( "Warning: cannot update modification time for file '$file': $!\n" ) if( $self->_warnings_is_enabled );
499 };
500 }
501 }
502 }
503 # The local copy is fresh enough, so just delete the temp file
504 else
505 {
506 $tmpfile->unlink;
507 }
508 return( $resolve->( $response ) );
509 }, { ( defined( $self->{serialiser} ) ? ( serialiser => $self->{serialiser} ) : () ) } ) );
510 }
511 else
512 {
513 return( $self->error({
514 code => 500,
515 message => 'Local file name is missing',
516 }) ) unless( defined( $file ) && length( $file ) );
517  
518 my $request = HTTP::Promise::Request->new( 'GET' => $url ) ||
519 return( $self->error({
520 code => 500,
521 message => HTTP::Promise::Request->error->message
522 }) );
523 $self->prepare_headers( $request ) || return( $self->pass_error );
524 $file = $self->new_file( $file ) || return( $self->pass_error );
525 # If the file exists, add a cache-related header
526 if( $file->exists )
527 {
528 # Module::Generic::Finfo->mtime returns a Module::Generic::DateTime object
529 my $mtime = $file->mtime;
530 if( $mtime )
531 {
532 my $strtime = $self->_datetime( $mtime ) ||
533 return( $self->pass_error );
534 $request->header( 'If-Modified-Since' => $strtime );
535 }
536 }
537  
538 my $tmpfile = $self->new_tempfile;
539 $tmpfile->touch || return( $self->pass_error( $tmpfile->error ) );
540  
541 my $response = $self->send( $request ) || return( $self->pass_error );
542  
543 if( $response->header( 'X-Died' ) )
544 {
545 $tmpfile->unlink;
546 return( $self->error({
547 code => 500,
548 message => $response->header( 'X-Died' ),
549 }) );
550 }
551  
552 # Only fetching a fresh copy of the file would be considered success.
553 # If the file was not modified, "304" would returned, which
554 # is considered by HTTP::Status to be a "redirect", /not/ "success"
555 if( $response->is_success )
556 {
557 my $body = $response->entity->body;
558 return( $self->error({
559 code => 500,
560 message => "No body set for this HTTP message entity.",
561 }) ) if( !$body );
562 my $io = $body->open( '<' ) ||
563 return( $self->error({
564 code => 500,
565 message => "Unable to open HTTP message entity body: " . $body->error,
566 }) );
567 my $out = $tmpfile->open( '>', { autoflush => 1 } ) ||
568 return( $self->error({
569 code => 500,
570 message => "Unable to open temporary file \"$tmpfile\" in write mode: " . $tmpfile->error,
571 }) );
572 while( $io->read( my $buff, 8192 ) )
573 {
574 $out->print( $buff ) ||
575 return( $self->error({
576 code => 500,
577 message => "Unable to write to temporary file \"$tmpfile\": " . $out->error,
578 }) );
579 }
580 $io->close;
581 $out->close;
582 my $stat = $tmpfile->stat or
583 return( $self->error({
584 code => 500,
585 message => "Could not stat tmpfile '$tmpfile': " . $tmpfile->error,
586 }) );
587 my $file_length = $stat->size;
588 my( $content_length ) = $response->header( 'Content-length' );
589  
590 if( defined( $content_length ) and $file_length < $content_length )
591 {
592 $tmpfile->unlink;
593 return( $self->error({
594 code => 500,
595 message => "Transfer truncated: only $file_length out of $content_length bytes received",
596 }) );
597 }
598 elsif( defined( $content_length ) and $file_length > $content_length )
599 {
600 $tmpfile->unlink;
601 return( $self->error({
602 code => 500,
603 message => "Content-length mismatch: expected $content_length bytes, got $file_length",
604 }) );
605 }
606 # The file was the expected length.
607 else
608 {
609 # Replace the stale file with a fresh copy
610 # File::Copy will attempt to do it atomically,
611 # and fall back to a delete + copy if that fails.
612 $file = $tmpfile->move( $file, overwrite => 1 ) ||
613 return( $self->error({
614 code => 500,
615 message => "Cannot copy '$tmpfile' to '$file': $!",
616 }) );
617  
618 # Set standard file permissions if umask is supported.
619 # If not, leave what Module::Generic::File created in effect.
620 if( defined( my $umask = umask() ) )
621 {
622 my $mode = 0666 &~ $umask;
623 $file->chmod( $mode ) ||
624 return( $self->error({
625 code => 500,
626 message => sprintf( "Cannot chmod %o '%s': %s", $mode, $file, $file->error ),
627 }) );
628 }
629  
630 # make sure the file has the same last modification time
631 if( my $lm = $response->last_modified )
632 {
633 $file->utime( $lm, $lm ) || do
634 {
635 warn( "Warning: cannot update modification time for file '$file': $!\n" ) if( $self->_warnings_is_enabled );
636 };
637 }
638 }
639 }
640 # The local copy is fresh enough, so just delete the temp file
641 else
642 {
643 $tmpfile->unlink;
644 }
645 return( $response );
646 }
647 }
648  
649 sub new_headers
650 {
651 my $self = shift( @_ );
652 $self->_load_class( 'HTTP::Promise::Headers' ) || return( $self->pass_error );
653 my $headers = HTTP::Promise::Headers->new( @_ ) ||
654 return( $self->pass_error( HTTP::Promise::Headers->error ) );
655 return( $headers );
656 }
657  
658 # NOTE: request parameter
659 sub no_proxy { return( shift->_set_get_array_as_object( 'no_proxy', @_ ) ); }
660  
661 sub options
662 {
663 my $self = shift( @_ );
664 if( $self->use_promise )
665 {
666 my $prom = Promise::Me->new(sub
667 {
668 my( $resolve, $reject ) = @$_;
669 my $req = $self->_make_request_data( OPTIONS => @_ ) ||
670 die( HTTP::Promise::Request->error );
671 my $resp = $self->send( $req ) || return( $reject->( $self->error ) );
672 return( $resolve->( $resp ) );
673 },
674 {
675 args => [@_],
676 ( defined( $self->{serialiser} ) ? ( serialiser => $self->{serialiser} ) : () ),
677 ( defined( $self->{medium} ) ? ( medium => $self->{medium} ) : () ),
678 ( defined( $self->{shared_mem_size} ) ? ( result_shared_mem_size => $self->{shared_mem_size} ) : () ),
679 }) || return( $self->pass_error( Promise::Me->error ) );
680 return( $prom );
681 }
682 else
683 {
684 my $req = $self->_make_request_data( OPTIONS => @_ ) ||
685 return( $self->pass_error( HTTP::Promise::Request->error ) );
686 my $resp = $self->send( $req ) ||
687 return( $self->pass_error );
688 return( $resp );
689 }
690 }
691  
692 sub patch
693 {
694 my $self = shift( @_ );
695 if( $self->use_promise )
696 {
697 my $prom = Promise::Me->new(sub
698 {
699 my( $resolve, $reject ) = @$_;
700 my $req = $self->_make_request_data( PATCH => @_ ) ||
701 die( HTTP::Promise::Request->error );
702 my $resp = $self->send( $req ) || return( $reject->( $self->error ) );
703 return( $resolve->( $resp ) );
704 },
705 {
706 args => [@_],
707 ( defined( $self->{serialiser} ) ? ( serialiser => $self->{serialiser} ) : () ),
708 ( defined( $self->{medium} ) ? ( medium => $self->{medium} ) : () ),
709 ( defined( $self->{shared_mem_size} ) ? ( result_shared_mem_size => $self->{shared_mem_size} ) : () ),
710 }) || return( $self->pass_error( Promise::Me->error ) );
711 return( $prom );
712 }
713 else
714 {
715 my $req = $self->_make_request_data( PATCH => @_ ) ||
716 return( $self->pass_error( HTTP::Promise::Request->error ) );
717 my $resp = $self->send( $req ) ||
718 return( $self->pass_error );
719 return( $resp );
720 }
721 }
722  
723 sub post
724 {
725 my $self = shift( @_ );
726 my @args = @_;
727 if( $self->use_promise )
728 {
729 my $prom = Promise::Me->new(sub
730 {
731 my( $resolve, $reject ) = @$_;
732 my $req = $self->_make_request_data( POST => @args ) ||
733 die( HTTP::Promise::Request->error );
734 my $resp = $self->send( $req ) || return( $reject->( $self->error ) );
735 return( $resolve->( $resp ) );
736 },
737 {
738 args => [@_],
739 ( defined( $self->{serialiser} ) ? ( serialiser => $self->{serialiser} ) : () ),
740 ( defined( $self->{medium} ) ? ( medium => $self->{medium} ) : () ),
741 ( defined( $self->{shared_mem_size} ) ? ( result_shared_mem_size => $self->{shared_mem_size} ) : () ),
742 }) || return( $self->pass_error( Promise::Me->error ) );
743 return( $prom );
744 }
745 else
746 {
747 my $req = $self->_make_request_data( POST => @args ) ||
748 return( $self->pass_error( HTTP::Promise::Request->error ) );
749 my $resp = $self->send( $req ) ||
750 return( $self->pass_error );
751 return( $resp );
752 }
753 }
754  
755 sub prepare
756 {
757 my $self = shift( @_ );
758 my $meth = shift( @_ ) || return( $self->error( "No HTTP method was provided to prepare the request." ) );
759 my @args = @_;
760 $meth = uc( $meth );
761 if( $meth eq 'GET' || $meth eq 'HEAD' )
762 {
763 return( $self->_make_request_query( $meth, @args ) );
764 }
765 elsif( $meth eq 'OPTIONS' || $meth eq 'PATCH' || $meth eq 'POST' || $meth eq 'PUT' )
766 {
767 return( $self->_make_request_data( $meth, @args ) );
768 }
769 else
770 {
771 my $req = HTTP::Promise::Request->new( $meth, @args ) ||
772 return( $self->pass_error( HTTP::Promise::Request->error ) );
773 return( $req );
774 }
775 }
776  
777 sub prepare_headers
778 {
779 my $self = shift( @_ );
780 my $req = shift( @_ );
781 return( $self->error( "Object provided is not an HTTP::Promise::Request object" ) ) if( !$self->_is_a( $req => 'HTTP::Promise::Request' ) );
782 my $h = $req->headers;
783 return( $self->error( "Request object provided does not have an HTTP::Promise::Headers object set to it!" ) ) if( !$h );
784 unless( $req->protocol )
785 {
786 $req->protocol( $self->default_protocol || 'HTTP/1.1' );
787 }
788
789 # Set default headers now
790 my $default_headers = $self->default_headers;
791 $default_headers->scan(sub
792 {
793 my( $name, $value ) = @_;
794 $h->header( $name => $value );
795 });
796
797 my $ua = $self->agent;
798 if( defined( $ua ) && !$h->user_agent )
799 {
800 $h->user_agent( $ua );
801 }
802 # e.g.: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
803 if( !$h->accept )
804 {
805 $h->accept( 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.8' );
806 }
807 # Accept-Encoding: gzip, deflate, br
808 my $ae = $self->accept_encoding;
809 if( !$h->accept_encoding && $ae ne 'none' )
810 {
811 $self->_load_class( 'HTTP::Promise::Stream' ) || return( $self->pass_error );
812 my $decodables;
813 no warnings 'once'; # REMOVE ME
814 local $HTTP::Promise::Stream::DEBUG = $self->debug; # REMOVE ME
815 if( !$ae->is_empty && $ae ne 'all' && $ae ne 'auto' )
816 {
817 $decodables = HTTP::Promise::Stream->decodable( [split( /[[:blank:]\h]*\,[[:blank:]\h]*/, "$ae" )] );
818 }
819 else
820 {
821 $decodables = HTTP::Promise::Stream->decodable( 'browser' );
822 }
823 $h->accept_encoding( $decodables->join( ',' )->scalar );
824 }
825 # Accept-Language: fr-FR,en-GB;q=0.8,fr;q=0.6,en;q=0.4,ja;q=0.2
826 if( !$h->accept_language && !$self->accept_language->is_empty )
827 {
828 my $pref = 0.9;
829 my $langs = [];
830 $self->accept_language->foreach(sub
831 {
832 push( @$langs, sprintf( '%s;q=%.1f', $_, $pref ) );
833 $pref -= 0.1 unless( $pref == 0.1 );
834 });
835 $h->accept_language( join( ',', @$langs ) );
836 }
837 my $dnt = $self->dnt;
838 if( !defined( $h->dnt ) && defined( $dnt ) )
839 {
840 $h->dnt( $dnt ? 1 : 0 );
841 }
842 # Upgrade-Insecure-Requests: 1
843 my $upgrade_ssl = $self->auto_switch_https;
844 if( $req->uri->scheme eq 'http' && ( !defined( $upgrade_ssl ) || $upgrade_ssl ) )
845 {
846 $h->upgrade_insecure_requests(1);
847 }
848 unless( $req->headers->host )
849 {
850 $req->headers->host( $req->host );
851 }
852 return( $req );
853 }
854  
855 sub proxy { return( shift->_set_get_scalar_as_object( 'proxy', @_ ) ); }
856  
857 sub proxy_authorization { return( shift->_set_get_scalar_as_object( 'proxy_authorization', @_ ) ); }
858  
859 sub put
860 {
861 my $self = shift( @_ );
862 if( $self->use_promise )
863 {
864 my $prom = Promise::Me->new(sub
865 {
866 my( $resolve, $reject ) = @$_;
867 my $req = $self->_make_request_data( PUT => @_ ) ||
868 die( HTTP::Promise::Request->error );
869 my $resp = $self->send( $req ) || return( $reject->( $self->error ) );
870 return( $resolve->( $resp ) );
871 },
872 {
873 args => [@_],
874 ( defined( $self->{serialiser} ) ? ( serialiser => $self->{serialiser} ) : () ),
875 ( defined( $self->{medium} ) ? ( medium => $self->{medium} ) : () ),
876 ( defined( $self->{shared_mem_size} ) ? ( result_shared_mem_size => $self->{shared_mem_size} ) : () ),
877 }) || return( $self->pass_error( Promise::Me->error ) );
878 return( $prom );
879 }
880 else
881 {
882 my $req = $self->_make_request_data( PUT => @_ ) ||
883 return( $self->pass_error( HTTP::Promise::Request->error ) );
884 my $resp = $self->send( $req ) ||
885 return( $self->pass_error );
886 return( $resp );
887 }
888 }
889  
890 sub request
891 {
892 my $self = shift( @_ );
893 my $req = shift( @_ );
894 my $opts = $self->_get_args_as_hash( @_ );
895 $opts->{read_size} //= 0;
896 if( $self->use_promise )
897 {
898 my $prom = Promise::Me->new(sub
899 {
900 my( $resolve, $reject ) = @$_;
901 return( $reject->( HTTP::Promise::Exception->new({
902 code => 500,
903 message => "No request object was provided."
904 }) ) ) if( !$req );
905 $self->use_content_file( $opts->{use_content_file} ) if( exists( $opts->{use_content_file} ) );
906 my $resp = $self->send( $req, $opts ) || return( $reject->( $self->pass_error ) );
907 return( $resolve->( $resp ) );
908 },
909 {
910 ( defined( $self->{serialiser} ) ? ( serialiser => $self->{serialiser} ) : () ),
911 ( defined( $self->{medium} ) ? ( medium => $self->{medium} ) : () ),
912 ( defined( $self->{shared_mem_size} ) ? ( result_shared_mem_size => $self->{shared_mem_size} ) : () ),
913 ( defined( $opts->{promise_debug} ) ? ( debug => $opts->{promise_debug} ) : () ),
914 }) || return( $self->pass_error( Promise::Me->error ) );
915 return( $prom );
916 }
917 else
918 {
919 return( $self->error( "No request object was provided." ) ) if( !$req );
920 $self->use_content_file( $opts->{use_content_file} ) if( exists( $opts->{use_content_file} ) );
921 my $resp = $self->send( $req, $opts ) || return( $self->pass_error );
922 return( $resp );
923 }
924 }
925  
926 # NOTE: request parameter
927 sub requests_redirectable { return( shift->_set_get_array_as_object( 'requests_redirectable', @_ ) ); }
928  
929 sub send
930 {
931 my $self = shift( @_ );
932 my $req = shift( @_ );
933 return( $self->error( "Request object provided ($req) is not a HTTP::Promise::Request object." ) ) if( !$self->_is_a( $req => 'HTTP::Promise::Request' ) );
934 my $opts = $self->_get_args_as_hash( @_ );
935 $opts->{expect_threshold} //= $self->expect_threshold // 0;
936 $opts->{total_attempts} //= 0;
937 # if( $self->debug >= 4 )
938 # {
939 # my $hcopy = $req->headers->clone;
940 # if( my $auth = $hcopy->authorization )
941 # {
942 # $auth =~ s/\b([A-Za-z]+)\s+(\S{6})\S+/$1 $2…/;
943 # $hcopy->authorization( $auth );
944 # }
945 # my $h = $hcopy->as_string;
946 # my $cl = $req->content_length // 0;
947 # my $preview = $req->start_line . "\n" . $h . "\n<" . $cl . " bytes body omitted>";
948 # }
949  
950 my $p = {};
951 # my $timeout = time() + $self->timeout;
952 my $timeout = $self->timeout;
953 my $uri = $req->uri;
954 if( !$uri->scheme )
955 {
956 $uri->scheme( 'http' );
957 }
958 elsif( $uri->scheme ne 'http' && $uri->scheme ne 'https' )
959 {
960 return( $self->error( "Unsupported scheme: ", $uri->scheme ) );
961 }
962 my $default_port = $uri->scheme eq 'http'
963 ? 80
964 : 443;
965 if( !$uri->can( 'port' ) || !defined( $uri->port ) || !length( $uri->port ) )
966 {
967 $p->{port} = $default_port;
968 }
969 else
970 {
971 $p->{port} = $uri->port;
972 }
973 $uri->path( '/' ) if( !length( $uri->path ) );
974  
975 $p->{host} = $uri->host ||
976 return( $self->error( "No host set for request uri \"$uri\"." ) );
977
978 if( my $local_host = $self->local_host )
979 {
980 $p->{local_host} = $local_host;
981 }
982 if( my $local_port = $self->local_port )
983 {
984 $p->{local_port} = $local_port;
985 }
986  
987 my $proxy = $self->proxy;
988 my $no_proxy = $self->no_proxy;
989 if( $proxy && $no_proxy )
990 {
991 if( $self->_match_no_proxy( $no_proxy, $p->{host} ) )
992 {
993 undef( $proxy );
994 }
995 }
996  
997 local $SIG{PIPE} = 'IGNORE';
998 my $io;
999 my $sock = $self->_pool->steal( @$p{qw( host port )} );
1000 if( defined( $sock ) && Scalar::Util::openhandle( $sock ) )
1001 {
1002 $io = HTTP::Promise::IO->new( $sock, stop_if => $self->stop_if ) ||
1003 return( $self->pass_error( HTTP::Promise::IO->error ) );
1004 if( !$io->make_select( write => 0, timeout => 0 ) )
1005 {
1006 close( $sock );
1007 undef( $sock );
1008 }
1009 else
1010 {
1011 $p->{in_keepalive} = 1;
1012 }
1013 }
1014 if( !$p->{in_keepalive} )
1015 {
1016 if( $proxy )
1017 {
1018 # my( undef, $proxy_user, $proxy_pass, $proxy_host, $proxy_port, undef) = $self->_parse_url($proxy);
1019 return( $self->error( "Proxy set '$proxy' (", overload::StrVal( $proxy ), ") is not URI object." ) ) if( !$self->_is_a( $proxy => 'URI' ) );
1020 my $proxy_auth = $proxy->userinfo;
1021 my( $proxy_user, $proxy_pass ) = split( /:/, $proxy_auth, 2 );
1022 my $proxy_authorization;
1023 if( defined( $proxy_user ) && length( $proxy_user ) )
1024 {
1025 $self->_load_class( 'URI::Escape::XS' ) || return( $self->pass_error );
1026 $p->{proxy_user} = URI::Escape::XS::uri_unescape( $proxy_user );
1027 $p->{proxy_pass} = URI::Escape::XS::uri_unescape( $proxy_pass );
1028 $self->_load_class( 'Crypt::Misc' ) || return( $self->pass_error );
1029 $proxy_authorization = 'Basic ' . Crypt::Misc::encode_b64( join( ':', @$p{qw( proxy_user proxy_pass )} ), '' );
1030 }
1031 local $HTTP::Promise::IO::DEBUG = $self->debug; # REMOVE ME
1032 if( $uri->scheme eq 'http' )
1033 {
1034 $io = HTTP::Promise::IO->connect(
1035 host => $proxy->host,
1036 port => $proxy->port,
1037 stop_if => $self->stop_if,
1038 timeout => $timeout,
1039 debug => $self->debug,
1040 ( defined( $p->{local_host} ) ? ( local_host => $p->{local_host} ) : () ),
1041 ( defined( $p->{local_port} ) ? ( local_port => $p->{local_port} ) : () ),
1042 ) || return( $self->pass_error( HTTP::Promise::IO->error ) );
1043 if( defined( $proxy_authorization ) )
1044 {
1045 $self->proxy_authorization( $proxy_authorization );
1046 }
1047 }
1048 else
1049 {
1050 $io = HTTP::Promise::IO->connect_ssl_over_proxy(
1051 proxy_host => $proxy->host,
1052 proxy_port => $proxy->port,
1053 host => $p->{host},
1054 port => $p->{port},
1055 stop_if => $self->stop_if,
1056 timeout => $timeout,
1057 proxy_authorization => $proxy_authorization,
1058 debug => $self->debug,
1059 ( defined( $p->{local_host} ) ? ( local_host => $p->{local_host} ) : () ),
1060 ( defined( $p->{local_port} ) ? ( local_port => $p->{local_port} ) : () ),
1061 ) || return( $self->pass_error( HTTP::Promise::IO->error ) );
1062 }
1063 }
1064 else
1065 {
1066 local $HTTP::Promise::IO::DEBUG = $self->debug; # REMOVE ME
1067 if( $uri->scheme eq 'http' )
1068 {
1069 $io = HTTP::Promise::IO->connect(
1070 host => $uri->host,
1071 port => $uri->port,
1072 stop_if => $self->stop_if,
1073 timeout => $timeout,
1074 debug => $self->debug,
1075 ( defined( $p->{local_host} ) ? ( local_host => $p->{local_host} ) : () ),
1076 ( defined( $p->{local_port} ) ? ( local_port => $p->{local_port} ) : () ),
1077 ) || return( $self->pass_error( HTTP::Promise::IO->error ) );
1078 }
1079 else
1080 {
1081 my $ssl_opts = $self->ssl_opts;
1082 $io = HTTP::Promise::IO->connect_ssl(
1083 host => $uri->host,
1084 port => $uri->port,
1085 stop_if => $self->stop_if,
1086 timeout => $timeout,
1087 debug => $self->debug,
1088 ( defined( $p->{local_host} ) ? ( local_host => $p->{local_host} ) : () ),
1089 ( defined( $p->{local_port} ) ? ( local_port => $p->{local_port} ) : () ),
1090 ( ( defined( $ssl_opts ) && scalar( keys( %$ssl_opts ) ) ) ? ( ssl_opts => $ssl_opts ) : () ),
1091 ) || return( $self->pass_error( HTTP::Promise::IO->error ) );
1092 }
1093 }
1094 # return( $self->pass_error ) unless( $io );
1095 }
1096  
1097 my $total_bytes_sent = 0;
1098 my $total_bytes_read = 0;
1099  
1100 my $send_body = sub
1101 {
1102 my $entity = shift( @_ );
1103 my $body = $entity->body;
1104 my $body_len = $body->length;
1105 my $ct_len = $req->headers->content_length;
1106 if( $body_len != $ct_len )
1107 {
1108 warn( "Content-Length set (${ct_len}) does not match the actual body size (${body_len})\n" ) if( warnings::enabled() );
1109 }
1110
1111 my $sock = $io->filehandle;
1112 my $bytes_sent = 0;
1113 $entity->print_body( $io ) || return( $self->pass_error( $entity->error ) );
1114 # NOTE: Hmmmm, really not great, but otherwise I would need to change a lot of code
1115 $bytes_sent = $body->length;
1116 return( $bytes_sent );
1117 };
1118  
1119 # write request
1120 my $method = $req->method;
1121 my $connection_header = $self->connection_header;
1122 # If no connection_header value was provided, let's guess it based on the protocol used
1123 unless( $connection_header )
1124 {
1125 if( uc( $method ) eq 'HEAD' )
1126 {
1127 $connection_header = 'close';
1128 }
1129 elsif( $req->version && $req->version > 1.0 )
1130 {
1131 $connection_header = 'keep-alive';
1132 }
1133 else
1134 {
1135 $connection_header = 'close';
1136 }
1137 }
1138
1139 my $cookie_jar = $self->cookie_jar;
1140 {
1141 my $headers = $req->headers;
1142 # Add headers that were provided as parameters
1143 my $in_headers = $opts->{headers};
1144 if( $self->_is_array( $in_headers ) )
1145 {
1146 for( my $i = 0; $i < @$in_headers; $i += 2 )
1147 {
1148 my $name = $in_headers->[$i];
1149 if( lc( $name ) eq 'connection' )
1150 {
1151 $connection_header = $in_headers->[$i + 1];
1152 }
1153 else
1154 {
1155 $headers->push_header( $name => $in_headers->[$i + 1] );
1156 }
1157 }
1158 }
1159 $headers->header( Connection => $connection_header );
1160
1161 if( my $pa = $self->proxy_authorization )
1162 {
1163 $headers->header( 'Proxy-Authorization' => $pa );
1164 }
1165 my $userinfo = $uri->userinfo;
1166 if( defined( $userinfo ) && length( $userinfo ) )
1167 {
1168 my( $username, $password ) = split( /:/, $userinfo, 2 );
1169 $self->_load_class( 'URI::Escape' ) || return( $self->pass_error );
1170 my $unescape_username = URI::Escape::uri_unescape( $username );
1171 my $unescape_password = URI::Escape::uri_unescape( $password );
1172 $self->_load_class( 'Crypt::Misc' ) || return( $self->pass_error );
1173 my $authorization = 'Basic ' . Crypt::Misc::encode_b64( "${unescape_username}:${unescape_password}" );
1174 $headers->header( Authorization => 'Basic ' . $authorization );
1175 $uri->userinfo( undef );
1176 }
1177  
1178 # set Cookie header
1179 if( defined( $cookie_jar ) )
1180 {
1181 if( $self->_can( $cookie_jar => 'add_request_header' ) )
1182 {
1183 $cookie_jar->add_request_header( $req ) ||
1184 return( $self->pass_error( $cookie_jar->error ) );
1185 }
1186 else
1187 {
1188 warn( "Cookie Jar object ", $self->_str_val( $cookie_jar ), " does not support the method 'add_request_header'." );
1189 }
1190 }
1191  
1192 my $body = $req->entity->body;
1193 if( defined( $body ) && $body )
1194 {
1195 if( $body->isa( 'HTTP::Promise::Body::Form' ) &&
1196 ( !$headers->exists( 'Content-Type' ) || $headers->content_type->is_empty ) )
1197 {
1198 $headers->header( 'Content-Type' => 'application/x-www-form-urlencoded' );
1199 }
1200 if( !$headers->exists( 'Content-Length' ) )
1201 {
1202 my $content_length = $body->length;
1203 $headers->header( 'Content-Length' => "$content_length" );
1204 }
1205 }
1206  
1207 # finally, set Host header
1208 unless( $headers->host )
1209 {
1210 my $request_target = ( $uri->port == $default_port ) ? $uri->host : $uri->host_port;
1211 $headers->header( Host => $request_target );
1212 }
1213
1214 my $expect_threshold = $opts->{expect_threshold} // $self->expect_threshold;
1215 if( defined( $expect_threshold ) )
1216 {
1217 if( $self->_is_integer( $expect_threshold ) )
1218 {
1219 $expect_threshold += 0;
1220 }
1221 else
1222 {
1223 undef( $expect_threshold );
1224 }
1225 }
1226
1227 if( $req->version &&
1228 $req->version > 1.0 &&
1229 defined( $expect_threshold ) &&
1230 $expect_threshold > 0 &&
1231 defined( $body ) &&
1232 $body->length > $expect_threshold )
1233 {
1234 $headers->expect( '100-Continue' );
1235 }
1236
1237 my $request = $req->start_line . $CRLF . $req->headers->as_string;
1238 $request .= $CRLF;
1239 my $bytes = $io->write_all( $request, $timeout );
1240 if( !defined( $bytes ) )
1241 {
1242 return( $self->pass_error( $io->error ) );
1243 }
1244 # Could not transmit the headers
1245 elsif( !$bytes )
1246 {
1247 return( $self->error({ code => 500, message => "Zero byte could actually be sent to the socket '", $io->filehandle, "'." }) );
1248 }
1249 $total_bytes_sent = $bytes;
1250  
1251 # If this is not an Expect query, we send the body now
1252 # otherwise if this is an Expect type of query, we would read the response header
1253 # and send the body
1254 if( !$headers->expect && defined( $body ) && $body )
1255 {
1256 my $bytes = $send_body->( $req->entity );
1257 return( $self->pass_error ) if( !defined( $bytes ) );
1258 $total_bytes_sent += $bytes;
1259 }
1260 }
1261
1262 # read response
1263 my $buff = '';
1264 my $parser = HTTP::Promise::Parser->new;
1265 my $bufsize = $self->buffer_size;
1266 $io->max_read_buffer( $bufsize );
1267 $io->debug( $self->debug );
1268
1269 # Maximum headers size is not oficial, but we definitely need to set some limit.
1270 # <https://security.stackexchange.com/questions/110565/large-over-sizesd-http-header-lengths-and-security-implications>
1271 my $max = $self->max_headers_size;
1272 my( $n, $def, $headers );
1273 $n = -1;
1274 LOOP: while(1)
1275 {
1276 $n = $io->read( $buff, 2048, length( $buff ) );
1277 if( !defined( $n ) || $n == 0 )
1278 {
1279 my $code = defined( $n ) ? '' : $io->error->code;
1280 if( $p->{in_keepalive} &&
1281 ( length( $buff ) // 0 ) == 0 &&
1282 !$opts->{total_attempts} &&
1283 ( defined( $n ) || $code == ECONNRESET || ( $IS_WIN32 && $code == ECONNABORTED ) ) )
1284 {
1285 # the server closed the connection (maybe because of keep-alive timeout)
1286 $opts->{total_attempts}++;
1287 return( $self->send( $req, %$opts ) );
1288 }
1289 elsif( !length( $buff ) )
1290 {
1291 return( $self->error({ code => HTTP_BAD_REQUEST, message => "Unexpected EOF while reading response from socket '", $io->filehandle, "'." }) );
1292 }
1293 elsif( !defined( $n ) )
1294 {
1295 return( $self->pass_error( $io->error ) );
1296 }
1297 else
1298 {
1299 return( $self->error({ code => HTTP_BAD_REQUEST, message => "No headers data could be retrieved in the first " . length( $buff ) . " bytes of data read." }) );
1300 }
1301 }
1302
1303 $def = $parser->parse_response_headers( \$buff );
1304 if( !defined( $def ) )
1305 {
1306 # Is it an error 425 Too Early, it means we need more data.
1307 if( $parser->error->code == HTTP_TOO_EARLY )
1308 {
1309 next LOOP;
1310 }
1311 # 400 Bad request
1312 elsif( $parser->error->code == HTTP_BAD_REQUEST && length( $buff ) > $max )
1313 {
1314 return( $self->error({ code => HTTP_BAD_REQUEST, message => "Unable to find the response headers, within the first ${max} bytes of data. Do you need to increase the value for max_headers_size() ?" }) );
1315 }
1316 # For other errors, we stop and pass the error received
1317 return( $self->pass_error );
1318 }
1319 else
1320 {
1321 $headers = $def->{headers} ||
1322 return( $self->error( "No headers object set by \$parser->parse_headers_xs() !" ) );
1323 return( $self->error( "\$parser->parse_headers_xs() did not return the headers length as an integer ($def->{length})" ) ) if( !$self->_is_integer( $def->{length} ) );
1324 return( $self->error( "Headers length returned by \$parser->parse_headers_xs() ($def->{length}) is higher than our buffer size (", length( $buff ), ") !" ) ) if( $def->{length} > length( $buff ) );
1325 # succeeded
1326 substr( $buff, 0, $def->{length}, '' );
1327 $total_bytes_read += $def->{length};
1328 $io->unread( $buff ) if( length( $buff ) );
1329 # We need to consume the blank line separating the headers and the body, so it does
1330 # not become part of the body, and because it does not belong anywhere
1331 my $trash = $io->read_until_in_memory( qr/${CRLF}/, include => 1 );
1332 return( $self->pass_error( $io->error ) ) if( !defined( $trash ) );
1333 if( $req->headers->exists( 'Expect' ) )
1334 {
1335 # If we initially sent an Expect request, i.e. without a body, we just got
1336 # The green light to proceed, so we remove the Expect: 100-Continue header and re-submit.
1337 # If we did not have that request header, we just read on as this is the final, albeit weird, response
1338 if( $def->{code} == HTTP_CONTINUE )
1339 {
1340 # Read on to get the actual server response headers
1341 my $bytes = $send_body->( $req->entity );
1342 return( $self->pass_error ) if( !defined( $bytes ) );
1343 $total_bytes_sent += $bytes;
1344 # moving on to read the full response headers
1345 # Something like this:
1346 # HTTP/1.1 100 Continue
1347 #
1348 # HTTP/1.1 200 OK
1349 # Content-Type: text/plain
1350 # Content-Length: 15
1351 # Host: example.com
1352 # User-Agent: hoge
1353 #
1354 next LOOP;
1355 }
1356 # If this is a HTTP/1.0 protocol (but not limited to), this just means the server did not support
1357 # the Expect: 100-Continue header, so we just remove it and re-submit.
1358 elsif( $def->{code} == HTTP_EXPECTATION_FAILED )
1359 {
1360 $req->headers->remove( 'Expect' );
1361 # Disable the Expect feature
1362 $opts->{expect_threshold} = 0;
1363 return( $self->send( $req, $opts ) );
1364 }
1365 }
1366 last LOOP;
1367 }
1368 }
1369  
1370 my $ent = HTTP::Promise::Entity->new(
1371 headers => $headers,
1372 ext_vary => $self->ext_vary,
1373 debug => $self->debug,
1374 ( ( $headers->exists( 'Content-Encoding' ) && !$headers->content_encoding->is_empty ) ? ( is_encoded => 1 ) : () ),
1375 );
1376 $self->_load_class( 'HTTP::Promise::Response' ) || return( $self->pass_error );
1377 my $resp = HTTP::Promise::Response->new( @$def{qw( code status headers )}, {
1378 protocol => $def->{protocol},
1379 version => $def->{version},
1380 uri => $uri,
1381 debug => $self->debug,
1382 } ) || return( $self->pass_error( HTTP::Promise::Response->error ) );
1383 # Mutual assignment for convenience
1384 $resp->entity( $ent );
1385 $ent->http_message( $resp );
1386 $resp->request( $req );
1387 my $body;
1388
1389 my $max_redirect = 0;
1390 my $do_redirect = undef;
1391 if( $headers->exists( 'Location' ) )
1392 {
1393 $max_redirect = ( defined( $opts->{max_redirect} ) && $opts->{max_redirect} =~ /^\d+$/ )
1394 ? $opts->{max_redirect}
1395 : $self->max_redirect;
1396 $max_redirect //= 0;
1397 # Perform redirect for:
1398 # Moved Permanently (301),
1399 # Moved Temporarily (302)
1400 # See Other (303)
1401 # Temporary Redirect (307)
1402 # Permanent Redirect (308)
1403 $do_redirect = ( $max_redirect && $def->{code} =~ /^30[12378]$/ );
1404 }
1405  
1406 my $chunked = ( ( $headers->transfer_encoding // '' ) eq 'chunked' );
1407 my $content_length = $headers->content_length;
1408 if( defined( $content_length ) &&
1409 length( $content_length ) &&
1410 $content_length !~ /^\d+$/ )
1411 {
1412 # return( $self->error({ code => 500, message => "Bad Content-Length: ${content_length}" }) );
1413 warn( "Bad Content-Length '${content_length}' in server response.\n" ) if( $self->_warnings_is_enabled );
1414 undef( $content_length );
1415 }
1416  
1417 unless( $req->method eq 'HEAD'
1418 || ( $def->{code} >= 100 && $def->{code} < 200 )
1419 || $def->{code} == 204
1420 || $def->{code} == 302
1421 || $def->{code} == 304 )
1422 {
1423 if( $chunked )
1424 {
1425 $body = $self->_read_body_chunked(
1426 reader => $io,
1427 headers => $headers,
1428 entity => $ent,
1429 );
1430 }
1431 else
1432 {
1433 $body = $self->_read_body(
1434 reader => $io,
1435 headers => $headers,
1436 entity => $ent,
1437 );
1438 }
1439 return( $self->pass_error ) if( !defined( $body ) );
1440 $total_bytes_read += $body->length;
1441 $ent->body( $body );
1442 }
1443  
1444 # manage connection cache (i.e. keep-alive)
1445 if( defined( $connection_header ) &&
1446 lc( $connection_header ) eq 'keep-alive' )
1447 {
1448 my $connection = $headers->connection->lc // '';
1449 if( ( $def->{version} > 1.0
1450 ? $connection ne 'close' # HTTP/1.1 can keep alive by default
1451 : $connection eq 'keep-alive' # HTTP/1.0 needs explicit keep-alive
1452 ) && ( defined( $content_length ) or $chunked ) )
1453 {
1454 my $sock = $io->filehandle;
1455 $self->_pool->push( $uri->host, $uri->port, $sock ) ||
1456 return( $self->pass_error );
1457 }
1458 }
1459 # explicitly close here, just after returning the socket to the pool,
1460 # since it might be reused in the upcoming recursive call
1461 # undef( $sock );
1462 $io->close;
1463  
1464 # Process 'Set-Cookie' header before redirect, because Cookies may have been set upon redirection.
1465 if( defined( $cookie_jar ) )
1466 {
1467 if( $self->_can( $cookie_jar => 'extract_cookies' ) )
1468 {
1469 $cookie_jar->extract_cookies( $resp ) ||
1470 return( $self->pass_error( $cookie_jar->error ) );
1471 }
1472 else
1473 {
1474 warn( "Cookie Jar object ", $self->_str_val( $cookie_jar ), " does not support the method 'extract_cookies'." );
1475 }
1476 }
1477
1478 if( $do_redirect )
1479 {
1480 my $location = $headers->location;
1481 unless( $location =~ m{^[a-zA-Z][a-zA-Z0-9]+://} )
1482 {
1483 # RFC 2616 14.30 says Location header is absolute URI.
1484 # But, a lot of servers return relative URI.
1485 $location = URI->new_abs( $location => $uri );
1486 }
1487 # Note: RFC 1945 and RFC 2068 specify that the client is not allowed
1488 # to change the method on the redirected request. However, most
1489 # existing user agent implementations treat 302 as if it were a 303
1490 # response, performing a GET on the Location field-value regardless
1491 # of the original request method. The status codes 303 and 307 have
1492 # been added for servers that wish to make unambiguously clear which
1493 # kind of reaction is expected of the client. Also, 308 was introduced
1494 # to avoid the ambiguity of 301.
1495 # TODO: Create new object and add the old one as previous() to the new request.
1496 my $clone = $req->clone || return( $self->pass_error( $req->error ) );
1497 unless( $def->{code} =~ /^30[178]$/ )
1498 {
1499 $clone->method( 'GET' );
1500 }
1501 $clone->uri( $location );
1502 $max_redirect-- if( $max_redirect > 0 );
1503 $opts->{max_redirect} = $max_redirect;
1504 return( $self->send( $clone, $opts ) );
1505 my $resp2 = $self->send( $clone, $opts ) ||
1506 return( $self->pass_error );
1507 $resp2->previous( $resp );
1508 return( $resp2 );
1509 }
1510  
1511 my $type = $ent->mime_type;
1512 # I we have a body at and it is a multipart, we parse it otherwise, we already have it stored
1513 if( $ent->body && $type =~ m,^multipart/,i )
1514 {
1515 # Now parse the raw data saved earlier
1516 my $fh = $ent->body->open( '+<', { binmode => 'raw' } ) ||
1517 return( $self->pass_error( $ent->body->error ) );
1518 my $reader = HTTP::Promise::IO->new( $fh, max_read_buffer => $bufsize, debug => $self->debug ) ||
1519 return( $self->pass_error( HTTP::Promise::IO->error ) );
1520 my $ent2 = HTTP::Promise::Entity->new( headers => $headers, http_message => $resp, debug => $self->debug ) ||
1521 return( $self->pass_error( HTTP::Promise::Entity->error ) );
1522 $resp->entity( $ent2 );
1523
1524 # Request body can be one of 3 types:
1525 # application/x-www-form-urlencoded
1526 # multipart/form-data
1527 # text/plain or other mime types
1528 # <https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST>
1529 my $part_ent = $parser->parse_multi_part( entity => $ent2, reader => $reader ) ||
1530 return( $parser->pass_error );
1531 }
1532
1533 return( $resp );
1534 }
1535  
1536 # NOTE: request parameter
1537 sub send_te { return( shift->_set_get_boolean( 'send_te', @_ ) ); }
1538  
1539 # NOTE: serialiser method for Promise::Me
1540 sub serialiser { return( shift->_set_get_scalar( 'serialiser', @_ ) ); }
1541  
1542 # NOTE: shared_mem_size method for Promise::Me
1543 sub shared_mem_size { return( shift->_set_get_scalar( 'shared_mem_size', @_ ) ); }
1544  
1545 sub simple_request
1546 {
1547 my $self = shift( @_ );
1548 my $req = shift( @_ );
1549 my $opts = $self->_get_args_as_hash( @_ );
1550 $opts->{read_size} //= 0;
1551 if( $self->use_promise )
1552 {
1553 return( Promise::Me->new(sub
1554 {
1555 my( $resolve, $reject ) = @$_;
1556 return( $reject->( HTTP::Promise::Exception->new({
1557 code => 500,
1558 message => "No request object was provided."
1559 }) ) ) if( !$req );
1560 $self->use_content_file( $opts->{use_content_file} ) if( exists( $opts->{use_content_file} ) );
1561 $opts->{max_redirect} = 0;
1562 my $resp = $self->send( $req, $opts ) || return( $reject->( $self->pass_error ) );
1563 return( $resolve->( $resp ) );
1564 }) );
1565 }
1566 else
1567 {
1568 return( $self->error( "No request object was provided." ) ) if( !$req );
1569 $self->use_content_file( $opts->{use_content_file} ) if( exists( $opts->{use_content_file} ) );
1570 $opts->{max_redirect} = 0;
1571 my $resp = $self->send( $req, $opts ) || return( $self->pass_error );
1572 return( $resp );
1573 }
1574 }
1575  
1576 sub ssl_opts { return( shift->_set_get_hash_as_mix_object( 'ssl_opts', @_ ) ); }
1577  
1578 sub stop_if { return( shift->_set_get_code( 'stop_if', @_ ) ); }
1579  
1580 sub threshold { return( shift->_set_get_scalar( 'threshold', @_ ) ); }
1581  
1582 # NOTE: request parameter
1583 sub timeout { return( shift->_set_get_number( 'timeout', @_ ) ); }
1584  
1585 # NOTE: upgrade_insecure_requestsis an alias for auto_switch_https
1586 sub upgrade_insecure_requests { return( shift->_set_get_boolean( 'auto_switch_https', @_ ) ); }
1587  
1588 sub uri_escape { return( URI::Escape::XS::uri_escape( $_[1] ) ); }
1589  
1590 sub uri_unescape { return( URI::Escape::XS::uri_unescape( $_[1] ) ); }
1591  
1592 sub use_content_file { return( shift->_set_get_boolean( 'use_content_file', @_ ) ); }
1593  
1594 sub use_promise { return( shift->_set_get_boolean( 'use_promise', @_ ) ); }
1595  
1596 sub _datetime
1597 {
1598 my $self = shift( @_ );
1599 my $dt;
1600 if( @_ )
1601 {
1602 return( $self->error( "Object provided (", ref( $_[0] ), ") is not a DateTime or Module::Generic::DateTime object." ) ) if( !$self->_is_a( $_[0] => [qw( DateTime Module::Generic::DateTime )] ) );
1603 $dt = shift( @_ );
1604 }
1605
1606 if( !defined( $dt ) )
1607 {
1608 $dt = DateTime->now;
1609 }
1610 # We need to get the underlying DateTime object if it is wrapped inside Module::Generic::DateTime
1611 elsif( $dt->isa( 'Module::Generic::DateTime' ) )
1612 {
1613 $dt = $dt->datetime;
1614 }
1615
1616 $dt->set_time_zone( 'GMT' );
1617 my $fmt = DateTime::Format::Strptime->new(
1618 pattern => '%a, %d %b %Y %H:%M:%S GMT',
1619 locale => 'en_GB',
1620 time_zone => 'GMT',
1621 );
1622 $dt->set_formatter( $fmt );
1623 return( $dt );
1624 }
1625  
1626 # my $res = $prom->_make_request_data( $form_object );
1627 # my $res = $prom->_make_request_data( $form_data_object );
1628 # my $res = $prom->_make_request_data( 'post' => $url, \%form );
1629 # my $res = $prom->_make_request_data( 'post' => $url, \%form );
1630 # my $res = $prom->_make_request_data( 'post' => $url, \@form );
1631 # my $res = $prom->_make_request_data( 'post' => $url, \%form, $field_name => $value, ... );
1632 # my $res = $prom->_make_request_data( 'post' => $url, $field_name => $value, Content => \%form, Query => $escaped_string );
1633 # my $res = $prom->_make_request_data( 'post' => $url, $field_name => $value, Content => \@form, Query => $escaped_string );
1634 # my $res = $prom->_make_request_data( 'post' => $url, $field_name => $value, Content => $content, Query => $escaped_string );
1635 sub _make_request_data
1636 {
1637 my $self = shift( @_ );
1638 my $meth = shift( @_ ) || return( $self->error( 'No http method was provided.' ) );
1639 my $uri = shift( @_ ) || return( $self->error( 'No uri was provided.' ) );
1640 my $req = HTTP::Promise::Request->new( $meth => $uri, { debug => $self->debug } ) ||
1641 return( $self->pass_error( HTTP::Promise::Request->error ) );
1642 $self->prepare_headers( $req );
1643 my @args = @_; # REMOVE ME
1644 $self->message( 4, "Received arguments -> ", sub{ $self->dump( \@args ) } );
1645 # To set up a possible escaped query string for this POST/PUT request
1646 my $u = $req->uri ||
1647 return( $self->error( "No URL was provided for this HTTP query." ) );
1648 my $ent = $req->entity;
1649 my $content;
1650 if( scalar( @_ ) == 1 &&
1651 defined( $_[0] ) &&
1652 ref( $_[0] ) eq 'HASH' &&
1653 CORE::exists( $_[0]->{Content} ) )
1654 {
1655 warn( "It seems you are passing an hash reference of parameters, but this should be avoided as it may be confused with an hash reference of form parameters." ) if( $self->_is_warnings_enabled );
1656 }
1657  
1658 # Maybe content is provided as the first argument?
1659 if( scalar( @_ ) && defined( $_[0] ) &&
1660 (
1661 $self->_is_array( $_[0] ) ||
1662 ( ref( $_[0] ) eq 'HASH' && !scalar( grep( /^Content$/i, @_ ) ) ) ||
1663 $self->_is_a( $_[0] => 'HTTP::Promise::Body::Form' ) ||
1664 $self->_is_a( $_[0] => 'HTTP::Promise::Body::Form::Data' )
1665 ) )
1666 {
1667 $content = shift( @_ );
1668 }
1669 # Maybe content is provided as the last argument?
1670 elsif( scalar( @_ ) &&
1671 ( @_ % 2 ) &&
1672 defined( $_[-1] ) &&
1673 (
1674 $self->_is_array( $_[-1] ) ||
1675 ( ref( $_[-1] ) eq 'HASH' && !scalar( grep( /^Content$/i, @_ ) ) ) ||
1676 $self->_is_a( $_[-1] => 'HTTP::Promise::Body::Form' ) ||
1677 $self->_is_a( $_[-1] => 'HTTP::Promise::Body::Form::Data' )
1678 ) )
1679 {
1680 $content = pop( @_ );
1681 }
1682
1683 my( $k, $v );
1684 while( ( $k, $v ) = splice( @_, 0, 2 ) )
1685 {
1686 if( lc( $k ) eq 'content' )
1687 {
1688 $content = $v;
1689 }
1690 # Handle possible escaped query string for this POST/PUT request
1691 elsif( lc( $k ) eq 'query' )
1692 {
1693 if( ref( $v ) eq 'HASH' || $self->_is_array( $v ) )
1694 {
1695 # try-catch
1696 local $@;
1697 eval
1698 {
1699 $u->query_form( $v );
1700 };
1701 if( $@ )
1702 {
1703 return( $self->error( "Error while setting query form key-value pairs: $@" ) );
1704 }
1705 }
1706 elsif( !ref( $v ) || ( ref( $v ) && overload::Method( $v => '""' ) ) )
1707 {
1708 $u->query( "$v" );
1709 }
1710 }
1711 else
1712 {
1713 # $req->headers->push_header( $k, $v );
1714 $req->headers->replace( $k, $v );
1715 }
1716 }
1717 my $orig_ct = $req->headers->header( 'Content-Type' );
1718 my $ct = $orig_ct;
1719 my( $obj, $type );
1720 # By default
1721 if( !$ct && defined( $content ) )
1722 {
1723 $ct = 'application/x-www-form-urlencoded';
1724 }
1725 # If the user used the short version of multipart/form-data, we update the Content-Type accordingly.
1726 elsif( $ct && $ct eq 'form-data' )
1727 {
1728 $ct = 'multipart/form-data';
1729 $req->headers->header( 'Content-Type' => $ct );
1730 }
1731  
1732 if( defined( $ct ) && length( "$ct" ) )
1733 {
1734 $obj = $req->headers->new_field( 'Content-Type' => "$ct" );
1735 return( $self->pass_error( $req->headers->error ) ) if( !defined( $obj ) );
1736 $type = $obj->type;
1737 }
1738  
1739 # $content can be an array reference, hash reference, an HTTP::Promise::Body::Form object, or an HTTP::Promise::Body::Form::Data object
1740 if( ref( $content ) )
1741 {
1742 # if( $ct =~ m,^multipart/form-data[[:blank:]\h]*(;|$),i )
1743 if( lc( substr( "$type", 0, 19 ) ) eq 'multipart/form-data' )
1744 {
1745 unless( $obj->boundary )
1746 {
1747 $obj->boundary( $req->make_boundary );
1748 }
1749 # HTTP::Promise::Body::Form::Data inherits from HTTP::Promise::Body::Form, so we do it first
1750 if( $self->_is_a( $content => 'HTTP::Promise::Body::Form::Data' ) )
1751 {
1752 $content->debug( $self->debug ); # REMOVE ME
1753 $content->boundary( $obj->boundary );
1754 my $parts = $content->make_parts ||
1755 return( $self->pass_error( $content->error ) );
1756 $ent->parts( $parts );
1757 $ent->body( $content );
1758 }
1759 if( $self->_is_a( $content => 'HTTP::Promise::Body::Form' ) )
1760 {
1761 my $form = $content->as_form_data ||
1762 return( $self->pass_error( $content->error ) );
1763 $form->debug( $self->debug ); # REMOVE ME
1764 $form->boundary( $obj->boundary );
1765 my $parts = $form->make_parts ||
1766 return( $self->pass_error( $form->error ) );
1767 $ent->parts( $parts );
1768 $ent->body( $form );
1769 }
1770 elsif( $self->_is_array( $content ) )
1771 {
1772 # Keep track of the order of the fields
1773 my $fields = [];
1774 for( my $i = 0; $i < scalar( @$content ); $i += 2 )
1775 {
1776 push( @$fields, $content->[$i] );
1777 }
1778 $self->_load_class( 'HTTP::Promise::Body::Form::Data' ) ||
1779 return( $self->pass_error );
1780 my $form = HTTP::Promise::Body::Form::Data->new( @$content ) ||
1781 return( $self->pass_error( HTTP::Promise::Body::Form::Data->error ) );
1782 $form->debug( $self->debug ); # REMOVE ME
1783 $form->boundary( $obj->boundary );
1784 my $parts = $form->make_parts( fields => $fields ) ||
1785 return( $self->pass_error( $form->error ) );
1786 $ent->parts( $parts );
1787 $ent->body( $form );
1788 }
1789 elsif( ref( $content ) eq 'HASH' )
1790 {
1791 $self->_load_class( 'HTTP::Promise::Body::Form::Data' ) ||
1792 return( $self->pass_error );
1793 my $form = HTTP::Promise::Body::Form::Data->new( $content ) ||
1794 return( $self->pass_error( HTTP::Promise::Body::Form::Data->error ) );
1795 $form->debug( $self->debug ); # REMOVE ME
1796 $form->boundary( $obj->boundary );
1797 my $parts = $form->make_parts ||
1798 return( $self->pass_error( $form->error ) );
1799 $ent->parts( $parts );
1800 $ent->body( $form );
1801 }
1802 else
1803 {
1804 return( $self->error( "Unsupported content of type '", ref( $content ), "'" ) );
1805 }
1806 }
1807 elsif( lc( $type ) eq TYPE_URL_ENCODED &&
1808 (
1809 Scalar::Util::reftype( $content ) eq 'ARRAY' ||
1810 ref( $content ) eq 'HASH' ||
1811 $self->_is_a( $content => 'HTTP::Promise::Body::Form' )
1812 ) )
1813 {
1814 my $form;
1815 if( $self->_is_a( $content => 'HTTP::Promise::Body::Form' ) )
1816 {
1817 $form = $content;
1818 }
1819 else
1820 {
1821 my $reftype = Scalar::Util::reftype( $content );
1822 $self->_load_class( 'HTTP::Promise::Body::Form' ) ||
1823 return( $self->pass_error );
1824 $form = HTTP::Promise::Body::Form->new( ( $reftype eq 'ARRAY' && !$self->_can_overload( $content => '""' ) ) ? @$content : $content ) ||
1825 return( $self->pass_error( HTTP::Promise::Body::Form->error ) );
1826 }
1827 $ent->body( $form );
1828 }
1829 elsif( $self->_is_a( $content => 'HTTP::Promise::Body' ) )
1830 {
1831 $ent->body( $content );
1832 }
1833 # Module::Generic::File has stringification overloaded, so we put it here first
1834 elsif( $self->_is_a( $content => 'Module::Generic::File' ) )
1835 {
1836 my $body = $ent->new_body( file => $content ) ||
1837 return( $self->pass_error( $ent->error ) );
1838 $ent->body( $body );
1839 }
1840 elsif( overload::Method( $content => '""' ) )
1841 {
1842 my $body = $ent->new_body( string => "$content" ) ||
1843 return( $self->pass_error( $ent->error ) );
1844 $ent->body( $body );
1845 }
1846 else
1847 {
1848 return( $self->error( "Unsupported Content-Type: $ct for data type '", ref( $content ), "'" ) );
1849 }
1850 }
1851 # $content is not a reference and is not empty
1852 elsif( defined( $content ) && length( $content ) )
1853 {
1854 my $charset = lc( $req->headers->charset // '' );
1855 my $ctype = lc( $type // '' );
1856 my( $ctype_major, $ctype_minor ) = split( /\//, $ctype, 2 ) if( $ctype );
1857 if( ( substr( $charset, 0, 4 ) eq 'utf8' ||
1858 substr( $charset, 0, 5 ) eq 'utf-8' ||
1859 ( defined( $ctype_major ) && defined( $ctype_minor ) && $ctype_major eq 'application' && substr( $ctype_minor, -4, 4 ) eq 'json' ) ) &&
1860 utf8::is_utf8( $content ) )
1861 {
1862 warn( "Content data provided has the Perl internal UTF-8 flag set. You need to encode it to UTF-8 bytes before passing it to HTTP::Promise, such as by calling Encode::encode_utf8( \$data ) on it beforehand.\n" ) if( $self->_is_warnings_enabled( 'HTTP::Promise' ) );
1863 }
1864  
1865 my $body = $ent->new_body( string => $content ) ||
1866 return( $self->pass_error( $ent->error ) );
1867 $ent->body( $body );
1868 }
1869  
1870 # Set Content-Type if needed
1871 $req->headers->content_type( "$obj" ) if( defined( $obj ) && !$orig_ct );
1872 if( defined( $content ) && length( $content ) )
1873 {
1874 # Make sure the content is encoded, if applicable, so we can get the proper content length.
1875 if( my $encodings = $req->headers->content_encoding )
1876 {
1877 $ent->encode_body( $encodings ) if( !$ent->is_encoded );
1878 }
1879 # Here we could pass a boundary => $boundary argument to $ent->body->length which would then be passed to the as_string method, but the as_string method in HTTP::Promise::Body::Form::Data will call the method 'boundary' if no boundary value is provided as an option.
1880 # $req->content_length( $ent->body->length );
1881 my $bytes = $ent->body->length ||
1882 return( $self->pass_error( $ent->body->error ) );
1883 $req->content_length( $bytes );
1884 }
1885 # Set the Content-Length to 0 only if there is a Content-Type set
1886 elsif( $ct )
1887 {
1888 $req->header( 'Content-Length' => 0 );
1889 }
1890 return( $req );
1891 }
1892  
1893 sub _make_request_query
1894 {
1895 my $self = shift( @_ );
1896 my $meth = shift( @_ ) || return( $self->error( 'No http method was provided.' ) );
1897 my $uri = shift( @_ ) || return( $self->error( 'No uri was provided.' ) );
1898 my $req = HTTP::Promise::Request->new( $meth => $uri, { debug => $self->debug } ) ||
1899 return( $self->pass_error( HTTP::Promise::Request->error ) );
1900 $self->prepare_headers( $req );
1901 my $u = $req->uri ||
1902 return( $self->error( "No URL was provided for this HTTP query." ) );
1903 my( $k, $v );
1904 while( ( $k, $v ) = ( @_ == 1 && ref( $_[0] ) eq 'HASH' ) ? each( %{$_[0]} ) : splice( @_, 0, 2 ) )
1905 {
1906 if( lc( $k ) eq 'content' || lc( $k ) eq 'query' )
1907 {
1908 if( ref( $v ) eq 'HASH' || $self->_is_array( $v ) )
1909 {
1910 # try-catch
1911 local $@;
1912 eval
1913 {
1914 $u->query_form( $v );
1915 };
1916 if( $@ )
1917 {
1918 return( $self->error( "Error while setting query form key-value pairs: $@" ) );
1919 }
1920 }
1921 elsif( !ref( $v ) || ( ref( $v ) && overload::Method( $v => '""' ) ) )
1922 {
1923 $u->query( "$v" );
1924 }
1925 else
1926 {
1927 warn( "Option \"$k\" was provided, but no content data (", overload::StrVal( $v ), ") is allowed for this type of HTTP query. Ignoring it.\n" ) if( $self->_warnings_is_enabled );
1928 }
1929 }
1930 else
1931 {
1932 # $req->headers->push_header( $k, $v );
1933 $req->headers->replace( $k, $v );
1934 }
1935 }
1936 return( $req );
1937 }
1938  
1939 sub _match_no_proxy
1940 {
1941 my( $self, $no_proxy, $host ) = @_;
1942  
1943 # ref. curl.1.
1944 # list of host names that shouldn't go through any proxy.
1945 # If set to a asterisk '*' only, it matches all hosts.
1946 if( $no_proxy eq '*' )
1947 {
1948 return(1);
1949 }
1950 elsif( $self->_is_array( $no_proxy ) )
1951 {
1952 for my $pat ( @$no_proxy )
1953 {
1954 # suffix match (same behavior as LWP)
1955 if( $host =~ /\Q$pat\E$/ )
1956 {
1957 return(1);
1958 }
1959 }
1960 }
1961 return(0);
1962 }
1963  
1964 sub _pool { return( shift->_set_get_object( '_pool', 'HTTP::Promise::Pool', @_ ) ); }
1965  
1966 # The purpose of this method is to read the entire HTPP message body, whatever that is, i.e. multipart o not
1967 # Parsing and decoding is done after data has been read from the socket, because speed matters.
1968 sub _read_body
1969 {
1970 my $self = shift( @_ );
1971 my $opts = $self->_get_args_as_hash( @_ );
1972 my $timeout = $opts->{timeout} // $self->timeout;
1973 my $headers = $opts->{headers};
1974 return( $self->error( "Headers object provided is not a HTTP::Promise::Headers object." ) ) if( !$self->_is_a( $headers => 'HTTP::Promise::Headers' ) );
1975 my $ent = $opts->{entity};
1976 return( $self->error( "Entity object provided is not a HTTP::Promise::Entity object." ) ) if( !$self->_is_a( $ent => 'HTTP::Promise::Entity' ) );
1977 my $reader = $opts->{reader};
1978 return( $self->error( "Reader object provided is not a HTTP::Promise::IO object." ) ) if( !$self->_is_a( $reader => 'HTTP::Promise::IO' ) );
1979 my $bufsize = $self->buffer_size;
1980  
1981 my $type = $headers->type;
1982 my $max_in_memory = $self->max_body_in_memory_size;
1983 # rfc7231, section 3.1.1.5 says we can assume applicatin/octet-stream if there
1984 # is no Content-Type header
1985 # <https://tools.ietf.org/html/rfc7231#section-3.1.1.5>
1986 my $default_mime = $DEFAULT_MIME_TYPE || 'application/octet-stream';
1987 my $len = $headers->content_length;
1988 my $chunk_size = $self->buffer_size;
1989 my( $body, $file, $mime_type, $mime, $ext );
1990 my $data = '';
1991 my $total_bytes = 0;
1992
1993 my $get_temp_file = sub
1994 {
1995 # Guessing extension
1996 $mime_type = $headers->mime_type( $default_mime );
1997 $self->_load_class( 'HTTP::Promise::MIME' ) || return( $self->pass_error );
1998 $mime = HTTP::Promise::MIME->new;
1999 $ext = $mime->suffix( $type );
2000 return( $self->pass_error( $mime->error ) ) if( !defined( $ext ) );
2001 $ext ||= 'dat';
2002 my $f = $self->new_tempfile( extension => $ext ) ||
2003 return( $self->pass_error );
2004 return( $f );
2005 };
2006
2007 if( defined( $len ) )
2008 {
2009 # Too big, saving it to file; or
2010 # use_content_file is set to true.
2011 if( ( $len > $max_in_memory ) || $self->use_content_file )
2012 {
2013 $file = $get_temp_file->() || return( $self->pass_error );
2014 my $io = $file->open( '+>', { binmode => 'raw', autoflush => 1 } ) ||
2015 return( $self->pass_error( $file->error ) );
2016 my $buff = '';
2017 my $bytes;
2018 $chunk_size = $len if( $chunk_size > $len );
2019 while( $bytes = $reader->read( $buff, $chunk_size ) )
2020 {
2021 my $bytes_out = $io->syswrite( $buff );
2022 return( $self->pass_error( $io->error ) ) if( !defined( $bytes_out ) );
2023 # We do not want to read more than we should
2024 $chunk_size = ( $len - $total_bytes ) if( ( $total_bytes < $len ) && ( ( $total_bytes + $chunk_size ) > $len ) );
2025 $total_bytes += $bytes;
2026 last if( $total_bytes == $len );
2027 }
2028 $io->close;
2029 return( $self->error( "Error reading http body from socket: ", $reader->error ) ) if( !defined( $bytes ) );
2030 }
2031 else
2032 {
2033 my $buff = '';
2034 my $bytes;
2035 $chunk_size = $len if( $chunk_size > $len );
2036 while( $bytes = $reader->read( $buff, $chunk_size ) )
2037 {
2038 $data .= $buff;
2039 # We do not want to read more than we should
2040 $chunk_size = ( $len - $total_bytes ) if( ( $total_bytes < $len ) && ( ( $total_bytes + $chunk_size ) > $len ) );
2041 $total_bytes += $bytes;
2042 last if( $total_bytes == $len );
2043 }
2044 return( $self->error( "Error reading HTTP body from socket: ", $reader->error ) ) if( !defined( $bytes ) );
2045 }
2046 warn( "HTTP::Promise: HTTP body size advertised ($len) does not match the size actually read from socket ($total_bytes)\n" ) if( $total_bytes != $len && $self->_warnings_is_enabled );
2047 }
2048 # No Content-Length defined
2049 else
2050 {
2051 my $buff = '';
2052 my $bytes = -1;
2053 my $io;
2054 while( $bytes )
2055 {
2056 $bytes = $reader->read( $buff, $chunk_size );
2057 return( $self->pass_error( $reader->error ) ) if( !defined( $bytes ) );
2058
2059 if( defined( $io ) )
2060 {
2061 my $bytes_out = $io->syswrite( $buff );
2062 return( $self->pass_error( $io->error ) ) if( !defined( $bytes_out ) );
2063 }
2064 # The cumulative bytes total for this part exceeds the allowed maximum in memory
2065 elsif( ( length( $data ) + length( $buff ) ) > $max_in_memory )
2066 {
2067 $file = $get_temp_file->() || return( $self->pass_error );
2068 $io = $file->open( '+>', { binmode => 'raw', autoflush => 1 } ) ||
2069 return( $self->pass_error( $file->error ) );
2070 my $bytes_out = $io->syswrite( $data );
2071 return( $self->pass_error( $io->error ) ) if( !defined( $bytes_out ) );
2072 $bytes_out = $io->syswrite( $buff );
2073 return( $self->pass_error( $io->error ) ) if( !defined( $bytes_out ) );
2074 $data = '';
2075 }
2076 else
2077 {
2078 $data .= $buff;
2079 }
2080 }
2081 $total_bytes = defined( $file ) ? $file->length : length( $data );
2082 }
2083  
2084 # If we used a file and the extension is 'dat', because we were clueless based on
2085 # the provided Content-Type, or maybe even the Content-Type is absent, we use the
2086 # XS module in HTTP::Promise::MIME to guess the mime-type based on the actual file
2087 # content
2088 if( defined( $file ) )
2089 {
2090 if( $mime_type eq $default_mime )
2091 {
2092 unless( $mime )
2093 {
2094 $self->_load_class( 'HTTP::Promise::MIME' ) || return( $self->pass_error );
2095 $mime = HTTP::Promise::MIME->new;
2096 }
2097
2098 # Guess the mime type from the file magic
2099 my $mtype = $mime->mime_type( $file );
2100 return( $self->pass_error( $mime->error ) ) if( !defined( $mime_type ) );
2101 my( $enc, $enc_ext );
2102 if( $self->ext_vary && ( $enc = $headers->content_encoding ) )
2103 {
2104 $self->_load_class( 'HTTP::Promise::Stream' ) || return( $self->pass_error );
2105 my $enc_exts = HTTP::Promise::Stream->encoding2suffix( $enc ) ||
2106 return( $self->pass_error( HTTP::Promise::Stream->error ) );
2107 $enc_ext = $enc_exts->join( '.' )->scalar if( !$enc_exts->is_empty );
2108 # Mark body as being encoded if necessary
2109 $ent->is_encoded(1);
2110 }
2111 if( $mtype && $mtype ne $default_mime )
2112 {
2113 $mime_type = $mtype;
2114 # Also update the type value in HTTP::Promise::Headers
2115 # It does not affect the actual Content-Type header
2116 $headers->type( $mtype );
2117 my $new_ext = $mime->suffix( $mtype );
2118 return( $self->pass_error( $mime->error ) ) if( !defined( $new_ext ) );
2119 if( $new_ext && $new_ext ne $ext )
2120 {
2121 $new_ext .= ".${enc_ext}" if( defined( $enc_ext ) );
2122 my $new_file = $file->extension( $new_ext ) || return( $self->pass_error( $file->error ) );
2123 my $this_file = $file->move( $new_file ) || return( $self->pass_error( $file->error ) );
2124 $file = $this_file;
2125 }
2126 }
2127 elsif( defined( $enc_ext ) )
2128 {
2129 my $old_ext = $file->extension;
2130 $old_ext .= ".${enc_ext}";
2131 my $new_file = $file->extension( $old_ext ) || return( $self->pass_error( $file->error ) );
2132 my $this_file = $file->move( $new_file ) || return( $self->pass_error( $file->error ) );
2133 $file = $this_file;
2134 }
2135 }
2136 else
2137 {
2138 my( $enc );
2139 if( $self->ext_vary && ( $enc = $headers->content_encoding ) )
2140 {
2141 $self->_load_class( 'HTTP::Promise::Stream' ) || return( $self->pass_error );
2142 my $old_ext = $file->extension;
2143 my $enc_exts = HTTP::Promise::Stream->encoding2suffix( $enc ) ||
2144 return( $self->pass_error( HTTP::Promise::Stream->error ) );
2145 if( !$enc_exts->is_empty )
2146 {
2147 $old_ext .= '.' . $enc_exts->join( '.' )->scalar;
2148 my $new_file = $file->extension( $old_ext ) || return( $self->pass_error( $file->error ) );
2149 my $this_file = $file->move( $new_file ) || return( $self->pass_error( $file->error ) );
2150 $file = $this_file;
2151 }
2152 # Mark body as being encoded if necessary
2153 $ent->is_encoded(1);
2154 }
2155 }
2156
2157 $body = $ent->new_body( file => $file ) ||
2158 return( $self->pass_error( $ent->error ) );
2159 $self->file( $file );
2160 }
2161 # in memory
2162 else
2163 {
2164 # If this is a application/x-www-form-urlencoded type, we save it as such, and
2165 # the HTTP::Promise::Body::Form makes those data accessible as an hash object
2166 if( $type && $type eq TYPE_URL_ENCODED )
2167 {
2168 $body = $ent->new_body( form => $data ) ||
2169 return( $self->pass_error( $ent->error ) );
2170 }
2171 else
2172 {
2173 $body = $ent->new_body( string => $data ) ||
2174 return( $self->pass_error( $ent->error ) );
2175 }
2176 }
2177 return( $body );
2178 }
2179  
2180 sub _read_body_chunked
2181 {
2182 my $self = shift( @_ );
2183 my $opts = $self->_get_args_as_hash( @_ );
2184 my $timeout = $opts->{timeout} // $self->timeout;
2185 my $headers = $opts->{headers};
2186 return( $self->error( "Headers object provided is not a HTTP::Promise::Headers object." ) ) if( !$self->_is_a( $headers => 'HTTP::Promise::Headers' ) );
2187 my $ent = $opts->{entity};
2188 return( $self->error( "Entity object provided is not a HTTP::Promise::Entity object." ) ) if( !$self->_is_a( $ent => 'HTTP::Promise::Entity' ) );
2189 my $reader = $opts->{reader};
2190 return( $self->error( "Reader object provided is not a HTTP::Promise::IO object." ) ) if( !$self->_is_a( $reader => 'HTTP::Promise::IO' ) );
2191 my $bufsize = $self->buffer_size;
2192 # rfc7231, section 3.1.1.5 says we can assume applicatin/octet-stream if there
2193 # is no Content-Type header
2194 # <https://tools.ietf.org/html/rfc7231#section-3.1.1.5>
2195 my $default_mime = $DEFAULT_MIME_TYPE || 'application/octet-stream';
2196 my $len = $headers->content_length;
2197  
2198 # Guessing extension
2199 my $mime_type = $headers->mime_type( $default_mime );
2200 $self->_load_class( 'HTTP::Promise::MIME' ) || return( $self->pass_error );
2201 my $mime = HTTP::Promise::MIME->new;
2202 my $ext = $mime->suffix( $mime_type );
2203 return( $self->pass_error( $mime->error ) ) if( !defined( $ext ) );
2204 $ext ||= 'dat';
2205 my $enc;
2206 if( $self->ext_vary && ( $enc = $headers->content_encoding ) )
2207 {
2208 $self->_load_class( 'HTTP::Promise::Stream' ) || return( $self->pass_error );
2209 my $enc_ext = HTTP::Promise::Stream->encoding2suffix( $enc ) ||
2210 return( $self->pass_error( HTTP::Promise::Stream->error ) );
2211 $ext .= '.' . $enc_ext->join( '.' )->scalar if( !$enc_ext->is_empty );
2212 }
2213 my $tempfile = $self->new_tempfile( extension => $ext ) ||
2214 return( $self->pass_error );
2215 # HTTP::Promise::Body::File inherits from Module::Generic::File, so we pass it some
2216 # appropriate parameters.
2217 my $body = $ent->new_body( 'file', $tempfile ) ||
2218 return( $self->pass_error( $ent->error ) );
2219 my $io = $body->open( '+>', { binmode => 'raw', autoflush => 1 } ) ||
2220 return( $self->pass_error( $body->error ) );
2221 my $buff = '';
2222 my $bytes = -1;
2223 my $te_re = qr{
2224 \A ( # header
2225 ( [0-9a-fA-F]+ ) # next_len (hex number)
2226 (?:;
2227 $HTTP_TOKEN
2228 =
2229 (?: $HTTP_TOKEN | $HTTP_QUOTED_STRING )
2230 )* # optional chunk-extensions
2231 [[:blank:]]* # www.yahoo.com adds spaces here.
2232 # Is this valid?
2233 \015\012 # CR+LF
2234 )
2235 }mxs;
2236
2237 READ_LOOP: while( $bytes )
2238 {
2239 # If we do not find anything within the maximum allocable memory size, this will
2240 # return an error, so we can bank on it
2241 my $hdr = $reader->read_until_in_memory( $te_re, include => 1 );
2242 return( $self->pass_error( $reader->error ) ) if( !defined( $hdr ) );
2243 last if( !length( $hdr ) );
2244
2245 my( $header, $hex_len ) = ( $hdr =~ m/$te_re/ );
2246 # remove header from buffer
2247 # $hdr = substr( $hdr, 0, length( $header ), '' );
2248 my $len = hex( $hex_len );
2249 if( $len == 0 )
2250 {
2251 last READ_LOOP;
2252 }
2253 # $reader->unread( $hdr ) if( length( $hdr ) );
2254  
2255 my $chunk_size = $bufsize;
2256 $chunk_size = $len if( $chunk_size > $len );
2257 my $total_bytes = 0;
2258 READ_CHUNK: while( $bytes = $reader->read( $buff, $chunk_size ) )
2259 {
2260 if( $ent->is_binary( $buff ) )
2261 {
2262 if( -t( STDIN ) )
2263 {
2264 $self->message_colour( 5, '<green>[' . length( $buff ) . ' bytes of binary data not shown here]</>', { prefix => '<<<' } );
2265 }
2266 else
2267 {
2268 $self->message_colour( 5, '[' . length( $buff ) . ' bytes of binary data not shown here]', { prefix => '<<<' } );
2269 }
2270 }
2271 else
2272 {
2273 }
2274  
2275 my $bytes_out = $io->syswrite( $buff );
2276 return( $self->pass_error( $io->error ) ) if( !defined( $bytes_out ) );
2277  
2278 if( $bytes_out != $bytes )
2279 {
2280 return( $self->error( "Error writing to body $body: bytes read ($bytes) do not equate to bytes writen ($bytes_out)" ) );
2281 }
2282 $total_bytes += $bytes;
2283 last READ_CHUNK if( $total_bytes == $len );
2284 # We do not want to read more than we should
2285 $chunk_size = ( $len - $total_bytes ) if( ( $total_bytes < $len ) && ( ( $total_bytes + $chunk_size ) > $len ) );
2286 }
2287 return( $self->error( "Error reading http body from socket: ", $reader->error ) ) if( !defined( $bytes ) );
2288 # consume the trailing CRLF sequence
2289 my $trash = $reader->read_until_in_memory( qr/${CRLF}/, include => 1 );
2290 return( $self->pass_error( $reader->error ) ) if( !defined( $trash ) );
2291 }
2292 $io->close;
2293 # consume the final CRLF sequence
2294 my $trash = $reader->read_until_in_memory( qr/${CRLF}/, include => 1 );
2295 # Mark body as being encoded if necessary
2296 $ent->is_encoded( ( defined( $enc ) && CORE::length( $enc ) ) ? 1 : 0 );
2297 return( $body );
2298 }
2299  
2300 # NOTE: sub FREEZE is inherited
2301  
2302 sub STORABLE_freeze { CORE::return( CORE::shift->FREEZE( @_ ) ); }
2303  
2304 sub STORABLE_thaw { CORE::return( CORE::shift->THAW( @_ ) ); }
2305  
2306 # NOTE: sub THAW is inherited
2307  
2308 1;
2309 # NOTE: POD
2310 __END__
2311  
2312 =encoding utf-8
2313  
2314 =head1 NAME
2315  
2316 HTTP::Promise - Asynchronous HTTP Request and Promise
2317  
2318 =head1 SYNOPSIS
2319  
2320 use HTTP::Promise;
2321 my $p = HTTP::Promise->new(
2322 agent => 'MyBot/1.0'
2323 accept_encoding => 'auto', # set to 'none' to disable receiving compressed data
2324 accept_language => [qw( fr-FR fr en-GB en ja-JP )],
2325 auto_switch_https => 1,
2326 # For example, a Cookie::Jar object
2327 cookie_jar => $cookie_jar,
2328 dnt => 1,
2329 # 2Mb. Any data to be sent being bigger than this will trigger a Continue conditional query
2330 expect_threshold => 2048000,
2331 # Have the file extension reflect the encoding, if any
2332 ext_vary => 1,
2333 # 100Kb. Anything bigger than this will be automatically saved on file rather than memory
2334 max_body_in_memory_size => 102400,
2335 # 8Kb
2336 max_headers_size => 8192,
2337 max_redirect => 3,
2338 # For Promise::Me
2339 medium => 'mmap',
2340 proxy => 'https://proxy.example.org:8080',
2341 # The serialiser to use for the promise in Promise::Me
2342 # Defaults to storable, but can also be cbor and sereal
2343 serialiser => 'sereal',
2344 shared_mem_size => 1048576,
2345 # You can also use decimals with Time::HiRes
2346 timeout => 15,
2347 # force the use of files to store the response content
2348 use_content_file => 1,
2349 # Should we use promise?
2350 # use_promise => 0,
2351 );
2352 my $prom = $p->get( 'https://www.example.org', $hash_of_query_params )->then(sub
2353 {
2354 # Nota bene: the last value in this sub will be passed as the argument to the next 'then'
2355 my $resp = shift( @_ ); # get the HTTP::Promise::Response object
2356 })->catch(sub
2357 {
2358 my $ex = shift( @_ ); # get a HTTP::Promise::Exception object
2359 say "Exception code is: ", $ex->code;
2360 });
2361 # or using hash reference of options to prepare the request
2362 my $req = HTTP::Promise::Request->new( get => 'https://www.example.org' ) ||
2363 die( HTTP::Promise::Request->error );
2364 my $prom = $p->request( $req )->then(sub{ #... })->catch(sub{ # ... });
2365 # Prepare the query and get an HTTP::Promise::Request in return
2366 # This is useful for debugging
2367 my $req = $p->prepare( GET => 'https://example.com',
2368 Authorization => "Bearer $some_token",
2369 Accept => 'application/json',
2370 Query => {
2371 param1 => $value1,
2372 param2 => $value2,
2373 },
2374 ) || die( $p->error );
2375 say "Request would be: ", $req->as_string;
2376  
2377 =head1 VERSION
2378  
2379 v0.7.3
2380  
2381 =head1 DESCRIPTION
2382  
2383 L<HTTP::Promise> provides with a fast and powerful yet memory-friendly API to make true asynchronous HTTP requests using fork with L<Promise::Me>.
2384  
2385 It is based on the design of L<HTTP::Message>, but with a much cleaner interface to make requests and manage HTTP entity bodies.
2386  
2387 Here are the key features:
2388  
2389 =over 4
2390  
2391 =item * Support for HTTP/1.0 and HTTP/1.1
2392  
2393 =item * Handles gracefully very large files by reading and sending them in chunks.
2394  
2395 =item * Supports C<Continue> conditional requests
2396  
2397 =item * Support redirects
2398  
2399 =item * Reads data in chunks of bytes and not line by line.
2400  
2401 =item * Easy-to-use interface to encode and decode with L<HTTP::Promise::Stream>
2402  
2403 =item * Multi-lingual and complete HTTP Status codes with L<HTTP::Promise::Status>
2404  
2405 =item * MIME guessing module with L<HTTP::Promise::MIME>
2406  
2407 =item * Powerful HTTP parser with L<HTTP::Promise::Parser> supporting complex C<multipart> HTTP messages.
2408  
2409 =item * Has thorough documentation
2410  
2411 =back
2412  
2413 Here is how it is organised in overall:
2414  
2415 +-------------------------+ +--------------------------+
2416 | | | |
2417 | HTTP::Promise::Request | | HTTP::Promise::Response |
2418 | | | |
2419 +------------|------------+ +-------------|------------+
2420 | |
2421 | |
2422 | |
2423 | +------------------------+ |
2424 | | | |
2425 +--- HTTP::Promise::Message |---+
2426 | |
2427 +------------|-----------+
2428 |
2429 |
2430 +------------|-----------+
2431 | |
2432 | HTTP::Promise::Entity |
2433 | |
2434 +------------|-----------+
2435 |
2436 |
2437 +------------|-----------+
2438 | |
2439 | HTTP::Promise::Body |
2440 | |
2441 +------------------------+
2442  
2443 It differentiates from other modules by using several XS modules for speed, and has a notion of HTTP L<entity|HTTP::Promise::Entity> and L<body|HTTP::Promise::Body> stored either on file or in memory.
2444  
2445 It also has modules to make it really super easy to create C<x-www-form-urlencoded> requests with L<HTTP::Promise::Body::Form>, or C<multipart> ones with L<HTTP::Promise::Body::Form::Data>
2446  
2447 Thus, you can either have a fine granularity by creating your own request using L<HTTP::Promise::Request>, or you can use the high level methods provided by L<HTTP::Promise>, which are: L</delete>, L</get>, L</head>, L</options>, L</patch>, L</post>, L</put> and each will occur asynchronously.
2448  
2449 Each of those methods returns a L<promise|Promise::Me>, which means you can chain the results using a chainable L<then|Promise::Me/then> and L<catch|Promise::Me/catch> for errors.
2450  
2451 You can also wait for all of them to finish using L<await|Promise::Me/await>, which is exported by default by L<HTTP::Promise> and L<all|Promise::Me/all> or L<race|Promise::Me/|race>.
2452  
2453 my @results = await( $p1, $p2 );
2454 my @results = HTTP::Promise->all( $p1, $p2 );
2455 # First promise that is resolved or rejected makes this super promise resolved and
2456 # return the result
2457 my @results = HTTP::Promise->race( $p1, $p2 );
2458  
2459 You can also share variables using C<share>, such as:
2460  
2461 my $data : shared = {};
2462 # or
2463 my( $name, @first_names, %preferences );
2464 share( $name, @first_names, %preferences );
2465  
2466 See L<Promise::Me> for more information.
2467  
2468 It calls L<resolve|Promise::Me/resolve> when the request has been completed and sends a L<HTTP::Promise::Response> object whose API is similar to that of L<HTTP::Response>.
2469  
2470 When an error occurs, it is caught and sent by calling L<Promise::Me/reject> with an L<HTTP::Promise::Exception> object.
2471  
2472 Cookies are automatically and transparently managed with L<Cookie::Jar> which can load and store cookies to a json file you specify. You can create a L<cookie object|Cookie::Jar> and pass it to the constructor with the C<cookie_jar> option.
2473  
2474 =head1 CONSTRUCTOR
2475  
2476 =head2 new
2477  
2478 Provided with some optional parameters, and this instantiates a new L<HTTP::Promise> objects and returns it. If an error occurred, it will return C<undef> and the error can be retrieved using L<error|Module::Generic/error> method.
2479  
2480 It accepts the following parameters. Each of those options have a corresponding method, so you can get or change its value later:
2481  
2482 =over 4
2483  
2484 =item * C<accept_encoding>
2485  
2486 String. This sets whether we should accept compressed data.
2487  
2488 You can set it to C<none> to disable it. By default, this is C<auto>, and it will set the C<Accept-Encoding> C<HTTP> header to all the supported encoding based on the availability of associated modules.
2489  
2490 You can also set this to a comma-separated list of known encoding, typically: C<bzip2,deflate,gzip,rawdeflate,brotli>
2491  
2492 See L<HTTP::Promise::Stream> for more details.
2493  
2494 =item * C<agent>
2495  
2496 String. Set the user agent, i.e. the way this interface identifies itself when communicating with an HTTP server. By default, it uses something like C<HTTP-Promise/v0.1.0>
2497  
2498 =item * C<cookie_jar>
2499  
2500 Object. Set the class handling the cookie jar. By default it uses L<Cookie::Jar>
2501  
2502 =item * C<default_headers>
2503  
2504 L<HTTP::Promise::Headers>, or L<HTTP::Headers> Object. Sets the headers object containing the default headers to use.
2505  
2506 =item * C<local_address>
2507  
2508 String. A local IP address or local host name to use when establishing TCP/IP connections.
2509  
2510 =item * C<local_host>
2511  
2512 String. Same as C<local_address>
2513  
2514 =item * C<local_port>
2515  
2516 Integer. A local port to use when establishing TCP/IP connections.
2517  
2518 =item * C<max_redirect>
2519  
2520 Integer. This is the maximum number of redirect L<HTTP::Promise> will follow until it gives up. Default value is C<7>
2521  
2522 =item * C<max_size>
2523  
2524 Integer. Set the size limit for response content. If the response content exceeds the value set here, the request will be aborted and a C<Client-Aborted> header will be added to the response object returned. Default value is C<undef>, i.e. no limit.
2525  
2526 See also the C<threshold> option.
2527  
2528 =item * C<medium>
2529  
2530 This can be either C<file>, C<mmap> or C<memory>. This will be passed on to L<Promise::Me> as C<result_shared_mem_size> to store resulting data between processes. See L<Promise::Me> for more details.
2531  
2532 It defaults to C<$Promise::Me::SHARE_MEDIUM>
2533  
2534 =item * C<no_proxy>
2535  
2536 Array reference. Do not proxy requests to the given domains.
2537  
2538 =item * C<proxy>
2539  
2540 The url of the proxy to use for the HTTP requests.
2541  
2542 =item * C<requests_redirectable>
2543  
2544 Array reference. This sets the list of http methods that are allowed to be redirected. Default to empty, which means that all methods can be redirected.
2545  
2546 =item * C<serialiser>
2547  
2548 String. Specify the serialiser to use for L<Promise::Me>. Possible values are: L<cbor|CBOR::XS>, L<sereal|Sereal> or L<storable|Storable::Improved>
2549  
2550 By default it uses the value set in the global variable C<$SERIALISER>, which is a copy of the C<$SERIALISER> in L<Promise::Me>, which should be by default C<storable>
2551  
2552 =item * C<shared_mem_size>
2553  
2554 Integer. This will be passed on to L<Promise::Me>. See L<Promise::Me> for more details.
2555  
2556 It defaults to C<$Promise::Me::RESULT_MEMORY_SIZE>
2557  
2558 =item * C<ssl_opts>
2559  
2560 Hash reference. Sets an hash reference of ssl options. The default values are set as follows:
2561  
2562 =over 8
2563  
2564 =item 1. C<verify_hostname>
2565  
2566 When enabled, this ensures it connects to servers that have a valid certificate matching the expected hostname.
2567  
2568 =over 12
2569  
2570 =item 1.1. If environment variable C<PERL_LWP_SSL_VERIFY_HOSTNAME> is set, the ssl option property C<verify_hostname> takes its value.
2571  
2572 =item 1.2. If environment variable C<HTTPS_CA_FILE> or C<HTTPS_CA_DIR> are set to a true value, then the ssl option property C<verify_hostname> is set to C<0> and option property C<SSL_verify_mode> is set to C<1>
2573  
2574 =item 1.3 If none of the above applies, it defaults C<verify_hostname> to C<1>
2575  
2576 =back
2577  
2578 =item 2. C<SSL_ca_file>
2579  
2580 This is the path to a file containing the Certificate Authority certificates.
2581  
2582 If environment variable C<PERL_LWP_SSL_CA_FILE> or C<HTTPS_CA_FILE> is set, then the ssl option property C<SSL_ca_file> takes its value.
2583  
2584 =item 3. C<SSL_ca_path>
2585  
2586 This is the path to a directory of files containing Certificate Authority certificates.
2587  
2588 If environment variable C<PERL_LWP_SSL_CA_PATH> or C<HTTPS_CA_DIR> is set, then the ssl option property C<SSL_ca_path> takes its value.
2589  
2590 =back
2591  
2592 Other options can be set and are processed directly by the SSL Socket implementation in use. See L<IO::Socket::SSL> or L<Net::SSL> for details.
2593  
2594 Example of C<ssl_opts>:
2595  
2596 my $ssl_opts =
2597 {
2598 SSL_ca_file => "/usr/local/lib/perl5/site_perl/5.36.1/Mozilla/CA/cacert.pem",
2599 SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_PEER(), # Explicit constant for clarity
2600 SSL_verifycn_scheme => "www",
2601 SSL_hostname => $host, # Explicit SNI; prevents issues if PeerHost changes
2602 SSL_version => "TLSv1_2:TLSv1_3", # Enforce modern TLS (adjust for legacy if needed)
2603 # SSL_fingerprint => "sha256$your_cert_fingerprint", # If pinning a specific cert
2604 # SSL_ocsp_mode => IO::Socket::SSL::SSL_OCSP_TRY_STAPLE(), # For revocation checks
2605 };
2606  
2607 =item * C<threshold>
2608  
2609 Integer. Sets the content length threshold beyond which, the response content will be stored to a locale file. It can then be fetch with L</file>. Default to global variable C<$CONTENT_SIZE_THRESHOLD>, which is C<undef> by default.
2610  
2611 See also the C<max_size> option.
2612  
2613 =item * C<timeout>
2614  
2615 Integer. Sets the timeout value. Defaults to 180 seconds, i.e. 3 minutes.
2616  
2617 =item * C<use_content_file>
2618  
2619 Boolean. Enables the use of a temporary local file to store the response content, no matter the size o the response content.
2620  
2621 =item * C<use_promise>
2622  
2623 Boolean. When true, this will have L<HTTP::Promise> HTTP methods return a L<HTTP::Promise|promise>, and when false, it returns directly the L<HTTP::Promise::Response|response object>. Defaults to true.
2624  
2625 =back
2626  
2627 =head1 METHODS
2628  
2629 The following methods are available. This interface provides similar interface as L<LWP::UserAgent> while providing more granular control.
2630  
2631 =head2 accept_encoding
2632  
2633 String. Sets or gets whether we should accept compressed data.
2634  
2635 You can set it to C<none> to disable it. By default, this is C<auto>, and it will set the C<Accept-Encoding> C<HTTP> header to all the supported encoding based on the availability of associated modules.
2636  
2637 You can also set this to a comma-separated list of known encoding, typically: C<bzip2,deflate,gzip,rawdeflate,brotli>
2638  
2639 See L<HTTP::Promise::Stream> for more details.
2640  
2641 Returns a L<scalar object|Module::Generic::Scalar> of the current value.
2642  
2643 =head2 accept_language
2644  
2645 An array of acceptable language. This will be used to set the C<Accept-Language> header.
2646  
2647 See also L<HTTP::Promise::Headers::AcceptLanguage>
2648  
2649 =head2 agent
2650  
2651 This is a string.
2652  
2653 Sets or gets the agent id used to identify when making the server connection.
2654  
2655 It defaults to C<HTTP-Promise/v0.1.0>
2656  
2657 my $p = HTTP::Promise->new( agent => 'MyBot/1.0' );
2658 $p->agent( 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:99.0) Gecko/20100101 Firefox/99.0' );
2659  
2660 The C<User-Agent> header field is only set to this provided value if it is not already set.
2661  
2662 =head2 accept_language
2663  
2664 Sets or gets an array of acceptable response content languages.
2665  
2666 For example:
2667  
2668 $http->accept_language( [qw( fr-FR ja-JP en-GB en )] );
2669  
2670 Would result into an C<Accept-Language> header set to C<fr-FR;q=0.9,ja-JP;q=0.8,en-GB;q=0.7,en;q=0.6>
2671  
2672 The C<Accept-Language> header would only be set if it is not set already.
2673  
2674 =head2 auto_switch_https
2675  
2676 Boolean. If set to a true value, or if left to C<undef> (default value), this will set the C<Upgrade-Insecure-Requests> header field to C<1>
2677  
2678 =head2 buffer_size
2679  
2680 The size of the buffer to use when reading data from the filehandle or socket.
2681  
2682 =head2 connection_header
2683  
2684 Sets or gets the value for the header C<Connection>. It can be C<close> or C<keep-alive>
2685  
2686 If it is let C<undef>, this module will try to guess the proper value based on the L<HTTP::Promise::Request/protocol> and L<HTTP::Promise::Request/version> used.
2687  
2688 For protocol C<HTTP/1.0>, C<Connection> value would be C<close>, but above C<HTTP/1.1> the connection can be set to C<keep-alive> and thus be re-used.
2689  
2690 =head2 cookie_jar
2691  
2692 Sets or gets the Cookie jar class object to use. This is typically L<Cookie::Jar> or maybe L<HTTP::Cookies>
2693  
2694 This defaults to L<Cookie::Jar>
2695  
2696 use Cookie::Jar;
2697 my $jar = Cookie::Jar->new;
2698 my $p = HTTP::Promise->new( cookie_jar => $jar );
2699 $p->cookie_jar( $jar );
2700  
2701 =for Pod::Coverage decodable
2702  
2703 =head2 decodable
2704  
2705 This calls L<HTTP::Promise::Stream/decodable> passing it whatever arguments that were provided.
2706  
2707 =head2 default_header
2708  
2709 Sets one more default headers. This is a shortcut to C<< $p->default_headers->header >>
2710  
2711 $p->default_header( $field );
2712 $p->default_header( $field => $value );
2713 $p->default_header( 'Accept-Encoding' => scalar( HTTP::Promise->decodable ) );
2714 $p->default_header( 'Accept-Language' => 'fr, en, ja' );
2715  
2716 =head2 default_headers
2717  
2718 Sets or gets the L<default header object|HTTP::Promise::Headers>, which is set to C<undef> by default.
2719  
2720 This can be either an L<HTTP::Promise::Headers> or L<HTTP::Headers> object.
2721  
2722 use HTTP::Promise::Headers;
2723 my $headers = HTTP::Promise::Headers->new(
2724 'Accept-Encoding' => scalar( HTTP::Promise->decodable ),
2725 'Accept-Language' => 'fr, en, ja',
2726 );
2727 my $p = HTTP::Promise->new( default_headers => $headers );
2728  
2729 =head2 default_protocol
2730  
2731 Sets or gets the default protocol to use. For example: C<HTTP/1.1>
2732  
2733 =head2 delete
2734  
2735 Provided with an C<uri> and an optional hash of header name/value pairs, and this will issue a C<DELETE> http request to the given C<uri>.
2736  
2737 It returns a L<promise|Promise::Me>, which can be used to call one or more L<then|Promise::Me/then> and L<catch|Promise::Me/catch>
2738  
2739 # or $p->delete( $uri, $field1 => $value1, $field2 => $value2 )
2740 $p->delete( $uri )->then(sub
2741 {
2742 my( $resolve, $reject ) = @$_;
2743 # an HTTP::Promise::Response is returned
2744 my $resp = shift( @_ );
2745 # Do something with the $resp object
2746 })->catch(sub
2747 {
2748 my $ex = shift( @_ );
2749 # An HTTP::Promise::Exception object is passed with an error code
2750 say( "Error code; ", $ex->code, " and message: ", $ex->message );
2751 });
2752  
2753 However, if L</use_promise> is set to false, this will return an L<HTTP::Promise::Response> object directly.
2754  
2755 =head2 dnt
2756  
2757 Boolean. If set to a true value, this will set the C<DNT> header to C<1>
2758  
2759 =head2 expect_threshold
2760  
2761 Sets or gets the body size threshold beyond which, this module will issue a conditional C<Expect> HTTP header in order to ensure the remote HTTP server is ok.
2762  
2763 =head2 ext_vary
2764  
2765 Boolean. When this is set to a true value, this will have the files use extensions that reflect not just their content, but also their encoding when applicable.
2766  
2767 For example, if an HTTP response HTML content is gzip encoded into a file, the file extensions will be C<html.gz>
2768  
2769 Default set to C<$EXTENSION_VARY>, which by default is true.
2770  
2771 =head2 file
2772  
2773 If a temporary file has been set, the response content file can be retrieved with this method.
2774  
2775 my $p = HTTP::Promise->new( threshold => 512000 ); # 500kb
2776 # If the response payload exceeds 500kb, HTTP::Promise will save the content to a
2777 # temporary file
2778 # or
2779 my $p = HTTP::Promise->new( use_content_file => 1 ); # always use a temporary file
2780 # Returns a Module::Generic::File object
2781 my $f = $p->file;
2782  
2783 =head2 from
2784  
2785 Get or set the email address for the human user who controls the requesting user agent. The address should be machine-usable, as defined in L<RFC2822|https://tools.ietf.org/html/rfc2822>. The C<from> value is sent as the C<From> header in the requests
2786  
2787 The default value is C<undef>, so no C<From> field is set by default.
2788  
2789 my $p = HTTP::Promise->new( from => 'john.doe@example.com' );
2790 $p->from( 'john.doe@example.com' );
2791  
2792 =head2 get
2793  
2794 Provided with an C<uri> and an optional hash of header name/value pairs, and this will issue a C<GET> http request to the given C<uri>.
2795  
2796 It returns a L<promise|Promise::Me>, which can be used to call one or more L<then|Promise::Me/then> and L<catch|Promise::Me/catch>
2797  
2798 # or $p->get( $uri, $field1 => $value1, $field2 => $value2 )
2799 $p->get( $uri )->then(sub
2800 {
2801 my( $resolve, $reject ) = @$_;
2802 # an HTTP::Promise::Response is returned
2803 my $resp = shift( @_ );
2804 # Do something with the $resp object
2805 })->catch(sub
2806 {
2807 my $ex = shift( @_ );
2808 # An HTTP::Promise::Exception object is passed with an error code
2809 say( "Error code; ", $ex->code, " and message: ", $ex->message );
2810 });
2811  
2812 If you pass a special header name C<Content> or C<Query>, it will be used to set the query string of the L<URI>.
2813  
2814 The value can be an hash reference, and L<query_form|URI/query_form> will be called.
2815  
2816 If the value is a string or an object that stringifies, L<query|URI/query> will be called to set the value as-is. this option gives you direct control of the query string.
2817  
2818 However, if L</use_promise> is set to false, this will return an L<HTTP::Promise::Response> object directly.
2819  
2820 =head2 head
2821  
2822 Provided with an C<uri> and an optional hash of header name/value pairs, and this will issue a C<HEAD> http request to the given C<uri>.
2823  
2824 It returns a L<promise|Promise::Me>, which can be used to call one or more L<then|Promise::Me/then> and L<catch|Promise::Me/catch>
2825  
2826 # or $p->head( $uri, $field1 => $value1, $field2 => $value2 )
2827 $p->head( $uri )->then(sub
2828 {
2829 my( $resolve, $reject ) = @$_;
2830 # an HTTP::Promise::Response is returned
2831 my $resp = shift( @_ );
2832 # Do something with the $resp object
2833 })->catch(sub
2834 {
2835 my $ex = shift( @_ );
2836 # An HTTP::Promise::Exception object is passed with an error code
2837 say( "Error code; ", $ex->code, " and message: ", $ex->message );
2838 });
2839  
2840 However, if L</use_promise> is set to false, this will return an L<HTTP::Promise::Response> object directly.
2841  
2842 =head2 httpize_datetime
2843  
2844 Provided with a L<DateTime> or L<Module::Generic::DateTime> object, and this will ensure the C<DateTime> object stringifies to a valid HTTP datetime.
2845  
2846 It returns the C<DateTime> object provided upon success, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>
2847  
2848 =head2 inactivity_timeout
2849  
2850 Sets or gets the inactivity timeout in seconds. If timeout is reached, the connection is closed.
2851  
2852 =head2 is_protocol_supported
2853  
2854 Provided with a protocol, such as C<http>, or C<https>, and this returns true if the protocol is supported or false otherwise.
2855  
2856 This basically returns true if the protocol is either C<http> or C<https> and false otherwise, because C<HTTP::Promise> supports only HTTP protocol.
2857  
2858 =head2 languages
2859  
2860 This is an alias for L</accept_language>
2861  
2862 =head2 local_address
2863  
2864 Get or set the local interface to bind to for network connections. The interface can be specified as a hostname or an IP address. This value is passed as the C<LocalHost> argument to L<IO::Socket>.
2865  
2866 The default value is C<undef>.
2867  
2868 my $p = HTTP::Promise->new( local_address => 'localhost' );
2869 $p->local_address( '127.0.0.1' );
2870  
2871 =head2 local_host
2872  
2873 This is the same as L</local_address>. You can use either interchangeably.
2874  
2875 =head2 local_port
2876  
2877 Get or set the local port to use to bind to for network connections. This value is passed as the C<LocalPort> argument to L<IO::Socket>
2878  
2879 =head2 max_body_in_memory_size
2880  
2881 Sets or gets the maximum HTTP response body size beyond which the data will automatically be saved in a temporary file.
2882  
2883 =head2 max_headers_size
2884  
2885 Sets or gets the maximum HTTP response headers size, beyond which an error is triggered.
2886  
2887 =head2 max_redirect
2888  
2889 An integer. Sets or gets the maximum number of allowed redirection possible. Default is 7.
2890  
2891 my $p = HTTP::Promise->new( max_redirect => 5 );
2892 $p->max_redirect(12);
2893 my $max = $p->max_redirect;
2894  
2895 =head2 max_size
2896  
2897 Get or set the size limit for response content. The default is C<undef>, which means that there is no limit. If the returned response content is only partial, because the size limit was exceeded, then a C<Client-Aborted> header will be added to the response. The content might end up longer than C<max_size> as we abort once appending a chunk of data makes the length exceed the limit. The C<Content-Length> header, if present, will indicate the length of the full content and will normally not be the same as C<< length( $resp->content ) >>
2898  
2899 my $p = HTTP::Promise->max_size(512000); # 512kb
2900 $p->max_size(512000);
2901 my $max = $p->max_size;
2902  
2903 =head2 mirror
2904  
2905 Provided with an C<uri> and a C<filepath> and this will issue a conditional request to the remote server to return the remote content if it has been modified since the last modification time of the C<filepath>. Of course, if that file does not exists, then it is downloaded. If the remote resource has been changed since last time, it is downloaded again and its content stored into the C<filepath>
2906  
2907 Just like other http methods, this returns a L<promise|Promise::Me> object.
2908  
2909 It can then be used to call one or more L<then|Promise::Me/then> and L<catch|Promise::Me/catch>
2910  
2911 $p->mirror( $uri => '/some/where/file.txt' )->then(sub
2912 {
2913 my( $resolve, $reject ) = @$_;
2914 # an HTTP::Promise::Response is returned
2915 my $resp = shift( @_ );
2916 # Do something with the $resp object
2917 })->catch(sub
2918 {
2919 my $ex = shift( @_ );
2920 # An HTTP::Promise::Exception object is passed with an error code
2921 say( "Error code; ", $ex->code, " and message: ", $ex->message );
2922 });
2923  
2924 However, if L</use_promise> is set to false, this will return an L<HTTP::Promise::Response> object directly.
2925  
2926 =head2 new_headers
2927  
2928 my $headers = $p->new_headers( Accept => 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.8' );
2929  
2930 This takes some key-value pairs as header name and value, and instantiate a new L<HTTP::Promise::Headers> object and returns it.
2931  
2932 If an error occurs, this set an L<error object|HTTP::Promise::Exception> and return C<undef> in scalar context or an empty list in list context.
2933  
2934 =head2 no_proxy
2935  
2936 Sets or gets a list of domain names for which the proxy will not apply. By default this is empty.
2937  
2938 This returns an L<array object|Module::Generic::Array>
2939  
2940 my $p = HTTP::Promise->new( no_proxy => [qw( example.com www2.example.net )] );
2941 $p->no_proxy( [qw( localhost example.net )] );
2942 my $ar = $p->no_proxy;
2943 say $ar->length, " proxy exception(s) set.";
2944  
2945 =head2 options
2946  
2947 Provided with an C<uri>, and this will issue an C<OPTIONS> http request to the given C<uri>.
2948  
2949 It returns a L<promise|Promise::Me>, which can be used to call one or more L<then|Promise::Me/then> and L<catch|Promise::Me/catch>
2950  
2951 # or $p->head( $uri, $field1 => $value1, $field2 => $value2 )
2952 $p->options( $uri )->then(sub
2953 {
2954 my( $resolve, $reject ) = @$_;
2955 # an HTTP::Promise::Response is returned
2956 my $resp = shift( @_ );
2957 # Do something with the $resp object
2958 })->catch(sub
2959 {
2960 my $ex = shift( @_ );
2961 # An HTTP::Promise::Exception object is passed with an error code
2962 say( "Error code; ", $ex->code, " and message: ", $ex->message );
2963 });
2964  
2965 However, if L</use_promise> is set to false, this will return an L<HTTP::Promise::Response> object directly.
2966  
2967 =head2 patch
2968  
2969 Provided with an C<uri> and an optional hash of form data, followed by an hash of header name/value pairs and this will issue a C<PATCH> http request to the given C<uri>.
2970  
2971 If a special header name C<Content> is provided, its value will be used to create the key-value pairs form data. That C<Content> value can either be an array reference, or an hash reference of key-value pairs. If if is just a string, it will be used as-is as the request body.
2972  
2973 If a special header name C<Query> is provided, its value will be used to set the C<URI> query string. The query string thus provided must already be escaped.
2974  
2975 It returns a L<promise|Promise::Me>, which can be used to call one or more L<then|Promise::Me/then> and L<catch|Promise::Me/catch>
2976  
2977 # or $p->patch( $uri, \@form, $field1 => $value1, $field2 => $value2 );
2978 # or $p->patch( $uri, \%form, $field1 => $value1, $field2 => $value2 );
2979 # or $p->patch( $uri, $field1 => $value1, $field2 => $value2 );
2980 # or $p->patch( $uri, $field1 => $value1, $field2 => $value2, Content => \@form, Query => $escaped_string );
2981 # or $p->patch( $uri, $field1 => $value1, $field2 => $value2, Content => \%form, Query => $escaped_string );
2982 # or $p->patch( $uri, $field1 => $value1, $field2 => $value2, Content => $content, Query => $escaped_string );
2983 $p->patch( $uri )->then(sub
2984 {
2985 my( $resolve, $reject ) = @$_;
2986 # an HTTP::Promise::Response is returned
2987 my $resp = shift( @_ );
2988 # Do something with the $resp object
2989 })->catch(sub
2990 {
2991 my $ex = shift( @_ );
2992 # An HTTP::Promise::Exception object is passed with an error code
2993 say( "Error code; ", $ex->code, " and message: ", $ex->message );
2994 });
2995  
2996 However, if L</use_promise> is set to false, this will return an L<HTTP::Promise::Response> object directly.
2997  
2998 =head2 post
2999  
3000 Provided with an C<uri> and an optional hash of form data, followed by an hash of header name/value pairs and this will issue a C<POST> http request to the given C<uri>.
3001  
3002 If a special header name C<Content> is provided, its value will be used to create the key-value pairs form data. That C<Content> value can either be an array reference, or an hash reference of key-value pairs. If if is just a string, it will be used as-is as the request body.
3003  
3004 If a special header name C<Query> is provided, its value will be used to set the C<URI> query string. The query string thus provided must already be escaped.
3005  
3006 How the form data is formatted depends on the C<Content-Type> set in the headers passed. If the C<Content-Type> header is C<form-data> or C<multipart/form-data>, the form data will be formatted as a C<multipart/form-data> post, otherwise they will be formatted as a C<application/x-www-form-urlencoded> post.
3007  
3008 It returns a L<promise|Promise::Me>, which can be used to call one or more L<then|Promise::Me/then> and L<catch|Promise::Me/catch>
3009  
3010 # or $p->post( $uri, \@form, $field1 => $value1, $field2 => $value2 );
3011 # or $p->post( $uri, \%form, $field1 => $value1, $field2 => $value2 );
3012 # or $p->post( $uri, $field1 => $value1, $field2 => $value2 );
3013 # or $p->post( $uri, $field1 => $value1, $field2 => $value2, Content => \@form, Query => $escaped_string );
3014 # or $p->post( $uri, $field1 => $value1, $field2 => $value2, Content => \%form, Query => $escaped_string );
3015 # or $p->post( $uri, $field1 => $value1, $field2 => $value2, Content => $content, Query => $escaped_string );
3016 $p->post( $uri )->then(sub
3017 {
3018 my( $resolve, $reject ) = @$_;
3019 # an HTTP::Promise::Response is returned
3020 my $resp = shift( @_ );
3021 # Do something with the $resp object
3022 })->catch(sub
3023 {
3024 my $ex = shift( @_ );
3025 # An HTTP::Promise::Exception object is passed with an error code
3026 say( "Error code; ", $ex->code, " and message: ", $ex->message );
3027 });
3028  
3029 However, if L</use_promise> is set to false, this will return an L<HTTP::Promise::Response> object directly.
3030  
3031 =head2 prepare
3032  
3033 This takes an HTTP method whose case does not matter, i.e. it could be C<get> or C<GET>, and C<URL>, and a set of HTTP headers or special parameters like C<Content> or C<Query>. You can refer to each standard method L</delete>, L</get>, L</head>, L</options>, L</patch>, L</post>, L</put> for more information.
3034  
3035 You can also pass other methods, and your parameters will be passed through directly to L<HTTP::Promise::Request>
3036  
3037 If successful, this returns an L<HTTP::Promise::Request> object, otherwise, it sets an L<HTTP::Promise::Exception> and returns C<undef> in scalar context, or an empty list in list context.
3038  
3039 =head2 prepare_headers
3040  
3041 Provided with an L<HTTP::Promise::Request> object, and this will set the following request headers, if they are not set already.
3042  
3043 You can override this method if you create a module of your own that inherits from L<HTTP::Promise>.
3044  
3045 It returns the L<HTTP::Promise::Request> received, or upon error, it sets an L<error|Module::Generic/error> and returns C<undef>
3046  
3047 Headers set, if not set already are:
3048  
3049 =over 4
3050  
3051 =item * C<Accept>
3052  
3053 This uses the values set with L</accept>
3054  
3055 =item * C<Accept-Language>
3056  
3057 This uses the values set with L</accept_language> or L</languages>
3058  
3059 =item * C<Accept-Encoding>
3060  
3061 This uses the value returned from L<HTTP::Promise::Stream/decodable> to find out the encoding installed and supported on your system.
3062  
3063 =item * C<DNT>
3064  
3065 This uses the value set with L</dnt>
3066  
3067 =item * C<Upgrade-Insecure-Requests>
3068  
3069 This uses the value set with L</auto_switch_https> or L</upgrade_insecure_requests>
3070  
3071 =item * C<User-Agent>
3072  
3073 This uses the value set with L</agent>
3074  
3075 =back
3076  
3077 =head2 proxy
3078  
3079 Array reference. This sets the scheme and their proxy or proxies. Default to C<undef>. For example:
3080  
3081 my $p = HTTP::Promise->new( proxy => [ [qw( http ftp )] => 'https://proxy.example.com:8001' ] );
3082 my $p = HTTP::Promise->new( proxy => [ http => 'https://proxy.example.com:8001' ] );
3083 my $p = HTTP::Promise->new( proxy => [ ftp => 'http://ftp.example.com:8001/',
3084 [qw( http https )] => 'https://proxy.example.com:8001' ] );
3085 my $proxy = $p->proxy( 'https' );
3086  
3087 =head2 proxy_authorization
3088  
3089 Sets or gets the proxy authorization string. This is computed automatically when you set a user and a password to the proxy URI by setting the value to L</proxy>
3090  
3091 =head2 put
3092  
3093 Provided with an C<uri> and an optional hash of form data, followed by an hash of header name/value pairs and this will issue a C<PUT> http request to the given C<uri>.
3094  
3095 If a special header name C<Content> is provided, its value will be used to create the key-value pairs form data. THat C<Content> value can either be an array reference, or an hash reference of key-value pairs. If if is just a string, it will be used as-is as the request body.
3096  
3097 If a special header name C<Query> is provided, its value will be used to set the C<URI> query string. The query string thus provided must already be escaped.
3098  
3099 How the form data is formatted depends on the C<Content-Type> set in the headers passed. If the C<Content-Type> header is C<form-data> or C<multipart/form-data>, the form data will be formatted as a C<multipart/form-data> post, otherwise they will be formatted as a C<application/x-www-form-urlencoded> put.
3100  
3101 It returns a L<promise|Promise::Me>, which can be used to call one or more L<then|Promise::Me/then> and L<catch|Promise::Me/catch>
3102  
3103 # or $p->put( $uri, \@form, $field1 => $value1, $field2 => $value2 );
3104 # or $p->put( $uri, \%form, $field1 => $value1, $field2 => $value2 );
3105 # or $p->put( $uri, $field1 => $value1, $field2 => $value2 );
3106 # or $p->put( $uri, $field1 => $value1, $field2 => $value2, Content => \@form, Query => $escaped_string );
3107 # or $p->put( $uri, $field1 => $value1, $field2 => $value2, Content => \%form, Query => $escaped_string );
3108 # or $p->put( $uri, $field1 => $value1, $field2 => $value2, Content => $content, Query => $escaped_string );
3109 $p->put( $uri )->then(sub
3110 {
3111 my( $resolve, $reject ) = @$_;
3112 # an HTTP::Promise::Response is returned
3113 my $resp = shift( @_ );
3114 # Do something with the $resp object
3115 })->catch(sub
3116 {
3117 my $ex = shift( @_ );
3118 # An HTTP::Promise::Exception object is passed with an error code
3119 say( "Error code; ", $ex->code, " and message: ", $ex->message );
3120 });
3121  
3122 However, if L</use_promise> is set to false, this will return an L<HTTP::Promise::Response> object directly.
3123  
3124 =head2 request
3125  
3126 This method will issue the proper request in accordance with the request object provided. It will process redirects and authentication responses transparently. This means it may end up sending multiple request, up to the limit set with the object option L</max_redirect>
3127  
3128 This method takes the following parameters:
3129  
3130 =over 4
3131  
3132 =item 1. a L<request object|HTTP::Promise::Request>, which is typically L<HTTP::Promise::Request>, or L<HTTP::Request>, but any class that implements a similar interface is acceptable
3133  
3134 =item 2. an optional hash or hash reference of parameters:
3135  
3136 =over 8
3137  
3138 =item C<read_size>
3139  
3140 Integer. If provided, this will instruct to read the response by that much bytes at a time.
3141  
3142 =item C<use_content_file>
3143  
3144 Boolean. If true, this will instruct the use of a temporary file to store the response content. That file may then be retrieved with the method L</file>.
3145  
3146 You can also control the use of a temporary file to store the response content with the L</threshold> object option.
3147  
3148 =back
3149  
3150 =back
3151  
3152 It returns a L<promise object|Promise::Me> just like other methods.
3153  
3154 For example:
3155  
3156 use HTTP::Promise::Request;
3157 my $req = HTTP::Promise::Request->new( get => 'https://example.com' );
3158 my $p = HTTP::Promise->new;
3159 my $prom = $p->request( $req )->then(sub
3160 {
3161 my( $resolve, $reject ) = @$_;
3162 # Get the HTTP::Promise::Response object
3163 my $resp = shift( @_ );
3164 # Do something with the response object
3165 })->catch(sub
3166 {
3167 # Get a HTTP::Promise::Exception object
3168 my $ex = shift( @_ );
3169 say "Got an error code ", $ex->code, " with message: ", $ex->message;
3170 });
3171  
3172 However, if L</use_promise> is set to false, this will return an L<HTTP::Promise::Response> object directly.
3173  
3174 =head2 requests_redirectable
3175  
3176 Array reference. Sets or gets the list of http method that are allowed to be redirected. By default this is an empty list, i.e. all http methods are allowed to be redirected. Defaults to C<GET> and C<HEAD> as per L<rfc 2616|https://tools.ietf.org/html/rfc2616>
3177  
3178 This returns an L<array object|Module::Generic::Array>
3179  
3180 my $p = HTTP::Promise->new( requests_redirectable => [qw( HEAD GET POST )] );
3181 $p->requests_redirectable( [qw( HEAD GET POST )] );
3182 my $ok_redir = $p->requests_redirectable;
3183 # Add put
3184 $ok_redir->push( 'PUT' );
3185 # Remove POST we just added
3186 $ok_redir->remove( 'POST' );
3187  
3188 =head2 send
3189  
3190 Provided with an L<HTTP::Promise::Request>, and an optional hash or hash reference of options and this will attempt to connect to the specified L<uri|HTTP::Promise::Request/uri>
3191  
3192 Supported options:
3193  
3194 =over 4
3195  
3196 =item * C<expect_threshold>
3197  
3198 A number specifying the request body size threshold beyond which, this will issue a conditional C<Expect> HTTP header.
3199  
3200 =item * C<total_attempts>
3201  
3202 Total number of attempts. This is a value that is decreased for each redirected requests it receives until the maximum is reached. The maximum is specified with L</max_redirect>
3203  
3204 After connected to the remote server, it will send the request using L<HTTP::Promise::Request/print>, and reads the HTTP response, possibly C<chunked>.
3205  
3206 It returns a new L<HTTP::Promise::Response> object, or upon error, this sets an L<error|Module::Generic/error> and returns C<undef>
3207  
3208 =back
3209  
3210 =head2 send_te
3211  
3212 Boolean. Enables or disables the C<TE> http header. Defaults to true. If true, the C<TE> will be added to the outgoing http request.
3213  
3214 my $p = HTTP::Promise->new( send_te => 1 );
3215 $p->send_te(1);
3216 my $bool = $p->send_te;
3217  
3218 =head2 serialiser
3219  
3220 String. Sets or gets the serialiser to use for L<Promise::Me>. Possible values are: L<cbor|CBOR::XS>, L<sereal|Sereal> or L<storable|Storable::Improved>
3221  
3222 By default, the value is set to the global variable C<$SERIALISER>, which is a copy of the C<$SERIALISER> in L<Promise::Me>, which should be by default C<storable>
3223  
3224 =head2 simple_request
3225  
3226 This method takes the same parameters as L</request> and differs in that it will not try to handle redirects or authentication.
3227  
3228 It returns a L<promise object|Promise::Me> just like other methods.
3229  
3230 For example:
3231  
3232 use HTTP::Promise::Request;
3233 my $req = HTTP::Promise::Request->new( get => 'https://example.com' );
3234 my $p = HTTP::Promise->new;
3235 my $prom = $p->simple_request( $req )->then(sub
3236 {
3237 my( $resolve, $reject ) = @$_;
3238 # Get the HTTP::Promise::Response object
3239 my $resp = shift( @_ );
3240 # Do something with the response object
3241 })->catch(sub
3242 {
3243 # Get a HTTP::Promise::Exception object
3244 my $ex = shift( @_ );
3245 say "Got an error code ", $ex->code, " with message: ", $ex->message;
3246 });
3247  
3248 However, if L</use_promise> is set to false, this will return an L<HTTP::Promise::Response> object directly.
3249  
3250 =head2 ssl_opts
3251  
3252 L<Hash reference object|Module::Generic::Hash>. Sets or gets the ssl options properties used when making requests over ssl. The default values are set as follows:
3253  
3254 =over 8
3255  
3256 =item 1. C<verify_hostname>
3257  
3258 When enabled, this ensures it connects to servers that have a valid certificate matching the expected hostname.
3259  
3260 =over 12
3261  
3262 =item 1.1. If environment variable C<PERL_LWP_SSL_VERIFY_HOSTNAME> is set, the ssl option property C<verify_hostname> takes its value.
3263  
3264 =item 1.2. If environment variable C<HTTPS_CA_FILE> or C<HTTPS_CA_DIR> are set to a true value, then the ssl option property C<verify_hostname> is set to C<0> and option property C<SSL_verify_mode> is set to C<1>
3265  
3266 =item 1.3 If none of the above applies, it defaults C<verify_hostname> to C<1>
3267  
3268 =back
3269  
3270 =item 2. C<SSL_ca_file>
3271  
3272 This is the path to a file containing the Certificate Authority certificates.
3273  
3274 If environment variable C<PERL_LWP_SSL_CA_FILE> or C<HTTPS_CA_FILE> is set, then the ssl option property C<SSL_ca_file> takes its value.
3275  
3276 =item 3. C<SSL_ca_path>
3277  
3278 This is the path to a directory of files containing Certificate Authority certificates.
3279  
3280 If environment variable C<PERL_LWP_SSL_CA_PATH> or C<HTTPS_CA_DIR> is set, then the ssl option property C<SSL_ca_path> takes its value.
3281  
3282 =back
3283  
3284 Other options can be set and are processed directly by the SSL Socket implementation in use. See L<IO::Socket::SSL> or L<Net::SSL> for details.
3285  
3286 =head2 stop_if
3287  
3288 Sets or gets a callback code reference (reference to a perl subroutine or an anonymous subroutine) that will be used to determine if we should keep trying upon reading data from the filehandle and an C<EINTR> error occurs.
3289  
3290 If the callback returns true, further attempts will stop and return an error. The default is to continue trying.
3291  
3292 =head2 threshold
3293  
3294 Integer. Sets the content length threshold beyond which, the response content will be stored to a locale file. It can then be fetch with L</file>. Default to global variable C<$CONTENT_SIZE_THRESHOLD>, which is C<undef> by default.
3295  
3296 See also the L</max_size> option.
3297  
3298 my $p = HTTP::Promise->new( threshold => 512000 );
3299 $p->threshold(512000);
3300 my $limit = $p->threshold;
3301  
3302 =head2 timeout
3303  
3304 Integer. Sets the timeout value. Defaults to 180 seconds, i.e. 3 minutes.
3305  
3306 The request is aborted if no activity on the connection to the server is observed for C<timeout> seconds. When a request times out, a L<response object|HTTP::Promise::Response> is still returned. The response object will have a standard http status code of C<500>, i.e. server error. This response will have the C<Client-Warning> header set to the value of C<Internal response>.
3307  
3308 Returns a L<number object|Module::Generic::Number>
3309  
3310 my $p = HTTP::Promise->new( timeout => 10 );
3311 $p->timeout(10);
3312 my $timeout = $p->timeout;
3313  
3314 =head2 upgrade_insecure_requests
3315  
3316 This is an alias for L</auto_switch_https>
3317  
3318 =head2 uri_escape
3319  
3320 URI-escape the given string using L<URI::Escape::XS/uri_escape>
3321  
3322 =head2 uri_unescape
3323  
3324 URI-unescape the given string using L<URI::Escape::XS/uri_unescape>
3325  
3326 =head2 use_content_file
3327  
3328 Boolean. Enables or disables the use of a temporary file to store the response content. Defaults to false.
3329  
3330 When true, the response content will be stored into a temporary file, whose object is a L<Module::Generic::File> object and can be retrieved with L</file>.
3331  
3332 =head2 use_promise
3333  
3334 Boolean. When true, this will have L<HTTP::Promise> HTTP methods return a L<HTTP::Promise|promise>, and when false, it returns directly the L<HTTP::Promise::Response|response object>. Defaults to true.
3335  
3336 =head1 CLASS FUNCTIONS
3337  
3338 =head2 fetch
3339  
3340 This method can be exported, such as:
3341  
3342 use HTTP::Promise qw( fetch );
3343 my $prom = fetch( 'http://example.com/something.json' );
3344 # or
3345 fetch( 'http://example.com/something.json' )->then(sub
3346 {
3347 my( $resolve, $reject ) = @$_;
3348 my $resp = shift( @_ );
3349 my $data = $resp->decoded_content;
3350 })->then(sub
3351 {
3352 my $json = shift( @_ );
3353 print( STDOUT "JSON data:\n$json\n" );
3354 });
3355  
3356 You can also call it with an object, such as:
3357  
3358 my $http = HTTP::Promise->new;
3359 my $prom = $http->fetch( 'http://example.com/something.json' );
3360  
3361 C<fetch> performs the same way as L</get>, by default, and accepts the same possible parameters. It sets an error and returns C<undef> upon error, or return a L<promise|Promise::Me>
3362  
3363 However, if L</use_promise> is set to false, this will return an L<HTTP::Promise::Response> object directly.
3364  
3365 You can, however, specify, another method by providing the C<method> option with value being an HTTP method, i.e. C<DELETE>, C<GET>, C<HEAD>, C<OPTIONS>, C<PATCH>, C<POST>, C<PUT>.
3366  
3367 See also L<Mozilla documentation on fetch|https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch>
3368  
3369 =head1 THREAD-SAFETY
3370  
3371 This module is thread-safe for all operations, as it operates on per-object state and uses thread-safe external libraries.
3372  
3373 =head1 AUTHOR
3374  
3375 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
3376  
3377 =head1 CREDITS
3378  
3379 This module is inspired by the design and workflow of Gisle Aas and his implementation of L<HTTP::Message>, but built completely differently.
3380  
3381 L<HTTP::Promise::Entity> and L<HTTP::Promise::Body> have been inspired by Erik Dorfman (a.k.a. Eryq) and Dianne Skoll's implementation of L<MIME::Entity>
3382  
3383 =head1 BUGS
3384  
3385 You can report bugs at <https://gitlab.com/jackdeguest/HTTP-Promise/issues>
3386  
3387 =head1 SEE ALSO
3388  
3389 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>
3390  
3391 L<Promise::Me>, L<Cookie::Jar>, L<Module::Generic::File>, L<Module::Generic::Scalar>, L<Module::Generic>
3392  
3393 L<HTTP::XSHeaders>, L<File::MMagic::XS>, L<CryptX>, L<HTTP::Parser2::XS>, L<URI::Encode::XS>, L<URI::Escape::XS>, L<URL::Encode::XS>
3394  
3395 L<IO::Compress::Bzip2>, L<IO::Compress::Deflate>, L<IO::Compress::Gzip>, L<IO::Compress::Lzf>, L<IO::Compress::Lzip>, L<IO::Compress::Lzma>, L<IO::Compress::Lzop>, L<IO::Compress::RawDeflate>, L<IO::Compress::Xz>, L<IO::Compress::Zip>, L<IO::Compress::Zstd>
3396  
3397 L<rfc6266 on Content-Disposition|https://datatracker.ietf.org/doc/html/rfc6266>,
3398 L<rfc7230 on Message Syntax and Routing|https://tools.ietf.org/html/rfc7230>,
3399 L<rfc7231 on Semantics and Content|https://tools.ietf.org/html/rfc7231>,
3400 L<rfc7232 on Conditional Requests|https://tools.ietf.org/html/rfc7232>,
3401 L<rfc7233 on Range Requests|https://tools.ietf.org/html/rfc7233>,
3402 L<rfc7234 on Caching|https://tools.ietf.org/html/rfc7234>,
3403 L<rfc7235 on Authentication|https://tools.ietf.org/html/rfc7235>,
3404 L<rfc7578 on multipart/form-data|https://tools.ietf.org/html/rfc7578>,
3405 L<rfc7540 on HTTP/2.0|https://tools.ietf.org/html/rfc7540>
3406  
3407 =head1 COPYRIGHT & LICENSE
3408  
3409 Copyright (c) 2021 DEGUEST Pte. Ltd.
3410  
3411 You can use, copy, modify and redistribute this package and associated files under the same terms as Perl itself.
3412  
3413 =cut