blib/lib/HTTP/Promise/IO.pm untested

filter: Statementstmt 0.0% 0 / 554 Branchbran 0.0% 0 / 384 Conditioncond 0.0% 0 / 270 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 44 Podpod 0.0% 0 / 31 totaltotal 0.0% 0 / 1283 CC 193 SCAR 57.7
CC
193
Cov
0%
read_until
992.0
read
650.0
connect
380.0
CRAP 319.9
1 ##----------------------------------------------------------------------------
2 ## Asynchronous HTTP Request and Promise - ~/lib/HTTP/Promise/IO.pm
3 ## Version v0.1.1
4 ## Copyright(c) 2022 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2022/05/02
7 ## Modified 2025/10/12
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::IO;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'HTTP::Promise' );
20 use parent qw( Module::Generic );
21 use vars qw( $CRLF $IS_WIN32 $INIT_PARAMS $VERSION );
22 use Errno qw( EAGAIN ECONNRESET EINPROGRESS EINTR EWOULDBLOCK ECONNABORTED EISCONN );
23 use Fcntl qw( F_GETFL F_SETFL O_NONBLOCK O_RDONLY O_RDWR SEEK_SET SEEK_END );
24 use Socket qw(
25 PF_INET SOCK_STREAM
26 IPPROTO_TCP
27 TCP_NODELAY
28 pack_sockaddr_in
29 INADDR_ANY
30 );
31 use Time::HiRes qw( time );
32 use constant ERROR_EINTR => ( abs( Errno::EINTR ) * -1 );
33 our $CRLF = "\015\012";
34 our $IS_WIN32 = ( $^O eq 'MSWin32' );
35 # This is for connect() so it knows
36 our $INIT_PARAMS = [qw( buffer debug inactivity_timeout last_delimiter max_read_buffer ssl_opts stop_if timeout )];
37 our $VERSION = 'v0.1.1';
38 };
39  
40 use strict;
41 use warnings;
42  
43 sub init
44 {
45 my $self = shift( @_ );
46 return( $self->error( "No filehandle was provided." ) ) if( !scalar( @_ ) );
47 my $fh = shift( @_ );
48 return( $self->error( "Filehandle provided (", overload::StrVal( $fh ), ") is not a proper filehandle." ) ) if( !$self->_is_glob( $fh ) );
49 # This needs to be set to empty string and not undef to make chaining work with Module::Generic::Scalar
50 $self->{buffer} = '';
51 $self->{inactivity_timeout} = 600;
52 $self->{last_delimiter} = '';
53 $self->{max_read_buffer} = 0;
54 $self->{ssl_opts} = {};
55 $self->{stop_if} = sub{};
56 $self->{timeout} = 5;
57 $self->{_init_strict_use_sub} = 1;
58 $self->SUPER::init( @_ ) || return( $self->pass_error );
59 # Ensure O_NONBLOCK is set so that calls to select in can_read() would not report ok
60 # although no data is available. See select in perlfunc for more details.
61 my $dummy = '';
62 if( $self->_can( $fh => 'fcntl' ) )
63 {
64 my $flags = $fh->fcntl( F_GETFL, $dummy );
65 return( $self->error({ code => 500, message => "Unable to get flags from filehandle '$fh': $!" }) ) if( !defined( $flags ) );
66 my $rv = $fh->fcntl( F_SETFL, ( $flags | O_NONBLOCK ) );
67 return( $self->error({ code => 500, message => "Unable to set flags to filehandle '$fh': $!" }) ) if( !defined( $rv ) );
68 }
69 else
70 {
71 my $flags = fcntl( $fh, F_GETFL, $dummy );
72 return( $self->error({ code => 500, message => "Unable to get flags from filehandle '$fh': $!" }) ) if( !defined( $flags ) );
73 my $rv = fcntl( $fh, F_SETFL, ( $flags | O_NONBLOCK ) );
74 return( $self->error({ code => 500, message => "Unable to set flags to filehandle '$fh': $!" }) ) if( !defined( $rv ) );
75 }
76 $self->{_fh} = $fh;
77 return( $self );
78 }
79  
80 sub buffer { return( shift->_set_get_scalar_as_object( 'buffer', @_ ) ); }
81  
82 sub can_read
83 {
84 my $self = shift( @_ );
85 my $fh = $self->filehandle;
86 my $opts = $self->_get_args_as_hash( @_ );
87 return(1) unless( defined( fileno( $fh ) ) );
88 return(1) if( $fh->isa( 'IO::Socket::SSL' ) && $fh->pending );
89 return(1) if( $fh->isa( 'Net::SSL' ) && $fh->can('pending') && $fh->pending );
90
91 # If this is an in-memory scalar filehandle
92 # check that it is opened so we can read from it
93 if( fileno( $fh ) == -1 )
94 {
95 if( $self->_can( $fh => 'can_read' ) )
96 {
97 return( $fh->can_read );
98 }
99 else
100 {
101 my( $dummy, $flags );
102 if( $self->_can( $fh => 'fcntl' ) )
103 {
104 $flags = $fh->fcntl( F_GETFL, $dummy );
105 }
106 else
107 {
108 $flags = fcntl( $fh, F_GETFL, $dummy );
109 }
110 return( $self->error({ code => 500, message => "Unable to get flags from filehandle '$fh': $!" }) ) if( !defined( $flags ) );
111 return( ( $flags == O_RDONLY ) || ( $flags & ( O_RDONLY | O_RDWR ) ) );
112 }
113 }
114  
115 # With no timeout, wait forever. An explicit timeout of 0 can be used to just check
116 # if the socket is readable without waiting.
117 my $timeout = $opts->{timeout} ? $opts->{timeout} : $self->timeout;
118  
119 my $fbits = '';
120 vec( $fbits, fileno( $fh ), 1 ) = 1;
121 SELECT:
122 {
123 my $before;
124 $before = time() if( $timeout );
125 my $nfound = select( $fbits, undef, undef, $timeout );
126 if( $nfound < 0 )
127 {
128 if( $!{EINTR} || $!{EAGAIN} || $!{EWOULDBLOCK} )
129 {
130 # don't really think EAGAIN/EWOULDBLOCK can happen here
131 if( $timeout )
132 {
133 $timeout -= time() - $before;
134 $timeout = 0 if( $timeout < 0 );
135 }
136 redo( SELECT );
137 }
138 return( $self->error({ code => 500, message => "select failed: $!" }) );
139 }
140 return( $nfound > 0 );
141 }
142 }
143  
144 sub close
145 {
146 my $self = shift( @_ );
147 my $fh = $self->filehandle;
148 $fh->close if( $self->_can( $fh, 'close' ) );
149 $self->filehandle( undef );
150 $self->DESTROY;
151 }
152  
153 sub connect
154 {
155 my $self = shift( @_ );
156 my $opts = $self->_get_args_as_hash( @_ );
157 my $host = $opts->{host} || return( $self->error( "No host to connect to was provided." ) );
158 my $port = $opts->{port} || return( $self->error( "No port to connect to was provided." ) );
159 return( $self->error( "Port provided ($port) is not a number" ) ) if( $port !~ /^\d+$/ );
160 return( $self->error( "No timeout was provided to connect." ) ) if( !exists( $opts->{timeout} ) || !length( $opts->{timeout} ) );
161 my $sock;
162  
163 my $stop_if = $self->_is_code( $opts->{stop_if} ) ? $opts->{stop_if} : sub{};
164 $opts->{stop_if} = $stop_if;
165 my $timeout = $opts->{timeout};
166 local $@;
167 my $sock_addr = eval
168 {
169 local $SIG{ALRM} = sub{ die( "timeout\n" ); };
170 alarm( $timeout ) if( defined( $timeout ) && $timeout > 0 );
171 my $ipbin = Socket::inet_aton( $host ) ||
172 return( $self->error( "Cannot resolve host name: ${host} (port: ${port}): $!" ) );
173 Socket::pack_sockaddr_in( $port, $ipbin );
174 };
175 alarm(0);
176 unless( $sock_addr )
177 {
178 return( $self->error( "Cannot resolve host name: ${host} (port: ${port}): $!" ) );
179 }
180 return( $self->error( "Failed to resolve host name '$host': timeout" ) ) if( $@ =~ /timeout/i );
181
182 my( $lport, $laddr );
183 $lport = $opts->{local_port} if( exists( $opts->{local_port} ) && defined( $opts->{local_port} ) );
184 $laddr = defined( $opts->{local_host} )
185 ? Socket::inet_aton( $opts->{local_host} )
186 : INADDR_ANY;
187 return( $self->error( "Bad local host provided \"$opts->{local_host}\": $!" ) ) if( !defined( $laddr ) );
188
189 if( defined( $lport ) ||
190 ( $laddr ne INADDR_ANY ) )
191 {
192 my $local_sock_addr = Socket::pack_sockaddr_in( ( $lport // 0 ), $laddr ) ||
193 return( $self->error( "Cannot resolve local host: $opts->{local_host} (port: $opts->{local_port}): $!" ) );
194 CORE::bind( $sock, $local_sock_addr ) || do
195 {
196 if( $laddr ne INADDR_ANY )
197 {
198 return( $self->error( "Unable to bind to local host \"$opts->{local_host}\": $!" ) );
199 }
200 else
201 {
202 return( $self->error( "Unable to bind to local port \"$opts->{local_port}\": $!" ) );
203 }
204 };
205 }
206  
207 RETRY:
208 CORE::socket( $sock, Socket::sockaddr_family( $sock_addr ), SOCK_STREAM, 0 ) ||
209 return( $self->error( "Unable to create socket: $!" ) );
210 $self->_set_sockopts( $sock ) || return( $self->pass_error );
211 my $params = {};
212 if( $self->_is_array( $INIT_PARAMS ) )
213 {
214 for( @$INIT_PARAMS )
215 {
216 $params->{ $_ } = $opts->{ $_ } if( exists( $opts->{ $_ } ) );
217 }
218 }
219 my $new = $self->new( $sock, $params ) || return( $self->pass_error );
220 if( CORE::connect( $sock, $sock_addr ) )
221 {
222 # connected
223 }
224 elsif( $! == EINPROGRESS || ( $IS_WIN32 && $! == EWOULDBLOCK ) )
225 {
226 my $rv = $new->make_select_timeout( write => 1, timeout => $opts->{timeout} );
227 return( $self->error( "Cannot connect to ${host}:${port}: ", $new->error->message ) ) if( !defined( $rv ) );
228 return( $self->error( "Select timeout on socket." ) ) if( !$rv );
229 }
230 # connected
231 else
232 {
233 if( $! == EINTR && !$stop_if->() )
234 {
235 CORE::close( $sock );
236 goto( RETRY );
237 }
238 return( $self->error( "Cannot connect to ${host}:${port}: $!" ) );
239 }
240 return( $new );
241 }
242  
243 # connect SSL socket.
244 # You can override this method in your child class, if you want to use Crypt::SSLeay or some other library.
245 # Returns file handle like object
246 sub connect_ssl
247 {
248 my $self = shift( @_ );
249 my $opts = $self->_get_args_as_hash( @_ );
250 my $host = $opts->{host} || return( $self->error( "No host to connect to was provided." ) );
251 my $port = $opts->{port} || return( $self->error( "No port to connect to was provided." ) );
252 return( $self->error( "Port provided ($port) is not a number" ) ) if( $port !~ /^\d+$/ );
253 return( $self->error( "No timeout was provided to connect." ) ) if( !exists( $opts->{timeout} ) || !length( $opts->{timeout} ) );
254
255 $self->_load_class( 'IO::Socket::SSL' ) || return( $self->pass_error );
256  
257 my $params = {};
258 if( $self->_is_array( $INIT_PARAMS ) )
259 {
260 for( @$INIT_PARAMS )
261 {
262 $params->{ $_ } = $opts->{ $_ } if( exists( $opts->{ $_ } ) );
263 }
264 }
265 $params->{host} = $host;
266 $params->{port} = $port;
267 my $new = $self->connect( %$params ) ||
268 return( $self->pass_error );
269 my $sock = $new->filehandle;
270  
271 my $timeout = $opts->{timeout} // $self->timeout // 5;
272 # my $timeout = ( $opts->{timeout} - time() );
273 # return( $self->error( "Cannot create SSL connection: timeout" ) ) if( $timeout <= 0 );
274  
275 my $ssl_opts = $new->_ssl_opts;
276 if( !IO::Socket::SSL->start_SSL(
277 $sock,
278 PeerHost => $host,
279 PeerPort => $port,
280 Timeout => $timeout,
281 ( defined( $opts->{local_host} ) ? ( LocalHost => $opts->{local_host} ) : () ),
282 ( defined( $opts->{local_port} ) ? ( LocalPort => $opts->{local_port} ) : () ),
283 %$ssl_opts,
284 ) )
285 {
286 return( $self->error( "Cannot create SSL connection: ", IO::Socket::SSL::errstr() ) );
287 }
288 $new->_set_sockopts( $sock );
289 return( $new );
290 }
291  
292 sub connect_ssl_over_proxy
293 {
294 my $self = shift( @_ );
295 my $opts = $self->_get_args_as_hash( @_ );
296 my $proxy_host = $opts->{proxy_host} || return( $self->error( "No proxy host to connect to was provided." ) );
297 my $proxy_port = $opts->{proxy_port} || return( $self->error( "No proxy port to connect to was provided." ) );
298 my $host = $opts->{host} || return( $self->error( "No host to connect to was provided." ) );
299 my $port = $opts->{port} || return( $self->error( "No port to connect to was provided." ) );
300 return( $self->error( "Proxy port provided ($proxy_port) is not a number" ) ) if( $proxy_port !~ /^\d+$/ );
301 return( $self->error( "Host port provided ($port) is not a number" ) ) if( $port !~ /^\d+$/ );
302 return( $self->error( "Port provided ($port) is not a number" ) ) if( $port !~ /^\d+$/ );
303 return( $self->error( "No timeout was provided to connect." ) ) if( !exists( $opts->{timeout} ) || !length( $opts->{timeout} ) );
304 my $proxy_authorization = $opts->{proxy_authorization};
305 $self->_load_class( 'IO::Socket::SSL' ) || return( $self->pass_error );
306  
307 my $params = {};
308 if( $self->_is_array( $INIT_PARAMS ) )
309 {
310 for( @$INIT_PARAMS )
311 {
312 $params->{ $_ } = $opts->{ $_ } if( exists( $opts->{ $_ } ) );
313 }
314 }
315 $params->{host} = $proxy_host;
316 $params->{port} = $proxy_port;
317 my $new = $self->connect( %$params ) ||
318 return( $self->pass_error );
319 my $sock = $new->filehandle;
320  
321 my $p = "CONNECT ${host}:${port} HTTP/1.0${CRLF}Server: ${host}${CRLF}";
322 if( defined( $proxy_authorization ) )
323 {
324 $p .= "Proxy-Authorization: ${proxy_authorization}${CRLF}";
325 }
326 $p .= $CRLF;
327 $new->_write_all( $sock, $p, $opts->{timeout} ) ||
328 return( $self->error({
329 code => 500,
330 message => "Failed to send HTTP request to proxy: " . ( $! != 0 ? "$!" : 'timeout' )
331 }) );
332 my $buf = '';
333 my $read = $new->read( \$buf, $new->buffer_size, length( $buf ), $opts->{timeout} );
334 if( !defined( $read ) )
335 {
336 return( $self->error( "Cannot read proxy response: " . ( $! != 0 ? "$!" : 'timeout' ) ) );
337 }
338 # eof
339 elsif( $read == 0 )
340 {
341 return( $self->error( "Unexpected EOF while reading proxy response" ) );
342 }
343 elsif( $buf !~ /^HTTP\/1\.[0-9] 200 .+\015\012/ )
344 {
345 return( $self->error( "Invalid HTTP Response via proxy" ) );
346 }
347  
348 my $timeout = ( $opts->{timeout} - time() );
349 return( $self->error( "Cannot start SSL connection: timeout" ) ) if( $opts->{timeout} <= 0 );
350  
351 my $ssl_opts = $new->_ssl_opts;
352 unless( exists( $ssl_opts->{SSL_verifycn_name} ) )
353 {
354 $ssl_opts->{SSL_verifycn_name} = $host;
355 }
356 IO::Socket::SSL->start_SSL(
357 $sock,
358 PeerHost => "$host",
359 PeerPort => "$port",
360 Timeout => "$timeout",
361 ( defined( $opts->{local_host} ) ? ( LocalHost => $opts->{local_host} ) : () ),
362 ( defined( $opts->{local_port} ) ? ( LocalPort => $opts->{local_port} ) : () ),
363 %$ssl_opts
364 ) or return( $self->error( "Cannot start SSL connection: " . IO::Socket::SSL::errstr() ) );
365 $new->_set_sockopts( $sock );
366 return( $new );
367 }
368  
369 sub filehandle { return( shift->_set_get_glob( '_fh', @_ ) ); }
370  
371 # Credits: Olaf Alders in Net::HTTP
372 sub getline
373 {
374 my $self = shift( @_ );
375 my $opts = $self->_get_args_as_hash( @_ );
376 $opts->{chomp} = 0 if( !CORE::exists( $opts->{chomp} ) );
377 $opts->{max_read_buffer} = 0;
378 my $fh = $self->filehandle || return( $self->error( "No filehandle currently set." ) );
379 my $buff = $self->buffer;
380 my $max = $opts->{max_read_buffer} || $self->max_read_buffer;
381 my $pos;
382 my $is_object = $self->_can( $fh => 'sysread' ) ? 1 : 0;
383 while(1)
384 {
385 # Get the position of line ending. \015 might not be there, but \012 will
386 $pos = $buff->index( "\012" );
387 last if( $pos >= 0 );
388 # 413 Entity too large
389 return( $self->error({ code => 413, message => "Line too long (limit is $max)" }) ) if( $max && $buff->length > $max );
390 # need to read more data to find a line ending
391 my $new_bytes = 0;
392 READ:
393 {
394 my $rv = $self->can_read;
395 return( $self->pass_error ) if( !defined( $rv ) );
396 return( $self->error( "Cannot read from filehandle '$fh'" ) ) if( !$rv );
397 # consume all incoming bytes
398 my $bytes_read = $is_object
399 ? $fh->sysread( $$buff, 1024, $buff->length )
400 : sysread( $fh, $$buff, 1024, $buff->length );
401 if( defined( $bytes_read ) )
402 {
403 $new_bytes += $bytes_read;
404 }
405 elsif( $!{EINTR} || $!{EAGAIN} || $!{EWOULDBLOCK} )
406 {
407 redo READ;
408 }
409 else
410 {
411 $self->mesage( 4, "$bytes_read bytes read from filehandle '$fh' with total read so far of ", $buff->length );
412 # if we have already accumulated some data let's at
413 # least return that as a line
414 $buff->length or return( $self->error( "read() failed: $!" ) );
415 }
416 # no line-ending, no new bytes
417 return(
418 $buff->length
419 ? $buff->substr( 0, $buff->length, '' )
420 # : undef
421 : ''
422 ) if( $new_bytes == 0 );
423 };
424 }
425 return( $self->error( "Line too long ($pos; limit is $max)" ) ) if( $max && $pos > $max );
426 my $line = $buff->substr( 0, $pos + 1, '' );
427 # $line =~ s/(\015?\012)\z// || return( $self->error( 'No end-of-line found' ) );
428 # return( wantarray() ? ($line, $1) : $line;
429 $$line =~ s/(\015?\012)\z// if( $opts->{chomp} );
430 return( $$line );
431 }
432  
433 sub inactivity_timeout { return( shift->_set_get_number_as_scalar( 'inactivity_timeout', @_ ) ); }
434  
435 sub last_delimiter { return( shift->_set_get_scalar_as_object( 'last_delimiter', @_ ) ); }
436  
437 sub make_select
438 {
439 my $self = shift( @_ );
440 my $opts = $self->_get_args_as_hash( @_ );
441 my $fh = $self->filehandle || return( $self->error( "No filehandle set to read from." ) );
442 my $timeout = $opts->{timeout} // $self->timeout;
443 return( $self->error( 'No timeout was provided.' ) ) if( !defined( $timeout ) );
444 my $is_write = $opts->{write} ? 1 : 0;
445 my( $rfd, $wfd );
446 my $efd = '';
447 vec( $efd, fileno( $fh ), 1 ) = 1;
448 if( $is_write )
449 {
450 $wfd = $efd;
451 }
452 else
453 {
454 $rfd = $efd;
455 }
456 my $nfound = select( $rfd, $wfd, $efd, $timeout );
457 return( $self->error( $! ) ) if( $nfound < 0 && $! );
458 return( $nfound );
459 }
460  
461 # returns true if the socket is ready to read, false if timeout has occurred ($! will be cleared upon timeout)
462 sub make_select_timeout
463 {
464 my $self = shift( @_ );
465 my $opts = $self->_get_args_as_hash( @_ );
466 my $is_write = $opts->{write} ? 1 : 0;
467 my $fh = $self->filehandle || return( $self->error( "No filehandle currently set." ) );
468 my $timeout;
469 $timeout = $opts->{timeout} if( exists( $opts->{timeout} ) && length( $opts->{timeout} ) );
470 $timeout //= $self->timeout;
471 my $timeout_at = time() + $timeout;
472 return( $self->error( "No timeout option was provided nor is it defined with timeout()." ) ) if( !defined( $timeout ) );
473 # Time::HiRes time()
474 my $now = time();
475 my $inactivity_timeout = $self->inactivity_timeout // $opts->{inactivity_timeout} // 600;
476 my $inactivity_timeout_at = ( $now + $inactivity_timeout );
477 $self->message( 4, "Setting timeout_at to $inactivity_timeout_at (${inactivity_timeout_at} [", scalar( localtime( $inactivity_timeout_at ) ), "]) ? ", ( $timeout_at > $inactivity_timeout_at ? 'yes' : 'no' ) );
478 $timeout_at = $inactivity_timeout_at if( $timeout_at > $inactivity_timeout_at );
479 my $stop_if = $self->stop_if;
480 # wait for data
481 while(1)
482 {
483 my $timeout2 = ( $timeout_at - $now );
484 if( $timeout2 <= 0 )
485 {
486 $! = 0;
487 return(0);
488 }
489 my $nfound = $self->make_select( write => $is_write, timeout => $timeout2 );
490 return( $self->pass_error ) if( !defined( $nfound ) );
491 return(1) if( $nfound > 0 );
492 return(0) if( $nfound == -1 && $! == EINTR && $stop_if->() );
493 # Time::HiRes time()
494 $now = time();
495 }
496 return( $self->error( 'Error checking for readiness of socket. Should not get here.' ) );
497 }
498  
499 # Maximum size of read buffer, beyond which, if still nothing is found, then we give up
500 sub max_read_buffer { return( shift->_set_get_number_as_scalar( 'max_read_buffer', @_ ) ); }
501  
502 sub print { return( defined( shift->write( @_ ) ) ? 1 : 0 ); }
503  
504 sub read
505 {
506 my $self = $_[0];
507 return( $self->error({ code => 500, message => "Wrong number of arguments. Usage: \$reader->read( \$buffer, \$length, \$offset )" }) ) unless( @_ > 2 && @_ < 5 );
508 my $len = $_[2];
509 return( $self->error( "Length provided (${len}) is not a positive integer." ) ) if( !defined( $len ) || $len !~ /^\d+$/ );
510 my $off = $_[3];
511 return( $self->error( "Offset provided (${off}) is not an integer." ) ) if( defined( $off ) && $off !~ /^-?\d+$/ );
512 my $is_scalar = $self->_is_scalar( $_[1] ) ? 1 : 0;
513 return( $self->error( "scalar provided as first argument to read() is a reference (", overload::StrVal( $_[1] ), "). You need to first dereference it." ) ) if( ref( $_[1] ) && !$is_scalar );
514 $off //= 0;
515 my $fh = $self->filehandle || return( $self->error( "No filehandle set to read from." ) );
516 my $buff = $self->buffer;
517 my $buff_len = $buff->length->scalar;
518 my $is_object = $self->_can( $fh => 'sysread' ) ? 1 : 0;
519 my $stop_if = $self->stop_if;
520
521 my $sysread = sub
522 {
523 while(1)
524 {
525 my $n = $is_object
526 ? $fh->sysread( $_[0], $_[1], ( @_ > 2 ? $_[2] : () ) )
527 : sysread( $fh, $_[0], $_[1], ( @_ > 2 ? $_[2] : () ) );
528 if( defined( $n ) )
529 {
530 return( $n );
531 }
532
533 if( $! == EAGAIN || $! == EWOULDBLOCK || ( $IS_WIN32 && $! == EISCONN ) )
534 {
535 # passthru
536 }
537 elsif( $! == EINTR )
538 {
539 return( $self->error({ code => $!+0, message => "Received interruption signal: $!" }) ) if( $stop_if->() );
540 # otherwise passthru
541 }
542 else
543 {
544 return( $self->error({ code => $!+0, message => "Unable to read from filehandle: $!" }) );
545 }
546 # on EINTER/EAGAIN/EWOULDBLOCK
547 my $rv = $self->make_select_timeout( write => 0 );
548 return( $self->pass_error ) if( !defined( $rv ) );
549 return( $self->error( "Timeout. Unable to select the filehandle." ) ) if( !$rv );
550 }
551 };
552
553 if( $buff_len )
554 {
555 # if our buffer is less than that is required, attempt to read the difference from the filehandle
556 if( $buff_len < $len )
557 {
558 return( $self->pass_error ) unless( defined( $self->can_read ) );
559 my $n = $sysread->( $$buff, ( $len - $buff_len ), $buff_len );
560 return( $self->pass_error ) if( !defined( $n ) );
561 }
562
563 # What we will return
564 my $bytes = ( $buff->length > $len ? $len : $buff->length );
565 # "A positive OFFSET greater than the length of SCALAR results in the string being
566 # padded to the required size with "\0" bytes before the result of the read is
567 # appended."
568 # (perlfunc)
569 if( $is_scalar )
570 {
571 if( $off > length( $$_[1] ) )
572 {
573 $$_[1] .= \0 x ( $off - length( $$_[1] ) );
574 }
575 substr( $$_[1], $off, 0, $buff->substr( 0, $bytes, '' )->scalar );
576 # Truncate
577 substr( $$_[1], ( $off + $bytes ), length( $$_[1] ), '' );
578 }
579 else
580 {
581 if( $off > length( $_[1] ) )
582 {
583 $_[1] .= \0 x ( $off - length( $_[1] ) );
584 }
585 substr( $_[1], $off, 0, $buff->substr( 0, $bytes, '' )->scalar );
586 # Truncate
587 substr( $_[1], ( $off + $bytes ), length( $_[1] ), '' );
588 }
589 return( $bytes );
590 }
591 else
592 {
593 return( $sysread->( $_[1], $len, ( defined( $off ) ? $off : () ) ) );
594 }
595 }
596  
597 sub read_until
598 {
599 my $self = $_[0];
600 return( $self->error({ code => 500, message => "Wrong number of arguments. Usage: \$reader->read_until( \$buffer, \$length, \$offset, { string => 'something', exclude => 1, include => 1, chunk_size => 2048 } )" }) ) unless( @_ > 2 );
601 my $len = $_[2];
602 return( $self->error( "Length provided (${len}) is not an integer." ) ) if( $len !~ /^\d+$/ );
603 return( $self->error( "scalar provided as first argument to read_until() is a reference (", overload::StrVal( $_[1] ), "). You need to first dereference it." ) ) if( ref( $_[1] ) );
604 my $off = ( $_[3] =~ /^\-?\d+$/ ? $_[3] : 0 );
605 my $opts = {};
606 $opts = $_[-1] if( ref( $_[-1] ) eq 'HASH' );
607 my $what = $opts->{string};
608 return( $self->error({ code => 500, message => "Nothing was provided to look for." }) ) if( !defined( $what ) || !CORE::length( $what ) );
609 $what = qr/\Q${what}\E/ unless( ref( $what ) eq 'Regexp' );
610 my $fh = $self->filehandle || return( $self->error( "No filehandle set to read from." ) );
611 $opts->{ignore} //= 0;
612 $opts->{exclude} = 0 if( !exists( $opts->{exclude} ) );
613 $opts->{inlude} = !$opts->{exclude} if( !exists( $opts->{include} ) );
614 # Should we capture the delimiter?
615 # This is useful for debugging, or in case of boundary for HTTP message multipart to know
616 # if we have reached the trailing delimiter for example.
617 $opts->{capture} //= 0;
618 my $re;
619 if( $opts->{ignore} )
620 {
621 $re = $opts->{capture} ? qr/(.*?)(?<__reader_delimiter>${what})/s : qr/(.*?)${what}/s;
622 }
623 elsif( $opts->{include} )
624 {
625 $re = $opts->{capture} ? qr/((?:.*?)(?<__reader_delimiter>${what}))/s : qr/((?:.*?)${what})/s;
626 }
627 else
628 {
629 $re = qr/(.*?)(?=${what})/s;
630 }
631 my $chunk_size = $opts->{chunk_size} // 2048;
632 $chunk_size = $len if( $len > $chunk_size );
633 my $buff = $self->buffer;
634 my $n = -1;
635 my $sliding_buffer_size = $chunk_size * 2;
636 my $is_object = $self->_can( $fh => 'sysread' ) ? 1 : 0;
637 my $buff_len = $buff->length->scalar;
638 my $stop_if = $self->stop_if;
639 if( !$buff_len || $$buff !~ /$re/ )
640 {
641 if( $buff_len < $sliding_buffer_size )
642 {
643 return( $self->pass_error ) unless( defined( $self->can_read ) );
644 while(1)
645 {
646 my $n = $is_object
647 ? $fh->sysread( $$buff, ( $sliding_buffer_size - $buff_len ), $buff_len )
648 : sysread( $fh, $$buff, ( $sliding_buffer_size - $buff_len ), $buff_len );
649 if( !defined( $n ) )
650 {
651 if( $! == EAGAIN || $! == EWOULDBLOCK || ( $IS_WIN32 && $! == EISCONN ) )
652 {
653 # passthru
654 }
655 elsif( $! == EINTR )
656 {
657 return( $self->error({ code => $!+0, message => "Received interruption signal: $!" }) ) if( $stop_if->() );
658 # otherwise passthru
659 }
660 else
661 {
662 return( $self->error({ code => $!+0, message => "Unable to read from filehandle: $!" }) );
663 }
664 # on EINTER/EAGAIN/EWOULDBLOCK
665 my $rv = $self->make_select_timeout( write => 0 );
666 return( $self->pass_error ) if( !defined( $rv ) );
667 return( $self->error( "Unable to select the filehandle." ) ) if( !$rv );
668 }
669 # 0, meaning there is no more data to read
670 # If our buffer still has some data, we'll return whatever we have left
671 elsif( !$n && $buff->is_empty )
672 {
673 return( $n );
674 }
675 else
676 {
677 last;
678 }
679 }
680 }
681 }
682
683 $_[1] //= '';
684 # "A positive OFFSET greater than the length of SCALAR results in the string being
685 # padded to the required size with "\0" bytes before the result of the read is
686 # appended."
687 # (perlfunc)
688 if( $off > length( $_[1] ) )
689 {
690 $_[1] .= \0 x ( $off - length( $_[1] ) );
691 }
692
693 if( $$buff =~ s/^$re// )
694 {
695 my $trail = $1;
696 if( exists( $+{__reader_delimiter} ) )
697 {
698 $self->last_delimiter( $+{__reader_delimiter} );
699 }
700 else
701 {
702 $self->last_delimiter->reset;
703 }
704 my $bytes = length( $trail );
705 substr( $_[1], $off, 0, $trail );
706 # Truncate
707 substr( $_[1], ( $off + $bytes ), length( $_[1] ), '' );
708 # < 0 means in our API there is a match and this is what was returned.
709 # The caller can simply use abs() to get the bytes value.
710 # 0 means no more data, and
711 # undef means there is an error
712 # > 0 is returned when no match was found, but only data
713 return( $bytes * -1 );
714 }
715 else
716 {
717 my $bytes = $buff->length > $len ? $len : $buff->length;
718 substr( $_[1], $off, 0, $buff->substr( 0, $bytes, '' ) );
719 # Truncate
720 substr( $_[1], ( $off + $bytes ), length( $_[1] ), '' );
721 return( $bytes );
722 }
723 }
724  
725 sub read_until_in_memory
726 {
727 my $self = shift( @_ );
728 my $what = shift( @_ );
729 my $opts = $self->_get_args_as_hash( @_ );
730 return( $self->error({ code => 500, message => "Nothing was provided to look for." }) ) if( !defined( $what ) || !CORE::length( $what ) );
731 $what = qr/\Q${what}\E/ unless( ref( $what ) eq 'Regexp' );
732 $opts->{ignore} //= 0;
733 $opts->{exclude} = 0 if( !exists( $opts->{exclude} ) );
734 $opts->{inlude} = !$opts->{exclude} if( !exists( $opts->{include} ) );
735 # Should we capture the delimiter?
736 # This is useful for debugging, or in case of boundary for HTTP message multipart to know
737 # if we have reached the trailing delimiter for example.
738 $opts->{capture} //= 0;
739 my $re;
740 if( $opts->{ignore} )
741 {
742 $re = $opts->{capture} ? qr/(.*?)(?<__reader_delimiter>${what})/s : qr/(.*?)${what}/s;
743 }
744 elsif( $opts->{include} )
745 {
746 $re = $opts->{capture} ? qr/((?:.*?)(?<__reader_delimiter>${what}))/s : qr/((?:.*?)${what})/s;
747 }
748 else
749 {
750 $re = qr/(.*?)(?=${what})/s;
751 }
752 my $chunk_size = $opts->{chunk_size} // 2048;
753 my $max = $self->max_read_buffer;
754 my $buff = '';
755 # Make an initial read to get whatever is in the internal buffer
756 # Maybe that is sufficient to satisfy the regular expression need
757 if( my $buff_len = $self->buffer->length )
758 {
759 my $bytes = $self->read( $buff, $buff_len );
760 return( $self->pass_error ) if( !defined( $bytes ) );
761 }
762  
763 while( $buff !~ /$re/ )
764 {
765 my $n = $self->read( $buff, $chunk_size, CORE::length( $buff ) );
766 return( $self->pass_error ) if( !defined( $n ) );
767 return( '' ) if( !$n );
768
769 if( $max && CORE::length( $buff ) > $max )
770 {
771 $self->unread( $buff );
772 return( $self->error({ code => 413, message => "Maximum read buffer limit ($max) reached." }) );
773 }
774 }
775 if( $buff =~ s/^$re// )
776 {
777 my $match = $1;
778 if( exists( $+{__reader_delimiter} ) )
779 {
780 $self->last_delimiter( $+{__reader_delimiter} );
781 }
782 else
783 {
784 $self->last_delimiter->reset;
785 }
786 $self->unread( $buff );
787 return( $match );
788 }
789 else
790 {
791 }
792 $self->unread( $buff );
793 return( '' );
794 }
795  
796 # NOTE: request parameter
797 sub ssl_opts { return( shift->_set_get_hash_as_mix_object( 'ssl_opts', @_ ) ); }
798  
799 sub stop_if { return( shift->_set_get_code( 'stop_if', @_ ) ); }
800  
801 # sub timeout { return( shift->_set_get_number_as_scalar( 'timeout', @_ ) ); }
802 sub timeout
803 {
804 my $self = shift( @_ );
805 $self->{timeout} = shift( @_ ) if( @_ );
806 return( $self->{timeout} );
807 }
808  
809 sub unread
810 {
811 my $self = shift( @_ );
812 my $buff = $self->buffer;
813 if( $buff->is_empty )
814 {
815 $buff->set( shift( @_ ) );
816 }
817 else
818 {
819 $buff->prepend( shift( @_ ) );
820 }
821 return( $self );
822 }
823  
824 # returns (positive) number of bytes written, or undef if the filehandle is to be closed
825 sub write
826 {
827 my $self = $_[0];
828 return( $self->error( "Invalid number of arguments. Usage: \$self->write( \$buffer, \$length, \$offset )" ) ) unless( @_ > 1 && @_ < 6 );
829 # Buffer is #1
830 my $len = @_ > 2 ? $_[2] : length( $_[1] );
831 my $off = @_ > 3 ? $_[3] : 0;
832 my $timeout = @_ > 4 ? $_[4] : $self->timeout;
833 my $fh = $self->filehandle || return( $self->error( "No filehandle set to read from." ) );
834 my $is_object = $self->_can( $fh => 'syswrite' ) ? 1 : 0;
835 while(1)
836 {
837 my $bytes = $is_object
838 ? $fh->syswrite( $_[1], $len, $off )
839 : syswrite( $fh, $_[1], $len, $off );
840 if( defined( $bytes ) )
841 {
842 return( $bytes );
843 }
844 if( $! == EAGAIN || $! == EWOULDBLOCK || ( $IS_WIN32 && $! == EISCONN ) )
845 {
846 # passthru
847 }
848 # Could not write because of an interruption
849 elsif( $! == EINTR )
850 {
851 return( $self->error({ code => ERROR_EINTR, message => "Interruption prevented writing to filehandle '$fh': $!" }) ) if( $self->stop_if->() );
852 # otherwise passthru
853 }
854 else
855 {
856 return( $self->error( "Error writing ${len} bytes at offset ${off} from buffer (size: ", length( $_[2] ), " bytes) to filehandle '$fh': $!" ) );
857 }
858 my $rv = $self->make_select_timeout( write => 1, timeout => $timeout );
859 return( $self->pass_error ) if( !defined( $rv ) );
860 return( $self->error( "Unable to select the filehandle." ) ) if( !$rv );
861 }
862 }
863  
864 sub write_all
865 {
866 my $self = $_[0];
867 return( $self->error( "Invalid number of arguments. Usage: \$self->_write_all( \$buffer )" ) ) unless( @_ > 1 && @_ < 4 );
868 # Buffer is #1
869 my $timeout = @_ > 2 ? $_[2] : $self->timeout;
870 my $off = 0;
871 while( my $len = length( $_[1] ) - $off )
872 {
873 my $bytes = $self->write( $_[1], $len, $off, $timeout );
874 return( $self->pass_error ) if( !defined( $bytes ) );
875 return( $bytes ) if( !$bytes );
876 $off += $bytes;
877 # Should never happen
878 last if( $len < 0 );
879 }
880 # Return total bytes sent
881 return( $off );
882 }
883  
884 sub _set_sockopts
885 {
886 my $self = shift( @_ );
887 my $sock = shift( @_ ) ||
888 return( $self->error( "No socket was provided." ) );
889  
890 setsockopt( $sock, IPPROTO_TCP, TCP_NODELAY, 1 ) or
891 return( $self->error( "Failed to setsockopt(TCP_NODELAY): $!" ) );
892 if( $IS_WIN32 )
893 {
894 if( ref( $sock ) ne 'IO::Socket::SSL' )
895 {
896 my $tmp = 1;
897 ioctl( $sock, 0x8004667E, \$tmp ) or
898 return( $self->error( "Cannot set flags for the socket: $!" ) );
899 }
900 }
901 else
902 {
903 my $flags = fcntl( $sock, F_GETFL, 0 ) or
904 return( $self->error( "Cannot get flags for the socket: $!" ) );
905 $flags = fcntl( $sock, F_SETFL, $flags | O_NONBLOCK ) or
906 return( $self->error( "Cannot set flags for the socket: $!" ) );
907 }
908  
909 {
910 # no buffering
911 my $orig = select();
912 select( $sock ); $| = 1;
913 select( $orig );
914 }
915 binmode( $sock );
916 return( $sock );
917 }
918  
919 sub _ssl_opts
920 {
921 my $self = shift( @_ );
922 my $ssl_opts = $self->ssl_opts;
923 unless( exists( $ssl_opts->{SSL_verify_mode} ) )
924 {
925 if( exists( $ssl_opts->{verify_hostname} ) &&
926 !$ssl_opts->{verify_hostname} )
927 {
928 $ssl_opts->{SSL_verify_mode} = IO::Socket::SSL::SSL_VERIFY_NONE();
929 }
930 else
931 {
932 # set SSL_VERIFY_PEER as default.
933 $ssl_opts->{SSL_verify_mode} = IO::Socket::SSL::SSL_VERIFY_PEER();
934 }
935 unless( exists( $ssl_opts->{SSL_verifycn_scheme} ) )
936 {
937 $ssl_opts->{SSL_verifycn_scheme} = 'www'
938 }
939 }
940 if( $ssl_opts->{SSL_verify_mode} )
941 {
942 unless( exists( $ssl_opts->{SSL_ca_file} ) || exists( $ssl_opts->{SSL_ca_path} ) )
943 {
944 $self->_load_class( 'Mozilla::CA' ) || return( $self->pass_error );
945 $ssl_opts->{SSL_ca_file} = Mozilla::CA::SSL_ca_file();
946 }
947 }
948 return( $ssl_opts );
949 }
950  
951 sub FREEZE
952 {
953 my $self = CORE::shift( @_ );
954 my $serialiser = CORE::shift( @_ ) // '';
955 my $class = CORE::ref( $self );
956 my %hash = %$self;
957 CORE::delete( @hash{ qw( _fh ) } );
958 if( CORE::exists( $hash{stop_if} ) &&
959 CORE::defined( $hash{stop_if} ) &&
960 CORE::ref( $hash{stop_if} ) )
961 {
962 require B::Deparse;
963 my $deparse = B::Deparse->new( '-p', '-sC' );
964 my $code = $deparse->coderef2text( CORE::delete( $hash{stop_if} ) );
965 $hash{stop_if_code} = $code;
966 }
967 # Return an array reference rather than a list so this works with Sereal and CBOR
968 CORE::return( [$class, \%hash] ) if( $serialiser eq 'Sereal' && Sereal::Encoder->VERSION <= version->parse( '4.023' ) );
969 # But Storable want a list with the first element being the serialised element
970 CORE::return( $class, \%hash );
971 }
972  
973 sub STORABLE_freeze { CORE::return( CORE::shift->FREEZE( @_ ) ); }
974  
975 sub STORABLE_thaw { CORE::return( CORE::shift->THAW( @_ ) ); }
976  
977 sub THAW
978 {
979 my( $self, undef, @args ) = @_;
980 my $ref = ( CORE::scalar( @args ) == 1 && CORE::ref( $args[0] ) eq 'ARRAY' ) ? CORE::shift( @args ) : \@args;
981 my $class = ( CORE::defined( $ref ) && CORE::ref( $ref ) eq 'ARRAY' && CORE::scalar( @$ref ) > 1 ) ? CORE::shift( @$ref ) : ( CORE::ref( $self ) || $self );
982 my $hash = CORE::ref( $ref ) eq 'ARRAY' ? CORE::shift( @$ref ) : {};
983 my $new;
984 # Storable pattern requires to modify the object it created rather than returning a new one
985 if( CORE::ref( $self ) )
986 {
987 foreach( CORE::keys( %$hash ) )
988 {
989 $self->{ $_ } = CORE::delete( $hash->{ $_ } );
990 }
991 $new = $self;
992 }
993 else
994 {
995 $new = bless( $hash => $class );
996 }
997 if( CORE::exists( $hash->{stop_if_code} ) &&
998 CORE::defined( $hash->{stop_if_code} ) &&
999 CORE::length( $hash->{stop_if_code} ) )
1000 {
1001 my $code = CORE::delete( $hash->{stop_if_code} );
1002 my $saved = $@;
1003 # "if you want to eval the result, you should prepend "sub subname ", or "sub " for an anonymous function constructor."
1004 # <https://metacpan.org/pod/B::Deparse#coderef2text>
1005 my $ref;
1006 {
1007 no strict;
1008 $ref = eval( "sub{ $code }" );
1009 }
1010 if( $@ )
1011 {
1012 $@ =~ s/ at .*\n//;
1013 die( $@ );
1014 }
1015 $@ = $saved;
1016 $new->{stop_if} = $ref;
1017 }
1018 CORE::return( $new );
1019 }
1020  
1021 1;
1022 # NOTE: POD
1023 __END__
1024  
1025 =encoding utf-8
1026  
1027 =head1 NAME
1028  
1029 HTTP::Promise::IO - I/O Handling Class for HTTP::Promise
1030  
1031 =head1 SYNOPSIS
1032  
1033 use HTTP::Promise::IO;
1034 my $this = HTTP::Promise::IO->new( $fh ) ||
1035 die( HTTP::Promise::IO->error, "\n" );
1036  
1037 =head1 VERSION
1038  
1039 v0.1.1
1040  
1041 =head1 DESCRIPTION
1042  
1043 This class implements a filehandle reader and writer with a twist.
1044  
1045 First off, it does not rely on lines, since data stream or in general data from HTTP requests and responses do not necessarily always contain lines. Binary data are sent without necessarily any line at all.
1046  
1047 Second, it is easy on memory by implementing L</read>, which uses a shared L</buffer>, and you can use L</unread> to return data to it (they would be prepended).
1048  
1049 Last, but not least, it implements 2 methods to read in chunks of data from the filehandle until some string pattern specified is found: L</read_until> and L</read_until_in_memory>
1050  
1051 =head1 CONSTRUCTOR
1052  
1053 =head2 new
1054  
1055 This takes a proper filehandle and will ensure the C<O_NONBLOCK> bit is set, so that it can timeout if there is no more data streamed from the filehandle.
1056  
1057 It returns the newly instantiated object upon success, and upon error, sets an L<error|Module::Generic/error> and return C<undef>
1058  
1059 Possible optional parameters are:
1060  
1061 =over 4
1062  
1063 =item C<buffer>
1064  
1065 You can pass some data that will set the initial read buffer, from which other methods in this class access before reading from the filehandle.
1066  
1067 =item C<max_read_buffer>
1068  
1069 An integer. You can set this a default value for the maximum size of the read buffer.
1070  
1071 This is used by L</getline> and L</read_until_in_memory> to limit how much data can be read into the buffer until it returns an error. Hopefully a line or a match specified with C<read_until> would be found and returned before this limit is reached.
1072  
1073 If this is greater than 0 and the amount of data loaded exceeds this limit, and error is returned.
1074  
1075 =item C<timeout>
1076  
1077 AN integer. This is the read timeout. It defaults to 10.
1078  
1079 =back
1080  
1081 =head1 METHODS
1082  
1083 =head2 buffer
1084  
1085 Sets or gets the buffer.
1086  
1087 This is used by those class methods to get leftover data from the buffer, if any, or from the filehandle if necessary.
1088  
1089 This returns a L<scalar object|Module::Generic::Scalar>
1090  
1091 =head2 can_read
1092  
1093 Returns true if it can read from the filehandle or false otherwise.
1094  
1095 It takes an optional hash or hash reference of options, of which, C<timeout> is the only one.
1096  
1097 =head2 close
1098  
1099 Close the filehandle and destroys the current object.
1100  
1101 =head2 connect
1102  
1103 Provided with an hash or hash reference of options and this will connect to the remote server.
1104  
1105 It returns a new L<HTTP::Promise::IO> object, or upon error, it sets an L<error|Module::Generic/error> and returns C<undef>
1106  
1107 Supported options are:
1108  
1109 All the options used for object instantiation. See L</CONSTRUCTOR> and the following ones:
1110  
1111 =over 4
1112  
1113 =item * C<debug>
1114  
1115 Integer representing the level of debug.
1116  
1117 =item * C<host>
1118  
1119 The remote host to connect to.
1120  
1121 =item * C<port>
1122  
1123 An integer representing the remote port to connect to.
1124  
1125 =item * C<stop_if>
1126  
1127 A code reference that serves as a callback and that is called where there is an C<EINTR> error. If the callback returns true, the connection attempts stop there and returns an error. This default to return false.
1128  
1129 =item * C<timeout>
1130  
1131 An integer or a decimal representing a timeout to be used when resolving the host, or when making remote connection.
1132  
1133 =back
1134  
1135 =head2 connect_ssl
1136  
1137 This takes the same options has L</connect>, but performs an SSL connection.
1138  
1139 Like L</connect>, this returns a new L<HTTP::Promise::IO> object, or upon error, it sets an L<error|Module::Generic/error> and returns C<undef>
1140  
1141 =head2 connect_ssl_over_proxy
1142  
1143 Provided with an hash or hash reference of options and this will connect to the remote server.
1144  
1145 It returns a new L<HTTP::Promise::IO> object, or upon error, it sets an L<error|Module::Generic/error> and returns C<undef>
1146  
1147 Supported options are:
1148  
1149 All the options used for object instantiation. See L</CONSTRUCTOR> and the following ones:
1150  
1151 =over 4
1152  
1153 =item * C<debug>
1154  
1155 Integer representing the level of debug.
1156  
1157 =item * C<host>
1158  
1159 The remote host to connect to.
1160  
1161 =item * C<port>
1162  
1163 An integer representing the remote port to connect to.
1164  
1165 =item * C<proxy_authorization>
1166  
1167 The proxy authorisation string to use for authentication.
1168  
1169 =item * C<proxy_host>
1170  
1171 The remote proxy host to connect to.
1172  
1173 =item * C<proxy_port>
1174  
1175 An integer representing the remote proxy port to connect to.
1176  
1177 =item * C<stop_if>
1178  
1179 A code reference that serves as a callback and that is called where there is an C<EINTR> error. If the callback returns true, the connection attempts stop there and returns an error. This default to return false.
1180  
1181 =item * C<timeout>
1182  
1183 An integer or a decimal representing a timeout to be used when resolving the host, or when making remote connection.
1184  
1185 =back
1186  
1187 =head2 filehandle
1188  
1189 Sets or gets the filehandle being used. This is the same filehandle that was passed upon object instantiation.
1190  
1191 =head2 getline
1192  
1193 Reads from the buffer, if there is enough data left over, or from the filehandle and returns the first line found.
1194  
1195 A line is a string that ends with C<\012> which is portable and universal. This would be the equivalent of C<\n>.
1196  
1197 It returns the line found, if any, or C<undef> if there was an error that you can retrieve with L<error|Module::Generic/error>.
1198  
1199 it takes an optional hash or hash reference of options:
1200  
1201 =over 4
1202  
1203 =item C<chomp>
1204  
1205 If true, this will chomp any trailing sequence of C<\012> possibly preceded by C<\015>
1206  
1207 =item C<max_read_buffer>
1208  
1209 An integer that limits how much cumulative data can be read until it exceeds this allowed maximum. When that happens, an error is returned.
1210  
1211 =back
1212  
1213 =head2 inactivity_timeout
1214  
1215 Integer representing the amount of second to wait until a connection is deemed idle and closed.
1216  
1217 =head2 last_delimiter
1218  
1219 Sets or gets the last delimiter found. A delimiter is some pattern that is provided to L</read_until> and L</read_until_in_memory> with the option C<capture> set to a true value.
1220  
1221 This returns the last delimited found as a L<scalar object|Module::Generic::Scalar>
1222  
1223 =head2 make_select
1224  
1225 Provided with an hash or hash reference of options and this L<perlfunc/select> the filehandle or socket using the C<timeout> provided.
1226  
1227 It returns a positive integer upon success, and upon error, this sets an L<error|Module::Generic/error> and returns C<undef>.
1228  
1229 Supported options are:
1230  
1231 =over 4
1232  
1233 =item * C<timeout>
1234  
1235 Integer representing the timeout.
1236  
1237 =item * C<write>
1238  
1239 Boolean. When true, this will check the filehandle or socket for write capability, or if false for read capability.
1240  
1241 =back
1242  
1243 =head2 make_select_timeout
1244  
1245 This takes the same options as L</make_select>, and it will retry selecting the filehandle or socket until success or a timeout occurs. If an C<EINTR> error occurs, it will query the callback provided with L</stop_if>. If the callback returns true, it will return an error, or keep trying otherwise.
1246  
1247 Returns true upon success, and upon error, this sets an L<error|Module::Generic/error> and returns C<undef>.
1248  
1249 =head2 max_read_buffer
1250  
1251 Sets or gets the maximum bytes amount of the read buffer.
1252  
1253 This is used by L</getline> and L</read_until_in_memory> to limit how much data can be read into the buffer until it returns an error. Hopefully a line or a match specified with C<read_until> would be found and returned before this limit is reached.
1254  
1255 If this is greater than 0 and the amount of data loaded exceeds this limit, and error is returned.
1256  
1257 =head2 print
1258  
1259 Provided with some data to print to the underlying filehandle or socket, and this will call L</write> and return true upon success, or false otherwise.
1260  
1261 =head2 read
1262  
1263 my $bytes = $r->read( $buffer, $length );
1264 my $bytes = $r->read( $buffer, $length, $offset );
1265  
1266 This reads C<$length> bytes from either the internal buffer if there are leftover data, or the filehandle, or even both if the internal buffer is not big enough to meet the C<$length> requirement.
1267  
1268 It returns how many bytes actually were loaded into the caller's C<$buffer>. It returns C<undef> after having set an L<error|Module::Generic/error> if an error occurred.
1269  
1270 Just like the perl core L<perlfunc/read> function, this one too will pad with C<\0> the caller's buffer if the offset specified is greater than the actual size of the caller's buffer.
1271  
1272 Note that there is no guarantee that you can read from the filehandle the desired amount of bytes in just one time, especially if the filehandle is a socket, so you may need to do:
1273  
1274 my $bytes;
1275 my $total_to_read = 102400;
1276 my $total_bytes;
1277 while( $bytes = $r->read( $buffer, $chunk_size ) )
1278 {
1279 $out-print( $buffer ) || die( $! );
1280 # If you want to make sure you do not read more than necessary, otherwise, you can discard this line
1281 $chunk_size = ( $total_to_read - $total_bytes ) if( ( $total_bytes < $total_to_read ) && ( ( $total_bytes + $chunk_size ) > $total_to_read ) );
1282 $total_bytes += $bytes;
1283 last if( $total_bytes == $total_to_read );
1284 }
1285 # Check if something bad happened
1286 die( "Something wrong happened: ", $r->error ) if( !defined( $bytes ) );
1287  
1288 =head2 read_until
1289  
1290 my $bytes = $r->read_until( $buffer, $length, $options_hashref );
1291 my $bytes = $r->read_until( $buffer, $length, $offset, $options_hashref );
1292  
1293 This is similar to L</read>, but will read data from either the buffer, the filehandle or a combination of both until the specified C<string>, passed as an option, is found.
1294  
1295 It loads data in chunks specified with the option C<chunk_size> or by default 2048 bytes. If the specified string is not found within that buffer, it returns how many bytes where read and sets the caller's buffer with the data collected.
1296  
1297 Upon the last call when the C<string> is finally found, this will return the number of bytes read, but as a negative number. This will tell you it has found the match. You can consider the number is negative because those are the last n bytes.
1298  
1299 When no more data at all can be read, this will return 0.
1300  
1301 If an error occurred, this will set an L<error|Module::Generic/error> and return C<undef>
1302  
1303 The possible options that can be passed as an hash reference B<only> are:
1304  
1305 =over 4
1306  
1307 =item C<capture>
1308  
1309 Boolean. When set to true, this will capture the match specified with C<string>. The resulting would then be retrievable using L</last_delimiter>
1310  
1311 =item C<chunk_size>
1312  
1313 An integer. This is the maximum bytes this will read per each iteration.
1314  
1315 =item C<exclude>
1316  
1317 Boolean. If this is true, this will exclude the C<string> sought from the buffer allocation.
1318  
1319 =item C<include>
1320  
1321 Boolean. If this is true, this will set the buffer including the C<string> sought after.
1322  
1323 =item C<string>
1324  
1325 This is the C<string> to read data until it is found. The C<string> can be a simple string, or a regular expression.
1326  
1327 =back
1328  
1329 =head2 read_until_in_memory
1330  
1331 my $data = $r->read_until_in_memory( $string );
1332 my $data = $r->read_until_in_memory( $string, $options_hash_or_hashref );
1333 die( "Error: ", $r->error ) if( !defined( $data ) );
1334  
1335 Provided with a C<string> to be found, this will load data from the internal buffer, the filehandle, or a combination of both into memory until the specified C<string> is found.
1336  
1337 Upon success, it returns the data read, which could be an empty string if nothing matched.
1338  
1339 If an error occurred, this will set an L<error|Module::Generic/error> and return C<undef>.
1340  
1341 It takes the following possible options, either as an hash or hash reference:
1342  
1343 =over
1344  
1345 =item C<capture>
1346  
1347 Boolean. When set to true, this will capture the match specified with C<string>. The resulting would then be retrievable using L</last_delimiter>
1348  
1349 =item C<chunk_size>
1350  
1351 An integer. This is the maximum bytes this will read per each iteration.
1352  
1353 =item C<exclude>
1354  
1355 Boolean. If this is true, this will exclude the C<string> sought from the buffer allocation.
1356  
1357 =item C<include>
1358  
1359 Boolean. If this is true, this will set the buffer including the C<string> sought after.
1360  
1361 =back
1362  
1363 =head2 ssl_opts
1364  
1365 Sets or gets an hash reference of ssl options to be used with L<IO::Socket::SSL/start_SSL>
1366  
1367 =head2 stop_if
1368  
1369 Sets or gets a code reference acting as a callback when an error C<EINTR> if encountered. If the callback returns true, the method using it, will stop and return an error, otherwise, it will keep trying.
1370  
1371 =head2 timeout
1372  
1373 Sets or gets the timeout threshold. This returns a L<number object|Module::Generic::Number>
1374  
1375 =head2 unread
1376  
1377 Provided with some data and this will put it back into the internal buffer, at its beginning.
1378  
1379 This returns the current object for chaining.
1380  
1381 =head2 write
1382  
1383 This write to the filehandle set, and takes a buffer to write, an optional length, an optional offset, and an optional timeout value.
1384  
1385 If no length is provided, this default to the length of the buffer.
1386  
1387 If no offset is provided, this default to C<0>.
1388  
1389 If no timeout is provided, this default to the value set with L</timeout>
1390  
1391 It returns the number of bytes written or, upon error, sets an L<error|Module::Generic/error> and returns C<undef>
1392  
1393 =head2 write_all
1394  
1395 Provided with some data an an optional timeout, and this will write the data to the filehandle set.
1396  
1397 It returns the number of bytes written or, upon error, sets an L<error|Module::Generic/error> and returns C<undef>
1398  
1399 =head1 THREAD-SAFETY
1400  
1401 This module is thread-safe for all operations, as it operates on per-object state and uses thread-safe external libraries.
1402  
1403 =head1 AUTHOR
1404  
1405 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
1406  
1407 =head1 SEE ALSO
1408  
1409 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>
1410  
1411 =head1 COPYRIGHT & LICENSE
1412  
1413 Copyright(c) 2022 DEGUEST Pte. Ltd.
1414  
1415 All rights reserved.
1416  
1417 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
1418  
1419 =cut