Skip to main content

rustorb_core/
pi.rs

1//! Portable Interceptors (`PortableInterceptor`): hooks on the requests an
2//! ORB sends and receives and on the references its POAs make.
3//!
4//! An [`OrbInitializer`], registered for every ORB
5//! ([`register_orb_initializer`]) or for one
6//! ([`OrbOptions::initializers`](crate::OrbOptions::initializers)), adds
7//! interceptors while the ORB is created:
8//!
9//! - a [`ClientRequestInterceptor`] sees each request the ORB sends, before
10//!   it goes out and when it ends;
11//! - a [`ServerRequestInterceptor`] sees each request the ORB's POAs
12//!   receive, before the servant runs and before the reply goes out;
13//! - an [`IorInterceptor`] adds tagged components to the references of a
14//!   new POA.
15//!
16//! Interceptors carry data in service contexts, usually encoded with an
17//! [`IOP::Codec`](crate::iop::Codec), and hand it to the application and
18//! back through the slots of [`PiCurrent`]. The design, and how rustorb
19//! fits the specification, is in docs/portable-interceptors.md.
20
21use std::cell::{Cell, RefCell};
22use std::collections::HashMap;
23use std::fmt;
24use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
25use std::sync::{Arc, Mutex};
26use std::time::Duration;
27
28use rustorb_giop::{Ior, TAG_INTERNET_IOP};
29pub use rustorb_giop::{ServiceContext, TaggedComponent, TaggedProfile};
30
31use crate::dii::{ArgMode, NamedValue};
32use crate::iop::CodecFactory;
33use crate::poa::{Policies, Policy};
34use crate::policy::{PolicyType, PolicyValue};
35use crate::typecode::TCKind;
36use crate::{
37    Any, CompletionStatus, Exception, ObjectRef, Orb, Poa, Reply, ResolveError, Servant,
38    SystemException, SystemExceptionKind, TypeCode, Value, trace,
39};
40
41/// Minor codes of the exceptions the interceptor interfaces raise.
42pub mod minor {
43    use crate::OMG_VMCID;
44
45    /// `BAD_INV_ORDER`: the attribute or operation cannot be used at this
46    /// interception point (or, on `ORBInitInfo`, at this stage).
47    pub const INVALID_POINT: u32 = OMG_VMCID | 14;
48    /// `BAD_INV_ORDER`: a service context with that id is there already,
49    /// and `replace` was false.
50    pub const DUPLICATE_SERVICE_CONTEXT: u32 = OMG_VMCID | 15;
51    /// `BAD_PARAM`: no service context with that id.
52    pub const NO_SERVICE_CONTEXT: u32 = OMG_VMCID | 26;
53    /// `BAD_PARAM`: no tagged component with that tag.
54    pub const NO_COMPONENT: u32 = OMG_VMCID | 28;
55    /// `BAD_PARAM`: a profile id other than `TAG_INTERNET_IOP`.
56    pub const UNKNOWN_PROFILE: u32 = OMG_VMCID | 29;
57    /// `NO_RESOURCES`: the language binding does not have the
58    /// information (arguments of a static stub, say).
59    pub const NOT_AVAILABLE: u32 = OMG_VMCID | 1;
60    /// `INV_POLICY`: the policy type is not allowed here.
61    pub const INVALID_POLICY_TYPE: u32 = OMG_VMCID | 2;
62    /// `OBJECT_NOT_EXIST`: the `ORBInitInfo` was used after the ORB was
63    /// created (a binding checks this).
64    pub const INIT_INFO_GONE: u32 = OMG_VMCID | 10;
65}
66
67/// `PortableInterceptor::ReplyStatus` values.
68pub mod reply_status {
69    /// `SUCCESSFUL`.
70    pub const SUCCESSFUL: i16 = 0;
71    /// `SYSTEM_EXCEPTION`.
72    pub const SYSTEM_EXCEPTION: i16 = 1;
73    /// `USER_EXCEPTION`.
74    pub const USER_EXCEPTION: i16 = 2;
75    /// `LOCATION_FORWARD`.
76    pub const LOCATION_FORWARD: i16 = 3;
77    /// `TRANSPORT_RETRY`.
78    pub const TRANSPORT_RETRY: i16 = 4;
79    /// `UNKNOWN`.
80    pub const UNKNOWN: i16 = 5;
81}
82
83/// `Messaging::SyncScope` values ([`ClientRequestInfo::sync_scope`]).
84pub mod sync_scope {
85    /// `SYNC_NONE`: a oneway request.
86    pub const SYNC_NONE: i16 = 0;
87    /// `SYNC_WITH_TRANSPORT`.
88    pub const SYNC_WITH_TRANSPORT: i16 = 1;
89    /// `SYNC_WITH_SERVER`.
90    pub const SYNC_WITH_SERVER: i16 = 2;
91    /// `SYNC_WITH_TARGET`: a request with a reply.
92    pub const SYNC_WITH_TARGET: i16 = 3;
93}
94
95/// `PortableInterceptor::SlotId`.
96pub type SlotId = u32;
97
98/// `PortableInterceptor::InvalidSlot`: no slot has this id.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub struct InvalidSlot;
101
102impl fmt::Display for InvalidSlot {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        f.write_str("PortableInterceptor::InvalidSlot")
105    }
106}
107
108impl std::error::Error for InvalidSlot {}
109
110/// `PortableInterceptor::ORBInitInfo::DuplicateName`: an interceptor of
111/// the same kind already has this name.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct DuplicateName(pub String);
114
115impl fmt::Display for DuplicateName {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        write!(f, "an interceptor named {:?} is registered already", self.0)
118    }
119}
120
121impl std::error::Error for DuplicateName {}
122
123/// What an interception point may raise besides returning: a system
124/// exception, or `PortableInterceptor::ForwardRequest` to send the request
125/// to another object.
126#[derive(Debug, Clone)]
127pub enum InterceptError {
128    /// A system exception, which becomes the result of the request.
129    System(SystemException),
130    /// `ForwardRequest`: the request goes to `forward` instead.
131    ForwardRequest(ObjectRef),
132}
133
134impl From<SystemException> for InterceptError {
135    fn from(e: SystemException) -> InterceptError {
136        InterceptError::System(e)
137    }
138}
139
140// --- registration --------------------------------------------------------------
141
142/// `PortableInterceptor::ORBInitializer`: adds interceptors and slots to
143/// an ORB while it is created.
144pub trait OrbInitializer: Send + Sync {
145    /// Called first, before the initial references of the ORB can be
146    /// resolved.
147    fn pre_init(&self, info: &mut OrbInitInfo<'_>) -> Result<(), SystemException> {
148        let _ = info;
149        Ok(())
150    }
151
152    /// Called after every initializer's `pre_init`.
153    fn post_init(&self, info: &mut OrbInitInfo<'_>) -> Result<(), SystemException> {
154        let _ = info;
155        Ok(())
156    }
157}
158
159impl fmt::Debug for dyn OrbInitializer {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        f.write_str("OrbInitializer")
162    }
163}
164
165static INITIALIZERS: Mutex<Vec<Arc<dyn OrbInitializer>>> = Mutex::new(Vec::new());
166
167/// `PortableInterceptor::register_orb_initializer`: runs `init` for every
168/// ORB created from now on in this process, before the initializers of
169/// [`OrbOptions::initializers`](crate::OrbOptions::initializers).
170pub fn register_orb_initializer(init: Arc<dyn OrbInitializer>) {
171    INITIALIZERS.lock().unwrap().push(init);
172}
173
174pub(crate) fn registered_initializers() -> Vec<Arc<dyn OrbInitializer>> {
175    INITIALIZERS.lock().unwrap().clone()
176}
177
178/// The interceptors and slots initializers add.
179#[derive(Default)]
180pub(crate) struct Additions {
181    client: Vec<Arc<dyn ClientRequestInterceptor>>,
182    server: Vec<Arc<dyn ServerRequestInterceptor>>,
183    ior: Vec<Arc<dyn IorInterceptor>>,
184    slots: u32,
185}
186
187impl Additions {
188    fn destroy(&self) {
189        for i in &self.client {
190            i.destroy();
191        }
192        for i in &self.server {
193            i.destroy();
194        }
195        for i in &self.ior {
196            i.destroy();
197        }
198    }
199}
200
201/// `PortableInterceptor::ORBInitInfo`, given to the initializers.
202pub struct OrbInitInfo<'a> {
203    orb: &'a Orb,
204    post: bool,
205    additions: &'a mut Additions,
206}
207
208impl fmt::Debug for OrbInitInfo<'_> {
209    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210        f.debug_struct("OrbInitInfo")
211            .field("post_init", &self.post)
212            .finish_non_exhaustive()
213    }
214}
215
216fn add_named<T: ?Sized + Interceptor>(
217    list: &mut Vec<Arc<T>>,
218    interceptor: Arc<T>,
219) -> Result<(), DuplicateName> {
220    let name = interceptor.name();
221    if !name.is_empty() && list.iter().any(|i| i.name() == name) {
222        return Err(DuplicateName(name.to_owned()));
223    }
224    list.push(interceptor);
225    Ok(())
226}
227
228impl OrbInitInfo<'_> {
229    /// `arguments`: the arguments the ORB was created with
230    /// ([`OrbOptions::arguments`](crate::OrbOptions::arguments)).
231    pub fn arguments(&self) -> &[String] {
232        &self.orb.inner.options.arguments
233    }
234
235    /// `orb_id` (`-ORBid`).
236    pub fn orb_id(&self) -> &str {
237        &self.orb.inner.options.orb_id
238    }
239
240    /// `codec_factory`.
241    pub fn codec_factory(&self) -> CodecFactory {
242        CodecFactory::new(self.orb)
243    }
244
245    /// The ORB being created. Calls on it may not work until it is.
246    pub fn orb(&self) -> &Orb {
247        self.orb
248    }
249
250    /// `register_initial_reference`, as [`Orb::register_initial_reference`].
251    pub fn register_initial_reference(
252        &self,
253        name: &str,
254        obj: Option<&ObjectRef>,
255    ) -> Result<(), ResolveError> {
256        self.orb.register_initial_reference(name, obj)
257    }
258
259    /// `resolve_initial_references`, only in `post_init` (`BAD_INV_ORDER`
260    /// in `pre_init`).
261    pub fn resolve_initial_references(&self, name: &str) -> Result<ObjectRef, ResolveError> {
262        if !self.post {
263            return Err(ResolveError::System(invalid_point()));
264        }
265        self.orb.resolve_initial_references(name)
266    }
267
268    /// `add_client_request_interceptor`. Names other than `""` must be
269    /// unique among the client interceptors.
270    pub fn add_client_request_interceptor(
271        &mut self,
272        interceptor: Arc<dyn ClientRequestInterceptor>,
273    ) -> Result<(), DuplicateName> {
274        add_named(&mut self.additions.client, interceptor)
275    }
276
277    /// `add_server_request_interceptor`.
278    pub fn add_server_request_interceptor(
279        &mut self,
280        interceptor: Arc<dyn ServerRequestInterceptor>,
281    ) -> Result<(), DuplicateName> {
282        add_named(&mut self.additions.server, interceptor)
283    }
284
285    /// `add_ior_interceptor`.
286    pub fn add_ior_interceptor(
287        &mut self,
288        interceptor: Arc<dyn IorInterceptor>,
289    ) -> Result<(), DuplicateName> {
290        add_named(&mut self.additions.ior, interceptor)
291    }
292
293    /// `allocate_slot_id`: a new slot of [`PiCurrent`].
294    pub fn allocate_slot_id(&mut self) -> SlotId {
295        self.additions.slots += 1;
296        self.additions.slots - 1
297    }
298
299    /// `register_policy_factory`: not supported yet (`NO_IMPLEMENT`).
300    pub fn register_policy_factory(
301        &mut self,
302        policy_type: PolicyType,
303    ) -> Result<(), SystemException> {
304        let _ = policy_type;
305        Err(SystemException::new(
306            SystemExceptionKind::NO_IMPLEMENT,
307            0,
308            CompletionStatus::No,
309        ))
310    }
311
312    /// The [`PiCurrent`] of the ORB, with the slots allocated so far.
313    pub fn pi_current(&self) -> PiCurrent {
314        PiCurrent {
315            serial: self.orb.inner.serial,
316            slots: self.additions.slots,
317        }
318    }
319}
320
321/// Runs the initializers of a new ORB. `Err` when one failed: the
322/// interceptors added are destroyed, and the ORB is not to be used.
323pub(crate) fn initialize(
324    orb: &Orb,
325    initializers: &[Arc<dyn OrbInitializer>],
326) -> Result<Option<Arc<Interceptors>>, SystemException> {
327    if initializers.is_empty() {
328        return Ok(None);
329    }
330    let mut additions = Additions::default();
331    for post in [false, true] {
332        for init in initializers {
333            let mut info = OrbInitInfo {
334                orb,
335                post,
336                additions: &mut additions,
337            };
338            let result = if post {
339                init.post_init(&mut info)
340            } else {
341                init.pre_init(&mut info)
342            };
343            if let Err(e) = result {
344                trace::warning!(
345                    "ORBInitializer {} raised {e}: the ORB is not created",
346                    if post { "post_init" } else { "pre_init" }
347                );
348                additions.destroy();
349                return Err(e);
350            }
351        }
352    }
353    if additions.client.is_empty()
354        && additions.server.is_empty()
355        && additions.ior.is_empty()
356        && additions.slots == 0
357    {
358        return Ok(None);
359    }
360    Ok(Some(Arc::new(Interceptors {
361        serial: orb.inner.serial,
362        client: additions.client,
363        server: additions.server,
364        ior: additions.ior,
365        slots: additions.slots,
366        next_request_id: AtomicU32::new(0),
367    })))
368}
369
370/// The interceptors and slots of one ORB, fixed once it is created.
371pub(crate) struct Interceptors {
372    serial: u64,
373    pub(crate) client: Vec<Arc<dyn ClientRequestInterceptor>>,
374    pub(crate) server: Vec<Arc<dyn ServerRequestInterceptor>>,
375    pub(crate) ior: Vec<Arc<dyn IorInterceptor>>,
376    pub(crate) slots: u32,
377    next_request_id: AtomicU32,
378}
379
380impl Interceptors {
381    /// Calls `destroy` on every interceptor (`ORB::destroy`).
382    pub(crate) fn destroy(&self) {
383        for i in &self.client {
384            i.destroy();
385        }
386        for i in &self.server {
387            i.destroy();
388        }
389        for i in &self.ior {
390            i.destroy();
391        }
392    }
393
394    pub(crate) fn has_client(&self) -> bool {
395        !self.client.is_empty()
396    }
397
398    pub(crate) fn has_server(&self) -> bool {
399        !self.server.is_empty()
400    }
401}
402
403static NEXT_SERIAL: AtomicU64 = AtomicU64::new(1);
404
405/// A number for an ORB that is never used again, to keep the slots of
406/// [`PiCurrent`] apart.
407pub(crate) fn new_serial() -> u64 {
408    NEXT_SERIAL.fetch_add(1, Ordering::Relaxed)
409}
410
411// --- interceptors --------------------------------------------------------------
412
413/// `PortableInterceptor::Interceptor`: what every interceptor has.
414pub trait Interceptor: Send + Sync {
415    /// `name`; `""` for an anonymous interceptor.
416    fn name(&self) -> &str;
417
418    /// `destroy`: called once, when the ORB is destroyed.
419    fn destroy(&self) {}
420}
421
422/// `PortableInterceptor::ClientRequestInterceptor`.
423///
424/// For each attempt to send a request (one address of the target, see
425/// docs/portable-interceptors.md), `send_request` is called on each
426/// interceptor in the order they were added, and then one of
427/// `receive_reply`, `receive_exception` or `receive_other` in the reverse
428/// order, on those whose `send_request` returned `Ok`. They run on the
429/// thread that makes the call (for an async call, the thread that polls
430/// it): keep them short.
431pub trait ClientRequestInterceptor: Interceptor {
432    /// Before the request is sent: may add service contexts.
433    fn send_request(&self, ri: &ClientRequestInfo<'_>) -> Result<(), InterceptError> {
434        let _ = ri;
435        Ok(())
436    }
437
438    /// `send_poll`: never called (rustorb has no time-independent
439    /// invocations).
440    fn send_poll(&self, ri: &ClientRequestInfo<'_>) -> Result<(), SystemException> {
441        let _ = ri;
442        Ok(())
443    }
444
445    /// After a normal reply.
446    fn receive_reply(&self, ri: &ClientRequestInfo<'_>) -> Result<(), SystemException> {
447        let _ = ri;
448        Ok(())
449    }
450
451    /// After an exception, from the server or from the ORB.
452    fn receive_exception(&self, ri: &ClientRequestInfo<'_>) -> Result<(), InterceptError> {
453        let _ = ri;
454        Ok(())
455    }
456
457    /// After another outcome: a forward, a retry, or a oneway request
458    /// sent.
459    fn receive_other(&self, ri: &ClientRequestInfo<'_>) -> Result<(), InterceptError> {
460        let _ = ri;
461        Ok(())
462    }
463}
464
465/// `PortableInterceptor::ServerRequestInterceptor`.
466///
467/// For each request, `receive_request_service_contexts` is called on each
468/// interceptor in the order they were added, then `receive_request` on
469/// each, the servant, and one of `send_reply`, `send_exception` or
470/// `send_other` in the reverse order. They all run on the thread the
471/// servant runs on.
472pub trait ServerRequestInterceptor: Interceptor {
473    /// Before the servant is found: reads the service contexts and keeps
474    /// what it needs in the slots ([`ServerRequestInfo::set_slot`]).
475    fn receive_request_service_contexts(
476        &self,
477        ri: &ServerRequestInfo<'_>,
478    ) -> Result<(), InterceptError> {
479        let _ = ri;
480        Ok(())
481    }
482
483    /// Just before the servant runs, on its thread.
484    fn receive_request(&self, ri: &ServerRequestInfo<'_>) -> Result<(), InterceptError> {
485        let _ = ri;
486        Ok(())
487    }
488
489    /// Before a normal reply goes out.
490    fn send_reply(&self, ri: &ServerRequestInfo<'_>) -> Result<(), SystemException> {
491        let _ = ri;
492        Ok(())
493    }
494
495    /// Before an exception reply goes out.
496    fn send_exception(&self, ri: &ServerRequestInfo<'_>) -> Result<(), InterceptError> {
497        let _ = ri;
498        Ok(())
499    }
500
501    /// Before another reply (a forward) goes out.
502    fn send_other(&self, ri: &ServerRequestInfo<'_>) -> Result<(), InterceptError> {
503        let _ = ri;
504        Ok(())
505    }
506}
507
508/// `PortableInterceptor::IORInterceptor`.
509pub trait IorInterceptor: Interceptor {
510    /// Adds the tagged components of the references of a new POA. Called
511    /// on the thread that creates the POA. An error is ignored (with a
512    /// warning).
513    fn establish_components(&self, info: &IorInfo<'_>) -> Result<(), SystemException>;
514}
515
516// --- PICurrent -----------------------------------------------------------------
517
518thread_local! {
519    /// The thread scope slots of each ORB, by serial.
520    static THREAD_SLOTS: RefCell<HashMap<u64, Vec<Any>>> = RefCell::new(HashMap::new());
521}
522
523fn empty_slot() -> Any {
524    Any::new(TypeCode::null(), Value::Void)
525}
526
527/// `PortableInterceptor::Current` of an ORB ([`Orb::pi_current`]): the
528/// slots of the calling thread. A request copies them when it starts, so
529/// client interceptors see what the application set; a server
530/// interceptor's slots are what the servant sees.
531#[derive(Debug, Clone)]
532pub struct PiCurrent {
533    serial: u64,
534    slots: u32,
535}
536
537impl PiCurrent {
538    pub(crate) fn new(orb: &Orb) -> PiCurrent {
539        PiCurrent {
540            serial: orb.inner.serial,
541            slots: orb.interceptors().map_or(0, |pi| pi.slots),
542        }
543    }
544
545    /// `get_slot`: the value of slot `id` for this thread; an Any of type
546    /// `null` when it has none.
547    pub fn get_slot(&self, id: SlotId) -> Result<Any, InvalidSlot> {
548        if id >= self.slots {
549            return Err(InvalidSlot);
550        }
551        Ok(THREAD_SLOTS.with(|t| {
552            t.borrow()
553                .get(&self.serial)
554                .and_then(|s| s.get(id as usize))
555                .cloned()
556                .unwrap_or_else(empty_slot)
557        }))
558    }
559
560    /// `set_slot`.
561    pub fn set_slot(&self, id: SlotId, data: Any) -> Result<(), InvalidSlot> {
562        if id >= self.slots {
563            return Err(InvalidSlot);
564        }
565        THREAD_SLOTS.with(|t| {
566            let mut t = t.borrow_mut();
567            let slots = t
568                .entry(self.serial)
569                .or_insert_with(|| vec![empty_slot(); self.slots as usize]);
570            if slots.len() < self.slots as usize {
571                slots.resize_with(self.slots as usize, empty_slot);
572            }
573            slots[id as usize] = data;
574        });
575        Ok(())
576    }
577}
578
579/// The thread scope slots of the ORB `pi` belongs to, copied: the request
580/// scope slots of a new request.
581pub(crate) fn thread_slots(pi: &Interceptors) -> Vec<Any> {
582    THREAD_SLOTS.with(|t| {
583        let mut slots = t.borrow().get(&pi.serial).cloned().unwrap_or_default();
584        slots.resize_with(pi.slots as usize, empty_slot);
585        slots
586    })
587}
588
589/// Sets the thread scope slots while it lives, and puts the old ones back
590/// after.
591pub(crate) struct ThreadSlotsGuard {
592    serial: u64,
593    old: Option<Vec<Any>>,
594}
595
596impl ThreadSlotsGuard {
597    fn enter(serial: u64, slots: Vec<Any>) -> ThreadSlotsGuard {
598        let old = THREAD_SLOTS.with(|t| t.borrow_mut().insert(serial, slots));
599        ThreadSlotsGuard { serial, old }
600    }
601}
602
603impl Drop for ThreadSlotsGuard {
604    fn drop(&mut self) {
605        let old = self.old.take();
606        // The thread may be ending (its locals going away).
607        let _ = THREAD_SLOTS.try_with(|t| match old {
608            Some(old) => {
609                t.borrow_mut().insert(self.serial, old);
610            }
611            None => {
612                t.borrow_mut().remove(&self.serial);
613            }
614        });
615    }
616}
617
618// --- request information ---------------------------------------------------------
619
620fn invalid_point() -> SystemException {
621    SystemException::new(
622        SystemExceptionKind::BAD_INV_ORDER,
623        minor::INVALID_POINT,
624        CompletionStatus::No,
625    )
626}
627
628fn not_available() -> SystemException {
629    SystemException::new(
630        SystemExceptionKind::NO_RESOURCES,
631        minor::NOT_AVAILABLE,
632        CompletionStatus::No,
633    )
634}
635
636fn no_context() -> SystemException {
637    SystemException::new(
638        SystemExceptionKind::BAD_PARAM,
639        minor::NO_SERVICE_CONTEXT,
640        CompletionStatus::No,
641    )
642}
643
644fn duplicate_context() -> SystemException {
645    SystemException::new(
646        SystemExceptionKind::BAD_INV_ORDER,
647        minor::DUPLICATE_SERVICE_CONTEXT,
648        CompletionStatus::No,
649    )
650}
651
652/// `Dynamic::Parameter`: an argument and its direction.
653#[derive(Debug, Clone)]
654pub struct Parameter {
655    /// The value; for an `out` argument before the reply, an Any of its
656    /// type holding `Value::Void`.
657    pub argument: Any,
658    /// `in`, `out` or `inout`.
659    pub mode: ArgMode,
660}
661
662fn parameters(list: &[NamedValue]) -> Vec<Parameter> {
663    list.iter()
664        .map(|nv| Parameter {
665            argument: nv.value.clone(),
666            mode: nv.mode,
667        })
668        .collect()
669}
670
671/// The ids rustorb writes itself; interceptors cannot add them.
672fn is_core_context(id: u32) -> bool {
673    id == rustorb_giop::service_id::CODE_SETS || id == rustorb_giop::service_id::BI_DIR_IIOP
674}
675
676fn find_context(list: &[ServiceContext], id: u32) -> Result<ServiceContext, SystemException> {
677    list.iter()
678        .find(|c| c.context_id == id)
679        .cloned()
680        .ok_or_else(no_context)
681}
682
683fn add_context(
684    list: &mut Vec<ServiceContext>,
685    sc: ServiceContext,
686    replace: bool,
687) -> Result<(), SystemException> {
688    match list.iter_mut().find(|c| c.context_id == sc.context_id) {
689        Some(_) if !replace => Err(duplicate_context()),
690        Some(old) => {
691            *old = sc;
692            Ok(())
693        }
694        None => {
695            list.push(sc);
696            Ok(())
697        }
698    }
699}
700
701/// The TypeCode of a system exception: `minor` and `completed`.
702fn system_exception_tc(id: &str) -> TypeCode {
703    let completion = TypeCode::enum_tc(
704        "IDL:omg.org/CORBA/CompletionStatus:1.0",
705        "CompletionStatus",
706        &["COMPLETED_YES", "COMPLETED_NO", "COMPLETED_MAYBE"],
707    )
708    .expect("a valid enum");
709    let name = id
710        .rsplit('/')
711        .next()
712        .and_then(|n| n.split(':').next())
713        .unwrap_or("UNKNOWN");
714    TypeCode::exception(
715        id,
716        name,
717        &[
718            ("minor", TypeCode::simple(TCKind::ULong).expect("simple")),
719            ("completed", completion),
720        ],
721    )
722    .unwrap_or_else(|_| TypeCode::null())
723}
724
725/// A system exception as an Any.
726pub fn system_exception_any(e: &SystemException) -> Any {
727    let completed = match e.completed {
728        CompletionStatus::Yes => 0,
729        CompletionStatus::No => 1,
730        CompletionStatus::Maybe => 2,
731    };
732    Any::new(
733        system_exception_tc(&e.repository_id),
734        Value::List(vec![Value::ULong(e.minor), Value::Enum(completed)]),
735    )
736}
737
738fn unknown_any() -> Any {
739    system_exception_any(&SystemException::new(
740        SystemExceptionKind::UNKNOWN,
741        crate::minor::UNLISTED_USER_EXCEPTION,
742        CompletionStatus::Yes,
743    ))
744}
745
746/// What the DII gives the client interceptors: the arguments, the result
747/// type and the exception list.
748#[derive(Debug, Clone)]
749pub(crate) struct DiiParams {
750    pub(crate) arguments: Vec<NamedValue>,
751    pub(crate) result: TypeCode,
752    pub(crate) exceptions: Vec<TypeCode>,
753}
754
755/// The client interception points.
756#[derive(Debug, Clone, Copy, PartialEq, Eq)]
757pub enum ClientPoint {
758    /// `send_request`.
759    SendRequest,
760    /// `send_poll`.
761    SendPoll,
762    /// `receive_reply`.
763    ReceiveReply,
764    /// `receive_exception`.
765    ReceiveException,
766    /// `receive_other`.
767    ReceiveOther,
768}
769
770/// `PortableInterceptor::ClientRequestInfo`: one request as the client
771/// interceptors see it, during one interception point.
772pub struct ClientRequestInfo<'a> {
773    point: Cell<ClientPoint>,
774    request_id: u32,
775    operation: &'a str,
776    response_expected: bool,
777    sync_scope: i16,
778    target: &'a ObjectRef,
779    effective_target: ObjectRef,
780    effective_profile: TaggedProfile,
781    timeout: Option<Duration>,
782    slots: Vec<Any>,
783    dii: Option<&'a DiiParams>,
784    request_contexts: RefCell<Vec<ServiceContext>>,
785    reply_contexts: RefCell<Vec<ServiceContext>>,
786    reply_status: Cell<i16>,
787    exception: RefCell<Option<Exception>>,
788    forward: RefCell<Option<ObjectRef>>,
789    reply: RefCell<Option<Reply>>,
790}
791
792impl fmt::Debug for ClientRequestInfo<'_> {
793    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
794        f.debug_struct("ClientRequestInfo")
795            .field("point", &self.point.get())
796            .field("request_id", &self.request_id)
797            .field("operation", &self.operation)
798            .finish_non_exhaustive()
799    }
800}
801
802/// The parts of a request [`ClientRequestInfo::new`] takes.
803pub(crate) struct ClientRequest<'a> {
804    pub(crate) operation: &'a str,
805    pub(crate) response_expected: bool,
806    /// The `Messaging::SyncScope` of a oneway request.
807    pub(crate) sync_scope: i16,
808    pub(crate) target: &'a ObjectRef,
809    pub(crate) effective: Arc<Ior>,
810    pub(crate) profile_index: Option<usize>,
811    pub(crate) timeout: Option<Duration>,
812    pub(crate) slots: Vec<Any>,
813    pub(crate) dii: Option<&'a DiiParams>,
814}
815
816impl<'a> ClientRequestInfo<'a> {
817    pub(crate) fn new(pi: &Interceptors, r: ClientRequest<'a>) -> ClientRequestInfo<'a> {
818        let effective_profile = r
819            .profile_index
820            .and_then(|i| r.effective.profiles.get(i))
821            .cloned()
822            .unwrap_or(TaggedProfile {
823                tag: TAG_INTERNET_IOP,
824                profile_data: Vec::new(),
825            });
826        let effective_target = if Arc::ptr_eq(&r.effective, &r.target.ior_arc()) {
827            r.target.clone()
828        } else {
829            ObjectRef::new(r.target.orb().clone(), (*r.effective).clone())
830        };
831        ClientRequestInfo {
832            point: Cell::new(ClientPoint::SendRequest),
833            request_id: pi.next_request_id.fetch_add(1, Ordering::Relaxed),
834            operation: r.operation,
835            response_expected: r.response_expected,
836            sync_scope: r.sync_scope,
837            target: r.target,
838            effective_target,
839            effective_profile,
840            timeout: r.timeout,
841            slots: r.slots,
842            dii: r.dii,
843            request_contexts: RefCell::new(Vec::new()),
844            reply_contexts: RefCell::new(Vec::new()),
845            reply_status: Cell::new(reply_status::SUCCESSFUL),
846            exception: RefCell::new(None),
847            forward: RefCell::new(None),
848            reply: RefCell::new(None),
849        }
850    }
851
852    fn check(&self, allowed: &[ClientPoint]) -> Result<(), SystemException> {
853        if allowed.contains(&self.point.get()) {
854            Ok(())
855        } else {
856            Err(invalid_point())
857        }
858    }
859
860    fn after_send(&self) -> Result<(), SystemException> {
861        use ClientPoint::*;
862        self.check(&[ReceiveReply, ReceiveException, ReceiveOther])
863    }
864
865    /// The interception point being run.
866    pub fn point(&self) -> ClientPoint {
867        self.point.get()
868    }
869
870    /// `request_id`: unique among the requests of this ORB in progress
871    /// (not the GIOP request id).
872    pub fn request_id(&self) -> u32 {
873        self.request_id
874    }
875
876    /// `operation`.
877    pub fn operation(&self) -> &str {
878        self.operation
879    }
880
881    /// `arguments`: only for a DII request (else `NO_RESOURCES`), in
882    /// `send_request` and `receive_reply`.
883    pub fn arguments(&self) -> Result<Vec<Parameter>, SystemException> {
884        use ClientPoint::*;
885        self.check(&[SendRequest, ReceiveReply])?;
886        let dii = self.dii.ok_or_else(not_available)?;
887        if self.point.get() == SendRequest {
888            return Ok(parameters(&dii.arguments));
889        }
890        let (_, out) = self.decode_reply(dii)?;
891        let mut out = out.into_iter();
892        Ok(dii
893            .arguments
894            .iter()
895            .map(|nv| Parameter {
896                argument: if nv.mode.is_out() {
897                    out.next().unwrap_or_else(|| nv.value.clone())
898                } else {
899                    nv.value.clone()
900                },
901                mode: nv.mode,
902            })
903            .collect())
904    }
905
906    /// The result and the `out` values of a DII reply.
907    fn decode_reply(&self, dii: &DiiParams) -> Result<(Any, Vec<Any>), SystemException> {
908        let reply = self.reply.borrow();
909        let reply = reply.as_ref().ok_or_else(not_available)?;
910        let mut input = reply.input();
911        let result = Any::new(dii.result.clone(), input.read_value(&dii.result)?);
912        let mut out = Vec::new();
913        for nv in dii.arguments.iter().filter(|nv| nv.mode.is_out()) {
914            let tc = nv.value.typecode().clone();
915            let value = input.read_value(&tc)?;
916            out.push(Any::new(tc, value));
917        }
918        Ok((result, out))
919    }
920
921    /// `exceptions`: the exception list of a DII request.
922    pub fn exceptions(&self) -> Result<Vec<TypeCode>, SystemException> {
923        self.check_not_poll()?;
924        Ok(self.dii.ok_or_else(not_available)?.exceptions.clone())
925    }
926
927    fn check_not_poll(&self) -> Result<(), SystemException> {
928        if self.point.get() == ClientPoint::SendPoll {
929            Err(invalid_point())
930        } else {
931            Ok(())
932        }
933    }
934
935    /// `contexts`: `NO_RESOURCES` (rustorb has no `context` clauses).
936    pub fn contexts(&self) -> Result<Vec<String>, SystemException> {
937        self.check_not_poll()?;
938        Err(not_available())
939    }
940
941    /// `operation_context`: `NO_RESOURCES`.
942    pub fn operation_context(&self) -> Result<Vec<String>, SystemException> {
943        self.check_not_poll()?;
944        Err(not_available())
945    }
946
947    /// `result`: only in `receive_reply` of a DII request.
948    pub fn result(&self) -> Result<Any, SystemException> {
949        self.check(&[ClientPoint::ReceiveReply])?;
950        let dii = self.dii.ok_or_else(not_available)?;
951        Ok(self.decode_reply(dii)?.0)
952    }
953
954    /// `response_expected`.
955    pub fn response_expected(&self) -> bool {
956        self.response_expected
957    }
958
959    /// `sync_scope`: the `Messaging::SyncScope` the request is sent with,
960    /// from the `SyncScopePolicy` in effect for a oneway request, and
961    /// `SYNC_WITH_TARGET` for a two-way one.
962    pub fn sync_scope(&self) -> i16 {
963        if self.response_expected {
964            sync_scope::SYNC_WITH_TARGET
965        } else {
966            self.sync_scope
967        }
968    }
969
970    /// `reply_status` ([`reply_status`]).
971    pub fn reply_status(&self) -> Result<i16, SystemException> {
972        self.after_send()?;
973        Ok(self.reply_status.get())
974    }
975
976    /// `forward_reference`: in `receive_other` of a `LOCATION_FORWARD`.
977    pub fn forward_reference(&self) -> Result<ObjectRef, SystemException> {
978        self.check(&[ClientPoint::ReceiveOther])?;
979        self.forward.borrow().clone().ok_or_else(invalid_point)
980    }
981
982    /// `get_slot`: the request's copy of the slots.
983    pub fn get_slot(&self, id: SlotId) -> Result<Any, InvalidSlot> {
984        self.slots.get(id as usize).cloned().ok_or(InvalidSlot)
985    }
986
987    /// `get_request_service_context`: one the interceptors added (the ones
988    /// rustorb writes itself, such as `CodeSets`, are not here).
989    pub fn get_request_service_context(&self, id: u32) -> Result<ServiceContext, SystemException> {
990        self.check_not_poll()?;
991        find_context(&self.request_contexts.borrow(), id)
992    }
993
994    /// `get_reply_service_context`.
995    pub fn get_reply_service_context(&self, id: u32) -> Result<ServiceContext, SystemException> {
996        self.after_send()?;
997        find_context(&self.reply_contexts.borrow(), id)
998    }
999
1000    /// `target`: the reference the call was made on.
1001    pub fn target(&self) -> &ObjectRef {
1002        self.target
1003    }
1004
1005    /// `effective_target`: where the request goes, after forwards.
1006    pub fn effective_target(&self) -> &ObjectRef {
1007        &self.effective_target
1008    }
1009
1010    /// `effective_profile`: the profile of the address being tried.
1011    pub fn effective_profile(&self) -> &TaggedProfile {
1012        &self.effective_profile
1013    }
1014
1015    /// `received_exception`: in `receive_exception`. A user exception
1016    /// whose TypeCode is not known (anything but a DII request with an
1017    /// exception list) is an Any of `UNKNOWN`.
1018    pub fn received_exception(&self) -> Result<Any, SystemException> {
1019        self.check(&[ClientPoint::ReceiveException])?;
1020        match &*self.exception.borrow() {
1021            Some(Exception::System(e)) => Ok(system_exception_any(e)),
1022            Some(Exception::User(e)) => Ok(self
1023                .dii
1024                .and_then(|dii| crate::dii::exception_any(&dii.exceptions, e).ok())
1025                .unwrap_or_else(unknown_any)),
1026            None => Err(invalid_point()),
1027        }
1028    }
1029
1030    /// `received_exception_id`.
1031    pub fn received_exception_id(&self) -> Result<String, SystemException> {
1032        self.check(&[ClientPoint::ReceiveException])?;
1033        match &*self.exception.borrow() {
1034            Some(e) => Ok(e.repository_id().to_owned()),
1035            None => Err(invalid_point()),
1036        }
1037    }
1038
1039    /// The exception, in `receive_exception` (rustorb).
1040    pub fn exception(&self) -> Option<Exception> {
1041        self.exception.borrow().clone()
1042    }
1043
1044    fn components(&self) -> Vec<TaggedComponent> {
1045        self.effective_profile
1046            .iiop()
1047            .map(|p| p.components)
1048            .unwrap_or_default()
1049    }
1050
1051    /// `get_effective_component`: the first component with `tag` in the
1052    /// effective profile (`BAD_PARAM` if none).
1053    pub fn get_effective_component(&self, tag: u32) -> Result<TaggedComponent, SystemException> {
1054        self.components()
1055            .into_iter()
1056            .find(|c| c.tag == tag)
1057            .ok_or_else(no_component)
1058    }
1059
1060    /// `get_effective_components`.
1061    pub fn get_effective_components(
1062        &self,
1063        tag: u32,
1064    ) -> Result<Vec<TaggedComponent>, SystemException> {
1065        let found: Vec<_> = self
1066            .components()
1067            .into_iter()
1068            .filter(|c| c.tag == tag)
1069            .collect();
1070        if found.is_empty() {
1071            Err(no_component())
1072        } else {
1073            Ok(found)
1074        }
1075    }
1076
1077    /// `get_request_policy`: the client policy of `policy_type` in effect
1078    /// (`None` if none is). `INV_POLICY` for a type that is not a client
1079    /// policy.
1080    pub fn get_request_policy(
1081        &self,
1082        policy_type: PolicyType,
1083    ) -> Result<Option<PolicyValue>, SystemException> {
1084        match policy_type {
1085            crate::policy::RELATIVE_RT_TIMEOUT_POLICY_TYPE => Ok(self.timeout.map(|t| {
1086                PolicyValue::RelativeRoundtripTimeout(crate::timeout::duration_to_time_t(t))
1087            })),
1088            crate::policy::SYNC_SCOPE_POLICY_TYPE => Ok(self.target.client_policy(policy_type)),
1089            _ => Err(SystemException::new(
1090                SystemExceptionKind::INV_POLICY,
1091                minor::INVALID_POLICY_TYPE,
1092                CompletionStatus::No,
1093            )),
1094        }
1095    }
1096
1097    /// `add_request_service_context`: in `send_request`.
1098    pub fn add_request_service_context(
1099        &self,
1100        sc: ServiceContext,
1101        replace: bool,
1102    ) -> Result<(), SystemException> {
1103        self.check(&[ClientPoint::SendRequest])?;
1104        if is_core_context(sc.context_id) {
1105            return Err(duplicate_context());
1106        }
1107        add_context(&mut self.request_contexts.borrow_mut(), sc, replace)
1108    }
1109
1110    pub(crate) fn take_request_contexts(&self) -> Vec<ServiceContext> {
1111        self.request_contexts.borrow().clone()
1112    }
1113
1114    fn enter(&self, ending: &ClientEnding) {
1115        *self.exception.borrow_mut() = None;
1116        *self.forward.borrow_mut() = None;
1117        let (point, status) = match ending {
1118            ClientEnding::Reply(_) => (ClientPoint::ReceiveReply, reply_status::SUCCESSFUL),
1119            ClientEnding::Oneway => (ClientPoint::ReceiveOther, reply_status::SUCCESSFUL),
1120            ClientEnding::Exception(e) => {
1121                *self.exception.borrow_mut() = Some(e.clone());
1122                let status = match e {
1123                    Exception::System(_) => reply_status::SYSTEM_EXCEPTION,
1124                    Exception::User(_) => reply_status::USER_EXCEPTION,
1125                };
1126                (ClientPoint::ReceiveException, status)
1127            }
1128            ClientEnding::Forward(to) => {
1129                *self.forward.borrow_mut() = Some(to.clone());
1130                (ClientPoint::ReceiveOther, reply_status::LOCATION_FORWARD)
1131            }
1132            ClientEnding::Retry => (ClientPoint::ReceiveOther, reply_status::TRANSPORT_RETRY),
1133        };
1134        if let ClientEnding::Reply(reply) = ending {
1135            *self.reply.borrow_mut() = Some(reply.clone());
1136        }
1137        self.point.set(point);
1138        self.reply_status.set(status);
1139    }
1140
1141    pub(crate) fn set_reply_contexts(&self, contexts: Vec<ServiceContext>) {
1142        *self.reply_contexts.borrow_mut() = contexts;
1143    }
1144}
1145
1146fn no_component() -> SystemException {
1147    SystemException::new(
1148        SystemExceptionKind::BAD_PARAM,
1149        minor::NO_COMPONENT,
1150        CompletionStatus::No,
1151    )
1152}
1153
1154/// How a client interception ends.
1155#[derive(Debug, Clone)]
1156pub(crate) enum ClientEnding {
1157    /// A normal reply.
1158    Reply(Reply),
1159    /// A oneway request was sent.
1160    Oneway,
1161    Exception(Exception),
1162    Forward(ObjectRef),
1163    /// The ORB sends the request again.
1164    Retry,
1165}
1166
1167impl ClientEnding {
1168    fn from_error(e: InterceptError) -> ClientEnding {
1169        match e {
1170            InterceptError::System(e) => ClientEnding::Exception(Exception::System(e)),
1171            InterceptError::ForwardRequest(to) => ClientEnding::Forward(to),
1172        }
1173    }
1174}
1175
1176/// Runs `send_request` on each interceptor. `Err` is how the interception
1177/// ended when one of them raised: the request is not sent.
1178pub(crate) fn send_request(
1179    pi: &Interceptors,
1180    info: &ClientRequestInfo<'_>,
1181) -> Result<(), ClientEnding> {
1182    info.point.set(ClientPoint::SendRequest);
1183    for (k, i) in pi.client.iter().enumerate() {
1184        if let Err(e) = catch_client(|| i.send_request(info)) {
1185            return Err(end_client(pi, info, ClientEnding::from_error(e), k));
1186        }
1187    }
1188    Ok(())
1189}
1190
1191/// Runs the ending points on every interceptor, in the reverse order, and
1192/// returns how the request ends.
1193pub(crate) fn receive(
1194    pi: &Interceptors,
1195    info: &ClientRequestInfo<'_>,
1196    ending: ClientEnding,
1197) -> ClientEnding {
1198    end_client(pi, info, ending, pi.client.len())
1199}
1200
1201fn end_client(
1202    pi: &Interceptors,
1203    info: &ClientRequestInfo<'_>,
1204    mut ending: ClientEnding,
1205    started: usize,
1206) -> ClientEnding {
1207    for i in pi.client[..started].iter().rev() {
1208        info.enter(&ending);
1209        let result = match &ending {
1210            ClientEnding::Reply(_) => {
1211                catch_client(|| i.receive_reply(info).map_err(InterceptError::System))
1212            }
1213            ClientEnding::Exception(_) => catch_client(|| i.receive_exception(info)),
1214            ClientEnding::Oneway | ClientEnding::Forward(_) | ClientEnding::Retry => {
1215                catch_client(|| i.receive_other(info))
1216            }
1217        };
1218        if let Err(e) = result {
1219            ending = ClientEnding::from_error(e);
1220        }
1221    }
1222    ending
1223}
1224
1225fn catch_client(f: impl FnOnce() -> Result<(), InterceptError>) -> Result<(), InterceptError> {
1226    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| {
1227        trace::warning!("client request interceptor panicked");
1228        Err(InterceptError::System(SystemException::new(
1229            SystemExceptionKind::UNKNOWN,
1230            0,
1231            CompletionStatus::Maybe,
1232        )))
1233    })
1234}
1235
1236// --- the server side -----------------------------------------------------------
1237
1238/// The server interception points.
1239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1240pub enum ServerPoint {
1241    /// `receive_request_service_contexts`.
1242    ReceiveRequestServiceContexts,
1243    /// `receive_request`.
1244    ReceiveRequest,
1245    /// `send_reply`.
1246    SendReply,
1247    /// `send_exception`.
1248    SendException,
1249    /// `send_other`.
1250    SendOther,
1251}
1252
1253/// What the DSI tells the server interceptors, after the servant ran.
1254#[derive(Debug, Clone, Default)]
1255pub(crate) struct DsiParams {
1256    pub(crate) arguments: Option<Vec<NamedValue>>,
1257    pub(crate) result: Option<Any>,
1258    pub(crate) exception: Option<Any>,
1259}
1260
1261thread_local! {
1262    /// Set while a request with server interceptors runs its servant: a
1263    /// DSI servant leaves its parameters here.
1264    static DSI: RefCell<Option<DsiParams>> = const { RefCell::new(None) };
1265}
1266
1267/// Whether a DSI servant should leave its parameters for the
1268/// interceptors ([`leave_dsi_params`]).
1269pub(crate) fn wants_dsi_params() -> bool {
1270    DSI.with(|d| d.borrow().is_some())
1271}
1272
1273pub(crate) fn leave_dsi_params(params: DsiParams) {
1274    DSI.with(|d| {
1275        let mut d = d.borrow_mut();
1276        if d.is_some() {
1277            *d = Some(params);
1278        }
1279    });
1280}
1281
1282/// Collects what a DSI servant leaves while it lives.
1283pub(crate) struct DsiGuard {
1284    old: Option<DsiParams>,
1285}
1286
1287impl DsiGuard {
1288    pub(crate) fn enter() -> DsiGuard {
1289        DsiGuard {
1290            old: DSI.with(|d| d.borrow_mut().replace(DsiParams::default())),
1291        }
1292    }
1293
1294    pub(crate) fn take(self) -> DsiParams {
1295        DSI.with(|d| d.borrow_mut().take()).unwrap_or_default()
1296    }
1297}
1298
1299impl Drop for DsiGuard {
1300    fn drop(&mut self) {
1301        let old = self.old.take();
1302        let _ = DSI.try_with(|d| *d.borrow_mut() = old);
1303    }
1304}
1305
1306/// The target of a request, once its POA is known.
1307pub(crate) struct ServerTarget {
1308    pub(crate) poa: Poa,
1309    pub(crate) id: Vec<u8>,
1310}
1311
1312/// `PortableInterceptor::ServerRequestInfo`: one request as the server
1313/// interceptors see it, during one interception point.
1314pub struct ServerRequestInfo<'a> {
1315    point: Cell<ServerPoint>,
1316    request_id: u32,
1317    operation: &'a str,
1318    response_expected: bool,
1319    sync_scope: i16,
1320    orb: &'a Orb,
1321    target: Option<&'a ServerTarget>,
1322    servant: RefCell<Option<Arc<dyn Servant>>>,
1323    request_contexts: &'a [ServiceContext],
1324    reply_contexts: RefCell<Vec<ServiceContext>>,
1325    slots: RefCell<Vec<Any>>,
1326    reply_status: Cell<i16>,
1327    exception: RefCell<Option<ServerException>>,
1328    forward: RefCell<Option<ObjectRef>>,
1329    dsi: RefCell<Option<DsiParams>>,
1330}
1331
1332impl fmt::Debug for ServerRequestInfo<'_> {
1333    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1334        f.debug_struct("ServerRequestInfo")
1335            .field("point", &self.point.get())
1336            .field("request_id", &self.request_id)
1337            .field("operation", &self.operation)
1338            .finish_non_exhaustive()
1339    }
1340}
1341
1342/// The exception of a server reply.
1343#[derive(Debug, Clone)]
1344pub(crate) enum ServerException {
1345    System(SystemException),
1346    /// A user exception the servant wrote, by repository id.
1347    User(String),
1348}
1349
1350/// How a server interception ends: the reply that goes out.
1351#[derive(Debug, Clone)]
1352pub(crate) enum ServerEnding {
1353    Reply,
1354    Exception(ServerException),
1355    Forward(ObjectRef),
1356}
1357
1358impl ServerEnding {
1359    fn from_error(e: InterceptError) -> ServerEnding {
1360        match e {
1361            InterceptError::System(e) => ServerEnding::Exception(ServerException::System(e)),
1362            InterceptError::ForwardRequest(to) => ServerEnding::Forward(to),
1363        }
1364    }
1365}
1366
1367/// The parts of a request [`ServerRequestInfo::new`] takes.
1368pub(crate) struct ServerRequest<'a> {
1369    pub(crate) request_id: u32,
1370    pub(crate) operation: &'a str,
1371    pub(crate) response_expected: bool,
1372    /// The `Messaging::SyncScope` the request's `response_flags` say.
1373    pub(crate) sync_scope: i16,
1374    pub(crate) orb: &'a Orb,
1375    pub(crate) target: Option<&'a ServerTarget>,
1376    pub(crate) contexts: &'a [ServiceContext],
1377}
1378
1379impl<'a> ServerRequestInfo<'a> {
1380    pub(crate) fn new(pi: &Interceptors, r: ServerRequest<'a>) -> ServerRequestInfo<'a> {
1381        ServerRequestInfo {
1382            point: Cell::new(ServerPoint::ReceiveRequestServiceContexts),
1383            request_id: r.request_id,
1384            operation: r.operation,
1385            response_expected: r.response_expected,
1386            sync_scope: r.sync_scope,
1387            orb: r.orb,
1388            target: r.target,
1389            servant: RefCell::new(None),
1390            request_contexts: r.contexts,
1391            reply_contexts: RefCell::new(Vec::new()),
1392            slots: RefCell::new(vec![empty_slot(); pi.slots as usize]),
1393            reply_status: Cell::new(reply_status::SUCCESSFUL),
1394            exception: RefCell::new(None),
1395            forward: RefCell::new(None),
1396            dsi: RefCell::new(None),
1397        }
1398    }
1399
1400    fn check(&self, allowed: &[ServerPoint]) -> Result<(), SystemException> {
1401        if allowed.contains(&self.point.get()) {
1402            Ok(())
1403        } else {
1404            Err(invalid_point())
1405        }
1406    }
1407
1408    fn sending(&self) -> Result<(), SystemException> {
1409        use ServerPoint::*;
1410        self.check(&[SendReply, SendException, SendOther])
1411    }
1412
1413    fn not_first(&self) -> Result<(), SystemException> {
1414        if self.point.get() == ServerPoint::ReceiveRequestServiceContexts {
1415            Err(invalid_point())
1416        } else {
1417            Ok(())
1418        }
1419    }
1420
1421    /// The interception point being run.
1422    pub fn point(&self) -> ServerPoint {
1423        self.point.get()
1424    }
1425
1426    /// `request_id`: the GIOP request id (0 for a call within the ORB).
1427    pub fn request_id(&self) -> u32 {
1428        self.request_id
1429    }
1430
1431    /// `operation`.
1432    pub fn operation(&self) -> &str {
1433        self.operation
1434    }
1435
1436    /// `arguments`: only for a DSI servant, in `send_reply` (else
1437    /// `NO_RESOURCES`).
1438    pub fn arguments(&self) -> Result<Vec<Parameter>, SystemException> {
1439        use ServerPoint::*;
1440        self.check(&[ReceiveRequest, SendReply])?;
1441        self.dsi
1442            .borrow()
1443            .as_ref()
1444            .and_then(|d| d.arguments.as_deref().map(parameters))
1445            .ok_or_else(not_available)
1446    }
1447
1448    /// `exceptions`: `NO_RESOURCES` (the servant's exception list is not
1449    /// known).
1450    pub fn exceptions(&self) -> Result<Vec<TypeCode>, SystemException> {
1451        self.not_first()?;
1452        Err(not_available())
1453    }
1454
1455    /// `contexts`: `NO_RESOURCES`.
1456    pub fn contexts(&self) -> Result<Vec<String>, SystemException> {
1457        self.not_first()?;
1458        Err(not_available())
1459    }
1460
1461    /// `operation_context`: `NO_RESOURCES`.
1462    pub fn operation_context(&self) -> Result<Vec<String>, SystemException> {
1463        self.not_first()?;
1464        Err(not_available())
1465    }
1466
1467    /// `result`: in `send_reply`, for a DSI servant.
1468    pub fn result(&self) -> Result<Any, SystemException> {
1469        self.check(&[ServerPoint::SendReply])?;
1470        self.dsi
1471            .borrow()
1472            .as_ref()
1473            .filter(|d| d.arguments.is_some())
1474            .map(|d| {
1475                d.result
1476                    .clone()
1477                    .unwrap_or_else(|| Any::new(TypeCode::void(), Value::Void))
1478            })
1479            .ok_or_else(not_available)
1480    }
1481
1482    /// `response_expected`.
1483    pub fn response_expected(&self) -> bool {
1484        self.response_expected
1485    }
1486
1487    /// `sync_scope`: what the request's `response_flags` say, which
1488    /// cannot tell `SYNC_NONE` from `SYNC_WITH_TRANSPORT` (`SYNC_NONE`
1489    /// for both) nor a oneway `SYNC_WITH_TARGET` request from a two-way
1490    /// one.
1491    pub fn sync_scope(&self) -> i16 {
1492        self.sync_scope
1493    }
1494
1495    /// `reply_status`: in the `send_*` points.
1496    pub fn reply_status(&self) -> Result<i16, SystemException> {
1497        self.sending()?;
1498        Ok(self.reply_status.get())
1499    }
1500
1501    /// `forward_reference`: in `send_other`.
1502    pub fn forward_reference(&self) -> Result<ObjectRef, SystemException> {
1503        self.check(&[ServerPoint::SendOther])?;
1504        self.forward.borrow().clone().ok_or_else(invalid_point)
1505    }
1506
1507    /// `get_slot`: the request's slots.
1508    pub fn get_slot(&self, id: SlotId) -> Result<Any, InvalidSlot> {
1509        self.slots
1510            .borrow()
1511            .get(id as usize)
1512            .cloned()
1513            .ok_or(InvalidSlot)
1514    }
1515
1516    /// `set_slot`: what the servant will see in [`PiCurrent`] (when set
1517    /// before `receive_request`).
1518    pub fn set_slot(&self, id: SlotId, data: Any) -> Result<(), InvalidSlot> {
1519        match self.slots.borrow_mut().get_mut(id as usize) {
1520            Some(slot) => {
1521                *slot = data;
1522                Ok(())
1523            }
1524            None => Err(InvalidSlot),
1525        }
1526    }
1527
1528    /// `get_request_service_context`: any context the client sent.
1529    pub fn get_request_service_context(&self, id: u32) -> Result<ServiceContext, SystemException> {
1530        find_context(self.request_contexts, id)
1531    }
1532
1533    /// The contexts the client sent (rustorb).
1534    pub fn request_service_contexts(&self) -> &[ServiceContext] {
1535        self.request_contexts
1536    }
1537
1538    /// `get_reply_service_context`: one added for the reply.
1539    pub fn get_reply_service_context(&self, id: u32) -> Result<ServiceContext, SystemException> {
1540        self.sending()?;
1541        find_context(&self.reply_contexts.borrow(), id)
1542    }
1543
1544    /// `add_reply_service_context`.
1545    pub fn add_reply_service_context(
1546        &self,
1547        sc: ServiceContext,
1548        replace: bool,
1549    ) -> Result<(), SystemException> {
1550        if is_core_context(sc.context_id) {
1551            return Err(duplicate_context());
1552        }
1553        add_context(&mut self.reply_contexts.borrow_mut(), sc, replace)
1554    }
1555
1556    /// `sending_exception`: in `send_exception`. A user exception a static
1557    /// skeleton wrote is an Any of `UNKNOWN`; one a DSI servant set is
1558    /// itself.
1559    pub fn sending_exception(&self) -> Result<Any, SystemException> {
1560        self.check(&[ServerPoint::SendException])?;
1561        match &*self.exception.borrow() {
1562            Some(ServerException::System(e)) => Ok(system_exception_any(e)),
1563            Some(ServerException::User(_)) => Ok(self
1564                .dsi
1565                .borrow()
1566                .as_ref()
1567                .and_then(|d| d.exception.clone())
1568                .unwrap_or_else(unknown_any)),
1569            None => Err(invalid_point()),
1570        }
1571    }
1572
1573    /// The repository id of the exception, in `send_exception` (rustorb).
1574    pub fn sending_exception_id(&self) -> Result<String, SystemException> {
1575        self.check(&[ServerPoint::SendException])?;
1576        match &*self.exception.borrow() {
1577            Some(ServerException::System(e)) => Ok(e.repository_id.clone()),
1578            Some(ServerException::User(id)) => Ok(id.clone()),
1579            None => Err(invalid_point()),
1580        }
1581    }
1582
1583    fn target(&self) -> Result<&ServerTarget, SystemException> {
1584        self.not_first()?;
1585        self.target.ok_or_else(not_available)
1586    }
1587
1588    /// `object_id`.
1589    pub fn object_id(&self) -> Result<Vec<u8>, SystemException> {
1590        Ok(self.target()?.id.clone())
1591    }
1592
1593    /// `adapter_id`: the POA's part of the object key.
1594    pub fn adapter_id(&self) -> Result<Vec<u8>, SystemException> {
1595        Ok(self.target()?.poa.inner.key(&[]))
1596    }
1597
1598    /// `adapter_name`: the names of the POAs from the RootPOA down.
1599    pub fn adapter_name(&self) -> Result<Vec<String>, SystemException> {
1600        let t = self.target()?;
1601        let mut names = vec!["RootPOA".to_owned()];
1602        names.extend(t.poa.inner.path().iter().cloned());
1603        Ok(names)
1604    }
1605
1606    /// `orb_id` (`-ORBid`).
1607    pub fn orb_id(&self) -> &str {
1608        &self.orb.inner.options.orb_id
1609    }
1610
1611    /// `server_id` (`-ORBServerId`).
1612    pub fn server_id(&self) -> &str {
1613        &self.orb.inner.options.server_id
1614    }
1615
1616    fn servant(&self) -> Result<Arc<dyn Servant>, SystemException> {
1617        self.not_first()?;
1618        self.servant.borrow().clone().ok_or_else(not_available)
1619    }
1620
1621    /// `target_most_derived_interface`: from `receive_request` on.
1622    pub fn target_most_derived_interface(&self) -> Result<String, SystemException> {
1623        Ok(self.servant()?.repository_id().to_owned())
1624    }
1625
1626    /// `target_is_a`.
1627    pub fn target_is_a(&self, id: &str) -> Result<bool, SystemException> {
1628        let servant = self.servant()?;
1629        Ok(id == "IDL:omg.org/CORBA/Object:1.0" || servant.is_a(id))
1630    }
1631
1632    /// `get_server_policy`: a policy of the target's POA.
1633    pub fn get_server_policy(
1634        &self,
1635        policy_type: PolicyType,
1636    ) -> Result<PolicyValue, SystemException> {
1637        let t = self.target.ok_or_else(not_available)?;
1638        policy_of(t.poa.inner.policies(), policy_type)
1639    }
1640
1641    pub(crate) fn set_servant(&self, servant: &Arc<dyn Servant>) {
1642        *self.servant.borrow_mut() = Some(Arc::clone(servant));
1643    }
1644
1645    pub(crate) fn set_dsi(&self, dsi: DsiParams) {
1646        *self.dsi.borrow_mut() = Some(dsi);
1647    }
1648
1649    pub(crate) fn reply_contexts(&self) -> Vec<ServiceContext> {
1650        self.reply_contexts.borrow().clone()
1651    }
1652
1653    /// Makes the request's slots those of the thread while the guard
1654    /// lives (the servant sees them).
1655    pub(crate) fn enter_thread_scope(&self, pi: &Interceptors) -> ThreadSlotsGuard {
1656        ThreadSlotsGuard::enter(pi.serial, self.slots.borrow().clone())
1657    }
1658
1659    fn enter(&self, ending: &ServerEnding) {
1660        *self.exception.borrow_mut() = None;
1661        *self.forward.borrow_mut() = None;
1662        let (point, status) = match ending {
1663            ServerEnding::Reply => (ServerPoint::SendReply, reply_status::SUCCESSFUL),
1664            ServerEnding::Exception(e) => {
1665                *self.exception.borrow_mut() = Some(e.clone());
1666                let status = match e {
1667                    ServerException::System(_) => reply_status::SYSTEM_EXCEPTION,
1668                    ServerException::User(_) => reply_status::USER_EXCEPTION,
1669                };
1670                (ServerPoint::SendException, status)
1671            }
1672            ServerEnding::Forward(to) => {
1673                *self.forward.borrow_mut() = Some(to.clone());
1674                (ServerPoint::SendOther, reply_status::LOCATION_FORWARD)
1675            }
1676        };
1677        self.point.set(point);
1678        self.reply_status.set(status);
1679    }
1680}
1681
1682fn policy_of(p: &Policies, policy_type: PolicyType) -> Result<PolicyValue, SystemException> {
1683    use crate::policy::*;
1684    let policy = match policy_type {
1685        THREAD_POLICY_ID => Policy::Thread(p.thread),
1686        BIDIRECTIONAL_POLICY_TYPE => Policy::Bidirectional(p.bidirectional),
1687        LIFESPAN_POLICY_ID => Policy::Lifespan(p.lifespan),
1688        ID_UNIQUENESS_POLICY_ID => Policy::IdUniqueness(p.id_uniqueness),
1689        ID_ASSIGNMENT_POLICY_ID => Policy::IdAssignment(p.id_assignment),
1690        IMPLICIT_ACTIVATION_POLICY_ID => Policy::ImplicitActivation(p.implicit_activation),
1691        SERVANT_RETENTION_POLICY_ID => Policy::ServantRetention(p.servant_retention),
1692        REQUEST_PROCESSING_POLICY_ID => Policy::RequestProcessing(p.request_processing),
1693        _ => {
1694            return Err(SystemException::new(
1695                SystemExceptionKind::INV_POLICY,
1696                minor::INVALID_POLICY_TYPE,
1697                CompletionStatus::No,
1698            ));
1699        }
1700    };
1701    Ok(PolicyValue::Poa(policy))
1702}
1703
1704/// Runs `receive_request_service_contexts` on each interceptor. `Err` is
1705/// how the request ends when one of them raised.
1706pub(crate) fn receive_request_service_contexts(
1707    pi: &Interceptors,
1708    info: &ServerRequestInfo<'_>,
1709) -> Result<(), ServerEnding> {
1710    info.point.set(ServerPoint::ReceiveRequestServiceContexts);
1711    for (k, i) in pi.server.iter().enumerate() {
1712        if let Err(e) = catch_server(|| i.receive_request_service_contexts(info)) {
1713            return Err(end_server(pi, info, ServerEnding::from_error(e), k));
1714        }
1715    }
1716    Ok(())
1717}
1718
1719/// Runs `receive_request` on each interceptor.
1720pub(crate) fn receive_request(
1721    pi: &Interceptors,
1722    info: &ServerRequestInfo<'_>,
1723) -> Result<(), ServerEnding> {
1724    info.point.set(ServerPoint::ReceiveRequest);
1725    for i in &pi.server {
1726        if let Err(e) = catch_server(|| i.receive_request(info)) {
1727            return Err(send_reply(pi, info, ServerEnding::from_error(e)));
1728        }
1729    }
1730    Ok(())
1731}
1732
1733/// Runs the `send_*` points on every interceptor, in the reverse order,
1734/// and returns the reply to send.
1735pub(crate) fn send_reply(
1736    pi: &Interceptors,
1737    info: &ServerRequestInfo<'_>,
1738    ending: ServerEnding,
1739) -> ServerEnding {
1740    end_server(pi, info, ending, pi.server.len())
1741}
1742
1743fn end_server(
1744    pi: &Interceptors,
1745    info: &ServerRequestInfo<'_>,
1746    mut ending: ServerEnding,
1747    started: usize,
1748) -> ServerEnding {
1749    for i in pi.server[..started].iter().rev() {
1750        info.enter(&ending);
1751        let result = match &ending {
1752            ServerEnding::Reply => {
1753                catch_server(|| i.send_reply(info).map_err(InterceptError::System))
1754            }
1755            ServerEnding::Exception(_) => catch_server(|| i.send_exception(info)),
1756            ServerEnding::Forward(_) => catch_server(|| i.send_other(info)),
1757        };
1758        if let Err(e) = result {
1759            ending = ServerEnding::from_error(e);
1760        }
1761    }
1762    ending
1763}
1764
1765fn catch_server(f: impl FnOnce() -> Result<(), InterceptError>) -> Result<(), InterceptError> {
1766    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| {
1767        trace::warning!("server request interceptor panicked");
1768        Err(InterceptError::System(SystemException::new(
1769            SystemExceptionKind::UNKNOWN,
1770            0,
1771            CompletionStatus::Maybe,
1772        )))
1773    })
1774}
1775
1776// --- IOR interceptors ----------------------------------------------------------
1777
1778/// `PortableInterceptor::IORInfo`: a new POA, for
1779/// [`IorInterceptor::establish_components`].
1780pub struct IorInfo<'a> {
1781    policies: &'a Policies,
1782    adapter_name: Vec<String>,
1783    components: RefCell<Vec<TaggedComponent>>,
1784}
1785
1786impl fmt::Debug for IorInfo<'_> {
1787    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1788        f.debug_struct("IorInfo")
1789            .field("adapter_name", &self.adapter_name)
1790            .finish_non_exhaustive()
1791    }
1792}
1793
1794impl IorInfo<'_> {
1795    /// `get_effective_policy`: a policy of the POA.
1796    pub fn get_effective_policy(
1797        &self,
1798        policy_type: PolicyType,
1799    ) -> Result<PolicyValue, SystemException> {
1800        policy_of(self.policies, policy_type)
1801    }
1802
1803    /// The names of the POAs from the RootPOA down to the new one
1804    /// (rustorb).
1805    pub fn adapter_name(&self) -> &[String] {
1806        &self.adapter_name
1807    }
1808
1809    /// `add_ior_component`: adds `component` to every profile of the
1810    /// POA's references.
1811    pub fn add_ior_component(&self, component: TaggedComponent) {
1812        self.components.borrow_mut().push(component);
1813    }
1814
1815    /// `add_ior_component_to_profile`: only `TAG_INTERNET_IOP`, the one
1816    /// profile rustorb makes (`BAD_PARAM` for another).
1817    pub fn add_ior_component_to_profile(
1818        &self,
1819        component: TaggedComponent,
1820        profile_id: u32,
1821    ) -> Result<(), SystemException> {
1822        if profile_id != TAG_INTERNET_IOP {
1823            return Err(SystemException::new(
1824                SystemExceptionKind::BAD_PARAM,
1825                minor::UNKNOWN_PROFILE,
1826                CompletionStatus::No,
1827            ));
1828        }
1829        self.add_ior_component(component);
1830        Ok(())
1831    }
1832}
1833
1834/// The components the IOR interceptors of `orb` add to the references of
1835/// a new POA with `policies`, whose names below the RootPOA are `path`.
1836pub(crate) fn establish_components(
1837    orb: &Orb,
1838    policies: &Policies,
1839    path: &[String],
1840) -> Vec<TaggedComponent> {
1841    let Some(pi) = orb.interceptors() else {
1842        return Vec::new();
1843    };
1844    if pi.ior.is_empty() {
1845        return Vec::new();
1846    }
1847    let mut adapter_name = vec!["RootPOA".to_owned()];
1848    adapter_name.extend(path.iter().cloned());
1849    let info = IorInfo {
1850        policies,
1851        adapter_name,
1852        components: RefCell::new(Vec::new()),
1853    };
1854    for i in &pi.ior {
1855        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1856            i.establish_components(&info)
1857        }));
1858        match result {
1859            Ok(Ok(())) => {}
1860            Ok(Err(e)) => trace::warning!(
1861                "IORInterceptor {:?} raised {e} in establish_components (ignored)",
1862                i.name()
1863            ),
1864            Err(_) => trace::warning!(
1865                "IORInterceptor {:?} panicked in establish_components (ignored)",
1866                i.name()
1867            ),
1868        }
1869    }
1870    info.components.into_inner()
1871}
1872
1873/// The information of a client request is held across the awaits of an
1874/// async call.
1875#[allow(dead_code)]
1876fn assert_send() {
1877    fn is_send<T: Send>() {}
1878    is_send::<ClientRequestInfo<'static>>();
1879}