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