| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! A minimal Docker Engine API client over the daemon's unix socket. |
| 4 | //! |
| 5 | //! One HTTP/1.1 connection per call: the daemon is local, the calls are |
| 6 | //! rare (a container starts once), and a pooled client would have to be |
| 7 | //! taught about hijacked exec streams and long-polled waits anyway. Podman |
| 8 | //! serves the same API on its own socket, so nothing here names Docker |
| 9 | //! beyond the default socket path. |
| 10 | |
| 11 | use anyhow::{anyhow, Context}; |
| 12 | use bytes::Bytes; |
| 13 | use http_body_util::{BodyExt, Full}; |
| 14 | use hyper::body::Incoming; |
| 15 | use hyper::header::{CONNECTION, CONTENT_TYPE, HOST, UPGRADE}; |
| 16 | use hyper::{Request, Response, StatusCode}; |
| 17 | use hyper_util::rt::TokioIo; |
| 18 | use std::path::{Path, PathBuf}; |
| 19 | use tokio::io::{AsyncRead, AsyncWrite}; |
| 20 | use tokio::net::UnixStream; |
| 21 | |
| 22 | /// Unversioned paths: the daemon answers with its newest API, and every |
| 23 | /// call here uses fields that have been stable since API 1.24. A pinned |
| 24 | /// version is refused by a daemon whose minimum moved past it, which Docker |
| 25 | /// 29 did for 1.41. |
| 26 | const API: &str = ""; |
| 27 | |
| 28 | #[derive(Clone, Debug)] |
| 29 | pub struct Docker { |
| 30 | socket: PathBuf, |
| 31 | } |
| 32 | |
| 33 | /// A raw bidirectional stream the daemon hijacked for an exec or attach. |
| 34 | pub trait Stream: AsyncRead + AsyncWrite + Send + Unpin {} |
| 35 | impl<T: AsyncRead + AsyncWrite + Send + Unpin> Stream for T {} |
| 36 | |
| 37 | pub struct Reply { |
| 38 | pub status: StatusCode, |
| 39 | pub body: Bytes, |
| 40 | } |
| 41 | |
| 42 | impl Reply { |
| 43 | pub fn json(&self) -> anyhow::Result<serde_json::Value> { |
| 44 | serde_json::from_slice(&self.body).context("decode Docker response") |
| 45 | } |
| 46 | |
| 47 | /// The daemon's `message` field, or the raw body. |
| 48 | pub fn message(&self) -> String { |
| 49 | self.json() |
| 50 | .ok() |
| 51 | .and_then(|value| value.get("message")?.as_str().map(str::to_string)) |
| 52 | .unwrap_or_else(|| String::from_utf8_lossy(&self.body).into_owned()) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | impl Docker { |
| 57 | pub fn new(socket: impl Into<PathBuf>) -> Self { |
| 58 | Self { |
| 59 | socket: socket.into(), |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /// The daemon socket: `DOCKER_HOST` when it names a unix socket, else |
| 64 | /// the first of the well-known paths that exists. Docker Desktop and |
| 65 | /// OrbStack put theirs under the home directory; Linux under `/var/run`. |
| 66 | pub fn discover() -> Option<Self> { |
| 67 | if let Ok(host) = std::env::var("DOCKER_HOST") { |
| 68 | let path = host.strip_prefix("unix://")?; |
| 69 | return Some(Self::new(path)); |
| 70 | } |
| 71 | let home = std::env::var_os("HOME").map(PathBuf::from); |
| 72 | let candidates = [ |
| 73 | Some(PathBuf::from("/var/run/docker.sock")), |
| 74 | home.as_ref() |
| 75 | .map(|home| home.join(".orbstack/run/docker.sock")), |
| 76 | home.as_ref() |
| 77 | .map(|home| home.join(".docker/run/docker.sock")), |
| 78 | Some(PathBuf::from("/run/podman/podman.sock")), |
| 79 | ]; |
| 80 | // A connect, not a stat: the socket is a daemon's, not node |
| 81 | // storage, and a stale socket file without a daemon behind it must |
| 82 | // not win over the next candidate. |
| 83 | candidates |
| 84 | .into_iter() |
| 85 | .flatten() |
| 86 | .find(|path| std::os::unix::net::UnixStream::connect(path).is_ok()) |
| 87 | .map(Self::new) |
| 88 | } |
| 89 | |
| 90 | pub fn socket(&self) -> &Path { |
| 91 | &self.socket |
| 92 | } |
| 93 | |
| 94 | async fn connect(&self) -> anyhow::Result<UnixStream> { |
| 95 | UnixStream::connect(&self.socket).await.with_context(|| { |
| 96 | format!( |
| 97 | "connect to the container engine at {}", |
| 98 | self.socket.display() |
| 99 | ) |
| 100 | }) |
| 101 | } |
| 102 | |
| 103 | fn request( |
| 104 | &self, |
| 105 | method: &str, |
| 106 | path: &str, |
| 107 | body: Bytes, |
| 108 | ) -> anyhow::Result<Request<Full<Bytes>>> { |
| 109 | Request::builder() |
| 110 | .method(method) |
| 111 | .uri(format!("{API}{path}")) |
| 112 | .header(HOST, "docker") |
| 113 | .header(CONTENT_TYPE, "application/json") |
| 114 | .body(Full::new(body)) |
| 115 | .context("build Docker request") |
| 116 | } |
| 117 | |
| 118 | async fn send( |
| 119 | &self, |
| 120 | request: Request<Full<Bytes>>, |
| 121 | ) -> anyhow::Result<( |
| 122 | Response<Incoming>, |
| 123 | hyper::client::conn::http1::SendRequest<Full<Bytes>>, |
| 124 | )> { |
| 125 | let stream = self.connect().await?; |
| 126 | let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(stream)) |
| 127 | .await |
| 128 | .context("HTTP handshake with the container engine")?; |
| 129 | drive(connection); |
| 130 | let response = sender |
| 131 | .send_request(request) |
| 132 | .await |
| 133 | .context("send request to the container engine")?; |
| 134 | Ok((response, sender)) |
| 135 | } |
| 136 | |
| 137 | /// One call, whole body. A long-polled `wait` is fine here: the body |
| 138 | /// arrives only when the container exits. |
| 139 | pub async fn call( |
| 140 | &self, |
| 141 | method: &str, |
| 142 | path: &str, |
| 143 | body: Option<serde_json::Value>, |
| 144 | ) -> anyhow::Result<Reply> { |
| 145 | let body = match body { |
| 146 | Some(value) => Bytes::from(serde_json::to_vec(&value)?), |
| 147 | None => Bytes::new(), |
| 148 | }; |
| 149 | let (response, _sender) = self.send(self.request(method, path, body)?).await?; |
| 150 | let status = response.status(); |
| 151 | let body = response |
| 152 | .into_body() |
| 153 | .collect() |
| 154 | .await |
| 155 | .context("read Docker response")? |
| 156 | .to_bytes(); |
| 157 | Ok(Reply { status, body }) |
| 158 | } |
| 159 | |
| 160 | /// `call`, failing on any non-success status with the daemon's message. |
| 161 | pub async fn expect( |
| 162 | &self, |
| 163 | method: &str, |
| 164 | path: &str, |
| 165 | body: Option<serde_json::Value>, |
| 166 | what: &str, |
| 167 | ) -> anyhow::Result<Reply> { |
| 168 | let reply = self.call(method, path, body).await?; |
| 169 | if !reply.status.is_success() { |
| 170 | return Err(anyhow!( |
| 171 | "{what} failed with [{}] {}", |
| 172 | reply.status.as_u16(), |
| 173 | reply.message() |
| 174 | )); |
| 175 | } |
| 176 | Ok(reply) |
| 177 | } |
| 178 | |
| 179 | /// Upload a request body that is not JSON: `POST /images/load` takes a |
| 180 | /// tar. The whole body is in memory, which bounds an image at what a |
| 181 | /// node can hold; a streaming upload is the next step when an image |
| 182 | /// outgrows that. |
| 183 | pub async fn post_octets(&self, path: &str, body: Bytes, what: &str) -> anyhow::Result<Reply> { |
| 184 | let request = Request::builder() |
| 185 | .method("POST") |
| 186 | .uri(format!("{API}{path}")) |
| 187 | .header(HOST, "docker") |
| 188 | .header(CONTENT_TYPE, "application/x-tar") |
| 189 | .body(Full::new(body)) |
| 190 | .context("build Docker request")?; |
| 191 | let (response, _sender) = self.send(request).await?; |
| 192 | let status = response.status(); |
| 193 | let body = response |
| 194 | .into_body() |
| 195 | .collect() |
| 196 | .await |
| 197 | .context("read Docker response")? |
| 198 | .to_bytes(); |
| 199 | let reply = Reply { status, body }; |
| 200 | if !reply.status.is_success() { |
| 201 | return Err(anyhow!( |
| 202 | "{what} failed with [{}] {}", |
| 203 | reply.status.as_u16(), |
| 204 | reply.message() |
| 205 | )); |
| 206 | } |
| 207 | Ok(reply) |
| 208 | } |
| 209 | |
| 210 | /// POST a file as the request body, streamed rather than read into |
| 211 | /// memory (homeflare: `images/load` of a tar that can be gigabytes). |
| 212 | /// The connection is driven by the ambient runtime, as [`drive`] does. |
| 213 | #[allow(clippy::disallowed_methods)] |
| 214 | pub async fn post_file( |
| 215 | &self, |
| 216 | path: &str, |
| 217 | file: tokio::fs::File, |
| 218 | content_type: &str, |
| 219 | what: &str, |
| 220 | ) -> anyhow::Result<Reply> { |
| 221 | use futures_util::TryStreamExt; |
| 222 | use http_body_util::StreamBody; |
| 223 | use hyper::body::Frame; |
| 224 | let stream = tokio_util::io::ReaderStream::with_capacity(file, 1 << 20).map_ok(Frame::data); |
| 225 | let body = http_body_util::combinators::BoxBody::new(StreamBody::new(stream)); |
| 226 | let request = Request::builder() |
| 227 | .method("POST") |
| 228 | .uri(format!("{API}{path}")) |
| 229 | .header(HOST, "docker") |
| 230 | .header(CONTENT_TYPE, content_type) |
| 231 | .body(body) |
| 232 | .context("build Docker request")?; |
| 233 | let stream = self.connect().await?; |
| 234 | let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(stream)) |
| 235 | .await |
| 236 | .context("HTTP handshake with the container engine")?; |
| 237 | tokio::spawn(async move { |
| 238 | let _ = connection.await; |
| 239 | }); |
| 240 | let response = sender |
| 241 | .send_request(request) |
| 242 | .await |
| 243 | .context("send request to the container engine")?; |
| 244 | let status = response.status(); |
| 245 | let body = response |
| 246 | .into_body() |
| 247 | .collect() |
| 248 | .await |
| 249 | .context("read Docker response")? |
| 250 | .to_bytes(); |
| 251 | let reply = Reply { status, body }; |
| 252 | if !reply.status.is_success() { |
| 253 | return Err(anyhow!( |
| 254 | "{what} failed with [{}] {}", |
| 255 | reply.status.as_u16(), |
| 256 | reply.message() |
| 257 | )); |
| 258 | } |
| 259 | Ok(reply) |
| 260 | } |
| 261 | |
| 262 | /// `POST /exec/{id}/start` with `Upgrade: tcp`: the daemon answers 101 |
| 263 | /// and the connection becomes the process's stdin and its multiplexed |
| 264 | /// stdout/stderr. The returned stream is that connection. |
| 265 | pub async fn hijack( |
| 266 | &self, |
| 267 | path: &str, |
| 268 | body: serde_json::Value, |
| 269 | ) -> anyhow::Result<Box<dyn Stream>> { |
| 270 | let request = Request::builder() |
| 271 | .method("POST") |
| 272 | .uri(format!("{API}{path}")) |
| 273 | .header(HOST, "docker") |
| 274 | .header(CONTENT_TYPE, "application/json") |
| 275 | .header(CONNECTION, "Upgrade") |
| 276 | .header(UPGRADE, "tcp") |
| 277 | .body(Full::new(Bytes::from(serde_json::to_vec(&body)?))) |
| 278 | .context("build Docker request")?; |
| 279 | let (mut response, _sender) = self.send(request).await?; |
| 280 | if response.status() != StatusCode::SWITCHING_PROTOCOLS { |
| 281 | let status = response.status(); |
| 282 | let body = response |
| 283 | .into_body() |
| 284 | .collect() |
| 285 | .await |
| 286 | .map(|body| body.to_bytes()) |
| 287 | .unwrap_or_default(); |
| 288 | let reply = Reply { status, body }; |
| 289 | return Err(anyhow!( |
| 290 | "exec start failed with [{}] {}", |
| 291 | status.as_u16(), |
| 292 | reply.message() |
| 293 | )); |
| 294 | } |
| 295 | let upgraded = hyper::upgrade::on(&mut response) |
| 296 | .await |
| 297 | .context("upgrade the exec connection")?; |
| 298 | Ok(Box::new(TokioIo::new(upgraded))) |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | /// Poll the connection to completion. The daemon socket is outside the |
| 303 | /// execution boundary: no engine decision depends on when the daemon |
| 304 | /// answers, which is why the ambient runtime drives it, as `ws_client` |
| 305 | /// drives its handshakes. |
| 306 | #[allow(clippy::disallowed_methods)] |
| 307 | fn drive(connection: hyper::client::conn::http1::Connection<TokioIo<UnixStream>, Full<Bytes>>) { |
| 308 | tokio::spawn(async move { |
| 309 | let _ = connection.with_upgrades().await; |
| 310 | }); |
| 311 | } |
| 312 | |
| 313 | /// Parse one frame header of Docker's multiplexed stream: one byte of |
| 314 | /// stream id (1 stdout, 2 stderr), three reserved, four of big-endian |
| 315 | /// length. |
| 316 | pub fn frame_header(header: &[u8; 8]) -> (u8, usize) { |
| 317 | let length = u32::from_be_bytes([header[4], header[5], header[6], header[7]]) as usize; |
| 318 | (header[0], length) |
| 319 | } |