1
//! Wrap [tor_cell::chancell::codec::ChannelCodec] for use with the futures_codec
2
//! crate.
3

            
4
use digest::Digest;
5
use tor_bytes::Reader;
6
use tor_cell::chancell::{
7
    AnyChanCell, ChanCell, ChanCmd, ChanMsg, codec,
8
    msg::{self, AnyChanMsg},
9
};
10
use tor_error::internal;
11
use tor_llcrypto as ll;
12

            
13
use asynchronous_codec as futures_codec;
14
use bytes::BytesMut;
15

            
16
use crate::{channel::msg::LinkVersion, util::err::Error as ChanError};
17

            
18
use super::{ChannelType, msg::MessageFilter};
19

            
20
/// Channel cell handler which is always in three state.
21
///
22
/// This ALWAYS starts the handler at New. This can only be constructed from a [ChannelType] which
23
/// forces it to start at New.
24
///
25
/// From the New state, it will automatically transition to the right state as information is
26
/// attached to it (ex: link protocol version).
27
pub(crate) enum ChannelCellHandler {
28
    /// When a network connection opens to another endpoint, the channel is considered "New" and
29
    /// so we use this handler to start the handshake.
30
    New(NewChannelHandler),
31
    /// We opened and negotiated a VERSIONS cell. If successful, we transition to this cell handler
32
    /// with sole purpose to handle the handshake phase.
33
    Handshake(HandshakeChannelHandler),
34
    /// Once the handshake is successful, the channel is Open and we use this handler.
35
    Open(OpenChannelHandler),
36
}
37

            
38
/// This is the only way to construct a ChannelCellHandler, from the channel type which will always
39
/// start the handler at the New state.
40
impl From<super::ChannelType> for ChannelCellHandler {
41
120
    fn from(ty: ChannelType) -> Self {
42
120
        Self::New(ty.into())
43
120
    }
44
}
45

            
46
impl ChannelCellHandler {
47
    /// Return the [`ChannelType`] of the inner handler.
48
50
    pub(crate) fn channel_type(&self) -> ChannelType {
49
50
        match self {
50
            Self::New(h) => h.channel_type,
51
            Self::Handshake(h) => h.channel_type(),
52
50
            Self::Open(h) => h.channel_type(),
53
        }
54
50
    }
55

            
56
    /// Set link protocol for this channel cell handler. This transition the handler into the
57
    /// handshake handler state.
58
    ///
59
    /// An error is returned if the current handler is NOT the New one or if the link version is
60
    /// unknown.
61
116
    pub(crate) fn set_link_version(&mut self, link_version: u16) -> Result<(), ChanError> {
62
116
        let Self::New(new_handler) = self else {
63
            return Err(ChanError::Bug(internal!(
64
                "Setting link protocol without a new handler",
65
            )));
66
        };
67
116
        *self = Self::Handshake(new_handler.next_handler(link_version.try_into()?));
68
116
        Ok(())
69
116
    }
70

            
71
    /// This transition into the open handler state.
72
    ///
73
    /// An error is returned if the current handler is NOT the Handshake one.
74
74
    pub(crate) fn set_open(&mut self) -> Result<(), ChanError> {
75
74
        let Self::Handshake(handler) = self else {
76
            return Err(ChanError::Bug(internal!(
77
                "Setting open without a handshake handler"
78
            )));
79
        };
80
74
        *self = Self::Open(handler.next_handler());
81
74
        Ok(())
82
74
    }
83

            
84
    /// Mark this handler as authenticated.
85
    ///
86
    /// This can only happen during the Handshake process as a New handler can't be authenticated
87
    /// from the start and an Open handler can only be opened after authentication.
88
    pub(crate) fn set_authenticated(&mut self) -> Result<(), ChanError> {
89
        let Self::Handshake(handler) = self else {
90
            return Err(ChanError::Bug(internal!(
91
                "Setting authenticated without a handshake handler"
92
            )));
93
        };
94
        handler.set_authenticated();
95
        Ok(())
96
    }
97

            
98
    /// The digest of bytes sent on this channel.
99
    ///
100
    /// This should only ever be called once as it consumes the send log.
101
    ///
102
    /// This will return an error if one of:
103
    /// - The channel is not recording the send log.
104
    /// - The send log digest has already been taken.
105
    /// - This cell handler is not using a handshake handler.
106
12
    pub(crate) fn take_send_log_digest(&mut self) -> Result<[u8; 32], ChanError> {
107
12
        if let Self::Handshake(handler) = self {
108
12
            handler
109
12
                .take_send_log_digest()
110
12
                .ok_or(ChanError::Bug(internal!("No send log digest on channel")))
111
        } else {
112
            Err(ChanError::Bug(internal!(
113
                "Getting send log digest without a handshake handler"
114
            )))
115
        }
116
12
    }
117

            
118
    /// The digest of bytes received on this channel.
119
    ///
120
    /// This should only ever be called once as it consumes the receive log.
121
    ///
122
    /// This will return `None` if one of:
123
    /// - The channel is not recording the receive log.
124
    /// - The receive log digest has already been taken.
125
    /// - This cell handler is not using a handshake handler.
126
12
    pub(crate) fn take_recv_log_digest(&mut self) -> Result<[u8; 32], ChanError> {
127
12
        if let Self::Handshake(handler) = self {
128
12
            handler
129
12
                .take_recv_log_digest()
130
12
                .ok_or(ChanError::Bug(internal!("No recv log digest on channel")))
131
        } else {
132
            Err(ChanError::Bug(internal!(
133
                "Getting recv log digest without a handshake handler"
134
            )))
135
        }
136
12
    }
137
}
138

            
139
// Security Consideration.
140
//
141
// Here is an explanation on why AnyChanCell is used as Item in the Handshake and Open handler and
142
// thus the higher level ChannelCellHandler.
143
//
144
// Technically, we could use a restricted message set and so the decoding and encoding wouldn't do
145
// anything if the cell/data was not part of that set.
146
//
147
// However, with relay and client, we have multiple channel types which means we have now a lot
148
// more sets of restricted message (see msg.rs) and each of them are per link protocol version, per
149
// stage of the channel opening process and per direction (inbound or outbound).
150
//
151
// To go around this, we use [MessageFilter] in order to decode on the specific restricted message
152
// set but still return a [AnyChanCell].
153
//
154
// If someone wants to contribute a more elegant solution that wouldn't require us to duplicate
155
// code for each restricted message set, by all means, go for it :).
156

            
157
impl futures_codec::Decoder for ChannelCellHandler {
158
    type Item = AnyChanCell;
159
    type Error = ChanError;
160

            
161
1076
    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
162
1076
        match self {
163
212
            Self::New(c) => c
164
212
                .decode(src)
165
248
                .map(|opt| opt.map(|msg| ChanCell::new(None, msg.into()))),
166
840
            Self::Handshake(c) => c.decode(src),
167
24
            Self::Open(c) => c.decode(src),
168
        }
169
1076
    }
170
}
171

            
172
impl futures_codec::Encoder for ChannelCellHandler {
173
    type Item<'a> = AnyChanCell;
174
    type Error = ChanError;
175

            
176
154
    fn encode(&mut self, item: Self::Item<'_>, dst: &mut BytesMut) -> Result<(), Self::Error> {
177
154
        match self {
178
82
            Self::New(c) => {
179
                // The new handler pins the only possible message to be a Versions. That is why we
180
                // extract it here and validate before else we can't pass Item to encode().
181
82
                let AnyChanMsg::Versions(versions) = item.into_circid_and_msg().1 else {
182
                    return Err(Self::Error::HandshakeProto(
183
                        "Non VERSIONS cell for new handler".into(),
184
                    ));
185
                };
186
82
                c.encode(versions, dst)
187
            }
188
60
            Self::Handshake(c) => c.encode(item, dst),
189
12
            Self::Open(c) => c.encode(item, dst),
190
        }
191
154
    }
192
}
193

            
194
/// A new channel handler used when a channel is created but before the handshake meaning there is no
195
/// link protocol version yet associated with it.
196
///
197
/// This handler only handles the VERSIONS cell.
198
pub(crate) struct NewChannelHandler {
199
    /// The channel type for this handler.
200
    channel_type: ChannelType,
201
    /// The digest of bytes sent on this channel.
202
    ///
203
    /// Will be used for the SLOG or CLOG of the AUTHENTICATE cell.
204
    send_log: Option<ll::d::Sha256>,
205
    /// The digest of bytes received on this channel.
206
    ///
207
    /// Will be used for the SLOG or CLOG of the AUTHENTICATE cell.
208
    recv_log: Option<ll::d::Sha256>,
209
}
210

            
211
impl NewChannelHandler {
212
    /// Return a handshake handler ready for the given link protocol.
213
116
    fn next_handler(&mut self, link_version: LinkVersion) -> HandshakeChannelHandler {
214
116
        HandshakeChannelHandler::new(self, link_version)
215
116
    }
216
}
217

            
218
impl From<ChannelType> for NewChannelHandler {
219
120
    fn from(channel_type: ChannelType) -> Self {
220
120
        match channel_type {
221
96
            ChannelType::ClientInitiator => Self {
222
96
                channel_type,
223
96
                send_log: None,
224
96
                recv_log: None,
225
96
            },
226
            // Relay responder might not need clog/slog but that is fine. We don't know until the
227
            // end of the handshake.
228
24
            ChannelType::RelayInitiator | ChannelType::RelayResponder { .. } => Self {
229
24
                channel_type,
230
24
                send_log: Some(ll::d::Sha256::new()),
231
24
                recv_log: Some(ll::d::Sha256::new()),
232
24
            },
233
        }
234
120
    }
235
}
236

            
237
impl futures_codec::Decoder for NewChannelHandler {
238
    type Item = msg::Versions;
239
    type Error = ChanError;
240

            
241
212
    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
242
        // NOTE: Until the body can be extracted from src buffer, it MUST NOT be modified as in
243
        // advanced with the Buf trait or modified in any ways. Reason is that we can realize we
244
        // don't have enough bytes in the src buffer for the expected body length from the header
245
        // so we have to leave the src buffer untouched and wait for more bytes.
246

            
247
        // See tor-spec, starting a handshake, all cells are variable length so the first 5 bytes
248
        // are: CircId as u16, Command as u8, Length as u16 totalling 5 bytes.
249
        const HEADER_SIZE: usize = 5;
250

            
251
        // Below this amount, this is not a valid cell we can decode. This is important because we
252
        // can get an empty buffer in normal circumstances (see how Framed work) and so we have to
253
        // return that we weren't able to decode and thus no Item.
254
212
        if src.len() < HEADER_SIZE {
255
130
            return Ok(None);
256
82
        }
257

            
258
        // Get the CircID and Command from the header. This is safe due to the header size check
259
        // above.
260
82
        let circ_id = u16::from_be_bytes([src[0], src[1]]);
261
82
        if circ_id != 0 {
262
2
            return Err(Self::Error::HandshakeProto(
263
2
                "Invalid CircID in variable cell".into(),
264
2
            ));
265
80
        }
266

            
267
        // We are only expecting these specific commands. We have to do this by hand here as after
268
        // that we can use a proper codec.
269
80
        let cmd = ChanCmd::from(src[2]);
270
80
        if cmd != ChanCmd::VERSIONS {
271
            return Err(Self::Error::HandshakeProto(format!(
272
                "Invalid command {cmd} variable cell, expected a VERSIONS."
273
            )));
274
80
        }
275

            
276
        // Get the body length now from the next two bytes. This is still safe due to the first
277
        // header size check at the start.
278
80
        let body_len = u16::from_be_bytes([src[3], src[4]]) as usize;
279

            
280
        // See https://gitlab.torproject.org/tpo/core/tor/-/issues/10365. The gist is that because
281
        // version numbers are u16, an odd payload would mean we have a trailing byte that is
282
        // unused which shouldn't be and because we don't expect not controlled that byte, as maxi
283
        // precaution, we don't allow.
284
80
        if body_len % 2 == 1 {
285
            return Err(Self::Error::HandshakeProto(
286
                "VERSIONS cell body length is odd. Rejecting.".into(),
287
            ));
288
80
        }
289

            
290
        // Make sure we have enough bytes in our payload.
291
80
        let wanted_bytes = HEADER_SIZE + body_len;
292
80
        if src.len() < wanted_bytes {
293
            // We don't haven't received enough data to decode the expected length from the header
294
            // so return no Item.
295
            //
296
            // IMPORTANT: The src buffer here can't be advance before reaching this check.
297
            return Ok(None);
298
80
        }
299
        // Extract the exact data we will be looking at.
300
80
        let mut data = src.split_to(wanted_bytes);
301

            
302
        // Update the receive log digest with the entire cell up to the end of the payload hence the
303
        // data we are looking at (and not the whole source). Even on error, this doesn't matter
304
        // because if decoding fails, the channel is closed.
305
80
        if let Some(recv_log) = self.recv_log.as_mut() {
306
12
            recv_log.update(&data);
307
68
        }
308

            
309
        // Get the actual boddy from the data.
310
80
        let body = data.split_off(HEADER_SIZE).freeze();
311
80
        let mut reader = Reader::from_bytes(&body);
312

            
313
        // Decode the VERSIONS.
314
80
        let cell = msg::Versions::decode_from_reader(cmd, &mut reader)
315
80
            .map_err(|e| Self::Error::from_bytes_err(e, "new cell handler"))?;
316
80
        Ok(Some(cell))
317
212
    }
318
}
319

            
320
impl futures_codec::Encoder for NewChannelHandler {
321
    type Item<'a> = msg::Versions;
322
    type Error = ChanError;
323

            
324
82
    fn encode(&mut self, item: Self::Item<'_>, dst: &mut BytesMut) -> Result<(), Self::Error> {
325
82
        let encoded_bytes = item
326
82
            .encode_for_handshake()
327
82
            .map_err(|e| Self::Error::from_bytes_enc(e, "new cell handler"))?;
328
        // Update the send log digest.
329
82
        if let Some(send_log) = self.send_log.as_mut() {
330
12
            send_log.update(&encoded_bytes);
331
70
        }
332
        // Special encoding for the VERSIONS cell.
333
82
        dst.extend_from_slice(&encoded_bytes);
334
82
        Ok(())
335
82
    }
336
}
337

            
338
/// The handshake channel handler which is used to decode and encode cells onto a channel that is
339
/// handshaking with an endpoint.
340
pub(crate) struct HandshakeChannelHandler {
341
    /// Message filter used to allow or not a certain message.
342
    filter: MessageFilter,
343
    /// The cell codec that we'll use to encode and decode our cells.
344
    inner: codec::ChannelCodec,
345
    /// The digest of bytes sent on this channel.
346
    ///
347
    /// Will be used for the SLOG or CLOG of the AUTHENTICATE cell.
348
    send_log: Option<ll::d::Sha256>,
349
    /// The digest of bytes received on this channel.
350
    ///
351
    /// Will be used for the SLOG or CLOG of the AUTHENTICATE cell.
352
    recv_log: Option<ll::d::Sha256>,
353
}
354

            
355
impl HandshakeChannelHandler {
356
    /// Constructor
357
116
    fn new(new_handler: &mut NewChannelHandler, link_version: LinkVersion) -> Self {
358
116
        Self {
359
116
            filter: MessageFilter::new(
360
116
                link_version,
361
116
                new_handler.channel_type,
362
116
                super::msg::MessageStage::Handshake,
363
116
            ),
364
116
            send_log: new_handler.send_log.take(),
365
116
            recv_log: new_handler.recv_log.take(),
366
116
            inner: codec::ChannelCodec::new(link_version.value()),
367
116
        }
368
116
    }
369

            
370
    /// Internal helper: Take a SHA256 digest and finalize it if any. None is returned if no log
371
    /// digest is given.
372
24
    fn finalize_log(log: Option<ll::d::Sha256>) -> Option<[u8; 32]> {
373
36
        log.map(|sha256| sha256.finalize().into())
374
24
    }
375

            
376
    /// Return an open handshake handler.
377
74
    fn next_handler(&mut self) -> OpenChannelHandler {
378
74
        OpenChannelHandler::new(
379
74
            self.inner
380
74
                .link_version()
381
74
                .try_into()
382
74
                .expect("Channel Codec with unknown link version"),
383
74
            self.channel_type(),
384
        )
385
74
    }
386

            
387
    /// The digest of bytes sent on this channel.
388
    ///
389
    /// This should only ever be called once as it consumes the send log.
390
    ///
391
    /// This will return `None` if one of:
392
    /// - The channel is not recording the send log.
393
    /// - The send log digest has already been taken.
394
12
    pub(crate) fn take_send_log_digest(&mut self) -> Option<[u8; 32]> {
395
12
        Self::finalize_log(self.send_log.take())
396
12
    }
397

            
398
    /// The digest of bytes received on this channel.
399
    ///
400
    /// This should only ever be called once as it consumes the receive log.
401
    ///
402
    /// This will return `None` if one of:
403
    /// - The channel is not recording the receive log.
404
    /// - The receive log digest has already been taken.
405
12
    pub(crate) fn take_recv_log_digest(&mut self) -> Option<[u8; 32]> {
406
12
        Self::finalize_log(self.recv_log.take())
407
12
    }
408

            
409
    /// Return the [`ChannelType`] of this handler.
410
74
    pub(crate) fn channel_type(&self) -> ChannelType {
411
74
        self.filter.channel_type()
412
74
    }
413

            
414
    /// Mark this handler as authenticated.
415
    pub(crate) fn set_authenticated(&mut self) {
416
        self.filter.channel_type_mut().set_authenticated();
417
    }
418
}
419

            
420
impl futures_codec::Encoder for HandshakeChannelHandler {
421
    type Item<'a> = AnyChanCell;
422
    type Error = ChanError;
423

            
424
60
    fn encode(
425
60
        &mut self,
426
60
        item: Self::Item<'_>,
427
60
        dst: &mut BytesMut,
428
60
    ) -> std::result::Result<(), Self::Error> {
429
60
        let before_dst_len = dst.len();
430
60
        self.filter.encode_cell(item, &mut self.inner, dst)?;
431
60
        let after_dst_len = dst.len();
432
60
        if let Some(send_log) = self.send_log.as_mut() {
433
12
            // Only use what we actually wrote. Variable length cell are not padded and thus this
434
12
            // won't catch a bunch of padding.
435
12
            send_log.update(&dst[before_dst_len..after_dst_len]);
436
60
        }
437
60
        Ok(())
438
60
    }
439
}
440

            
441
impl futures_codec::Decoder for HandshakeChannelHandler {
442
    type Item = AnyChanCell;
443
    type Error = ChanError;
444

            
445
840
    fn decode(
446
840
        &mut self,
447
840
        src: &mut BytesMut,
448
840
    ) -> std::result::Result<Option<Self::Item>, Self::Error> {
449
840
        let orig = src.clone(); // NOTE: Not fun. But This is only done during handshake.
450
840
        let cell = self.filter.decode_cell(&mut self.inner, src)?;
451
836
        if let Some(recv_log) = self.recv_log.as_mut() {
452
24
            let n_used = orig.len() - src.len();
453
24
            recv_log.update(&orig[..n_used]);
454
812
        }
455
836
        Ok(cell)
456
840
    }
457
}
458

            
459
/// The open channel handler which is used to decode and encode cells onto an open Channel.
460
pub(crate) struct OpenChannelHandler {
461
    /// Message filter used to allow or not a certain message.
462
    filter: MessageFilter,
463
    /// The cell codec that we'll use to encode and decode our cells.
464
    inner: codec::ChannelCodec,
465
}
466

            
467
impl OpenChannelHandler {
468
    /// Constructor
469
98
    fn new(link_version: LinkVersion, channel_type: ChannelType) -> Self {
470
98
        Self {
471
98
            inner: codec::ChannelCodec::new(link_version.value()),
472
98
            filter: MessageFilter::new(link_version, channel_type, super::msg::MessageStage::Open),
473
98
        }
474
98
    }
475

            
476
    /// Return the [`ChannelType`] of this handler.
477
50
    fn channel_type(&self) -> ChannelType {
478
50
        self.filter.channel_type()
479
50
    }
480
}
481

            
482
impl futures_codec::Encoder for OpenChannelHandler {
483
    type Item<'a> = AnyChanCell;
484
    type Error = ChanError;
485

            
486
12
    fn encode(&mut self, item: Self::Item<'_>, dst: &mut BytesMut) -> Result<(), Self::Error> {
487
12
        self.filter.encode_cell(item, &mut self.inner, dst)
488
12
    }
489
}
490

            
491
impl futures_codec::Decoder for OpenChannelHandler {
492
    type Item = AnyChanCell;
493
    type Error = ChanError;
494

            
495
24
    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
496
24
        self.filter.decode_cell(&mut self.inner, src)
497
24
    }
498
}
499

            
500
#[cfg(test)]
501
pub(crate) mod test {
502
    #![allow(clippy::unwrap_used)]
503
    use bytes::BytesMut;
504
    use digest::Digest;
505
    use futures::io::{AsyncRead, AsyncWrite, Cursor, Result};
506
    use futures::sink::SinkExt;
507
    use futures::stream::StreamExt;
508
    use futures::task::{Context, Poll};
509
    use hex_literal::hex;
510
    use std::pin::Pin;
511

            
512
    use tor_bytes::Writer;
513
    use tor_llcrypto as ll;
514
    use tor_rtcompat::StreamOps;
515

            
516
    use crate::channel::msg::LinkVersion;
517
    use crate::channel::{ChannelType, new_frame};
518

            
519
    use super::{ChannelCellHandler, OpenChannelHandler, futures_codec};
520
    use tor_cell::chancell::{AnyChanCell, ChanCmd, ChanMsg, CircId, msg};
521

            
522
    /// Helper type for reading and writing bytes to/from buffers.
523
    pub(crate) struct MsgBuf {
524
        /// Data we have received as a reader.
525
        inbuf: futures::io::Cursor<Vec<u8>>,
526
        /// Data we write as a writer.
527
        outbuf: futures::io::Cursor<Vec<u8>>,
528
    }
529

            
530
    impl AsyncRead for MsgBuf {
531
        fn poll_read(
532
            mut self: Pin<&mut Self>,
533
            cx: &mut Context<'_>,
534
            buf: &mut [u8],
535
        ) -> Poll<Result<usize>> {
536
            Pin::new(&mut self.inbuf).poll_read(cx, buf)
537
        }
538
    }
539
    impl AsyncWrite for MsgBuf {
540
        fn poll_write(
541
            mut self: Pin<&mut Self>,
542
            cx: &mut Context<'_>,
543
            buf: &[u8],
544
        ) -> Poll<Result<usize>> {
545
            Pin::new(&mut self.outbuf).poll_write(cx, buf)
546
        }
547
        fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
548
            Pin::new(&mut self.outbuf).poll_flush(cx)
549
        }
550
        fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
551
            Pin::new(&mut self.outbuf).poll_close(cx)
552
        }
553
    }
554

            
555
    impl StreamOps for MsgBuf {}
556

            
557
    impl MsgBuf {
558
        pub(crate) fn new<T: Into<Vec<u8>>>(output: T) -> Self {
559
            let inbuf = Cursor::new(output.into());
560
            let outbuf = Cursor::new(Vec::new());
561
            MsgBuf { inbuf, outbuf }
562
        }
563

            
564
        pub(crate) fn consumed(&self) -> usize {
565
            self.inbuf.position() as usize
566
        }
567

            
568
        pub(crate) fn all_consumed(&self) -> bool {
569
            self.inbuf.get_ref().len() == self.consumed()
570
        }
571

            
572
        pub(crate) fn into_response(self) -> Vec<u8> {
573
            self.outbuf.into_inner()
574
        }
575
    }
576

            
577
    fn new_client_open_frame(mbuf: MsgBuf) -> futures_codec::Framed<MsgBuf, ChannelCellHandler> {
578
        let open_handler = ChannelCellHandler::Open(OpenChannelHandler::new(
579
            LinkVersion::V5,
580
            ChannelType::ClientInitiator,
581
        ));
582
        futures_codec::Framed::new(mbuf, open_handler)
583
    }
584

            
585
    #[test]
586
    fn check_client_encoding() {
587
        tor_rtcompat::test_with_all_runtimes!(|_rt| async move {
588
            let mb = MsgBuf::new(&b""[..]);
589
            let mut framed = new_client_open_frame(mb);
590

            
591
            let destroycell = msg::Destroy::new(2.into());
592
            framed
593
                .send(AnyChanCell::new(CircId::new(7), destroycell.into()))
594
                .await
595
                .unwrap();
596

            
597
            framed.flush().await.unwrap();
598

            
599
            let data = framed.into_inner().into_response();
600

            
601
            assert_eq!(&data[0..10], &hex!("00000007 04 0200000000")[..]);
602
        });
603
    }
604

            
605
    #[test]
606
    fn check_client_decoding() {
607
        tor_rtcompat::test_with_all_runtimes!(|_rt| async move {
608
            let mut dat = Vec::new();
609
            // DESTROY cell.
610
            dat.extend_from_slice(&hex!("00000007 04 0200000000")[..]);
611
            dat.resize(514, 0);
612
            let mb = MsgBuf::new(&dat[..]);
613
            let mut framed = new_client_open_frame(mb);
614

            
615
            let destroy = framed.next().await.unwrap().unwrap();
616

            
617
            let circ_id = CircId::new(7);
618
            assert_eq!(destroy.circid(), circ_id);
619
            assert_eq!(destroy.msg().cmd(), ChanCmd::DESTROY);
620

            
621
            assert!(framed.into_inner().all_consumed());
622
        });
623
    }
624

            
625
    #[test]
626
    fn handler_transition() {
627
        // Start as a client initiating a channel to a relay.
628
        let mut handler: ChannelCellHandler = ChannelType::ClientInitiator.into();
629
        assert!(matches!(handler, ChannelCellHandler::New(_)));
630

            
631
        // Set the link version protocol. Should transition to Handshake.
632
        let r = handler.set_link_version(5);
633
        assert!(r.is_ok());
634
        assert!(matches!(handler, ChannelCellHandler::Handshake(_)));
635

            
636
        // Set the link version protocol.
637
        let r = handler.set_open();
638
        assert!(r.is_ok());
639
        assert!(matches!(handler, ChannelCellHandler::Open(_)));
640
    }
641

            
642
    #[test]
643
    fn clog_digest() {
644
        tor_rtcompat::test_with_all_runtimes!(|_rt| async move {
645
            let mut our_clog = ll::d::Sha256::new();
646
            let mbuf = MsgBuf::new(*b"");
647
            let mut frame = new_frame(mbuf, ChannelType::RelayInitiator);
648

            
649
            // This is a VERSIONS cell with value 5 in it.
650
            our_clog.update(hex!("0000 07 0002 0005"));
651
            let version_cell = AnyChanCell::new(
652
                None,
653
                msg::Versions::new(vec![5]).expect("Fail VERSIONS").into(),
654
            );
655
            let _ = frame.send(version_cell).await.unwrap();
656

            
657
            frame
658
                .codec_mut()
659
                .set_link_version(5)
660
                .expect("Fail link version set");
661

            
662
            // This is what an empty CERTS cell looks like.
663
            our_clog.update(hex!("0000 0000 81 0001 00"));
664
            let certs_cell = msg::Certs::new_empty();
665
            frame
666
                .send(AnyChanCell::new(None, certs_cell.into()))
667
                .await
668
                .unwrap();
669

            
670
            // Final CLOG should match.
671
            let clog_hash: [u8; 32] = our_clog.finalize().into();
672
            assert_eq!(frame.codec_mut().take_send_log_digest().unwrap(), clog_hash);
673
        });
674
    }
675

            
676
    #[test]
677
    fn slog_digest() {
678
        tor_rtcompat::test_with_all_runtimes!(|_rt| async move {
679
            let mut our_slog = ll::d::Sha256::new();
680

            
681
            // Build a VERSIONS cell to start with.
682
            let mut data = BytesMut::new();
683
            data.extend_from_slice(
684
                msg::Versions::new(vec![5])
685
                    .unwrap()
686
                    .encode_for_handshake()
687
                    .expect("Fail VERSIONS encoding")
688
                    .as_slice(),
689
            );
690
            our_slog.update(&data);
691

            
692
            let mbuf = MsgBuf::new(data);
693
            let mut frame = new_frame(mbuf, ChannelType::RelayInitiator);
694

            
695
            // Receive the VERSIONS
696
            let _ = frame.next().await.transpose().expect("Fail to get cell");
697
            // Set the link version which will move the handler to Handshake state and then we'll be
698
            // able to decode the AUTH_CHALLENGE.
699
            frame
700
                .codec_mut()
701
                .set_link_version(5)
702
                .expect("Fail link version set");
703

            
704
            // Setup a new buffer for the next cell.
705
            let mut data = BytesMut::new();
706
            // This is a variable length cell with a wide circ ID of 0.
707
            data.write_u32(0);
708
            data.write_u8(ChanCmd::AUTH_CHALLENGE.into());
709
            data.write_u16(36); // This is the length of the payload.
710
            msg::AuthChallenge::new([42_u8; 32], vec![3])
711
                .encode_onto(&mut data)
712
                .expect("Fail AUTH_CHALLENGE encoding");
713
            our_slog.update(&data);
714

            
715
            // Change the I/O part of the Framed with this new buffer containing our new cell.
716
            *frame = MsgBuf::new(data);
717
            // Receive the AUTH_CHALLENGE
718
            let _ = frame.next().await.transpose().expect("Fail to get cell");
719

            
720
            // Final SLOG should match.
721
            let slog_hash: [u8; 32] = our_slog.finalize().into();
722
            assert_eq!(frame.codec_mut().take_recv_log_digest().unwrap(), slog_hash);
723
        });
724
    }
725
}