Skip to main content

oxdock_cli/
endpoints.rs

1//! CLI endpoint mapping: virtual service keys to physical binds.
2//!
3//! Scripts declare logical endpoints (`NET_LISTEN("2251")`,
4//! `SSH_SERVE("demo-proxy")`); these flags decide what they bind to:
5//!
6//! - default: bare ports bind loopback, names open memory rendezvous;
7//! - `--listen 0.0.0.0:2251`: expose a logical port on an interface;
8//! - `-p 2222:2251`: map outer port 2222 to inner virtual 2251
9//!   (`-p 0:2251` takes an ephemeral outer port);
10//! - `--offline`: no sockets at all (conflicts with both above).
11//!
12//! [`build_registry`] turns the flags into a bound [`EndpointRegistry`];
13//! binding happens before script parsing so `EADDRINUSE` fails fast.
14
15use std::net::SocketAddr;
16#[cfg(feature = "net")]
17use std::sync::Arc;
18
19use anyhow::{Context, Result, bail};
20#[cfg(feature = "net")]
21use oxdock_net_plugin::{BindingSpec, EndpointKey, EndpointRegistry, Protocol, parse_endpoint_ref};
22
23/// Endpoint exposure flags from CLI args. Built by `Options::parse`,
24/// consumed by [`build_registry`].
25#[derive(Debug, Clone, Default)]
26pub struct EndpointFlags {
27    /// `--listen` addresses: each maps its own port as a virtual port.
28    pub listens: Vec<SocketAddr>,
29    /// `-p` mappings: (outer socket address, inner virtual endpoint as raw
30    /// text). A bare outer port binds all interfaces; outer port `0` takes an
31    /// ephemeral port, resolved at bind time. The inner text is validated by
32    /// [`build_registry`] so this container stays free of net types.
33    pub publishes: Vec<(SocketAddr, String)>,
34    /// `--offline`: socketless run, conflicts with both lists above.
35    pub offline: bool,
36}
37
38/// Parse one `--listen` value: `[host:]port`. Bare digits bind loopback;
39/// otherwise a full socket address (the only place a wildcard or a
40/// non-loopback interface may appear). Port `0` is rejected: an exposed
41/// ephemeral port has no stable inner key, so it belongs to `-p 0:<inner>`.
42pub fn parse_listen_arg(raw: &str) -> Result<SocketAddr> {
43    let text = raw.trim();
44    if text.is_empty() {
45        bail!("--listen requires an address ([host:]port)");
46    }
47    if text.chars().all(|c| c.is_ascii_digit()) {
48        let port: u16 = text
49            .parse()
50            .map_err(|_| anyhow::anyhow!("--listen port must be numeric 1-65535, got {raw:?}"))?;
51        if port == 0 {
52            bail!(
53                "--listen port 0 has no stable service key (use -p 0:<endpoint> for an ephemeral outer port)"
54            );
55        }
56        return Ok(SocketAddr::from(([127, 0, 0, 1], port)));
57    }
58    let addr: SocketAddr = text.parse().with_context(|| {
59        format!("--listen address must be [host:]port (try 0.0.0.0:2251), got {raw:?}")
60    })?;
61    if addr.port() == 0 {
62        bail!(
63            "--listen port 0 has no stable service key (use -p 0:<endpoint> for an ephemeral outer port)"
64        );
65    }
66    Ok(addr)
67}
68
69/// Parse one `-p` value: `[host:]outer:inner` (Docker-style). The outer
70/// side is a bare port (all interfaces) or a full socket address; the
71/// inner side stays raw text here and is validated by [`build_registry`]
72/// (when `net` is enabled the inner is also validated eagerly so parse
73/// errors keep their current shape). The inner may carry a protocol
74/// qualifier (`-p 5353:dns/udp` maps the UDP slot; unqualified inners map
75/// TCP).
76/// Supported shapes: `2222:2251`, `127.0.0.1:1234:2251`,
77/// `127.0.0.1:1234:ssh-server`, `[::1]:8080:web`, `0:2251` (ephemeral
78/// outer port, resolved at bind time).
79pub fn parse_publish_arg(raw: &str) -> Result<(SocketAddr, String)> {
80    let text = raw.trim();
81    let Some((outer_text, inner_text)) = text.rsplit_once(':') else {
82        bail!(
83            "-p requires [host:]outer:inner (try -p 2222:2251 or -p 127.0.0.1:1234:ssh-server), got {raw:?}"
84        );
85    };
86    let inner_text = inner_text.trim();
87    if inner_text.is_empty() {
88        bail!(
89            "-p requires [host:]outer:inner (try -p 2222:2251 or -p 127.0.0.1:1234:ssh-server), got {raw:?}"
90        );
91    }
92    #[cfg(feature = "net")]
93    parse_endpoint_ref(inner_text, "-p")
94        .with_context(|| format!("-p inner endpoint invalid in {raw:?}"))?;
95    let outer_text = outer_text.trim();
96    let addr = if let Ok(port) = outer_text.parse::<u16>() {
97        SocketAddr::from(([0, 0, 0, 0], port))
98    } else if let Ok(addr) = outer_text.parse::<SocketAddr>() {
99        addr
100    } else {
101        bail!(
102            "-p outer address invalid in {raw:?} (expected a port 0-65535 or a [host:]port address)"
103        );
104    };
105    Ok((addr, inner_text.to_string()))
106}
107
108/// Build the run's endpoint registry from CLI flags and bind every mapped
109/// socket now: callers run this before parsing so bind conflicts fail
110/// fast, never parse-then-fail-on-bind.
111#[cfg(feature = "net")]
112pub fn build_registry(flags: &EndpointFlags) -> Result<Arc<EndpointRegistry>> {
113    use oxdock_net_plugin::VirtualEndpoint;
114    use std::collections::HashSet;
115    if flags.offline && (!flags.listens.is_empty() || !flags.publishes.is_empty()) {
116        bail!("--offline conflicts with --listen/-p (offline runs open no sockets)");
117    }
118    let registry = Arc::new(EndpointRegistry::new(flags.offline));
119    let mut inners: HashSet<EndpointKey> = HashSet::new();
120    let mut outers: HashSet<SocketAddr> = HashSet::new();
121    for addr in &flags.listens {
122        let key = EndpointKey::tcp(VirtualEndpoint::Port(addr.port()));
123        if !inners.insert(key.clone()) {
124            bail!("virtual endpoint '{key}' is mapped twice");
125        }
126        if addr.port() != 0 && !outers.insert(*addr) {
127            bail!("outer socket address {addr} is mapped twice");
128        }
129        registry.add_mapping(&key, BindingSpec::Exposed { addr: *addr })?;
130    }
131    for (addr, inner) in &flags.publishes {
132        let (protocol, endpoint) = parse_endpoint_ref(inner, "-p")
133            .with_context(|| format!("-p inner endpoint invalid in {inner:?}"))?;
134        let key = EndpointKey {
135            protocol: protocol.unwrap_or(Protocol::Tcp),
136            endpoint,
137        };
138        if !inners.insert(key.clone()) {
139            bail!("virtual endpoint '{key}' is mapped twice");
140        }
141        if addr.port() != 0 && !outers.insert(*addr) {
142            bail!("outer socket address {addr} is mapped twice");
143        }
144        registry.add_mapping(&key, BindingSpec::Exposed { addr: *addr })?;
145    }
146    registry.bind_all()?;
147    Ok(registry)
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn listen_forms() {
156        assert_eq!(
157            parse_listen_arg("2251").unwrap(),
158            SocketAddr::from(([127, 0, 0, 1], 2251))
159        );
160        assert_eq!(
161            parse_listen_arg("0.0.0.0:2251").unwrap(),
162            SocketAddr::from(([0, 0, 0, 0], 2251))
163        );
164        for bad in ["", "0", "2251:0", "0.0.0.0:0", "not-an-addr"] {
165            parse_listen_arg(bad).expect_err("bad listen must fail");
166        }
167    }
168
169    #[test]
170    fn publish_forms() {
171        assert_eq!(
172            parse_publish_arg("2222:2251").unwrap(),
173            (SocketAddr::from(([0, 0, 0, 0], 2222)), "2251".to_string())
174        );
175        assert_eq!(
176            parse_publish_arg("0:demo-proxy").unwrap(),
177            (
178                SocketAddr::from(([0, 0, 0, 0], 0)),
179                "demo-proxy".to_string()
180            )
181        );
182        for bad in ["", "2251", "abc:2251"] {
183            parse_publish_arg(bad).expect_err("bad publish must fail");
184        }
185        // Inner-endpoint validation is eager only with `net`; without it the
186        // raw text is stored and rejected later with the feature message.
187        #[cfg(feature = "net")]
188        for bad in ["2222:0", "2222:127.0.0.1:2251"] {
189            parse_publish_arg(bad).expect_err("bad inner must fail");
190        }
191    }
192
193    #[test]
194    fn publish_three_part_host_port_forms() {
195        assert_eq!(
196            parse_publish_arg("127.0.0.1:1234:ssh-server").unwrap(),
197            ("127.0.0.1:1234".parse().unwrap(), "ssh-server".to_string())
198        );
199        assert_eq!(
200            parse_publish_arg("127.0.0.1:1234:2251").unwrap(),
201            ("127.0.0.1:1234".parse().unwrap(), "2251".to_string())
202        );
203        assert_eq!(
204            parse_publish_arg("[::1]:8080:web").unwrap(),
205            ("[::1]:8080".parse().unwrap(), "web".to_string())
206        );
207    }
208
209    #[cfg(feature = "net")]
210    #[test]
211    fn registry_rejects_conflicts() {
212        let flags = EndpointFlags {
213            offline: true,
214            listens: vec![SocketAddr::from(([0, 0, 0, 0], 2251))],
215            ..EndpointFlags::default()
216        };
217        build_registry(&flags).expect_err("offline plus listen must fail");
218        let flags = EndpointFlags {
219            publishes: vec![
220                (SocketAddr::from(([0, 0, 0, 0], 2222)), "2251".to_string()),
221                (SocketAddr::from(([0, 0, 0, 0], 2223)), "2251".to_string()),
222            ],
223            ..EndpointFlags::default()
224        };
225        build_registry(&flags).expect_err("duplicate inner must fail");
226        let flags = EndpointFlags {
227            publishes: vec![
228                (SocketAddr::from(([0, 0, 0, 0], 2222)), "2251".to_string()),
229                (SocketAddr::from(([0, 0, 0, 0], 2222)), "2252".to_string()),
230            ],
231            ..EndpointFlags::default()
232        };
233        build_registry(&flags).expect_err("duplicate outer must fail");
234    }
235
236    #[cfg(feature = "net")]
237    #[test]
238    fn registry_rejects_bad_inner() {
239        let flags = EndpointFlags {
240            publishes: vec![(SocketAddr::from(([0, 0, 0, 0], 2222)), "0".to_string())],
241            ..EndpointFlags::default()
242        };
243        build_registry(&flags).expect_err("bad inner must fail");
244    }
245}