1use std::fmt;
4use std::str::FromStr;
5
6use rustorb_cdr::ByteOrder;
7
8use crate::{AlternateIiopAddress, Error, IiopProfile, Ior, Result, TaggedProfile, Version};
9
10pub const DEFAULT_CORBALOC_PORT: u16 = 2809;
12
13pub const DEFAULT_CORBANAME_KEY: &[u8] = b"NameService";
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum ObjAddr {
19 Rir,
22 Iiop(IiopAddr),
24 Other {
27 protocol: String,
29 address: String,
31 },
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct IiopAddr {
37 pub version: Version,
39 pub host: String,
42 pub port: u16,
44}
45
46impl IiopAddr {
47 pub fn new(host: impl Into<String>, port: u16) -> IiopAddr {
49 IiopAddr {
50 version: Version::V1_0,
51 host: host.into(),
52 port,
53 }
54 }
55
56 pub fn to_profile(&self, object_key: &[u8]) -> IiopProfile {
59 IiopProfile {
60 version: self.version,
61 host: self.host.clone(),
62 port: self.port,
63 object_key: object_key.to_vec(),
64 components: Vec::new(),
65 }
66 }
67}
68
69#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct Corbaloc {
84 pub addresses: Vec<ObjAddr>,
86 pub key: Vec<u8>,
88}
89
90impl Corbaloc {
91 pub fn iiop(host: impl Into<String>, port: u16, key: impl Into<Vec<u8>>) -> Corbaloc {
93 Corbaloc {
94 addresses: vec![ObjAddr::Iiop(IiopAddr::new(host, port))],
95 key: key.into(),
96 }
97 }
98
99 pub fn parse(s: &str) -> Result<Corbaloc> {
101 let rest = strip_scheme(s.trim_ascii(), "corbaloc:")
102 .ok_or(Error::InvalidObjectUrl("missing corbaloc: scheme"))?;
103 let mut parser = Parser { rest };
104 let loc = parser.corbaloc(None)?;
105 if !parser.rest.is_empty() {
106 return Err(Error::InvalidObjectUrl("unexpected text after the key"));
107 }
108 Ok(loc)
109 }
110
111 pub fn is_rir(&self) -> bool {
113 matches!(self.addresses.as_slice(), [ObjAddr::Rir])
114 }
115
116 pub fn iiop_addresses(&self) -> impl Iterator<Item = &IiopAddr> {
118 self.addresses.iter().filter_map(|a| match a {
119 ObjAddr::Iiop(addr) => Some(addr),
120 _ => None,
121 })
122 }
123
124 pub fn to_ior(&self, order: ByteOrder) -> Result<Ior> {
136 let mut addrs = self.iiop_addresses();
137 let first = addrs
138 .next()
139 .ok_or(Error::InvalidObjectUrl("no IIOP address"))?;
140 let mut profile = first.to_profile(&self.key);
141 let mut alternates = Vec::new();
142 for addr in addrs {
143 profile.version = profile.version.min(addr.version);
144 let alternate = AlternateIiopAddress {
145 host: addr.host.clone(),
146 port: addr.port,
147 };
148 alternates.push(alternate.to_component(order)?);
149 }
150 let mut profiles = Vec::with_capacity(2);
151 if profile.version.minor == 0 {
152 profiles.push(profile.to_tagged_profile(order)?);
153 if !alternates.is_empty() {
154 profiles.push(TaggedProfile::multiple_components_profile(
155 &alternates,
156 order,
157 )?);
158 }
159 } else {
160 profile.components = alternates;
161 profiles.push(profile.to_tagged_profile(order)?);
162 }
163 Ok(Ior {
164 type_id: String::new(),
165 profiles,
166 })
167 }
168
169 fn write_location(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 for (i, addr) in self.addresses.iter().enumerate() {
171 if i > 0 {
172 f.write_str(",")?;
173 }
174 write!(f, "{addr}")?;
175 }
176 f.write_str("/")?;
177 write_escaped(f, &self.key)
178 }
179}
180
181impl FromStr for Corbaloc {
182 type Err = Error;
183
184 fn from_str(s: &str) -> Result<Corbaloc> {
185 Corbaloc::parse(s)
186 }
187}
188
189impl fmt::Display for Corbaloc {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 f.write_str("corbaloc:")?;
192 self.write_location(f)
193 }
194}
195
196impl fmt::Display for ObjAddr {
197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198 match self {
199 ObjAddr::Rir => f.write_str("rir:"),
200 ObjAddr::Iiop(addr) => write!(f, "iiop:{addr}"),
201 ObjAddr::Other { protocol, address } => write!(f, "{protocol}:{address}"),
202 }
203 }
204}
205
206impl fmt::Display for IiopAddr {
207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208 if self.version != Version::V1_0 {
209 write!(f, "{}.{}@", self.version.major, self.version.minor)?;
210 }
211 if self.host.contains(':') {
212 write!(f, "[{}]:{}", self.host, self.port)
213 } else {
214 write!(f, "{}:{}", self.host, self.port)
215 }
216 }
217}
218
219#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct CorbaName {
229 pub context: Corbaloc,
231 pub name: String,
233}
234
235impl CorbaName {
236 pub fn parse(s: &str) -> Result<CorbaName> {
238 let rest = strip_scheme(s.trim_ascii(), "corbaname:")
239 .ok_or(Error::InvalidObjectUrl("missing corbaname: scheme"))?;
240 let mut parser = Parser { rest };
241 let context = parser.corbaloc(Some(DEFAULT_CORBANAME_KEY))?;
242 let name = match parser.rest.strip_prefix('#') {
243 Some(escaped) => String::from_utf8(unescape(escaped)?)
244 .map_err(|_| Error::InvalidObjectUrl("name is not UTF-8"))?,
245 None if parser.rest.is_empty() => String::new(),
246 None => return Err(Error::InvalidObjectUrl("unexpected text after the key")),
247 };
248 Ok(CorbaName { context, name })
249 }
250}
251
252impl FromStr for CorbaName {
253 type Err = Error;
254
255 fn from_str(s: &str) -> Result<CorbaName> {
256 CorbaName::parse(s)
257 }
258}
259
260impl fmt::Display for CorbaName {
261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 f.write_str("corbaname:")?;
263 self.context.write_location(f)?;
264 if !self.name.is_empty() {
265 f.write_str("#")?;
266 write_escaped(f, self.name.as_bytes())?;
267 }
268 Ok(())
269 }
270}
271
272#[derive(Debug, Clone, PartialEq, Eq)]
274pub enum ObjectUrl {
275 Ior(Ior),
277 Corbaloc(Corbaloc),
279 CorbaName(CorbaName),
281}
282
283impl ObjectUrl {
284 pub fn parse(s: &str) -> Result<ObjectUrl> {
287 let s = s.trim_ascii();
288 if strip_scheme(s, "IOR:").is_some() {
289 Ior::from_ior_string(s).map(ObjectUrl::Ior)
290 } else if strip_scheme(s, "corbaloc:").is_some() {
291 Corbaloc::parse(s).map(ObjectUrl::Corbaloc)
292 } else if strip_scheme(s, "corbaname:").is_some() {
293 CorbaName::parse(s).map(ObjectUrl::CorbaName)
294 } else {
295 Err(Error::InvalidObjectUrl("unknown scheme"))
296 }
297 }
298}
299
300impl FromStr for ObjectUrl {
301 type Err = Error;
302
303 fn from_str(s: &str) -> Result<ObjectUrl> {
304 ObjectUrl::parse(s)
305 }
306}
307
308impl fmt::Display for ObjectUrl {
309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310 match self {
311 ObjectUrl::Ior(ior) => write!(f, "{ior}"),
312 ObjectUrl::Corbaloc(loc) => write!(f, "{loc}"),
313 ObjectUrl::CorbaName(name) => write!(f, "{name}"),
314 }
315 }
316}
317
318fn strip_scheme<'a>(s: &'a str, scheme: &str) -> Option<&'a str> {
320 let head = s.get(..scheme.len())?;
321 head.eq_ignore_ascii_case(scheme)
322 .then(|| &s[scheme.len()..])
323}
324
325fn is_addr_end(c: char) -> bool {
327 matches!(c, ',' | '/' | '#')
328}
329
330struct Parser<'a> {
331 rest: &'a str,
332}
333
334impl<'a> Parser<'a> {
335 fn corbaloc(&mut self, default_key: Option<&[u8]>) -> Result<Corbaloc> {
338 let mut addresses = vec![self.obj_addr()?];
339 while let Some(rest) = self.rest.strip_prefix(',') {
340 self.rest = rest;
341 addresses.push(self.obj_addr()?);
342 }
343 if addresses.len() > 1 && addresses.contains(&ObjAddr::Rir) {
344 return Err(Error::InvalidObjectUrl("rir: must be the only address"));
345 }
346 let key = match self.rest.strip_prefix('/') {
347 Some(rest) => {
348 let end = rest.find('#').unwrap_or(rest.len());
349 self.rest = &rest[end..];
350 unescape(&rest[..end])?
351 }
352 None => default_key.unwrap_or_default().to_vec(),
353 };
354 Ok(Corbaloc { addresses, key })
355 }
356
357 fn obj_addr(&mut self) -> Result<ObjAddr> {
358 let colon = self
359 .rest
360 .find(|c: char| c == ':' || is_addr_end(c))
361 .filter(|&i| self.rest[i..].starts_with(':'))
362 .ok_or(Error::InvalidObjectUrl("address without a protocol"))?;
363 let protocol = &self.rest[..colon];
364 self.rest = &self.rest[colon + 1..];
365 if protocol.is_empty() || protocol.eq_ignore_ascii_case("iiop") {
366 return self.iiop_addr().map(ObjAddr::Iiop);
367 }
368 if !protocol
369 .chars()
370 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.' | '_'))
371 {
372 return Err(Error::InvalidObjectUrl("invalid protocol name"));
373 }
374 let end = self.rest.find(is_addr_end).unwrap_or(self.rest.len());
375 let address = &self.rest[..end];
376 self.rest = &self.rest[end..];
377 if protocol.eq_ignore_ascii_case("rir") {
378 if !address.is_empty() {
379 return Err(Error::InvalidObjectUrl("rir: takes no address"));
380 }
381 return Ok(ObjAddr::Rir);
382 }
383 Ok(ObjAddr::Other {
384 protocol: protocol.to_owned(),
385 address: address.to_owned(),
386 })
387 }
388
389 fn iiop_addr(&mut self) -> Result<IiopAddr> {
391 if self.rest.is_empty() || self.rest.starts_with(is_addr_end) {
392 return Ok(IiopAddr::new("localhost", DEFAULT_CORBALOC_PORT));
393 }
394 let version = self.version()?;
395 let bracketed = self.rest.starts_with('[');
396 let host = if let Some(rest) = self.rest.strip_prefix('[') {
397 let end = rest
398 .find(']')
399 .ok_or(Error::InvalidObjectUrl("unterminated IPv6 address"))?;
400 self.rest = &rest[end + 1..];
401 &rest[..end]
402 } else {
403 let end = self
404 .rest
405 .find(|c: char| c == ':' || is_addr_end(c))
406 .unwrap_or(self.rest.len());
407 let host = &self.rest[..end];
408 self.rest = &self.rest[end..];
409 host
410 };
411 if host.is_empty() {
412 return Err(Error::InvalidObjectUrl("empty host"));
413 }
414 if !host
415 .bytes()
416 .all(|b| is_host_char(b) || (bracketed && b == b':'))
417 {
418 return Err(Error::InvalidObjectUrl("invalid character in host"));
419 }
420 let port = match self.rest.strip_prefix(':') {
421 Some(rest) => {
422 let end = rest.find(is_addr_end).unwrap_or(rest.len());
423 let digits = &rest[..end];
424 self.rest = &rest[end..];
425 if digits.is_empty() {
426 DEFAULT_CORBALOC_PORT
427 } else if digits.bytes().all(|b| b.is_ascii_digit()) {
428 digits
429 .parse()
430 .map_err(|_| Error::InvalidObjectUrl("port out of range"))?
431 } else {
432 return Err(Error::InvalidObjectUrl("invalid port"));
433 }
434 }
435 None if self.rest.is_empty() || self.rest.starts_with(is_addr_end) => {
436 DEFAULT_CORBALOC_PORT
437 }
438 None => return Err(Error::InvalidObjectUrl("invalid address")),
439 };
440 Ok(IiopAddr {
441 version,
442 host: host.to_owned(),
443 port,
444 })
445 }
446
447 fn version(&mut self) -> Result<Version> {
449 let end = self
450 .rest
451 .find(|c: char| c == '@' || c == ':' || c == '[' || is_addr_end(c))
452 .unwrap_or(self.rest.len());
453 let Some(rest) = self.rest[end..].strip_prefix('@') else {
454 return Ok(Version::V1_0);
455 };
456 let (major, minor) = self.rest[..end]
457 .split_once('.')
458 .ok_or(Error::InvalidObjectUrl("invalid version"))?;
459 let number = |s: &str| -> Result<u8> {
460 if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
461 return Err(Error::InvalidObjectUrl("invalid version"));
462 }
463 s.parse()
464 .map_err(|_| Error::InvalidObjectUrl("invalid version"))
465 };
466 let version = Version {
467 major: number(major)?,
468 minor: number(minor)?,
469 };
470 self.rest = rest;
471 Ok(version)
472 }
473}
474
475fn is_host_char(b: u8) -> bool {
479 b.is_ascii_alphanumeric() || b"-._~%!$&'()*+;=".contains(&b)
480}
481
482fn is_unreserved(b: u8) -> bool {
484 b.is_ascii_alphanumeric() || b";/:?@&=+$,-_.!~*'()".contains(&b)
485}
486
487fn unescape(s: &str) -> Result<Vec<u8>> {
490 let mut out = Vec::with_capacity(s.len());
491 let mut bytes = s.bytes();
492 while let Some(b) = bytes.next() {
493 if b == b'%' {
494 let mut digit = || {
495 bytes
496 .next()
497 .and_then(|d| (d as char).to_digit(16))
498 .ok_or(Error::InvalidObjectUrl("invalid % escape"))
499 };
500 let value = digit()? << 4 | digit()?;
501 out.push(value as u8);
502 } else if is_unreserved(b) {
503 out.push(b);
504 } else {
505 return Err(Error::InvalidObjectUrl("character must be escaped"));
506 }
507 }
508 Ok(out)
509}
510
511fn write_escaped(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
512 for &b in bytes {
513 if is_unreserved(b) {
514 write!(f, "{}", b as char)?;
515 } else {
516 write!(f, "%{b:02X}")?;
517 }
518 }
519 Ok(())
520}