Skip to main content

rustorb_giop/
corbaloc.rs

1//! `corbaloc:` and `corbaname:` object URLs (CORBA 3.0, 13.6.10).
2
3use std::fmt;
4use std::str::FromStr;
5
6use rustorb_cdr::ByteOrder;
7
8use crate::{AlternateIiopAddress, Error, IiopProfile, Ior, Result, TaggedProfile, Version};
9
10/// Port used when a corbaloc IIOP address has none.
11pub const DEFAULT_CORBALOC_PORT: u16 = 2809;
12
13/// Object key used by `corbaname:` URLs that have none.
14pub const DEFAULT_CORBANAME_KEY: &[u8] = b"NameService";
15
16/// One address of a corbaloc URL.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum ObjAddr {
19    /// `rir:`, which looks the key up with `resolve_initial_references`.
20    /// It must be the only address.
21    Rir,
22    /// `iiop:` or the empty protocol (`:`).
23    Iiop(IiopAddr),
24    /// Any other protocol, such as omniORB's `ssliop:` or `omniunix:`, kept
25    /// as text. The address ends at the first `,`, `/` or `#`.
26    Other {
27        /// Protocol token without the colon.
28        protocol: String,
29        /// Address after the colon.
30        address: String,
31    },
32}
33
34/// An IIOP address in a corbaloc URL: `[major.minor@]host[:port]`.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct IiopAddr {
37    /// IIOP version, 1.0 when not given.
38    pub version: Version,
39    /// Host name or IP address. IPv6 addresses are stored without the
40    /// brackets they have in the URL.
41    pub host: String,
42    /// TCP port, [`DEFAULT_CORBALOC_PORT`] when not given.
43    pub port: u16,
44}
45
46impl IiopAddr {
47    /// An IIOP 1.0 address.
48    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    /// The IIOP profile for this address and `object_key`, with no
57    /// components.
58    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/// A `corbaloc:` URL: a list of addresses and an object key.
70///
71/// Parsing follows the specification and omniORB:
72///
73/// - an empty IIOP address means `localhost` on the default port,
74/// - a missing port, or `:` with no digits, means the default port,
75/// - the key is URL-unescaped (`%xx`) into bytes; a URL without `/` has an
76///   empty key,
77/// - scheme and protocol names are matched without regard to case.
78///
79/// [`Display`](fmt::Display) writes `iiop:` addresses with an explicit port
80/// and escapes key bytes outside the characters the specification allows,
81/// so parsing the output gives the same value.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct Corbaloc {
84    /// Addresses, at least one.
85    pub addresses: Vec<ObjAddr>,
86    /// Object key.
87    pub key: Vec<u8>,
88}
89
90impl Corbaloc {
91    /// A corbaloc URL with one IIOP 1.0 address.
92    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    /// Parses a `corbaloc:` URL.
100    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    /// Whether this URL is `rir:`.
112    pub fn is_rir(&self) -> bool {
113        matches!(self.addresses.as_slice(), [ObjAddr::Rir])
114    }
115
116    /// The IIOP addresses, in order.
117    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    /// Builds the IOR this URL stands for, the way omniORB does: no type
125    /// id, and one IIOP profile for the first IIOP address with the lowest
126    /// version of all of them. The other IIOP addresses become
127    /// [`ALTERNATE_IIOP_ADDRESS`](crate::component_tag::ALTERNATE_IIOP_ADDRESS)
128    /// components, which go in the IIOP profile from IIOP 1.1 on and in a
129    /// separate [`TAG_MULTIPLE_COMPONENTS`] profile for IIOP 1.0. Other
130    /// protocols are skipped.
131    ///
132    /// Fails for `rir:` and when there is no IIOP address.
133    ///
134    /// [`TAG_MULTIPLE_COMPONENTS`]: crate::TAG_MULTIPLE_COMPONENTS
135    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/// A `corbaname:` URL: a naming context given as a corbaloc location, and
220/// a stringified name to resolve in it.
221///
222/// The key defaults to [`DEFAULT_CORBANAME_KEY`] when the URL has no `/`.
223/// The name is the URL-unescaped text after `#`, in the stringified name
224/// syntax of `CosNaming::NamingContextExt` (`a.kind/b`); splitting it into
225/// name components is left to the naming service code. An empty name
226/// stands for the naming context itself, and is written without `#`.
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct CorbaName {
229    /// The naming context.
230    pub context: Corbaloc,
231    /// Stringified name to resolve in the context, or empty.
232    pub name: String,
233}
234
235impl CorbaName {
236    /// Parses a `corbaname:` URL.
237    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/// Any string `CORBA::ORB::string_to_object` accepts.
273#[derive(Debug, Clone, PartialEq, Eq)]
274pub enum ObjectUrl {
275    /// A stringified IOR.
276    Ior(Ior),
277    /// A `corbaloc:` URL.
278    Corbaloc(Corbaloc),
279    /// A `corbaname:` URL.
280    CorbaName(CorbaName),
281}
282
283impl ObjectUrl {
284    /// Parses a stringified IOR, `corbaloc:` or `corbaname:` URL, choosing
285    /// by the scheme (in any case).
286    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
318/// Strips `scheme` from the start of `s`, ignoring case.
319fn 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
325/// Whether `c` ends an address.
326fn 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    /// Parses `<obj_addr_list>["/"<key_string>]`, leaving `#` and what
336    /// follows it in `rest`.
337    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    /// Parses `[<version>]<host>[":"<port>]` after `iiop:`.
390    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    /// Parses an optional `<major>.<minor>@`.
448    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
475/// Characters a host may contain: the unreserved and sub-delimiter
476/// characters of RFC 3986 except `,`, and `%` for IPv6 zone ids. IPv6
477/// addresses in brackets may also contain `:`.
478fn is_host_char(b: u8) -> bool {
479    b.is_ascii_alphanumeric() || b"-._~%!$&'()*+;=".contains(&b)
480}
481
482/// Characters a key or name may contain without escaping.
483fn is_unreserved(b: u8) -> bool {
484    b.is_ascii_alphanumeric() || b";/:?@&=+$,-_.!~*'()".contains(&b)
485}
486
487/// Undoes `%xx` escapes. Characters other than the unreserved ones and
488/// escapes are rejected.
489fn 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}