Skip to main content

krab_runtime/
docker.rs

1use crate::{
2    ContainerInfo, ContainerSpec, ExecHandle, ExecOpts, LogOpts, MANAGED_LABEL, Mount, NAME_PREFIX,
3    Runtime, is_managed, seccomp_supported,
4};
5use bytes::{Buf, Bytes, BytesMut};
6use http_body_util::{BodyExt, Full};
7use hyper::body::Incoming;
8use hyper::{Method, Request, Response, StatusCode};
9use hyper_util::rt::TokioIo;
10use serde::Deserialize;
11use serde_json::{Value, json};
12use std::collections::BTreeMap;
13use std::io;
14use tokio::io::{AsyncReadExt, AsyncWriteExt};
15use tokio::net::UnixStream;
16use tokio::sync::mpsc;
17
18#[derive(Clone)]
19pub struct Docker {
20    sock: String,
21}
22
23#[derive(Deserialize)]
24#[serde(rename_all = "PascalCase")]
25struct ListItem {
26    id: String,
27    #[serde(default)]
28    names: Vec<String>,
29    #[serde(default)]
30    image: String,
31    #[serde(default, rename = "ImageID")]
32    image_id: String,
33    #[serde(default)]
34    created: i64,
35    #[serde(default)]
36    ports: Vec<Port>,
37    #[serde(default)]
38    labels: Option<BTreeMap<String, String>>,
39    #[serde(default)]
40    state: String,
41    #[serde(default)]
42    network_settings: Option<NetSettings>,
43}
44
45#[derive(Deserialize)]
46#[serde(rename_all = "PascalCase")]
47struct Port {
48    #[serde(default)]
49    private_port: u16,
50    #[serde(default, rename = "Type")]
51    proto: String,
52}
53
54#[derive(Deserialize)]
55#[serde(rename_all = "PascalCase")]
56struct NetSettings {
57    #[serde(default)]
58    networks: BTreeMap<String, Net>,
59}
60
61#[derive(Deserialize)]
62#[serde(rename_all = "PascalCase")]
63struct Net {
64    #[serde(default, rename = "IPAddress")]
65    ip: String,
66}
67
68#[derive(Deserialize)]
69#[serde(rename_all = "PascalCase")]
70struct Inspect {
71    #[serde(default)]
72    id: String,
73    state: InspectState,
74    #[serde(default)]
75    restart_count: u64,
76    config: InspectConfig,
77    #[serde(default)]
78    name: String,
79    #[serde(default)]
80    image: String,
81    #[serde(default)]
82    network_settings: Option<NetSettings>,
83}
84
85#[derive(Deserialize)]
86#[serde(rename_all = "PascalCase")]
87struct InspectState {
88    #[serde(default)]
89    status: String,
90    #[serde(default)]
91    pid: i64,
92    #[serde(default)]
93    exit_code: i64,
94    #[serde(default, rename = "OOMKilled")]
95    oom_killed: bool,
96    #[serde(default)]
97    started_at: String,
98    #[serde(default)]
99    finished_at: String,
100}
101
102#[derive(Deserialize)]
103#[serde(rename_all = "PascalCase")]
104struct InspectConfig {
105    #[serde(default)]
106    tty: bool,
107    #[serde(default)]
108    image: String,
109    #[serde(default)]
110    labels: Option<BTreeMap<String, String>>,
111}
112
113impl Docker {
114    pub fn new(sock: impl Into<String>) -> Self {
115        Self { sock: sock.into() }
116    }
117
118    async fn request(&self, path: &str) -> io::Result<Response<Incoming>> {
119        self.call(Method::GET, path, None).await
120    }
121
122    async fn call(
123        &self,
124        method: Method,
125        path: &str,
126        body: Option<Value>,
127    ) -> io::Result<Response<Incoming>> {
128        let stream = UnixStream::connect(&self.sock).await?;
129        let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
130            .await
131            .map_err(io::Error::other)?;
132        tokio::spawn(async move {
133            let _ = conn.await;
134        });
135        let mut req = Request::builder()
136            .method(method)
137            .uri(path)
138            .header("Host", "docker");
139        let payload = match body {
140            Some(v) => {
141                req = req.header("Content-Type", "application/json");
142                Bytes::from(serde_json::to_vec(&v).map_err(io::Error::other)?)
143            }
144            None => Bytes::new(),
145        };
146        let req = req.body(Full::new(payload)).map_err(io::Error::other)?;
147        let resp = sender.send_request(req).await.map_err(io::Error::other)?;
148        let status = resp.status();
149        if status.is_success() || status == StatusCode::NOT_MODIFIED {
150            return Ok(resp);
151        }
152        let text = resp
153            .into_body()
154            .collect()
155            .await
156            .map(|b| b.to_bytes())
157            .unwrap_or_default();
158        let msg = serde_json::from_slice::<Value>(&text)
159            .ok()
160            .and_then(|v| v["message"].as_str().map(str::to_string))
161            .unwrap_or_else(|| String::from_utf8_lossy(&text).into_owned());
162        let kind = match status {
163            StatusCode::NOT_FOUND => io::ErrorKind::NotFound,
164            StatusCode::CONFLICT => io::ErrorKind::AlreadyExists,
165            _ => io::ErrorKind::Other,
166        };
167        Err(io::Error::new(
168            kind,
169            format!("docker {path} {status}: {}", msg.trim()),
170        ))
171    }
172
173    async fn call_bytes(
174        &self,
175        method: Method,
176        path: &str,
177        body: Option<Value>,
178    ) -> io::Result<Bytes> {
179        let resp = self.call(method, path, body).await?;
180        Ok(resp
181            .into_body()
182            .collect()
183            .await
184            .map_err(io::Error::other)?
185            .to_bytes())
186    }
187
188    async fn get_json(&self, path: &str) -> io::Result<Bytes> {
189        self.call_bytes(Method::GET, path, None).await
190    }
191
192    async fn hijack(&self, path: &str, body: Value) -> io::Result<(UnixStream, BytesMut)> {
193        let mut stream = UnixStream::connect(&self.sock).await?;
194        let payload = serde_json::to_vec(&body).map_err(io::Error::other)?;
195        let head = format!(
196            "POST {path} HTTP/1.1\r\nHost: docker\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n",
197            payload.len()
198        );
199        stream.write_all(head.as_bytes()).await?;
200        stream.write_all(&payload).await?;
201        stream.flush().await?;
202        let mut buf = BytesMut::new();
203        let split = loop {
204            if let Some(w) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
205                break w;
206            }
207            let mut tmp = [0u8; 1024];
208            let n = stream.read(&mut tmp).await?;
209            if n == 0 {
210                return Err(io::Error::other(
211                    "docker: connection closed while reading response",
212                ));
213            }
214            buf.extend_from_slice(&tmp[..n]);
215        };
216        let status = String::from_utf8_lossy(&buf[..split])
217            .lines()
218            .next()
219            .unwrap_or_default()
220            .to_string();
221        buf.advance(split + 4);
222        if !status.contains(" 200") && !status.contains(" 101") {
223            return Err(io::Error::other(format!("docker: {status}")));
224        }
225        Ok((stream, buf))
226    }
227
228    async fn ensure_managed(&self, id: &str) -> io::Result<()> {
229        let mut info = ContainerInfo {
230            id: id.to_string(),
231            ..Default::default()
232        };
233        self.inspect(&mut info).await?;
234        if is_managed(&info) {
235            Ok(())
236        } else {
237            Err(io::Error::new(
238                io::ErrorKind::PermissionDenied,
239                format!("container {id} is not managed by krab"),
240            ))
241        }
242    }
243
244    async fn managed_object(&self, path: &str, name: &str) -> io::Result<()> {
245        let body = self.get_json(path).await?;
246        let v: Value = serde_json::from_slice(&body).map_err(io::Error::other)?;
247        if name.starts_with("krab") && v["Labels"][MANAGED_LABEL].as_str() == Some("true") {
248            Ok(())
249        } else {
250            Err(io::Error::new(
251                io::ErrorKind::PermissionDenied,
252                format!("{name} is not managed by krab"),
253            ))
254        }
255    }
256}
257
258pub fn split_image(image: &str) -> (&str, &str) {
259    if let Some((repo, digest)) = image.split_once('@') {
260        return (repo, digest);
261    }
262    match image.rfind(':') {
263        Some(i) if !image[i..].contains('/') => (&image[..i], &image[i + 1..]),
264        _ => (image, "latest"),
265    }
266}
267
268fn enc(s: &str) -> String {
269    let mut out = String::with_capacity(s.len());
270    for b in s.bytes() {
271        if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) {
272            out.push(b as char);
273        } else {
274            out.push_str(&format!("%{b:02X}"));
275        }
276    }
277    out
278}
279
280const SUPPORTED_SECCOMP: &[&str] = &["RuntimeDefault"];
281
282fn create_body(spec: &ContainerSpec) -> Value {
283    let mut exposed = serde_json::Map::new();
284    let mut bindings = serde_json::Map::new();
285    for p in &spec.ports {
286        let key = format!("{}/{}", p.container_port, p.protocol.to_lowercase());
287        exposed.insert(key.clone(), json!({}));
288        if let Some(hp) = p.host_port {
289            bindings.insert(
290                key,
291                json!([{"HostIp": p.host_ip.clone().unwrap_or_default(), "HostPort": hp.to_string()}]),
292            );
293        }
294    }
295    let mut mounts = Vec::new();
296    let mut tmpfs = serde_json::Map::new();
297    for m in &spec.mounts {
298        match m {
299            Mount::Bind {
300                src,
301                dst,
302                read_only,
303            } => mounts.push(json!({
304                "Type": "bind",
305                "Source": src,
306                "Target": dst,
307                "ReadOnly": read_only,
308            })),
309            Mount::Volume {
310                name,
311                dst,
312                read_only,
313            } => mounts.push(json!({
314                "Type": "volume",
315                "Source": name,
316                "Target": dst,
317                "ReadOnly": read_only,
318                "VolumeOptions": {"Labels": {MANAGED_LABEL: "true"}}
319            })),
320            Mount::Tmpfs { dst } => {
321                tmpfs.insert(dst.clone(), json!(""));
322            }
323        }
324    }
325    let mut host = json!({
326        "RestartPolicy": {"Name": spec.restart.docker_name()},
327        "Mounts": mounts,
328        "Tmpfs": tmpfs,
329        "PortBindings": bindings,
330        "DnsSearch": spec.dns_search,
331        "DnsOptions": spec.dns_options,
332        "CapDrop": ["NET_RAW"],
333        "PidsLimit": 4096,
334        "ReadonlyRootfs": spec.read_only_root,
335    });
336    if !spec.allow_privilege_escalation {
337        host["SecurityOpt"] = json!(["no-new-privileges"]);
338    }
339    if let Some(m) = spec.memory_bytes {
340        host["Memory"] = json!(m);
341    }
342    if let Some(c) = spec.nano_cpus {
343        host["NanoCpus"] = json!(c);
344    }
345    let mut body = json!({
346        "Image": spec.image,
347        "Env": spec.env.iter().map(|e| e.replace(crate::POD_IP_TOKEN, "")).collect::<Vec<_>>(),
348        "Labels": spec.labels,
349        "ExposedPorts": exposed,
350        "Tty": spec.tty,
351        "OpenStdin": spec.stdin,
352        "HostConfig": host,
353    });
354    if !spec.command.is_empty() {
355        body["Entrypoint"] = json!(spec.command);
356    }
357    if !spec.args.is_empty() || !spec.command.is_empty() {
358        body["Cmd"] = json!(spec.args);
359    }
360    if let Some(w) = &spec.working_dir {
361        body["WorkingDir"] = json!(w);
362    }
363    if let Some(h) = &spec.hostname {
364        body["Hostname"] = json!(h);
365    }
366    if let Some(u) = &spec.user {
367        body["User"] = json!(u);
368    }
369    if let Some(net) = &spec.network {
370        body["HostConfig"]["NetworkMode"] = json!(net);
371        body["NetworkingConfig"] =
372            json!({"EndpointsConfig": {net.as_str(): {"Aliases": spec.aliases}}});
373    }
374    body
375}
376
377fn demux(buf: &mut BytesMut, out: &mut Vec<u8>, limit: usize) {
378    while buf.len() >= 8 {
379        let len = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;
380        if buf.len() < 8 + len {
381            break;
382        }
383        buf.advance(8);
384        let chunk = buf.split_to(len);
385        let room = limit.saturating_sub(out.len());
386        out.extend_from_slice(&chunk[..chunk.len().min(room)]);
387    }
388}
389
390impl Runtime for Docker {
391    fn name(&self) -> &str {
392        "docker"
393    }
394
395    async fn list(&self) -> io::Result<Vec<ContainerInfo>> {
396        let body = self.get_json("/containers/json?all=1").await?;
397        let items: Vec<ListItem> = serde_json::from_slice(&body).map_err(io::Error::other)?;
398        Ok(items
399            .into_iter()
400            .map(|i| {
401                let ip = i
402                    .network_settings
403                    .and_then(|n| {
404                        n.networks
405                            .into_values()
406                            .map(|n| n.ip)
407                            .find(|ip| !ip.is_empty())
408                    })
409                    .unwrap_or_default();
410                ContainerInfo {
411                    name: i
412                        .names
413                        .first()
414                        .map(|n| n.trim_start_matches('/').to_string())
415                        .unwrap_or_else(|| i.id[..12.min(i.id.len())].to_string()),
416                    id: i.id,
417                    image: i.image,
418                    image_id: i.image_id,
419                    state: i.state,
420                    created: i.created,
421                    labels: i.labels.unwrap_or_default(),
422                    ports: i
423                        .ports
424                        .into_iter()
425                        .filter(|p| p.private_port > 0)
426                        .map(|p| (p.private_port, p.proto))
427                        .collect(),
428                    ip,
429                    ..Default::default()
430                }
431            })
432            .collect())
433    }
434
435    async fn inspect(&self, info: &mut ContainerInfo) -> io::Result<()> {
436        let body = self
437            .get_json(&format!("/containers/{}/json", enc(&info.id)))
438            .await?;
439        let i: Inspect = serde_json::from_slice(&body).map_err(io::Error::other)?;
440        info.started_at = i.state.started_at;
441        info.finished_at = i.state.finished_at;
442        info.exit_code = i.state.exit_code;
443        info.oom_killed = i.state.oom_killed;
444        info.pid = i.state.pid;
445        info.restart_count = i.restart_count;
446        info.tty = i.config.tty;
447        if !i.id.is_empty() {
448            info.id = i.id;
449        }
450        if !i.state.status.is_empty() {
451            info.state = i.state.status;
452        }
453        if !i.name.is_empty() {
454            info.name = i.name.trim_start_matches('/').to_string();
455        }
456        if !i.image.is_empty() {
457            info.image_id = i.image;
458        }
459        if info.image.is_empty() {
460            info.image = i.config.image;
461        }
462        if info.labels.is_empty() {
463            info.labels = i.config.labels.unwrap_or_default();
464        }
465        if let Some(ip) = i.network_settings.and_then(|n| {
466            n.networks
467                .into_values()
468                .map(|n| n.ip)
469                .find(|ip| !ip.is_empty())
470        }) {
471            info.ip = ip;
472        }
473        Ok(())
474    }
475
476    async fn logs(
477        &self,
478        info: &ContainerInfo,
479        opts: &LogOpts,
480    ) -> io::Result<mpsc::Receiver<Bytes>> {
481        let mut path = format!("/containers/{}/logs?stdout=1&stderr=1", enc(&info.id));
482        if let Some(t) = opts.tail {
483            path.push_str(&format!("&tail={t}"));
484        }
485        if opts.follow {
486            path.push_str("&follow=1");
487        }
488        if opts.timestamps {
489            path.push_str("&timestamps=1");
490        }
491        if let Some(s) = opts.since_seconds {
492            let now = std::time::SystemTime::now()
493                .duration_since(std::time::UNIX_EPOCH)
494                .map(|d| d.as_secs())
495                .unwrap_or(0);
496            path.push_str(&format!("&since={}", now.saturating_sub(s)));
497        }
498        let resp = self.request(&path).await?;
499        let tty = info.tty;
500        let (tx, rx) = mpsc::channel(8);
501        tokio::spawn(async move {
502            let mut body = resp.into_body();
503            let mut buf = BytesMut::new();
504            while let Some(Ok(frame)) = body.frame().await {
505                let Ok(data) = frame.into_data() else {
506                    continue;
507                };
508                if tty {
509                    if tx.send(data).await.is_err() {
510                        return;
511                    }
512                    continue;
513                }
514                buf.extend_from_slice(&data);
515                while buf.len() >= 8 {
516                    let len = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;
517                    if buf.len() < 8 + len {
518                        break;
519                    }
520                    buf.advance(8);
521                    let chunk = buf.split_to(len).freeze();
522                    if tx.send(chunk).await.is_err() {
523                        return;
524                    }
525                }
526            }
527        });
528        Ok(rx)
529    }
530
531    async fn pull_image(&self, image: &str) -> io::Result<()> {
532        let (repo, tag) = split_image(image);
533        let path = format!("/images/create?fromImage={}&tag={}", enc(repo), enc(tag));
534        let resp = self.call(Method::POST, &path, None).await?;
535        let mut body = resp.into_body();
536        let mut buf = BytesMut::new();
537        let mut err = None;
538        while let Some(frame) = body.frame().await {
539            let Ok(data) = frame.map_err(io::Error::other)?.into_data() else {
540                continue;
541            };
542            buf.extend_from_slice(&data);
543            while let Some(i) = buf.iter().position(|b| *b == b'\n') {
544                let line = buf.split_to(i + 1);
545                if let Ok(v) = serde_json::from_slice::<Value>(&line)
546                    && let Some(e) = v["error"].as_str()
547                {
548                    err = Some(e.to_string());
549                }
550            }
551        }
552        match err {
553            Some(e) => Err(io::Error::other(format!("pull {image}: {e}"))),
554            None => Ok(()),
555        }
556    }
557
558    async fn create_container(&self, spec: &ContainerSpec) -> io::Result<String> {
559        if !spec.name.starts_with(NAME_PREFIX)
560            || spec.labels.get(MANAGED_LABEL).map(String::as_str) != Some("true")
561        {
562            return Err(io::Error::new(
563                io::ErrorKind::PermissionDenied,
564                "container spec is not krab-managed",
565            ));
566        }
567        seccomp_supported("docker", spec.seccomp.as_deref(), SUPPORTED_SECCOMP)?;
568        let path = format!("/containers/create?name={}", enc(&spec.name));
569        let body = self
570            .call_bytes(Method::POST, &path, Some(create_body(spec)))
571            .await?;
572        let v: Value = serde_json::from_slice(&body).map_err(io::Error::other)?;
573        v["Id"]
574            .as_str()
575            .map(str::to_string)
576            .ok_or_else(|| io::Error::other("docker create: no Id"))
577    }
578
579    async fn start(&self, id: &str) -> io::Result<()> {
580        self.ensure_managed(id).await?;
581        self.call(
582            Method::POST,
583            &format!("/containers/{}/start", enc(id)),
584            None,
585        )
586        .await
587        .map(|_| ())
588    }
589
590    async fn stop(&self, id: &str, timeout_secs: u64) -> io::Result<()> {
591        self.ensure_managed(id).await?;
592        self.call(
593            Method::POST,
594            &format!("/containers/{}/stop?t={timeout_secs}", enc(id)),
595            None,
596        )
597        .await
598        .map(|_| ())
599    }
600
601    async fn remove(&self, id: &str, force: bool) -> io::Result<()> {
602        self.ensure_managed(id).await?;
603        let f = if force { 1 } else { 0 };
604        self.call(
605            Method::DELETE,
606            &format!("/containers/{}?force={f}&v=1", enc(id)),
607            None,
608        )
609        .await
610        .map(|_| ())
611    }
612
613    async fn ensure_network(&self, name: &str) -> io::Result<()> {
614        match self.get_json(&format!("/networks/{}", enc(name))).await {
615            Ok(_) => Ok(()),
616            Err(e) if e.kind() == io::ErrorKind::NotFound => {
617                let body = json!({"Name": name, "Driver": "bridge", "CheckDuplicate": true, "Labels": {MANAGED_LABEL: "true"}});
618                match self
619                    .call(Method::POST, "/networks/create", Some(body))
620                    .await
621                {
622                    Ok(_) => Ok(()),
623                    Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
624                    Err(e) => Err(e),
625                }
626            }
627            Err(e) => Err(e),
628        }
629    }
630
631    async fn remove_network(&self, name: &str) -> io::Result<()> {
632        let path = format!("/networks/{}", enc(name));
633        self.managed_object(&path, name).await?;
634        self.call(Method::DELETE, &path, None).await.map(|_| ())
635    }
636
637    async fn connect_network(
638        &self,
639        container: &str,
640        network: &str,
641        aliases: &[String],
642    ) -> io::Result<()> {
643        self.ensure_managed(container).await?;
644        let body = json!({"Container": container, "EndpointConfig": {"Aliases": aliases}});
645        self.call(
646            Method::POST,
647            &format!("/networks/{}/connect", enc(network)),
648            Some(body),
649        )
650        .await
651        .map(|_| ())
652    }
653
654    async fn disconnect_network(&self, container: &str, network: &str) -> io::Result<()> {
655        self.ensure_managed(container).await?;
656        let body = json!({"Container": container, "Force": true});
657        self.call(
658            Method::POST,
659            &format!("/networks/{}/disconnect", enc(network)),
660            Some(body),
661        )
662        .await
663        .map(|_| ())
664    }
665
666    async fn remove_volume(&self, name: &str) -> io::Result<()> {
667        let path = format!("/volumes/{}", enc(name));
668        self.managed_object(&path, name).await?;
669        self.call(Method::DELETE, &path, None).await.map(|_| ())
670    }
671
672    async fn exec_run(&self, id: &str, cmd: &[String]) -> io::Result<(i64, Vec<u8>)> {
673        self.ensure_managed(id).await?;
674        let body = json!({"Cmd": cmd, "AttachStdout": true, "AttachStderr": true, "Tty": false});
675        let created = self
676            .call_bytes(
677                Method::POST,
678                &format!("/containers/{}/exec", enc(id)),
679                Some(body),
680            )
681            .await?;
682        let v: Value = serde_json::from_slice(&created).map_err(io::Error::other)?;
683        let eid = v["Id"]
684            .as_str()
685            .ok_or_else(|| io::Error::other("docker exec: no Id"))?
686            .to_string();
687        let resp = self
688            .call(
689                Method::POST,
690                &format!("/exec/{}/start", enc(&eid)),
691                Some(json!({"Detach": false, "Tty": false})),
692            )
693            .await?;
694        let mut body = resp.into_body();
695        let mut buf = BytesMut::new();
696        let mut out = Vec::new();
697        while let Some(Ok(frame)) = body.frame().await {
698            if let Ok(data) = frame.into_data() {
699                buf.extend_from_slice(&data);
700                demux(&mut buf, &mut out, 64 * 1024);
701            }
702        }
703        let info = self.get_json(&format!("/exec/{}/json", enc(&eid))).await?;
704        let v: Value = serde_json::from_slice(&info).map_err(io::Error::other)?;
705        Ok((v["ExitCode"].as_i64().unwrap_or(-1), out))
706    }
707
708    async fn exec_stream(&self, id: &str, opts: &ExecOpts) -> io::Result<ExecHandle> {
709        self.ensure_managed(id).await?;
710        let body = json!({
711            "Cmd": opts.cmd,
712            "AttachStdin": opts.stdin,
713            "AttachStdout": true,
714            "AttachStderr": !opts.tty,
715            "Tty": opts.tty,
716        });
717        let created = self
718            .call_bytes(
719                Method::POST,
720                &format!("/containers/{}/exec", enc(id)),
721                Some(body),
722            )
723            .await?;
724        let v: Value = serde_json::from_slice(&created).map_err(io::Error::other)?;
725        let eid = v["Id"]
726            .as_str()
727            .ok_or_else(|| io::Error::other("docker exec: no Id"))?
728            .to_string();
729        let (stream, head_buf) = self
730            .hijack(
731                &format!("/exec/{}/start", enc(&eid)),
732                json!({"Detach": false, "Tty": opts.tty}),
733            )
734            .await?;
735        let (r, w) = tokio::io::split(stream);
736        type Sink = Box<dyn tokio::io::AsyncWrite + Unpin + Send>;
737        let (stdin, hold): (Option<Sink>, Option<Sink>) = if opts.stdin {
738            (Some(Box::new(w)), None)
739        } else {
740            (None, Some(Box::new(w)))
741        };
742        let (otx, orx) = mpsc::channel::<Bytes>(16);
743        let (etx, erx) = mpsc::channel::<Bytes>(16);
744        let tty = opts.tty;
745        tokio::spawn(async move {
746            let mut r = r;
747            let mut buf = head_buf;
748            let mut eof = false;
749            loop {
750                loop {
751                    if tty {
752                        if buf.is_empty() {
753                            break;
754                        }
755                        if otx.send(buf.split().freeze()).await.is_err() {
756                            return;
757                        }
758                    } else if buf.len() >= 8 {
759                        let len = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;
760                        if buf.len() < 8 + len {
761                            break;
762                        }
763                        let stream_ty = buf[0];
764                        buf.advance(8);
765                        let chunk = buf.split_to(len).freeze();
766                        let tx = if stream_ty == 2 { &etx } else { &otx };
767                        if !chunk.is_empty() && tx.send(chunk).await.is_err() {
768                            return;
769                        }
770                    } else {
771                        break;
772                    }
773                }
774                if eof {
775                    break;
776                }
777                let mut tmp = [0u8; 8192];
778                match r.read(&mut tmp).await {
779                    Ok(0) => eof = true,
780                    Ok(n) => buf.extend_from_slice(&tmp[..n]),
781                    Err(_) => break,
782                }
783            }
784        });
785        Ok(ExecHandle {
786            exec_id: eid,
787            stdout: orx,
788            stderr: erx,
789            stdin,
790            hold,
791        })
792    }
793
794    async fn exec_resize(&self, exec_id: &str, width: u32, height: u32) -> io::Result<()> {
795        self.call(
796            Method::POST,
797            &format!("/exec/{}/resize?h={height}&w={width}", enc(exec_id)),
798            None,
799        )
800        .await
801        .map(|_| ())
802    }
803
804    async fn exec_exit_code(&self, exec_id: &str) -> io::Result<i64> {
805        let info = self
806            .get_json(&format!("/exec/{}/json", enc(exec_id)))
807            .await?;
808        let v: Value = serde_json::from_slice(&info).map_err(io::Error::other)?;
809        Ok(v["ExitCode"].as_i64().unwrap_or(-1))
810    }
811}
812
813#[cfg(test)]
814mod tests {
815    use super::*;
816
817    #[test]
818    fn image_split() {
819        assert_eq!(split_image("nginx:alpine"), ("nginx", "alpine"));
820        assert_eq!(split_image("nginx"), ("nginx", "latest"));
821        assert_eq!(split_image("reg:5000/a/b"), ("reg:5000/a/b", "latest"));
822        assert_eq!(split_image("reg:5000/a/b:1.2"), ("reg:5000/a/b", "1.2"));
823        assert_eq!(split_image("a@sha256:ff"), ("a", "sha256:ff"));
824    }
825
826    #[test]
827    fn ids_are_escaped_in_paths() {
828        assert_eq!(
829            enc("abc/archive?path=/etc&"),
830            "abc%2Farchive%3Fpath%3D%2Fetc%26"
831        );
832        assert_eq!(enc("krab_default_p_c"), "krab_default_p_c");
833    }
834
835    #[test]
836    fn create_body_maps_spec() {
837        let spec = ContainerSpec {
838            name: "krab_default_p_c".into(),
839            image: "nginx:alpine".into(),
840            command: vec!["sh".into()],
841            restart: crate::RestartPolicy::OnFailure,
842            memory_bytes: Some(1 << 20),
843            nano_cpus: Some(500_000_000),
844            ports: vec![crate::PortSpec {
845                container_port: 80,
846                protocol: "TCP".into(),
847                host_port: Some(8080),
848                host_ip: None,
849            }],
850            mounts: vec![
851                Mount::Bind {
852                    src: "/a".into(),
853                    dst: "/b".into(),
854                    read_only: true,
855                },
856                Mount::Tmpfs { dst: "/t".into() },
857            ],
858            network: Some("krab".into()),
859            aliases: vec!["web".into()],
860            ..Default::default()
861        };
862        let b = create_body(&spec);
863        assert_eq!(b["HostConfig"]["RestartPolicy"]["Name"], "on-failure");
864        assert_eq!(b["HostConfig"]["Memory"], 1 << 20);
865        assert_eq!(b["HostConfig"]["NanoCpus"], 500_000_000);
866        assert_eq!(
867            b["HostConfig"]["Mounts"][0],
868            json!({"Type": "bind", "Source": "/a", "Target": "/b", "ReadOnly": true})
869        );
870        assert_eq!(b["HostConfig"]["SecurityOpt"][0], "no-new-privileges");
871        assert_eq!(b["HostConfig"]["CapDrop"][0], "NET_RAW");
872        assert_eq!(
873            b["HostConfig"]["PortBindings"]["80/tcp"][0]["HostPort"],
874            "8080"
875        );
876        assert_eq!(b["Cmd"], json!([]));
877        assert_eq!(
878            b["NetworkingConfig"]["EndpointsConfig"]["krab"]["Aliases"][0],
879            "web"
880        );
881    }
882
883    #[test]
884    fn seccomp_modes_checked() {
885        for t in [None, Some("RuntimeDefault")] {
886            seccomp_supported("docker", t, SUPPORTED_SECCOMP).unwrap();
887        }
888        for t in [Some("Localhost"), Some("Unconfined"), Some("Weird")] {
889            assert_eq!(
890                seccomp_supported("docker", t, SUPPORTED_SECCOMP)
891                    .unwrap_err()
892                    .kind(),
893                io::ErrorKind::InvalidInput
894            );
895        }
896    }
897
898    #[test]
899    fn runtime_default_keeps_docker_default_profile() {
900        let spec = ContainerSpec {
901            name: "krab_default_p_c".into(),
902            image: "nginx:alpine".into(),
903            seccomp: Some("RuntimeDefault".into()),
904            ..Default::default()
905        };
906        assert!(
907            !create_body(&spec)
908                .to_string()
909                .to_lowercase()
910                .contains("seccomp")
911        );
912    }
913}