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    target: &'a ObjectRef,
778    effective_target: ObjectRef,
779    effective_profile: TaggedProfile,
780    timeout: Option<Duration>,
781    slots: Vec<Any>,
782    dii: Option<&'a DiiParams>,
783    request_contexts: RefCell<Vec<ServiceContext>>,
784    reply_contexts: RefCell<Vec<ServiceContext>>,
785    reply_status: Cell<i16>,
786    exception: RefCell<Option<Exception>>,
787    forward: RefCell<Option<ObjectRef>>,
788    reply: RefCell<Option<Reply>>,
789}
790
791impl fmt::Debug for ClientRequestInfo<'_> {
792    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
793        f.debug_struct("ClientRequestInfo")
794            .field("point", &self.point.get())
795            .field("request_id", &self.request_id)
796            .field("operation", &self.operation)
797            .finish_non_exhaustive()
798    }
799}
800
801/// The parts of a request [`ClientRequestInfo::new`] takes.
802pub(crate) struct ClientRequest<'a> {
803    pub(crate) operation: &'a str,
804    pub(crate) response_expected: bool,
805    pub(crate) target: &'a ObjectRef,
806    pub(crate) effective: Arc<Ior>,
807    pub(crate) profile_index: Option<usize>,
808    pub(crate) timeout: Option<Duration>,
809    pub(crate) slots: Vec<Any>,
810    pub(crate) dii: Option<&'a DiiParams>,
811}
812
813impl<'a> ClientRequestInfo<'a> {
814    pub(crate) fn new(pi: &Interceptors, r: ClientRequest<'a>) -> ClientRequestInfo<'a> {
815        let effective_profile = r
816            .profile_index
817            .and_then(|i| r.effective.profiles.get(i))
818            .cloned()
819            .unwrap_or(TaggedProfile {
820                tag: TAG_INTERNET_IOP,
821                profile_data: Vec::new(),
822            });
823        let effective_target = if Arc::ptr_eq(&r.effective, &r.target.ior_arc()) {
824            r.target.clone()
825        } else {
826            ObjectRef::new(r.target.orb().clone(), (*r.effective).clone())
827        };
828        ClientRequestInfo {
829            point: Cell::new(ClientPoint::SendRequest),
830            request_id: pi.next_request_id.fetch_add(1, Ordering::Relaxed),
831            operation: r.operation,
832            response_expected: r.response_expected,
833            target: r.target,
834            effective_target,
835            effective_profile,
836            timeout: r.timeout,
837            slots: r.slots,
838            dii: r.dii,
839            request_contexts: RefCell::new(Vec::new()),
840            reply_contexts: RefCell::new(Vec::new()),
841            reply_status: Cell::new(reply_status::SUCCESSFUL),
842            exception: RefCell::new(None),
843            forward: RefCell::new(None),
844            reply: RefCell::new(None),
845        }
846    }
847
848    fn check(&self, allowed: &[ClientPoint]) -> Result<(), SystemException> {
849        if allowed.contains(&self.point.get()) {
850            Ok(())
851        } else {
852            Err(invalid_point())
853        }
854    }
855
856    fn after_send(&self) -> Result<(), SystemException> {
857        use ClientPoint::*;
858        self.check(&[ReceiveReply, ReceiveException, ReceiveOther])
859    }
860
861    /// The interception point being run.
862    pub fn point(&self) -> ClientPoint {
863        self.point.get()
864    }
865
866    /// `request_id`: unique among the requests of this ORB in progress
867    /// (not the GIOP request id).
868    pub fn request_id(&self) -> u32 {
869        self.request_id
870    }
871
872    /// `operation`.
873    pub fn operation(&self) -> &str {
874        self.operation
875    }
876
877    /// `arguments`: only for a DII request (else `NO_RESOURCES`), in
878    /// `send_request` and `receive_reply`.
879    pub fn arguments(&self) -> Result<Vec<Parameter>, SystemException> {
880        use ClientPoint::*;
881        self.check(&[SendRequest, ReceiveReply])?;
882        let dii = self.dii.ok_or_else(not_available)?;
883        if self.point.get() == SendRequest {
884            return Ok(parameters(&dii.arguments));
885        }
886        let (_, out) = self.decode_reply(dii)?;
887        let mut out = out.into_iter();
888        Ok(dii
889            .arguments
890            .iter()
891            .map(|nv| Parameter {
892                argument: if nv.mode.is_out() {
893                    out.next().unwrap_or_else(|| nv.value.clone())
894                } else {
895                    nv.value.clone()
896                },
897                mode: nv.mode,
898            })
899            .collect())
900    }
901
902    /// The result and the `out` values of a DII reply.
903    fn decode_reply(&self, dii: &DiiParams) -> Result<(Any, Vec<Any>), SystemException> {
904        let reply = self.reply.borrow();
905        let reply = reply.as_ref().ok_or_else(not_available)?;
906        let mut input = reply.input();
907        let result = Any::new(dii.result.clone(), input.read_value(&dii.result)?);
908        let mut out = Vec::new();
909        for nv in dii.arguments.iter().filter(|nv| nv.mode.is_out()) {
910            let tc = nv.value.typecode().clone();
911            let value = input.read_value(&tc)?;
912            out.push(Any::new(tc, value));
913        }
914        Ok((result, out))
915    }
916
917    /// `exceptions`: the exception list of a DII request.
918    pub fn exceptions(&self) -> Result<Vec<TypeCode>, SystemException> {
919        self.check_not_poll()?;
920        Ok(self.dii.ok_or_else(not_available)?.exceptions.clone())
921    }
922
923    fn check_not_poll(&self) -> Result<(), SystemException> {
924        if self.point.get() == ClientPoint::SendPoll {
925            Err(invalid_point())
926        } else {
927            Ok(())
928        }
929    }
930
931    /// `contexts`: `NO_RESOURCES` (rustorb has no `context` clauses).
932    pub fn contexts(&self) -> Result<Vec<String>, SystemException> {
933        self.check_not_poll()?;
934        Err(not_available())
935    }
936
937    /// `operation_context`: `NO_RESOURCES`.
938    pub fn operation_context(&self) -> Result<Vec<String>, SystemException> {
939        self.check_not_poll()?;
940        Err(not_available())
941    }
942
943    /// `result`: only in `receive_reply` of a DII request.
944    pub fn result(&self) -> Result<Any, SystemException> {
945        self.check(&[ClientPoint::ReceiveReply])?;
946        let dii = self.dii.ok_or_else(not_available)?;
947        Ok(self.decode_reply(dii)?.0)
948    }
949
950    /// `response_expected`.
951    pub fn response_expected(&self) -> bool {
952        self.response_expected
953    }
954
955    /// `sync_scope`.
956    pub fn sync_scope(&self) -> i16 {
957        if self.response_expected {
958            sync_scope::SYNC_WITH_TARGET
959        } else {
960            sync_scope::SYNC_NONE
961        }
962    }
963
964    /// `reply_status` ([`reply_status`]).
965    pub fn reply_status(&self) -> Result<i16, SystemException> {
966        self.after_send()?;
967        Ok(self.reply_status.get())
968    }
969
970    /// `forward_reference`: in `receive_other` of a `LOCATION_FORWARD`.
971    pub fn forward_reference(&self) -> Result<ObjectRef, SystemException> {
972        self.check(&[ClientPoint::ReceiveOther])?;
973        self.forward.borrow().clone().ok_or_else(invalid_point)
974    }
975
976    /// `get_slot`: the request's copy of the slots.
977    pub fn get_slot(&self, id: SlotId) -> Result<Any, InvalidSlot> {
978        self.slots.get(id as usize).cloned().ok_or(InvalidSlot)
979    }
980
981    /// `get_request_service_context`: one the interceptors added (the ones
982    /// rustorb writes itself, such as `CodeSets`, are not here).
983    pub fn get_request_service_context(&self, id: u32) -> Result<ServiceContext, SystemException> {
984        self.check_not_poll()?;
985        find_context(&self.request_contexts.borrow(), id)
986    }
987
988    /// `get_reply_service_context`.
989    pub fn get_reply_service_context(&self, id: u32) -> Result<ServiceContext, SystemException> {
990        self.after_send()?;
991        find_context(&self.reply_contexts.borrow(), id)
992    }
993
994    /// `target`: the reference the call was made on.
995    pub fn target(&self) -> &ObjectRef {
996        self.target
997    }
998
999    /// `effective_target`: where the request goes, after forwards.
1000    pub fn effective_target(&self) -> &ObjectRef {
1001        &self.effective_target
1002    }
1003
1004    /// `effective_profile`: the profile of the address being tried.
1005    pub fn effective_profile(&self) -> &TaggedProfile {
1006        &self.effective_profile
1007    }
1008
1009    /// `received_exception`: in `receive_exception`. A user exception
1010    /// whose TypeCode is not known (anything but a DII request with an
1011    /// exception list) is an Any of `UNKNOWN`.
1012    pub fn received_exception(&self) -> Result<Any, SystemException> {
1013        self.check(&[ClientPoint::ReceiveException])?;
1014        match &*self.exception.borrow() {
1015            Some(Exception::System(e)) => Ok(system_exception_any(e)),
1016            Some(Exception::User(e)) => Ok(self
1017                .dii
1018                .and_then(|dii| crate::dii::exception_any(&dii.exceptions, e).ok())
1019                .unwrap_or_else(unknown_any)),
1020            None => Err(invalid_point()),
1021        }
1022    }
1023
1024    /// `received_exception_id`.
1025    pub fn received_exception_id(&self) -> Result<String, SystemException> {
1026        self.check(&[ClientPoint::ReceiveException])?;
1027        match &*self.exception.borrow() {
1028            Some(e) => Ok(e.repository_id().to_owned()),
1029            None => Err(invalid_point()),
1030        }
1031    }
1032
1033    /// The exception, in `receive_exception` (rustorb).
1034    pub fn exception(&self) -> Option<Exception> {
1035        self.exception.borrow().clone()
1036    }
1037
1038    fn components(&self) -> Vec<TaggedComponent> {
1039        self.effective_profile
1040            .iiop()
1041            .map(|p| p.components)
1042            .unwrap_or_default()
1043    }
1044
1045    /// `get_effective_component`: the first component with `tag` in the
1046    /// effective profile (`BAD_PARAM` if none).
1047    pub fn get_effective_component(&self, tag: u32) -> Result<TaggedComponent, SystemException> {
1048        self.components()
1049            .into_iter()
1050            .find(|c| c.tag == tag)
1051            .ok_or_else(no_component)
1052    }
1053
1054    /// `get_effective_components`.
1055    pub fn get_effective_components(
1056        &self,
1057        tag: u32,
1058    ) -> Result<Vec<TaggedComponent>, SystemException> {
1059        let found: Vec<_> = self
1060            .components()
1061            .into_iter()
1062            .filter(|c| c.tag == tag)
1063            .collect();
1064        if found.is_empty() {
1065            Err(no_component())
1066        } else {
1067            Ok(found)
1068        }
1069    }
1070
1071    /// `get_request_policy`: the client policy of `policy_type` in effect
1072    /// (`None` if none is). `INV_POLICY` for a type that is not a client
1073    /// policy.
1074    pub fn get_request_policy(
1075        &self,
1076        policy_type: PolicyType,
1077    ) -> Result<Option<PolicyValue>, SystemException> {
1078        if policy_type != crate::policy::RELATIVE_RT_TIMEOUT_POLICY_TYPE {
1079            return Err(SystemException::new(
1080                SystemExceptionKind::INV_POLICY,
1081                minor::INVALID_POLICY_TYPE,
1082                CompletionStatus::No,
1083            ));
1084        }
1085        Ok(self
1086            .timeout
1087            .map(|t| PolicyValue::RelativeRoundtripTimeout(crate::timeout::duration_to_time_t(t))))
1088    }
1089
1090    /// `add_request_service_context`: in `send_request`.
1091    pub fn add_request_service_context(
1092        &self,
1093        sc: ServiceContext,
1094        replace: bool,
1095    ) -> Result<(), SystemException> {
1096        self.check(&[ClientPoint::SendRequest])?;
1097        if is_core_context(sc.context_id) {
1098            return Err(duplicate_context());
1099        }
1100        add_context(&mut self.request_contexts.borrow_mut(), sc, replace)
1101    }
1102
1103    pub(crate) fn take_request_contexts(&self) -> Vec<ServiceContext> {
1104        self.request_contexts.borrow().clone()
1105    }
1106
1107    fn enter(&self, ending: &ClientEnding) {
1108        *self.exception.borrow_mut() = None;
1109        *self.forward.borrow_mut() = None;
1110        let (point, status) = match ending {
1111            ClientEnding::Reply(_) => (ClientPoint::ReceiveReply, reply_status::SUCCESSFUL),
1112            ClientEnding::Oneway => (ClientPoint::ReceiveOther, reply_status::SUCCESSFUL),
1113            ClientEnding::Exception(e) => {
1114                *self.exception.borrow_mut() = Some(e.clone());
1115                let status = match e {
1116                    Exception::System(_) => reply_status::SYSTEM_EXCEPTION,
1117                    Exception::User(_) => reply_status::USER_EXCEPTION,
1118                };
1119                (ClientPoint::ReceiveException, status)
1120            }
1121            ClientEnding::Forward(to) => {
1122                *self.forward.borrow_mut() = Some(to.clone());
1123                (ClientPoint::ReceiveOther, reply_status::LOCATION_FORWARD)
1124            }
1125            ClientEnding::Retry => (ClientPoint::ReceiveOther, reply_status::TRANSPORT_RETRY),
1126        };
1127        if let ClientEnding::Reply(reply) = ending {
1128            *self.reply.borrow_mut() = Some(reply.clone());
1129        }
1130        self.point.set(point);
1131        self.reply_status.set(status);
1132    }
1133
1134    pub(crate) fn set_reply_contexts(&self, contexts: Vec<ServiceContext>) {
1135        *self.reply_contexts.borrow_mut() = contexts;
1136    }
1137}
1138
1139fn no_component() -> SystemException {
1140    SystemException::new(
1141        SystemExceptionKind::BAD_PARAM,
1142        minor::NO_COMPONENT,
1143        CompletionStatus::No,
1144    )
1145}
1146
1147/// How a client interception ends.
1148#[derive(Debug, Clone)]
1149pub(crate) enum ClientEnding {
1150    /// A normal reply.
1151    Reply(Reply),
1152    /// A oneway request was sent.
1153    Oneway,
1154    Exception(Exception),
1155    Forward(ObjectRef),
1156    /// The ORB sends the request again.
1157    Retry,
1158}
1159
1160impl ClientEnding {
1161    fn from_error(e: InterceptError) -> ClientEnding {
1162        match e {
1163            InterceptError::System(e) => ClientEnding::Exception(Exception::System(e)),
1164            InterceptError::ForwardRequest(to) => ClientEnding::Forward(to),
1165        }
1166    }
1167}
1168
1169/// Runs `send_request` on each interceptor. `Err` is how the interception
1170/// ended when one of them raised: the request is not sent.
1171pub(crate) fn send_request(
1172    pi: &Interceptors,
1173    info: &ClientRequestInfo<'_>,
1174) -> Result<(), ClientEnding> {
1175    info.point.set(ClientPoint::SendRequest);
1176    for (k, i) in pi.client.iter().enumerate() {
1177        if let Err(e) = catch_client(|| i.send_request(info)) {
1178            return Err(end_client(pi, info, ClientEnding::from_error(e), k));
1179        }
1180    }
1181    Ok(())
1182}
1183
1184/// Runs the ending points on every interceptor, in the reverse order, and
1185/// returns how the request ends.
1186pub(crate) fn receive(
1187    pi: &Interceptors,
1188    info: &ClientRequestInfo<'_>,
1189    ending: ClientEnding,
1190) -> ClientEnding {
1191    end_client(pi, info, ending, pi.client.len())
1192}
1193
1194fn end_client(
1195    pi: &Interceptors,
1196    info: &ClientRequestInfo<'_>,
1197    mut ending: ClientEnding,
1198    started: usize,
1199) -> ClientEnding {
1200    for i in pi.client[..started].iter().rev() {
1201        info.enter(&ending);
1202        let result = match &ending {
1203            ClientEnding::Reply(_) => {
1204                catch_client(|| i.receive_reply(info).map_err(InterceptError::System))
1205            }
1206            ClientEnding::Exception(_) => catch_client(|| i.receive_exception(info)),
1207            ClientEnding::Oneway | ClientEnding::Forward(_) | ClientEnding::Retry => {
1208                catch_client(|| i.receive_other(info))
1209            }
1210        };
1211        if let Err(e) = result {
1212            ending = ClientEnding::from_error(e);
1213        }
1214    }
1215    ending
1216}
1217
1218fn catch_client(f: impl FnOnce() -> Result<(), InterceptError>) -> Result<(), InterceptError> {
1219    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| {
1220        trace::warning!("client request interceptor panicked");
1221        Err(InterceptError::System(SystemException::new(
1222            SystemExceptionKind::UNKNOWN,
1223            0,
1224            CompletionStatus::Maybe,
1225        )))
1226    })
1227}
1228
1229// --- the server side -----------------------------------------------------------
1230
1231/// The server interception points.
1232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1233pub enum ServerPoint {
1234    /// `receive_request_service_contexts`.
1235    ReceiveRequestServiceContexts,
1236    /// `receive_request`.
1237    ReceiveRequest,
1238    /// `send_reply`.
1239    SendReply,
1240    /// `send_exception`.
1241    SendException,
1242    /// `send_other`.
1243    SendOther,
1244}
1245
1246/// What the DSI tells the server interceptors, after the servant ran.
1247#[derive(Debug, Clone, Default)]
1248pub(crate) struct DsiParams {
1249    pub(crate) arguments: Option<Vec<NamedValue>>,
1250    pub(crate) result: Option<Any>,
1251    pub(crate) exception: Option<Any>,
1252}
1253
1254thread_local! {
1255    /// Set while a request with server interceptors runs its servant: a
1256    /// DSI servant leaves its parameters here.
1257    static DSI: RefCell<Option<DsiParams>> = const { RefCell::new(None) };
1258}
1259
1260/// Whether a DSI servant should leave its parameters for the
1261/// interceptors ([`leave_dsi_params`]).
1262pub(crate) fn wants_dsi_params() -> bool {
1263    DSI.with(|d| d.borrow().is_some())
1264}
1265
1266pub(crate) fn leave_dsi_params(params: DsiParams) {
1267    DSI.with(|d| {
1268        let mut d = d.borrow_mut();
1269        if d.is_some() {
1270            *d = Some(params);
1271        }
1272    });
1273}
1274
1275/// Collects what a DSI servant leaves while it lives.
1276pub(crate) struct DsiGuard {
1277    old: Option<DsiParams>,
1278}
1279
1280impl DsiGuard {
1281    pub(crate) fn enter() -> DsiGuard {
1282        DsiGuard {
1283            old: DSI.with(|d| d.borrow_mut().replace(DsiParams::default())),
1284        }
1285    }
1286
1287    pub(crate) fn take(self) -> DsiParams {
1288        DSI.with(|d| d.borrow_mut().take()).unwrap_or_default()
1289    }
1290}
1291
1292impl Drop for DsiGuard {
1293    fn drop(&mut self) {
1294        let old = self.old.take();
1295        let _ = DSI.try_with(|d| *d.borrow_mut() = old);
1296    }
1297}
1298
1299/// The target of a request, once its POA is known.
1300pub(crate) struct ServerTarget {
1301    pub(crate) poa: Poa,
1302    pub(crate) id: Vec<u8>,
1303}
1304
1305/// `PortableInterceptor::ServerRequestInfo`: one request as the server
1306/// interceptors see it, during one interception point.
1307pub struct ServerRequestInfo<'a> {
1308    point: Cell<ServerPoint>,
1309    request_id: u32,
1310    operation: &'a str,
1311    response_expected: bool,
1312    orb: &'a Orb,
1313    target: Option<&'a ServerTarget>,
1314    servant: RefCell<Option<Arc<dyn Servant>>>,
1315    request_contexts: &'a [ServiceContext],
1316    reply_contexts: RefCell<Vec<ServiceContext>>,
1317    slots: RefCell<Vec<Any>>,
1318    reply_status: Cell<i16>,
1319    exception: RefCell<Option<ServerException>>,
1320    forward: RefCell<Option<ObjectRef>>,
1321    dsi: RefCell<Option<DsiParams>>,
1322}
1323
1324impl fmt::Debug for ServerRequestInfo<'_> {
1325    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1326        f.debug_struct("ServerRequestInfo")
1327            .field("point", &self.point.get())
1328            .field("request_id", &self.request_id)
1329            .field("operation", &self.operation)
1330            .finish_non_exhaustive()
1331    }
1332}
1333
1334/// The exception of a server reply.
1335#[derive(Debug, Clone)]
1336pub(crate) enum ServerException {
1337    System(SystemException),
1338    /// A user exception the servant wrote, by repository id.
1339    User(String),
1340}
1341
1342/// How a server interception ends: the reply that goes out.
1343#[derive(Debug, Clone)]
1344pub(crate) enum ServerEnding {
1345    Reply,
1346    Exception(ServerException),
1347    Forward(ObjectRef),
1348}
1349
1350impl ServerEnding {
1351    fn from_error(e: InterceptError) -> ServerEnding {
1352        match e {
1353            InterceptError::System(e) => ServerEnding::Exception(ServerException::System(e)),
1354            InterceptError::ForwardRequest(to) => ServerEnding::Forward(to),
1355        }
1356    }
1357}
1358
1359/// The parts of a request [`ServerRequestInfo::new`] takes.
1360pub(crate) struct ServerRequest<'a> {
1361    pub(crate) request_id: u32,
1362    pub(crate) operation: &'a str,
1363    pub(crate) response_expected: bool,
1364    pub(crate) orb: &'a Orb,
1365    pub(crate) target: Option<&'a ServerTarget>,
1366    pub(crate) contexts: &'a [ServiceContext],
1367}
1368
1369impl<'a> ServerRequestInfo<'a> {
1370    pub(crate) fn new(pi: &Interceptors, r: ServerRequest<'a>) -> ServerRequestInfo<'a> {
1371        ServerRequestInfo {
1372            point: Cell::new(ServerPoint::ReceiveRequestServiceContexts),
1373            request_id: r.request_id,
1374            operation: r.operation,
1375            response_expected: r.response_expected,
1376            orb: r.orb,
1377            target: r.target,
1378            servant: RefCell::new(None),
1379            request_contexts: r.contexts,
1380            reply_contexts: RefCell::new(Vec::new()),
1381            slots: RefCell::new(vec![empty_slot(); pi.slots as usize]),
1382            reply_status: Cell::new(reply_status::SUCCESSFUL),
1383            exception: RefCell::new(None),
1384            forward: RefCell::new(None),
1385            dsi: RefCell::new(None),
1386        }
1387    }
1388
1389    fn check(&self, allowed: &[ServerPoint]) -> Result<(), SystemException> {
1390        if allowed.contains(&self.point.get()) {
1391            Ok(())
1392        } else {
1393            Err(invalid_point())
1394        }
1395    }
1396
1397    fn sending(&self) -> Result<(), SystemException> {
1398        use ServerPoint::*;
1399        self.check(&[SendReply, SendException, SendOther])
1400    }
1401
1402    fn not_first(&self) -> Result<(), SystemException> {
1403        if self.point.get() == ServerPoint::ReceiveRequestServiceContexts {
1404            Err(invalid_point())
1405        } else {
1406            Ok(())
1407        }
1408    }
1409
1410    /// The interception point being run.
1411    pub fn point(&self) -> ServerPoint {
1412        self.point.get()
1413    }
1414
1415    /// `request_id`: the GIOP request id (0 for a call within the ORB).
1416    pub fn request_id(&self) -> u32 {
1417        self.request_id
1418    }
1419
1420    /// `operation`.
1421    pub fn operation(&self) -> &str {
1422        self.operation
1423    }
1424
1425    /// `arguments`: only for a DSI servant, in `send_reply` (else
1426    /// `NO_RESOURCES`).
1427    pub fn arguments(&self) -> Result<Vec<Parameter>, SystemException> {
1428        use ServerPoint::*;
1429        self.check(&[ReceiveRequest, SendReply])?;
1430        self.dsi
1431            .borrow()
1432            .as_ref()
1433            .and_then(|d| d.arguments.as_deref().map(parameters))
1434            .ok_or_else(not_available)
1435    }
1436
1437    /// `exceptions`: `NO_RESOURCES` (the servant's exception list is not
1438    /// known).
1439    pub fn exceptions(&self) -> Result<Vec<TypeCode>, SystemException> {
1440        self.not_first()?;
1441        Err(not_available())
1442    }
1443
1444    /// `contexts`: `NO_RESOURCES`.
1445    pub fn contexts(&self) -> Result<Vec<String>, SystemException> {
1446        self.not_first()?;
1447        Err(not_available())
1448    }
1449
1450    /// `operation_context`: `NO_RESOURCES`.
1451    pub fn operation_context(&self) -> Result<Vec<String>, SystemException> {
1452        self.not_first()?;
1453        Err(not_available())
1454    }
1455
1456    /// `result`: in `send_reply`, for a DSI servant.
1457    pub fn result(&self) -> Result<Any, SystemException> {
1458        self.check(&[ServerPoint::SendReply])?;
1459        self.dsi
1460            .borrow()
1461            .as_ref()
1462            .filter(|d| d.arguments.is_some())
1463            .map(|d| {
1464                d.result
1465                    .clone()
1466                    .unwrap_or_else(|| Any::new(TypeCode::void(), Value::Void))
1467            })
1468            .ok_or_else(not_available)
1469    }
1470
1471    /// `response_expected`.
1472    pub fn response_expected(&self) -> bool {
1473        self.response_expected
1474    }
1475
1476    /// `sync_scope`.
1477    pub fn sync_scope(&self) -> i16 {
1478        if self.response_expected {
1479            sync_scope::SYNC_WITH_TARGET
1480        } else {
1481            sync_scope::SYNC_NONE
1482        }
1483    }
1484
1485    /// `reply_status`: in the `send_*` points.
1486    pub fn reply_status(&self) -> Result<i16, SystemException> {
1487        self.sending()?;
1488        Ok(self.reply_status.get())
1489    }
1490
1491    /// `forward_reference`: in `send_other`.
1492    pub fn forward_reference(&self) -> Result<ObjectRef, SystemException> {
1493        self.check(&[ServerPoint::SendOther])?;
1494        self.forward.borrow().clone().ok_or_else(invalid_point)
1495    }
1496
1497    /// `get_slot`: the request's slots.
1498    pub fn get_slot(&self, id: SlotId) -> Result<Any, InvalidSlot> {
1499        self.slots
1500            .borrow()
1501            .get(id as usize)
1502            .cloned()
1503            .ok_or(InvalidSlot)
1504    }
1505
1506    /// `set_slot`: what the servant will see in [`PiCurrent`] (when set
1507    /// before `receive_request`).
1508    pub fn set_slot(&self, id: SlotId, data: Any) -> Result<(), InvalidSlot> {
1509        match self.slots.borrow_mut().get_mut(id as usize) {
1510            Some(slot) => {
1511                *slot = data;
1512                Ok(())
1513            }
1514            None => Err(InvalidSlot),
1515        }
1516    }
1517
1518    /// `get_request_service_context`: any context the client sent.
1519    pub fn get_request_service_context(&self, id: u32) -> Result<ServiceContext, SystemException> {
1520        find_context(self.request_contexts, id)
1521    }
1522
1523    /// The contexts the client sent (rustorb).
1524    pub fn request_service_contexts(&self) -> &[ServiceContext] {
1525        self.request_contexts
1526    }
1527
1528    /// `get_reply_service_context`: one added for the reply.
1529    pub fn get_reply_service_context(&self, id: u32) -> Result<ServiceContext, SystemException> {
1530        self.sending()?;
1531        find_context(&self.reply_contexts.borrow(), id)
1532    }
1533
1534    /// `add_reply_service_context`.
1535    pub fn add_reply_service_context(
1536        &self,
1537        sc: ServiceContext,
1538        replace: bool,
1539    ) -> Result<(), SystemException> {
1540        if is_core_context(sc.context_id) {
1541            return Err(duplicate_context());
1542        }
1543        add_context(&mut self.reply_contexts.borrow_mut(), sc, replace)
1544    }
1545
1546    /// `sending_exception`: in `send_exception`. A user exception a static
1547    /// skeleton wrote is an Any of `UNKNOWN`; one a DSI servant set is
1548    /// itself.
1549    pub fn sending_exception(&self) -> Result<Any, SystemException> {
1550        self.check(&[ServerPoint::SendException])?;
1551        match &*self.exception.borrow() {
1552            Some(ServerException::System(e)) => Ok(system_exception_any(e)),
1553            Some(ServerException::User(_)) => Ok(self
1554                .dsi
1555                .borrow()
1556                .as_ref()
1557                .and_then(|d| d.exception.clone())
1558                .unwrap_or_else(unknown_any)),
1559            None => Err(invalid_point()),
1560        }
1561    }
1562
1563    /// The repository id of the exception, in `send_exception` (rustorb).
1564    pub fn sending_exception_id(&self) -> Result<String, SystemException> {
1565        self.check(&[ServerPoint::SendException])?;
1566        match &*self.exception.borrow() {
1567            Some(ServerException::System(e)) => Ok(e.repository_id.clone()),
1568            Some(ServerException::User(id)) => Ok(id.clone()),
1569            None => Err(invalid_point()),
1570        }
1571    }
1572
1573    fn target(&self) -> Result<&ServerTarget, SystemException> {
1574        self.not_first()?;
1575        self.target.ok_or_else(not_available)
1576    }
1577
1578    /// `object_id`.
1579    pub fn object_id(&self) -> Result<Vec<u8>, SystemException> {
1580        Ok(self.target()?.id.clone())
1581    }
1582
1583    /// `adapter_id`: the POA's part of the object key.
1584    pub fn adapter_id(&self) -> Result<Vec<u8>, SystemException> {
1585        Ok(self.target()?.poa.inner.key(&[]))
1586    }
1587
1588    /// `adapter_name`: the names of the POAs from the RootPOA down.
1589    pub fn adapter_name(&self) -> Result<Vec<String>, SystemException> {
1590        let t = self.target()?;
1591        let mut names = vec!["RootPOA".to_owned()];
1592        names.extend(t.poa.inner.path().iter().cloned());
1593        Ok(names)
1594    }
1595
1596    /// `orb_id` (`-ORBid`).
1597    pub fn orb_id(&self) -> &str {
1598        &self.orb.inner.options.orb_id
1599    }
1600
1601    /// `server_id` (`-ORBServerId`).
1602    pub fn server_id(&self) -> &str {
1603        &self.orb.inner.options.server_id
1604    }
1605
1606    fn servant(&self) -> Result<Arc<dyn Servant>, SystemException> {
1607        self.not_first()?;
1608        self.servant.borrow().clone().ok_or_else(not_available)
1609    }
1610
1611    /// `target_most_derived_interface`: from `receive_request` on.
1612    pub fn target_most_derived_interface(&self) -> Result<String, SystemException> {
1613        Ok(self.servant()?.repository_id().to_owned())
1614    }
1615
1616    /// `target_is_a`.
1617    pub fn target_is_a(&self, id: &str) -> Result<bool, SystemException> {
1618        let servant = self.servant()?;
1619        Ok(id == "IDL:omg.org/CORBA/Object:1.0" || servant.is_a(id))
1620    }
1621
1622    /// `get_server_policy`: a policy of the target's POA.
1623    pub fn get_server_policy(
1624        &self,
1625        policy_type: PolicyType,
1626    ) -> Result<PolicyValue, SystemException> {
1627        let t = self.target.ok_or_else(not_available)?;
1628        policy_of(t.poa.inner.policies(), policy_type)
1629    }
1630
1631    pub(crate) fn set_servant(&self, servant: &Arc<dyn Servant>) {
1632        *self.servant.borrow_mut() = Some(Arc::clone(servant));
1633    }
1634
1635    pub(crate) fn set_dsi(&self, dsi: DsiParams) {
1636        *self.dsi.borrow_mut() = Some(dsi);
1637    }
1638
1639    pub(crate) fn reply_contexts(&self) -> Vec<ServiceContext> {
1640        self.reply_contexts.borrow().clone()
1641    }
1642
1643    /// Makes the request's slots those of the thread while the guard
1644    /// lives (the servant sees them).
1645    pub(crate) fn enter_thread_scope(&self, pi: &Interceptors) -> ThreadSlotsGuard {
1646        ThreadSlotsGuard::enter(pi.serial, self.slots.borrow().clone())
1647    }
1648
1649    fn enter(&self, ending: &ServerEnding) {
1650        *self.exception.borrow_mut() = None;
1651        *self.forward.borrow_mut() = None;
1652        let (point, status) = match ending {
1653            ServerEnding::Reply => (ServerPoint::SendReply, reply_status::SUCCESSFUL),
1654            ServerEnding::Exception(e) => {
1655                *self.exception.borrow_mut() = Some(e.clone());
1656                let status = match e {
1657                    ServerException::System(_) => reply_status::SYSTEM_EXCEPTION,
1658                    ServerException::User(_) => reply_status::USER_EXCEPTION,
1659                };
1660                (ServerPoint::SendException, status)
1661            }
1662            ServerEnding::Forward(to) => {
1663                *self.forward.borrow_mut() = Some(to.clone());
1664                (ServerPoint::SendOther, reply_status::LOCATION_FORWARD)
1665            }
1666        };
1667        self.point.set(point);
1668        self.reply_status.set(status);
1669    }
1670}
1671
1672fn policy_of(p: &Policies, policy_type: PolicyType) -> Result<PolicyValue, SystemException> {
1673    use crate::policy::*;
1674    let policy = match policy_type {
1675        THREAD_POLICY_ID => Policy::Thread(p.thread),
1676        BIDIRECTIONAL_POLICY_TYPE => Policy::Bidirectional(p.bidirectional),
1677        LIFESPAN_POLICY_ID => Policy::Lifespan(p.lifespan),
1678        ID_UNIQUENESS_POLICY_ID => Policy::IdUniqueness(p.id_uniqueness),
1679        ID_ASSIGNMENT_POLICY_ID => Policy::IdAssignment(p.id_assignment),
1680        IMPLICIT_ACTIVATION_POLICY_ID => Policy::ImplicitActivation(p.implicit_activation),
1681        SERVANT_RETENTION_POLICY_ID => Policy::ServantRetention(p.servant_retention),
1682        REQUEST_PROCESSING_POLICY_ID => Policy::RequestProcessing(p.request_processing),
1683        _ => {
1684            return Err(SystemException::new(
1685                SystemExceptionKind::INV_POLICY,
1686                minor::INVALID_POLICY_TYPE,
1687                CompletionStatus::No,
1688            ));
1689        }
1690    };
1691    Ok(PolicyValue::Poa(policy))
1692}
1693
1694/// Runs `receive_request_service_contexts` on each interceptor. `Err` is
1695/// how the request ends when one of them raised.
1696pub(crate) fn receive_request_service_contexts(
1697    pi: &Interceptors,
1698    info: &ServerRequestInfo<'_>,
1699) -> Result<(), ServerEnding> {
1700    info.point.set(ServerPoint::ReceiveRequestServiceContexts);
1701    for (k, i) in pi.server.iter().enumerate() {
1702        if let Err(e) = catch_server(|| i.receive_request_service_contexts(info)) {
1703            return Err(end_server(pi, info, ServerEnding::from_error(e), k));
1704        }
1705    }
1706    Ok(())
1707}
1708
1709/// Runs `receive_request` on each interceptor.
1710pub(crate) fn receive_request(
1711    pi: &Interceptors,
1712    info: &ServerRequestInfo<'_>,
1713) -> Result<(), ServerEnding> {
1714    info.point.set(ServerPoint::ReceiveRequest);
1715    for i in &pi.server {
1716        if let Err(e) = catch_server(|| i.receive_request(info)) {
1717            return Err(send_reply(pi, info, ServerEnding::from_error(e)));
1718        }
1719    }
1720    Ok(())
1721}
1722
1723/// Runs the `send_*` points on every interceptor, in the reverse order,
1724/// and returns the reply to send.
1725pub(crate) fn send_reply(
1726    pi: &Interceptors,
1727    info: &ServerRequestInfo<'_>,
1728    ending: ServerEnding,
1729) -> ServerEnding {
1730    end_server(pi, info, ending, pi.server.len())
1731}
1732
1733fn end_server(
1734    pi: &Interceptors,
1735    info: &ServerRequestInfo<'_>,
1736    mut ending: ServerEnding,
1737    started: usize,
1738) -> ServerEnding {
1739    for i in pi.server[..started].iter().rev() {
1740        info.enter(&ending);
1741        let result = match &ending {
1742            ServerEnding::Reply => {
1743                catch_server(|| i.send_reply(info).map_err(InterceptError::System))
1744            }
1745            ServerEnding::Exception(_) => catch_server(|| i.send_exception(info)),
1746            ServerEnding::Forward(_) => catch_server(|| i.send_other(info)),
1747        };
1748        if let Err(e) = result {
1749            ending = ServerEnding::from_error(e);
1750        }
1751    }
1752    ending
1753}
1754
1755fn catch_server(f: impl FnOnce() -> Result<(), InterceptError>) -> Result<(), InterceptError> {
1756    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| {
1757        trace::warning!("server request interceptor panicked");
1758        Err(InterceptError::System(SystemException::new(
1759            SystemExceptionKind::UNKNOWN,
1760            0,
1761            CompletionStatus::Maybe,
1762        )))
1763    })
1764}
1765
1766// --- IOR interceptors ----------------------------------------------------------
1767
1768/// `PortableInterceptor::IORInfo`: a new POA, for
1769/// [`IorInterceptor::establish_components`].
1770pub struct IorInfo<'a> {
1771    policies: &'a Policies,
1772    adapter_name: Vec<String>,
1773    components: RefCell<Vec<TaggedComponent>>,
1774}
1775
1776impl fmt::Debug for IorInfo<'_> {
1777    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1778        f.debug_struct("IorInfo")
1779            .field("adapter_name", &self.adapter_name)
1780            .finish_non_exhaustive()
1781    }
1782}
1783
1784impl IorInfo<'_> {
1785    /// `get_effective_policy`: a policy of the POA.
1786    pub fn get_effective_policy(
1787        &self,
1788        policy_type: PolicyType,
1789    ) -> Result<PolicyValue, SystemException> {
1790        policy_of(self.policies, policy_type)
1791    }
1792
1793    /// The names of the POAs from the RootPOA down to the new one
1794    /// (rustorb).
1795    pub fn adapter_name(&self) -> &[String] {
1796        &self.adapter_name
1797    }
1798
1799    /// `add_ior_component`: adds `component` to every profile of the
1800    /// POA's references.
1801    pub fn add_ior_component(&self, component: TaggedComponent) {
1802        self.components.borrow_mut().push(component);
1803    }
1804
1805    /// `add_ior_component_to_profile`: only `TAG_INTERNET_IOP`, the one
1806    /// profile rustorb makes (`BAD_PARAM` for another).
1807    pub fn add_ior_component_to_profile(
1808        &self,
1809        component: TaggedComponent,
1810        profile_id: u32,
1811    ) -> Result<(), SystemException> {
1812        if profile_id != TAG_INTERNET_IOP {
1813            return Err(SystemException::new(
1814                SystemExceptionKind::BAD_PARAM,
1815                minor::UNKNOWN_PROFILE,
1816                CompletionStatus::No,
1817            ));
1818        }
1819        self.add_ior_component(component);
1820        Ok(())
1821    }
1822}
1823
1824/// The components the IOR interceptors of `orb` add to the references of
1825/// a new POA with `policies`, whose names below the RootPOA are `path`.
1826pub(crate) fn establish_components(
1827    orb: &Orb,
1828    policies: &Policies,
1829    path: &[String],
1830) -> Vec<TaggedComponent> {
1831    let Some(pi) = orb.interceptors() else {
1832        return Vec::new();
1833    };
1834    if pi.ior.is_empty() {
1835        return Vec::new();
1836    }
1837    let mut adapter_name = vec!["RootPOA".to_owned()];
1838    adapter_name.extend(path.iter().cloned());
1839    let info = IorInfo {
1840        policies,
1841        adapter_name,
1842        components: RefCell::new(Vec::new()),
1843    };
1844    for i in &pi.ior {
1845        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1846            i.establish_components(&info)
1847        }));
1848        match result {
1849            Ok(Ok(())) => {}
1850            Ok(Err(e)) => trace::warning!(
1851                "IORInterceptor {:?} raised {e} in establish_components (ignored)",
1852                i.name()
1853            ),
1854            Err(_) => trace::warning!(
1855                "IORInterceptor {:?} panicked in establish_components (ignored)",
1856                i.name()
1857            ),
1858        }
1859    }
1860    info.components.into_inner()
1861}
1862
1863/// The information of a client request is held across the awaits of an
1864/// async call.
1865#[allow(dead_code)]
1866fn assert_send() {
1867    fn is_send<T: Send>() {}
1868    is_send::<ClientRequestInfo<'static>>();
1869}