Docker/Role/HTTP.pm

filter: Statementstmt 97.9% 577 / 589 Branchbran 90.1% 339 / 376 Conditioncond 70.7% 99 / 140 MC/DCmcdc 51.8% 42 / 81 Subroutinesub 100% 72 / 72 Podpod 100% 6 / 6 totaltotal 89.7% 1135 / 1264 CC 245 SCAR 27.5
CC
245
Cov
92%
_request
51.2
_build__socket
27.2
_read_streaming_response
25.3
CRAP 15.6
« Docker/API/Images.pm ↑ Summary Docker/API/Containers.pm »
1 package API::Docker::Role::HTTP;
2 # ABSTRACT: HTTP transport role for Docker Engine API
3 52 our $VERSION = '0.006';
4 52 ▶use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 52 ▶use IO::Socket::UNIX;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 52 ▶use IO::Socket::INET;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 # For the sysread method on a plain filehandle: _pull calls it as a method so
8 # that IO::Socket::SSL's own gets picked up rather than the builtin. See _pull.
9 52 ▶use IO::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 52 ▶use Socket qw( SOL_SOCKET SO_RCVTIMEO );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 # How a read that delivered nothing says it ran out of time rather than out of
12 # stream (EAGAIN/EWOULDBLOCK), and how it says it was interrupted rather than
13 # either (EINTR). See _pull and _timed_out.
14 52 ▶use Errno qw( EAGAIN EWOULDBLOCK EINTR );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 52 ▶use JSON::MaybeXS qw( encode_json decode_json );
Subroutine BEGIN: called CC=1 SCAR=0.0
16 52 ▶use Scalar::Util qw( looks_like_number );
Subroutine BEGIN: called CC=1 SCAR=0.0
17 52 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 52 ▶use Carp qw( croak shortmess );
Subroutine BEGIN: called CC=1 SCAR=0.0
19 52 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
20 52 ▶use API::Docker::Error::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 52 ▶use API::Docker::Error::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 52 ▶use API::Docker::Error::Timeout;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 52 ▶use API::Docker::Error::Truncated;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 52 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26  
27 52 requires 'host';
28 52 requires 'api_version';
29 52 requires 'tls';
30 52 requires 'cert_path';
31 52 requires 'tls_insecure';
32  
33 # Docker stream frame types, indexed by the first byte of the frame header.
34 52 my @STREAM_TYPE = qw( stdin stdout stderr );
35  
36 # A field name is an RFC 9110 token and nothing else. Anything outside this
37 # set -- CR, LF, a space, a colon -- is rejected rather than stripped; see
38 # _assert_header_name.
39 52 my $HEADER_NAME = qr/\A[0-9A-Za-z!#\$%&'*+.^_`|~-]+\z/;
40  
41 # The request-target path is caller data -- a container name, an image
42 # reference -- spliced straight into the request line as /v$version$path, so a
43 # byte the line's own grammar reads rewrites the request rather than naming a
44 # resource: CR or LF ends the line, a space opens the HTTP-version field, and
45 # a ? or # opens the query or fragment. It is held to the RFC 3986 origin-form
46 # path character set -- unreserved, the sub-delims, and : @ % / -- and
47 # rejected, not sanitised, for the reason a header name is (see
48 # _assert_request_path). Query parameters carry the ? and everything after it
49 # and are assembled separately below, each element run through _uri_encode.
50 52 my $REQUEST_PATH = qr{\A[A-Za-z0-9\-._~:/\@!\$&'()*+,;=%]*\z};
51  
52 # The three units a response can be cut into, one option each. A request picks
53 # one of them, or none and gets the buffered path; see _stream_handler.
54 52 my @STREAM_OPTION = qw( on_event on_frame on_chunk );
55  
56 # What a response body has to start with to be worth handing to decode_json.
57 # An object or an array is not the whole of JSON: the engine answers several
58 # endpoints with a bare JSON scalar, and a `null` used to come back as the
59 # four-character string 'null'. See _request.
60 52 my $JSON_BODY = qr/\A\s*(?:[\[\{"]|-?[0-9]|true|false|null)/;
61  
62 # How much is asked for per sysread. Strictly an upper bound -- sysread
63 # returns what has arrived rather than filling to it (see _pull), so on a live
64 # feed a call typically comes back with one burst, and asking for 64K costs
65 # nothing but the size of the buffer it lands in.
66 52 my $READ_SIZE = 64 * 1024;
67  
68 52 has read_timeout => (
69 is => 'ro',
70 );
71  
72  
73 52 has connect_timeout => (
74 is => 'ro',
75 );
76  
77  
78 52 has _socket => (
79 is => 'lazy',
80 clearer => '_clear_socket',
81 );
82  
83 # The connect timeout and the endpoint it belongs to, on their way to
84 # _build__socket. It is a lazy builder and so cannot be handed an argument,
85 # and the value is per request rather than per client -- hence rw, with
86 # _reconnect as the only writer, setting it immediately before the build and
87 # clearing it immediately after. Unset is the whole of the old behaviour: no
88 # Timeout on any constructor, and the plain croak on a failure.
89 52 has _pending_connect => (
90 is => 'rw',
91 init_arg => undef,
92 );
93  
94 17 ▶sub _build__socket {
Subroutine _build__socket: called CC=17 SCAR=33.0
95 17 my ($self) = @_;
96 17 my $host = $self->host;
97 17 my $pending = $self->_pending_connect;
98 17 ▶ my $timeout = $pending ? $pending->{timeout} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$pending ? : 17 0 17
99  
100 17 ▶ if ($host =~ m{^unix://(.+)$}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($host =~ m[^unix://(.+)$]) { } 5 12 17
elsif ($host =~ m[^tcp://([^:]+):(\d+)$]) { } 12 0 12
101 5 my $path = $1;
102 5 $log->debugf("Connecting to Unix socket: %s", $path);
103 5 ▶ my $sock = IO::Socket::UNIX->new(
Branch: 1 branch
BranchTrueFalseTotal
$timeout ? : 3 2 5
104 Peer => $path,
105 Type => SOCK_STREAM,
106 $timeout ? (Timeout => $timeout) : (),
107 );
108 5 ▶ unless ($sock) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sock) 3 2 5
109 # Asked before anything else can touch $@ or $!, which is the whole of
110 # the evidence; see _connect_expired.
111 3 ▶ $self->_croak_connect_timeout($pending, 'unix://' . $path)
Branch: 1 branch
BranchTrueFalseTotal
if $self->_connect_expired($timeout) 1 2 3
112 if $self->_connect_expired($timeout);
113 2 croak "Cannot connect to Unix socket $path: $!";
114 }
115 2 return $sock;
116 }
117 elsif ($host =~ m{^tcp://([^:]+):(\d+)$}) {
118 12 my ($addr, $port) = ($1, $2);
119  
120 12 ▶ unless ($self->tls) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->tls) 0 12 12
121 0 $log->debugf("Connecting to TCP %s:%s", $addr, $port);
122 0 ▶ my $sock = IO::Socket::INET->new(
Branch: 1 branch
BranchTrueFalseTotal
$timeout ? : 0 0 0
123 PeerAddr => $addr,
124 PeerPort => $port,
125 Proto => 'tcp',
126 $timeout ? (Timeout => $timeout) : (),
127 );
128 0 ▶ unless ($sock) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sock) 0 0 0
129 0 ▶ $self->_croak_connect_timeout($pending, $addr . ':' . $port)
Branch: 1 branch
BranchTrueFalseTotal
if $self->_connect_expired($timeout) 0 0 0
130 if $self->_connect_expired($timeout);
131 0 croak "Cannot connect to $addr:$port: $!";
132 }
133 0 return $sock;
134 }
135  
136 # Built before the connection is opened: a cert_path that names nothing,
137 # or half a client certificate, is a configuration mistake and the caller
138 # should hear about it as one rather than as a handshake failure.
139 12 my %ssl = $self->_ssl_options($addr);
140  
141 12 ▶ $log->debugf("Connecting to TCP %s:%s over TLS (verification %s)",
Branch: 1 branch
BranchTrueFalseTotal
$self->tls_insecure ? : 1 11 12
142 $addr, $port, $self->tls_insecure ? 'off' : 'on');
143 12 ▶ my $sock = IO::Socket::SSL->new(
Branch: 1 branch
BranchTrueFalseTotal
$timeout ? : 0 12 12
144 PeerAddr => $addr,
145 PeerPort => $port,
146 Proto => 'tcp',
147 $timeout ? (Timeout => $timeout) : (),
148 %ssl,
149 );
150 12 ▶ unless ($sock) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sock) 3 9 12
151 3 ▶ $self->_croak_connect_timeout($pending, $addr . ':' . $port . ' (TLS)')
Branch: 1 branch
BranchTrueFalseTotal
if $self->_connect_expired($timeout) 0 3 3
152 if $self->_connect_expired($timeout);
153 # $SSL_ERROR carries the handshake failure -- an untrusted certificate,
154 # a name that does not match -- and $! the plain connect failure. Both
155 # are named because either can be the one that happened. The pragma is
156 # for the package variable of a module that is not loaded at compile
157 # time, which perl would otherwise report as a probable typo.
158 52 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
159 3 ▶ croak 'Cannot connect to ' . $addr . ':' . $port . ' over TLS: '
Condition40%2/5
$IO::Socket::SSL::SSL_ERROR || $! || 'unknown error'
l!l
30
$IO::Socket::SSL::SSL_ERROR or $!
l!l&&r!l&&!r
300
MC/DC0%0/2
$IO::Socket::SSL::SSL_ERROR || $! || 'unknown error'
$IO::Socket::SSL::SSL_ERROR $!
Truth table33%1/3
A or B
A= $IO::Socket::SSL::SSL_ERRORB= $!
ABresult
1X1
011
000
160 . ($IO::Socket::SSL::SSL_ERROR || $! || 'unknown error');
161 }
162 9 return $sock;
163 }
164 else {
165 0 croak "Unsupported host format: $host (expected unix:// or tcp://)";
166 }
167 }
168  
169 # Loaded here rather than with the other modules at the top of the file.
170 # IO::Socket::SSL pulls in Net::SSLeay, which is XS compiled against libssl,
171 # and the unix:// transport -- local Docker, rootless Podman, the default and
172 # the only one most installations use -- never needs a byte of it. A hard
173 # dependency would make this client unbuildable on a machine with no OpenSSL
174 # headers for the sake of a transport it is not using, so it is a recommended
175 # one and this is the point where its absence becomes an error.
176 48 ▶sub _load_ssl {
Subroutine _load_ssl: called CC=3 SCAR=11.0
177 48 my ($self) = @_;
178  
179 48 ▶ return 1 if eval { require IO::Socket::SSL; 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { require IO::Socket::SSL; 1 } } 44 4 48
180 4 ▶ my $why = $@ || 'unknown error';
Condition50%1/2
$@ || 'unknown error'
l!l
40
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
181 4 $why =~ s/\s+\z//;
182 4 croak __PACKAGE__ . ': tls => 1 needs IO::Socket::SSL, which failed to '
183 . 'load (' . $why . '). It is a recommended rather than a required '
184 . 'dependency because the unix:// transport never uses it -- install it '
185 . 'with `cpanm IO::Socket::SSL` (or `cpanm --with-recommends '
186 . 'API::Docker`)';
187 }
188  
189 # The IO::Socket::SSL arguments for this client, as a plain hash, so the
190 # policy can be read off without opening a connection.
191 44 ▶sub _ssl_options {
Subroutine _ssl_options: called CC=2 SCAR=6.9
192 44 my ($self, $addr) = @_;
193  
194 44 $self->_load_ssl;
195  
196 # SNI, sent whether or not the certificate is checked: a terminator serving
197 # several names needs it to pick the right one, and that is true of an
198 # unverified connection too.
199 44 my %ssl = ( SSL_hostname => $addr );
200  
201 44 ▶ if ($self->tls_insecure) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->tls_insecure) { } 5 39 44
202 # Everything below is off deliberately, and the attribute that got us here
203 # says so in its name. Encryption without verification stops a passive
204 # listener and nothing else: whoever answers the connection chooses the
205 # certificate, so anyone able to redirect it reads and rewrites the
206 # traffic -- credentials, image contents, container commands.
207 5 $ssl{SSL_verify_mode} = IO::Socket::SSL::SSL_VERIFY_NONE();
208 5 $ssl{SSL_verifycn_scheme} = undef;
209 }
210 else {
211 39 $ssl{SSL_verify_mode} = IO::Socket::SSL::SSL_VERIFY_PEER();
212 # The name is checked against the certificate as well as the chain: a
213 # valid certificate for some other host is not this host.
214 39 $ssl{SSL_verifycn_scheme} = 'http';
215 39 $ssl{SSL_verifycn_name} = $addr;
216 }
217  
218 44 return (%ssl, $self->_ssl_certificates);
219 }
220  
221 # cert.pem, key.pem and ca.pem in one directory -- the layout the docker CLI
222 # writes and the one cert_path has always pointed at, whether or not anything
223 # read it.
224 44 ▶sub _ssl_certificates {
Subroutine _ssl_certificates: called CC=7 SCAR=19.5
225 44 my ($self) = @_;
226  
227 44 my $dir = $self->cert_path;
228 44 ▶ return () unless defined $dir && length $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir and length $dir 11 33 44
Condition66%2/3
defined $dir and length $dir
!ll&&!rl&&r
11033
MC/DC50%1/2
defined $dir and length $dir
defined $dir length $dir
Truth table66%2/3
A and B
A= defined $dirB= length $dir
ABresult
0X0
100
111
229  
230 # cert_path defaults from DOCKER_CERT_PATH, so it can arrive from a machine's
231 # environment rather than from this caller -- but it is only looked at once
232 # TLS was asked for, and at that point a path naming nothing is a mistake
233 # worth stopping on rather than quietly connecting without the certificates
234 # the caller believes are in use.
235 33 my $path = path($dir);
236 33 ▶ croak __PACKAGE__ . ": cert_path $dir is not a directory. TLS expects the "
Branch: 1 branch
BranchTrueFalseTotal
unless $path->is_dir 4 29 33
237 . 'layout the docker CLI writes -- ca.pem, cert.pem and key.pem in one '
238 . 'directory -- and this names nothing that could hold it'
239 unless $path->is_dir;
240  
241 29 my %ssl;
242  
243 # No ca.pem is not an error: verifying a daemon behind a terminator with a
244 # publicly trusted certificate needs no private trust anchor, and the
245 # default store is then the right one. See L</"TLS on a tcp:// connection">.
246 29 my $ca = $path->child('ca.pem');
247 29 ▶ $ssl{SSL_ca_file} = "$ca" if $ca->exists;
Branch: 1 branch
BranchTrueFalseTotal
if $ca->exists 17 12 29
248  
249 29 my $cert = $path->child('cert.pem');
250 29 my $key = $path->child('key.pem');
251 29 my @half = grep { !$_->[1]->exists }
252 ( [ 'cert.pem', $cert ], [ 'key.pem', $key ] );
253  
254 # One of the two is never a mode, only ever an accident: a key with no
255 # certificate proves nothing and a certificate with no key cannot be used.
256 29 ▶ croak __PACKAGE__ . ': cert_path ' . $dir . ' has ' . $half[0][0]
Branch: 1 branch
BranchTrueFalseTotal
if @half == 1 8 21 29
257 . ' missing while the other half of the client certificate is there. '
258 . 'Both cert.pem and key.pem are needed, or neither'
259 if @half == 1;
260  
261 21 ▶ if (!@half) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@half) 14 7 21
262 14 $ssl{SSL_cert_file} = "$cert";
263 14 $ssl{SSL_key_file} = "$key";
264 }
265  
266 21 return %ssl;
267 }
268  
269 301 ▶sub _reconnect {
Subroutine _reconnect: called CC=2 SCAR=6.9
270 301 my ($self, $pending) = @_;
271 301 $self->_clear_socket;
272  
273 # Cleared on the way out whichever way the build went, so a later _socket
274 # built by anything but a request -- a test subclass, a caller reaching for
275 # it directly -- never picks up the last request's bound.
276 301 $self->_pending_connect($pending);
277 301 my $sock;
278 301 my $ok = eval { $sock = $self->_socket; 1 };
279 301 my $err = $@;
280 301 $self->_pending_connect(undef);
281 301 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 18 283 301
282  
283 283 return $sock;
284 }
285  
286 # Whether the connect that has just failed failed because the bound fired.
287 # Asked with nothing in between, because $@ and $! are the whole of the
288 # evidence and both are global.
289 #
290 # $@ rather than errno: IO::Socket writes 'connect: timeout' there, and only
291 # there, when its own select() ran out -- measured, against a host that drops
292 # SYNs, where $! is ETIMEDOUT, which the kernel also produces on its own after
293 # two minutes with no Timeout set at all.
294 #
295 # EAGAIN is the second shape and belongs to unix:// alone. Measured against a
296 # listener whose backlog is full: with no Timeout the connect blocks
297 # indefinitely (still blocked after 8s), and with one it fails at once with
298 # EAGAIN, because IO::Socket does the timed connect non-blocking and an
299 # AF_UNIX connect has no in-progress state to wait on. So on that transport
300 # the option does not wait, it refuses -- but a connect that failed with
301 # EAGAIN is still one the bound ended, and reporting it as anything else would
302 # name a cause the caller cannot act on.
303 12 ▶sub _connect_expired {
Subroutine _connect_expired: called CC=6 SCAR=18.0
304 12 my ($self, $timeout) = @_;
305  
306 12 ▶ return 0 unless $timeout;
Branch: 1 branch
BranchTrueFalseTotal
unless $timeout 5 7 12
307 7 ▶ return 1 if defined $@ && $@ =~ /connect: timeout\z/;
Branch: 1 branch
BranchTrueFalseTotal
if defined $@ and $@ =~ /connect: timeout\z/ 1 6 7
Condition66%2/3
defined $@ and $@ =~ /connect: timeout\z/
!ll&&!rl&&r
061
MC/DC50%1/2
defined $@ and $@ =~ /connect: timeout\z/
defined $@ $@ =~ /connect: timeout\z/
Truth table66%2/3
A and B
A= defined $@B= $@ =~ /connect: timeout\z/
ABresult
0X0
100
111
308 6 ▶ return 1 if $! == EAGAIN || $! == EWOULDBLOCK;
Branch: 1 branch
BranchTrueFalseTotal
if $! == 11 or $! == 11 2 4 6
Condition66%2/3
$! == 11 or $! == 11
l!l&&r!l&&!r
204
MC/DC50%1/2
$! == 11 or $! == 11
$! == 11 $! == 11
Truth table66%2/3
A or B
A= $! == 11B= $! == 11
ABresult
1X1
011
000
309 4 return 0;
310 }
311  
312 1 ▶sub _croak_connect_timeout {
Subroutine _croak_connect_timeout: called CC=4 SCAR=15.6
313 1 my ($self, $pending, $where) = @_;
314  
315 1 my $endpoint = $pending->{endpoint};
316 # See _croak_timeout for why the object goes into a variable first and why
317 # the location is captured by hand.
318 my $error = API::Docker::Error::Timeout->new(
319 message => 'Docker API connect timeout'
320 . (defined $endpoint && length $endpoint ? ' (' . $endpoint . ')' : '')
321 . ': ' . $where . ' did not accept within ' . $pending->{timeout} . 's',
322 location => shortmess(''),
323 endpoint => defined $endpoint ? $endpoint : '',
324 timeout => $pending->{timeout},
325 1 ▶ phase => 'connect',
Branch: 2 branches
BranchTrueFalseTotal
defined $endpoint && length $endpoint ? : 1 0 1
defined $endpoint ? : 1 0 1
Condition33%1/3
defined $endpoint and length $endpoint
!ll&&!rl&&r
001
MC/DC0%0/2
defined $endpoint and length $endpoint
defined $endpoint length $endpoint
Truth table33%1/3
A and B
A= defined $endpointB= length $endpoint
ABresult
0X0
100
111
326 );
327 1 croak $error;
328 }
329  
330 # undef for "no timeout", which is both the default and the explicit 0, so a
331 # client carrying a default can be opted out of for one request. Anything that
332 # is not a non-negative number is a caller mistake and is refused rather than
333 # rounded to something: silently reading a typo as "off" would hand back the
334 # hang the caller was asking to be protected from.
335 614 ▶sub _timeout_value {
Subroutine _timeout_value: called CC=6 SCAR=17.9
336 614 my ($self, $name, $timeout) = @_;
337  
338 614 ▶ return undef unless defined $timeout;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $timeout 579 35 614
339 35 ▶ croak __PACKAGE__ . '->_request ' . $name . ' must be a non-negative number '
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $timeout and &looks_like_number($timeout) and $timeout >= 0 9 26 35
Condition100%6/6
not ref $timeout and &looks_like_number($timeout) and $timeout >= 0
!ll&&!rl&&r
7226
not ref $timeout and &looks_like_number($timeout)
!ll&&!rl&&r
3428
MC/DC100%3/3
not ref $timeout and &looks_like_number($timeout) and $timeout >= 0
not ref $timeout &looks_like_number($timeout) $timeout >= 0
Truth table100%4/4
not(A) and B and C
A= not ref $timeoutB= &looks_like_number($timeout)C= $timeout >= 0
ABCresult
0XX0
10X0
1100
1111
340 . 'of seconds (0 or undef for none), not "' . $timeout . '"'
341 unless !ref $timeout && looks_like_number($timeout) && $timeout >= 0;
342  
343 26 ▶ return $timeout > 0 ? $timeout : undef;
Branch: 1 branch
BranchTrueFalseTotal
$timeout > 0 ? : 20 6 26
344 }
345  
346 305 ▶sub _read_timeout_value {
Subroutine _read_timeout_value: called CC=1 SCAR=0.0
347 305 my ($self, $timeout) = @_;
348 305 return $self->_timeout_value('read_timeout', $timeout);
349 }
350  
351 309 ▶sub _connect_timeout_value {
Subroutine _connect_timeout_value: called CC=1 SCAR=0.0
352 309 my ($self, $timeout) = @_;
353 309 return $self->_timeout_value('connect_timeout', $timeout);
354 }
355  
356 # Why SO_RCVTIMEO and not select(): a bound that reads the socket cannot see
357 # what is already buffered above it, and would fire while the data it was
358 # waiting for was in hand. That was true of PerlIO's read-ahead when this was
359 # written (measured: after one readline of a socket holding
360 # "one\ntwo\nthree\n", two whole lines sit in the PerlIO buffer and select()
361 # says the handle is not ready), and it is true of _read_buffer now. A
362 # select-based bound would have to be asked only when that buffer is empty,
363 # which is one more invariant to keep for no gain: SO_RCVTIMEO bounds the one
364 # syscall in _pull for one setsockopt, and gets idle-since-the-last-byte
365 # semantics for free, which is the semantics these endpoints need (karr k52:
366 # the buffered frames arrive, and *then* the socket stalls -- a
367 # time-to-first-byte bound would never fire).
368 287 ▶sub _apply_read_timeout {
Subroutine _apply_read_timeout: called CC=7 SCAR=23.0
369 287 my ($self, $sock, $timeout) = @_;
370  
371 287 ▶ return unless $timeout;
Branch: 1 branch
BranchTrueFalseTotal
unless $timeout 276 11 287
372  
373 11 my $packed;
374 11 ▶ if ($^O eq 'MSWin32' || $^O eq 'cygwin') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq 'MSWin32' or $^O eq 'cygwin') { } 0 11 11
Condition33%1/3
$^O eq "MSWin32" or $^O eq "cygwin"
l!l&&r!l&&!r
0011
MC/DC0%0/2
$^O eq "MSWin32" or $^O eq "cygwin"
$^O eq "MSWin32" $^O eq "cygwin"
Truth table33%1/3
A or B
A= $^O eq "MSWin32"B= $^O eq "cygwin"
ABresult
1X1
011
000
375 # Winsock takes a DWORD of milliseconds here rather than a struct timeval,
376 # and reads a zero as "wait forever" -- so a sub-millisecond request is
377 # rounded up instead of becoming the hang it asked to avoid. Reasoned from
378 # the Winsock documentation and NOT measured: there is no Windows here.
379 # What makes that safe to ship is the croak below -- a shape the platform
380 # rejects is reported rather than ignored.
381 0 my $ms = int($timeout * 1000 + 0.5);
382 0 ▶ $ms = 1 if $ms < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $ms < 1 0 0 0
383 0 $packed = pack('L', $ms);
384 }
385 else {
386 # struct timeval: two native longs, seconds then microseconds. Measured on
387 # Linux x86_64 against unix://, plain tcp:// and TLS.
388 11 my $sec = int($timeout);
389 11 my $usec = int(($timeout - $sec) * 1_000_000 + 0.5);
390 0 ▶ if ($usec >= 1_000_000) { $sec++; $usec -= 1_000_000 }
Branch: 1 branch
BranchTrueFalseTotal
if ($usec >= 1000000) 0 11 11
391 11 $packed = pack('l!l!', $sec, $usec);
392 }
393  
394 # Never a warning and never a silent pass. A caller that asked for a bound
395 # and did not get one is left waiting on exactly the hang the option exists
396 # to end, and would have no way to tell that from a daemon being slow.
397 11 ▶ setsockopt($sock, SOL_SOCKET, SO_RCVTIMEO, $packed)
Branch: 1 branch
BranchTrueFalseTotal
setsockopt $sock, 1, 20, $packed or croak('API::Docker::Role::HTTP: cannot set a read timeout of ' . $timeout . 's on this socket: ' . $! . '. Refusing to continue without it -- a ' . "bound that is not in force is worse than no bound at all, because " . 'the caller is relying on it') 10 1 11
398 or croak __PACKAGE__ . ': cannot set a read timeout of ' . $timeout
399 . 's on this socket: ' . $! . '. Refusing to continue without it -- a '
400 . 'bound that is not in force is worse than no bound at all, because '
401 . 'the caller is relying on it';
402  
403 10 return;
404 }
405  
406 # A read that did not deliver did not deliver for one of two reasons, and they
407 # are not the same thing: the stream ended, or the clock ran out. errno is the
408 # only thing that separates them -- measured, both eof() and $fh->error are
409 # true after a timeout just as they are at a clean end, and asking eof() costs
410 # a second full timeout. So $! is zeroed immediately before the read in _pull
411 # and captured immediately after it, with nothing in between: it is only
412 # meaningful after a failure, and any operation in between would overwrite it.
413 #
414 # Without this the readers would take a timeout for the end of the response and
415 # return a truncated body as a whole one. That is the reason karr k59 is not
416 # just the setsockopt: switching the option on alone would turn a hang into
417 # silent data loss, which is the worse of the two.
418 46 ▶sub _timed_out {
Subroutine _timed_out: called CC=4 SCAR=13.9
419 46 my ($self, $ctx, $errno) = @_;
420  
421 46 ▶ return 0 unless $ctx->{timeout};
Branch: 1 branch
BranchTrueFalseTotal
unless $ctx->{"timeout"} 17 29 46
422 29 ▶ return ($errno == EAGAIN || $errno == EWOULDBLOCK) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$errno == 11 || $errno == 11 ? : 27 2 29
Condition66%2/3
$errno == 11 or $errno == 11
l!l&&r!l&&!r
2702
MC/DC50%1/2
$errno == 11 or $errno == 11
$errno == 11 $errno == 11
Truth table66%2/3
A or B
A= $errno == 11B= $errno == 11
ABresult
1X1
011
000
423 }
424  
425 27 ▶sub _croak_timeout {
Subroutine _croak_timeout: called CC=7 SCAR=19.6
426 27 my ($self, $ctx, $partial) = @_;
427  
428 27 ▶ $partial = '' unless defined $partial;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $partial 0 27 27
429 # Only ever set once a stream is past its status line, so an error body read
430 # whole on the way to a >= 400 croak is still reported in bytes.
431 27 ▶ my $summary = $ctx->{summary} ? $ctx->{summary}->() : undef;
Branch: 1 branch
BranchTrueFalseTotal
$ctx->{'summary'} ? : 9 18 27
432  
433 my $after = $summary
434 ? ' after ' . $summary->{delivered} . ' unit'
435 27 ▶ . ($summary->{delivered} == 1 ? '' : 's')
Branch: 4 branches
BranchTrueFalseTotal
$summary ? : 9 18 27
$summary->{'delivered'} == 1 ? : 6 3 9
length $partial ? : 11 7 18
length $partial == 1 ? : 0 11 11
436 : length($partial)
437 ? ' after ' . length($partial) . ' byte'
438 . (length($partial) == 1 ? '' : 's')
439 : ', nothing arrived at all';
440  
441 # Carp hands a reference straight back rather than decorating it, so this
442 # croak is a die with an object -- hence the location captured by hand,
443 # which names the same frame a croak of a plain string would have named.
444 # The object goes into a variable first: `croak CLASS->new(...)` is indirect
445 # object syntax and parses as CLASS->croak(new(...)).
446 my $error = API::Docker::Error::Timeout->new(
447 message => 'Docker API read timeout (' . $ctx->{endpoint} . '): '
448 . $ctx->{timeout} . 's of silence' . $after,
449 location => shortmess(''),
450 endpoint => $ctx->{endpoint},
451 timeout => $ctx->{timeout},
452 27 partial => $partial,
453 summary => $summary,
454 );
455 27 croak $error;
456 }
457  
458 # The other way a response ends before it is finished, and the one that needs
459 # no option to be armed: the daemon closed mid-sentence (karr k64).
460 #
461 # It is deliberately not folded into _croak_timeout. A timeout is the absence
462 # of an answer inside a bound the caller asked for, and it can fire on a
463 # response that would have completed; this is a statement about the response
464 # itself, made by comparing the body against what the response announced, and
465 # it fires whether or not anything was bounded. The two carry the same
466 # "here is what did arrive" contract and nothing else.
467 #
468 # $ctx->{partial} and $ctx->{summary} are read exactly as _croak_timeout reads
469 # them, so a buffered read reports bytes and a streamed one reports units,
470 # with no site having to know which it is.
471 57 ▶sub _croak_truncated {
Subroutine _croak_truncated: called CC=11 SCAR=24.0
472 57 my ($self, $ctx, %what) = @_;
473  
474 57 ▶ my $summary = $ctx->{summary} ? $ctx->{summary}->() : undef;
Branch: 1 branch
BranchTrueFalseTotal
$ctx->{'summary'} ? : 14 43 57
475 57 ▶ my $partial = $ctx->{partial} ? ${ $ctx->{partial} } : '';
Branch: 1 branch
BranchTrueFalseTotal
$ctx->{'partial'} ? : 23 34 57
476  
477 my $arrived = $summary
478 ? $summary->{delivered} . ' unit'
479 57 ▶ . ($summary->{delivered} == 1 ? '' : 's') . ' delivered'
Branch: 4 branches
BranchTrueFalseTotal
$summary ? : 14 43 57
$summary->{'delivered'} == 1 ? : 9 5 14
length $partial ? : 21 22 43
length $partial == 1 ? : 0 21 21
480 : length($partial)
481 ? length($partial) . ' byte'
482 . (length($partial) == 1 ? '' : 's') . ' arrived'
483 : 'nothing arrived at all';
484  
485 # Empty when a reader is driven directly rather than through _request, which
486 # is how t/role_http.t drives them: an endpoint nobody named is left out of
487 # the message rather than interpolated as the empty string.
488 57 ▶ my $endpoint = defined $ctx->{endpoint} ? $ctx->{endpoint} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $ctx->{'endpoint'} ? : 34 23 57
489  
490 # The two phases with an announced length say the same sentence about it, so
491 # they name the piece and let this write it; the two without pass the whole
492 # detail, there being no count to put in one.
493 57 my $detail = $what{detail};
494 57 ▶ unless (defined $detail) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $detail) 19 38 57
495 19 my $short = $what{expected} - $what{received};
496 $detail = $what{piece} . ' stopped ' . $short . ' byte'
497 . ($short == 1 ? '' : 's') . ' short of the ' . $what{expected}
498 19 ▶ . ' it announced';
Branch: 1 branch
BranchTrueFalseTotal
$short == 1 ? : 0 19 19
499 }
500  
501 # Carp hands a reference straight back rather than decorating it, so this
502 # croak is a die with an object -- hence the location captured by hand,
503 # which names the same frame a croak of a plain string would have named.
504 # The object goes into a variable first: `croak CLASS->new(...)` is indirect
505 # object syntax and parses as CLASS->croak(new(...)).
506 my $error = API::Docker::Error::Truncated->new(
507 message => 'Docker API response truncated'
508 . (length $endpoint ? ' (' . $endpoint . ')' : '') . ': '
509 . $detail . '; ' . $arrived,
510 location => shortmess(''),
511 endpoint => $endpoint,
512 phase => $what{phase},
513 expected => $what{expected},
514 received => $what{received},
515 57 ▶ partial => $partial,
Branch: 1 branch
BranchTrueFalseTotal
length $endpoint ? : 34 23 57
516 summary => $summary,
517 );
518 57 croak $error;
519 }
520  
521 # ---------------------------------------------------------------------------
522 # Reading, in one buffer regime
523 #
524 # Every byte of a response is taken off the handle by _pull and by nothing
525 # else, and every reader below is served out of the buffer _pull fills. That
526 # is not an optimisation, it is the only shape that works (karr k60).
527 #
528 # What forced it: perl's read() is fread-shaped. It loops until it has the
529 # LENGTH it was asked for or the stream ends -- it does not return what has
530 # arrived. Measured on an AF_UNIX socketpair whose peer writes 6 bytes, waits
531 # half a second, writes 6 more and closes: read($sock, $buf, 65536) came back
532 # with 12 after 0.90s, having waited for the close, while sysread came back
533 # with 6 in 0.00s. On the endpoints with neither a Content-Length nor chunked
534 # encoding -- attach, logs(follow), exec/start, all
535 # application/vnd.docker.raw-stream -- the reader asks for $READ_SIZE, so
536 # read() delivered nothing to an on_frame/on_chunk callback until 64K had
537 # piled up or the daemon hung up. On a stream that never ends it would deliver
538 # nothing at all. The POD promised those callbacks the bytes as they arrive,
539 # and that promise was not kept.
540 #
541 # Why it could not be fixed at the one site that had the bug: _read_head read
542 # the status line and the headers with <$sock>, and PerlIO reads ahead. The
543 # bytes past the header block were sitting in a buffer this code cannot reach
544 # -- there is no supported way to take them back out; ungetc is layer-
545 # dependent, seek does not work on a socket, and select/MSG_PEEK see the
546 # kernel's buffer rather than PerlIO's. So switching only the body reads to
547 # sysread would have silently dropped the start of every body. Either all read
548 # sites move together or none do.
549 #
550 # The buffer lives on the handle rather than on the client or in the context:
551 # it is the unconsumed bytes of *that* handle, its lifetime is the handle's,
552 # and a client that opens a socket per request therefore has nothing to reset.
553 # ${*$sock}{...} is the IO::Socket idiom for exactly this and was measured to
554 # work on a real socket, a lexical filehandle, a bareword glob and a tied
555 # handle alike.
556 52 my $RBUF = __PACKAGE__ . '/rbuf';
557  
558 4174 ▶sub _read_buffer {
Subroutine _read_buffer: called CC=2 SCAR=6.9
559 4174 my ($self, $sock) = @_;
560  
561 4174 ▶ ${*$sock}{$RBUF} = '' unless defined ${*$sock}{$RBUF};
Branch: 1 branch
BranchTrueFalseTotal
unless defined do { *$sock }->{$RBUF} 206 3968 4174
562 4174 return \${*$sock}{$RBUF};
563 }
564  
565 # The one physical read. It answers with what happened rather than with a
566 # count, because a count makes every reader re-derive the same distinction and
567 # an undef quietly becoming an end of stream at any one of them is the silent
568 # truncation this transport must not have:
569 #
570 # 'data' something was appended to the buffer -- however little
571 # 'eof' the stream ended
572 # 'timeout' the read_timeout expired with nothing to show for it
573 #
574 # What TLS does here, since it is not obvious from the call. IO::Socket::SSL
575 # ties the glob, so the builtin sysread reaches the same place -- SSL_HANDLE's
576 # READ delegates to the object's own sysread -- and the method form is written
577 # out only so that the dispatch is visible rather than accidental. What does
578 # matter is sysread rather than read: IO::Socket::SSL's sysread is a single
579 # Net::SSLeay::read, one record, while its read is ssl_read_all on a blocking
580 # socket, which is the same fill semantics this is here to get away from.
581 #
582 # A short positive read is never an end of stream and never an expiry. Over
583 # TLS it is the normal case, one plaintext record at a time; over a plain
584 # socket it is whatever the kernel had. Both are data.
585 #
586 # SSL_WANT_READ and SSL_WANT_WRITE are deliberately not retried. On a blocking
587 # socket they arrive as EWOULDBLOCK (IO::Socket::SSL's _skip_rw_error does
588 # `$! ||= EWOULDBLOCK`) and mean the underlying receive would have blocked --
589 # which, with SO_RCVTIMEO in force, is the bound firing and nothing else.
590 # Retrying would be a busy loop on WANT_READ and could not make progress on
591 # WANT_WRITE in any case, so they are reported as the timeout they are.
592 2096 ▶sub _pull {
Subroutine _pull: called CC=5 SCAR=16.1
593 2096 my ($self, $sock, $ctx) = @_;
594  
595 2096 my $buf = $self->_read_buffer($sock);
596  
597 2096 while (1) {
598 # errno immediately before, errno immediately after, nothing in between:
599 # it is only meaningful after a failure, and any operation at all would
600 # overwrite it. See _timed_out.
601 2099 $! = 0;
602 2099 my $n = $sock->sysread(my $got, $READ_SIZE);
603 2096 my $errno = 0 + $!;
604  
605 2096 ▶ if (defined $n) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $n) 2047 49 2096
606 2047 ▶ return 'eof' unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 62 1985 2047
607 1985 $$buf .= $got;
608 1985 return 'data';
609 }
610  
611 # A signal is not an answer. perl's read() retried here of its own accord
612 # (PerlIOUnix_read loops while errno is EINTR), so retrying keeps the
613 # behaviour this replaces rather than introducing one.
614 49 ▶ next if $errno == EINTR;
Branch: 1 branch
BranchTrueFalseTotal
if $errno == 4 3 46 49
615  
616 46 ▶ return 'timeout' if $self->_timed_out($ctx, $errno);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_timed_out($ctx, $errno) 27 19 46
617  
618 # Anything else -- a reset connection, a handle that cannot be read at
619 # all -- ends the response, which is what it did before this too: every
620 # reader answered a failed read with `last unless $n`. Whether the
621 # response was complete when it ended is a question about its structure,
622 # and is asked by the readers that know the structure.
623 19 return 'eof';
624 }
625 }
626  
627 # The two reads every reader below is built out of. Both serve from the buffer
628 # and pull only when it is empty, so both hand back what has arrived rather
629 # than waiting for what was asked for.
630 851 ▶sub _read_line {
Subroutine _read_line: called CC=8 SCAR=20.8
631 851 my ($self, $sock, $ctx) = @_;
632 851 ▶ $ctx ||= {};
Condition50%1/2
$ctx ||= {}
l!l
8510
MC/DC0%0/1
$ctx ||= {}
$ctx
Truth table50%1/2
A
A= $ctx
Aresult
11
00
633  
634 851 my $buf = $self->_read_buffer($sock);
635 851 my $idx = index($$buf, "\n");
636  
637 851 ▶ while ($idx < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idx < 0) 1015 801 1816
638 1015 my $kind = $self->_pull($sock, $ctx);
639 # The part of a line already in the buffer is dropped, exactly as the
640 # readline this replaces dropped it: every line read here is protocol --
641 # a status line, a header, a chunk header -- never payload, so there is no
642 # callback it could belong to. What a buffered body had collected is
643 # reported instead, from $ctx->{partial}.
644 1012 ▶ $self->_croak_timeout($ctx, $ctx->{partial} ? ${ $ctx->{partial} } : '')
Branch: 2 branches
BranchTrueFalseTotal
if $kind eq "timeout" 13 999 1012
$ctx->{'partial'} ? : 3 10 13
645 if $kind eq 'timeout';
646 999 ▶ last if $kind eq 'eof';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "eof" 34 965 999
647 965 $idx = index($$buf, "\n");
648 }
649  
650 835 ▶ return substr($$buf, 0, $idx + 1, '') if $idx >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $idx >= 0 801 34 835
651  
652 # The stream ended. Whatever is left is a final line with no terminator,
653 # which is what readline hands back there as well; nothing left is undef.
654 34 ▶ return undef unless length $$buf;
Branch: 1 branch
BranchTrueFalseTotal
unless length $$buf 21 13 34
655 13 return substr($$buf, 0, length($$buf), '');
656 }
657  
658 # Returns (count, bytes) like the read() it replaces, so `last unless $n`
659 # still ends a loop at the end of the response. What changed is the count: it
660 # is now what had arrived, never more and no longer padded out by waiting.
661 # Every caller loops until it has what it needs, so a short count is a
662 # delivery rather than a truncation.
663 1225 ▶sub _read_bytes {
Subroutine _read_bytes: called CC=7 SCAR=19.5
664 1225 my ($self, $sock, $want, $ctx) = @_;
665 1225 ▶ $ctx ||= {};
Condition50%1/2
$ctx ||= {}
l!l
12250
MC/DC0%0/1
$ctx ||= {}
$ctx
Truth table50%1/2
A
A= $ctx
Aresult
11
00
666  
667 1225 my $buf = $self->_read_buffer($sock);
668  
669 1225 ▶ if (!length $$buf) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $$buf) 1081 144 1225
670 1081 my $kind = $self->_pull($sock, $ctx);
671 # Nothing is lost with this exception, and unlike under read() nothing has
672 # to be rescued for it either. sysread does not hand back data and EAGAIN
673 # together the way PerlIO's read() did: the bytes of every successful pull
674 # are already in the accumulator or already through the callback by the
675 # time a later pull expires, and the pull that expires carries none.
676 1081 ▶ $self->_croak_timeout($ctx, $ctx->{partial} ? ${ $ctx->{partial} } : '')
Branch: 2 branches
BranchTrueFalseTotal
if $kind eq "timeout" 14 1067 1081
$ctx->{'partial'} ? : 9 5 14
677 if $kind eq 'timeout';
678 1067 ▶ return (0, '') if $kind eq 'eof';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "eof" 47 1020 1067
679 }
680  
681 1164 ▶ my $take = $want < length($$buf) ? $want : length($$buf);
Branch: 1 branch
BranchTrueFalseTotal
$want < length $$buf ? : 83 1081 1164
682 1164 return ($take, substr($$buf, 0, $take, ''));
683 }
684  
685 # _read_bytes for a length the response announced, which is the whole of the
686 # difference: it appends onto the accumulator until it has all of $want, and
687 # an end of stream before then is truncation rather than the end of the body.
688 #
689 # Every `last unless $n` in a buffered reader used to be both -- the loop
690 # ended and what had been collected was returned as the response. Nothing
691 # compared the two, so a daemon that closed mid-body handed back a short body
692 # that every return shape this role promises accepts (karr k64).
693 #
694 # $into is the same scalar the reader is accumulating into, so the bytes of
695 # the incomplete piece are in $ctx->{partial} by the time this croaks and go
696 # out on the exception rather than being dropped.
697 104 ▶sub _read_exact {
Subroutine _read_exact: called CC=4 SCAR=13.9
698 104 my ($self, $sock, $want, $into, $ctx, $phase, $piece) = @_;
699  
700 104 my $read = 0;
701 104 ▶ while ($read < $want) {
Branch: 1 branch
BranchTrueFalseTotal
if ($read < $want) 516 84 600
702 516 my ($n, $buf) = $self->_read_bytes($sock, $want - $read, $ctx);
703 509 ▶ last unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 13 496 509
704 496 $$into .= $buf;
705 496 $read += $n;
706 }
707  
708 97 ▶ $self->_croak_truncated($ctx, phase => $phase, piece => $piece,
Branch: 1 branch
BranchTrueFalseTotal
if $read < $want 13 84 97
709 expected => $want, received => $read) if $read < $want;
710  
711 84 return $read;
712 }
713  
714 325 ▶sub _request {
Subroutine _request: called CC=51 SCAR=39.4
715 325 my ($self, $method, $path, %opts) = @_;
716  
717 # Checked while the request is assembled, like a header name: a caller that
718 # passes something else gets told before anything reaches the daemon,
719 # instead of after the round trip when the metadata fails to arrive.
720 croak __PACKAGE__ . '->_request response option must be a HashRef'
721 325 ▶ if exists $opts{response} && ref $opts{response} ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"response"} and ref $opts{"response"} ne "HASH" 1 324 325
Condition100%3/3
exists $opts{"response"} and ref $opts{"response"} ne "HASH"
!ll&&!rl&&r
288361
MC/DC100%2/2
exists $opts{"response"} and ref $opts{"response"} ne "HASH"
exists $opts{"response"} ref $opts{"response"} ne "HASH"
Truth table100%3/3
A and B
A= exists $opts{"response"}B= ref $opts{"response"} ne "HASH"
ABresult
0X0
100
111
722  
723 # Checked here for the same reason, and one at a time: the three units are
724 # three shapes the engine's streaming endpoints have, not three views of one
725 # stream, so a request asking for two of them has no answer.
726 324 my @streaming = grep { exists $opts{$_} } @STREAM_OPTION;
727 324 ▶ croak __PACKAGE__ . '->_request takes one of ' . join(', ', @STREAM_OPTION)
Branch: 1 branch
BranchTrueFalseTotal
if @streaming > 1 1 323 324
728 . ', not ' . join(' and ', @streaming) if @streaming > 1;
729 croak __PACKAGE__ . '->_request ' . $streaming[0] . ' option must be a CodeRef'
730 323 ▶ if @streaming && ref $opts{$streaming[0]} ne 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if @streaming and ref $opts{$streaming[0]} ne "CODE" 2 321 323
Condition100%3/3
@streaming and ref $opts{$streaming[0]} ne "CODE"
!ll&&!rl&&r
290312
MC/DC100%2/2
@streaming and ref $opts{$streaming[0]} ne "CODE"
@streaming ref $opts{$streaming[0]} ne "CODE"
Truth table100%3/3
A and B
A= @streamingB= ref $opts{$streaming[0]} ne "CODE"
ABresult
0X0
100
111
731  
732 321 my $version = $self->api_version;
733  
734 # Caller data -- a container name, an image reference -- is spliced straight
735 # into the request line through $path, so it is validated before it can reach
736 # the wire, exactly as a header name is. See _assert_request_path.
737 321 $self->_assert_request_path($path);
738  
739 312 ▶ my $url_path = defined $version ? "/v$version$path" : $path;
Branch: 1 branch
BranchTrueFalseTotal
defined $version ? : 312 0 312
740  
741 # Kept before the query string is appended: it names the request in an
742 # error message, and the query string is where /build carries buildargs,
743 # which can hold credentials and have no business in an exception.
744 312 my $endpoint = $method . ' ' . $url_path;
745  
746 # Definedness, not truth. A raw_body of '' (an empty tar) or of the string
747 # '0' is a body the caller asked to send, and testing it for truth dropped
748 # both: they fell through to the body branch, and the request then went out
749 # with no Content-Length, no Content-Type and no payload at all. Whether
750 # there is a body is therefore tracked separately from what it says.
751 312 my $body_content;
752 312 my $content_type = 'application/json';
753 312 ▶ if (defined $opts{raw_body}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'raw_body'}) { } 21 291 312
elsif ($opts{'body'}) { } 19 272 291
754 21 $body_content = $opts{raw_body};
755 21 ▶ $content_type = $opts{content_type} // 'application/x-tar';
Condition100%2/2
$opts{"content_type"} // "application/x-tar"
l!l
183
MC/DC100%1/1
$opts{"content_type"} // "application/x-tar"
$opts{"content_type"}
Truth table100%2/2
A
A= $opts{"content_type"}
Aresult
11
00
756 }
757 elsif ($opts{body}) {
758 19 $body_content = encode_json($opts{body});
759 }
760  
761 312 ▶ if ($opts{params}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"params"}) 129 183 312
762 129 my @pairs;
763 129 for my $k (sort keys %{$opts{params}}) {
764 179 my $v = $opts{params}{$k};
765 179 ▶ next unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 179 179
766 # An ArrayRef is one parameter given more than once, not one value:
767 # `names => ['a', 'b']` is `names=a&names=b`. That spelling is the only
768 # one GET /images/get accepts -- the comma-joined form is read as a
769 # single image reference and answered with 500 -- and Go's r.Form[k] is
770 # a list for every parameter, so it is the general shape rather than
771 # that endpoint's quirk. Element order is the caller's and is kept;
772 # only the keys are sorted.
773 179 ▶ for my $item (ref $v eq 'ARRAY' ? @$v : ($v)) {
Branch: 1 branch
BranchTrueFalseTotal
ref $v eq 'ARRAY' ? : 11 168 179
774 190 ▶ next unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 1 189 190
775 189 ▶ push @pairs, _uri_encode($k) . '='
Branch: 1 branch
BranchTrueFalseTotal
ref $item eq 'HASH' ? : 18 171 189
776 . _uri_encode(ref $item eq 'HASH' ? encode_json($item) : $item);
777 }
778 }
779 129 ▶ $url_path .= '?' . join('&', @pairs) if @pairs;
Branch: 1 branch
BranchTrueFalseTotal
if @pairs 110 19 129
780 }
781  
782 312 $log->debugf("%s %s", $method, $url_path);
783  
784 312 my $request = "$method $url_path HTTP/1.1\r\n";
785 312 $request .= "Host: localhost\r\n";
786 312 $request .= "Connection: close\r\n";
787 312 $request .= "User-Agent: API-Docker\r\n";
788  
789 312 ▶ if (defined $body_content) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $body_content) 40 272 312
790 40 $request .= "Content-Type: $content_type\r\n";
791 40 $request .= "Content-Length: " . length($body_content) . "\r\n";
792 }
793  
794 312 ▶ if ($opts{headers}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"headers"}) 19 293 312
795 19 for my $h (sort keys %{$opts{headers}}) {
796 # The name is validated before the value is even looked at: a name that
797 # cannot go on the wire is a caller bug whether or not the header ends
798 # up being sent.
799 19 $self->_assert_header_name($h);
800 11 my $v = $opts{headers}{$h};
801 11 ▶ next unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 11 11
802 11 $v =~ s/[\r\n]//g;
803 11 $request .= "$h: $v\r\n";
804 }
805 }
806  
807 304 $request .= "\r\n";
808 304 ▶ $request .= $body_content if defined $body_content;
Branch: 1 branch
BranchTrueFalseTotal
if defined $body_content 40 264 304
809  
810 my $handler = @streaming
811 ? $self->_stream_handler($endpoint, $streaming[0], $opts{$streaming[0]},
812 304 ▶ $opts{croak_on_error} // 1)
Branch: 1 branch
BranchTrueFalseTotal
@streaming ? : 31 273 304
Condition100%2/2
$opts{"croak_on_error"} // 1
l!l
1120
MC/DC100%1/1
$opts{"croak_on_error"} // 1
$opts{"croak_on_error"}
Truth table100%2/2
A
A= $opts{"croak_on_error"}
Aresult
11
00
813 : undef;
814  
815 # Resolved with exists rather than truth, so `read_timeout => 0` is a
816 # request to wait as long as it takes and can turn a client-wide default off
817 # for one call -- which `//` would have read as "no opinion" and overridden.
818 my $timeout = $self->_read_timeout_value(
819 304 ▶ exists $opts{read_timeout} ? $opts{read_timeout} : $self->read_timeout);
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'read_timeout'} ? : 11 293 304
820  
821 # Same resolution, same reason.
822 my $connect_timeout = $self->_connect_timeout_value(
823 exists $opts{connect_timeout}
824 301 ▶ ? $opts{connect_timeout} : $self->connect_timeout);
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'connect_timeout'} ? : 9 292 301
825  
826 # The endpoint without its query string, for the same reason the >= 400
827 # croak uses that form.
828 301 my $ctx = { endpoint => $endpoint, timeout => $timeout };
829  
830 301 my $sock = $self->_reconnect(
831 { timeout => $connect_timeout, endpoint => $endpoint });
832 # Applied here rather than in _build__socket because the value is per
833 # request, not per client: a socket is opened and closed for each one, so
834 # this is the connection the option belongs to.
835 283 $self->_apply_read_timeout($sock, $timeout);
836  
837 # The request goes out with SIGPIPE ignored and every write checked
838 # (karr k114). A daemon that answers and closes before it has read the
839 # body -- dockerd does this for a rejected put_archive or build -- used to
840 # raise SIGPIPE on the next write and end the calling process with status
841 # 141, no exception. Now the failed write is only remembered: the response
842 # the daemon may already have sent is still read, so a 4xx reaches the
843 # caller as an Error::HTTP, and only when there is none is the write error
844 # the answer.
845 283 my $write_error;
846 # print rather than syswrite: it also serves the in-memory sinks the test
847 # transports use, and IO::Socket handles are autoflushed, so its result is
848 # the result of the write.
849 {
850 283 local $SIG{PIPE} = 'IGNORE';
851 283 ▶ $write_error = $!.'' unless print $sock $request;
Branch: 1 branch
BranchTrueFalseTotal
unless print $sock $request 2 281 283
852 }
853  
854 # Reading can croak, and now does so from further in than it used to: an
855 # on_event stream raises Error::Stream at the event that reports the
856 # failure, and an on_frame stream refuses a header that is not one. Without
857 # the eval those exceptions leave the socket open until the next request
858 # replaces it, so it is closed on the way out either way and the exception
859 # re-raised unchanged.
860 283 my $response;
861 283 ▶ my $ok = eval { $response = $handler
Branch: 1 branch
BranchTrueFalseTotal
$handler ? : 31 252 283
862 ? $self->_read_streaming_response($sock, $method, $handler, $ctx)
863 266 : $self->_read_response($sock, $method, $ctx); 1 };
864 283 my $err = $@;
865 283 close $sock;
866 283 $self->_clear_socket;
867 283 ▶ if (!$ok && defined $write_error) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ok and defined $write_error) 1 282 283
Condition100%3/3
not $ok and defined $write_error
!ll&&!rl&&r
266161
MC/DC100%2/2
not $ok and defined $write_error
not $ok defined $write_error
Truth table100%3/3
not(A) and B
A= not $okB= defined $write_error
ABresult
0X0
100
111
868 # The daemon sent nothing usable and the write had failed: the write is
869 # the cause, and the endpoint belongs in the message.
870 1 croak 'Docker API request to '.$endpoint.' failed: could not send the '
871 .'request ('.$write_error.') and no response followed';
872 }
873 282 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 16 266 282
874  
875 266 my ($status_code, $status_text, $headers, $body, $summary) = @$response;
876  
877 266 $log->debugf("Response: %s %s", $status_code, $status_text);
878  
879 # The status line and the response headers are metadata the return value
880 # cannot carry: it is the decoded body and nothing else, so 204 and 304 are
881 # both undef and a header holding the payload -- HEAD
882 # /containers/{id}/archive answers with an empty body and
883 # X-Docker-Container-Path-Stat -- is unreachable. They go into a hash the
884 # caller supplies, so no existing caller's return shape changes. Filled
885 # before the croak below, so an eval'ing caller can still read the status.
886 266 ▶ if (my $out = $opts{response}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $out = $opts{"response"}) 35 231 266
887 35 %$out = (
888 status => $status_code,
889 reason => $status_text,
890 headers => $headers,
891 );
892 }
893  
894 266 ▶ if ($status_code >= 400) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status_code >= 400) 23 243 266
895 23 my $error_msg = $body;
896 23 my $data;
897 23 ▶ if ($body && $body =~ /^\s*[\{\[]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body and $body =~ /^\s*[\{\[]/) 21 2 23
Condition66%2/3
$body and $body =~ /^\s*[\{\[]/
!ll&&!rl&&r
0221
MC/DC50%1/2
$body and $body =~ /^\s*[\{\[]/
$body $body =~ /^\s*[\{\[]/
Truth table66%2/3
A and B
A= $bodyB= $body =~ /^\s*[\{\[]/
ABresult
0X0
100
111
898 21 eval {
899 21 $data = decode_json($body);
900 # Docker answers with {"message":...}. Podman answers a failed push
901 # with the stream shape instead -- {"errorDetail":{"message":...},
902 # "error":...} and no message key at all -- so without these two
903 # fallbacks the whole JSON object became the croak text (karr k13).
904 my $detail = ref $data->{errorDetail} eq 'HASH'
905 19 ▶ ? $data->{errorDetail}{message} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $data->{'errorDetail'} eq 'HASH' ? : 2 16 18
906 18 ▶ $error_msg = $data->{message} // $detail // $data->{error} // $body;
Condition66%6/9
(($data->{"message"} // $detail) // $data->{"error"}) // $body
l!l&&r!l&&!r
1800
($data->{"message"} // $detail) // $data->{"error"}
l!l&&r!l&&!r
1710
$data->{"message"} // $detail
l!l&&r!l&&!r
1611
MC/DC0%0/4
(($data->{"message"} // $detail) // $data->{"error"}) // $body
$data->{"message"} $detail $data->{"error"} $body
Truth table60%3/5
A // B // C // D
A= $data->{"message"}B= $detailC= $data->{"error"}D= $body
ABCDresult
1XXX1
01XX1
001X1
00011
00000
907 };
908 }
909  
910 # Carp hands a reference straight back rather than decorating it, so this
911 # croak is a die with an object -- hence the location captured by hand,
912 # which names the same frame a croak of a plain string would have named.
913 # message . location is byte for byte what the string croak produced,
914 # newline-terminated engine messages included: Carp appends the suffix
915 # after the newline rather than skipping it (karr k50).
916 23 ▶ my $error = API::Docker::Error::HTTP->new(
Condition50%1/2
$body // ""
l!l
230
MC/DC0%0/1
$body // ""
$body
Truth table50%1/2
A
A= $body
Aresult
11
00
917 message => "Docker API error ($status_code): $error_msg",
918 location => shortmess(''),
919 status => $status_code,
920 reason => $status_text,
921 body => $body // '',
922 data => $data,
923 );
924 23 croak $error;
925 }
926  
927 # A streamed request has handed every unit to the callback already and kept
928 # none of them, so there is no body left to decode and return. What the
929 # caller cannot know otherwise is how the stream ended, and that is what
930 # comes back instead.
931 243 ▶ return $summary if $summary;
Branch: 1 branch
BranchTrueFalseTotal
if $summary 23 220 243
932  
933 # Zero bytes is a different answer in each shape a request can ask for, so
934 # the two options that promise one are answered before the empty-body check
935 # rather than after it. `raw` promises the response bytes and a body of no
936 # bytes is '', which a caller can take length() of; `ndjson` promises an
937 # ArrayRef of events even for a stream carrying a single object, so a stream
938 # that carried none is []. Returning undef for both broke each promise
939 # exactly where the engine legitimately says nothing.
940 220 ▶ $body = '' unless defined $body;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $body 3 217 220
941  
942 # The framed endpoints (logs, attach, exec/start) carry arbitrary bytes
943 # that must not be mistaken for JSON -- a TTY container printing a JSON
944 # line would otherwise come back decoded.
945 220 ▶ return $body if $opts{raw};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"raw"} 32 188 220
946  
947 # Streaming endpoints (/build, /images/create, /images/*/push) always
948 # return an ArrayRef of events, even when the stream carried exactly one
949 # object. See _decode_stream.
950 188 ▶ if ($opts{ndjson}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"ndjson"}) 34 154 188
951 34 my $events = $self->_decode_stream($body);
952 # A failed build, pull or push is HTTP 200 with the failure buried in the
953 # stream, so the status line above cannot catch it. Opt out for a stream
954 # whose objects are engine data rather than the outcome of one operation.
955 $self->_assert_no_stream_error($endpoint, $events)
956 34 ▶ if $opts{croak_on_error} // 1;
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"croak_on_error"} // 1 31 3 34
Condition100%2/2
$opts{"croak_on_error"} // 1
l!l
331
MC/DC100%1/1
$opts{"croak_on_error"} // 1
$opts{"croak_on_error"}
Truth table100%2/2
A
A= $opts{"croak_on_error"}
Aresult
11
00
957 25 return $events;
958 }
959  
960 # Nothing was asked of the body's shape and there is no body, so there is
961 # nothing to hand back. 204 says so in the status line and is taken at its
962 # word even if bytes follow it.
963 154 ▶ return undef if $status_code == 204 || $body eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $status_code == 204 or $body eq "" 65 89 154
Condition100%3/3
$status_code == 204 or $body eq ""
l!l&&r!l&&!r
135289
MC/DC100%2/2
$status_code == 204 or $body eq ""
$status_code == 204 $body eq ""
Truth table100%3/3
A or B
A= $status_code == 204B= $body eq ""
ABresult
1X1
011
000
964  
965 # A body that is JSON is decoded, whichever JSON value it is. The guard was
966 # `{` or `[` alone, which returned a body that is a bare JSON scalar as its
967 # own bytes: `null` came back as the four-character string 'null'. The
968 # engine sends exactly that where a Go nil slice or pointer is the whole
969 # response -- GET /plugins/privileges for a plugin that demands nothing,
970 # GET /containers/{id}/changes for a container that changed nothing -- and
971 # the string is neither the ArrayRef those endpoints document nor anything
972 # a caller can iterate.
973 #
974 # The eval decides, not the pattern: a plain-text body that happens to
975 # start with one of these characters fails to decode and is returned as
976 # itself. So must the eval's success, not its result -- decode_json('null')
977 # is a successful decode to undef.
978 89 ▶ if ($body =~ $JSON_BODY) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body =~ /$JSON_BODY/) 88 1 89
979 88 my $decoded;
980 88 ▶ return $decoded if eval { $decoded = decode_json($body); 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $decoded = &decode_json($body); 1 } } 85 3 88
981 }
982  
983 4 return $body;
984 }
985  
986 41 ▶sub _decode_stream {
Subroutine _decode_stream: called CC=6 SCAR=17.9
987 41 my ($self, $body) = @_;
988  
989 # Newline-delimited JSON: one object per line. A literal newline cannot
990 # occur inside a JSON string, so splitting on lines is safe.
991 41 my @events;
992 41 for my $line (split /\r?\n/, $body) {
993 97 ▶ next unless $line =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /\S/ 0 97 97
994 97 my $event = eval { decode_json($line) };
995 97 ▶ push @events, $event if defined $event;
Branch: 1 branch
BranchTrueFalseTotal
if defined $event 93 4 97
996 }
997  
998 # Fall back to the whole body for a stream that is not newline-framed
999 # (a single pretty-printed object), so nothing is silently dropped.
1000 41 ▶ unless (@events) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@events) 4 37 41
1001 4 my $event = eval { decode_json($body) };
1002 4 ▶ push @events, $event if defined $event;
Branch: 1 branch
BranchTrueFalseTotal
if defined $event 1 3 4
1003 }
1004  
1005 41 return \@events;
1006 }
1007  
1008 40 ▶sub _assert_no_stream_error {
Subroutine _assert_no_stream_error: called CC=9 SCAR=22.1
1009 40 my ($self, $endpoint, $events) = @_;
1010  
1011 40 for my $event (@$events) {
1012 67 ▶ next unless ref $event eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $event eq "HASH" 2 65 67
1013 65 my $detail = $event->{errorDetail};
1014 65 ▶ next unless defined $detail;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $detail 54 11 65
1015  
1016 # errorDetail is a HashRef carrying the message. The engine sends a flat
1017 # `error` next to it with the same text; that is the fallback, not the
1018 # trigger -- the trigger is errorDetail, and nothing else.
1019 11 ▶ my $reason = ref $detail eq 'HASH' ? $detail->{message} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $detail eq 'HASH' ? : 11 0 11
1020 11 ▶ $reason = $event->{error} unless defined $reason && length $reason;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $reason and length $reason 2 9 11
Condition66%2/3
defined $reason and length $reason
!ll&&!rl&&r
209
MC/DC50%1/2
defined $reason and length $reason
defined $reason length $reason
Truth table66%2/3
A and B
A= defined $reasonB= length $reason
ABresult
0X0
100
111
1021 11 ▶ $reason = 'no message given' unless defined $reason && length $reason;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $reason and length $reason 1 10 11
Condition66%2/3
defined $reason and length $reason
!ll&&!rl&&r
1010
MC/DC50%1/2
defined $reason and length $reason
defined $reason length $reason
Truth table66%2/3
A and B
A= defined $reasonB= length $reason
ABresult
0X0
100
111
1022 # Engine messages end in a newline, and Carp appends no location to a
1023 # message that already does.
1024 11 $reason =~ s/\s+\z//;
1025  
1026 # Carp hands a reference straight back rather than decorating it, so this
1027 # croak is a die with an object -- hence the location captured by hand,
1028 # which names the same frame a croak of a plain string would have named.
1029 # The object goes into a variable first: `croak CLASS->new(...)` is
1030 # indirect object syntax and parses as CLASS->croak(new(...)).
1031 11 my $error = API::Docker::Error::Stream->new(
1032 message => 'Docker API stream error (' . $endpoint . '): ' . $reason,
1033 events => $events,
1034 location => shortmess(''),
1035 );
1036 11 croak $error;
1037 }
1038  
1039 29 return;
1040 }
1041  
1042 19 ▶sub _assert_header_name {
Subroutine _assert_header_name: called CC=4 SCAR=14.0
1043 19 my ($self, $name) = @_;
1044  
1045 19 ▶ return if defined $name && $name =~ $HEADER_NAME;
Branch: 1 branch
BranchTrueFalseTotal
if defined $name and $name =~ /$HEADER_NAME/ 11 8 19
Condition66%2/3
defined $name and $name =~ /$HEADER_NAME/
!ll&&!rl&&r
0811
MC/DC50%1/2
defined $name and $name =~ /$HEADER_NAME/
defined $name $name =~ /$HEADER_NAME/
Truth table66%2/3
A and B
A= defined $nameB= $name =~ /$HEADER_NAME/
ABresult
0X0
100
111
1046  
1047 8 ▶ my $display = defined $name ? $name : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 8 0 8
1048 8 $display =~ s/([^\x20-\x7E])/sprintf('\\x%02X', ord $1)/ge;
1049 8 croak __PACKAGE__ . '->_request invalid header name "' . $display . '": a '
1050 . 'header name must be an RFC 9110 token (letters, digits and '
1051 . '!#$%&\'*+-.^_`|~). A name is rejected rather than sanitised: unlike a '
1052 . 'value, there is no benign way for one to carry CR, LF, a space or a '
1053 . 'colon, and rewriting it would send a header the caller never wrote';
1054 }
1055  
1056 321 ▶sub _assert_request_path {
Subroutine _assert_request_path: called CC=4 SCAR=14.0
1057 321 my ($self, $path) = @_;
1058  
1059 321 ▶ return if defined $path && $path =~ $REQUEST_PATH;
Branch: 1 branch
BranchTrueFalseTotal
if defined $path and $path =~ /$REQUEST_PATH/ 312 9 321
Condition66%2/3
defined $path and $path =~ /$REQUEST_PATH/
!ll&&!rl&&r
09312
MC/DC50%1/2
defined $path and $path =~ /$REQUEST_PATH/
defined $path $path =~ /$REQUEST_PATH/
Truth table66%2/3
A and B
A= defined $pathB= $path =~ /$REQUEST_PATH/
ABresult
0X0
100
111
1060  
1061 9 ▶ my $display = defined $path ? $path : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $path ? : 9 0 9
1062 9 $display =~ s/([^\x20-\x7E])/sprintf('\\x%02X', ord $1)/ge;
1063 9 croak __PACKAGE__ . '->_request invalid request path "' . $display . '": a '
1064 . 'path may hold only request-target characters (letters, digits, -._~ '
1065 . 'and :/@!$&\'()*+,;=%). It is spliced straight into the request line, so '
1066 . 'a space, CR, LF, ? or # in a container name or image reference would '
1067 . 'rewrite the request rather than name a resource. A path is rejected '
1068 . 'rather than sanitised: percent-encoding it here cannot tell a path '
1069 . 'separator from data -- pass query parameters as `params`, not in the '
1070 . 'path';
1071 }
1072  
1073 82 ▶sub _read_response {
Subroutine _read_response: called CC=2 SCAR=6.9
1074 82 my ($self, $sock, $method, $ctx) = @_;
1075 # A context is what _request builds to say how long a silence may last and
1076 # what the exception has to name. It defaults to an empty one -- no timeout,
1077 # every read exactly as it was -- so the readers stay drivable directly, as
1078 # t/role_http.t drives them.
1079 82 ▶ $ctx ||= {};
Condition100%2/2
$ctx ||= {}
l!l
6517
MC/DC100%1/1
$ctx ||= {}
$ctx
Truth table100%2/2
A
A= $ctx
Aresult
11
00
1080  
1081 82 my $head = $self->_read_head($sock, $ctx);
1082 70 return [ @$head, $self->_read_body($sock, $head->[2], $method, $ctx) ];
1083 }
1084  
1085 174 ▶sub _read_head {
Subroutine _read_head: called CC=7 SCAR=19.5
1086 174 my ($self, $sock, $ctx) = @_;
1087 174 ▶ $ctx ||= {};
Condition50%1/2
$ctx ||= {}
l!l
1740
MC/DC0%0/1
$ctx ||= {}
$ctx
Truth table50%1/2
A
A= $ctx
Aresult
11
00
1088  
1089 # Looped so a 1xx informational response is read whole and passed by: it is a
1090 # complete head -- a status line and an optional field section closed by the
1091 # blank line -- with no body of its own, sent before the real response
1092 # (RFC 9110 section 15.2). Without this the reader took the 1xx status as the
1093 # response and then read the real response as its body. A 100 Continue is the
1094 # one an HTTP/1.1 client is most likely to be sent; 102 and 103 have the same
1095 # framing.
1096 174 while (1) {
1097 178 my $status_line = $self->_read_line($sock, $ctx);
1098 # A daemon that closed without answering at all, which is the one shape here
1099 # that was never silent and is left saying exactly what it always said.
1100 175 ▶ croak "No response from Docker daemon" unless defined $status_line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $status_line 4 171 175
1101 171 $self->_assert_status_line($ctx, $status_line);
1102 163 $status_line =~ s/\r?\n$//;
1103  
1104 163 my ($proto, $status_code, $status_text) = split /\s+/, $status_line, 3;
1105  
1106 # while(1)-and-assert rather than `while (my $line = ...)`, which is the
1107 # same shape _read_chunked uses and for the same reason: the loop used to
1108 # end on anything false, so an end of stream inside the header block left it
1109 # exactly as the blank line would have. The assert is now the only way out
1110 # that is not the blank line.
1111 163 my %headers;
1112 163 while (1) {
1113 362 my $line = $self->_read_line($sock, $ctx);
1114 360 $self->_assert_header_line($ctx, $line);
1115 352 $line =~ s/\r?\n$//;
1116 352 ▶ last if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 153 199 352
1117 199 ▶ if ($line =~ /^([^:]+):\s*(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^([^:]+):\s*(.*)$/) 199 0 199
1118 199 $headers{lc $1} = $2;
1119 }
1120 }
1121  
1122 # The status code is three digits by now (_assert_status_line), so a 1xx is
1123 # exactly 100..199. Its headers are dropped with it and the next head read.
1124 153 ▶ next if $status_code >= 100 && $status_code < 200;
Branch: 1 branch
BranchTrueFalseTotal
if $status_code >= 100 and $status_code < 200 4 149 153
Condition66%2/3
$status_code >= 100 and $status_code < 200
!ll&&!rl&&r
01494
MC/DC50%1/2
$status_code >= 100 and $status_code < 200
$status_code >= 100 $status_code < 200
Truth table66%2/3
A and B
A= $status_code >= 100B= $status_code < 200
ABresult
0X0
100
111
1125  
1126 149 return [$status_code, $status_text, \%headers];
1127 }
1128 }
1129  
1130 # The two ways the head ends early, and neither of them has a byte count to
1131 # compare either (karr k73).
1132 #
1133 # karr k64 left the head out on the grounds that nothing in a status line or a
1134 # header block announces its own length, so there was no announcement to hold
1135 # a short one against. True, and beside the point: an announcement is not what
1136 # is being checked here, any more than it is in _assert_chunk_header one level
1137 # down. HTTP/1.1 frames the head by terminating every line, and the field
1138 # section by an empty line that is mandatory even when there are no fields at
1139 # all (RFC 9112 section 2.1), so "the stream ended where the terminator
1140 # belongs" is a complete test on its own. It is the same question that reader
1141 # already asks about a chunk header, asked of the head.
1142 #
1143 # What it was worth. A head cut short is not just a bogus status: the response
1144 # is then read with whichever headers happened to arrive, and a cut landing
1145 # before Content-Length or Transfer-Encoding leaves neither -- which is
1146 # exactly the close-delimited branch of _read_body, where an EOF is the
1147 # legitimate end and nothing looks wrong. Measured over a socketpair whose
1148 # peer writes "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nX-Half"
1149 # and closes: status 200, one header, an empty body, no complaint. The cuts
1150 # that did get caught were caught by accident one level lower, because the
1151 # half-arrived header happened to be one of those two.
1152 #
1153 # Nothing legitimate ends a head without the blank line, which was measured
1154 # rather than taken from the RFC, on both engines and including the two heads
1155 # an engine writes by hand instead of through its HTTP server: attach and
1156 # /exec/{id}/start answer with "HTTP/1.1 200 OK", one Content-Type line and
1157 # the blank line, on Docker 29.7.2 and on rootless Podman 5.8.4 alike. So do
1158 # 204, 304, HEAD, chunked and every other shape either of them produces.
1159 171 ▶sub _assert_status_line {
Subroutine _assert_status_line: called CC=4 SCAR=13.9
1160 171 my ($self, $ctx, $line) = @_;
1161  
1162 # Only the unterminated half: a status line that never started at all is the
1163 # croak above, which says something better than this could.
1164 171 ▶ $self->_croak_truncated($ctx, phase => 'status-line',
Branch: 2 branches
BranchTrueFalseTotal
unless $line =~ /\n\z/ 4 167 171
length $line == 1 ? : 0 4 4
1165 detail => 'the stream ended inside the status line, after '
1166 . length($line) . ' byte' . (length($line) == 1 ? '' : 's') . ' of one')
1167 unless $line =~ /\n\z/;
1168  
1169 # Terminated, and now: is it an HTTP status line at all? RFC 9112 section 4:
1170 # HTTP-version SP status-code SP [ reason-phrase ], with status-code exactly
1171 # three digits. A line that arrived whole but is not this shape -- a proxy's
1172 # plain-text banner, an ICY greeting, an HTML error page -- would otherwise
1173 # be split on whitespace in _read_head and its second word run through the
1174 # >= 400 comparison as the status. It is refused here rather than silently
1175 # misread, the same way a non-hexadecimal chunk size is one level down.
1176 167 my $stripped = $line =~ s/\r?\n\z//r;
1177 167 ▶ $self->_croak_truncated($ctx, phase => 'status-line',
Branch: 1 branch
BranchTrueFalseTotal
unless $stripped =~ m[\AHTTP/[0-9]+\.[0-9]+ [0-9]{3}(?: .*)?\z] 4 163 167
1178 detail => "the status line '" . $stripped
1179 . "' is not a well-formed HTTP status line")
1180 unless $stripped =~ m{\AHTTP/[0-9]+\.[0-9]+ [0-9]{3}(?: .*)?\z};
1181  
1182 163 return;
1183 }
1184  
1185 # Both halves here, because the header block has no equivalent of that croak:
1186 # undef is a block that was never closed -- with no headers at all, or after
1187 # some -- and an unterminated line is one cut in the middle of a field.
1188 360 ▶sub _assert_header_line {
Subroutine _assert_header_line: called CC=4 SCAR=13.9
1189 360 my ($self, $ctx, $line) = @_;
1190  
1191 360 ▶ $self->_croak_truncated($ctx, phase => 'header-block',
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 5 355 360
1192 detail => 'the stream ended where a header line belongs, with no blank '
1193 . 'line to close the header block')
1194 unless defined $line;
1195  
1196 355 ▶ $self->_croak_truncated($ctx, phase => 'header-block',
Branch: 2 branches
BranchTrueFalseTotal
unless $line =~ /\n\z/ 3 352 355
length $line == 1 ? : 0 3 3
1197 detail => 'the stream ended inside a header line, after '
1198 . length($line) . ' byte' . (length($line) == 1 ? '' : 's') . ' of one')
1199 unless $line =~ /\n\z/;
1200  
1201 352 return;
1202 }
1203  
1204 80 ▶sub _read_body {
Subroutine _read_body: called CC=9 SCAR=22.0
1205 80 my ($self, $sock, $headers, $method, $ctx) = @_;
1206 80 ▶ $ctx ||= {};
Condition50%1/2
$ctx ||= {}
l!l
800
MC/DC0%0/1
$ctx ||= {}
$ctx
Truth table50%1/2
A
A= $ctx
Aresult
11
00
1207  
1208 # A HEAD response repeats the header fields the equivalent GET would send --
1209 # Content-Length and Transfer-Encoding included -- and then sends no body at
1210 # all. Every branch below would wait for bytes that never arrive: until the
1211 # daemon closes the connection at best, and forever if it does not. So the
1212 # body is not read for HEAD, whatever the headers promise.
1213 80 ▶ return '' if defined $method && uc($method) eq 'HEAD';
Branch: 1 branch
BranchTrueFalseTotal
if defined $method and uc $method eq "HEAD" 3 77 80
Condition100%3/3
defined $method and uc $method eq "HEAD"
!ll&&!rl&&r
11663
MC/DC100%2/2
defined $method and uc $method eq "HEAD"
defined $method uc $method eq "HEAD"
Truth table100%3/3
A and B
A= defined $methodB= uc $method eq "HEAD"
ABresult
0X0
100
111
1214  
1215 77 ▶ if ($headers->{'transfer-encoding'}
Branch: 1 branch
BranchTrueFalseTotal
if ($headers->{"transfer-encoding"} and lc $headers->{"transfer-encoding"} eq "chunked") 20 57 77
Condition66%2/3
$headers->{"transfer-encoding"} and lc $headers->{"transfer-encoding"} eq "chunked"
!ll&&!rl&&r
57020
MC/DC50%1/2
$headers->{"transfer-encoding"} and lc $headers->{"transfer-encoding"} eq "chunked"
$headers->{"transfer-encoding"} lc $headers->{"transfer-encoding"} eq "chunked"
Truth table66%2/3
A and B
A= $headers->{"transfer-encoding"}B= lc $headers->{"transfer-encoding"} eq "chunked"
ABresult
0X0
100
111
1216 && lc($headers->{'transfer-encoding'}) eq 'chunked') {
1217 20 return $self->_read_chunked($sock, $ctx);
1218 }
1219  
1220 57 ▶ if (defined $headers->{'content-length'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $headers->{"content-length"}) 45 12 57
1221 45 my $len = $self->_assert_content_length($ctx, $headers->{'content-length'});
1222 41 ▶ return '' unless $len > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $len > 0 1 40 41
1223 40 my $body = '';
1224 # What a timeout hands over instead of dropping: see
1225 # API::Docker::Error::Timeout/partial. localised so the context goes back
1226 # to carrying nothing once this body is done with.
1227 40 local $ctx->{partial} = \$body;
1228 # An announced length is a promise, and a stream that ends before it is
1229 # kept is truncation rather than the end of the body; see _read_exact.
1230 40 $self->_read_exact($sock, $len, \$body, $ctx, 'content-length',
1231 'the body');
1232 25 return $body;
1233 }
1234  
1235 # Read until the daemon closes. This used to be a `local $/; <$sock>` slurp;
1236 # it is a loop over the same primitive as the other two branches now, which
1237 # is what karr k60 needed and what the timeout wanted anyway -- with $/ undef
1238 # a whole body and a truncated one are both just bytes, so the slurp's own
1239 # result could never say which it was. This is the path karr k52's hang is
1240 # on, an attach whose buffered frames arrive and whose socket then never
1241 # closes.
1242 #
1243 # And the one shape with no completeness check to make: the response
1244 # announced no end, so the close IS the end (karr k64). Treating an EOF here
1245 # as truncation would make every attach, every logs(follow) and every
1246 # exec/start fail on the daemon hanging up, which is how all three finish.
1247 12 my $body = '';
1248 # What a timeout hands over instead of dropping; see the content-length
1249 # branch above.
1250 12 local $ctx->{partial} = \$body;
1251 12 while (1) {
1252 20 my ($n, $buf) = $self->_read_bytes($sock, $READ_SIZE, $ctx);
1253 18 ▶ last unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 10 8 18
1254 8 $body .= $buf;
1255 }
1256  
1257 10 return $body;
1258 }
1259  
1260 # The incremental sibling of _read_response. Same [status, reason, headers,
1261 # body] shape, plus a fifth element: the summary of what the callback was
1262 # handed. The body it returns is empty -- that is the point, nothing is kept --
1263 # except on the two paths that fall back to reading whole, which return undef
1264 # as the summary instead so _request treats them exactly as before.
1265 79 ▶sub _read_streaming_response {
Subroutine _read_streaming_response: called CC=25 SCAR=32.3
1266 79 my ($self, $sock, $method, $handler, $ctx) = @_;
1267 79 ▶ $ctx ||= {};
Condition50%1/2
$ctx ||= {}
l!l
790
MC/DC0%0/1
$ctx ||= {}
$ctx
Truth table50%1/2
A
A= $ctx
Aresult
11
00
1268  
1269 79 my ($status_code, $status_text, $headers) = @{ $self->_read_head($sock, $ctx) };
1270  
1271 # Neither of these is a stream. A >= 400 body is a short JSON object naming
1272 # the failure and _request has to croak with it, so it is read whole and the
1273 # callback never sees it; a HEAD response has no body at all.
1274 79 ▶ if ($status_code >= 400 || (defined $method && uc($method) eq 'HEAD')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status_code >= 400 or defined $method and uc $method eq "HEAD") 2 77 79
Condition50%3/6
$status_code >= 400 or defined $method and uc $method eq "HEAD"
l!l&&r!l&&!r
2077
defined $method and uc $method eq "HEAD"
!ll&&!rl&&r
0770
MC/DC33%1/3
$status_code >= 400 or defined $method and uc $method eq "HEAD"
$status_code >= 400 defined $method uc $method eq "HEAD"
Truth table50%2/4
A or B and C
A= $status_code >= 400B= defined $methodC= uc $method eq "HEAD"
ABCresult
1XX1
0111
00X0
0100
1275 2 return [$status_code, $status_text, $headers,
1276 $self->_read_body($sock, $headers, $method, $ctx), undef];
1277 }
1278  
1279 # Set only here, past the two branches above, so a timeout while reading an
1280 # error body is still reported in bytes rather than in units nothing
1281 # delivered. From this point on an expiry carries the callback's own summary
1282 # instead: the units are with the caller already, and how many is the part it
1283 # cannot know otherwise.
1284 77 local $ctx->{summary} = $handler->{summary};
1285  
1286 77 my $feed = $handler->{feed};
1287 77 my $more = 1;
1288  
1289 # There is deliberately nothing here to hand the callback the bytes of the
1290 # read that expires. karr k59 needed that hook because PerlIO's read() could
1291 # come back with data *and* EAGAIN at once, so a stall could land with the
1292 # whole response read and none of it fed; sysread cannot (karr k60). Every
1293 # byte reaches the callback in the pull that delivered it, and the pull that
1294 # expires delivers none -- so the property k59 established now holds by
1295 # construction instead of by rescue.
1296  
1297 77 ▶ if ($headers->{'transfer-encoding'}
Branch: 2 branches
BranchTrueFalseTotal
if ($headers->{'transfer-encoding'} and lc $headers->{'transfer-encoding'} eq 'chunked') { } 44 33 77
elsif (defined $headers->{'content-length'}) { } 10 23 33
Condition66%2/3
$headers->{"transfer-encoding"} and lc $headers->{"transfer-encoding"} eq "chunked"
!ll&&!rl&&r
33044
MC/DC50%1/2
$headers->{"transfer-encoding"} and lc $headers->{"transfer-encoding"} eq "chunked"
$headers->{"transfer-encoding"} lc $headers->{"transfer-encoding"} eq "chunked"
Truth table66%2/3
A and B
A= $headers->{"transfer-encoding"}B= lc $headers->{"transfer-encoding"} eq "chunked"
ABresult
0X0
100
111
1298 && lc($headers->{'transfer-encoding'}) eq 'chunked') {
1299 44 ▶ while ($more) {
Branch: 1 branch
BranchTrueFalseTotal
if ($more) 98 0 98
1300 98 my $chunk_header = $self->_read_line($sock, $ctx);
1301 95 my $chunk_size = $self->_assert_chunk_header($ctx, $chunk_header);
1302 90 ▶ last if $chunk_size == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk_size == 0 18 72 90
1303  
1304 72 my $read = 0;
1305 72 ▶ while ($read < $chunk_size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($read < $chunk_size) 567 57 624
1306 567 my ($n, $buf) = $self->_read_bytes($sock, $chunk_size - $read, $ctx);
1307 566 ▶ last unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 3 563 566
1308 563 $read += $n;
1309 # Fed per read rather than per completed chunk. A chunk is the
1310 # daemon's framing, not the caller's -- the engine is free to send an
1311 # hour of log output as one chunk -- so waiting for the whole of one
1312 # would reintroduce exactly the buffering this path exists to avoid.
1313 563 $more = $feed->($buf);
1314 560 ▶ last unless $more;
Branch: 1 branch
BranchTrueFalseTotal
unless $more 8 552 560
1315 }
1316  
1317 # Every truncation check on this path is guarded by $more, and that is
1318 # the whole of what distinguishes the two ways a streamed chunk ends
1319 # early: the daemon ran out, or the callback said stop. A caller that
1320 # stopped left the rest of the chunk unread on purpose (karr k64).
1321 68 ▶ $self->_croak_truncated($ctx, phase => 'chunk-data', piece => 'a chunk',
Branch: 1 branch
BranchTrueFalseTotal
if $more and $read < $chunk_size 3 65 68
Condition100%3/3
$more and $read < $chunk_size
!ll&&!rl&&r
8573
MC/DC100%2/2
$more and $read < $chunk_size
$more $read < $chunk_size
Truth table100%3/3
A and B
A= $moreB= $read < $chunk_size
ABresult
0X0
100
111
1322 expected => $chunk_size, received => $read)
1323 if $more && $read < $chunk_size;
1324 65 ▶ last unless $more;
Branch: 1 branch
BranchTrueFalseTotal
unless $more 8 57 65
1325  
1326 # The CRLF that terminates the chunk data. Skipped when the caller
1327 # stopped mid-chunk: the socket is closed straight after, and the
1328 # remaining bytes of that chunk are still unread in front of it.
1329 57 $self->_assert_chunk_terminator($ctx, $self->_read_line($sock, $ctx));
1330 }
1331 }
1332 elsif (defined $headers->{'content-length'}) {
1333 10 my $len = $self->_assert_content_length($ctx, $headers->{'content-length'});
1334 9 my $read = 0;
1335 9 ▶ while ($more && $read < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($more and $read < $len) 41 5 46
Condition100%3/3
$more and $read < $len
!ll&&!rl&&r
2341
MC/DC100%2/2
$more and $read < $len
$more $read < $len
Truth table100%3/3
A and B
A= $moreB= $read < $len
ABresult
0X0
100
111
1336 41 my $want = $len - $read;
1337 41 ▶ $want = $READ_SIZE if $want > $READ_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
if $want > $READ_SIZE 0 41 41
1338 41 my ($n, $buf) = $self->_read_bytes($sock, $want, $ctx);
1339 40 ▶ last unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 3 37 40
1340 37 $read += $n;
1341 37 $more = $feed->($buf);
1342 }
1343 8 ▶ $self->_croak_truncated($ctx, phase => 'content-length',
Branch: 1 branch
BranchTrueFalseTotal
if $more and $read < $len 3 5 8
Condition100%3/3
$more and $read < $len
!ll&&!rl&&r
233
MC/DC100%2/2
$more and $read < $len
$more $read < $len
Truth table100%3/3
A and B
A= $moreB= $read < $len
ABresult
0X0
100
111
1344 piece => 'the body', expected => $len, received => $read)
1345 if $more && $read < $len;
1346 }
1347 else {
1348 23 ▶ while ($more) {
Branch: 1 branch
BranchTrueFalseTotal
if ($more) 75 3 78
1349 75 my ($n, $buf) = $self->_read_bytes($sock, $READ_SIZE, $ctx);
1350 72 ▶ last unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 17 55 72
1351 55 $more = $feed->($buf);
1352 }
1353 }
1354  
1355 # Only a stream the daemon ended has a tail worth flushing, or a leftover
1356 # worth complaining about. One the caller stopped has bytes in the carry
1357 # buffer by construction, and treating those as truncation would turn every
1358 # early stop into an error.
1359 51 ▶ $handler->{finish}->() unless $handler->{stopped}->();
Branch: 1 branch
BranchTrueFalseTotal
unless $handler->{"stopped"}->() 38 13 51
1360  
1361 50 return [$status_code, $status_text, $headers, '', $handler->{summary}->()];
1362 }
1363  
1364 # One unit per call, and the unit is whichever of the three the caller asked
1365 # for. The engine's streaming endpoints do not share one: /events and the
1366 # build/pull/push progress streams are newline-delimited JSON, logs and
1367 # exec/start are 8-byte-framed, and an image export is bytes with no structure
1368 # above them at all. Forcing one unit on all three would mean handing two of
1369 # them back undecoded and calling it streaming.
1370 #
1371 # The three decoders differ only in how they cut the byte stream up; the carry
1372 # buffer, the delivery and the stop handling below are common to all of them.
1373 79 ▶sub _stream_handler {
Subroutine _stream_handler: called CC=3 SCAR=11.0
1374 79 my ($self, $endpoint, $option, $cb, $croak_on_error) = @_;
1375  
1376 79 my $carry = '';
1377 79 my $delivered = 0;
1378 79 my $stopped = 0;
1379  
1380 # Stopping is an explicit call, not a return value, and the callback's
1381 # return value is deliberately never looked at. Every truthiness convention
1382 # has a silent failure mode here: `push @got, $_[0]` returns a count and
1383 # `$last = $event->{status}` returns whatever the engine said -- and a
1384 # container event's status is literally 'stop'. Both would end the stream by
1385 # accident and hand back a truncated one with no diagnostic. A closure the
1386 # caller has to invoke cannot be produced by accident.
1387 79 ▶ my $stop = sub { $stopped = 1; return };
Subroutine __ANON__: called CC=1 SCAR=0.0
1388  
1389 163 ▶ my $deliver = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1390 163 my ($unit) = @_;
1391 163 $delivered++;
1392 163 $cb->($unit, $stop);
1393 163 return !$stopped;
1394 79 };
1395  
1396 79 my ($feed, $finish);
1397  
1398 79 ▶ if ($option eq 'on_chunk') {
Branch: 2 branches
BranchTrueFalseTotal
if ($option eq 'on_chunk') { } 47 32 79
elsif ($option eq 'on_event') { } 18 14 32
1399 # No carry: the bytes as they arrive are the unit, so there is no boundary
1400 # to reassemble across.
1401 110 ▶ $feed = sub {
Subroutine __ANON__: called CC=3 SCAR=12.5
1402 110 my ($bytes) = @_;
1403 110 ▶ return 1 unless defined $bytes && length $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes and length $bytes 0 110 110
Condition33%1/3
defined $bytes and length $bytes
!ll&&!rl&&r
00110
MC/DC0%0/2
defined $bytes and length $bytes
defined $bytes length $bytes
Truth table33%1/3
A and B
A= defined $bytesB= length $bytes
ABresult
0X0
100
111
1404 110 return $deliver->($bytes);
1405 47 };
1406 47 ▶ $finish = sub { return };
Subroutine __ANON__: called CC=1 SCAR=0.0
1407 }
1408 elsif ($option eq 'on_event') {
1409 36 ▶ my $emit_line = sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
1410 36 my ($line) = @_;
1411 36 $line =~ s/\r\z//;
1412 36 ▶ return 1 unless $line =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /\S/ 0 36 36
1413 36 my $event = eval { decode_json($line) };
1414 36 ▶ return 1 unless defined $event;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $event 0 36 36
1415 # Checked per event rather than over the finished list, so a failed
1416 # build croaks at the event that reports it instead of when the daemon
1417 # eventually closes. The Error::Stream then carries that one event: a
1418 # callback stream keeps no history, having been given all of it already.
1419 36 ▶ $self->_assert_no_stream_error($endpoint, [$event]) if $croak_on_error;
Branch: 1 branch
BranchTrueFalseTotal
if $croak_on_error 9 27 36
1420 34 return $deliver->($event);
1421 18 };
1422 439 ▶ $feed = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1423 439 my ($bytes) = @_;
1424 439 $carry .= $bytes;
1425 # A JSON string cannot contain a literal newline, so a newline in the
1426 # buffer always ends an event -- and everything after the last one is
1427 # an event still arriving, which stays in the carry for the next read.
1428 439 ▶ while ((my $idx = index($carry, "\n")) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $idx = index($carry, "\n")) >= 0) 35 433 468
1429 35 my $line = substr($carry, 0, $idx, '');
1430 35 substr($carry, 0, 1, '');
1431 35 ▶ return 0 unless $emit_line->($line);
Branch: 1 branch
BranchTrueFalseTotal
unless &$emit_line($line) 4 29 33
1432 }
1433 433 return 1;
1434 18 };
1435 8 ▶ $finish = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1436 # A last event with no trailing newline is a complete event, not a
1437 # truncated one: the daemon closing is what ended it.
1438 8 ▶ return unless length $carry;
Branch: 1 branch
BranchTrueFalseTotal
unless length $carry 7 1 8
1439 1 my $line = $carry;
1440 1 $carry = '';
1441 1 $emit_line->($line);
1442 1 return;
1443 18 };
1444 }
1445 else {
1446 106 ▶ $feed = sub {
Subroutine __ANON__: called CC=8 SCAR=20.9
1447 106 my ($bytes) = @_;
1448 106 $carry .= $bytes;
1449 106 ▶ while (length($carry) >= 8) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $carry >= 8) 47 75 122
1450 47 my ($type, $pad1, $pad2, $pad3, $size) = unpack 'C4 N', substr($carry, 0, 8);
1451 47 ▶ croak __PACKAGE__ . '->_request on_frame: not a framed stream (header '
Branch: 1 branch
BranchTrueFalseTotal
if $type > $#STREAM_TYPE or $pad1 or $pad2 or $pad3 1 46 47
Condition66%6/9
$type > $#STREAM_TYPE or $pad1 or $pad2 or $pad3
l!l&&r!l&&!r
1046
$type > $#STREAM_TYPE or $pad1 or $pad2
l!l&&r!l&&!r
1046
$type > $#STREAM_TYPE or $pad1
l!l&&r!l&&!r
1046
MC/DC25%1/4
$type > $#STREAM_TYPE or $pad1 or $pad2 or $pad3
$type > $#STREAM_TYPE $pad1 $pad2 $pad3
Truth table40%2/5
A or B or C or D
A= $type > $#STREAM_TYPEB= $pad1C= $pad2D= $pad3
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1452 . 'byte 0 is ' . $type . ', bytes 1-3 are ' . $pad1 . '/' . $pad2
1453 . '/' . $pad3 . '). A callback stream cannot sniff its own framing '
1454 . 'the way the buffered path does -- that needs the whole body, '
1455 . 'which is what is not being kept. Declare an unframed stream with '
1456 . 'tty => 1'
1457 if $type > $#STREAM_TYPE || $pad1 || $pad2 || $pad3;
1458 # The header is complete but the payload is not yet: leave the whole
1459 # frame in the carry and wait for the rest of it. This is the case a
1460 # per-chunk reader gets wrong -- an 8-byte header can be split across
1461 # two chunks just as easily as a payload can.
1462 46 ▶ last if length($carry) < 8 + $size;
Branch: 1 branch
BranchTrueFalseTotal
if length $carry < 8 + $size 27 19 46
1463 19 my $frame = {
1464 stream => $STREAM_TYPE[$type],
1465 data => substr($carry, 8, $size),
1466 };
1467 19 substr($carry, 0, 8 + $size, '');
1468 19 ▶ return 0 unless $deliver->($frame);
Branch: 1 branch
BranchTrueFalseTotal
unless &$deliver($frame) 3 16 19
1469 }
1470 102 return 1;
1471 14 };
1472 10 ▶ $finish = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1473 10 ▶ return unless length $carry;
Branch: 1 branch
BranchTrueFalseTotal
unless length $carry 9 1 10
1474 1 croak __PACKAGE__ . '->_request on_frame: the daemon closed mid-frame, '
1475 . 'leaving ' . length($carry) . ' bytes that do not complete one';
1476 14 };
1477 }
1478  
1479 return {
1480 feed => $feed,
1481 finish => $finish,
1482 51 ▶ stopped => sub { $stopped },
Subroutine __ANON__: called CC=1 SCAR=0.0
1483 79 ▶ summary => sub { { delivered => $delivered, stopped => $stopped ? 1 : 0 } },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$stopped ? : 16 63 79
1484 79 };
1485 }
1486  
1487 36 ▶sub _read_chunked {
Subroutine _read_chunked: called CC=3 SCAR=11.0
1488 36 my ($self, $sock, $ctx) = @_;
1489 36 ▶ $ctx ||= {};
Condition100%2/2
$ctx ||= {}
l!l
333
MC/DC100%1/1
$ctx ||= {}
$ctx
Truth table100%2/2
A
A= $ctx
Aresult
11
00
1490 36 my $body = '';
1491 # See _read_body: the accumulator a timeout hands over. The chunk data is
1492 # appended to it directly rather than to a per-chunk temporary, so a stall
1493 # in the middle of a chunk still carries the bytes of that chunk out with
1494 # the exception. The two are otherwise the same -- the temporary was only
1495 # ever concatenated onto $body straight afterwards.
1496 36 local $ctx->{partial} = \$body;
1497  
1498 36 while (1) {
1499 91 my $chunk_header = $self->_read_line($sock, $ctx);
1500 86 my $chunk_size = $self->_assert_chunk_header($ctx, $chunk_header);
1501 79 ▶ last if $chunk_size == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk_size == 0 15 64 79
1502  
1503 64 $self->_read_exact($sock, $chunk_size, \$body, $ctx, 'chunk-data',
1504 'a chunk');
1505  
1506 # Read trailing \r\n after chunk data
1507 59 $self->_assert_chunk_terminator($ctx, $self->_read_line($sock, $ctx));
1508 }
1509  
1510 15 return $body;
1511 }
1512  
1513 # The two places a chunked body ends without saying so, and neither of them
1514 # has a byte count to compare (karr k64).
1515 #
1516 # A chunked body is terminated by a chunk of size zero and by nothing else, so
1517 # an end of stream where the next chunk header belongs is the daemon hanging
1518 # up mid-body -- not the end of it. The reader used to `last unless defined`
1519 # there and hand back the chunks that had completed as the whole response.
1520 #
1521 # _read_line answers an end of stream with what is left in the buffer and no
1522 # terminator, exactly as the readline it replaces did (see there), so an
1523 # unterminated line is the other half of the same question: a header cut in
1524 # half is `hex('1')` and reads as a perfectly good chunk of one byte.
1525 181 ▶sub _assert_chunk_header {
Subroutine _assert_chunk_header: called CC=5 SCAR=16.1
1526 181 my ($self, $ctx, $line) = @_;
1527  
1528 181 ▶ $self->_croak_truncated($ctx, phase => 'chunk-header',
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 5 176 181
1529 detail => 'the stream ended where a chunk header belongs, with no '
1530 . 'terminating zero chunk')
1531 unless defined $line;
1532  
1533 176 ▶ $self->_croak_truncated($ctx, phase => 'chunk-header',
Branch: 2 branches
BranchTrueFalseTotal
unless $line =~ /\n\z/ 5 171 176
length $line == 1 ? : 1 4 5
1534 detail => 'the stream ended inside a chunk header, after '
1535 . length($line) . ' byte' . (length($line) == 1 ? '' : 's') . ' of one')
1536 unless $line =~ /\n\z/;
1537  
1538 # The line arrived whole and terminated, and its size is not a hexadecimal
1539 # number. Left to hex() that warns once and reads as 0 -- the terminating
1540 # zero chunk -- so a 200 whose framing is corrupt used to come back as an
1541 # empty body, the same body-shaped lie a truncation is. A chunk size is hex
1542 # digits, optionally followed by a ';' extension (RFC 9112 section 7.1.1),
1543 # which is read past and discarded; anything else is refused here rather than
1544 # silently misread by the caller. The returned size is parsed from the same
1545 # match, so hex() is called on nothing but hex digits and never has cause to
1546 # warn on a legal extension either.
1547 171 my ($size) = $line =~ /^([0-9A-Fa-f]+)(?:;.*)?\r?\n\z/;
1548 171 ▶ $self->_croak_truncated($ctx, phase => 'chunk-header',
Branch: 1 branch
BranchTrueFalseTotal
unless defined $size 2 169 171
1549 detail => "the chunk size line '" . ($line =~ s/\r?\n\z//r)
1550 . "' is not a hexadecimal number")
1551 unless defined $size;
1552  
1553 169 return hex($size);
1554 }
1555  
1556 # Completeness only, never content: a terminator that arrived but is not CRLF
1557 # is a daemon speaking chunked wrongly, which is a different complaint and one
1558 # this reader has never made.
1559 114 ▶sub _assert_chunk_terminator {
Subroutine _assert_chunk_terminator: called CC=3 SCAR=11.0
1560 114 my ($self, $ctx, $line) = @_;
1561  
1562 114 ▶ $self->_croak_truncated($ctx, phase => 'chunk-terminator',
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line and $line =~ /\n\z/ 5 109 114
Condition66%2/3
defined $line and $line =~ /\n\z/
!ll&&!rl&&r
50109
MC/DC50%1/2
defined $line and $line =~ /\n\z/
defined $line $line =~ /\n\z/
Truth table66%2/3
A and B
A= defined $lineB= $line =~ /\n\z/
ABresult
0X0
100
111
1563 detail => 'the stream ended before the CRLF that terminates a chunk')
1564 unless defined $line && $line =~ /\n\z/;
1565  
1566 109 return;
1567 }
1568  
1569 # The declared body length, validated to be the digits RFC 9110 section 8.6
1570 # requires before it is compared against or counted down (karr k113). The
1571 # sibling of _assert_chunk_header's hex check: a Content-Length that is not a
1572 # number -- 'abc', an empty value, a duplicated '11, 11', a leading space --
1573 # left as it stood is run through `$len > 0`, which warns once ("isn't
1574 # numeric") and reads as 0, so the body is taken to be empty and a response
1575 # that had one comes back blank. Refused here rather than silently misread, so
1576 # hex()'s sibling warning is never reached either.
1577 55 ▶sub _assert_content_length {
Subroutine _assert_content_length: called CC=2 SCAR=6.9
1578 55 my ($self, $ctx, $value) = @_;
1579  
1580 55 ▶ return $value if $value =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /\A[0-9]+\z/ 50 5 55
1581  
1582 5 $self->_croak_truncated($ctx, phase => 'content-length',
1583 detail => "the Content-Length header '" . $value . "' is not a number");
1584 }
1585  
1586 389 ▶sub _uri_encode {
Subroutine _uri_encode: called CC=2 SCAR=6.9
1587 389 my ($str) = @_;
1588 # Escape a character string by its UTF-8 bytes ('ΓΌ' -> %C3%BC, not %FC), and
1589 # a byte string as it stands. ord() on a character is not its wire byte: a
1590 # name or tag typed under `use utf8`, or read through a :utf8 layer, arrives
1591 # as characters and used to escape to a lone high byte or a bare codepoint
1592 # (%FC, %4E2D) that is not UTF-8 at all. But the encoding cannot be
1593 # unconditional: encode_json has already handed a HASH param (filters among
1594 # them) its UTF-8 octets, and re-encoding those would double them
1595 # (%C3%BC -> %C3%83%C2%BC). The utf8 flag is exactly that distinction -- on
1596 # for a decoded string, off for encode_json's output -- so a copy is encoded
1597 # only when it carries one, leaving the caller's own value untouched either
1598 # way.
1599 389 my $bytes = $str;
1600 389 ▶ utf8::encode($bytes) if utf8::is_utf8($bytes);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($bytes) 2 387 389
1601 389 $bytes =~ s/([^A-Za-z0-9\-_.~:\/])/sprintf("%%%02X", ord($1))/ge;
1602 389 return $bytes;
1603 }
1604  
1605 362 ▶sub get {
Subroutine get: called CC=1 SCAR=0.0
Pod documented
1606 362 my ($self, $path, %opts) = @_;
1607 362 return $self->_request('GET', $path, %opts);
1608 }
1609  
1610  
1611 224 ▶sub post {
Subroutine post: called CC=2 SCAR=6.9
Pod documented
1612 224 my ($self, $path, $body, %opts) = @_;
1613 224 ▶ $opts{body} = $body if defined $body;
Branch: 1 branch
BranchTrueFalseTotal
if defined $body 63 161 224
1614 224 return $self->_request('POST', $path, %opts);
1615 }
1616  
1617  
1618 9 ▶sub put {
Subroutine put: called CC=2 SCAR=7.1
Pod documented
1619 9 my ($self, $path, $body, %opts) = @_;
1620 9 ▶ $opts{body} = $body if defined $body;
Branch: 1 branch
BranchTrueFalseTotal
if defined $body 0 9 9
1621 9 return $self->_request('PUT', $path, %opts);
1622 }
1623  
1624  
1625 37 ▶sub delete_request {
Subroutine delete_request: called CC=1 SCAR=0.0
Pod documented
1626 37 my ($self, $path, %opts) = @_;
1627 37 return $self->_request('DELETE', $path, %opts);
1628 }
1629  
1630  
1631 12 ▶sub head {
Subroutine head: called CC=1 SCAR=0.0
Pod documented
1632 12 my ($self, $path, %opts) = @_;
1633 12 return $self->_request('HEAD', $path, %opts);
1634 }
1635  
1636  
1637 48 ▶sub stream_frames {
Subroutine stream_frames: called CC=7 SCAR=19.5
Pod documented
1638 48 my ($self, $method, $path, %opts) = @_;
1639  
1640 48 my $tty = delete $opts{tty};
1641  
1642 48 ▶ if (my $cb = delete $opts{on_frame}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = delete $opts{"on_frame"}) 9 39 48
1643 # tty is a declaration here, not the hint it is on the buffered path. The
1644 # sniff below needs the whole body to decide, and the whole body is what a
1645 # callback stream does not have; so an unframed stream has to say so, and
1646 # anything not declared is required to be framed.
1647 return $self->_request($method, $path, %opts,
1648 $tty
1649 3 ▶ ? ( on_chunk => sub { $cb->({ stream => 'raw', data => $_[0] }, $_[1]) } )
Subroutine __ANON__: called CC=1 SCAR=0.0
1650 9 ▶ : ( on_frame => $cb ),
Branch: 1 branch
BranchTrueFalseTotal
$tty ? : 1 8 9
1651 );
1652 }
1653  
1654 39 my $body = $self->_request($method, $path, %opts, raw => 1);
1655  
1656 37 ▶ return [] unless defined $body && length $body;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $body and length $body 14 23 37
Condition100%3/3
defined $body and length $body
!ll&&!rl&&r
11323
MC/DC100%2/2
defined $body and length $body
defined $body length $body
Truth table100%3/3
A and B
A= defined $bodyB= length $body
ABresult
0X0
100
111
1657  
1658 23 ▶ my $frames = $tty ? undef : $self->_demux_frames($body);
Branch: 1 branch
BranchTrueFalseTotal
$tty ? : 3 20 23
1659  
1660 23 ▶ return $frames if $frames;
Branch: 1 branch
BranchTrueFalseTotal
if $frames 17 6 23
1661 6 return [ { stream => 'raw', data => $body } ];
1662 }
1663  
1664  
1665 30 ▶sub _demux_frames {
Subroutine _demux_frames: called CC=9 SCAR=22.0
1666 30 my ($self, $body) = @_;
1667  
1668 30 my $len = length $body;
1669 30 my $pos = 0;
1670 30 my @frames;
1671  
1672 30 ▶ while ($pos < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $len) 48 20 68
1673 48 ▶ return undef if $len - $pos < 8;
Branch: 1 branch
BranchTrueFalseTotal
if $len - $pos < 8 2 46 48
1674 46 my ($type, $pad1, $pad2, $pad3, $size) = unpack 'C4 N', substr($body, $pos, 8);
1675 46 ▶ return undef if $type > $#STREAM_TYPE;
Branch: 1 branch
BranchTrueFalseTotal
if $type > $#STREAM_TYPE 6 40 46
1676 40 ▶ return undef if $pad1 || $pad2 || $pad3;
Branch: 1 branch
BranchTrueFalseTotal
if $pad1 or $pad2 or $pad3 1 39 40
Condition50%3/6
$pad1 or $pad2 or $pad3
l!l&&r!l&&!r
0139
$pad1 or $pad2
l!l&&r!l&&!r
0040
MC/DC33%1/3
$pad1 or $pad2 or $pad3
$pad1 $pad2 $pad3
Truth table50%2/4
A or B or C
A= $pad1B= $pad2C= $pad3
ABCresult
1XX1
01X1
0011
0000
1677 39 ▶ return undef if $len - $pos - 8 < $size;
Branch: 1 branch
BranchTrueFalseTotal
if $len - $pos - 8 < $size 1 38 39
1678 38 push @frames, {
1679 stream => $STREAM_TYPE[$type],
1680 data => substr($body, $pos + 8, $size),
1681 };
1682 38 $pos += 8 + $size;
1683 }
1684  
1685 20 ▶ return undef unless @frames;
Branch: 1 branch
BranchTrueFalseTotal
unless @frames 1 19 20
1686 19 return \@frames;
1687 }
1688  
1689  
1690 52 1;
1691  
1692 __END__
« Docker/API/Images.pm ↑ Summary Docker/API/Containers.pm »