Skip to main content

rustorb_giop/
message.rs

1use std::sync::Arc;
2
3use rustorb_cdr::{ByteOrder, CdrDecode, CdrEncode, CdrVersion, Decoder, Encoder, Segment};
4
5use crate::{Error, Ior, MessageHeader, MsgType, Result, ServiceContext, TaggedProfile, Version};
6
7/// Values of the GIOP 1.2 `response_flags` octet.
8pub mod response_flags {
9    /// Oneway with no synchronisation (`SYNC_NONE`, `SYNC_WITH_TRANSPORT`).
10    pub const NONE: u8 = 0x00;
11    /// Oneway answered once the server has the request (`SYNC_WITH_SERVER`).
12    pub const SYNC_WITH_SERVER: u8 = 0x01;
13    /// Normal two-way call (`SYNC_WITH_TARGET`).
14    pub const SYNC_WITH_TARGET: u8 = 0x03;
15}
16
17/// `GIOP::AddressingDisposition`, the kind of [`TargetAddress`].
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub enum AddressingDisposition {
20    /// `KeyAddr` (0).
21    Key,
22    /// `ProfileAddr` (1).
23    Profile,
24    /// `ReferenceAddr` (2).
25    Reference,
26}
27
28impl AddressingDisposition {
29    /// The discriminator value.
30    pub fn to_i16(self) -> i16 {
31        self as i16
32    }
33
34    /// Converts a discriminator value.
35    pub fn from_i16(value: i16) -> Result<AddressingDisposition> {
36        match value {
37            0 => Ok(AddressingDisposition::Key),
38            1 => Ok(AddressingDisposition::Profile),
39            2 => Ok(AddressingDisposition::Reference),
40            other => Err(Error::InvalidAddressingDisposition(other)),
41        }
42    }
43}
44
45/// `GIOP::TargetAddress`, the object a request is sent to.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum TargetAddress {
48    /// The object key from the profile.
49    Key(Vec<u8>),
50    /// A whole profile.
51    Profile(TaggedProfile),
52    /// An IOR and the index of the profile that was used.
53    Reference {
54        /// Index into `ior.profiles`.
55        selected_profile_index: u32,
56        /// The full reference.
57        ior: Ior,
58    },
59}
60
61impl TargetAddress {
62    /// The addressing disposition of this target.
63    pub fn disposition(&self) -> AddressingDisposition {
64        match self {
65            TargetAddress::Key(_) => AddressingDisposition::Key,
66            TargetAddress::Profile(_) => AddressingDisposition::Profile,
67            TargetAddress::Reference { .. } => AddressingDisposition::Reference,
68        }
69    }
70
71    /// The object key when addressed by key.
72    pub fn object_key(&self) -> Option<&[u8]> {
73        match self {
74            TargetAddress::Key(key) => Some(key),
75            _ => None,
76        }
77    }
78
79    pub(crate) fn encode(&self, enc: &mut Encoder) -> Result<()> {
80        enc.write_i16(self.disposition().to_i16());
81        match self {
82            TargetAddress::Key(key) => enc.write_octet_seq(key)?,
83            TargetAddress::Profile(profile) => profile.encode(enc)?,
84            TargetAddress::Reference {
85                selected_profile_index,
86                ior,
87            } => {
88                enc.write_u32(*selected_profile_index);
89                ior.encode(enc)?;
90            }
91        }
92        Ok(())
93    }
94
95    pub(crate) fn decode(dec: &mut Decoder<'_>) -> Result<TargetAddress> {
96        Ok(match AddressingDisposition::from_i16(dec.read_i16()?)? {
97            AddressingDisposition::Key => TargetAddress::Key(dec.read_octet_seq()?.to_vec()),
98            AddressingDisposition::Profile => TargetAddress::Profile(TaggedProfile::decode(dec)?),
99            AddressingDisposition::Reference => TargetAddress::Reference {
100                selected_profile_index: dec.read_u32()?,
101                ior: Ior::decode(dec)?,
102            },
103        })
104    }
105}
106
107/// The header of a `Request` message, in its GIOP 1.2 shape.
108///
109/// GIOP 1.0/1.1 requests are mapped onto it: `response_expected` becomes
110/// [`response_flags::SYNC_WITH_TARGET`] or [`response_flags::NONE`], and the
111/// object key becomes [`TargetAddress::Key`].
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct RequestHeader {
114    /// Request id, unique per connection and direction.
115    pub request_id: u32,
116    /// See [`response_flags`].
117    pub response_flags: u8,
118    /// The target object.
119    pub target: TargetAddress,
120    /// Operation name, or `_get_x`/`_set_x` for attributes.
121    pub operation: String,
122    /// Service contexts.
123    pub service_context: Vec<ServiceContext>,
124    /// `requesting_principal`, only sent by GIOP 1.0 and 1.1 and usually
125    /// empty.
126    pub requesting_principal: Vec<u8>,
127}
128
129impl RequestHeader {
130    /// Whether the client waits for a reply.
131    pub fn response_expected(&self) -> bool {
132        self.response_flags & 0x01 != 0
133    }
134}
135
136/// `GIOP::ReplyStatusType`.
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
138pub enum ReplyStatus {
139    /// `NO_EXCEPTION` (0).
140    NoException,
141    /// `USER_EXCEPTION` (1).
142    UserException,
143    /// `SYSTEM_EXCEPTION` (2); the body is a [`SystemExceptionBody`].
144    SystemException,
145    /// `LOCATION_FORWARD` (3); the body is an [`Ior`].
146    LocationForward,
147    /// `LOCATION_FORWARD_PERM` (4), GIOP 1.2.
148    LocationForwardPerm,
149    /// `NEEDS_ADDRESSING_MODE` (5), GIOP 1.2; the body is an addressing
150    /// disposition.
151    NeedsAddressingMode,
152}
153
154impl ReplyStatus {
155    /// The wire value.
156    pub fn to_u32(self) -> u32 {
157        self as u32
158    }
159
160    /// Converts a wire value.
161    pub fn from_u32(value: u32) -> Result<ReplyStatus> {
162        Ok(match value {
163            0 => ReplyStatus::NoException,
164            1 => ReplyStatus::UserException,
165            2 => ReplyStatus::SystemException,
166            3 => ReplyStatus::LocationForward,
167            4 => ReplyStatus::LocationForwardPerm,
168            5 => ReplyStatus::NeedsAddressingMode,
169            other => return Err(Error::InvalidReplyStatus(other)),
170        })
171    }
172}
173
174/// The header of a `Reply` message.
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct ReplyHeader {
177    /// Id of the request this answers.
178    pub request_id: u32,
179    /// Outcome of the request.
180    pub reply_status: ReplyStatus,
181    /// Service contexts.
182    pub service_context: Vec<ServiceContext>,
183}
184
185/// The header of a `CancelRequest` message.
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub struct CancelRequestHeader {
188    /// Id of the request to cancel.
189    pub request_id: u32,
190}
191
192/// The header of a `LocateRequest` message.
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct LocateRequestHeader {
195    /// Request id.
196    pub request_id: u32,
197    /// The object to locate; always [`TargetAddress::Key`] for GIOP 1.0/1.1.
198    pub target: TargetAddress,
199}
200
201/// `GIOP::LocateStatusType`.
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
203pub enum LocateStatus {
204    /// `UNKNOWN_OBJECT` (0).
205    UnknownObject,
206    /// `OBJECT_HERE` (1).
207    ObjectHere,
208    /// `OBJECT_FORWARD` (2); the body is an [`Ior`].
209    ObjectForward,
210    /// `OBJECT_FORWARD_PERM` (3), GIOP 1.2.
211    ObjectForwardPerm,
212    /// `LOC_SYSTEM_EXCEPTION` (4), GIOP 1.2.
213    LocSystemException,
214    /// `LOC_NEEDS_ADDRESSING_MODE` (5), GIOP 1.2.
215    LocNeedsAddressingMode,
216}
217
218impl LocateStatus {
219    /// The wire value.
220    pub fn to_u32(self) -> u32 {
221        self as u32
222    }
223
224    /// Converts a wire value.
225    pub fn from_u32(value: u32) -> Result<LocateStatus> {
226        Ok(match value {
227            0 => LocateStatus::UnknownObject,
228            1 => LocateStatus::ObjectHere,
229            2 => LocateStatus::ObjectForward,
230            3 => LocateStatus::ObjectForwardPerm,
231            4 => LocateStatus::LocSystemException,
232            5 => LocateStatus::LocNeedsAddressingMode,
233            other => return Err(Error::InvalidLocateStatus(other)),
234        })
235    }
236}
237
238/// The header of a `LocateReply` message.
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240pub struct LocateReplyHeader {
241    /// Id of the locate request this answers.
242    pub request_id: u32,
243    /// Outcome.
244    pub locate_status: LocateStatus,
245}
246
247/// The header of a `Fragment` message.
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249pub struct FragmentHeader {
250    /// Id of the fragmented message; GIOP 1.2 only.
251    pub request_id: Option<u32>,
252}
253
254/// The body of a message: the bytes after the message header, kept with
255/// their offset in the message so that CDR alignment is preserved.
256///
257/// The bytes are shared with the buffer the message was read into, not
258/// copied: cloning a body is cheap.
259#[derive(Debug, Clone)]
260pub struct Body {
261    buf: Arc<Vec<u8>>,
262    start: usize,
263    offset: usize,
264    segments: Vec<Segment>,
265    byte_order: ByteOrder,
266    version: CdrVersion,
267}
268
269impl PartialEq for Body {
270    fn eq(&self, other: &Body) -> bool {
271        self.as_bytes() == other.as_bytes()
272            && self.offset == other.offset
273            && self.segments == other.segments
274            && self.byte_order == other.byte_order
275            && self.version == other.version
276    }
277}
278
279impl Eq for Body {}
280
281impl Body {
282    fn new(dec: &Decoder<'_>, src: &Source<'_>) -> Body {
283        let start = src.buf.len() - dec.remaining();
284        Body {
285            buf: Arc::clone(src.buf),
286            start,
287            offset: dec.position(),
288            segments: src
289                .segments
290                .iter()
291                .filter(|s| s.start > start)
292                .map(|s| Segment {
293                    start: s.start - start,
294                    offset: s.offset,
295                })
296                .collect(),
297            byte_order: dec.byte_order(),
298            version: dec.version(),
299        }
300    }
301
302    /// The body bytes.
303    pub fn as_bytes(&self) -> &[u8] {
304        &self.buf[self.start..]
305    }
306
307    /// Offset of the first body byte from the start of the message.
308    pub fn offset(&self) -> usize {
309        self.offset
310    }
311
312    /// Byte order of the body.
313    pub fn byte_order(&self) -> ByteOrder {
314        self.byte_order
315    }
316
317    /// Whether the body is empty.
318    pub fn is_empty(&self) -> bool {
319        self.as_bytes().is_empty()
320    }
321
322    /// Where the alignment restarts inside the body: one segment for each
323    /// fragment after the first in a message joined by a
324    /// [`FragmentAssembler`](crate::FragmentAssembler), empty otherwise.
325    pub fn segments(&self) -> &[Segment] {
326        &self.segments
327    }
328
329    /// A CDR decoder over the body with the message's alignment.
330    pub fn decoder(&self) -> Decoder<'_> {
331        let mut dec =
332            Decoder::with_offset(self.as_bytes(), self.byte_order, self.version, self.offset);
333        dec.set_segments(&self.segments);
334        dec.set_shared(&self.buf);
335        dec
336    }
337}
338
339/// The message a body is decoded from: its bytes and alignment segments.
340struct Source<'a> {
341    buf: &'a Arc<Vec<u8>>,
342    segments: &'a [Segment],
343}
344
345/// A decoded GIOP message.
346#[derive(Debug, Clone, PartialEq, Eq)]
347pub enum Message {
348    /// `Request`; the body holds the in and inout arguments.
349    Request {
350        /// Request header.
351        header: RequestHeader,
352        /// Arguments.
353        body: Body,
354    },
355    /// `Reply`; the body depends on the reply status.
356    Reply {
357        /// Reply header.
358        header: ReplyHeader,
359        /// Result, exception or forward reference.
360        body: Body,
361    },
362    /// `CancelRequest`.
363    CancelRequest(CancelRequestHeader),
364    /// `LocateRequest`.
365    LocateRequest(LocateRequestHeader),
366    /// `LocateReply`; the body depends on the locate status.
367    LocateReply {
368        /// Locate reply header.
369        header: LocateReplyHeader,
370        /// Forward reference or exception, if any.
371        body: Body,
372    },
373    /// `CloseConnection`.
374    CloseConnection,
375    /// `MessageError`.
376    MessageError,
377    /// `Fragment`; the body continues an earlier message.
378    Fragment {
379        /// Fragment header.
380        header: FragmentHeader,
381        /// Continuation bytes.
382        body: Body,
383    },
384}
385
386impl Message {
387    /// The message type.
388    pub fn msg_type(&self) -> MsgType {
389        match self {
390            Message::Request { .. } => MsgType::Request,
391            Message::Reply { .. } => MsgType::Reply,
392            Message::CancelRequest(_) => MsgType::CancelRequest,
393            Message::LocateRequest(_) => MsgType::LocateRequest,
394            Message::LocateReply { .. } => MsgType::LocateReply,
395            Message::CloseConnection => MsgType::CloseConnection,
396            Message::MessageError => MsgType::MessageError,
397            Message::Fragment { .. } => MsgType::Fragment,
398        }
399    }
400}
401
402/// Decodes one complete GIOP message: the header followed by exactly
403/// `message_size` bytes.
404///
405/// A message with the more-fragments flag set is decoded only as far as
406/// its own bytes allow; pass fragments through a
407/// [`FragmentAssembler`](crate::FragmentAssembler) first to get the whole
408/// message.
409pub fn decode_message(buf: &[u8]) -> Result<(MessageHeader, Message)> {
410    decode_segmented(&Arc::new(buf.to_vec()), &[])
411}
412
413/// Decodes a message whose alignment restarts at `segments`, as one joined
414/// from fragments. The bodies share `buf`.
415pub(crate) fn decode_segmented(
416    buf: &Arc<Vec<u8>>,
417    segments: &[Segment],
418) -> Result<(MessageHeader, Message)> {
419    let header = MessageHeader::parse(buf)?;
420    let expected = header.total_len();
421    if buf.len() < expected {
422        return Err(Error::Truncated {
423            expected,
424            actual: buf.len(),
425        });
426    }
427    if buf.len() > expected {
428        return Err(Error::TrailingBytes(buf.len() - expected));
429    }
430    let mut dec = Decoder::new(buf, header.byte_order, header.version.cdr_version());
431    dec.set_segments(segments);
432    dec.skip(MessageHeader::SIZE)?;
433    let src = Source { buf, segments };
434    let message = decode_body(&header, &mut dec, &src)?;
435    Ok((header, message))
436}
437
438fn decode_body(header: &MessageHeader, dec: &mut Decoder<'_>, src: &Source<'_>) -> Result<Message> {
439    let v12 = header.version >= Version::V1_2;
440    Ok(match header.msg_type {
441        MsgType::Request => {
442            let header = if v12 {
443                let request_id = dec.read_u32()?;
444                let response_flags = dec.read_octet()?;
445                dec.skip(3)?;
446                let target = TargetAddress::decode(dec)?;
447                let operation = dec.read_string()?;
448                let service_context = Vec::decode(dec)?;
449                RequestHeader {
450                    request_id,
451                    response_flags,
452                    target,
453                    operation,
454                    service_context,
455                    requesting_principal: Vec::new(),
456                }
457            } else {
458                let service_context = Vec::decode(dec)?;
459                let request_id = dec.read_u32()?;
460                let response_expected = dec.read_bool()?;
461                if header.version.minor == 1 {
462                    dec.skip(3)?;
463                }
464                let object_key = dec.read_octet_seq()?.to_vec();
465                let operation = dec.read_string()?;
466                let requesting_principal = dec.read_octet_seq()?.to_vec();
467                RequestHeader {
468                    request_id,
469                    response_flags: if response_expected {
470                        response_flags::SYNC_WITH_TARGET
471                    } else {
472                        response_flags::NONE
473                    },
474                    target: TargetAddress::Key(object_key),
475                    operation,
476                    service_context,
477                    requesting_principal,
478                }
479            };
480            Message::Request {
481                header,
482                body: body_after_header(dec, src, v12),
483            }
484        }
485        MsgType::Reply => {
486            let header = if v12 {
487                let request_id = dec.read_u32()?;
488                let reply_status = ReplyStatus::from_u32(dec.read_u32()?)?;
489                let service_context = Vec::decode(dec)?;
490                ReplyHeader {
491                    request_id,
492                    reply_status,
493                    service_context,
494                }
495            } else {
496                let service_context = Vec::decode(dec)?;
497                let request_id = dec.read_u32()?;
498                let reply_status = ReplyStatus::from_u32(dec.read_u32()?)?;
499                ReplyHeader {
500                    request_id,
501                    reply_status,
502                    service_context,
503                }
504            };
505            Message::Reply {
506                header,
507                body: body_after_header(dec, src, v12),
508            }
509        }
510        MsgType::CancelRequest => Message::CancelRequest(CancelRequestHeader {
511            request_id: dec.read_u32()?,
512        }),
513        MsgType::LocateRequest => {
514            let request_id = dec.read_u32()?;
515            let target = if v12 {
516                TargetAddress::decode(dec)?
517            } else {
518                TargetAddress::Key(dec.read_octet_seq()?.to_vec())
519            };
520            Message::LocateRequest(LocateRequestHeader { request_id, target })
521        }
522        MsgType::LocateReply => {
523            let header = LocateReplyHeader {
524                request_id: dec.read_u32()?,
525                locate_status: LocateStatus::from_u32(dec.read_u32()?)?,
526            };
527            Message::LocateReply {
528                header,
529                body: body_after_header(dec, src, v12),
530            }
531        }
532        MsgType::CloseConnection => Message::CloseConnection,
533        MsgType::MessageError => Message::MessageError,
534        MsgType::Fragment => {
535            let request_id = if v12 { Some(dec.read_u32()?) } else { None };
536            Message::Fragment {
537                header: FragmentHeader { request_id },
538                body: Body::new(dec, src),
539            }
540        }
541    })
542}
543
544/// In GIOP 1.2 a body is aligned to 8 bytes. Senders may leave out the
545/// padding when there is no body, so padding is only skipped when there
546/// are bytes past it.
547fn body_after_header(dec: &mut Decoder<'_>, src: &Source<'_>, v12: bool) -> Body {
548    if v12 {
549        let pad = (8 - dec.position() % 8) % 8;
550        if dec.remaining() > pad {
551            dec.skip(pad).expect("checked remaining");
552        } else {
553            dec.skip(dec.remaining()).expect("checked remaining");
554        }
555    }
556    Body::new(dec, src)
557}
558
559/// `CORBA::CompletionStatus`.
560#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
561pub enum CompletionStatus {
562    /// `COMPLETED_YES` (0).
563    Yes,
564    /// `COMPLETED_NO` (1).
565    No,
566    /// `COMPLETED_MAYBE` (2).
567    Maybe,
568}
569
570/// The body of a `SYSTEM_EXCEPTION` reply.
571#[derive(Debug, Clone, PartialEq, Eq)]
572pub struct SystemExceptionBody {
573    /// Repository id such as `IDL:omg.org/CORBA/OBJECT_NOT_EXIST:1.0`.
574    pub exception_id: String,
575    /// Minor code.
576    pub minor_code_value: u32,
577    /// Whether the operation completed.
578    pub completion_status: CompletionStatus,
579}
580
581impl CdrEncode for SystemExceptionBody {
582    fn encode(&self, enc: &mut Encoder) -> rustorb_cdr::Result<()> {
583        enc.write_string(&self.exception_id)?;
584        enc.write_u32(self.minor_code_value);
585        enc.write_u32(self.completion_status as u32);
586        Ok(())
587    }
588}
589
590impl CdrDecode for SystemExceptionBody {
591    fn decode(dec: &mut Decoder<'_>) -> rustorb_cdr::Result<Self> {
592        let exception_id = dec.read_string()?;
593        let minor_code_value = dec.read_u32()?;
594        let completion_status = match dec.read_u32()? {
595            0 => CompletionStatus::Yes,
596            1 => CompletionStatus::No,
597            2 => CompletionStatus::Maybe,
598            other => return Err(rustorb_cdr::Error::InvalidEnumValue(other)),
599        };
600        Ok(SystemExceptionBody {
601            exception_id,
602            minor_code_value,
603            completion_status,
604        })
605    }
606}