1use std::path::{Path, PathBuf};
31use std::time::Duration;
32
33use bollard::Docker;
34
35use crate::backend::container::ContainerManager;
36
37const PING_TIMEOUT: Duration = Duration::from_secs(2);
39const API_TIMEOUT_SECS: u64 = 120;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Kind {
45 Docker,
46 RootlessDocker,
47 DockerDesktop,
48 Podman,
49 RootlessPodman,
50 Colima,
51 OrbStack,
52 RancherDesktop,
53 Configured,
55}
56
57impl Kind {
58 pub fn name(self) -> &'static str {
59 match self {
60 Kind::Docker => "Docker",
61 Kind::RootlessDocker => "rootless Docker",
62 Kind::DockerDesktop => "Docker Desktop",
63 Kind::Podman => "Podman",
64 Kind::RootlessPodman => "rootless Podman",
65 Kind::Colima => "Colima",
66 Kind::OrbStack => "OrbStack",
67 Kind::RancherDesktop => "Rancher Desktop",
68 Kind::Configured => "the runtime in DOCKER_HOST",
69 }
70 }
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum Endpoint {
76 Unix(PathBuf),
77 Tcp { host: String, tls: bool },
79 Pipe(String),
81}
82
83impl std::fmt::Display for Endpoint {
84 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85 match self {
86 Endpoint::Unix(p) => write!(f, "unix://{}", p.display()),
87 Endpoint::Tcp { host, tls: true } => write!(f, "tcp://{host} (TLS)"),
88 Endpoint::Tcp { host, tls: false } => write!(f, "tcp://{host}"),
89 Endpoint::Pipe(p) => write!(f, "npipe://{p}"),
90 }
91 }
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum Os {
96 Linux,
97 MacOs,
98 Windows,
99}
100
101#[derive(Debug, Clone)]
103pub struct Env {
104 pub docker_host: Option<String>,
106 pub tls_verify: bool,
108 pub xdg_runtime_dir: Option<PathBuf>,
109 pub home: Option<PathBuf>,
110 pub cert_dir: Option<PathBuf>,
113 pub os: Os,
114 pub uid: Option<u32>,
116 pub root: PathBuf,
118 pub ping_timeout: Duration,
119}
120
121impl Env {
122 pub fn from_process() -> Self {
123 let var = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty());
124 Self {
125 docker_host: var("DOCKER_HOST").map(|v| v.to_string_lossy().trim().to_string()).filter(|v| !v.is_empty()),
126 tls_verify: var("DOCKER_TLS_VERIFY").is_some(),
127 xdg_runtime_dir: var("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|p| p.is_absolute()),
128 home: dirs::home_dir(),
129 cert_dir: var("DOCKER_CERT_PATH")
130 .or_else(|| var("DOCKER_CONFIG"))
131 .map(PathBuf::from)
132 .or_else(|| dirs::home_dir().map(|h| h.join(".docker"))),
133 os: if cfg!(windows) {
134 Os::Windows
135 } else if cfg!(target_os = "macos") {
136 Os::MacOs
137 } else {
138 Os::Linux
139 },
140 #[cfg(unix)]
141 uid: Some(unsafe { libc::geteuid() }),
142 #[cfg(not(unix))]
143 uid: None,
144 root: PathBuf::from("/"),
145 ping_timeout: PING_TIMEOUT,
146 }
147 }
148}
149
150#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct Candidate {
153 pub kind: Kind,
154 pub endpoint: Endpoint,
155 pub user_owned: bool,
157}
158
159pub fn candidates(env: &Env) -> Result<Vec<Candidate>, String> {
161 if let Some(host) = &env.docker_host {
162 return configured(host, env.tls_verify).map(|c| vec![c]);
163 }
164 let unix = |kind, p: PathBuf, user_owned| Candidate { kind, endpoint: Endpoint::Unix(p), user_owned };
165 let system_docker = unix(Kind::Docker, env.root.join("var/run/docker.sock"), false);
166 let mut out = Vec::new();
167 match env.os {
168 Os::Windows => out.push(Candidate {
169 kind: Kind::Docker,
170 endpoint: Endpoint::Pipe("//./pipe/docker_engine".to_string()),
171 user_owned: false,
172 }),
173 Os::Linux => {
174 if let Some(xdg) = &env.xdg_runtime_dir {
175 out.push(unix(Kind::RootlessDocker, xdg.join("docker.sock"), true));
176 out.push(unix(Kind::RootlessPodman, xdg.join("podman/podman.sock"), true));
177 }
178 if let Some(home) = &env.home {
179 out.push(unix(Kind::DockerDesktop, home.join(".docker/desktop/docker.sock"), true));
181 out.push(unix(Kind::DockerDesktop, home.join(".docker/run/docker.sock"), true));
182 }
183 out.push(system_docker);
184 out.push(unix(Kind::Podman, env.root.join("run/podman/podman.sock"), false));
185 }
186 Os::MacOs => {
187 if let Some(home) = &env.home {
188 out.push(unix(Kind::DockerDesktop, home.join(".docker/run/docker.sock"), true));
189 out.push(unix(Kind::OrbStack, home.join(".orbstack/run/docker.sock"), true));
190 out.push(unix(Kind::Colima, home.join(".colima/default/docker.sock"), true));
191 out.push(unix(Kind::RancherDesktop, home.join(".rd/docker.sock"), true));
192 }
193 out.push(system_docker);
194 }
195 }
196 Ok(out)
197}
198
199fn configured(host: &str, tls_verify: bool) -> Result<Candidate, String> {
201 let (scheme, rest) = host.split_once("://").ok_or_else(|| {
202 format!("DOCKER_HOST is \"{host}\", which is not an address (expected unix://, tcp://, https:// or npipe://)")
203 })?;
204 let scheme = scheme.to_ascii_lowercase();
205 if matches!(scheme.as_str(), "tcp" | "http" | "https") && host_of(rest.trim_end_matches('/')).is_none() {
206 return Err(format!(
207 "DOCKER_HOST is {host}, which is not a plain host and port (no user name, path or query), as in tcp://localhost:2375"
208 ));
209 }
210 let endpoint = match scheme.as_str() {
211 "unix" => Endpoint::Unix(PathBuf::from(rest)),
212 "tcp" | "http" => {
213 let host = rest.trim_end_matches('/').to_string();
214 if !tls_verify && !is_loopback(&host) {
217 return Err(format!(
218 "DOCKER_HOST is {scheme}://{host}, an unencrypted connection to another computer, \
219 and a container agent's daemon is given the account's credentials. \
220 Use https:// or set DOCKER_TLS_VERIFY and DOCKER_CERT_PATH, or point DOCKER_HOST at localhost"
221 ));
222 }
223 Endpoint::Tcp { host, tls: tls_verify }
224 }
225 "https" => Endpoint::Tcp { host: rest.trim_end_matches('/').to_string(), tls: true },
226 "npipe" => Endpoint::Pipe(rest.to_string()),
227 other => {
228 return Err(format!(
229 "DOCKER_HOST uses {other}://, which AgentMux can't connect through. \
230 Use a unix:// socket, tcp:// (with DOCKER_TLS_VERIFY and DOCKER_CERT_PATH for TLS) or https://"
231 ))
232 }
233 };
234 Ok(Candidate { kind: Kind::Configured, endpoint, user_owned: false })
235}
236
237fn host_of(host_port: &str) -> Option<&str> {
241 if host_port.is_empty() || host_port.contains(|c: char| c.is_whitespace() || matches!(c, '@' | '/' | '?' | '#' | '\\')) {
242 return None;
243 }
244 let port_ok = |p: &str| !p.is_empty() && p.len() <= 5 && p.bytes().all(|b| b.is_ascii_digit());
245 if let Some(rest) = host_port.strip_prefix('[') {
246 let (host, after) = rest.split_once(']')?;
247 let ok = after.is_empty() || after.strip_prefix(':').is_some_and(port_ok);
248 return (ok && !host.is_empty()).then_some(host);
249 }
250 match host_port.matches(':').count() {
251 0 => Some(host_port),
252 1 => {
253 let (host, port) = host_port.split_once(':')?;
254 (!host.is_empty() && port_ok(port)).then_some(host)
255 }
256 _ => Some(host_port),
258 }
259}
260
261fn is_loopback(host_port: &str) -> bool {
263 let Some(host) = host_of(host_port) else { return false };
264 host.eq_ignore_ascii_case("localhost")
265 || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.to_canonical().is_loopback())
266}
267
268#[derive(Debug, Clone, PartialEq, Eq)]
270pub struct Tried {
271 pub kind: Kind,
272 pub endpoint: Endpoint,
273 pub why: String,
274}
275
276#[derive(Debug, Clone, PartialEq, Eq, Default)]
278pub struct Missing {
279 pub tried: Vec<Tried>,
280 pub unusable: Option<String>,
282}
283
284impl Missing {
285 pub fn message(&self) -> String {
287 if let Some(why) = &self.unusable {
288 return format!("Container agents need Docker or Podman: {why}.");
289 }
290 let broken: Vec<String> = self
291 .tried
292 .iter()
293 .filter(|t| !t.why.starts_with(ABSENT))
294 .map(|t| format!("{} at {} ({})", t.kind.name(), t.endpoint, t.why))
295 .collect();
296 let absent: Vec<String> =
297 self.tried.iter().filter(|t| t.why.starts_with(ABSENT)).map(|t| t.endpoint.to_string()).collect();
298 let mut out = String::from("Container agents need Docker or Podman, and none answered.");
299 if !broken.is_empty() {
300 out.push_str(&format!(" Found but not working: {}.", broken.join("; ")));
301 }
302 if !absent.is_empty() {
303 out.push_str(&format!(" Nothing at: {}.", absent.join(", ")));
304 }
305 let any = |needle: &str| self.tried.iter().any(|t| t.why.contains(needle));
306 if self.tried.iter().any(|t| t.kind == Kind::Configured) {
307 out.push_str(" DOCKER_HOST is set, so no other place was tried; unset it to look for Docker or Podman in the usual places.");
309 return out;
310 }
311 if any("permission denied") {
312 out.push_str(" Add your user to the docker group, or use rootless Docker or Podman.");
313 } else if self.tried.iter().any(|t| matches!(t.kind, Kind::RootlessPodman) && t.why.starts_with(ABSENT)) {
314 out.push_str(" For Podman, `systemctl --user enable --now podman.socket` starts its Docker-compatible socket.");
315 } else {
316 out.push_str(" Start Docker Desktop (or your runtime) and send your message again.");
317 }
318 out.push_str(" To use another socket, set DOCKER_HOST.");
319 out
320 }
321}
322
323const ABSENT: &str = "not found";
325
326pub struct Connected {
328 pub docker: Docker,
329 pub kind: Kind,
330 pub endpoint: Endpoint,
331}
332
333impl Connected {
334 pub fn label(&self) -> String {
336 format!("{} at {}", self.kind.name(), self.endpoint)
337 }
338}
339
340static IN_USE: std::sync::Mutex<Option<Endpoint>> = std::sync::Mutex::new(None);
342
343pub fn docker_host_in_use() -> Option<String> {
346 docker_host_of(IN_USE.lock().unwrap_or_else(|e| e.into_inner()).as_ref()?)
347}
348
349fn docker_host_of(endpoint: &Endpoint) -> Option<String> {
350 match endpoint {
351 Endpoint::Unix(path) => Some(format!("unix://{}", path.display())),
352 Endpoint::Tcp { host, tls: false } => Some(format!("tcp://{host}")),
353 _ => None,
354 }
355}
356
357pub async fn connect(env: &Env) -> Result<Connected, Missing> {
359 let places = candidates(env).map_err(|why| Missing { tried: Vec::new(), unusable: Some(why) })?;
360 let mut tried = Vec::new();
361 for c in places {
362 match try_candidate(&c, env).await {
363 Ok(docker) => {
364 *IN_USE.lock().unwrap_or_else(|e| e.into_inner()) = Some(c.endpoint.clone());
365 return Ok(Connected { docker, kind: c.kind, endpoint: c.endpoint });
366 }
367 Err(why) => tried.push(Tried { kind: c.kind, endpoint: c.endpoint, why }),
368 }
369 }
370 Err(Missing { tried, unusable: None })
371}
372
373async fn try_candidate(c: &Candidate, env: &Env) -> Result<Docker, String> {
375 match &c.endpoint {
376 Endpoint::Unix(path) => {
377 check_socket(path, c.user_owned, env.uid)?;
378 ping_unix(path, env.ping_timeout).await?;
379 #[cfg(unix)]
380 return Docker::connect_with_unix(&path.to_string_lossy(), API_TIMEOUT_SECS, bollard::API_DEFAULT_VERSION)
381 .map_err(|e| e.to_string());
382 #[cfg(not(unix))]
384 Err("unix sockets are not available on this system".to_string())
385 }
386 Endpoint::Tcp { host, tls } => {
389 let addr = format!("tcp://{host}");
390 let docker = if *tls {
391 let dir = env.cert_dir.as_deref().ok_or_else(|| {
392 "TLS needs key.pem, cert.pem and ca.pem, and neither DOCKER_CERT_PATH nor ~/.docker is known".to_string()
393 })?;
394 Docker::connect_with_ssl(
395 &addr,
396 &dir.join("key.pem"),
397 &dir.join("cert.pem"),
398 &dir.join("ca.pem"),
399 API_TIMEOUT_SECS,
400 bollard::API_DEFAULT_VERSION,
401 )
402 } else {
403 Docker::connect_with_http(&addr, API_TIMEOUT_SECS, bollard::API_DEFAULT_VERSION)
404 }
405 .map_err(|e| connection_error(&e.to_string()))?;
406 ping_docker(docker, env.ping_timeout).await
407 }
408 Endpoint::Pipe(pipe) => {
409 #[cfg(windows)]
410 {
411 let docker = Docker::connect_with_named_pipe(pipe, API_TIMEOUT_SECS, bollard::API_DEFAULT_VERSION)
412 .map_err(|e| connection_error(&e.to_string()))?;
413 return ping_docker(docker, env.ping_timeout).await;
414 }
415 #[cfg(not(windows))]
416 {
417 let _ = pipe;
418 Err("named pipes are only on Windows".to_string())
419 }
420 }
421 }
422}
423
424async fn ping_docker(docker: Docker, timeout: Duration) -> Result<Docker, String> {
426 match tokio::time::timeout(timeout, docker.ping()).await {
427 Ok(Ok(_)) => Ok(docker),
428 Ok(Err(e)) => Err(connection_error(&e.to_string())),
429 Err(_) => Err(format!("no answer within {}s", timeout.as_secs_f32().ceil())),
430 }
431}
432
433fn connection_error(text: &str) -> String {
435 if text.contains("(Connect)") || text.to_ascii_lowercase().contains("connection refused") {
436 "could not connect: is the daemon running and reachable?".to_string()
437 } else {
438 text.to_string()
439 }
440}
441
442#[cfg(unix)]
444fn check_socket(path: &Path, user_owned: bool, uid: Option<u32>) -> Result<(), String> {
445 use std::os::unix::fs::{FileTypeExt, MetadataExt};
446 let meta = std::fs::metadata(path).map_err(|e| match e.kind() {
447 std::io::ErrorKind::NotFound => ABSENT.to_string(),
448 std::io::ErrorKind::PermissionDenied => "permission denied".to_string(),
449 _ => e.to_string(),
450 })?;
451 if !meta.file_type().is_socket() {
452 return Err("not a socket".to_string());
453 }
454 if let (true, Some(uid)) = (user_owned, uid) {
455 if meta.uid() != uid {
456 return Err(format!("owned by another user (uid {}), not you", meta.uid()));
457 }
458 }
459 Ok(())
460}
461
462#[cfg(not(unix))]
463fn check_socket(_path: &Path, _user_owned: bool, _uid: Option<u32>) -> Result<(), String> {
464 Err("unix sockets are not available on this system".to_string())
465}
466
467#[cfg(unix)]
469async fn ping_unix(path: &Path, timeout: Duration) -> Result<(), String> {
470 use tokio::io::{AsyncReadExt, AsyncWriteExt};
471 let exchange = async {
472 let mut s = tokio::net::UnixStream::connect(path).await.map_err(connect_error)?;
473 s.write_all(b"GET /_ping HTTP/1.1\r\nHost: docker\r\nConnection: close\r\n\r\n")
474 .await
475 .map_err(|e| e.to_string())?;
476 let mut head = Vec::new();
478 let mut chunk = [0u8; 256];
479 while !head.windows(2).any(|w| w == b"\r\n") && head.len() < 1024 {
480 let n = s.read(&mut chunk).await.map_err(|e| e.to_string())?;
481 if n == 0 {
482 break;
483 }
484 head.extend_from_slice(&chunk[..n]);
485 }
486 status_of(&head)
487 };
488 match tokio::time::timeout(timeout, exchange).await {
489 Ok(r) => r,
490 Err(_) => Err(format!("accepted the connection but gave no answer within {}s", timeout.as_secs_f32().ceil())),
491 }
492}
493
494#[cfg(not(unix))]
495async fn ping_unix(_path: &Path, _timeout: Duration) -> Result<(), String> {
496 Err("unix sockets are not available on this system".to_string())
497}
498
499#[cfg(unix)]
500fn connect_error(e: std::io::Error) -> String {
501 match e.kind() {
502 std::io::ErrorKind::PermissionDenied => "permission denied".to_string(),
503 std::io::ErrorKind::ConnectionRefused => "connection refused: nothing is listening, so start the service".to_string(),
504 std::io::ErrorKind::NotFound => ABSENT.to_string(),
505 _ => e.to_string(),
506 }
507}
508
509#[cfg(unix)]
511fn status_of(head: &[u8]) -> Result<(), String> {
512 let line = String::from_utf8_lossy(head);
513 let line = line.lines().next().unwrap_or("").trim();
514 let mut parts = line.split_whitespace();
515 match (parts.next(), parts.next()) {
516 (Some(v), Some("200")) if v.starts_with("HTTP/1.") => Ok(()),
517 (Some(v), Some(code)) if v.starts_with("HTTP/") => Err(format!("answered HTTP {code}, not a container runtime's ping")),
518 _ => Err("did not answer like a container runtime".to_string()),
519 }
520}
521
522enum RuntimeSlot {
524 #[cfg(any(test, feature = "test-support"))]
527 Disabled,
528 Empty,
532 Connected(ContainerManager),
533}
534
535const RETRY_DETECT_AFTER: std::time::Duration = std::time::Duration::from_secs(3);
537
538pub struct ContainerRuntimeHandle {
550 slot: tokio::sync::RwLock<RuntimeSlot>,
551 last_miss: std::sync::Mutex<Option<(std::time::Instant, String)>>,
554 dev_proxy: std::sync::RwLock<Option<crate::backend::dev_proxy::DevProxyRegistry>>,
563}
564
565impl ContainerRuntimeHandle {
566 pub fn connect_at_startup() -> Self {
571 Self {
572 slot: tokio::sync::RwLock::new(RuntimeSlot::Empty),
573 last_miss: std::sync::Mutex::new(None),
574 dev_proxy: std::sync::RwLock::new(None),
575 }
576 }
577
578 #[cfg(any(test, feature = "test-support"))]
582 pub fn disabled() -> Self {
583 Self {
584 slot: tokio::sync::RwLock::new(RuntimeSlot::Disabled),
585 last_miss: std::sync::Mutex::new(None),
586 dev_proxy: std::sync::RwLock::new(None),
587 }
588 }
589
590 #[cfg(test)]
592 fn connected_for_test(mgr: ContainerManager) -> Self {
593 Self {
594 slot: tokio::sync::RwLock::new(RuntimeSlot::Connected(mgr)),
595 last_miss: std::sync::Mutex::new(None),
596 dev_proxy: std::sync::RwLock::new(None),
597 }
598 }
599
600 pub fn set_dev_proxy_registry(&self, registry: crate::backend::dev_proxy::DevProxyRegistry) {
606 if let Ok(mut slot) = self.dev_proxy.write() {
607 *slot = Some(registry.clone());
608 }
609 if let Ok(slot) = self.slot.try_read() {
612 if let RuntimeSlot::Connected(mgr) = &*slot {
613 mgr.attach_dev_proxy_registry(registry);
614 }
615 }
616 }
617
618 pub async fn get(&self) -> Option<ContainerManager> {
624 {
625 let slot = self.slot.read().await;
626 match &*slot {
627 RuntimeSlot::Connected(mgr) => return Some(mgr.clone()),
628 #[cfg(any(test, feature = "test-support"))]
629 RuntimeSlot::Disabled => return None,
630 RuntimeSlot::Empty => {}
631 }
632 }
633 let mut slot = self.slot.write().await;
634 if let RuntimeSlot::Connected(mgr) = &*slot {
637 return Some(mgr.clone());
638 }
639 #[cfg(any(test, feature = "test-support"))]
640 if matches!(&*slot, RuntimeSlot::Disabled) {
641 return None;
642 }
643 if let Some((at, _)) = &*self.last_miss.lock().unwrap() {
644 if at.elapsed() < RETRY_DETECT_AFTER {
645 return None;
646 }
647 }
648 match ContainerManager::connect_detected().await {
649 Ok(mgr) => {
650 if let Ok(guard) = self.dev_proxy.read() {
655 if let Some(registry) = guard.as_ref() {
656 mgr.attach_dev_proxy_registry(registry.clone());
657 }
658 }
659 *self.last_miss.lock().unwrap() = None;
660 *slot = RuntimeSlot::Connected(mgr.clone());
661 Some(mgr)
662 }
663 Err(e) => {
664 *self.last_miss.lock().unwrap() = Some((std::time::Instant::now(), e.user_message()));
665 None
666 }
667 }
668 }
669
670 pub async fn get_or_explain(&self) -> Result<crate::backend::container::ContainerManager, String> {
673 match self.get().await {
674 Some(mgr) => Ok(mgr),
675 None => Err(self
676 .missing_message()
677 .unwrap_or_else(|| "Docker not available on this host; cannot start container agent".to_string())),
678 }
679 }
680
681 pub async fn runtime_label(&self) -> Option<String> {
683 match &*self.slot.read().await {
684 RuntimeSlot::Connected(mgr) => mgr.runtime_label().map(str::to_string),
685 _ => None,
686 }
687 }
688
689 pub fn missing_message(&self) -> Option<String> {
692 self.last_miss.lock().unwrap().as_ref().map(|(_, m)| m.clone())
693 }
694
695 pub async fn is_available(&self) -> bool {
700 match self.get().await {
701 Some(mgr) => {
702 if mgr.check_available().await.is_ok() {
703 return true;
704 }
705 let mut slot = self.slot.write().await;
708 if matches!(&*slot, RuntimeSlot::Connected(_)) {
709 *slot = RuntimeSlot::Empty;
710 let said = match mgr.runtime_label() {
712 Some(label) => format!("Container agents need Docker or Podman, and {label} stopped answering. Start it again, or set DOCKER_HOST to another socket."),
713 None => "Container agents need Docker or Podman, and the runtime stopped answering. Start it again, or set DOCKER_HOST to another socket.".to_string(),
714 };
715 let at = std::time::Instant::now().checked_sub(RETRY_DETECT_AFTER).unwrap_or_else(std::time::Instant::now);
716 *self.last_miss.lock().unwrap() = Some((at, said));
717 }
718 false
719 }
720 None => false,
721 }
722 }
723}
724
725#[cfg(all(test, unix))]
726mod tests {
727 use super::*;
728 use tokio::io::{AsyncReadExt, AsyncWriteExt};
729 use tokio::net::UnixListener;
730
731 fn env(dir: &Path, os: Os) -> Env {
732 Env {
733 docker_host: None,
734 tls_verify: false,
735 xdg_runtime_dir: Some(dir.join("run-user")),
736 home: Some(dir.join("home")),
737 cert_dir: None,
738 os,
739 uid: Some(unsafe { libc::geteuid() }),
740 root: dir.join("root"),
741 ping_timeout: Duration::from_millis(300),
742 }
743 }
744
745 fn at(dir: &Path, rel: &str) -> PathBuf {
746 let p = dir.join(rel);
747 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
748 p
749 }
750
751 fn serve(path: PathBuf, status: &'static str) -> tokio::task::JoinHandle<()> {
753 let listener = UnixListener::bind(path).unwrap();
754 tokio::spawn(async move {
755 while let Ok((mut s, _)) = listener.accept().await {
756 tokio::spawn(async move {
757 let mut buf = [0u8; 512];
758 let _ = s.read(&mut buf).await;
759 let _ = s.write_all(format!("HTTP/1.1 {status}\r\nContent-Length: 2\r\n\r\nOK").as_bytes()).await;
760 });
761 }
762 })
763 }
764
765 fn stale(path: PathBuf) {
767 drop(std::os::unix::net::UnixListener::bind(path).unwrap());
768 }
769
770 fn kinds(env: &Env) -> Vec<Kind> {
771 candidates(env).unwrap().into_iter().map(|c| c.kind).collect()
772 }
773
774 #[test]
775 fn linux_tries_rootless_first_then_desktop_then_the_system_sockets() {
776 let e = env(Path::new("/t"), Os::Linux);
777 assert_eq!(
778 candidates(&e).unwrap().into_iter().map(|c| c.endpoint.to_string()).collect::<Vec<_>>(),
779 [
780 "unix:///t/run-user/docker.sock",
781 "unix:///t/run-user/podman/podman.sock",
782 "unix:///t/home/.docker/desktop/docker.sock",
783 "unix:///t/home/.docker/run/docker.sock",
784 "unix:///t/root/var/run/docker.sock",
785 "unix:///t/root/run/podman/podman.sock",
786 ]
787 );
788 assert_eq!(
789 kinds(&e),
790 [
791 Kind::RootlessDocker,
792 Kind::RootlessPodman,
793 Kind::DockerDesktop,
794 Kind::DockerDesktop,
795 Kind::Docker,
796 Kind::Podman
797 ]
798 );
799 let e = Env { xdg_runtime_dir: None, ..e };
801 assert_eq!(kinds(&e), [Kind::DockerDesktop, Kind::DockerDesktop, Kind::Docker, Kind::Podman]);
802 }
803
804 #[test]
805 fn macos_tries_desktop_orbstack_colima_and_rancher() {
806 let e = env(Path::new("/t"), Os::MacOs);
807 assert_eq!(
808 kinds(&e),
809 [Kind::DockerDesktop, Kind::OrbStack, Kind::Colima, Kind::RancherDesktop, Kind::Docker]
810 );
811 assert!(candidates(&e).unwrap()[2].endpoint.to_string().ends_with("/.colima/default/docker.sock"));
812 }
813
814 #[test]
815 fn windows_keeps_the_named_pipe() {
816 let c = candidates(&env(Path::new("/t"), Os::Windows)).unwrap();
817 assert_eq!(c.len(), 1);
818 assert_eq!(c[0].endpoint, Endpoint::Pipe("//./pipe/docker_engine".to_string()));
819 }
820
821 #[test]
824 fn an_unencrypted_docker_host_is_for_this_computer_only() {
825 let with = |h: &str, tls: bool| Env {
826 docker_host: Some(h.to_string()),
827 tls_verify: tls,
828 ..env(Path::new("/t"), Os::Linux)
829 };
830 for local in ["tcp://localhost:2375", "http://LOCALHOST:2375", "tcp://127.0.0.1:2375", "tcp://127.8.9.10", "tcp://[::1]:2375", "tcp://[::ffff:127.0.0.1]:2375", "tcp://::1"] {
831 assert!(candidates(&with(local, false)).is_ok(), "{local} is this computer");
832 }
833 for remote in ["tcp://203.0.113.5:2375", "http://dock.example:2375", "tcp://198.51.100.2", "tcp://[2001:db8::1]:2375", "tcp://localhost.example.com:2375", "tcp://127.0.0.1.example.com:2375"] {
834 let why = candidates(&with(remote, false)).unwrap_err();
835 assert!(why.contains("unencrypted") && why.contains("https://") && why.contains("DOCKER_TLS_VERIFY"), "{remote}: {why}");
836 assert!(!why.contains(" ") && !why.contains('\n'), "the sentence is one line, single-spaced: {why}");
837 }
838 for tricky in [
841 "tcp://[::1]@203.0.113.5:2375",
842 "tcp://127.0.0.1@203.0.113.5:2375",
843 "tcp://localhost@dock.example",
844 "tcp://127.0.0.1:2375/../",
845 "tcp://127.0.0.1:2375?x=1",
846 "tcp://127.0.0.1:",
847 "tcp://127.0.0.1:99999999",
848 "tcp://127.0.0.1 :2375",
849 "tcp://",
850 ] {
851 assert!(candidates(&with(tricky, false)).is_err(), "{tricky} must be refused");
852 assert!(candidates(&with(tricky, true)).is_err(), "{tricky} must be refused with TLS too");
853 }
854 assert!(candidates(&with("tcp://203.0.113.5:2376", true)).is_ok());
856 assert!(candidates(&with("https://dock.example:2376", false)).is_ok());
857 }
858
859 #[test]
860 fn the_cli_is_pointed_at_a_unix_socket_or_plain_tcp_and_left_alone_otherwise() {
861 let sock = Endpoint::Unix(PathBuf::from("/run/user/1000/podman/podman.sock"));
862 assert_eq!(docker_host_of(&sock).as_deref(), Some("unix:///run/user/1000/podman/podman.sock"));
863 assert_eq!(docker_host_of(&Endpoint::Tcp { host: "10.0.0.5:2375".into(), tls: false }).as_deref(), Some("tcp://10.0.0.5:2375"));
864 assert_eq!(docker_host_of(&Endpoint::Tcp { host: "h:2376".into(), tls: true }), None, "TLS needs files the CLI finds itself");
865 assert_eq!(docker_host_of(&Endpoint::Pipe("//./pipe/docker_engine".into())), None);
866 }
867
868 #[test]
869 fn docker_host_decides_alone() {
870 let with = |h: &str, tls: bool| Env {
871 docker_host: Some(h.to_string()),
872 tls_verify: tls,
873 ..env(Path::new("/t"), Os::Linux)
874 };
875 let one = |h: &str, tls: bool| {
876 let c = candidates(&with(h, tls)).unwrap();
877 assert_eq!(c.len(), 1, "no probing beside an explicit DOCKER_HOST: {h}");
878 c[0].endpoint.clone()
879 };
880 assert_eq!(one("unix:///run/x.sock", false), Endpoint::Unix("/run/x.sock".into()));
881 assert_eq!(one("tcp://127.0.0.1:2375", false), Endpoint::Tcp { host: "127.0.0.1:2375".into(), tls: false });
882 assert_eq!(one("tcp://203.0.113.5:2376", true), Endpoint::Tcp { host: "203.0.113.5:2376".into(), tls: true });
883 assert_eq!(one("https://dock.example:2376/", false), Endpoint::Tcp { host: "dock.example:2376".into(), tls: true });
884 assert_eq!(one("npipe:////./pipe/docker_engine", false), Endpoint::Pipe("//./pipe/docker_engine".into()));
885 assert_eq!(
886 candidates(&with("ssh://me@box", false)).unwrap_err().contains("ssh://"),
887 true,
888 "an unsupported scheme is named"
889 );
890 assert!(candidates(&with("/var/run/docker.sock", false)).unwrap_err().contains("not an address"));
891 }
892
893 #[tokio::test]
894 async fn the_first_socket_that_answers_wins_and_stale_ones_are_skipped() {
895 let t = tempfile::TempDir::new().unwrap();
896 let e = env(t.path(), Os::Linux);
897 stale(at(t.path(), "run-user/docker.sock"));
898 let podman = serve(at(t.path(), "run-user/podman/podman.sock"), "200 OK");
899 let system = serve(at(t.path(), "root/var/run/docker.sock"), "200 OK");
901
902 let got = connect(&e).await.ok().expect("podman answers");
903 assert_eq!(got.kind, Kind::RootlessPodman);
904 assert!(got.label().starts_with("rootless Podman at unix://"), "{}", got.label());
905 assert!(got.label().ends_with("/run-user/podman/podman.sock"));
906 podman.abort();
907 system.abort();
908 }
909
910 #[tokio::test]
913 async fn a_tcp_docker_host_is_connected_at_the_parsed_address() {
914 use tokio::net::TcpListener;
915 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
916 let port = listener.local_addr().unwrap().port();
917 let server = tokio::spawn(async move {
918 while let Ok((mut s, _)) = listener.accept().await {
919 tokio::spawn(async move {
920 let mut buf = [0u8; 1024];
921 let _ = s.read(&mut buf).await;
922 let _ = s.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK").await;
923 });
924 }
925 });
926 let t = tempfile::TempDir::new().unwrap();
927 let e = Env { docker_host: Some(format!("tcp://127.0.0.1:{port}")), ..env(t.path(), Os::Linux) };
928 let got = connect(&e).await.ok().expect("the tcp runtime answers");
929 assert_eq!(got.kind, Kind::Configured);
930 assert_eq!(got.endpoint, Endpoint::Tcp { host: format!("127.0.0.1:{port}"), tls: false });
931 server.abort();
932 }
933
934 #[tokio::test]
936 async fn docker_desktop_on_linux_is_found_at_its_own_path() {
937 let t = tempfile::TempDir::new().unwrap();
938 let desktop = serve(at(t.path(), "home/.docker/desktop/docker.sock"), "200 OK");
939 let got = connect(&env(t.path(), Os::Linux)).await.ok().expect("Docker Desktop answers");
940 assert_eq!(got.kind, Kind::DockerDesktop);
941 assert!(got.label().ends_with("/home/.docker/desktop/docker.sock"), "{}", got.label());
942 desktop.abort();
943 }
944
945 #[tokio::test]
946 async fn nothing_answering_says_what_each_place_was() {
947 let t = tempfile::TempDir::new().unwrap();
948 let e = env(t.path(), Os::Linux);
949 stale(at(t.path(), "run-user/docker.sock"));
950 std::fs::write(at(t.path(), "root/var/run/docker.sock"), b"not a socket").unwrap();
951 let bad = serve(at(t.path(), "home/.docker/desktop/docker.sock"), "500 Internal Server Error");
952
953 let Err(missing) = connect(&e).await else { panic!("nothing should answer") };
954 let why = |k: Kind| missing.tried.iter().find(|t| t.kind == k).unwrap().why.clone();
955 assert!(why(Kind::RootlessDocker).contains("connection refused"), "{}", why(Kind::RootlessDocker));
956 assert_eq!(why(Kind::Docker), "not a socket");
957 assert!(why(Kind::DockerDesktop).contains("HTTP 500"), "{}", why(Kind::DockerDesktop));
958 assert!(why(Kind::Podman).starts_with(ABSENT));
959
960 let m = missing.message();
961 assert!(m.contains("none answered"), "{m}");
962 assert!(m.contains("rootless Docker at unix://") && m.contains("connection refused"), "{m}");
963 assert!(m.contains("Nothing at:") && m.contains("/root/run/podman/podman.sock"), "{m}");
964 assert!(m.contains("systemctl --user enable --now podman.socket"), "{m}");
965 assert!(m.contains("DOCKER_HOST"), "{m}");
966 bad.abort();
967 }
968
969 #[tokio::test]
970 async fn a_socket_under_the_users_directories_must_be_theirs() {
971 let t = tempfile::TempDir::new().unwrap();
972 let server = serve(at(t.path(), "run-user/docker.sock"), "200 OK");
973 let mine = env(t.path(), Os::Linux);
974 assert!(connect(&mine).await.is_ok());
975
976 let other = Env { uid: Some(mine.uid.unwrap().wrapping_add(1)), ..mine };
978 let Err(missing) = connect(&other).await else { panic!("another user's socket must not be used") };
979 let t0 = &missing.tried[0];
980 assert_eq!(t0.kind, Kind::RootlessDocker);
981 assert!(t0.why.starts_with("owned by another user"), "{}", t0.why);
982 server.abort();
983 }
984
985 #[tokio::test]
986 async fn a_system_socket_is_used_whoever_owns_it() {
987 let t = tempfile::TempDir::new().unwrap();
988 let server = serve(at(t.path(), "root/var/run/docker.sock"), "200 OK");
989 let e = Env { uid: Some(unsafe { libc::geteuid() }.wrapping_add(1)), ..env(t.path(), Os::Linux) };
990 assert_eq!(connect(&e).await.ok().expect("the system socket answers").kind, Kind::Docker);
991 server.abort();
992 }
993
994 #[tokio::test]
995 async fn a_socket_that_accepts_but_never_answers_is_given_up_on() {
996 let t = tempfile::TempDir::new().unwrap();
997 let path = at(t.path(), "run-user/docker.sock");
998 let listener = UnixListener::bind(&path).unwrap();
999 let hold = tokio::spawn(async move {
1000 let mut held = Vec::new();
1001 while let Ok((s, _)) = listener.accept().await {
1002 held.push(s);
1003 }
1004 });
1005 let Err(missing) = connect(&env(t.path(), Os::Linux)).await else { panic!("no answer expected") };
1006 assert!(missing.tried[0].why.contains("gave no answer"), "{}", missing.tried[0].why);
1007 hold.abort();
1008 }
1009
1010 #[tokio::test]
1011 async fn a_docker_host_that_does_not_answer_is_not_second_guessed() {
1012 let t = tempfile::TempDir::new().unwrap();
1013 let server = serve(at(t.path(), "run-user/docker.sock"), "200 OK");
1015 let e = Env { docker_host: Some("unix:///nonexistent.sock".into()), ..env(t.path(), Os::Linux) };
1016 let Err(missing) = connect(&e).await else { panic!("DOCKER_HOST alone decides") };
1017 assert_eq!(missing.tried.len(), 1);
1018 let m = missing.message();
1019 assert!(m.contains("/nonexistent.sock") && m.contains("DOCKER_HOST is set"), "{m}");
1020 assert!(!m.contains("To use another socket"), "{m}");
1021 server.abort();
1022 }
1023
1024 #[tokio::test]
1026 async fn a_runtime_that_stops_answering_is_forgotten_with_a_reason() {
1027 let t = tempfile::TempDir::new().unwrap();
1028 let path = at(t.path(), "run-user/docker.sock");
1029 let server = serve(path.clone(), "200 OK");
1030 let docker = Docker::connect_with_unix(&path.to_string_lossy(), 5, bollard::API_DEFAULT_VERSION).unwrap();
1031 let mgr = ContainerManager::with_docker(docker, Some(format!("rootless Docker at unix://{}", path.display())));
1032 let handle = ContainerRuntimeHandle::connected_for_test(mgr);
1033 assert!(handle.is_available().await, "answers while the service is up");
1034 assert!(handle.runtime_label().await.unwrap().starts_with("rootless Docker at"));
1035
1036 server.abort();
1037 let _ = server.await; assert!(!handle.is_available().await, "stopped");
1039 assert!(handle.runtime_label().await.is_none(), "forgotten");
1040 let said = handle.missing_message().expect("says why");
1041 assert!(said.contains("rootless Docker at") && said.contains("stopped answering"), "{said}");
1042 }
1043
1044 #[test]
1045 fn hypers_connect_error_is_said_plainly() {
1046 assert!(connection_error("Error in the hyper legacy client: client error (Connect)").starts_with("could not connect"));
1047 assert_eq!(connection_error("something else"), "something else");
1048 }
1049
1050 #[tokio::test]
1051 async fn an_unusable_docker_host_is_the_whole_answer() {
1052 let e = Env { docker_host: Some("ssh://me@box".into()), ..env(Path::new("/t"), Os::Linux) };
1053 let Err(missing) = connect(&e).await else { panic!("ssh is not supported") };
1054 assert!(missing.tried.is_empty());
1055 assert!(missing.message().starts_with("Container agents need Docker or Podman: DOCKER_HOST uses ssh://"));
1056 }
1057
1058 #[tokio::test]
1061 #[ignore = "reads this machine's real sockets"]
1062 async fn itest_what_this_machine_has() {
1063 match connect(&Env::from_process()).await {
1064 Ok(found) => {
1065 let version = found.docker.version().await.map(|v| v.version.unwrap_or_default());
1066 println!("runtime: {} (daemon version: {version:?})", found.label());
1067 }
1068 Err(missing) => println!("no runtime: {}", missing.message()),
1069 }
1070 }
1071}