sunset 0.6.0

A SSH library suitable for embedded and larger programs
Documentation
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
use core::fmt;
use core::ops::{Deref, DerefMut};

#[allow(unused_imports)]
use {
    crate::error::{Error, Result},
    log::{debug, error, info, log, trace, warn},
};

use zeroize::Zeroize;

#[cfg(feature = "alloc")]
use alloc::boxed::Box;
use heapless::Deque;

use crate::encrypt::{KeyState, KeysRecv, KeysSend, SSH_PAYLOAD_START};
use crate::ident::RemoteVersion;
use crate::*;
use crate::{
    channel::{ChanData, ChanNum},
    packets::Packet,
};

/// Number of `DeferredPacket`s to queue.
///
/// Each entry takes around 40 bytes.
const DEFER_COUNT: usize = 10;

// Either a slice or boxed array.
// Similar to managed::ManagedSlice.
//
// Zeroize is slow for fuzzing, so skip it.
// In normal operation one zeroize per connection is fine.
#[cfg_attr(not(fuzzing), derive(zeroize::ZeroizeOnDrop))]
enum SliceOrVec<'a> {
    Borrowed(&'a mut [u8]),

    /// `'static` variant
    #[cfg(feature = "alloc")]
    Owned(Box<[u8; config::SSH_MAX_PACKET]>),
}

impl Deref for SliceOrVec<'_> {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        match self {
            Self::Borrowed(r) => r,
            #[cfg(feature = "alloc")]
            Self::Owned(r) => r.as_ref(),
        }
    }
}

impl DerefMut for SliceOrVec<'_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        match self {
            Self::Borrowed(r) => r,
            #[cfg(feature = "alloc")]
            Self::Owned(r) => r.as_mut(),
        }
    }
}

impl Zeroize for SliceOrVec<'_> {
    fn zeroize(&mut self) {
        self.deref_mut().zeroize();
    }
}

// TODO: if smoltcp exposed both ends of a CircularBuffer to recv()
// we could perhaps just work directly in smoltcp's provided buffer?
// Would need changes to ciphers with block boundaries

// TODO only pub for testing
// pub(crate) struct TrafIn<'a> {
pub struct TrafIn<'a> {
    // TODO: decompression will need another buffer
    /// Accumulated input buffer.
    ///
    /// Should be sized to fit the largest packet allowed for input.
    /// Contains ciphertext or cleartext, decrypted in-place.
    /// Only contains a single SSH packet at a time.
    buf: SliceOrVec<'a>,
    state: RxState,
}

#[derive(Debug)]
enum RxState {
    /// Awaiting read, buffer is unused
    Idle,
    /// Reading initial encrypted block for packet length. idx > 0.
    ReadInitial { idx: usize },
    /// Reading remainder of encrypted packet
    Read { idx: usize, expect: usize },
    /// Whole encrypted packet has been read
    ReadComplete { len: usize },
    /// Decrypted complete input payload
    InPayload { len: usize, seq: u32 },
    /// Decrypted incoming channel data
    InChannelData {
        /// channel number
        chan: ChanNum,
        /// Normal or Stderr
        dt: ChanData,
        /// read index of channel data. should transition to Idle once `idx==len`
        idx: usize,
        /// length of channel data
        len: usize,
    },
}

impl core::fmt::Debug for TrafIn<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TrafIn").field("state", &self.state).finish_non_exhaustive()
    }
}

impl<'a> TrafIn<'a> {
    pub fn new(buf: &'a mut [u8]) -> Self {
        Self { buf: SliceOrVec::Borrowed(buf), state: RxState::Idle }
    }

    pub fn is_input_ready(&self) -> bool {
        match self.state {
            RxState::Idle | RxState::ReadInitial { .. } | RxState::Read { .. } => {
                true
            }
            RxState::ReadComplete { .. }
            | RxState::InPayload { .. }
            | RxState::InChannelData { .. } => false,
        }
    }

    /// Returns the number of bytes consumed.
    pub fn input(
        &mut self,
        keys: &mut KeyState,
        remote_version: &mut RemoteVersion,
        buf: &[u8],
    ) -> Result<usize, Error> {
        let mut inlen = 0;
        debug_assert!(self.is_input_ready());
        if remote_version.version().is_none() && matches!(self.state, RxState::Idle)
        {
            // Handle initial version string
            inlen += remote_version.consume(buf)?;
        }
        let buf = &buf[inlen..];

        inlen += self.fill_input(keys, buf)?;
        Ok(inlen)
    }

    /// Called when `payload()` is complete.
    pub(crate) fn done_payload(&mut self) {
        if let RxState::InPayload { .. } = self.state {
            self.state = RxState::Idle
        }
    }

    /// Called when `payload()` is complete, zeroizes the payload
    /// Also calls `done_payload()`.
    pub(crate) fn zeroize_payload(&mut self) {
        if let RxState::InPayload { len, .. } = self.state {
            self.buf[SSH_PAYLOAD_START..SSH_PAYLOAD_START + len].zeroize();
            self.done_payload()
        }
    }

    /// Returns a reference to the decrypted payload buffer if ready,
    /// and the `seq` of that packet.
    pub(crate) fn payload(&self) -> Option<(&[u8], u32)> {
        match self.state {
            RxState::InPayload { len, seq } => {
                let payload = &self.buf[SSH_PAYLOAD_START..SSH_PAYLOAD_START + len];
                Some((payload, seq))
            }
            _ => None,
        }
    }

    fn fill_input(
        &mut self,
        keys: &mut KeyState,
        buf: &[u8],
    ) -> Result<usize, Error> {
        let size_block = keys.size_block_dec();
        // 'r' is the remaining input, a slice that moves along.
        // Used to calculate the size to return
        let mut r = buf;

        trace!("fill_input {:?}", self.state);

        // Fill the initial block from either Idle with input,
        // partial initial block
        if let Some(idx) = match self.state {
            RxState::Idle if !r.is_empty() => Some(0),
            RxState::ReadInitial { idx } => Some(idx),
            _ => None,
        } {
            trace!("fill_input idle idx {idx}");
            let need = (size_block - idx).clamp(0, r.len());
            let x;
            (x, r) = r.split_at(need);
            let w = &mut self.buf[idx..idx + need];
            w.copy_from_slice(x);
            self.state = RxState::ReadInitial { idx: idx + need }
        }

        // Have enough input now to decrypt the packet length
        if let RxState::ReadInitial { idx } = self.state {
            trace!("fill_input readinit {idx}");
            if idx >= size_block {
                let w = &mut self.buf[..size_block];
                let total_len = keys.decrypt_first_block(w)?;
                if total_len > self.buf.len() {
                    // TODO: Or just BadDecrypt could make more sense if
                    // it were packet corruption/decryption failure
                    return Err(Error::BigPacket { size: total_len });
                }
                if total_len < size_block {
                    return Err(Error::BadDecrypt);
                }
                trace!("fill_input set read  {idx} ex {total_len}");
                self.state = RxState::Read { idx, expect: total_len }
            }
        }

        // Know expected length, read until the end of the packet.
        // We have already validated that expect_len <= buf_size
        if let RxState::Read { ref mut idx, expect } = self.state {
            trace!("expect {expect} idx {idx}");
            let need = (expect - *idx).min(r.len());
            let x;
            (x, r) = r.split_at(need);
            let w = &mut self.buf[*idx..*idx + need];
            w.copy_from_slice(x);
            *idx += need;
            if *idx == expect {
                self.state = RxState::ReadComplete { len: expect }
            }
        }

        if let RxState::ReadComplete { len } = self.state {
            let w = &mut self.buf[..len];
            let seq = keys.recv_seq();
            let payload_len = keys.decrypt(w)?;
            self.state = RxState::InPayload { len: payload_len, seq }
        }
        trace!("out");

        Ok(buf.len() - r.len())
    }

    /// Returns `(channel, dt, length)`
    pub fn read_channel_ready(&self) -> Option<(ChanNum, ChanData, usize)> {
        match self.state {
            RxState::InChannelData { chan, dt, idx, len } => {
                debug_assert!(len > idx);
                let rem = len - idx;
                Some((chan, dt, rem))
            }
            _ => None,
        }
    }

    /// Set channel data ready to be read.
    pub fn set_read_channel_data(
        &mut self,
        di: channel::DataIn,
    ) -> Result<(ChanNum, ChanData)> {
        match self.state {
            RxState::InPayload { .. } => {
                let idx = SSH_PAYLOAD_START + di.dt.packet_offset();
                self.state = RxState::InChannelData {
                    chan: di.num,
                    dt: di.dt,
                    idx,
                    len: idx + di.len.get(),
                };
                Ok((di.num, di.dt))
            }
            _ => Error::bug(),
        }
    }

    // Returns the length returned, and an Option<len> indicating whether the whole
    // data packet has been completed, or None if some is still pending.
    pub fn read_channel(
        &mut self,
        chan: ChanNum,
        dt: ChanData,
        buf: &mut [u8],
    ) -> (usize, Option<usize>) {
        match self.state {
            RxState::InChannelData { chan: c, dt: e, ref mut idx, len }
                if (c, e) == (chan, dt) =>
            {
                debug_assert!(len > *idx);
                let wlen = (len - *idx).min(buf.len());
                buf[..wlen].copy_from_slice(&self.buf[*idx..*idx + wlen]);
                *idx += wlen;

                if *idx == len {
                    // all done.
                    self.state = RxState::Idle;
                    (wlen, Some(len))
                } else {
                    (wlen, None)
                }
            }
            _ => (0, None),
        }
    }

    // Returns (length, complete: Option<len: usize>>, Option(dt))
    pub fn read_channel_either(
        &mut self,
        chan: ChanNum,
        buf: &mut [u8],
    ) -> (usize, Option<usize>, ChanData) {
        match self.state {
            RxState::InChannelData { chan: c, dt, ref mut idx, len }
                if c == chan =>
            {
                debug_assert!(len > *idx);
                let wlen = (len - *idx).min(buf.len());
                buf[..wlen].copy_from_slice(&self.buf[*idx..*idx + wlen]);
                // info!("idx {} += wlen {} = {}", *idx, wlen, *idx+wlen);
                *idx += wlen;

                if *idx == len {
                    // all done.
                    self.state = RxState::Idle;
                    (wlen, Some(len), dt)
                } else {
                    (wlen, None, dt)
                }
            }
            _ => (0, None, ChanData::Normal),
        }
    }

    /// Returns the length of data discarded
    pub fn discard_read_channel(&mut self, chan: ChanNum) -> usize {
        match self.state {
            RxState::InChannelData { chan: c, len, .. } if c == chan => {
                self.state = RxState::Idle;
                len
            }
            _ => 0,
        }
    }
}

pub(crate) struct TrafOut<'a> {
    // TODO: decompression will need another buffer
    /// Accumulated output buffer.
    ///
    /// Should be sized to fit the largest
    /// sequence of packets to be sent at once.
    /// Contains ciphertext or cleartext, encrypted in-place.
    /// Writing may contain multiple SSH packets to write out, encrypted
    /// in-place as they are written to `buf`.
    buf: SliceOrVec<'a>,
    state: TxState,

    drain: bool,

    // Set between sending KexInit and sending NewKeys.
    sending_kex: bool,

    deferred_packets: Deque<DeferredPacket, DEFER_COUNT>,
}

/// State machine for writes
#[derive(Debug)]
enum TxState {
    /// Awaiting write, buffer is unused
    Idle,

    /// Writing to the socket. Buffer is encrypted in-place.
    /// Should never be left in `idx==len` state,
    /// instead should transition to Idle
    Write {
        /// Cursor position in the buffer
        idx: usize,
        /// Buffer available to write
        len: usize,
    },

    /// No more output will be produced
    Closed,
}

impl core::fmt::Debug for TrafOut<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TrafOut").field("state", &self.state).finish_non_exhaustive()
    }
}

#[cfg(feature = "alloc")]
impl TrafIn<'static> {
    pub fn new_owned() -> Self {
        let mut s = Self::new(&mut []);
        s.buf = SliceOrVec::Owned(Box::new([0; _]));
        s
    }
}

impl<'a> TrafOut<'a> {
    pub fn new(buf: &'a mut [u8]) -> Self {
        Self {
            buf: SliceOrVec::Borrowed(buf),
            state: TxState::Idle,
            drain: false,
            sending_kex: false,
            deferred_packets: Deque::new(),
        }
    }

    /// Serializes and and encrypts a packet to send
    ///
    /// If the output buffer is full or a rekey is in progress, the
    /// packet will be enqueued to be sent later. If the deferred packet queue
    /// is full, `NoRoom` will be returned.
    ///
    /// `BusySend` error is recoverable, others should be treated as fatal.
    pub(crate) fn send_packet(
        &mut self,
        p: packets::Packet,
        keys: &mut KeyState,
    ) -> Result<()> {
        let is_kex = matches!(p.category(), packets::Category::Kex);

        if is_kex || (self.deferred_packets.is_empty() && !self.sending_kex) {
            // Send the packet normally if it fits.
            // KEX packets can be sent even if other packets are deferred
            // (KEX packets don't get deferred themselves).
            // A KexInit is only sent when there are no deferred packets,
            // so we don't need to worry about incorrect reordering.
            match self.send_packet_inner(&p, keys) {
                Err(Error::NoRoom { .. }) => {
                    debug_assert!(!is_kex, "KEX packets should have room");
                    // non-kex packets get deferred
                }
                res => return res,
            }
        }

        // Either it didn't fit (NoRoom), or the deferred queue
        // is already in use so we need to enqueue after that.
        // Attempt to defer the packet.

        let pnum = p.message_num();
        trace!("Delay packet type {pnum:?}");

        // Convert to a DeferredPacket if possible
        let Ok(dp) = DeferredPacket::try_from(p) else {
            // Packet type isn't expected to be deferred.
            trace!("NoRoom packet type {pnum:?}");
            return error::BusySend { packet: pnum, unsupported: true }.fail();
        };

        self.deferred_packets.push_front(dp).map_err(|_| {
            error!("No space to queue packet");
            trace!("NoRoom packet type {pnum:?}");
            error::BusySend { packet: pnum, unsupported: false }.build()
        })
    }

    // Check some invariants, and track whether we're sending KEX.
    fn track_send_packet(
        &mut self,
        p: &packets::Packet,
        keys: &mut KeyState,
    ) -> Result<()> {
        // Check that packets are being encrypted
        // This is checked in release and debug.
        match p.category() {
            packets::Category::All | packets::Category::Kex => (),
            _ => {
                if keys.is_send_cleartext() {
                    return Error::bug_msg("send cleartext");
                }
            }
        }

        // KEX send packet catetory checked in debug builds for fuzzing.
        if self.sending_kex {
            // strict kex is ignored since we don't have access to
            // conn.kex.
            debug_assert!(matches!(
                p.category(),
                packets::Category::All | packets::Category::Kex
            ));
        }

        // Track KEX sending state
        match p {
            Packet::KexInit(_) => {
                debug_assert!(!self.sending_kex);
                self.sending_kex = true;
            }
            Packet::NewKeys(_) => {
                debug_assert!(self.sending_kex);
                self.sending_kex = false;
            }
            _ => (),
        }

        Ok(())
    }

    /// Serializes and and encrypts a packet to send
    ///
    /// The packet will not be enqueued to the deferred queue.
    /// This function should not usually be called directly.
    ///
    /// `NoRoom` error is recoverable, others should be treated as fatal.
    pub fn send_packet_inner(
        &mut self,
        p: &packets::Packet,
        keys: &mut KeyState,
    ) -> Result<()> {
        self.track_send_packet(p, keys)?;

        // Either a fresh buffer or appending to write
        let (idx, len) = match self.state {
            TxState::Idle => (0, 0),
            TxState::Write { idx, len } => (idx, len),
            TxState::Closed => {
                trace!("Dropped output after close {p:?}");
                return Ok(());
            }
        };

        // Use the remainder of our buffer to write the packet. Payload starts
        // after the length and padding bytes which get filled by encrypt()
        let wbuf = &mut self.buf[len..];
        if wbuf.len() < SSH_PAYLOAD_START {
            return error::NoRoom.fail();
        }
        let plen = sshwire::write_ssh(&mut wbuf[SSH_PAYLOAD_START..], &p)?;
        trace!("Sending {p:?}");

        // Encrypt in place
        let elen = keys.encrypt(plen, wbuf)?;
        self.state = TxState::Write { idx, len: len + elen };
        Ok(())
    }

    pub fn send_deferred_packets(&mut self, keys: &mut KeyState) -> Result<()> {
        while let Some(d) = self.deferred_packets.back() {
            let p = Packet::from(d);
            match self.send_packet_inner(&p, keys) {
                Ok(()) => {
                    self.deferred_packets.pop_back();
                }
                Err(Error::NoRoom { .. }) => {
                    // Can't progress, let the caller retry later
                    break;
                }
                Err(e) => return Err(e),
            }
        }

        Ok(())
    }

    pub fn have_deferred_packets(&self) -> bool {
        !self.deferred_packets.is_empty()
    }

    pub fn is_output_pending(&self) -> bool {
        trace!("is_output_pending st {:?}", self.state);
        matches!(self.state, TxState::Write { .. })
    }

    /// Returns payload space available to send a packet. Returns 0 if not ready or full
    pub fn send_allowed(&self, keys: &KeyState) -> usize {
        if !self.deferred_packets.is_empty() {
            // Don't allow sending packets when deferred ones are waiting.
            // Otherwise the deferred queue will run out of room.
            return 0;
        }

        // TODO: test for full output buffer
        match self.state {
            TxState::Write { len, .. } => keys.max_enc_payload(self.buf.len() - len),
            TxState::Idle => keys.max_enc_payload(self.buf.len()),
            // output will just be dropped in closed state.
            TxState::Closed => self.buf.len(),
        }
    }

    /// Move to Closed state. Current output is lost, future output
    /// is discarded. This is called when the output tcp pipe
    /// has closed so there's nowhere to send output anyway.
    pub fn close(&mut self) {
        self.state = TxState::Closed
    }

    pub fn closed(&self) -> bool {
        matches!(self.state, TxState::Closed)
    }

    pub fn send_version(&mut self) -> Result<(), Error> {
        if !matches!(self.state, TxState::Idle) {
            return Error::bug();
        }

        let len = ident::write_version(&mut self.buf)?;
        self.state = TxState::Write { idx: 0, len };
        Ok(())
    }

    pub fn output_buf(&mut self) -> &[u8] {
        match self.state {
            TxState::Write { ref mut idx, len } => {
                let wlen = len - *idx;
                &self.buf[*idx..*idx + wlen]
            }
            _ => &[],
        }
    }

    pub fn consume_output(&mut self, l: usize) {
        if let TxState::Write { ref mut idx, len } = self.state {
            let wlen = (len - *idx).min(l);
            *idx += wlen;

            if *idx == len {
                // all done, read the next packet
                self.state = TxState::Idle
            }
        }
    }

    pub fn sender<'s>(&'s mut self, keys: &'s mut KeyState) -> TrafSend<'s, 'a> {
        TrafSend::new(self, keys)
    }

    /// Return whether output is draining.
    ///
    /// Used to determine whether to initiate outbound traffic, such as channel writes.
    /// Generally immediate responses to incoming messages should still be sent
    /// even when draining. Otherwise they would need to be put in deferred_packets
    /// which may run out.
    pub fn is_draining(&self) -> bool {
        self.drain
    }
}

#[cfg(feature = "alloc")]
impl TrafOut<'static> {
    pub fn new_owned() -> Self {
        let mut s = Self::new(&mut []);
        s.buf = SliceOrVec::Owned(Box::new([0; _]));
        s
    }
}

/// Convenience to pass TrafOut with keys
pub(crate) struct TrafSend<'s, 'a> {
    out: &'s mut TrafOut<'a>,
    keys: &'s mut KeyState,
}

impl<'s, 'a> TrafSend<'s, 'a> {
    fn new(out: &'s mut TrafOut<'a>, keys: &'s mut KeyState) -> Self {
        Self { out, keys }
    }

    pub fn send<'p, P: Into<packets::Packet<'p>>>(&mut self, p: P) -> Result<()> {
        self.out.send_packet(p.into(), self.keys)
    }

    pub fn rekey_send(&mut self, keys: KeysSend) {
        self.keys.rekey_send(keys);
    }

    pub fn rekey_recv(&mut self, keys: KeysRecv) {
        self.keys.rekey_recv(keys)
    }

    pub fn send_version(&mut self) -> Result<(), Error> {
        self.out.send_version()
    }

    /// Returns the current receive sequence number
    pub fn recv_seq(&self) -> u32 {
        self.keys.seq_decrypt.0
    }

    pub fn enable_strict_kex(&mut self) {
        self.keys.enable_strict_kex();
    }

    pub fn is_rekey_needed(&self) -> bool {
        self.keys.is_rekey_needed()
    }

    /// Set TrafOut to start draining output.
    ///
    /// Only one caller/area should be using set_drain_output() at a time.
    /// For `TrafOut` itself there isn't a problem with multiple
    /// callers enabling/disabling drain, but it could result in races
    /// between callers. Only kex should be using it currently, so
    /// there is a debug_assert! to that effect.
    pub fn set_drain_output(&mut self, drain: bool) {
        debug_assert!(drain != self.out.drain, "set_drain_output() dupe");
        self.out.drain = drain;
    }

    /// Test if output buffer is empty.
    ///
    /// Fails if `set_drain_output(true)` wasn't set (debug panic)
    /// This isn't inherent, but helps catch misuse (see comment
    /// for set_drain_output()).
    pub fn is_drained(&self) -> bool {
        debug_assert!(self.out.drain);
        matches!(self.out.state, TxState::Idle)
            && self.out.deferred_packets.is_empty()
    }
}

/// Packet types that may be sent once a currently-NoRoom TrafOut clears.
///
/// Rather than storing an entire `Packet<'static>`, keep a queue of smaller
/// `DeferredPacket`s.
///
/// These packet types account for most packets that may be sent as responses
/// or from other asynchronous events (rekey packet count reached, as an example).
///
/// These also queue packets to be sent while a KEX is in progress
/// (other packet types aren't allowed)
///
/// Some packet types aren't included here since they're deferred via other
/// mechanisms:
///
/// - ChannelWindowAdjust. Can be retried later.
/// - KEX packets. The output buffer is drained at the start of a KEX.
/// - Userauth - we hope it only occurs early when traffic is
///   well defined (no channels) and no KEXes are happening.
#[derive(Debug)]
pub enum DeferredPacket {
    ChannelSuccess(packets::ChannelSuccess),
    ChannelFailure(packets::ChannelFailure),
    ChannelOpenFailure(packets::ChannelOpenFailure<'static>),
    ChannelOpenConfirmation(packets::ChannelOpenConfirmation),
    ChannelEof(packets::ChannelEof),
    ChannelClose(packets::ChannelClose),
    Unimplemented(packets::Unimplemented),
    RequestFailure(packets::RequestFailure),
    RequestSuccess(packets::RequestSuccess),
}

impl DeferredPacket {}

impl From<&DeferredPacket> for Packet<'static> {
    fn from(d: &DeferredPacket) -> Self {
        match d {
            DeferredPacket::ChannelSuccess(p) => (p.clone()).into(),
            DeferredPacket::ChannelFailure(p) => (p.clone()).into(),
            DeferredPacket::ChannelOpenFailure(p) => (p.clone()).into(),
            DeferredPacket::ChannelOpenConfirmation(p) => (p.clone()).into(),
            DeferredPacket::ChannelEof(p) => (p.clone()).into(),
            DeferredPacket::ChannelClose(p) => (p.clone()).into(),
            DeferredPacket::Unimplemented(p) => (p.clone()).into(),
            DeferredPacket::RequestFailure(p) => (p.clone()).into(),
            DeferredPacket::RequestSuccess(p) => (p.clone()).into(),
        }
    }
}

impl<'a> TryFrom<Packet<'a>> for DeferredPacket {
    type Error = Error;
    fn try_from(packet: Packet<'a>) -> Result<Self> {
        Ok(match packet {
            Packet::ChannelSuccess(p) => Self::ChannelSuccess(p),
            Packet::ChannelFailure(p) => Self::ChannelFailure(p),
            Packet::ChannelOpenConfirmation(p) => Self::ChannelOpenConfirmation(p),
            Packet::ChannelEof(p) => Self::ChannelEof(p),
            Packet::ChannelClose(p) => Self::ChannelClose(p),
            Packet::Unimplemented(p) => Self::Unimplemented(p),
            Packet::RequestFailure(p) => Self::RequestFailure(p),
            Packet::RequestSuccess(p) => Self::RequestSuccess(p),

            Packet::ChannelOpenFailure(p) => {
                Self::ChannelOpenFailure(packets::ChannelOpenFailure {
                    // empty desc for 'static
                    desc: TextString::new(),
                    lang: "",
                    ..p
                })
            }

            // Unhandled types
            _ => return error::SSHProtoUnsupported.fail(),
        })
    }
}