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