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