API-Docker

 view release on metacpan or  search on metacpan

lib/API/Docker/Role/HTTP.pm  view on Meta::CPAN

# reference -- spliced straight into the request line as /v$version$path, so a
# byte the line's own grammar reads rewrites the request rather than naming a
# resource: CR or LF ends the line, a space opens the HTTP-version field, and
# a ? or # opens the query or fragment. It is held to the RFC 3986 origin-form
# path character set -- unreserved, the sub-delims, and : @ % / -- and
# rejected, not sanitised, for the reason a header name is (see
# _assert_request_path). Query parameters carry the ? and everything after it
# and are assembled separately below, each element run through _uri_encode.
my $REQUEST_PATH = qr{\A[A-Za-z0-9\-._~:/\@!\$&'()*+,;=%]*\z};

# The three units a response can be cut into, one option each. A request picks
# one of them, or none and gets the buffered path; see _stream_handler.
my @STREAM_OPTION = qw( on_event on_frame on_chunk );

# What a response body has to start with to be worth handing to decode_json.
# An object or an array is not the whole of JSON: the engine answers several
# endpoints with a bare JSON scalar, and a `null` used to come back as the
# four-character string 'null'. See _request.
my $JSON_BODY = qr/\A\s*(?:[\[\{"]|-?[0-9]|true|false|null)/;

# How much is asked for per sysread. Strictly an upper bound -- sysread
# returns what has arrived rather than filling to it (see _pull), so on a live
# feed a call typically comes back with one burst, and asking for 64K costs
# nothing but the size of the buffer it lands in.
my $READ_SIZE = 64 * 1024;

has read_timeout => (
  is => 'ro',
);


has connect_timeout => (
  is => 'ro',
);


has _socket => (
  is      => 'lazy',
  clearer => '_clear_socket',
);

# The connect timeout and the endpoint it belongs to, on their way to
# _build__socket. It is a lazy builder and so cannot be handed an argument,
# and the value is per request rather than per client -- hence rw, with
# _reconnect as the only writer, setting it immediately before the build and
# clearing it immediately after. Unset is the whole of the old behaviour: no
# Timeout on any constructor, and the plain croak on a failure.
has _pending_connect => (
  is       => 'rw',
  init_arg => undef,
);

sub _build__socket {
  my ($self) = @_;
  my $host    = $self->host;
  my $pending = $self->_pending_connect;
  my $timeout = $pending ? $pending->{timeout} : undef;

  if ($host =~ m{^unix://(.+)$}) {
    my $path = $1;
    $log->debugf("Connecting to Unix socket: %s", $path);
    my $sock = IO::Socket::UNIX->new(
      Peer => $path,
      Type => SOCK_STREAM,
      $timeout ? (Timeout => $timeout) : (),
    );
    unless ($sock) {
      # Asked before anything else can touch $@ or $!, which is the whole of
      # the evidence; see _connect_expired.
      $self->_croak_connect_timeout($pending, 'unix://' . $path)
        if $self->_connect_expired($timeout);
      croak "Cannot connect to Unix socket $path: $!";
    }
    return $sock;
  }
  elsif ($host =~ m{^tcp://([^:]+):(\d+)$}) {
    my ($addr, $port) = ($1, $2);

    unless ($self->tls) {
      $log->debugf("Connecting to TCP %s:%s", $addr, $port);
      my $sock = IO::Socket::INET->new(
        PeerAddr => $addr,
        PeerPort => $port,
        Proto    => 'tcp',
        $timeout ? (Timeout => $timeout) : (),
      );
      unless ($sock) {
        $self->_croak_connect_timeout($pending, $addr . ':' . $port)
          if $self->_connect_expired($timeout);
        croak "Cannot connect to $addr:$port: $!";
      }
      return $sock;
    }

    # Built before the connection is opened: a cert_path that names nothing,
    # or half a client certificate, is a configuration mistake and the caller
    # should hear about it as one rather than as a handshake failure.
    my %ssl = $self->_ssl_options($addr);

    $log->debugf("Connecting to TCP %s:%s over TLS (verification %s)",
      $addr, $port, $self->tls_insecure ? 'off' : 'on');
    my $sock = IO::Socket::SSL->new(
      PeerAddr => $addr,
      PeerPort => $port,
      Proto    => 'tcp',
      $timeout ? (Timeout => $timeout) : (),
      %ssl,
    );
    unless ($sock) {
      $self->_croak_connect_timeout($pending, $addr . ':' . $port . ' (TLS)')
        if $self->_connect_expired($timeout);
      # $SSL_ERROR carries the handshake failure -- an untrusted certificate,
      # a name that does not match -- and $! the plain connect failure. Both
      # are named because either can be the one that happened. The pragma is
      # for the package variable of a module that is not loaded at compile
      # time, which perl would otherwise report as a probable typo.
      no warnings 'once';
      croak 'Cannot connect to ' . $addr . ':' . $port . ' over TLS: '
        . ($IO::Socket::SSL::SSL_ERROR || $! || 'unknown error');
    }
    return $sock;
  }
  else {
    croak "Unsupported host format: $host (expected unix:// or tcp://)";
  }
}

# Loaded here rather than with the other modules at the top of the file.
# IO::Socket::SSL pulls in Net::SSLeay, which is XS compiled against libssl,
# and the unix:// transport -- local Docker, rootless Podman, the default and
# the only one most installations use -- never needs a byte of it. A hard
# dependency would make this client unbuildable on a machine with no OpenSSL
# headers for the sake of a transport it is not using, so it is a recommended
# one and this is the point where its absence becomes an error.
sub _load_ssl {
  my ($self) = @_;

  return 1 if eval { require IO::Socket::SSL; 1 };
  my $why = $@ || 'unknown error';
  $why =~ s/\s+\z//;
  croak __PACKAGE__ . ': tls => 1 needs IO::Socket::SSL, which failed to '
    . 'load (' . $why . '). It is a recommended rather than a required '
    . 'dependency because the unix:// transport never uses it -- install it '
    . 'with `cpanm IO::Socket::SSL` (or `cpanm --with-recommends '
    . 'API::Docker`)';
}

# The IO::Socket::SSL arguments for this client, as a plain hash, so the
# policy can be read off without opening a connection.
sub _ssl_options {
  my ($self, $addr) = @_;

  $self->_load_ssl;

  # SNI, sent whether or not the certificate is checked: a terminator serving
  # several names needs it to pick the right one, and that is true of an
  # unverified connection too.
  my %ssl = ( SSL_hostname => $addr );

  if ($self->tls_insecure) {

lib/API/Docker/Role/HTTP.pm  view on Meta::CPAN


  # Checked here for the same reason, and one at a time: the three units are
  # three shapes the engine's streaming endpoints have, not three views of one
  # stream, so a request asking for two of them has no answer.
  my @streaming = grep { exists $opts{$_} } @STREAM_OPTION;
  croak __PACKAGE__ . '->_request takes one of ' . join(', ', @STREAM_OPTION)
    . ', not ' . join(' and ', @streaming) if @streaming > 1;
  croak __PACKAGE__ . '->_request ' . $streaming[0] . ' option must be a CodeRef'
    if @streaming && ref $opts{$streaming[0]} ne 'CODE';

  my $version = $self->api_version;

  # Caller data -- a container name, an image reference -- is spliced straight
  # into the request line through $path, so it is validated before it can reach
  # the wire, exactly as a header name is. See _assert_request_path.
  $self->_assert_request_path($path);

  my $url_path = defined $version ? "/v$version$path" : $path;

  # Kept before the query string is appended: it names the request in an
  # error message, and the query string is where /build carries buildargs,
  # which can hold credentials and have no business in an exception.
  my $endpoint = $method . ' ' . $url_path;

  # Definedness, not truth. A raw_body of '' (an empty tar) or of the string
  # '0' is a body the caller asked to send, and testing it for truth dropped
  # both: they fell through to the body branch, and the request then went out
  # with no Content-Length, no Content-Type and no payload at all. Whether
  # there is a body is therefore tracked separately from what it says.
  my $body_content;
  my $content_type = 'application/json';
  if (defined $opts{raw_body}) {
    $body_content = $opts{raw_body};
    $content_type = $opts{content_type} // 'application/x-tar';
  }
  elsif ($opts{body}) {
    $body_content = encode_json($opts{body});
  }

  if ($opts{params}) {
    my @pairs;
    for my $k (sort keys %{$opts{params}}) {
      my $v = $opts{params}{$k};
      next unless defined $v;
      # An ArrayRef is one parameter given more than once, not one value:
      # `names => ['a', 'b']` is `names=a&names=b`. That spelling is the only
      # one GET /images/get accepts -- the comma-joined form is read as a
      # single image reference and answered with 500 -- and Go's r.Form[k] is
      # a list for every parameter, so it is the general shape rather than
      # that endpoint's quirk. Element order is the caller's and is kept;
      # only the keys are sorted.
      for my $item (ref $v eq 'ARRAY' ? @$v : ($v)) {
        next unless defined $item;
        push @pairs, _uri_encode($k) . '='
          . _uri_encode(ref $item eq 'HASH' ? encode_json($item) : $item);
      }
    }
    $url_path .= '?' . join('&', @pairs) if @pairs;
  }

  $log->debugf("%s %s", $method, $url_path);

  my $request = "$method $url_path HTTP/1.1\r\n";
  $request .= "Host: localhost\r\n";
  $request .= "Connection: close\r\n";
  $request .= "User-Agent: API-Docker\r\n";

  if (defined $body_content) {
    $request .= "Content-Type: $content_type\r\n";
    $request .= "Content-Length: " . length($body_content) . "\r\n";
  }

  if ($opts{headers}) {
    for my $h (sort keys %{$opts{headers}}) {
      # The name is validated before the value is even looked at: a name that
      # cannot go on the wire is a caller bug whether or not the header ends
      # up being sent.
      $self->_assert_header_name($h);
      my $v = $opts{headers}{$h};
      next unless defined $v;
      $v =~ s/[\r\n]//g;
      $request .= "$h: $v\r\n";
    }
  }

  $request .= "\r\n";
  $request .= $body_content if defined $body_content;

  my $handler = @streaming
    ? $self->_stream_handler($endpoint, $streaming[0], $opts{$streaming[0]},
        $opts{croak_on_error} // 1)
    : undef;

  # Resolved with exists rather than truth, so `read_timeout => 0` is a
  # request to wait as long as it takes and can turn a client-wide default off
  # for one call -- which `//` would have read as "no opinion" and overridden.
  my $timeout = $self->_read_timeout_value(
    exists $opts{read_timeout} ? $opts{read_timeout} : $self->read_timeout);

  # Same resolution, same reason.
  my $connect_timeout = $self->_connect_timeout_value(
    exists $opts{connect_timeout}
      ? $opts{connect_timeout} : $self->connect_timeout);

  # The endpoint without its query string, for the same reason the >= 400
  # croak uses that form.
  my $ctx = { endpoint => $endpoint, timeout => $timeout };

  my $sock = $self->_reconnect(
    { timeout => $connect_timeout, endpoint => $endpoint });
  # Applied here rather than in _build__socket because the value is per
  # request, not per client: a socket is opened and closed for each one, so
  # this is the connection the option belongs to.
  $self->_apply_read_timeout($sock, $timeout);

  # The request goes out with SIGPIPE ignored and every write checked
  # (karr k114). A daemon that answers and closes before it has read the
  # body -- dockerd does this for a rejected put_archive or build -- used to
  # raise SIGPIPE on the next write and end the calling process with status
  # 141, no exception. Now the failed write is only remembered: the response
  # the daemon may already have sent is still read, so a 4xx reaches the
  # caller as an Error::HTTP, and only when there is none is the write error
  # the answer.
  my $write_error;
  # print rather than syswrite: it also serves the in-memory sinks the test
  # transports use, and IO::Socket handles are autoflushed, so its result is
  # the result of the write.
  {
    local $SIG{PIPE} = 'IGNORE';
    $write_error = $!.'' unless print $sock $request;
  }

  # Reading can croak, and now does so from further in than it used to: an
  # on_event stream raises Error::Stream at the event that reports the
  # failure, and an on_frame stream refuses a header that is not one. Without
  # the eval those exceptions leave the socket open until the next request
  # replaces it, so it is closed on the way out either way and the exception
  # re-raised unchanged.
  my $response;
  my $ok  = eval { $response = $handler
    ? $self->_read_streaming_response($sock, $method, $handler, $ctx)
    : $self->_read_response($sock, $method, $ctx); 1 };
  my $err = $@;
  close $sock;
  $self->_clear_socket;
  if (!$ok && defined $write_error) {
    # The daemon sent nothing usable and the write had failed: the write is
    # the cause, and the endpoint belongs in the message.
    croak 'Docker API request to '.$endpoint.' failed: could not send the '
      .'request ('.$write_error.') and no response followed';
  }
  die $err unless $ok;

  my ($status_code, $status_text, $headers, $body, $summary) = @$response;

  $log->debugf("Response: %s %s", $status_code, $status_text);

  # The status line and the response headers are metadata the return value
  # cannot carry: it is the decoded body and nothing else, so 204 and 304 are
  # both undef and a header holding the payload -- HEAD
  # /containers/{id}/archive answers with an empty body and
  # X-Docker-Container-Path-Stat -- is unreachable. They go into a hash the
  # caller supplies, so no existing caller's return shape changes. Filled
  # before the croak below, so an eval'ing caller can still read the status.
  if (my $out = $opts{response}) {
    %$out = (
      status  => $status_code,
      reason  => $status_text,
      headers => $headers,
    );
  }

  if ($status_code >= 400) {
    my $error_msg = $body;
    my $data;
    if ($body && $body =~ /^\s*[\{\[]/) {
      eval {
        $data = decode_json($body);
        # Docker answers with {"message":...}. Podman answers a failed push
        # with the stream shape instead -- {"errorDetail":{"message":...},
        # "error":...} and no message key at all -- so without these two
        # fallbacks the whole JSON object became the croak text (karr k13).
        my $detail = ref $data->{errorDetail} eq 'HASH'
          ? $data->{errorDetail}{message} : undef;
        $error_msg = $data->{message} // $detail // $data->{error} // $body;
      };
    }

    # Carp hands a reference straight back rather than decorating it, so this
    # croak is a die with an object -- hence the location captured by hand,
    # which names the same frame a croak of a plain string would have named.
    # message . location is byte for byte what the string croak produced,
    # newline-terminated engine messages included: Carp appends the suffix
    # after the newline rather than skipping it (karr k50).
    my $error = API::Docker::Error::HTTP->new(
      message  => "Docker API error ($status_code): $error_msg",
      location => shortmess(''),
      status   => $status_code,
      reason   => $status_text,
      body     => $body // '',
      data     => $data,
    );
    croak $error;
  }

  # A streamed request has handed every unit to the callback already and kept
  # none of them, so there is no body left to decode and return. What the
  # caller cannot know otherwise is how the stream ended, and that is what
  # comes back instead.
  return $summary if $summary;

  # Zero bytes is a different answer in each shape a request can ask for, so
  # the two options that promise one are answered before the empty-body check
  # rather than after it. `raw` promises the response bytes and a body of no
  # bytes is '', which a caller can take length() of; `ndjson` promises an
  # ArrayRef of events even for a stream carrying a single object, so a stream



( run in 1.043 second using v1.01-cache-2.11-cpan-c32d3c3b8f1 )