Docker/Role/HTTP.pm

filter: Statementstmt 97.7% 571 / 584 Branchbran 89.5% 333 / 372 Conditioncond 70.0% 96 / 137 MC/DCmcdc 50.6% 40 / 79 Subroutinesub 100% 72 / 72 Podpod 100% 6 / 6 totaltotal 89.4% 1118 / 1250 CC 242 SCAR 27.1
CC
242
Cov
91%
_request
48.2
_build__socket
32.2
_read_streaming_response
25.3
CRAP 15.1
« 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 47 our $VERSION = '0.004';
4 47 ▶use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 47 ▶use IO::Socket::UNIX;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 47 ▶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 47 ▶use IO::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 47 ▶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 47 ▶use Errno qw( EAGAIN EWOULDBLOCK EINTR );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 47 ▶use JSON::MaybeXS qw( encode_json decode_json );
Subroutine BEGIN: called CC=1 SCAR=0.0
16 47 ▶use Scalar::Util qw( looks_like_number );
Subroutine BEGIN: called CC=1 SCAR=0.0
17 47 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 47 ▶use Carp qw( croak shortmess );
Subroutine BEGIN: called CC=1 SCAR=0.0
19 47 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
20 47 ▶use API::Docker::Error::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 47 ▶use API::Docker::Error::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 47 ▶use API::Docker::Error::Timeout;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 47 ▶use API::Docker::Error::Truncated;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 47 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26  
27 47 requires 'host';
28 47 requires 'api_version';
29 47 requires 'tls';
30 47 requires 'cert_path';
31 47 requires 'tls_insecure';
32  
33 # Docker stream frame types, indexed by the first byte of the frame header.
34 47 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 47 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 47 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 47 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 47 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 47 my $READ_SIZE = 64 * 1024;
67  
68 47 has read_timeout => (
69 is => 'ro',
70 );
71  
72  
73 47 has connect_timeout => (
74 is => 'ro',
75 );
76  
77  
78 47 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 47 has _pending_connect => (
90 is => 'rw',
91 init_arg => undef,
92 );
93  
94 15 ▶sub _build__socket {
Subroutine _build__socket: called CC=17 SCAR=34.7
95 15 my ($self) = @_;
96 15 my $host = $self->host;
97 15 my $pending = $self->_pending_connect;
98 15 ▶ my $timeout = $pending ? $pending->{timeout} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$pending ? : 15 0 15
99  
100 15 ▶ if ($host =~ m{^unix://(.+)$}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($host =~ m[^unix://(.+)$]) { } 3 12 15
elsif ($host =~ m[^tcp://([^:]+):(\d+)$]) { } 12 0 12
101 3 my $path = $1;
102 3 $log->debugf("Connecting to Unix socket: %s", $path);
103 3 ▶ my $sock = IO::Socket::UNIX->new(
Branch: 1 branch
BranchTrueFalseTotal
$timeout ? : 3 0 3
104 Peer => $path,
105 Type => SOCK_STREAM,
106 $timeout ? (Timeout => $timeout) : (),
107 );
108 3 ▶ unless ($sock) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sock) 3 0 3
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 0 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 47 ▶ 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 299 ▶sub _reconnect {
Subroutine _reconnect: called CC=2 SCAR=6.9
270 299 my ($self, $pending) = @_;
271 299 $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 299 $self->_pending_connect($pending);
277 299 my $sock;
278 299 my $ok = eval { $sock = $self->_socket; 1 };
279 299 my $err = $@;
280 299 $self->_pending_connect(undef);
281 299 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 18 281 299
282  
283 281 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 610 ▶sub _timeout_value {
Subroutine _timeout_value: called CC=6 SCAR=17.9
336 610 my ($self, $name, $timeout) = @_;
337  
338 610 ▶ return undef unless defined $timeout;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $timeout 575 35 610
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 303 ▶sub _read_timeout_value {
Subroutine _read_timeout_value: called CC=1 SCAR=0.0
347 303 my ($self, $timeout) = @_;
348 303 return $self->_timeout_value('read_timeout', $timeout);
349 }
350  
351 307 ▶sub _connect_timeout_value {
Subroutine _connect_timeout_value: called CC=1 SCAR=0.0
352 307 my ($self, $timeout) = @_;
353 307 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 285 ▶sub _apply_read_timeout {
Subroutine _apply_read_timeout: called CC=7 SCAR=23.0
369 285 my ($self, $sock, $timeout) = @_;
370  
371 285 ▶ return unless $timeout;
Branch: 1 branch
BranchTrueFalseTotal
unless $timeout 274 11 285
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 45 ▶sub _timed_out {
Subroutine _timed_out: called CC=4 SCAR=13.9
419 45 my ($self, $ctx, $errno) = @_;
420  
421 45 ▶ return 0 unless $ctx->{timeout};
Branch: 1 branch
BranchTrueFalseTotal
unless $ctx->{"timeout"} 16 29 45
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 47 my $RBUF = __PACKAGE__ . '/rbuf';
557  
558 4165 ▶sub _read_buffer {
Subroutine _read_buffer: called CC=2 SCAR=6.9
559 4165 my ($self, $sock) = @_;
560  
561 4165 ▶ ${*$sock}{$RBUF} = '' unless defined ${*$sock}{$RBUF};
Branch: 1 branch
BranchTrueFalseTotal
unless defined do { *$sock }->{$RBUF} 204 3961 4165
562 4165 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 2094 ▶sub _pull {
Subroutine _pull: called CC=5 SCAR=16.1
593 2094 my ($self, $sock, $ctx) = @_;
594  
595 2094 my $buf = $self->_read_buffer($sock);
596  
597 2094 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 2097 $! = 0;
602 2097 my $n = $sock->sysread(my $got, $READ_SIZE);
603 2094 my $errno = 0 + $!;
604  
605 2094 ▶ if (defined $n) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $n) 2046 48 2094
606 2046 ▶ return 'eof' unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 62 1984 2046
607 1984 $$buf .= $got;
608 1984 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 48 ▶ next if $errno == EINTR;
Branch: 1 branch
BranchTrueFalseTotal
if $errno == 4 3 45 48
615  
616 45 ▶ return 'timeout' if $self->_timed_out($ctx, $errno);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_timed_out($ctx, $errno) 27 18 45
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 18 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 845 ▶sub _read_line {
Subroutine _read_line: called CC=8 SCAR=20.8
631 845 my ($self, $sock, $ctx) = @_;
632 845 ▶ $ctx ||= {};
Condition50%1/2
$ctx ||= {}
l!l
8450
MC/DC0%0/1
$ctx ||= {}
$ctx
Truth table50%1/2
A
A= $ctx
Aresult
11
00
633  
634 845 my $buf = $self->_read_buffer($sock);
635 845 my $idx = index($$buf, "\n");
636  
637 845 ▶ while ($idx < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idx < 0) 1013 796 1809
638 1013 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 1010 ▶ $self->_croak_timeout($ctx, $ctx->{partial} ? ${ $ctx->{partial} } : '')
Branch: 2 branches
BranchTrueFalseTotal
if $kind eq "timeout" 13 997 1010
$ctx->{'partial'} ? : 3 10 13
645 if $kind eq 'timeout';
646 997 ▶ last if $kind eq 'eof';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "eof" 33 964 997
647 964 $idx = index($$buf, "\n");
648 }
649  
650 829 ▶ return substr($$buf, 0, $idx + 1, '') if $idx >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $idx >= 0 796 33 829
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 33 ▶ return undef unless length $$buf;
Branch: 1 branch
BranchTrueFalseTotal
unless length $$buf 20 13 33
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 1224 ▶sub _read_bytes {
Subroutine _read_bytes: called CC=7 SCAR=19.5
664 1224 my ($self, $sock, $want, $ctx) = @_;
665 1224 ▶ $ctx ||= {};
Condition50%1/2
$ctx ||= {}
l!l
12240
MC/DC0%0/1
$ctx ||= {}
$ctx
Truth table50%1/2
A
A= $ctx
Aresult
11
00
666  
667 1224 my $buf = $self->_read_buffer($sock);
668  
669 1224 ▶ if (!length $$buf) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $$buf) 1081 143 1224
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 1163 ▶ my $take = $want < length($$buf) ? $want : length($$buf);
Branch: 1 branch
BranchTrueFalseTotal
$want < length $$buf ? : 83 1080 1163
682 1163 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 103 ▶sub _read_exact {
Subroutine _read_exact: called CC=4 SCAR=13.9
698 103 my ($self, $sock, $want, $into, $ctx, $phase, $piece) = @_;
699  
700 103 my $read = 0;
701 103 ▶ while ($read < $want) {
Branch: 1 branch
BranchTrueFalseTotal
if ($read < $want) 515 83 598
702 515 my ($n, $buf) = $self->_read_bytes($sock, $want - $read, $ctx);
703 508 ▶ last unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 13 495 508
704 495 $$into .= $buf;
705 495 $read += $n;
706 }
707  
708 96 ▶ $self->_croak_truncated($ctx, phase => $phase, piece => $piece,
Branch: 1 branch
BranchTrueFalseTotal
if $read < $want 13 83 96
709 expected => $want, received => $read) if $read < $want;
710  
711 83 return $read;
712 }
713  
714 323 ▶sub _request {
Subroutine _request: called CC=48 SCAR=38.8
715 323 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 323 ▶ if exists $opts{response} && ref $opts{response} ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"response"} and ref $opts{"response"} ne "HASH" 1 322 323
Condition100%3/3
exists $opts{"response"} and ref $opts{"response"} ne "HASH"
!ll&&!rl&&r
286361
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 322 my @streaming = grep { exists $opts{$_} } @STREAM_OPTION;
727 322 ▶ croak __PACKAGE__ . '->_request takes one of ' . join(', ', @STREAM_OPTION)
Branch: 1 branch
BranchTrueFalseTotal
if @streaming > 1 1 321 322
728 . ', not ' . join(' and ', @streaming) if @streaming > 1;
729 croak __PACKAGE__ . '->_request ' . $streaming[0] . ' option must be a CodeRef'
730 321 ▶ if @streaming && ref $opts{$streaming[0]} ne 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if @streaming and ref $opts{$streaming[0]} ne "CODE" 2 319 321
Condition100%3/3
@streaming and ref $opts{$streaming[0]} ne "CODE"
!ll&&!rl&&r
288312
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 319 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 319 $self->_assert_request_path($path);
738  
739 310 ▶ my $url_path = defined $version ? "/v$version$path" : $path;
Branch: 1 branch
BranchTrueFalseTotal
defined $version ? : 310 0 310
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 310 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 310 my $body_content;
752 310 my $content_type = 'application/json';
753 310 ▶ if (defined $opts{raw_body}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'raw_body'}) { } 19 291 310
elsif ($opts{'body'}) { } 19 272 291
754 19 $body_content = $opts{raw_body};
755 19 ▶ $content_type = $opts{content_type} // 'application/x-tar';
Condition100%2/2
$opts{"content_type"} // "application/x-tar"
l!l
181
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 310 ▶ if ($opts{params}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"params"}) 129 181 310
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 310 $log->debugf("%s %s", $method, $url_path);
783  
784 310 my $request = "$method $url_path HTTP/1.1\r\n";
785 310 $request .= "Host: localhost\r\n";
786 310 $request .= "Connection: close\r\n";
787 310 $request .= "User-Agent: API-Docker\r\n";
788  
789 310 ▶ if (defined $body_content) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $body_content) 38 272 310
790 38 $request .= "Content-Type: $content_type\r\n";
791 38 $request .= "Content-Length: " . length($body_content) . "\r\n";
792 }
793  
794 310 ▶ if ($opts{headers}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"headers"}) 19 291 310
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 302 $request .= "\r\n";
808 302 ▶ $request .= $body_content if defined $body_content;
Branch: 1 branch
BranchTrueFalseTotal
if defined $body_content 38 264 302
809  
810 my $handler = @streaming
811 ? $self->_stream_handler($endpoint, $streaming[0], $opts{$streaming[0]},
812 302 ▶ $opts{croak_on_error} // 1)
Branch: 1 branch
BranchTrueFalseTotal
@streaming ? : 31 271 302
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 302 ▶ exists $opts{read_timeout} ? $opts{read_timeout} : $self->read_timeout);
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'read_timeout'} ? : 11 291 302
820  
821 # Same resolution, same reason.
822 my $connect_timeout = $self->_connect_timeout_value(
823 exists $opts{connect_timeout}
824 299 ▶ ? $opts{connect_timeout} : $self->connect_timeout);
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'connect_timeout'} ? : 9 290 299
825  
826 # The endpoint without its query string, for the same reason the >= 400
827 # croak uses that form.
828 299 my $ctx = { endpoint => $endpoint, timeout => $timeout };
829  
830 299 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 281 $self->_apply_read_timeout($sock, $timeout);
836 281 print $sock $request;
837  
838 # Reading can croak, and now does so from further in than it used to: an
839 # on_event stream raises Error::Stream at the event that reports the
840 # failure, and an on_frame stream refuses a header that is not one. Without
841 # the eval those exceptions leave the socket open until the next request
842 # replaces it, so it is closed on the way out either way and the exception
843 # re-raised unchanged.
844 281 my $response;
845 281 ▶ my $ok = eval { $response = $handler
Branch: 1 branch
BranchTrueFalseTotal
$handler ? : 31 250 281
846 ? $self->_read_streaming_response($sock, $method, $handler, $ctx)
847 265 : $self->_read_response($sock, $method, $ctx); 1 };
848 281 my $err = $@;
849 281 close $sock;
850 281 $self->_clear_socket;
851 281 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 16 265 281
852  
853 265 my ($status_code, $status_text, $headers, $body, $summary) = @$response;
854  
855 265 $log->debugf("Response: %s %s", $status_code, $status_text);
856  
857 # The status line and the response headers are metadata the return value
858 # cannot carry: it is the decoded body and nothing else, so 204 and 304 are
859 # both undef and a header holding the payload -- HEAD
860 # /containers/{id}/archive answers with an empty body and
861 # X-Docker-Container-Path-Stat -- is unreachable. They go into a hash the
862 # caller supplies, so no existing caller's return shape changes. Filled
863 # before the croak below, so an eval'ing caller can still read the status.
864 265 ▶ if (my $out = $opts{response}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $out = $opts{"response"}) 35 230 265
865 35 %$out = (
866 status => $status_code,
867 reason => $status_text,
868 headers => $headers,
869 );
870 }
871  
872 265 ▶ if ($status_code >= 400) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status_code >= 400) 22 243 265
873 22 my $error_msg = $body;
874 22 my $data;
875 22 ▶ if ($body && $body =~ /^\s*[\{\[]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body and $body =~ /^\s*[\{\[]/) 20 2 22
Condition66%2/3
$body and $body =~ /^\s*[\{\[]/
!ll&&!rl&&r
0220
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
876 20 eval {
877 20 $data = decode_json($body);
878 # Docker answers with {"message":...}. Podman answers a failed push
879 # with the stream shape instead -- {"errorDetail":{"message":...},
880 # "error":...} and no message key at all -- so without these two
881 # fallbacks the whole JSON object became the croak text (karr k13).
882 my $detail = ref $data->{errorDetail} eq 'HASH'
883 18 ▶ ? $data->{errorDetail}{message} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $data->{'errorDetail'} eq 'HASH' ? : 2 15 17
884 17 ▶ $error_msg = $data->{message} // $detail // $data->{error} // $body;
Condition66%6/9
(($data->{"message"} // $detail) // $data->{"error"}) // $body
l!l&&r!l&&!r
1700
($data->{"message"} // $detail) // $data->{"error"}
l!l&&r!l&&!r
1610
$data->{"message"} // $detail
l!l&&r!l&&!r
1511
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
885 };
886 }
887  
888 # Carp hands a reference straight back rather than decorating it, so this
889 # croak is a die with an object -- hence the location captured by hand,
890 # which names the same frame a croak of a plain string would have named.
891 # message . location is byte for byte what the string croak produced,
892 # newline-terminated engine messages included: Carp appends the suffix
893 # after the newline rather than skipping it (karr k50).
894 22 ▶ my $error = API::Docker::Error::HTTP->new(
Condition50%1/2
$body // ""
l!l
220
MC/DC0%0/1
$body // ""
$body
Truth table50%1/2
A
A= $body
Aresult
11
00
895 message => "Docker API error ($status_code): $error_msg",
896 location => shortmess(''),
897 status => $status_code,
898 reason => $status_text,
899 body => $body // '',
900 data => $data,
901 );
902 22 croak $error;
903 }
904  
905 # A streamed request has handed every unit to the callback already and kept
906 # none of them, so there is no body left to decode and return. What the
907 # caller cannot know otherwise is how the stream ended, and that is what
908 # comes back instead.
909 243 ▶ return $summary if $summary;
Branch: 1 branch
BranchTrueFalseTotal
if $summary 23 220 243
910  
911 # Zero bytes is a different answer in each shape a request can ask for, so
912 # the two options that promise one are answered before the empty-body check
913 # rather than after it. `raw` promises the response bytes and a body of no
914 # bytes is '', which a caller can take length() of; `ndjson` promises an
915 # ArrayRef of events even for a stream carrying a single object, so a stream
916 # that carried none is []. Returning undef for both broke each promise
917 # exactly where the engine legitimately says nothing.
918 220 ▶ $body = '' unless defined $body;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $body 3 217 220
919  
920 # The framed endpoints (logs, attach, exec/start) carry arbitrary bytes
921 # that must not be mistaken for JSON -- a TTY container printing a JSON
922 # line would otherwise come back decoded.
923 220 ▶ return $body if $opts{raw};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"raw"} 32 188 220
924  
925 # Streaming endpoints (/build, /images/create, /images/*/push) always
926 # return an ArrayRef of events, even when the stream carried exactly one
927 # object. See _decode_stream.
928 188 ▶ if ($opts{ndjson}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"ndjson"}) 34 154 188
929 34 my $events = $self->_decode_stream($body);
930 # A failed build, pull or push is HTTP 200 with the failure buried in the
931 # stream, so the status line above cannot catch it. Opt out for a stream
932 # whose objects are engine data rather than the outcome of one operation.
933 $self->_assert_no_stream_error($endpoint, $events)
934 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
935 25 return $events;
936 }
937  
938 # Nothing was asked of the body's shape and there is no body, so there is
939 # nothing to hand back. 204 says so in the status line and is taken at its
940 # word even if bytes follow it.
941 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
942  
943 # A body that is JSON is decoded, whichever JSON value it is. The guard was
944 # `{` or `[` alone, which returned a body that is a bare JSON scalar as its
945 # own bytes: `null` came back as the four-character string 'null'. The
946 # engine sends exactly that where a Go nil slice or pointer is the whole
947 # response -- GET /plugins/privileges for a plugin that demands nothing,
948 # GET /containers/{id}/changes for a container that changed nothing -- and
949 # the string is neither the ArrayRef those endpoints document nor anything
950 # a caller can iterate.
951 #
952 # The eval decides, not the pattern: a plain-text body that happens to
953 # start with one of these characters fails to decode and is returned as
954 # itself. So must the eval's success, not its result -- decode_json('null')
955 # is a successful decode to undef.
956 89 ▶ if ($body =~ $JSON_BODY) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body =~ /$JSON_BODY/) 88 1 89
957 88 my $decoded;
958 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
959 }
960  
961 4 return $body;
962 }
963  
964 41 ▶sub _decode_stream {
Subroutine _decode_stream: called CC=6 SCAR=17.9
965 41 my ($self, $body) = @_;
966  
967 # Newline-delimited JSON: one object per line. A literal newline cannot
968 # occur inside a JSON string, so splitting on lines is safe.
969 41 my @events;
970 41 for my $line (split /\r?\n/, $body) {
971 97 ▶ next unless $line =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /\S/ 0 97 97
972 97 my $event = eval { decode_json($line) };
973 97 ▶ push @events, $event if defined $event;
Branch: 1 branch
BranchTrueFalseTotal
if defined $event 93 4 97
974 }
975  
976 # Fall back to the whole body for a stream that is not newline-framed
977 # (a single pretty-printed object), so nothing is silently dropped.
978 41 ▶ unless (@events) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@events) 4 37 41
979 4 my $event = eval { decode_json($body) };
980 4 ▶ push @events, $event if defined $event;
Branch: 1 branch
BranchTrueFalseTotal
if defined $event 1 3 4
981 }
982  
983 41 return \@events;
984 }
985  
986 40 ▶sub _assert_no_stream_error {
Subroutine _assert_no_stream_error: called CC=9 SCAR=22.1
987 40 my ($self, $endpoint, $events) = @_;
988  
989 40 for my $event (@$events) {
990 67 ▶ next unless ref $event eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $event eq "HASH" 2 65 67
991 65 my $detail = $event->{errorDetail};
992 65 ▶ next unless defined $detail;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $detail 54 11 65
993  
994 # errorDetail is a HashRef carrying the message. The engine sends a flat
995 # `error` next to it with the same text; that is the fallback, not the
996 # trigger -- the trigger is errorDetail, and nothing else.
997 11 ▶ my $reason = ref $detail eq 'HASH' ? $detail->{message} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $detail eq 'HASH' ? : 11 0 11
998 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
999 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
1000 # Engine messages end in a newline, and Carp appends no location to a
1001 # message that already does.
1002 11 $reason =~ s/\s+\z//;
1003  
1004 # Carp hands a reference straight back rather than decorating it, so this
1005 # croak is a die with an object -- hence the location captured by hand,
1006 # which names the same frame a croak of a plain string would have named.
1007 # The object goes into a variable first: `croak CLASS->new(...)` is
1008 # indirect object syntax and parses as CLASS->croak(new(...)).
1009 11 my $error = API::Docker::Error::Stream->new(
1010 message => 'Docker API stream error (' . $endpoint . '): ' . $reason,
1011 events => $events,
1012 location => shortmess(''),
1013 );
1014 11 croak $error;
1015 }
1016  
1017 29 return;
1018 }
1019  
1020 19 ▶sub _assert_header_name {
Subroutine _assert_header_name: called CC=4 SCAR=14.0
1021 19 my ($self, $name) = @_;
1022  
1023 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
1024  
1025 8 ▶ my $display = defined $name ? $name : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 8 0 8
1026 8 $display =~ s/([^\x20-\x7E])/sprintf('\\x%02X', ord $1)/ge;
1027 8 croak __PACKAGE__ . '->_request invalid header name "' . $display . '": a '
1028 . 'header name must be an RFC 9110 token (letters, digits and '
1029 . '!#$%&\'*+-.^_`|~). A name is rejected rather than sanitised: unlike a '
1030 . 'value, there is no benign way for one to carry CR, LF, a space or a '
1031 . 'colon, and rewriting it would send a header the caller never wrote';
1032 }
1033  
1034 319 ▶sub _assert_request_path {
Subroutine _assert_request_path: called CC=4 SCAR=14.0
1035 319 my ($self, $path) = @_;
1036  
1037 319 ▶ return if defined $path && $path =~ $REQUEST_PATH;
Branch: 1 branch
BranchTrueFalseTotal
if defined $path and $path =~ /$REQUEST_PATH/ 310 9 319
Condition66%2/3
defined $path and $path =~ /$REQUEST_PATH/
!ll&&!rl&&r
09310
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
1038  
1039 9 ▶ my $display = defined $path ? $path : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $path ? : 9 0 9
1040 9 $display =~ s/([^\x20-\x7E])/sprintf('\\x%02X', ord $1)/ge;
1041 9 croak __PACKAGE__ . '->_request invalid request path "' . $display . '": a '
1042 . 'path may hold only request-target characters (letters, digits, -._~ '
1043 . 'and :/@!$&\'()*+,;=%). It is spliced straight into the request line, so '
1044 . 'a space, CR, LF, ? or # in a container name or image reference would '
1045 . 'rewrite the request rather than name a resource. A path is rejected '
1046 . 'rather than sanitised: percent-encoding it here cannot tell a path '
1047 . 'separator from data -- pass query parameters as `params`, not in the '
1048 . 'path';
1049 }
1050  
1051 80 ▶sub _read_response {
Subroutine _read_response: called CC=2 SCAR=6.9
1052 80 my ($self, $sock, $method, $ctx) = @_;
1053 # A context is what _request builds to say how long a silence may last and
1054 # what the exception has to name. It defaults to an empty one -- no timeout,
1055 # every read exactly as it was -- so the readers stay drivable directly, as
1056 # t/role_http.t drives them.
1057 80 ▶ $ctx ||= {};
Condition100%2/2
$ctx ||= {}
l!l
6317
MC/DC100%1/1
$ctx ||= {}
$ctx
Truth table100%2/2
A
A= $ctx
Aresult
11
00
1058  
1059 80 my $head = $self->_read_head($sock, $ctx);
1060 69 return [ @$head, $self->_read_body($sock, $head->[2], $method, $ctx) ];
1061 }
1062  
1063 172 ▶sub _read_head {
Subroutine _read_head: called CC=7 SCAR=19.5
1064 172 my ($self, $sock, $ctx) = @_;
1065 172 ▶ $ctx ||= {};
Condition50%1/2
$ctx ||= {}
l!l
1720
MC/DC0%0/1
$ctx ||= {}
$ctx
Truth table50%1/2
A
A= $ctx
Aresult
11
00
1066  
1067 # Looped so a 1xx informational response is read whole and passed by: it is a
1068 # complete head -- a status line and an optional field section closed by the
1069 # blank line -- with no body of its own, sent before the real response
1070 # (RFC 9110 section 15.2). Without this the reader took the 1xx status as the
1071 # response and then read the real response as its body. A 100 Continue is the
1072 # one an HTTP/1.1 client is most likely to be sent; 102 and 103 have the same
1073 # framing.
1074 172 while (1) {
1075 176 my $status_line = $self->_read_line($sock, $ctx);
1076 # A daemon that closed without answering at all, which is the one shape here
1077 # that was never silent and is left saying exactly what it always said.
1078 173 ▶ croak "No response from Docker daemon" unless defined $status_line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $status_line 3 170 173
1079 170 $self->_assert_status_line($ctx, $status_line);
1080 162 $status_line =~ s/\r?\n$//;
1081  
1082 162 my ($proto, $status_code, $status_text) = split /\s+/, $status_line, 3;
1083  
1084 # while(1)-and-assert rather than `while (my $line = ...)`, which is the
1085 # same shape _read_chunked uses and for the same reason: the loop used to
1086 # end on anything false, so an end of stream inside the header block left it
1087 # exactly as the blank line would have. The assert is now the only way out
1088 # that is not the blank line.
1089 162 my %headers;
1090 162 while (1) {
1091 358 my $line = $self->_read_line($sock, $ctx);
1092 356 $self->_assert_header_line($ctx, $line);
1093 348 $line =~ s/\r?\n$//;
1094 348 ▶ last if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 152 196 348
1095 196 ▶ if ($line =~ /^([^:]+):\s*(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^([^:]+):\s*(.*)$/) 196 0 196
1096 196 $headers{lc $1} = $2;
1097 }
1098 }
1099  
1100 # The status code is three digits by now (_assert_status_line), so a 1xx is
1101 # exactly 100..199. Its headers are dropped with it and the next head read.
1102 152 ▶ next if $status_code >= 100 && $status_code < 200;
Branch: 1 branch
BranchTrueFalseTotal
if $status_code >= 100 and $status_code < 200 4 148 152
Condition66%2/3
$status_code >= 100 and $status_code < 200
!ll&&!rl&&r
01484
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
1103  
1104 148 return [$status_code, $status_text, \%headers];
1105 }
1106 }
1107  
1108 # The two ways the head ends early, and neither of them has a byte count to
1109 # compare either (karr k73).
1110 #
1111 # karr k64 left the head out on the grounds that nothing in a status line or a
1112 # header block announces its own length, so there was no announcement to hold
1113 # a short one against. True, and beside the point: an announcement is not what
1114 # is being checked here, any more than it is in _assert_chunk_header one level
1115 # down. HTTP/1.1 frames the head by terminating every line, and the field
1116 # section by an empty line that is mandatory even when there are no fields at
1117 # all (RFC 9112 section 2.1), so "the stream ended where the terminator
1118 # belongs" is a complete test on its own. It is the same question that reader
1119 # already asks about a chunk header, asked of the head.
1120 #
1121 # What it was worth. A head cut short is not just a bogus status: the response
1122 # is then read with whichever headers happened to arrive, and a cut landing
1123 # before Content-Length or Transfer-Encoding leaves neither -- which is
1124 # exactly the close-delimited branch of _read_body, where an EOF is the
1125 # legitimate end and nothing looks wrong. Measured over a socketpair whose
1126 # peer writes "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nX-Half"
1127 # and closes: status 200, one header, an empty body, no complaint. The cuts
1128 # that did get caught were caught by accident one level lower, because the
1129 # half-arrived header happened to be one of those two.
1130 #
1131 # Nothing legitimate ends a head without the blank line, which was measured
1132 # rather than taken from the RFC, on both engines and including the two heads
1133 # an engine writes by hand instead of through its HTTP server: attach and
1134 # /exec/{id}/start answer with "HTTP/1.1 200 OK", one Content-Type line and
1135 # the blank line, on Docker 29.7.2 and on rootless Podman 5.8.4 alike. So do
1136 # 204, 304, HEAD, chunked and every other shape either of them produces.
1137 170 ▶sub _assert_status_line {
Subroutine _assert_status_line: called CC=4 SCAR=13.9
1138 170 my ($self, $ctx, $line) = @_;
1139  
1140 # Only the unterminated half: a status line that never started at all is the
1141 # croak above, which says something better than this could.
1142 170 ▶ $self->_croak_truncated($ctx, phase => 'status-line',
Branch: 2 branches
BranchTrueFalseTotal
unless $line =~ /\n\z/ 4 166 170
length $line == 1 ? : 0 4 4
1143 detail => 'the stream ended inside the status line, after '
1144 . length($line) . ' byte' . (length($line) == 1 ? '' : 's') . ' of one')
1145 unless $line =~ /\n\z/;
1146  
1147 # Terminated, and now: is it an HTTP status line at all? RFC 9112 section 4:
1148 # HTTP-version SP status-code SP [ reason-phrase ], with status-code exactly
1149 # three digits. A line that arrived whole but is not this shape -- a proxy's
1150 # plain-text banner, an ICY greeting, an HTML error page -- would otherwise
1151 # be split on whitespace in _read_head and its second word run through the
1152 # >= 400 comparison as the status. It is refused here rather than silently
1153 # misread, the same way a non-hexadecimal chunk size is one level down.
1154 166 my $stripped = $line =~ s/\r?\n\z//r;
1155 166 ▶ $self->_croak_truncated($ctx, phase => 'status-line',
Branch: 1 branch
BranchTrueFalseTotal
unless $stripped =~ m[\AHTTP/[0-9]+\.[0-9]+ [0-9]{3}(?: .*)?\z] 4 162 166
1156 detail => "the status line '" . $stripped
1157 . "' is not a well-formed HTTP status line")
1158 unless $stripped =~ m{\AHTTP/[0-9]+\.[0-9]+ [0-9]{3}(?: .*)?\z};
1159  
1160 162 return;
1161 }
1162  
1163 # Both halves here, because the header block has no equivalent of that croak:
1164 # undef is a block that was never closed -- with no headers at all, or after
1165 # some -- and an unterminated line is one cut in the middle of a field.
1166 356 ▶sub _assert_header_line {
Subroutine _assert_header_line: called CC=4 SCAR=13.9
1167 356 my ($self, $ctx, $line) = @_;
1168  
1169 356 ▶ $self->_croak_truncated($ctx, phase => 'header-block',
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 5 351 356
1170 detail => 'the stream ended where a header line belongs, with no blank '
1171 . 'line to close the header block')
1172 unless defined $line;
1173  
1174 351 ▶ $self->_croak_truncated($ctx, phase => 'header-block',
Branch: 2 branches
BranchTrueFalseTotal
unless $line =~ /\n\z/ 3 348 351
length $line == 1 ? : 0 3 3
1175 detail => 'the stream ended inside a header line, after '
1176 . length($line) . ' byte' . (length($line) == 1 ? '' : 's') . ' of one')
1177 unless $line =~ /\n\z/;
1178  
1179 348 return;
1180 }
1181  
1182 79 ▶sub _read_body {
Subroutine _read_body: called CC=9 SCAR=22.0
1183 79 my ($self, $sock, $headers, $method, $ctx) = @_;
1184 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
1185  
1186 # A HEAD response repeats the header fields the equivalent GET would send --
1187 # Content-Length and Transfer-Encoding included -- and then sends no body at
1188 # all. Every branch below would wait for bytes that never arrive: until the
1189 # daemon closes the connection at best, and forever if it does not. So the
1190 # body is not read for HEAD, whatever the headers promise.
1191 79 ▶ return '' if defined $method && uc($method) eq 'HEAD';
Branch: 1 branch
BranchTrueFalseTotal
if defined $method and uc $method eq "HEAD" 3 76 79
Condition100%3/3
defined $method and uc $method eq "HEAD"
!ll&&!rl&&r
11653
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
1192  
1193 76 ▶ if ($headers->{'transfer-encoding'}
Branch: 1 branch
BranchTrueFalseTotal
if ($headers->{"transfer-encoding"} and lc $headers->{"transfer-encoding"} eq "chunked") 20 56 76
Condition66%2/3
$headers->{"transfer-encoding"} and lc $headers->{"transfer-encoding"} eq "chunked"
!ll&&!rl&&r
56020
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
1194 && lc($headers->{'transfer-encoding'}) eq 'chunked') {
1195 20 return $self->_read_chunked($sock, $ctx);
1196 }
1197  
1198 56 ▶ if (defined $headers->{'content-length'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $headers->{"content-length"}) 44 12 56
1199 44 my $len = $self->_assert_content_length($ctx, $headers->{'content-length'});
1200 40 ▶ return '' unless $len > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $len > 0 1 39 40
1201 39 my $body = '';
1202 # What a timeout hands over instead of dropping: see
1203 # API::Docker::Error::Timeout/partial. localised so the context goes back
1204 # to carrying nothing once this body is done with.
1205 39 local $ctx->{partial} = \$body;
1206 # An announced length is a promise, and a stream that ends before it is
1207 # kept is truncation rather than the end of the body; see _read_exact.
1208 39 $self->_read_exact($sock, $len, \$body, $ctx, 'content-length',
1209 'the body');
1210 24 return $body;
1211 }
1212  
1213 # Read until the daemon closes. This used to be a `local $/; <$sock>` slurp;
1214 # it is a loop over the same primitive as the other two branches now, which
1215 # is what karr k60 needed and what the timeout wanted anyway -- with $/ undef
1216 # a whole body and a truncated one are both just bytes, so the slurp's own
1217 # result could never say which it was. This is the path karr k52's hang is
1218 # on, an attach whose buffered frames arrive and whose socket then never
1219 # closes.
1220 #
1221 # And the one shape with no completeness check to make: the response
1222 # announced no end, so the close IS the end (karr k64). Treating an EOF here
1223 # as truncation would make every attach, every logs(follow) and every
1224 # exec/start fail on the daemon hanging up, which is how all three finish.
1225 12 my $body = '';
1226 # What a timeout hands over instead of dropping; see the content-length
1227 # branch above.
1228 12 local $ctx->{partial} = \$body;
1229 12 while (1) {
1230 20 my ($n, $buf) = $self->_read_bytes($sock, $READ_SIZE, $ctx);
1231 18 ▶ last unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 10 8 18
1232 8 $body .= $buf;
1233 }
1234  
1235 10 return $body;
1236 }
1237  
1238 # The incremental sibling of _read_response. Same [status, reason, headers,
1239 # body] shape, plus a fifth element: the summary of what the callback was
1240 # handed. The body it returns is empty -- that is the point, nothing is kept --
1241 # except on the two paths that fall back to reading whole, which return undef
1242 # as the summary instead so _request treats them exactly as before.
1243 79 ▶sub _read_streaming_response {
Subroutine _read_streaming_response: called CC=25 SCAR=32.3
1244 79 my ($self, $sock, $method, $handler, $ctx) = @_;
1245 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
1246  
1247 79 my ($status_code, $status_text, $headers) = @{ $self->_read_head($sock, $ctx) };
1248  
1249 # Neither of these is a stream. A >= 400 body is a short JSON object naming
1250 # the failure and _request has to croak with it, so it is read whole and the
1251 # callback never sees it; a HEAD response has no body at all.
1252 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
1253 2 return [$status_code, $status_text, $headers,
1254 $self->_read_body($sock, $headers, $method, $ctx), undef];
1255 }
1256  
1257 # Set only here, past the two branches above, so a timeout while reading an
1258 # error body is still reported in bytes rather than in units nothing
1259 # delivered. From this point on an expiry carries the callback's own summary
1260 # instead: the units are with the caller already, and how many is the part it
1261 # cannot know otherwise.
1262 77 local $ctx->{summary} = $handler->{summary};
1263  
1264 77 my $feed = $handler->{feed};
1265 77 my $more = 1;
1266  
1267 # There is deliberately nothing here to hand the callback the bytes of the
1268 # read that expires. karr k59 needed that hook because PerlIO's read() could
1269 # come back with data *and* EAGAIN at once, so a stall could land with the
1270 # whole response read and none of it fed; sysread cannot (karr k60). Every
1271 # byte reaches the callback in the pull that delivered it, and the pull that
1272 # expires delivers none -- so the property k59 established now holds by
1273 # construction instead of by rescue.
1274  
1275 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
1276 && lc($headers->{'transfer-encoding'}) eq 'chunked') {
1277 44 ▶ while ($more) {
Branch: 1 branch
BranchTrueFalseTotal
if ($more) 98 0 98
1278 98 my $chunk_header = $self->_read_line($sock, $ctx);
1279 95 my $chunk_size = $self->_assert_chunk_header($ctx, $chunk_header);
1280 90 ▶ last if $chunk_size == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk_size == 0 18 72 90
1281  
1282 72 my $read = 0;
1283 72 ▶ while ($read < $chunk_size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($read < $chunk_size) 567 57 624
1284 567 my ($n, $buf) = $self->_read_bytes($sock, $chunk_size - $read, $ctx);
1285 566 ▶ last unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 3 563 566
1286 563 $read += $n;
1287 # Fed per read rather than per completed chunk. A chunk is the
1288 # daemon's framing, not the caller's -- the engine is free to send an
1289 # hour of log output as one chunk -- so waiting for the whole of one
1290 # would reintroduce exactly the buffering this path exists to avoid.
1291 563 $more = $feed->($buf);
1292 560 ▶ last unless $more;
Branch: 1 branch
BranchTrueFalseTotal
unless $more 8 552 560
1293 }
1294  
1295 # Every truncation check on this path is guarded by $more, and that is
1296 # the whole of what distinguishes the two ways a streamed chunk ends
1297 # early: the daemon ran out, or the callback said stop. A caller that
1298 # stopped left the rest of the chunk unread on purpose (karr k64).
1299 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
1300 expected => $chunk_size, received => $read)
1301 if $more && $read < $chunk_size;
1302 65 ▶ last unless $more;
Branch: 1 branch
BranchTrueFalseTotal
unless $more 8 57 65
1303  
1304 # The CRLF that terminates the chunk data. Skipped when the caller
1305 # stopped mid-chunk: the socket is closed straight after, and the
1306 # remaining bytes of that chunk are still unread in front of it.
1307 57 $self->_assert_chunk_terminator($ctx, $self->_read_line($sock, $ctx));
1308 }
1309 }
1310 elsif (defined $headers->{'content-length'}) {
1311 10 my $len = $self->_assert_content_length($ctx, $headers->{'content-length'});
1312 9 my $read = 0;
1313 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
1314 41 my $want = $len - $read;
1315 41 ▶ $want = $READ_SIZE if $want > $READ_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
if $want > $READ_SIZE 0 41 41
1316 41 my ($n, $buf) = $self->_read_bytes($sock, $want, $ctx);
1317 40 ▶ last unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 3 37 40
1318 37 $read += $n;
1319 37 $more = $feed->($buf);
1320 }
1321 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
1322 piece => 'the body', expected => $len, received => $read)
1323 if $more && $read < $len;
1324 }
1325 else {
1326 23 ▶ while ($more) {
Branch: 1 branch
BranchTrueFalseTotal
if ($more) 75 3 78
1327 75 my ($n, $buf) = $self->_read_bytes($sock, $READ_SIZE, $ctx);
1328 72 ▶ last unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 17 55 72
1329 55 $more = $feed->($buf);
1330 }
1331 }
1332  
1333 # Only a stream the daemon ended has a tail worth flushing, or a leftover
1334 # worth complaining about. One the caller stopped has bytes in the carry
1335 # buffer by construction, and treating those as truncation would turn every
1336 # early stop into an error.
1337 51 ▶ $handler->{finish}->() unless $handler->{stopped}->();
Branch: 1 branch
BranchTrueFalseTotal
unless $handler->{"stopped"}->() 38 13 51
1338  
1339 50 return [$status_code, $status_text, $headers, '', $handler->{summary}->()];
1340 }
1341  
1342 # One unit per call, and the unit is whichever of the three the caller asked
1343 # for. The engine's streaming endpoints do not share one: /events and the
1344 # build/pull/push progress streams are newline-delimited JSON, logs and
1345 # exec/start are 8-byte-framed, and an image export is bytes with no structure
1346 # above them at all. Forcing one unit on all three would mean handing two of
1347 # them back undecoded and calling it streaming.
1348 #
1349 # The three decoders differ only in how they cut the byte stream up; the carry
1350 # buffer, the delivery and the stop handling below are common to all of them.
1351 79 ▶sub _stream_handler {
Subroutine _stream_handler: called CC=3 SCAR=11.0
1352 79 my ($self, $endpoint, $option, $cb, $croak_on_error) = @_;
1353  
1354 79 my $carry = '';
1355 79 my $delivered = 0;
1356 79 my $stopped = 0;
1357  
1358 # Stopping is an explicit call, not a return value, and the callback's
1359 # return value is deliberately never looked at. Every truthiness convention
1360 # has a silent failure mode here: `push @got, $_[0]` returns a count and
1361 # `$last = $event->{status}` returns whatever the engine said -- and a
1362 # container event's status is literally 'stop'. Both would end the stream by
1363 # accident and hand back a truncated one with no diagnostic. A closure the
1364 # caller has to invoke cannot be produced by accident.
1365 79 ▶ my $stop = sub { $stopped = 1; return };
Subroutine __ANON__: called CC=1 SCAR=0.0
1366  
1367 163 ▶ my $deliver = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1368 163 my ($unit) = @_;
1369 163 $delivered++;
1370 163 $cb->($unit, $stop);
1371 163 return !$stopped;
1372 79 };
1373  
1374 79 my ($feed, $finish);
1375  
1376 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
1377 # No carry: the bytes as they arrive are the unit, so there is no boundary
1378 # to reassemble across.
1379 110 ▶ $feed = sub {
Subroutine __ANON__: called CC=3 SCAR=12.5
1380 110 my ($bytes) = @_;
1381 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
1382 110 return $deliver->($bytes);
1383 47 };
1384 47 ▶ $finish = sub { return };
Subroutine __ANON__: called CC=1 SCAR=0.0
1385 }
1386 elsif ($option eq 'on_event') {
1387 36 ▶ my $emit_line = sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
1388 36 my ($line) = @_;
1389 36 $line =~ s/\r\z//;
1390 36 ▶ return 1 unless $line =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /\S/ 0 36 36
1391 36 my $event = eval { decode_json($line) };
1392 36 ▶ return 1 unless defined $event;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $event 0 36 36
1393 # Checked per event rather than over the finished list, so a failed
1394 # build croaks at the event that reports it instead of when the daemon
1395 # eventually closes. The Error::Stream then carries that one event: a
1396 # callback stream keeps no history, having been given all of it already.
1397 36 ▶ $self->_assert_no_stream_error($endpoint, [$event]) if $croak_on_error;
Branch: 1 branch
BranchTrueFalseTotal
if $croak_on_error 9 27 36
1398 34 return $deliver->($event);
1399 18 };
1400 439 ▶ $feed = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1401 439 my ($bytes) = @_;
1402 439 $carry .= $bytes;
1403 # A JSON string cannot contain a literal newline, so a newline in the
1404 # buffer always ends an event -- and everything after the last one is
1405 # an event still arriving, which stays in the carry for the next read.
1406 439 ▶ while ((my $idx = index($carry, "\n")) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $idx = index($carry, "\n")) >= 0) 35 433 468
1407 35 my $line = substr($carry, 0, $idx, '');
1408 35 substr($carry, 0, 1, '');
1409 35 ▶ return 0 unless $emit_line->($line);
Branch: 1 branch
BranchTrueFalseTotal
unless &$emit_line($line) 4 29 33
1410 }
1411 433 return 1;
1412 18 };
1413 8 ▶ $finish = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1414 # A last event with no trailing newline is a complete event, not a
1415 # truncated one: the daemon closing is what ended it.
1416 8 ▶ return unless length $carry;
Branch: 1 branch
BranchTrueFalseTotal
unless length $carry 7 1 8
1417 1 my $line = $carry;
1418 1 $carry = '';
1419 1 $emit_line->($line);
1420 1 return;
1421 18 };
1422 }
1423 else {
1424 106 ▶ $feed = sub {
Subroutine __ANON__: called CC=8 SCAR=20.9
1425 106 my ($bytes) = @_;
1426 106 $carry .= $bytes;
1427 106 ▶ while (length($carry) >= 8) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $carry >= 8) 47 75 122
1428 47 my ($type, $pad1, $pad2, $pad3, $size) = unpack 'C4 N', substr($carry, 0, 8);
1429 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
1430 . 'byte 0 is ' . $type . ', bytes 1-3 are ' . $pad1 . '/' . $pad2
1431 . '/' . $pad3 . '). A callback stream cannot sniff its own framing '
1432 . 'the way the buffered path does -- that needs the whole body, '
1433 . 'which is what is not being kept. Declare an unframed stream with '
1434 . 'tty => 1'
1435 if $type > $#STREAM_TYPE || $pad1 || $pad2 || $pad3;
1436 # The header is complete but the payload is not yet: leave the whole
1437 # frame in the carry and wait for the rest of it. This is the case a
1438 # per-chunk reader gets wrong -- an 8-byte header can be split across
1439 # two chunks just as easily as a payload can.
1440 46 ▶ last if length($carry) < 8 + $size;
Branch: 1 branch
BranchTrueFalseTotal
if length $carry < 8 + $size 27 19 46
1441 19 my $frame = {
1442 stream => $STREAM_TYPE[$type],
1443 data => substr($carry, 8, $size),
1444 };
1445 19 substr($carry, 0, 8 + $size, '');
1446 19 ▶ return 0 unless $deliver->($frame);
Branch: 1 branch
BranchTrueFalseTotal
unless &$deliver($frame) 3 16 19
1447 }
1448 102 return 1;
1449 14 };
1450 10 ▶ $finish = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1451 10 ▶ return unless length $carry;
Branch: 1 branch
BranchTrueFalseTotal
unless length $carry 9 1 10
1452 1 croak __PACKAGE__ . '->_request on_frame: the daemon closed mid-frame, '
1453 . 'leaving ' . length($carry) . ' bytes that do not complete one';
1454 14 };
1455 }
1456  
1457 return {
1458 feed => $feed,
1459 finish => $finish,
1460 51 ▶ stopped => sub { $stopped },
Subroutine __ANON__: called CC=1 SCAR=0.0
1461 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
1462 79 };
1463 }
1464  
1465 36 ▶sub _read_chunked {
Subroutine _read_chunked: called CC=3 SCAR=11.0
1466 36 my ($self, $sock, $ctx) = @_;
1467 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
1468 36 my $body = '';
1469 # See _read_body: the accumulator a timeout hands over. The chunk data is
1470 # appended to it directly rather than to a per-chunk temporary, so a stall
1471 # in the middle of a chunk still carries the bytes of that chunk out with
1472 # the exception. The two are otherwise the same -- the temporary was only
1473 # ever concatenated onto $body straight afterwards.
1474 36 local $ctx->{partial} = \$body;
1475  
1476 36 while (1) {
1477 91 my $chunk_header = $self->_read_line($sock, $ctx);
1478 86 my $chunk_size = $self->_assert_chunk_header($ctx, $chunk_header);
1479 79 ▶ last if $chunk_size == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk_size == 0 15 64 79
1480  
1481 64 $self->_read_exact($sock, $chunk_size, \$body, $ctx, 'chunk-data',
1482 'a chunk');
1483  
1484 # Read trailing \r\n after chunk data
1485 59 $self->_assert_chunk_terminator($ctx, $self->_read_line($sock, $ctx));
1486 }
1487  
1488 15 return $body;
1489 }
1490  
1491 # The two places a chunked body ends without saying so, and neither of them
1492 # has a byte count to compare (karr k64).
1493 #
1494 # A chunked body is terminated by a chunk of size zero and by nothing else, so
1495 # an end of stream where the next chunk header belongs is the daemon hanging
1496 # up mid-body -- not the end of it. The reader used to `last unless defined`
1497 # there and hand back the chunks that had completed as the whole response.
1498 #
1499 # _read_line answers an end of stream with what is left in the buffer and no
1500 # terminator, exactly as the readline it replaces did (see there), so an
1501 # unterminated line is the other half of the same question: a header cut in
1502 # half is `hex('1')` and reads as a perfectly good chunk of one byte.
1503 181 ▶sub _assert_chunk_header {
Subroutine _assert_chunk_header: called CC=5 SCAR=16.1
1504 181 my ($self, $ctx, $line) = @_;
1505  
1506 181 ▶ $self->_croak_truncated($ctx, phase => 'chunk-header',
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 5 176 181
1507 detail => 'the stream ended where a chunk header belongs, with no '
1508 . 'terminating zero chunk')
1509 unless defined $line;
1510  
1511 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
1512 detail => 'the stream ended inside a chunk header, after '
1513 . length($line) . ' byte' . (length($line) == 1 ? '' : 's') . ' of one')
1514 unless $line =~ /\n\z/;
1515  
1516 # The line arrived whole and terminated, and its size is not a hexadecimal
1517 # number. Left to hex() that warns once and reads as 0 -- the terminating
1518 # zero chunk -- so a 200 whose framing is corrupt used to come back as an
1519 # empty body, the same body-shaped lie a truncation is. A chunk size is hex
1520 # digits, optionally followed by a ';' extension (RFC 9112 section 7.1.1),
1521 # which is read past and discarded; anything else is refused here rather than
1522 # silently misread by the caller. The returned size is parsed from the same
1523 # match, so hex() is called on nothing but hex digits and never has cause to
1524 # warn on a legal extension either.
1525 171 my ($size) = $line =~ /^([0-9A-Fa-f]+)(?:;.*)?\r?\n\z/;
1526 171 ▶ $self->_croak_truncated($ctx, phase => 'chunk-header',
Branch: 1 branch
BranchTrueFalseTotal
unless defined $size 2 169 171
1527 detail => "the chunk size line '" . ($line =~ s/\r?\n\z//r)
1528 . "' is not a hexadecimal number")
1529 unless defined $size;
1530  
1531 169 return hex($size);
1532 }
1533  
1534 # Completeness only, never content: a terminator that arrived but is not CRLF
1535 # is a daemon speaking chunked wrongly, which is a different complaint and one
1536 # this reader has never made.
1537 114 ▶sub _assert_chunk_terminator {
Subroutine _assert_chunk_terminator: called CC=3 SCAR=11.0
1538 114 my ($self, $ctx, $line) = @_;
1539  
1540 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
1541 detail => 'the stream ended before the CRLF that terminates a chunk')
1542 unless defined $line && $line =~ /\n\z/;
1543  
1544 109 return;
1545 }
1546  
1547 # The declared body length, validated to be the digits RFC 9110 section 8.6
1548 # requires before it is compared against or counted down (karr k113). The
1549 # sibling of _assert_chunk_header's hex check: a Content-Length that is not a
1550 # number -- 'abc', an empty value, a duplicated '11, 11', a leading space --
1551 # left as it stood is run through `$len > 0`, which warns once ("isn't
1552 # numeric") and reads as 0, so the body is taken to be empty and a response
1553 # that had one comes back blank. Refused here rather than silently misread, so
1554 # hex()'s sibling warning is never reached either.
1555 54 ▶sub _assert_content_length {
Subroutine _assert_content_length: called CC=2 SCAR=6.9
1556 54 my ($self, $ctx, $value) = @_;
1557  
1558 54 ▶ return $value if $value =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /\A[0-9]+\z/ 49 5 54
1559  
1560 5 $self->_croak_truncated($ctx, phase => 'content-length',
1561 detail => "the Content-Length header '" . $value . "' is not a number");
1562 }
1563  
1564 389 ▶sub _uri_encode {
Subroutine _uri_encode: called CC=2 SCAR=6.9
1565 389 my ($str) = @_;
1566 # Escape a character string by its UTF-8 bytes ('ΓΌ' -> %C3%BC, not %FC), and
1567 # a byte string as it stands. ord() on a character is not its wire byte: a
1568 # name or tag typed under `use utf8`, or read through a :utf8 layer, arrives
1569 # as characters and used to escape to a lone high byte or a bare codepoint
1570 # (%FC, %4E2D) that is not UTF-8 at all. But the encoding cannot be
1571 # unconditional: encode_json has already handed a HASH param (filters among
1572 # them) its UTF-8 octets, and re-encoding those would double them
1573 # (%C3%BC -> %C3%83%C2%BC). The utf8 flag is exactly that distinction -- on
1574 # for a decoded string, off for encode_json's output -- so a copy is encoded
1575 # only when it carries one, leaving the caller's own value untouched either
1576 # way.
1577 389 my $bytes = $str;
1578 389 ▶ utf8::encode($bytes) if utf8::is_utf8($bytes);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($bytes) 2 387 389
1579 389 $bytes =~ s/([^A-Za-z0-9\-_.~:\/])/sprintf("%%%02X", ord($1))/ge;
1580 389 return $bytes;
1581 }
1582  
1583 361 ▶sub get {
Subroutine get: called CC=1 SCAR=0.0
Pod documented
1584 361 my ($self, $path, %opts) = @_;
1585 361 return $self->_request('GET', $path, %opts);
1586 }
1587  
1588  
1589 222 ▶sub post {
Subroutine post: called CC=2 SCAR=6.9
Pod documented
1590 222 my ($self, $path, $body, %opts) = @_;
1591 222 ▶ $opts{body} = $body if defined $body;
Branch: 1 branch
BranchTrueFalseTotal
if defined $body 63 159 222
1592 222 return $self->_request('POST', $path, %opts);
1593 }
1594  
1595  
1596 9 ▶sub put {
Subroutine put: called CC=2 SCAR=7.1
Pod documented
1597 9 my ($self, $path, $body, %opts) = @_;
1598 9 ▶ $opts{body} = $body if defined $body;
Branch: 1 branch
BranchTrueFalseTotal
if defined $body 0 9 9
1599 9 return $self->_request('PUT', $path, %opts);
1600 }
1601  
1602  
1603 37 ▶sub delete_request {
Subroutine delete_request: called CC=1 SCAR=0.0
Pod documented
1604 37 my ($self, $path, %opts) = @_;
1605 37 return $self->_request('DELETE', $path, %opts);
1606 }
1607  
1608  
1609 12 ▶sub head {
Subroutine head: called CC=1 SCAR=0.0
Pod documented
1610 12 my ($self, $path, %opts) = @_;
1611 12 return $self->_request('HEAD', $path, %opts);
1612 }
1613  
1614  
1615 48 ▶sub stream_frames {
Subroutine stream_frames: called CC=7 SCAR=19.5
Pod documented
1616 48 my ($self, $method, $path, %opts) = @_;
1617  
1618 48 my $tty = delete $opts{tty};
1619  
1620 48 ▶ if (my $cb = delete $opts{on_frame}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = delete $opts{"on_frame"}) 9 39 48
1621 # tty is a declaration here, not the hint it is on the buffered path. The
1622 # sniff below needs the whole body to decide, and the whole body is what a
1623 # callback stream does not have; so an unframed stream has to say so, and
1624 # anything not declared is required to be framed.
1625 return $self->_request($method, $path, %opts,
1626 $tty
1627 3 ▶ ? ( on_chunk => sub { $cb->({ stream => 'raw', data => $_[0] }, $_[1]) } )
Subroutine __ANON__: called CC=1 SCAR=0.0
1628 9 ▶ : ( on_frame => $cb ),
Branch: 1 branch
BranchTrueFalseTotal
$tty ? : 1 8 9
1629 );
1630 }
1631  
1632 39 my $body = $self->_request($method, $path, %opts, raw => 1);
1633  
1634 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
1635  
1636 23 ▶ my $frames = $tty ? undef : $self->_demux_frames($body);
Branch: 1 branch
BranchTrueFalseTotal
$tty ? : 3 20 23
1637  
1638 23 ▶ return $frames if $frames;
Branch: 1 branch
BranchTrueFalseTotal
if $frames 17 6 23
1639 6 return [ { stream => 'raw', data => $body } ];
1640 }
1641  
1642  
1643 30 ▶sub _demux_frames {
Subroutine _demux_frames: called CC=9 SCAR=22.0
1644 30 my ($self, $body) = @_;
1645  
1646 30 my $len = length $body;
1647 30 my $pos = 0;
1648 30 my @frames;
1649  
1650 30 ▶ while ($pos < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $len) 48 20 68
1651 48 ▶ return undef if $len - $pos < 8;
Branch: 1 branch
BranchTrueFalseTotal
if $len - $pos < 8 2 46 48
1652 46 my ($type, $pad1, $pad2, $pad3, $size) = unpack 'C4 N', substr($body, $pos, 8);
1653 46 ▶ return undef if $type > $#STREAM_TYPE;
Branch: 1 branch
BranchTrueFalseTotal
if $type > $#STREAM_TYPE 6 40 46
1654 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
1655 39 ▶ return undef if $len - $pos - 8 < $size;
Branch: 1 branch
BranchTrueFalseTotal
if $len - $pos - 8 < $size 1 38 39
1656 38 push @frames, {
1657 stream => $STREAM_TYPE[$type],
1658 data => substr($body, $pos + 8, $size),
1659 };
1660 38 $pos += 8 + $size;
1661 }
1662  
1663 20 ▶ return undef unless @frames;
Branch: 1 branch
BranchTrueFalseTotal
unless @frames 1 19 20
1664 19 return \@frames;
1665 }
1666  
1667  
1668 47 1;
1669  
1670 __END__
« Docker/API/Images.pm ↑ Summary Docker/API/Containers.pm »