1use 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#[derive(Debug, Clone, Default)]
27pub struct EndpointFlags {
28 pub listens: Vec<SocketAddr>,
30 pub publishes: Vec<(SocketAddr, String)>,
36 pub offline: bool,
38}
39
40pub 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
71pub 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#[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 #[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 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}