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