Skip to main content

rustorb_core/
orb.rs

1use std::collections::{BTreeMap, HashMap, VecDeque};
2use std::fmt;
3use std::future::Future;
4use std::panic::{self, AssertUnwindSafe};
5use std::path::PathBuf;
6use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
7use std::sync::{Arc, Condvar, Mutex, OnceLock};
8use std::time::{Duration, Instant};
9
10use rustorb_cdr::ByteOrder;
11use rustorb_giop::{CorbaName, Corbaloc, Ior, ObjectUrl, Version};
12use tokio::runtime::{Handle, Runtime};
13
14use crate::connection::{Connection, ConnectionPool};
15use crate::poa::{self, MainThreadGuard, Poa};
16use crate::pool::Job;
17use crate::server::Server;
18use crate::{
19    CompletionStatus, Exception, ObjectRef, SystemException, SystemExceptionKind, minor, name,
20    timeout,
21};
22use crate::{tls, trace};
23
24/// Settings of an [`Orb`].
25#[derive(Debug, Clone)]
26pub struct OrbOptions {
27    /// The highest GIOP version used for requests. A request uses the
28    /// lower of this and the version of the target's IIOP profile.
29    pub max_giop_version: Version,
30    /// Byte order of the messages rustorb sends.
31    pub byte_order: ByteOrder,
32    /// How long to wait for a TCP connection; `None` waits until the call
33    /// timeout expires, or as long as the operating system does. Expiry
34    /// raises `TIMEOUT`, completed no. The initial value of
35    /// [`Orb::set_connect_timeout`].
36    pub connect_timeout: Option<Duration>,
37    /// How long to wait for a reply; `None` waits forever. Expiry raises
38    /// `TIMEOUT`, completed maybe. The initial value of
39    /// [`Orb::set_call_timeout`]; see there for the timeouts that override
40    /// it.
41    pub request_timeout: Option<Duration>,
42    /// Largest GIOP message, header included and fragments joined, that
43    /// the ORB sends or accepts (`-ORBgiopMaxMsgSize N`; default 64 MiB).
44    /// A request over it is not sent (`MARSHAL`, completed no), a reply
45    /// over it is replaced by `MARSHAL`, completed yes; a message
46    /// received over it closes the connection.
47    pub max_message_size: usize,
48    /// Splits GIOP 1.2 requests and replies longer than this many bytes
49    /// into `Fragment` messages of at most this length
50    /// (`-ORBgiopFragmentSize N`; at least 1024, rounded down to a
51    /// multiple of 8). 0, the default, sends every message whole. GIOP 1.1
52    /// messages are never split. See docs/message-size.md.
53    pub fragment_size: usize,
54    /// How many `LOCATION_FORWARD` replies one invocation follows before
55    /// it gives up with `TRANSIENT`.
56    pub max_forwards: u32,
57    /// Initial references by name (`-ORBInitRef Name=URL`).
58    pub init_refs: HashMap<String, String>,
59    /// Base URL for initial references not in `init_refs`
60    /// (`-ORBDefaultInitRef URL`); the name is appended after a `/`.
61    pub default_init_ref: Option<String>,
62    /// Number of tokio worker threads for network I/O.
63    pub io_threads: usize,
64    /// Addresses to listen on for requests (`-ORBendPoint giop:tcp:HOST:PORT`).
65    /// Empty means one endpoint on every interface with a port the
66    /// operating system chooses. The server side starts listening when the
67    /// RootPOA is first used.
68    pub endpoints: Vec<EndpointAddr>,
69    /// Address published in IORs instead of the listening one
70    /// (`-ORBendPointPublish giop:tcp:HOST:PORT`); a port of 0 keeps the
71    /// listening port.
72    pub endpoint_publish: Option<EndpointAddr>,
73    /// Upcall threads kept running even when idle.
74    pub min_server_threads: usize,
75    /// Most upcall threads running at once (`-ORBmaxServerThreadPoolSize`).
76    /// Requests beyond that wait in a queue.
77    pub max_server_threads: usize,
78    /// How long an upcall thread beyond `min_server_threads` waits for work
79    /// before it ends.
80    pub server_thread_idle_timeout: Duration,
81    /// How long an upcall thread that answered a request waits for the
82    /// next request of the same connection, to read and run it itself
83    /// (`-ORBfollowLinger US`, in microseconds; docs/read-ownership.md).
84    /// Zero turns this off: the I/O task reads every request.
85    pub follow_linger: Duration,
86    /// How many requests of one connection an upcall thread reads in a
87    /// row before it lets the I/O task read again (`-ORBfollowLimit N`).
88    /// Zero turns this off.
89    pub follow_limit: usize,
90    /// Requests of one connection that may wait or run at once. Beyond
91    /// that the connection is not read until one completes.
92    pub max_requests_per_connection: usize,
93    /// Closes a client connection nothing was sent or received on for
94    /// this long, with no reply awaited (`-ORBoutConScanPeriod S`, in
95    /// seconds, 0 for never; default 120 s). The next call opens a new
96    /// one. See docs/connections.md.
97    pub client_idle_timeout: Option<Duration>,
98    /// Closes a server connection with `CloseConnection` when no request
99    /// came in for this long and none is running
100    /// (`-ORBinConScanPeriod S`, in seconds, 0 for never; default 180 s).
101    pub server_idle_timeout: Option<Duration>,
102    /// Most connections the server side keeps open at once
103    /// (`-ORBmaxServerConnections N`; 0, the default, for no limit). At
104    /// the limit the connection used least recently, of those with no
105    /// request running, is closed with `CloseConnection`, and new
106    /// connections wait in the listen backlog until one ends.
107    pub max_server_connections: usize,
108    /// Offers the connections this ORB opens for requests from the server
109    /// (bidirectional GIOP, `-ORBofferBiDirectionalGIOP 0|1`; default
110    /// off): GIOP 1.2 requests carry the addresses of this ORB's endpoints
111    /// in a `BI_DIR_IIOP` service context, and requests that come back
112    /// over the connection reach the POAs with the `BidirectionalPolicy`
113    /// `BOTH`. See docs/bidir-giop.md.
114    pub offer_bidir: bool,
115    /// Uses a connection a client offered for bidirectional GIOP to call
116    /// the objects at the addresses it gave
117    /// (`-ORBacceptBiDirectionalGIOP 0|1`; default off). See
118    /// docs/bidir-giop.md for when the addresses are believed.
119    pub accept_bidir: bool,
120    /// The socket send buffer of each connection (`SO_SNDBUF`), client and
121    /// server; `None` leaves the operating system's default (which on
122    /// Linux grows as needed).
123    pub socket_send_buffer: Option<usize>,
124    /// The socket receive buffer of each connection (`SO_RCVBUF`); `None`
125    /// leaves the operating system's default.
126    pub socket_receive_buffer: Option<usize>,
127    /// Addresses to listen on for requests over TLS (SSLIOP,
128    /// `-ORBendPoint giop:ssl:HOST:PORT`). Published in the
129    /// `TAG_SSL_SEC_TRANS` component of IORs; with TLS endpoints and none
130    /// in [`endpoints`](OrbOptions::endpoints), the ORB has no unprotected
131    /// endpoint. Needs [`tls`](OrbOptions::tls) with a key file.
132    pub tls_endpoints: Vec<EndpointAddr>,
133    /// Address published for the first TLS endpoint instead of the
134    /// listening one (`-ORBendPointPublish giop:ssl:HOST:PORT`).
135    pub tls_endpoint_publish: Option<EndpointAddr>,
136    /// Certificates, key and checks of TLS connections, client and server.
137    pub tls: TlsOptions,
138    /// The trace level of the process (`-ORBtraceLevel N`), set when the
139    /// ORB is created; `None` leaves it as it is (1 at first). See
140    /// [`trace`](crate::trace) and docs/tracing.md.
141    pub trace_level: Option<u32>,
142    /// Whether trace lines on standard error start with the time
143    /// (`-ORBtraceTime 0|1`), set when the ORB is created; `None` leaves
144    /// it as it is (off at first).
145    pub trace_time: Option<bool>,
146    /// The arguments the ORB was created with, for
147    /// [`OrbInitInfo::arguments`](crate::pi::OrbInitInfo::arguments).
148    /// [`Orb::init`] sets them to its arguments, ORB options included.
149    pub arguments: Vec<String>,
150    /// The ORB id (`-ORBid`), for the Portable Interceptors.
151    pub orb_id: String,
152    /// The server id (`-ORBServerId`), for the Portable Interceptors.
153    pub server_id: String,
154    /// The [`OrbInitializer`](crate::pi::OrbInitializer)s of this ORB,
155    /// run after those of
156    /// [`register_orb_initializer`](crate::pi::register_orb_initializer)
157    /// (docs/portable-interceptors.md).
158    pub initializers: Vec<Arc<dyn crate::pi::OrbInitializer>>,
159}
160
161/// The TLS settings of an ORB (docs/ssliop.md). Files are PEM.
162///
163/// A client connects with TLS to the objects whose IORs offer it when
164/// [`ca_file`](TlsOptions::ca_file) is set; a server listens on the
165/// [TLS endpoints](OrbOptions::tls_endpoints).
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct TlsOptions {
168    /// The CA certificates trusted for the peer's certificate
169    /// (`-ORBsslCAFile`). A client needs it to use TLS, a server to check
170    /// client certificates.
171    pub ca_file: Option<PathBuf>,
172    /// This ORB's certificate, followed by its intermediate CAs
173    /// (`-ORBsslCertFile`). Without it the certificates are read from
174    /// [`key_file`](TlsOptions::key_file), which may hold both.
175    pub cert_file: Option<PathBuf>,
176    /// This ORB's private key, unencrypted (`-ORBsslKeyFile`). A server
177    /// needs it; a client sends its certificate when it has one.
178    pub key_file: Option<PathBuf>,
179    /// Whether a server asks clients for a certificate
180    /// (`-ORBsslVerifyClient none|optional|required`).
181    pub client_auth: ClientAuth,
182    /// Whether a client checks that the server's certificate is for the
183    /// host it connects to, as named in the IOR (`-ORBsslVerifyHost 0|1`).
184    /// The chain is checked either way.
185    pub verify_host: bool,
186}
187
188impl Default for TlsOptions {
189    fn default() -> TlsOptions {
190        TlsOptions {
191            ca_file: None,
192            cert_file: None,
193            key_file: None,
194            client_auth: ClientAuth::None,
195            verify_host: true,
196        }
197    }
198}
199
200/// Whether a TLS server asks clients for a certificate. A certificate a
201/// client sends is checked against [`TlsOptions::ca_file`].
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
203pub enum ClientAuth {
204    /// Clients are not asked.
205    #[default]
206    None,
207    /// Clients are asked; one without a certificate is accepted.
208    Optional,
209    /// Clients without a valid certificate are refused.
210    Required,
211}
212
213/// A TCP address of an endpoint, as in `giop:tcp:HOST:PORT` (or
214/// `giop:ssl:HOST:PORT` for a TLS endpoint).
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct EndpointAddr {
217    /// Host name or address. Empty means every interface when listening,
218    /// and the host name of the machine when published.
219    pub host: String,
220    /// TCP port; 0 lets the operating system choose.
221    pub port: u16,
222}
223
224impl EndpointAddr {
225    /// Parses `giop:tcp:HOST:PORT`; the host and the port may be empty, and
226    /// an IPv6 address is written in brackets.
227    pub fn parse(s: &str) -> Option<EndpointAddr> {
228        EndpointAddr::parse_after(s.strip_prefix("giop:tcp:")?)
229    }
230
231    /// Parses `giop:ssl:HOST:PORT`, a TLS endpoint, like
232    /// [`parse`](EndpointAddr::parse).
233    pub fn parse_tls(s: &str) -> Option<EndpointAddr> {
234        EndpointAddr::parse_after(s.strip_prefix("giop:ssl:")?)
235    }
236
237    fn parse_after(rest: &str) -> Option<EndpointAddr> {
238        let (host, port) = rest.rsplit_once(':')?;
239        let port = if port.is_empty() {
240            0
241        } else {
242            port.parse().ok()?
243        };
244        let host = match host.strip_prefix('[') {
245            Some(h) => h.strip_suffix(']')?,
246            None if host.contains(':') => return None,
247            None => host,
248        };
249        Some(EndpointAddr {
250            host: host.to_owned(),
251            port,
252        })
253    }
254}
255
256impl Default for OrbOptions {
257    fn default() -> OrbOptions {
258        OrbOptions {
259            max_giop_version: Version::V1_2,
260            byte_order: ByteOrder::NATIVE,
261            connect_timeout: None,
262            request_timeout: None,
263            max_message_size: 64 * 1024 * 1024,
264            fragment_size: 0,
265            max_forwards: 16,
266            init_refs: HashMap::new(),
267            default_init_ref: None,
268            io_threads: 2,
269            endpoints: Vec::new(),
270            endpoint_publish: None,
271            min_server_threads: 4,
272            max_server_threads: 100,
273            server_thread_idle_timeout: Duration::from_secs(60),
274            follow_linger: Duration::from_millis(1),
275            follow_limit: 64,
276            max_requests_per_connection: 256,
277            client_idle_timeout: Some(Duration::from_secs(120)),
278            server_idle_timeout: Some(Duration::from_secs(180)),
279            max_server_connections: 0,
280            offer_bidir: false,
281            accept_bidir: false,
282            socket_send_buffer: None,
283            socket_receive_buffer: None,
284            tls_endpoints: Vec::new(),
285            tls_endpoint_publish: None,
286            tls: TlsOptions::default(),
287            trace_level: None,
288            trace_time: None,
289            arguments: Vec::new(),
290            orb_id: String::new(),
291            server_id: String::new(),
292            initializers: Vec::new(),
293        }
294    }
295}
296
297impl OrbOptions {
298    /// Reads ORB options from command line arguments and removes them,
299    /// like `CORBA::ORB_init`. Other arguments are left in place.
300    ///
301    /// | Option | Setting |
302    /// | --- | --- |
303    /// | `-ORBInitRef Name=URL` | [`init_refs`](OrbOptions::init_refs) |
304    /// | `-ORBid ID` | [`orb_id`](OrbOptions::orb_id) |
305    /// | `-ORBServerId ID` | [`server_id`](OrbOptions::server_id) |
306    /// | `-ORBDefaultInitRef URL` | [`default_init_ref`](OrbOptions::default_init_ref) |
307    /// | `-ORBmaxGIOPVersion 1.1` | [`max_giop_version`](OrbOptions::max_giop_version) |
308    /// | `-ORBgiopMaxMsgSize N` | [`max_message_size`](OrbOptions::max_message_size), in bytes (at least 1024) |
309    /// | `-ORBgiopFragmentSize N` | [`fragment_size`](OrbOptions::fragment_size), in bytes (0, or at least 1024) |
310    /// | `-ORBclientConnectTimeOutPeriod MS` | [`connect_timeout`](OrbOptions::connect_timeout) (0 for none) |
311    /// | `-ORBclientCallTimeOutPeriod MS` | [`request_timeout`](OrbOptions::request_timeout) (0 for none) |
312    /// | `-ORBsupportPerThreadTimeOut 0\|1` | accepted and ignored: per-thread timeouts always work |
313    /// | `-ORBendPoint giop:tcp:HOST:PORT` | [`endpoints`](OrbOptions::endpoints) (repeatable) |
314    /// | `-ORBendPointPublish giop:tcp:HOST:PORT` | [`endpoint_publish`](OrbOptions::endpoint_publish) (`all(addr)` for the default) |
315    /// | `-ORBmaxServerThreadPoolSize N` | [`max_server_threads`](OrbOptions::max_server_threads) |
316    /// | `-ORBfollowLinger US` | [`follow_linger`](OrbOptions::follow_linger), in microseconds |
317    /// | `-ORBfollowLimit N` | [`follow_limit`](OrbOptions::follow_limit) |
318    /// | `-ORBoutConScanPeriod S` | [`client_idle_timeout`](OrbOptions::client_idle_timeout), in seconds (0 for never) |
319    /// | `-ORBinConScanPeriod S` | [`server_idle_timeout`](OrbOptions::server_idle_timeout), in seconds (0 for never) |
320    /// | `-ORBmaxServerConnections N` | [`max_server_connections`](OrbOptions::max_server_connections) (0 for no limit) |
321    /// | `-ORBofferBiDirectionalGIOP 0\|1` | [`offer_bidir`](OrbOptions::offer_bidir) |
322    /// | `-ORBacceptBiDirectionalGIOP 0\|1` | [`accept_bidir`](OrbOptions::accept_bidir) |
323    /// | `-ORBendPoint giop:ssl:HOST:PORT` | [`tls_endpoints`](OrbOptions::tls_endpoints) (repeatable) |
324    /// | `-ORBendPointPublish giop:ssl:HOST:PORT` | [`tls_endpoint_publish`](OrbOptions::tls_endpoint_publish) |
325    /// | `-ORBsslCAFile PATH` | [`TlsOptions::ca_file`] |
326    /// | `-ORBsslCertFile PATH` | [`TlsOptions::cert_file`] |
327    /// | `-ORBsslKeyFile PATH` | [`TlsOptions::key_file`] |
328    /// | `-ORBsslVerifyClient none\|optional\|required` | [`TlsOptions::client_auth`] |
329    /// | `-ORBsslVerifyHost 0\|1` | [`TlsOptions::verify_host`] |
330    /// | `-ORBtraceLevel N` | [`trace_level`](OrbOptions::trace_level) |
331    /// | `-ORBtraceTime 0\|1` | [`trace_time`](OrbOptions::trace_time) |
332    ///
333    /// The value may also follow the option name after `=`, as in
334    /// `-ORBmaxGIOPVersion=1.1`.
335    pub fn parse_args(&mut self, args: &mut Vec<String>) -> Result<(), SystemException> {
336        let mut rest = Vec::with_capacity(args.len());
337        let mut iter = std::mem::take(args).into_iter();
338        while let Some(arg) = iter.next() {
339            let Some(option) = arg.strip_prefix("-ORB") else {
340                rest.push(arg);
341                continue;
342            };
343            let (name, inline) = match option.split_once('=') {
344                Some((name, value))
345                    if matches!(
346                        name,
347                        "maxGIOPVersion"
348                            | "giopMaxMsgSize"
349                            | "giopFragmentSize"
350                            | "clientConnectTimeOutPeriod"
351                            | "clientCallTimeOutPeriod"
352                            | "supportPerThreadTimeOut"
353                            | "maxServerThreadPoolSize"
354                            | "followLinger"
355                            | "followLimit"
356                            | "outConScanPeriod"
357                            | "inConScanPeriod"
358                            | "maxServerConnections"
359                            | "offerBiDirectionalGIOP"
360                            | "acceptBiDirectionalGIOP"
361                            | "sslCAFile"
362                            | "sslCertFile"
363                            | "sslKeyFile"
364                            | "sslVerifyClient"
365                            | "sslVerifyHost"
366                            | "traceLevel"
367                            | "traceTime"
368                            | "id"
369                            | "ServerId"
370                    ) =>
371                {
372                    (name.to_owned(), Some(value.to_owned()))
373                }
374                _ => (option.to_owned(), None),
375            };
376            if !matches!(
377                name.as_str(),
378                "InitRef"
379                    | "DefaultInitRef"
380                    | "maxGIOPVersion"
381                    | "giopMaxMsgSize"
382                    | "giopFragmentSize"
383                    | "clientConnectTimeOutPeriod"
384                    | "clientCallTimeOutPeriod"
385                    | "supportPerThreadTimeOut"
386                    | "endPoint"
387                    | "endPointPublish"
388                    | "maxServerThreadPoolSize"
389                    | "followLinger"
390                    | "followLimit"
391                    | "outConScanPeriod"
392                    | "inConScanPeriod"
393                    | "maxServerConnections"
394                    | "offerBiDirectionalGIOP"
395                    | "acceptBiDirectionalGIOP"
396                    | "sslCAFile"
397                    | "sslCertFile"
398                    | "sslKeyFile"
399                    | "sslVerifyClient"
400                    | "sslVerifyHost"
401                    | "traceLevel"
402                    | "traceTime"
403                    | "id"
404                    | "ServerId"
405            ) {
406                rest.push(arg);
407                continue;
408            }
409            let value = match inline.or_else(|| iter.next()) {
410                Some(value) => value,
411                None => return Err(bad_option()),
412            };
413            match name.as_str() {
414                "InitRef" => {
415                    let (id, url) = value.split_once('=').ok_or_else(bad_option)?;
416                    self.init_refs.insert(id.to_owned(), url.to_owned());
417                }
418                "DefaultInitRef" => self.default_init_ref = Some(value),
419                "maxGIOPVersion" => {
420                    let (major, minor) = value.split_once('.').ok_or_else(bad_option)?;
421                    let version = Version {
422                        major: major.parse().map_err(|_| bad_option())?,
423                        minor: minor.parse().map_err(|_| bad_option())?,
424                    };
425                    if !version.is_supported() {
426                        return Err(bad_option());
427                    }
428                    self.max_giop_version = version;
429                }
430                "giopMaxMsgSize" => {
431                    let n: usize = value.parse().map_err(|_| bad_option())?;
432                    if n < MIN_MESSAGE_SIZE {
433                        return Err(bad_option());
434                    }
435                    self.max_message_size = n;
436                }
437                "giopFragmentSize" => {
438                    let n: usize = value.parse().map_err(|_| bad_option())?;
439                    if n != 0 && n < MIN_MESSAGE_SIZE {
440                        return Err(bad_option());
441                    }
442                    self.fragment_size = n;
443                }
444                "clientConnectTimeOutPeriod" => self.connect_timeout = millis(&value)?,
445                "clientCallTimeOutPeriod" => self.request_timeout = millis(&value)?,
446                // rustorb always honours per-thread timeouts.
447                "supportPerThreadTimeOut" => {
448                    if !matches!(value.as_str(), "0" | "1") {
449                        return Err(bad_option());
450                    }
451                }
452                "endPoint" if value.starts_with("giop:ssl:") => self
453                    .tls_endpoints
454                    .push(EndpointAddr::parse_tls(&value).ok_or_else(bad_option)?),
455                "endPoint" => self
456                    .endpoints
457                    .push(EndpointAddr::parse(&value).ok_or_else(bad_option)?),
458                // `all(addr)` (every address of the host, omniORB's
459                // spelling) is what the ORB publishes anyway.
460                "endPointPublish" if value == "all(addr)" => self.endpoint_publish = None,
461                "endPointPublish" if value.starts_with("giop:ssl:") => {
462                    self.tls_endpoint_publish =
463                        Some(EndpointAddr::parse_tls(&value).ok_or_else(bad_option)?);
464                }
465                "endPointPublish" => {
466                    self.endpoint_publish =
467                        Some(EndpointAddr::parse(&value).ok_or_else(bad_option)?);
468                }
469                "maxServerThreadPoolSize" => {
470                    let n: usize = value.parse().map_err(|_| bad_option())?;
471                    if n == 0 {
472                        return Err(bad_option());
473                    }
474                    self.max_server_threads = n;
475                }
476                "followLinger" => {
477                    let us: u64 = value.parse().map_err(|_| bad_option())?;
478                    self.follow_linger = Duration::from_micros(us);
479                }
480                "followLimit" => {
481                    self.follow_limit = value.parse().map_err(|_| bad_option())?;
482                }
483                "outConScanPeriod" => self.client_idle_timeout = seconds(&value)?,
484                "inConScanPeriod" => self.server_idle_timeout = seconds(&value)?,
485                "maxServerConnections" => {
486                    self.max_server_connections = value.parse().map_err(|_| bad_option())?;
487                }
488                "sslCAFile" => self.tls.ca_file = Some(value.into()),
489                "sslCertFile" => self.tls.cert_file = Some(value.into()),
490                "sslKeyFile" => self.tls.key_file = Some(value.into()),
491                "sslVerifyClient" => {
492                    self.tls.client_auth = match value.as_str() {
493                        "none" => ClientAuth::None,
494                        "optional" => ClientAuth::Optional,
495                        "required" => ClientAuth::Required,
496                        _ => return Err(bad_option()),
497                    };
498                }
499                "offerBiDirectionalGIOP" => self.offer_bidir = flag(&value)?,
500                "acceptBiDirectionalGIOP" => self.accept_bidir = flag(&value)?,
501                "sslVerifyHost" => {
502                    self.tls.verify_host = match value.as_str() {
503                        "0" => false,
504                        "1" => true,
505                        _ => return Err(bad_option()),
506                    };
507                }
508                "traceLevel" => {
509                    self.trace_level = Some(value.parse().map_err(|_| bad_option())?);
510                }
511                "id" => self.orb_id = value,
512                "ServerId" => self.server_id = value,
513                "traceTime" => {
514                    self.trace_time = Some(match value.as_str() {
515                        "0" => false,
516                        "1" => true,
517                        _ => return Err(bad_option()),
518                    });
519                }
520                _ => unreachable!(),
521            }
522        }
523        *args = rest;
524        Ok(())
525    }
526}
527
528fn flag(value: &str) -> Result<bool, SystemException> {
529    match value {
530        "0" => Ok(false),
531        "1" => Ok(true),
532        _ => Err(bad_option()),
533    }
534}
535
536fn millis(value: &str) -> Result<Option<Duration>, SystemException> {
537    let ms: u64 = value.parse().map_err(|_| bad_option())?;
538    Ok((ms > 0).then(|| Duration::from_millis(ms)))
539}
540
541fn seconds(value: &str) -> Result<Option<Duration>, SystemException> {
542    let s: u64 = value.parse().map_err(|_| bad_option())?;
543    Ok((s > 0).then(|| Duration::from_secs(s)))
544}
545
546fn bad_param() -> SystemException {
547    SystemException::new(SystemExceptionKind::BAD_PARAM, 0, CompletionStatus::No)
548}
549
550/// The smallest `-ORBgiopMaxMsgSize`: room for the headers of any request
551/// and for a system exception reply.
552const MIN_MESSAGE_SIZE: usize = 1024;
553
554fn bad_option() -> SystemException {
555    SystemException::new(SystemExceptionKind::BAD_PARAM, 0, CompletionStatus::No)
556}
557
558/// Why `resolve_initial_references` failed.
559#[derive(Debug, Clone, PartialEq, Eq)]
560pub enum ResolveError {
561    /// `CORBA::ORB::InvalidName`: no initial reference has this name.
562    InvalidName(String),
563    /// The configured URL could not be turned into a reference.
564    System(SystemException),
565}
566
567impl fmt::Display for ResolveError {
568    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
569        match self {
570            ResolveError::InvalidName(name) => write!(f, "no initial reference named {name:?}"),
571            ResolveError::System(e) => e.fmt(f),
572        }
573    }
574}
575
576impl std::error::Error for ResolveError {}
577
578impl From<SystemException> for ResolveError {
579    fn from(e: SystemException) -> Self {
580        ResolveError::System(e)
581    }
582}
583
584/// An ORB: the client side, and the server side once the RootPOA is used.
585///
586/// Network I/O runs on a tokio runtime owned by the ORB, or on one the
587/// application shares with it ([`with_runtime`](Orb::with_runtime)); the
588/// methods here and on [`ObjectRef`] block the calling thread. They must
589/// not be called from inside a tokio runtime, the threads of
590/// `spawn_blocking` included (they fail with `BAD_INV_ORDER`): async code
591/// uses [`ObjectRef::request_async`] and [`run_async`](Orb::run_async)
592/// instead. Servants run on a pool of upcall threads owned by the ORB.
593///
594/// `Orb` is a cheap handle: clones share the same ORB, which shuts down
595/// when the last clone and the last [`ObjectRef`] are gone. Servants that
596/// hold the ORB keep it alive until [`shutdown`](Orb::shutdown) or
597/// [`destroy`](Orb::destroy) drops them.
598#[derive(Clone)]
599pub struct Orb {
600    pub(crate) inner: Arc<OrbInner>,
601}
602
603pub(crate) struct OrbInner {
604    runtime: Option<Runtime>,
605    pub(crate) handle: Handle,
606    pub(crate) options: OrbOptions,
607    /// [`Orb::set_call_timeout`] and [`Orb::set_connect_timeout`], as
608    /// [`timeout::encode`](crate::timeout::encode) stores them.
609    call_timeout: AtomicU64,
610    connect_timeout: AtomicU64,
611    pub(crate) connections: Arc<ConnectionPool>,
612    /// The task closing idle client connections, started with the first
613    /// connection when [`OrbOptions::client_idle_timeout`] is set.
614    idle_scan: OnceLock<tokio::task::JoinHandle<()>>,
615    /// The configuration of client TLS connections, made when first used.
616    tls_client: OnceLock<Result<Arc<rustls::ClientConfig>, String>>,
617    /// [`Orb::register_initial_reference`] and
618    /// [`Orb::register_local_initial_reference`]. IORs rather than
619    /// references, which would hold the ORB.
620    registered: Mutex<BTreeMap<String, Registered>>,
621    shut_down: AtomicBool,
622    server: Mutex<Option<Arc<Server>>>,
623    /// The MAIN_THREAD_MODEL requests, and whether shutdown has completed;
624    /// `run` waits for both.
625    main: Mutex<MainQueue>,
626    main_cond: Condvar,
627    /// Wakes [`Orb::run_async`] when shutdown has completed.
628    stopped: tokio::sync::Notify,
629    /// A number no other ORB of the process has, for the Portable
630    /// Interceptors' slots.
631    pub(crate) serial: u64,
632    /// Whether `pi` is set: what each request looks at first.
633    pi_on: AtomicBool,
634    /// The Portable Interceptors, until the ORB is destroyed.
635    pi: Mutex<Option<Arc<crate::pi::Interceptors>>>,
636    /// The `BidirectionalPolicy` set with [`Orb::set_policy_overrides`].
637    pub(crate) bidir_override: Mutex<Option<crate::Bidirectional>>,
638    /// The threads that run the callbacks of
639    /// [`CallbackRequest`](crate::CallbackRequest)s, started with the
640    /// first; `Err` once the ORB is destroyed.
641    replies: Mutex<Result<Option<crate::pool::Pool>, ()>>,
642}
643
644/// An initial reference registered at run time.
645enum Registered {
646    Object(Ior),
647    Local(Arc<dyn std::any::Any + Send + Sync>),
648}
649
650#[derive(Default)]
651struct MainQueue {
652    jobs: VecDeque<Job>,
653    /// No more requests are queued (the server is shutting down).
654    closed: bool,
655    /// Shutdown has completed.
656    stopped: bool,
657}
658
659impl OrbInner {
660    /// Queues a MAIN_THREAD_MODEL request.
661    pub(crate) fn push_main(&self, job: Job) {
662        let mut main = self.main.lock().unwrap();
663        if main.closed {
664            return;
665        }
666        main.jobs.push_back(job);
667        self.main_cond.notify_one();
668    }
669
670    /// Drops the queued MAIN_THREAD_MODEL requests and refuses new ones.
671    pub(crate) fn close_main(&self) {
672        let jobs = {
673            let mut main = self.main.lock().unwrap();
674            main.closed = true;
675            std::mem::take(&mut main.jobs)
676        };
677        drop(jobs);
678    }
679}
680
681impl Drop for OrbInner {
682    fn drop(&mut self) {
683        if let Some(runtime) = self.runtime.take() {
684            runtime.shutdown_background();
685        }
686    }
687}
688
689/// Clones of one ORB are equal.
690impl PartialEq for Orb {
691    fn eq(&self, other: &Self) -> bool {
692        Arc::ptr_eq(&self.inner, &other.inner)
693    }
694}
695
696impl Eq for Orb {}
697
698impl fmt::Debug for Orb {
699    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
700        f.debug_struct("Orb")
701            .field("options", &self.inner.options)
702            .finish_non_exhaustive()
703    }
704}
705
706impl Orb {
707    /// Initialises an ORB from command line arguments, removing the ORB
708    /// options (see [`OrbOptions::parse_args`]).
709    pub fn init(args: &mut Vec<String>) -> Result<Orb, SystemException> {
710        let mut options = OrbOptions {
711            arguments: args.clone(),
712            ..OrbOptions::default()
713        };
714        options.parse_args(args)?;
715        Orb::with_options(options)
716    }
717
718    /// Initialises an ORB with `options`. Fails with the exception of an
719    /// [`OrbInitializer`](crate::pi::OrbInitializer) that failed.
720    pub fn with_options(options: OrbOptions) -> Result<Orb, SystemException> {
721        ignore_sigpipe();
722        let runtime = tokio::runtime::Builder::new_multi_thread()
723            .worker_threads(options.io_threads.max(1))
724            .thread_name("rustorb-io")
725            .enable_io()
726            .enable_time()
727            .build()
728            .map_err(|_| {
729                SystemException::new(SystemExceptionKind::INITIALIZE, 0, CompletionStatus::No)
730            })?;
731        let handle = runtime.handle().clone();
732        Orb::new(options, Some(runtime), handle)
733    }
734
735    /// Initialises an ORB with `options` whose network I/O runs on the
736    /// application's runtime `handle` instead of a runtime of its own
737    /// ([`OrbOptions::io_threads`] is not used). The runtime must have I/O
738    /// and time enabled. A `current_thread` runtime does I/O only while a
739    /// thread runs its `block_on`, so blocking calls (from servants, say)
740    /// wait until one does; a multi-thread runtime has no such limit.
741    ///
742    /// Shutting the ORB down needs the runtime to run. On a
743    /// `current_thread` runtime, a blocking [`shutdown(true)`](Orb::shutdown)
744    /// or [`destroy`](Orb::destroy) outside its `block_on` waits for it, and
745    /// inside it blocks the runtime: shut down from inside instead, with
746    /// `shutdown(false)` and [`run_async`](Orb::run_async), and destroy
747    /// after that.
748    ///
749    /// Destroy the ORB before the runtime shuts down. Destroying it closes
750    /// its connections and stops its listening tasks; the runtime keeps no
751    /// task of the ORB. Once the runtime is gone, calls fail with
752    /// `COMM_FAILURE` or `TRANSIENT`.
753    ///
754    /// When an [`OrbInitializer`](crate::pi::OrbInitializer) fails, the
755    /// ORB is returned shut down (calls fail with `BAD_INV_ORDER`); use
756    /// [`try_with_runtime`](Orb::try_with_runtime) to get the exception.
757    pub fn with_runtime(options: OrbOptions, handle: Handle) -> Orb {
758        match Orb::build(options, None, handle) {
759            (orb, Ok(())) => orb,
760            (orb, Err(_)) => {
761                orb.inner.shut_down.store(true, Ordering::Release);
762                orb
763            }
764        }
765    }
766
767    /// [`with_runtime`](Orb::with_runtime), failing with the exception of
768    /// an [`OrbInitializer`](crate::pi::OrbInitializer) that failed.
769    pub fn try_with_runtime(options: OrbOptions, handle: Handle) -> Result<Orb, SystemException> {
770        Orb::new(options, None, handle)
771    }
772
773    fn new(
774        options: OrbOptions,
775        runtime: Option<Runtime>,
776        handle: Handle,
777    ) -> Result<Orb, SystemException> {
778        let (orb, result) = Orb::build(options, runtime, handle);
779        result.map(|()| orb)
780    }
781
782    /// Makes the ORB and runs its initializers.
783    fn build(
784        options: OrbOptions,
785        runtime: Option<Runtime>,
786        handle: Handle,
787    ) -> (Orb, Result<(), SystemException>) {
788        if let Some(level) = options.trace_level {
789            crate::trace::set_trace_level(level);
790        }
791        if let Some(on) = options.trace_time {
792            crate::trace::set_trace_time(on);
793        }
794        let orb = Orb {
795            inner: Arc::new(OrbInner {
796                runtime,
797                handle,
798                call_timeout: AtomicU64::new(timeout::encode(options.request_timeout)),
799                connect_timeout: AtomicU64::new(timeout::encode(options.connect_timeout)),
800                options,
801                connections: Arc::default(),
802                idle_scan: OnceLock::new(),
803                tls_client: OnceLock::new(),
804                registered: Mutex::default(),
805                shut_down: AtomicBool::new(false),
806                server: Mutex::new(None),
807                main: Mutex::default(),
808                main_cond: Condvar::new(),
809                stopped: tokio::sync::Notify::new(),
810                serial: crate::pi::new_serial(),
811                pi_on: AtomicBool::new(false),
812                pi: Mutex::new(None),
813                bidir_override: Mutex::new(None),
814                replies: Mutex::new(Ok(None)),
815            }),
816        };
817        let mut initializers = crate::pi::registered_initializers();
818        initializers.extend(orb.inner.options.initializers.iter().cloned());
819        match crate::pi::initialize(&orb, &initializers) {
820            Ok(Some(pi)) => {
821                *orb.inner.pi.lock().unwrap() = Some(pi);
822                orb.inner.pi_on.store(true, Ordering::Release);
823                (orb, Ok(()))
824            }
825            Ok(None) => (orb, Ok(())),
826            Err(e) => (orb, Err(e)),
827        }
828    }
829
830    /// The interceptors of the ORB, if it has any.
831    pub(crate) fn interceptors(&self) -> Option<Arc<crate::pi::Interceptors>> {
832        if !self.inner.pi_on.load(Ordering::Acquire) {
833            return None;
834        }
835        self.inner.pi.lock().unwrap().clone()
836    }
837
838    /// `resolve_initial_references("PICurrent")`: the slots of the
839    /// Portable Interceptors for the calling thread.
840    pub fn pi_current(&self) -> crate::pi::PiCurrent {
841        crate::pi::PiCurrent::new(self)
842    }
843
844    /// `resolve_initial_references("CodecFactory")`.
845    pub fn codec_factory(&self) -> crate::iop::CodecFactory {
846        crate::iop::CodecFactory::new(self)
847    }
848
849    /// The handle of the runtime the ORB's network I/O runs on: its own,
850    /// or the one given to [`with_runtime`](Orb::with_runtime).
851    pub fn runtime_handle(&self) -> &Handle {
852        &self.inner.handle
853    }
854
855    /// The options the ORB was created with.
856    pub fn options(&self) -> &OrbOptions {
857        &self.inner.options
858    }
859
860    /// Sets how long calls through this ORB may take (`None`: no limit),
861    /// like omniORB's `setClientCallTimeout(millisecs)`. The time covers
862    /// connecting (unless a [connect timeout](Orb::set_connect_timeout)
863    /// is set), following forwards and waiting for the reply. When it
864    /// expires the call raises `TIMEOUT`: completed maybe once the request
865    /// was sent, and then a `CancelRequest` goes to the server; completed
866    /// no before.
867    ///
868    /// A timeout of the calling thread
869    /// ([`set_thread_call_timeout`](crate::set_thread_call_timeout))
870    /// overrides it, one of the object reference
871    /// ([`ObjectRef::set_call_timeout`]) overrides both, and one given for
872    /// the request ([`Request::timeout`](crate::Request::timeout)) all of
873    /// them.
874    pub fn set_call_timeout(&self, timeout: Option<Duration>) {
875        self.inner
876            .call_timeout
877            .store(timeout::encode(timeout), Ordering::Relaxed);
878    }
879
880    /// The timeout [`set_call_timeout`](Orb::set_call_timeout) set, or
881    /// [`OrbOptions::request_timeout`].
882    pub fn call_timeout(&self) -> Option<Duration> {
883        timeout::decode(self.inner.call_timeout.load(Ordering::Relaxed))
884    }
885
886    /// Sets how long to wait for a new TCP connection, like omniORB's
887    /// `setClientConnectTimeout`: while connecting it replaces the call
888    /// timeout. `None` connects until the call timeout expires, or as long
889    /// as the operating system waits. Expiry raises `TIMEOUT`, completed
890    /// no.
891    pub fn set_connect_timeout(&self, timeout: Option<Duration>) {
892        self.inner
893            .connect_timeout
894            .store(timeout::encode(timeout), Ordering::Relaxed);
895    }
896
897    /// The timeout [`set_connect_timeout`](Orb::set_connect_timeout) set,
898    /// or [`OrbOptions::connect_timeout`].
899    pub fn connect_timeout(&self) -> Option<Duration> {
900        timeout::decode(self.inner.connect_timeout.load(Ordering::Relaxed))
901    }
902
903    /// Turns a stringified IOR, a `corbaloc:` or a `corbaname:` URL into a
904    /// reference. Returns `None` for a nil IOR, or a name bound to nil.
905    ///
906    /// `corbaloc:rir:` goes through
907    /// [`resolve_initial_references`](Orb::resolve_initial_references).
908    /// `corbaname:` resolves the name after `#` in the naming context the
909    /// rest of the URL denotes (with no name, the context itself is
910    /// returned). The name must be a valid stringified name
911    /// (`BAD_PARAM`, minor `BAD_SCHEME_SPECIFIC_PART`); a name the naming
912    /// service cannot resolve raises `BAD_PARAM` with minor
913    /// `STRING_TO_OBJECT_OTHER`, and system exceptions from the naming
914    /// service are passed on.
915    pub fn string_to_object(&self, s: &str) -> Result<Option<ObjectRef>, SystemException> {
916        self.check_running()?;
917        let url = ObjectUrl::parse(s).map_err(|_| {
918            let trimmed = s.trim_ascii_start();
919            let known = ["IOR:", "corbaloc:", "corbaname:"].iter().any(|scheme| {
920                trimmed
921                    .get(..scheme.len())
922                    .is_some_and(|head| head.eq_ignore_ascii_case(scheme))
923            });
924            let minor = if known {
925                minor::BAD_SCHEME_SPECIFIC_PART
926            } else {
927                minor::BAD_SCHEME_NAME
928            };
929            SystemException::new(SystemExceptionKind::BAD_PARAM, minor, CompletionStatus::No)
930        })?;
931        match url {
932            ObjectUrl::Ior(ior) if ior.is_nil() => Ok(None),
933            ObjectUrl::Ior(ior) => Ok(Some(ObjectRef::new(self.clone(), ior))),
934            ObjectUrl::Corbaloc(loc) => self.corbaloc_to_object(loc).map(Some),
935            ObjectUrl::CorbaName(url) => self.resolve_corbaname(url),
936        }
937    }
938
939    fn corbaloc_to_object(&self, loc: Corbaloc) -> Result<ObjectRef, SystemException> {
940        if loc.is_rir() {
941            let name = String::from_utf8(loc.key).map_err(|_| {
942                SystemException::new(
943                    SystemExceptionKind::BAD_PARAM,
944                    minor::BAD_SCHEME_SPECIFIC_PART,
945                    CompletionStatus::No,
946                )
947            })?;
948            return match self.resolve_initial_references(&name) {
949                Ok(obj) => Ok(obj),
950                Err(ResolveError::System(e)) => Err(e),
951                Err(ResolveError::InvalidName(_)) => Err(SystemException::new(
952                    SystemExceptionKind::BAD_PARAM,
953                    minor::STRING_TO_OBJECT_OTHER,
954                    CompletionStatus::No,
955                )),
956            };
957        }
958        let ior = loc.to_ior(self.inner.options.byte_order).map_err(|_| {
959            SystemException::new(
960                SystemExceptionKind::BAD_PARAM,
961                minor::BAD_ADDRESS,
962                CompletionStatus::No,
963            )
964        })?;
965        Ok(ObjectRef::new(self.clone(), ior))
966    }
967
968    /// Resolves a `corbaname:` URL: the `corbaloc` part gives the naming
969    /// context, and the name after `#`, if any, is resolved in it with
970    /// `CosNaming::NamingContext::resolve`.
971    fn resolve_corbaname(&self, url: CorbaName) -> Result<Option<ObjectRef>, SystemException> {
972        let context = self.corbaloc_to_object(url.context)?;
973        if url.name.is_empty() {
974            return Ok(Some(context));
975        }
976        let name = name::to_name(&url.name).map_err(|_| {
977            SystemException::new(
978                SystemExceptionKind::BAD_PARAM,
979                minor::BAD_SCHEME_SPECIFIC_PART,
980                CompletionStatus::No,
981            )
982        })?;
983        let reply = context
984            .request("resolve")
985            .args(|out| name::write_name(out, &name))
986            .invoke();
987        match reply {
988            Ok(reply) => reply.input().read_object(),
989            Err(Exception::System(e)) => Err(e),
990            // NotFound, CannotProceed or InvalidName.
991            Err(Exception::User(_)) => Err(SystemException::new(
992                SystemExceptionKind::BAD_PARAM,
993                minor::STRING_TO_OBJECT_OTHER,
994                CompletionStatus::No,
995            )),
996        }
997    }
998
999    /// Writes a reference as a stringified IOR; `None` gives the nil IOR.
1000    pub fn object_to_string(&self, obj: Option<&ObjectRef>) -> Result<String, SystemException> {
1001        let nil = Ior::nil();
1002        let ior = obj.map_or(&nil, |obj| obj.ior());
1003        ior.to_ior_string(self.inner.options.byte_order)
1004            .map_err(|_| {
1005                SystemException::new(SystemExceptionKind::MARSHAL, 0, CompletionStatus::No)
1006            })
1007    }
1008
1009    /// Looks up an initial reference: first among those
1010    /// [registered](Orb::register_initial_reference), then in
1011    /// [`init_refs`](OrbOptions::init_refs), then under
1012    /// [`default_init_ref`](OrbOptions::default_init_ref).
1013    pub fn resolve_initial_references(&self, name: &str) -> Result<ObjectRef, ResolveError> {
1014        match self.inner.registered.lock().unwrap().get(name) {
1015            Some(Registered::Object(ior)) => {
1016                return Ok(ObjectRef::new(self.clone(), ior.clone()));
1017            }
1018            Some(Registered::Local(_)) => {
1019                return Err(ResolveError::InvalidName(name.to_owned()));
1020            }
1021            None => {}
1022        }
1023        let options = &self.inner.options;
1024        let url = match (options.init_refs.get(name), &options.default_init_ref) {
1025            (Some(url), _) => url.clone(),
1026            (None, Some(base)) => format!("{}/{name}", base.trim_end_matches('/')),
1027            (None, None) => return Err(ResolveError::InvalidName(name.to_owned())),
1028        };
1029        // An init ref pointing at rir: again would loop.
1030        if url
1031            .trim_ascii()
1032            .to_ascii_lowercase()
1033            .starts_with("corbaloc:rir:")
1034        {
1035            return Err(ResolveError::InvalidName(name.to_owned()));
1036        }
1037        self.string_to_object(&url)?
1038            .ok_or_else(|| ResolveError::InvalidName(name.to_owned()))
1039    }
1040
1041    /// The names [`resolve_initial_references`](Orb::resolve_initial_references)
1042    /// knows without the default URL, sorted.
1043    pub fn list_initial_services(&self) -> Vec<String> {
1044        let mut names: Vec<_> = self.inner.options.init_refs.keys().cloned().collect();
1045        names.extend(self.inner.registered.lock().unwrap().keys().cloned());
1046        names.sort();
1047        names.dedup();
1048        names
1049    }
1050
1051    /// `CORBA::ORB::register_initial_reference`: makes
1052    /// [`resolve_initial_references`](Orb::resolve_initial_references)
1053    /// return `obj` for `name`. `InvalidName` if `name` is empty or
1054    /// already an initial reference (registered or given with
1055    /// `-ORBInitRef`), `BAD_PARAM` (minor
1056    /// [`NIL_INITIAL_REFERENCE`](crate::minor::NIL_INITIAL_REFERENCE)) for
1057    /// a nil `obj`. The names a binding resolves itself, such as
1058    /// `RootPOA`, are the binding's to refuse.
1059    pub fn register_initial_reference(
1060        &self,
1061        name: &str,
1062        obj: Option<&ObjectRef>,
1063    ) -> Result<(), ResolveError> {
1064        let obj = obj.ok_or_else(|| {
1065            SystemException::new(
1066                SystemExceptionKind::BAD_PARAM,
1067                minor::NIL_INITIAL_REFERENCE,
1068                CompletionStatus::No,
1069            )
1070        });
1071        self.register(name, || Ok(Registered::Object(obj?.ior().clone())))
1072    }
1073
1074    /// [`register_initial_reference`](Orb::register_initial_reference) for
1075    /// an object of a binding that has no reference, such as a local
1076    /// object: the ORB keeps `obj` under `name` until it is destroyed, for
1077    /// [`resolve_local_initial_reference`](Orb::resolve_local_initial_reference).
1078    /// `resolve_initial_references` does not resolve it.
1079    pub fn register_local_initial_reference(
1080        &self,
1081        name: &str,
1082        obj: Arc<dyn std::any::Any + Send + Sync>,
1083    ) -> Result<(), ResolveError> {
1084        self.register(name, || Ok(Registered::Local(obj)))
1085    }
1086
1087    /// An object registered with
1088    /// [`register_local_initial_reference`](Orb::register_local_initial_reference).
1089    pub fn resolve_local_initial_reference(
1090        &self,
1091        name: &str,
1092    ) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
1093        match self.inner.registered.lock().unwrap().get(name) {
1094            Some(Registered::Local(obj)) => Some(Arc::clone(obj)),
1095            _ => None,
1096        }
1097    }
1098
1099    fn register(
1100        &self,
1101        name: &str,
1102        entry: impl FnOnce() -> Result<Registered, SystemException>,
1103    ) -> Result<(), ResolveError> {
1104        let mut registered = self.inner.registered.lock().unwrap();
1105        if name.is_empty()
1106            || registered.contains_key(name)
1107            || self.inner.options.init_refs.contains_key(name)
1108        {
1109            return Err(ResolveError::InvalidName(name.to_owned()));
1110        }
1111        registered.insert(name.to_owned(), entry()?);
1112        Ok(())
1113    }
1114
1115    /// The RootPOA. The first call starts the server side: it opens the
1116    /// [`endpoints`](OrbOptions::endpoints) (`INITIALIZE` if one cannot be
1117    /// opened) and the upcall thread pool.
1118    pub fn root_poa(&self) -> Result<Poa, SystemException> {
1119        self.check_running()?;
1120        // The IOR interceptors run without the lock (they may use the ORB).
1121        let root_components = match &*self.inner.server.lock().unwrap() {
1122            Some(_) => Vec::new(),
1123            None => crate::pi::establish_components(self, &poa::Policies::root(), &[]),
1124        };
1125        let mut server = self.inner.server.lock().unwrap();
1126        let server = match &*server {
1127            Some(s) => Arc::clone(s),
1128            None => {
1129                let s = Server::start(self, root_components)?;
1130                *server = Some(Arc::clone(&s));
1131                s
1132            }
1133        };
1134        Ok(Poa {
1135            orb: self.clone(),
1136            inner: Arc::clone(server.root()),
1137        })
1138    }
1139
1140    /// Makes `obj`, an object of this ORB's POAs, answer to the simple
1141    /// object key `key`, as in `corbaloc::host:port/NameService`, and
1142    /// returns a reference with that key. Requests with the key are
1143    /// dispatched to `obj` as if they had its own key: no
1144    /// `LOCATION_FORWARD` is involved, so the reference stays valid as
1145    /// long as the key is registered, also across restarts that register
1146    /// it again.
1147    ///
1148    /// `BAD_PARAM` if `key` is empty or `obj` is not an object of this
1149    /// ORB's POAs.
1150    pub fn register_object_key(
1151        &self,
1152        key: &str,
1153        obj: &ObjectRef,
1154    ) -> Result<ObjectRef, SystemException> {
1155        let server = self.server().ok_or_else(bad_param)?;
1156        if key.is_empty() {
1157            return Err(bad_param());
1158        }
1159        let target = obj
1160            .ior()
1161            .iiop_profiles()
1162            .filter_map(Result::ok)
1163            .find(|p| {
1164                server.is_own_profile(p)
1165                    && matches!(poa::parse_key(&p.object_key), poa::ParsedKey::Poa { .. })
1166            })
1167            .map(|p| p.object_key)
1168            .ok_or_else(bad_param)?;
1169        let ior = server.ior(obj.type_id(), key.as_bytes().to_vec(), &[])?;
1170        server.set_simple_key(key.as_bytes(), Some(target));
1171        Ok(ObjectRef::new(self.clone(), ior))
1172    }
1173
1174    /// Removes a key registered with
1175    /// [`register_object_key`](Orb::register_object_key); requests with it
1176    /// then raise `OBJECT_NOT_EXIST`.
1177    pub fn unregister_object_key(&self, key: &str) {
1178        if let Some(server) = self.server() {
1179            server.set_simple_key(key.as_bytes(), None);
1180        }
1181    }
1182
1183    /// The server side, if the RootPOA was used.
1184    /// Whether connections opened from now on are offered for
1185    /// bidirectional GIOP: [`OrbOptions::offer_bidir`], or a
1186    /// `BidirectionalPolicy` override of the ORB.
1187    pub(crate) fn offers_bidir(&self) -> bool {
1188        match *self.inner.bidir_override.lock().unwrap() {
1189            Some(v) => v == crate::Bidirectional::Both,
1190            None => self.inner.options.offer_bidir,
1191        }
1192    }
1193
1194    /// Whether a client's offer of bidirectional GIOP is taken:
1195    /// [`OrbOptions::accept_bidir`], or a `BidirectionalPolicy` override
1196    /// of the ORB.
1197    pub(crate) fn accepts_bidir(&self) -> bool {
1198        match *self.inner.bidir_override.lock().unwrap() {
1199            Some(v) => v == crate::Bidirectional::Both,
1200            None => self.inner.options.accept_bidir,
1201        }
1202    }
1203
1204    pub(crate) fn server(&self) -> Option<Arc<Server>> {
1205        self.inner.server.lock().unwrap().clone()
1206    }
1207
1208    /// The server side, if `host:port` is one of its endpoints (a TLS one
1209    /// if `tls`).
1210    pub(crate) fn local_server(&self, host: &str, port: u16, tls: bool) -> Option<Arc<Server>> {
1211        self.server().filter(|s| s.is_local(host, port, tls))
1212    }
1213
1214    /// The addresses the server side publishes in IORs, as host and port;
1215    /// empty until the RootPOA is used.
1216    pub fn endpoints(&self) -> Vec<(String, u16)> {
1217        self.server()
1218            .map(|s| s.published().to_vec())
1219            .unwrap_or_default()
1220    }
1221
1222    /// The TLS endpoints the server side publishes in IORs, as host and
1223    /// port; empty until the RootPOA is used.
1224    pub fn tls_endpoints(&self) -> Vec<(String, u16)> {
1225        self.server()
1226            .map(|s| s.published_tls().to_vec())
1227            .unwrap_or_default()
1228    }
1229
1230    /// `CORBA::ORB::run`: blocks until the ORB has shut down, running the
1231    /// requests of MAIN_THREAD_MODEL POAs meanwhile. Other requests are
1232    /// processed on the upcall threads whether or not a thread runs this.
1233    /// Several threads may run it at once.
1234    pub fn run(&self) {
1235        while !self.run_timeout(None) {}
1236    }
1237
1238    /// [`run`](Orb::run) for at most `timeout` (`None` for no limit).
1239    /// Returns true when the ORB has shut down, false when the time ran
1240    /// out. For a binding that must look at its own events, such as
1241    /// signals, while it runs the ORB.
1242    pub fn run_timeout(&self, timeout: Option<Duration>) -> bool {
1243        let deadline = timeout.map(|t| Instant::now() + t);
1244        let _main = MainThreadGuard::enter();
1245        let mut main = self.inner.main.lock().unwrap();
1246        loop {
1247            if let Some(job) = main.jobs.pop_front() {
1248                drop(main);
1249                run_job(job);
1250                main = self.inner.main.lock().unwrap();
1251                continue;
1252            }
1253            if main.stopped {
1254                return true;
1255            }
1256            main = match deadline {
1257                None => self.inner.main_cond.wait(main).unwrap(),
1258                Some(deadline) => {
1259                    let now = Instant::now();
1260                    if now >= deadline {
1261                        return false;
1262                    }
1263                    self.inner
1264                        .main_cond
1265                        .wait_timeout(main, deadline - now)
1266                        .unwrap()
1267                        .0
1268                }
1269            };
1270        }
1271    }
1272
1273    /// [`run`](Orb::run) for async code: resolves when the ORB has shut
1274    /// down. It does not run MAIN_THREAD_MODEL requests, which need
1275    /// [`run`](Orb::run) or [`perform_work`](Orb::perform_work) on a
1276    /// thread. With [`shutdown(false)`](Orb::shutdown), the way to shut the
1277    /// ORB down from async code and wait for it.
1278    pub async fn run_async(&self) {
1279        loop {
1280            let notified = std::pin::pin!(self.inner.stopped.notified());
1281            let mut notified = notified;
1282            notified.as_mut().enable();
1283            let stopped = self.inner.main.lock().unwrap().stopped;
1284            if stopped {
1285                return;
1286            }
1287            notified.await;
1288        }
1289    }
1290
1291    /// `CORBA::ORB::work_pending`: whether a MAIN_THREAD_MODEL request
1292    /// waits for [`perform_work`](Orb::perform_work). `BAD_INV_ORDER` after
1293    /// shutdown.
1294    pub fn work_pending(&self) -> Result<bool, SystemException> {
1295        self.check_running()?;
1296        Ok(!self.inner.main.lock().unwrap().jobs.is_empty())
1297    }
1298
1299    /// `CORBA::ORB::perform_work`: runs one waiting MAIN_THREAD_MODEL
1300    /// request on the calling thread, if there is one, and returns without
1301    /// waiting otherwise. For an application's own event loop.
1302    /// `BAD_INV_ORDER` after shutdown.
1303    pub fn perform_work(&self) -> Result<(), SystemException> {
1304        self.check_running()?;
1305        let job = self.inner.main.lock().unwrap().jobs.pop_front();
1306        if let Some(job) = job {
1307            let _main = MainThreadGuard::enter();
1308            run_job(job);
1309        }
1310        Ok(())
1311    }
1312
1313    /// `CORBA::ORB::shutdown`. Refuses new invocations (`BAD_INV_ORDER`)
1314    /// and new requests, drops the requests the POA managers hold, lets the
1315    /// running ones finish and send their replies, destroys every POA, and
1316    /// then closes every connection, client and server side, with
1317    /// `CloseConnection`. Invocations still waiting for a reply fail with
1318    /// `COMM_FAILURE` or `TRANSIENT`.
1319    ///
1320    /// With `wait_for_completion`, returns when all that is done; called
1321    /// from a servant it fails with `BAD_INV_ORDER` (would deadlock).
1322    /// Without it, the shutdown runs on another thread and the call returns
1323    /// at once, so a servant can call it and still send its reply.
1324    pub fn shutdown(&self, wait_for_completion: bool) -> Result<(), SystemException> {
1325        if wait_for_completion && poa::in_upcall() {
1326            return Err(SystemException::new(
1327                SystemExceptionKind::BAD_INV_ORDER,
1328                minor::WOULD_DEADLOCK,
1329                CompletionStatus::No,
1330            ));
1331        }
1332        if self.inner.shut_down.swap(true, Ordering::AcqRel) {
1333            if wait_for_completion {
1334                self.run();
1335            }
1336            return Ok(());
1337        }
1338        if wait_for_completion {
1339            // The shutdown blocks on the runtime, which cannot be done from
1340            // inside a runtime (the caller's own, say).
1341            if Handle::try_current().is_ok() {
1342                std::thread::scope(|s| {
1343                    let _ = s.spawn(|| self.complete_shutdown()).join();
1344                });
1345            } else {
1346                self.complete_shutdown();
1347            }
1348        } else {
1349            let orb = self.clone();
1350            std::thread::Builder::new()
1351                .name("rustorb-shutdown".into())
1352                .spawn(move || orb.complete_shutdown())
1353                .map_err(|_| {
1354                    SystemException::new(SystemExceptionKind::NO_RESOURCES, 0, CompletionStatus::No)
1355                })?;
1356        }
1357        Ok(())
1358    }
1359
1360    fn complete_shutdown(&self) {
1361        if let Some(server) = self.server() {
1362            server.shutdown(&self.inner.handle);
1363        }
1364        let conns: Vec<_> = self
1365            .inner
1366            .connections
1367            .lock()
1368            .unwrap()
1369            .drain()
1370            .map(|(_, c)| c)
1371            .collect();
1372        if let Some(task) = self.inner.idle_scan.get() {
1373            task.abort();
1374        }
1375        let version = self.inner.options.max_giop_version;
1376        let order = self.inner.options.byte_order;
1377        let _ = self.block_on(async move {
1378            for conn in conns {
1379                conn.close(Some((version, order))).await;
1380            }
1381        });
1382        self.inner.close_main();
1383        self.inner.main.lock().unwrap().stopped = true;
1384        self.inner.main_cond.notify_all();
1385        self.inner.stopped.notify_waiters();
1386    }
1387
1388    /// `CORBA::ORB::destroy`: [`shutdown(true)`](Orb::shutdown), and then
1389    /// ends the upcall threads. Fails like `shutdown(true)` when called
1390    /// from a servant.
1391    pub fn destroy(&self) -> Result<(), SystemException> {
1392        self.shutdown(true)?;
1393        if let Some(server) = self.inner.server.lock().unwrap().take() {
1394            server.stop_pool();
1395        }
1396        // The callbacks queued run on this thread (the pool drops them).
1397        let replies = std::mem::replace(&mut *self.inner.replies.lock().unwrap(), Err(()));
1398        drop(replies);
1399        // Local objects may hold the ORB.
1400        let registered = std::mem::take(&mut *self.inner.registered.lock().unwrap());
1401        drop(registered);
1402        // So may interceptors.
1403        self.inner.pi_on.store(false, Ordering::Release);
1404        let pi = self.inner.pi.lock().unwrap().take();
1405        if let Some(pi) = pi {
1406            pi.destroy();
1407        }
1408        Ok(())
1409    }
1410
1411    /// Runs `job` on the reply pool of [`CallbackRequest`]s, or on the
1412    /// calling thread once the ORB is destroyed.
1413    ///
1414    /// [`CallbackRequest`]: crate::CallbackRequest
1415    pub(crate) fn submit_reply(&self, job: Job) {
1416        let mut replies = self.inner.replies.lock().unwrap();
1417        match &mut *replies {
1418            Ok(pool) => {
1419                let options = &self.inner.options;
1420                pool.get_or_insert_with(|| {
1421                    crate::pool::Pool::new(
1422                        0,
1423                        options.max_server_threads,
1424                        options.server_thread_idle_timeout,
1425                    )
1426                })
1427                .submit(job);
1428            }
1429            Err(()) => {
1430                drop(replies);
1431                run_reply_job(job);
1432            }
1433        }
1434    }
1435
1436    pub(crate) fn check_running(&self) -> Result<(), SystemException> {
1437        if self.inner.shut_down.load(Ordering::Acquire) {
1438            return Err(SystemException::new(
1439                SystemExceptionKind::BAD_INV_ORDER,
1440                minor::ORB_SHUT_DOWN,
1441                CompletionStatus::No,
1442            ));
1443        }
1444        Ok(())
1445    }
1446
1447    /// `fut`, polled inside the ORB's runtime: the sockets, timers and
1448    /// tasks it makes belong to that runtime whichever executor polls it.
1449    pub(crate) fn in_runtime<F: Future>(&self, fut: F) -> InRuntime<F> {
1450        InRuntime {
1451            handle: self.inner.handle.clone(),
1452            fut: Box::pin(fut),
1453        }
1454    }
1455
1456    /// Runs `fut` on the ORB's runtime and waits for it.
1457    pub(crate) fn block_on<F: Future>(&self, fut: F) -> Result<F::Output, SystemException> {
1458        if Handle::try_current().is_ok() {
1459            return Err(SystemException::new(
1460                SystemExceptionKind::BAD_INV_ORDER,
1461                0,
1462                CompletionStatus::No,
1463            ));
1464        }
1465        Ok(self.inner.handle.block_on(fut))
1466    }
1467
1468    /// Whether this ORB can make TLS connections: it has CA certificates
1469    /// to check servers with.
1470    pub(crate) fn has_tls_client(&self) -> bool {
1471        self.inner.options.tls.ca_file.is_some()
1472    }
1473
1474    /// The configuration of client TLS connections. A configuration that
1475    /// cannot be loaded makes every TLS connection fail with `TRANSIENT`.
1476    fn tls_client(&self) -> Result<Arc<rustls::ClientConfig>, SystemException> {
1477        self.inner
1478            .tls_client
1479            .get_or_init(|| tls::client_config(&self.inner.options.tls))
1480            .clone()
1481            .map_err(|_| {
1482                SystemException::new(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No)
1483            })
1484    }
1485
1486    /// A usable connection to `host:port`, with TLS if `tls`, opened if
1487    /// needed.
1488    ///
1489    /// Connecting stops at the connect timeout, else at `deadline` (the
1490    /// end of the call), with `TIMEOUT`, completed no, like omniORB. The
1491    /// TLS handshake counts as part of connecting.
1492    pub(crate) async fn connection(
1493        &self,
1494        host: &str,
1495        port: u16,
1496        tls: bool,
1497        deadline: Option<Instant>,
1498    ) -> Result<Arc<Connection>, SystemException> {
1499        self.check_running()?;
1500        let key = (host.to_owned(), port, tls);
1501        if let Some(conn) = self.inner.connections.lock().unwrap().get(&key) {
1502            if conn.is_usable() {
1503                return Ok(Arc::clone(conn));
1504            }
1505        }
1506        let config = if tls { Some(self.tls_client()?) } else { None };
1507        if let Some(timeout) = self.inner.options.client_idle_timeout {
1508            self.inner.idle_scan.get_or_init(|| {
1509                self.inner.handle.spawn(close_idle(
1510                    Arc::downgrade(&self.inner.connections),
1511                    timeout,
1512                    self.inner.options.byte_order,
1513                ))
1514            });
1515        }
1516        let connect = Connection::connect(
1517            host,
1518            port,
1519            config,
1520            &self.inner.options,
1521            Arc::downgrade(&self.inner.connections),
1522        );
1523        let limit = match self.connect_timeout() {
1524            Some(t) => Some(Instant::now() + t),
1525            None => deadline,
1526        };
1527        let result = match limit {
1528            Some(at) => match tokio::time::timeout_at(at.into(), connect).await {
1529                Ok(result) => result,
1530                Err(_) => {
1531                    return Err(SystemException::new(
1532                        SystemExceptionKind::TIMEOUT,
1533                        0,
1534                        CompletionStatus::No,
1535                    ));
1536                }
1537            },
1538            None => connect.await,
1539        };
1540        let conn = result.map_err(|_| {
1541            SystemException::new(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No)
1542        })?;
1543        // Bidirectional GIOP: offered when the ORB has endpoints to give.
1544        if self.offers_bidir() {
1545            if let Some(server) = self.server() {
1546                let (serving, context) =
1547                    server.serve_connection(&conn, conn.inbound(), self.inner.handle.clone());
1548                if let Some(context) = context {
1549                    conn.serve(Arc::downgrade(&server), serving, context);
1550                }
1551            }
1552        }
1553        let mut conns = self.inner.connections.lock().unwrap();
1554        match conns.get(&key) {
1555            // Another caller connected first: use its connection, and
1556            // close this one (its reader task would keep it open).
1557            Some(existing) if existing.is_usable() => {
1558                tokio::spawn(async move { conn.close(None).await });
1559                Ok(Arc::clone(existing))
1560            }
1561            _ => {
1562                conns.insert(key, Arc::clone(&conn));
1563                Ok(conn)
1564            }
1565        }
1566    }
1567
1568    /// Drops `conn` from the pool, if it is still the pooled one.
1569    pub(crate) fn discard(&self, conn: &Arc<Connection>) {
1570        conn.leave_pool();
1571    }
1572}
1573
1574/// Closes the client connections of `pool` idle for `timeout`, until the
1575/// ORB is gone or shut down (which aborts the task).
1576async fn close_idle(
1577    pool: std::sync::Weak<ConnectionPool>,
1578    timeout: Duration,
1579    order: rustorb_cdr::ByteOrder,
1580) {
1581    let period = crate::idle::scan_period(timeout);
1582    loop {
1583        tokio::time::sleep(period).await;
1584        let Some(pool) = pool.upgrade() else {
1585            return;
1586        };
1587        let idle: Vec<_> = {
1588            let mut conns = pool.lock().unwrap();
1589            let idle: Vec<_> = conns
1590                .iter()
1591                .filter(|(_, c)| c.choose_idle(timeout))
1592                .map(|(key, _)| key.clone())
1593                .collect();
1594            idle.iter().filter_map(|key| conns.remove(key)).collect()
1595        };
1596        drop(pool);
1597        for conn in idle {
1598            trace::info!(
1599                "closing the connection to {}:{}: idle for {timeout:?}",
1600                conn.endpoint().0,
1601                conn.endpoint().1
1602            );
1603            tokio::spawn(async move { conn.close_idle(order).await });
1604        }
1605    }
1606}
1607
1608/// Runs a MAIN_THREAD_MODEL request. Requests catch the panics of user
1609/// code themselves; this keeps the loop going if anything else panics.
1610fn run_job(job: Job) {
1611    let _ = panic::catch_unwind(AssertUnwindSafe(job));
1612}
1613
1614/// Runs a reply callback that cannot go to the reply pool (the ORB is
1615/// destroyed, or it was dropped undelivered): on this thread, unless this
1616/// is a thread of a runtime, where the synchronous API the callback may
1617/// use fails; then on a thread of [`REPLY_FALLBACK`].
1618/// Sets SIGPIPE to be ignored, once, if nothing in the process has set it
1619/// (a Rust program ignores it already; a C++ one does not). The ORB writes
1620/// to sockets with `writev`, which raises SIGPIPE when the other side has
1621/// closed: the write should fail with EPIPE instead of ending the process.
1622#[cfg(unix)]
1623fn ignore_sigpipe() {
1624    static ONCE: std::sync::Once = std::sync::Once::new();
1625    ONCE.call_once(|| {
1626        // SAFETY: sigaction with a zeroed, then filled, struct; the old
1627        // action is kept unless it is the default one.
1628        unsafe {
1629            let mut old: libc::sigaction = std::mem::zeroed();
1630            if libc::sigaction(libc::SIGPIPE, std::ptr::null(), &mut old) == 0
1631                && old.sa_sigaction == libc::SIG_DFL
1632            {
1633                let mut ignore: libc::sigaction = std::mem::zeroed();
1634                ignore.sa_sigaction = libc::SIG_IGN;
1635                libc::sigemptyset(&mut ignore.sa_mask);
1636                libc::sigaction(libc::SIGPIPE, &ignore, std::ptr::null_mut());
1637            }
1638        }
1639    });
1640}
1641
1642#[cfg(not(unix))]
1643fn ignore_sigpipe() {}
1644
1645pub(crate) fn run_reply_job(job: Job) {
1646    if Handle::try_current().is_err() {
1647        run_job(job);
1648        return;
1649    }
1650    REPLY_FALLBACK
1651        .get_or_init(|| crate::pool::Pool::new(0, 64, Duration::from_secs(600)))
1652        .submit(job);
1653}
1654
1655/// The threads of the reply callbacks of [`run_reply_job`], for every
1656/// ORB. Threads that stay, rather than one started for each callback: a
1657/// JVM called on a thread that ended right after crashed now and then on
1658/// Windows.
1659static REPLY_FALLBACK: std::sync::OnceLock<crate::pool::Pool> = std::sync::OnceLock::new();
1660
1661/// See [`Orb::in_runtime`].
1662pub(crate) struct InRuntime<F> {
1663    handle: Handle,
1664    fut: std::pin::Pin<Box<F>>,
1665}
1666
1667impl<F: Future> Future for InRuntime<F> {
1668    type Output = F::Output;
1669
1670    fn poll(
1671        mut self: std::pin::Pin<&mut Self>,
1672        cx: &mut std::task::Context<'_>,
1673    ) -> std::task::Poll<F::Output> {
1674        let this = &mut *self;
1675        let _runtime = this.handle.enter();
1676        this.fut.as_mut().poll(cx)
1677    }
1678}