1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
//! Declare a restricted variant of our message types.

/// Re-export tor_bytes and paste here, so that the macro can use it.
pub use {paste, tor_bytes};

/// Declare a restricted version of
/// [`AnyRelayMsg`](crate::relaycell::msg::AnyRelayMsg) or
/// [`AnyChanMsg`](crate::chancell::msg::AnyChanMsg).
///
/// Frequently we only want to handle a subset of the possible channel or relay
/// commands that we might see.  In those situations, it makes sense to define a
/// a message types that will only try to parse the allowable commands.  That way,
/// we can avoid exposing any unnecessary parsers to a possible attacker.
///
/// The restricted message type is an enum, and is declared with a syntax as follows:
/// ```
/// use tor_cell::{restrict::restricted_msg, relaycell::RelayCell};
///
/// restricted_msg! {
///     enum OpenStreamMsg : RelayMsg {
///         Data,
///         Sendme,
///         End,
///         _ => Unrecognized,
///    }
/// }
///
/// type OpenStreamCell = RelayCell<OpenStreamMsg>;
/// ```
///
/// Instead of `RelayMsg`, you can say `ChanMsg` to get a restricted channel
/// message.
///
/// Only message variants exposed from the `tor_cell::{chan,relay}cell::msg` are
/// supported.
///
/// You can omit the `_ => Unrecognized` clause at the end.  If you do, then any
/// unexpected command types will be treated as a parse error.
#[macro_export]
macro_rules! restricted_msg {
    {
        $(#[$meta:meta])*
        $(@omit_from $omit_from:literal)?
        $v:vis enum $name:ident : RelayMsg {
            $($tt:tt)*
        }
    } => {
        $crate::restrict::restricted_msg!{
            [
            any_type: $crate::relaycell::msg::AnyRelayMsg,
            msg_mod: $crate::relaycell::msg,
            cmd_type: $crate::relaycell::RelayCmd,
            unrecognized: $crate::relaycell::msg::Unrecognized,
            body_trait: $crate::relaycell::msg::Body,
            msg_trait: $crate::relaycell::RelayMsg,
            omit_from: $($omit_from)?
            ]
            $(#[$meta])*
            $v enum $name { $($tt)*}
        }
    };
    {
        $(#[$meta:meta])*
        $(@omit_from $omit_from:literal)?
        $v:vis enum $name:ident : ChanMsg {
            $($tt:tt)*
        }
    } => {
        $crate::restrict::restricted_msg!{
            [
            any_type: $crate::chancell::msg::AnyChanMsg,
            msg_mod: $crate::chancell::msg,
            cmd_type: $crate::chancell::ChanCmd,
            unrecognized: $crate::chancell::msg::Unrecognized,
            body_trait: $crate::chancell::msg::Body,
            msg_trait: $crate::chancell::ChanMsg,
            omit_from: $($omit_from)?
            ]
            $(#[$meta])*
            $v enum $name { $($tt)*}
        }
    };
    {
        [
          any_type: $any_msg:ty,
          msg_mod: $msg_mod:path,
          cmd_type: $cmd_type:ty,
          unrecognized: $unrec_type:ty,
          body_trait: $body_type:ty,
          msg_trait: $msg_trait:ty,
          omit_from: $($omit_from:literal)?
        ]
        $(#[$meta:meta])*
        $v:vis enum $name:ident {
            $(
                $(#[$case_meta:meta])*
                $([feature=$feat:literal])?
                $case:ident
            ),*
            $(, _ =>
                $(#[$unrec_meta:meta])*
                $unrecognized:ident )?
            $(,)?
        }
    } => {
    $crate::restrict::paste::paste!{
        $(#[$meta])*
        $v enum $name {
            $(
                $(#[$case_meta])*
                $( #[cfg(feature=$feat)] )?
                $case($msg_mod :: $case),
            )*
            $(
                $(#[$unrec_meta])*
                $unrecognized($unrec_type)
            )?
        }

        impl $msg_trait for $name {
            fn cmd(&self) -> $cmd_type {
                match self {
                    $(
                        $( #[cfg(feature=$feat)] )?
                        Self::$case(_) => $cmd_type:: [<$case:snake:upper>] ,
                    )*
                    $(
                        Self::$unrecognized(u) => u.cmd(),
                    )?
                }
            }

             fn encode_onto<W:>(self, w: &mut W) -> $crate::restrict::tor_bytes::EncodeResult<()>
             where
                W: $crate::restrict::tor_bytes::Writer + ?Sized
             {
                match self {
                    $(
                        $( #[cfg(feature=$feat)] )?
                        Self::$case(m) => $body_type::encode_onto(m, w),
                    )*
                    $(
                        Self::$unrecognized(u) => $body_type::encode_onto(u, w),
                    )?
                }
            }

            fn decode_from_reader(cmd: $cmd_type, r: &mut $crate::restrict::tor_bytes::Reader<'_>) -> $crate::restrict::tor_bytes::Result<Self> {
                Ok(match cmd {
                    $(
                        $( #[cfg(feature=$feat)] )?
                        $cmd_type:: [<$case:snake:upper>] => Self::$case( <$msg_mod :: $case as $body_type> :: decode_from_reader(r)? ),
                    )*
                    $(
                        _ => Self::$unrecognized($unrec_type::decode_with_cmd(cmd, r)?),
                    )?
                    #[allow(unreachable_patterns)] // This is unreachable if we had an Unrecognized variant above.
                    _ => return Err($crate::restrict::tor_bytes::Error::InvalidMessage(
                        format!("Unexpected command {} in {}", cmd, stringify!($name)).into()
                    )),
                })
            }
        }

        $(
            #[cfg(feature = $omit_from)]
        )?
        impl From<$name> for $any_msg {
            fn from(msg: $name) -> $any_msg {
                match msg {
                    $(
                        $( #[cfg(feature=$feat)] )?
                        $name::$case(b) => Self::$case(b),
                    )*
                    $(
                        $name::$unrecognized(u) => $any_msg::Unrecognized(u),
                    )?
                }
            }
        }

        $(
            #[cfg(feature = $omit_from)]
        )?
        impl TryFrom<$any_msg> for $name {
            type Error = $any_msg;
            fn try_from(msg: $any_msg) -> std::result::Result<$name, $any_msg> {
                Ok(match msg {
                    $(
                        $( #[cfg(feature=$feat)] )?
                        $any_msg::$case(b) => $name::$case(b),
                    )*
                    $(
                        $any_msg::Unrecognized(u) => Self::$unrecognized(u),
                    )?
                    #[allow(unreachable_patterns)]
                    other => return Err(other),
                })
            }
        }
        $(
            $( #[cfg(feature=$feat)] )?
            impl From<$msg_mod :: $case> for $name {
                fn from(m: $msg_mod::$case) -> $name {
                    $name :: $case(m)
                }
            }
        )*
        $(
            impl From<$unrec_type> for $name {
                fn from (u: $unrec_type) -> $name {
                    $name::$unrecognized(u)
                }
            }
        )?
    }
    }
}

pub use restricted_msg;

#[cfg(test)]
mod test {
    use super::*;
    // Here we do a couple of other variations of the example in the doctest, to
    // make sure they work.

    // As in the doctest, but no "unrecognized" variant.
    restricted_msg! {
        enum StrictOpenStreamMsg : RelayMsg {
            Data,
            Sendme,
            End,
       }
    }

    // Try it with chanmsg.
    restricted_msg! {
        enum CircuitBuildReply : ChanMsg {
            Created,
            Created2,
            CreatedFast,
            Destroy,
            _ => Unrecognized,
       }
    }

    // As above, but no "unrecognized" variant.
    restricted_msg! {
        enum StrictCircuitBuildReply : ChanMsg {
            Created,
            Created2,
            CreatedFast,
            Destroy,
       }
    }
}