1
//! Implementation for encoding and decoding of ChanCells.
2

            
3
use super::{CELL_DATA_LEN, ChanCell};
4
use crate::Error;
5
use crate::chancell::{ChanCmd, ChanMsg, CircId};
6
use tor_bytes::{self, Reader, Writer};
7
use tor_error::internal;
8

            
9
use bytes::BytesMut;
10

            
11
/// This object can be used to encode and decode channel cells.
12
///
13
/// NOTE: only link protocol versions 4 and higher are supported.
14
/// VERSIONS cells are not supported via the encoder/decoder, since
15
/// VERSIONS cells always use a two-byte circuit-ID for backwards
16
/// compatibility with protocol versions < 4.
17
///
18
/// The implemented format is one of the following:
19
///
20
/// Variable-length cells:
21
///
22
/// ```ignore
23
/// u32 circid;
24
/// u8 command;
25
/// u16 len;
26
/// u8 body[len];
27
/// ```
28
///
29
/// Fixed-width cells:
30
///
31
/// ```ignore
32
/// u32 circid;
33
/// u8 command;
34
/// u8 body[509];
35
/// ```
36
pub struct ChannelCodec {
37
    #[allow(dead_code)] // We don't support any link versions where this matters
38
    /// The link protocol version being used for this channel.
39
    ///
40
    /// (We don't currently support any versions of the link protocol
41
    /// where this version matters, but for protocol versions below 4, it would
42
    /// have affected the length of the circuit ID.)
43
    link_version: u16,
44
}
45

            
46
impl ChannelCodec {
47
    /// Create a new ChannelCodec with a given link protocol version
48
4611
    pub fn new(link_version: u16) -> Self {
49
4611
        ChannelCodec { link_version }
50
4611
    }
51

            
52
    /// Return the link protocol version of this codec.
53
742
    pub fn link_version(&self) -> u16 {
54
742
        self.link_version
55
742
    }
56

            
57
    /// Write the given cell into the provided BytesMut object.
58
87
    pub fn write_cell<M: ChanMsg>(
59
87
        &mut self,
60
87
        item: ChanCell<M>,
61
87
        dst: &mut BytesMut,
62
87
    ) -> crate::Result<()> {
63
87
        let ChanCell { circid, msg } = item;
64
87
        let cmd = msg.cmd();
65
87
        dst.write_u32(CircId::get_or_zero(circid));
66
87
        dst.write_u8(cmd.into());
67

            
68
        // this is typically 5, but not always
69
        // (for example if we were given a non-empty `dst`)
70
87
        let pos = dst.len();
71

            
72
        // now write the cell body and handle the length.
73
87
        if cmd.is_var_cell() {
74
16
            dst.write_u16(0);
75
16
            msg.encode_onto(dst)?;
76
16
            let len = dst.len() - pos - 2;
77
16
            if len > u16::MAX as usize {
78
                return Err(Error::Internal(internal!("ran out of space for varcell")));
79
16
            }
80
            // go back and set the length.
81
16
            *(<&mut [u8; 2]>::try_from(&mut dst[pos..pos + 2])
82
16
                .expect("two-byte slice was not two bytes!?")) = (len as u16).to_be_bytes();
83
        } else {
84
71
            msg.encode_onto(dst)?;
85
71
            let len = dst.len() - pos;
86
71
            if len > CELL_DATA_LEN {
87
                return Err(Error::Internal(internal!("ran out of space for cell")));
88
71
            }
89
            // pad to end of fixed-length cell
90
71
            dst.write_zeros(CELL_DATA_LEN - len);
91
        }
92
87
        Ok(())
93
87
    }
94

            
95
    /// Try to decode a cell from the provided BytesMut object.
96
    ///
97
    /// On a definite decoding error, return Err(_).  On a cell that might
98
    /// just be truncated, return Ok(None).
99
1000
    pub fn decode_cell<M: ChanMsg>(
100
1000
        &mut self,
101
1000
        src: &mut BytesMut,
102
1000
    ) -> crate::Result<Option<ChanCell<M>>> {
103
        /// Wrap `be` as an appropriate type.
104
212
        fn wrap_err(be: tor_bytes::Error) -> crate::Error {
105
212
            crate::Error::BytesErr {
106
212
                err: be,
107
212
                parsed: "channel cell",
108
212
            }
109
212
        }
110

            
111
1000
        if src.len() < 7 {
112
            // Smallest possible command: varcell with len 0
113
199
            return Ok(None);
114
801
        }
115
801
        let cmd: ChanCmd = src[4].into();
116
801
        let varcell = cmd.is_var_cell();
117
801
        let cell_len: usize = if varcell {
118
549
            let msg_len = u16::from_be_bytes(
119
549
                src[5..7]
120
549
                    .try_into()
121
549
                    .expect("Two-byte slice was not two bytes long!?"),
122
            );
123
549
            msg_len as usize + 7
124
        } else {
125
252
            514
126
        };
127
801
        if src.len() < cell_len {
128
518
            return Ok(None);
129
283
        }
130

            
131
283
        let cell = src.split_to(cell_len).freeze();
132
        //trace!("{:?} cell body ({}) is {:?}", cmd, cell.len(), &cell[..]);
133
283
        let mut r = Reader::from_bytes(&cell);
134
283
        let circid: Option<CircId> = CircId::new(r.take_u32().map_err(wrap_err)?);
135
283
        r.advance(if varcell { 3 } else { 1 }).map_err(wrap_err)?;
136
283
        let msg = M::decode_from_reader(cmd, &mut r).map_err(wrap_err)?;
137

            
138
275
        if !cmd.accepts_circid_val(circid) {
139
4
            return Err(Error::ChanProto(format!(
140
4
                "Invalid circuit ID {} for cell command {}",
141
4
                CircId::get_or_zero(circid),
142
4
                cmd
143
4
            )));
144
271
        }
145
271
        Ok(Some(ChanCell { circid, msg }))
146
1000
    }
147
}