sunset 0.4.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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
use self::packets::ExitSignal;

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

use core::num::NonZeroUsize;
use core::task::Waker;

use heapless::{String, Vec};

use crate::{runner::set_waker, *};
use config::*;
use conn::DispatchEvent;
use event::{CliEventId, ServEventId};
use packets::{
    ChannelData, ChannelDataExt, ChannelOpen, ChannelOpenType, ChannelReqType,
    ChannelRequest, Packet,
};
use runner::ChanHandle;
use sshnames::*;
use sshwire::{BinString, SSHEncodeEnum, TextString};
use traffic::TrafSend;

pub(crate) struct Channels {
    ch: [Option<Channel>; config::MAX_CHANNELS],
    is_client: bool,
}

impl Channels {
    pub fn new(is_client: bool) -> Self {
        Channels { ch: Default::default(), is_client }
    }

    pub fn open<'b>(
        &mut self,
        ty: packets::ChannelOpenType<'b>,
    ) -> Result<(ChanNum, Packet<'b>)> {
        let num = self.unused_chan()?;

        let chan = Channel::new(num, (&ty).into());
        let p = packets::ChannelOpen {
            sender_num: num.0,
            initial_window: chan.recv.window as u32,
            max_packet: chan.recv.max_packet as u32,
            ty,
        }
        .into();
        let ch = &mut self.ch[num.0 as usize];
        let ch = ch.insert(chan);
        Ok((ch.num(), p))
    }

    /// Returns a `Channel` for a local number, any state including `InOpen`.
    fn get_any(&self, num: ChanNum) -> Result<&Channel> {
        self.ch
            .get(num.0 as usize)
            // out of range
            .ok_or(error::BadChannel { num }.build())?
            .as_ref()
            // unused channel
            .ok_or(error::BadChannel { num }.build())
    }

    /// Returns a `Channel` for a local number. Excludes `InOpen` or `Opening` state.
    pub(crate) fn get(&self, num: ChanNum) -> Result<&Channel> {
        let ch = self.get_any(num)?;

        match ch.state {
            ChanState::InOpen | ChanState::Opening => {
                error::BadChannel { num }.fail()
            }
            _ => Ok(ch),
        }
    }

    fn get_any_mut(&mut self, num: ChanNum) -> Result<&mut Channel> {
        self.ch
            .get_mut(num.0 as usize)
            // out of range
            .ok_or(error::BadChannel { num }.build())?
            .as_mut()
            // unused channel
            .ok_or(error::BadChannel { num }.build())
    }

    fn get_mut(&mut self, num: ChanNum) -> Result<&mut Channel> {
        let ch = self.get_any_mut(num)?;

        match ch.state {
            ChanState::InOpen | ChanState::Opening => {
                error::BadChannel { num }.fail()
            }
            _ => Ok(ch),
        }
    }

    pub fn by_handle_mut(&mut self, handle: &ChanHandle) -> &mut Channel {
        self.get_mut(handle.0).unwrap()
    }

    /// Must be called when an application has finished with a channel.
    pub fn done(&mut self, num: ChanNum) -> Result<()> {
        let ch = self.get_mut(num)?;
        debug_assert!(!ch.app_done);
        ch.app_done = true;
        Ok(())
    }

    fn remove_any(&mut self, num: ChanNum) -> Result<()> {
        trace!("remove_any channel {}", num);
        self.ch[num.0 as usize] = None;
        Ok(())
    }

    fn remove(&mut self, num: ChanNum) -> Result<()> {
        // TODO any checks?
        let ch = self.get_any_mut(num)?;
        if ch.app_done {
            trace!("removing channel {}", num);
            self.ch[num.0 as usize] = None;
        } else {
            ch.state = ChanState::PendingDone;
            trace!("not removing channel {}, not finished", num);
        }
        Ok(())
    }

    /// Returns the first available channel
    fn unused_chan(&self) -> Result<ChanNum> {
        self.ch
            .iter()
            .enumerate()
            .find_map(|(i, ch)| {
                if ch.as_ref().is_none() {
                    Some(ChanNum(i as u32))
                } else {
                    None
                }
            })
            .ok_or(Error::NoChannels)
    }

    /// Creates a new channel in InOpen state.
    fn reserve_chan(&mut self, co: &ChannelOpen) -> Result<&mut Channel> {
        let num = self.unused_chan()?;
        let mut chan = Channel::new(num, (&co.ty).into());
        chan.send = Some(ChanDir {
            num: co.sender_num,
            max_packet: co.max_packet as usize,
            window: co.initial_window as usize,
        });
        chan.state = ChanState::InOpen;

        let ch = &mut self.ch[num.0 as usize];
        *ch = Some(chan);
        Ok(ch.as_mut().unwrap())
    }

    /// Returns the channel data packet to send.
    ///
    /// Caller has already checked valid length with send_allowed(), and
    /// validated `dt`.
    /// Don't call with zero length data.
    pub(crate) fn send_data<'b>(
        &mut self,
        num: ChanNum,
        dt: ChanData,
        data: &'b [u8],
    ) -> Result<Packet<'b>> {
        debug_assert!(!data.is_empty());

        let ch = self.get_mut(num)?;
        let send = ch.send.as_mut().trap()?;
        if data.len() > send.max_packet || data.len() > send.window {
            trace!(
                "data len {}, max {}, window {}",
                data.len(),
                send.max_packet,
                send.window
            );
            return Err(Error::bug());
        }
        send.window -= data.len();
        trace!("send_data: new window {}", send.window);

        let data = BinString(data);
        let p = match dt {
            ChanData::Normal => packets::ChannelData { num: send.num, data }.into(),
            ChanData::Stderr => packets::ChannelDataExt {
                num: send.num,
                code: sshnames::SSH_EXTENDED_DATA_STDERR,
                data,
            }
            .into(),
        };

        Ok(p)
    }

    /// Informs the channel layer that an incoming packet has been read out,
    /// so a window adjustment can be sent.
    pub(crate) fn finished_read(
        &mut self,
        num: ChanNum,
        len: usize,
        s: &mut TrafSend,
    ) -> Result<()> {
        let ch = self.get_mut(num)?;
        ch.finished_input(len);
        if let Some(w) = ch.check_window_adjust()? {
            s.send(w)?;
        }
        Ok(())
    }

    pub(crate) fn have_recv_eof(&self, num: ChanNum) -> bool {
        self.get(num).is_ok_and(|c| c.have_recv_eof())
    }

    pub(crate) fn is_closed(&self, num: ChanNum) -> bool {
        self.get(num).is_ok_and(|c| c.is_closed())
    }

    pub(crate) fn send_allowed(&self, num: ChanNum) -> Option<usize> {
        self.get(num).map_or(Some(0), |c| c.send_allowed())
    }

    pub(crate) fn valid_send(&self, num: ChanNum, dt: ChanData) -> bool {
        self.get(num).is_ok_and(|c| c.valid_send(dt))
    }

    /// Wake the channel with a ready input data packet.
    pub fn wake_read(&mut self, num: ChanNum, dt: ChanData, is_client: bool) {
        if let Ok(ch) = self.get_mut(num) {
            ch.wake_read(dt, is_client);
        } else {
            debug_assert!(false, "wake_read bad channel");
        }
    }

    /// Wake all ready output channels
    pub fn wake_write(&mut self, is_client: bool) {
        for ch in self.ch.iter_mut().filter_map(|c| c.as_mut()) {
            ch.wake_write(None, is_client)
        }
    }

    pub(crate) fn term_window_change(
        &self,
        num: ChanNum,
        winch: &packets::WinChange,
        s: &mut TrafSend,
    ) -> Result<()> {
        let ch = self.get(num)?;
        match ch.ty {
            ChanType::Session => Req::WinChange(winch.clone()).send(ch, s),
            _ => error::BadChannelData.fail(),
        }
    }

    pub(crate) fn term_break(
        &self,
        num: ChanNum,
        length: u32,
        s: &mut TrafSend,
    ) -> Result<()> {
        let ch = self.get(num)?;
        let br = packets::Break {
            length: if length == 0 { 0 } else { length.clamp(500, 3000) },
        };
        match ch.ty {
            ChanType::Session => Req::Break(br).send(ch, s),
            _ => error::BadChannelData.fail(),
        }
    }

    fn dispatch_open(
        &mut self,
        p: &ChannelOpen<'_>,
        s: &mut TrafSend,
    ) -> Result<DispatchEvent> {
        match self.dispatch_open_inner(p) {
            Err(DispatchOpenError::Failure(f)) => {
                s.send(packets::ChannelOpenFailure {
                    num: p.sender_num,
                    reason: f as u32,
                    desc: "".into(),
                    lang: "",
                })?;
                Ok(DispatchEvent::None)
            }
            Err(DispatchOpenError::Error(e)) => Err(e),
            Ok(ev) => Ok(ev),
        }
    }

    // the caller will send failure messages if required
    fn dispatch_open_inner(
        &mut self,
        p: &ChannelOpen,
    ) -> Result<DispatchEvent, DispatchOpenError> {
        // Check validity before reserving a channel
        match &p.ty {
            ChannelOpenType::Unknown(u) => {
                error!("Rejecting unknown channel type '{u}'");
                return Err(ChanFail::SSH_OPEN_UNKNOWN_CHANNEL_TYPE.into());
            }
            ChannelOpenType::Session if self.is_client => {
                trace!("dispatch not server");
                return Err(error::SSHProto.build().into());
            }
            ChannelOpenType::ForwardedTcpip(_) => {
                // TODO implement it
                debug!("Rejecting forwarded tcp");
                return Err(ChanFail::SSH_OPEN_UNKNOWN_CHANNEL_TYPE.into());
            }
            ChannelOpenType::DirectTcpip(_) => {
                // TODO implement it
                debug!("Rejecting direct tcp");
                return Err(ChanFail::SSH_OPEN_UNKNOWN_CHANNEL_TYPE.into());
            }
            _ => (),
        }

        // Reserve a channel
        let ch = self.reserve_chan(p)?;

        // Beware that a reserved channel must be cleaned up on failure

        match &p.ty {
            ChannelOpenType::Session => {
                Ok(DispatchEvent::ServEvent(ServEventId::OpenSession {
                    num: ch.num(),
                }))
            }
            // ChannelOpenType::ForwardedTcpip(t) => b.open_tcp_forwarded(handle, t),
            // ChannelOpenType::DirectTcpip(t) => b.open_tcp_direct(handle, t),
            _ => {
                // Checked above
                unreachable!()
            }
        }
    }

    pub fn resume_open(
        &mut self,
        c: ChanNum,
        failure: Option<ChanFail>,
        s: &mut TrafSend,
    ) -> Result<()> {
        let ch = self.get_any_mut(c)?;
        if let Some(failure) = failure {
            let sender_num = ch.send_num()?;
            self.remove_any(c)?;
            s.send(packets::ChannelOpenFailure {
                num: sender_num,
                reason: failure as u32,
                desc: "".into(),
                lang: "",
            })?;
            Ok(())
        } else {
            // Success
            s.send(ch.open_done()?)
        }
    }

    // Some returned errors will be caught by caller and returned as SSH messages
    fn dispatch_inner(
        &mut self,
        packet: Packet,
        s: &mut TrafSend,
    ) -> Result<DispatchEvent> {
        let mut ev = DispatchEvent::default();
        let is_client = self.is_client;

        match packet {
            Packet::ChannelOpen(p) => {
                ev = self.dispatch_open(&p, s)?;
            }

            Packet::ChannelOpenConfirmation(p) => {
                let ch = self.get_any_mut(ChanNum(p.num))?;
                match ch.state {
                    ChanState::Opening => {
                        debug_assert!(ch.send.is_none());

                        if ch.app_done {
                            return Ok(DispatchEvent::None);
                        }

                        ch.send = Some(ChanDir {
                            num: p.sender_num,
                            max_packet: p.max_packet as usize,
                            window: p.initial_window as usize,
                        });

                        match ch.ty {
                            ChanType::Session => {
                                ev = DispatchEvent::CliEvent(
                                    CliEventId::SessionOpened(ch.num()),
                                );
                            }
                            ChanType::Tcp => {
                                trace!("TODO tcp channel")
                            }
                        }

                        ch.state = ChanState::Normal;
                    }
                    _ => {
                        trace!("Bad channel state {:?}", ch.state);
                        return error::SSHProto.fail();
                    }
                }
            }

            Packet::ChannelOpenFailure(p) => {
                let ch = self.get_any(ChanNum(p.num))?;
                if ch.send.is_some() {
                    // TODO: or just warn?
                    trace!("open failure late?");
                    return error::SSHProto.fail();
                } else {
                    self.remove(ChanNum(p.num))?;
                    // TODO event
                }
            }
            Packet::ChannelWindowAdjust(p) => {
                let chan = self.get_mut(ChanNum(p.num))?;
                let send = chan.send.as_mut().trap()?;
                send.window = send.window.saturating_add(p.adjust as usize);
                trace!("new window {}", send.window);
                // Wake any writers that might have been blocked.
                chan.wake_write(None, is_client);
            }
            Packet::ChannelData(p) => {
                let ch = self.get(ChanNum(p.num))?;
                if ch.app_done {
                    trace!("Ignoring data for done channel");
                } else if let Some(len) = NonZeroUsize::new(p.data.0.len()) {
                    // TODO check we are expecting input
                    let di =
                        DataIn { num: ChanNum(p.num), dt: ChanData::Normal, len };
                    ev = DispatchEvent::Data(di);
                } else {
                    trace!("Zero length channeldata");
                }
            }
            Packet::ChannelDataExt(p) => {
                let ch = self.get_mut(ChanNum(p.num))?;
                if ch.app_done {
                    trace!("Ignoring data for done channel");
                } else if !is_client || p.code != sshnames::SSH_EXTENDED_DATA_STDERR
                {
                    // Discard the data, sunset can't handle this
                    debug!("Ignoring unexpected dt data, code {}", p.code);
                    ch.finished_input(p.data.0.len());
                } else if let Some(len) = NonZeroUsize::new(p.data.0.len()) {
                    // TODO check we are expecting input and dt is valid.
                    let di =
                        DataIn { num: ChanNum(p.num), dt: ChanData::Stderr, len };
                    ev = DispatchEvent::Data(di);
                } else {
                    trace!("Zero length channeldataext");
                }
            }
            Packet::ChannelEof(p) => {
                let ch = self.get_mut(ChanNum(p.num))?;
                ch.handle_eof(s, is_client)?;
            }
            Packet::ChannelClose(p) => {
                let is_client = self.is_client;
                let ch = self.get_mut(ChanNum(p.num))?;
                ch.handle_close(s, is_client)?;
            }
            Packet::ChannelRequest(p) => {
                let is_client = self.is_client;
                match self.get_mut(ChanNum(p.num)) {
                    Ok(ch) => {
                        ev = ch.dispatch_request(&p, s, is_client);
                    }
                    Err(_) => debug!("Ignoring request to unknown channel: {p:#?}"),
                }
            }
            Packet::ChannelSuccess(_p) => {
                trace!("channel success, TODO");
            }
            Packet::ChannelFailure(_p) => {
                trace!("channel failure, TODO");
            }
            _ => Error::bug_msg("unreachable")?,
        };

        Ok(ev)
    }

    /// Incoming packet handling
    // TODO: protocol errors etc should perhaps be less fatal,
    // ssh implementations are usually imperfect.
    pub fn dispatch(
        &mut self,
        packet: Packet,
        s: &mut TrafSend,
    ) -> Result<DispatchEvent> {
        let r = self.dispatch_inner(packet, s);

        match r {
            Err(Error::BadChannel { num, .. }) => {
                warn!("Ignoring bad channel number {:?}", num);
                // warn!("Ignoring bad channel number {:?}", r.unwrap_err().backtrace());
                Ok(DispatchEvent::default())
            }
            // TODO: close channel on error? or on SSHProtoError?
            r => r,
        }
    }

    pub fn resume_chanreq(
        &self,
        p: &Packet,
        success: bool,
        s: &mut TrafSend,
    ) -> Result<()> {
        if let Packet::ChannelRequest(r) = p {
            let ch = self.get(ChanNum(r.num))?;
            if r.want_reply {
                let num = ch.send_num()?;
                if success {
                    s.send(packets::ChannelSuccess { num })
                } else {
                    s.send(packets::ChannelFailure { num })
                }
            } else {
                Ok(())
            }
        } else {
            Err(Error::bug())
        }
    }

    pub fn fetch_servcommand<'p>(&self, p: &Packet<'p>) -> Result<TextString<'p>> {
        match p {
            Packet::ChannelRequest(ChannelRequest {
                req: ChannelReqType::Exec(packets::Exec { command }),
                ..
            })
            | Packet::ChannelRequest(ChannelRequest {
                req:
                    ChannelReqType::Subsystem(packets::Subsystem { subsystem: command }),
                ..
            }) => Ok(*command),
            _ => Err(Error::bug()),
        }
    }

    pub fn fetch_env_name<'p>(&self, p: &Packet<'p>) -> Result<TextString<'p>> {
        match p {
            Packet::ChannelRequest(ChannelRequest {
                req: ChannelReqType::Environment(packets::Environment { name, .. }),
                ..
            }) => Ok(*name),
            _ => Err(Error::bug()),
        }
    }

    pub fn fetch_env_value<'p>(&self, p: &Packet<'p>) -> Result<TextString<'p>> {
        match p {
            Packet::ChannelRequest(ChannelRequest {
                req:
                    ChannelReqType::Environment(packets::Environment { name: _, value }),
                ..
            }) => Ok(*value),
            _ => Err(Error::bug()),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum ChanType {
    Session,
    Tcp,
}

impl From<&ChannelOpenType<'_>> for ChanType {
    fn from(c: &ChannelOpenType) -> Self {
        match c {
            ChannelOpenType::Session => ChanType::Session,
            ChannelOpenType::DirectTcpip(_) => ChanType::Tcp,
            ChannelOpenType::ForwardedTcpip(_) => ChanType::Tcp,
            ChannelOpenType::Unknown(_) => unreachable!(),
        }
    }
}

#[derive(Debug)]
pub struct ModePair {
    pub opcode: u8,
    pub arg: u32,
}

#[derive(Debug)]
pub struct Pty {
    pub term: String<MAX_TERM>,
    pub cols: u32,
    pub rows: u32,
    pub width: u32,
    pub height: u32,
    pub modes: Vec<ModePair, { termmodes::NUM_MODES }>,
}

impl TryFrom<&packets::PtyReq<'_>> for Pty {
    type Error = Error;
    fn try_from(p: &packets::PtyReq) -> Result<Self, Self::Error> {
        debug!("TODO implement pty modes");
        let term = p.term.as_ascii()?.try_into().map_err(|_| Error::BadString)?;
        Ok(Pty {
            term,
            cols: p.cols,
            rows: p.rows,
            width: p.width,
            height: p.height,
            modes: Vec::new(),
        })
    }
}
/// Like a `packets::ChannelReqType` but with storage.
/// Lifetime-free variants have the packet part directly.
#[derive(Debug)]
pub enum Req<'a> {
    // TODO let hook impls provide a string type?
    Shell,
    Exec(&'a str),
    Subsystem(&'a str),
    Pty(Pty),
    WinChange(packets::WinChange),
    Break(packets::Break),
    // Signal,
    // ExitStatus,
    // ExitSignal,
}

impl Req<'_> {
    pub(crate) fn send(self, ch: &Channel, s: &mut TrafSend) -> Result<()> {
        let t;
        let req = match self {
            Req::Shell => ChannelReqType::Shell,
            Req::Pty(pty) => {
                debug!("TODO implement pty modes");
                t = pty.term;
                ChannelReqType::Pty(packets::PtyReq {
                    term: TextString(t.as_bytes()),
                    cols: pty.cols,
                    rows: pty.rows,
                    width: pty.width,
                    height: pty.height,
                    modes: BinString(&[]),
                })
            }
            Req::Exec(cmd) => {
                ChannelReqType::Exec(packets::Exec { command: cmd.into() })
            }
            Req::Subsystem(cmd) => ChannelReqType::Subsystem(packets::Subsystem {
                subsystem: cmd.into(),
            }),
            Req::WinChange(rt) => ChannelReqType::WinChange(rt),
            Req::Break(rt) => ChannelReqType::Break(rt),
        };

        let p = ChannelRequest {
            num: ch.send_num()?,
            // we aren't handling responses for anything
            want_reply: false,
            req,
        };
        let p: Packet = p.into();
        s.send(p)
    }
}

/// Convenience for the types of session channels that can be opened
pub enum SessionCommand<S: AsRef<str>> {
    Shell,
    Exec(S),
    Subsystem(S),
}

impl<'a, S: AsRef<str> + 'a> From<&'a SessionCommand<S>> for Req<'a> {
    fn from(val: &'a SessionCommand<S>) -> Self {
        match val {
            SessionCommand::Shell => Req::Shell,
            SessionCommand::Exec(s) => Req::Exec(s.as_ref()),
            SessionCommand::Subsystem(s) => Req::Subsystem(s.as_ref()),
        }
    }
}

/// Per-direction channel variables
#[derive(Debug)]
struct ChanDir {
    /// `u32` rather than `ChanNum` because it can also be used
    /// for the sender-side number
    num: u32,
    max_packet: usize,
    window: usize,
}

#[derive(Debug)]
enum ChanState {
    /// An incoming channel open request that has not yet been responded to.
    ///
    /// Not to be used for normal channel messages
    InOpen,

    // TODO: perhaps .get() and .get_mut() should ignore Opening state channels?
    Opening,
    Normal,
    RecvEof,
    // TODO: recvclose state probably shouldn't be possible, we remove it straight away?
    RecvClose,
    /// The channel is unused and ready to close after a call to `done()`
    PendingDone,
}

#[derive(Debug)]
pub(crate) struct Channel {
    ty: ChanType,
    state: ChanState,
    sent_eof: bool,
    sent_close: bool,

    recv: ChanDir,
    /// populated in all states except `Opening`
    send: Option<ChanDir>,

    /// Accumulated bytes for the next window adjustment (inbound data direction)
    pending_adjust: usize,

    full_window: usize,

    /// Set once application has called `done()`. The channel
    /// will only be removed from the list
    /// (allowing channel number re-use) if `app_done` is set
    app_done: bool,

    // Wakers for notifying readyness. Usually used for async.
    read_waker: Option<Waker>,
    write_waker: Option<Waker>,
    /// Will be a stderr read waker for a client, or stderr write waker for
    /// a server.
    ext_waker: Option<Waker>,
}

impl Channel {
    fn new(num: ChanNum, ty: ChanType) -> Self {
        Channel {
            ty,
            state: ChanState::Opening,
            sent_close: false,
            sent_eof: false,
            recv: ChanDir {
                num: num.0,
                // TODO these should depend on SSH rx buffer size minus overhead
                max_packet: config::DEFAULT_MAX_PACKET,
                window: config::DEFAULT_WINDOW,
            },
            send: None,
            pending_adjust: 0,
            full_window: config::DEFAULT_WINDOW,
            app_done: false,
            read_waker: None,
            write_waker: None,
            ext_waker: None,
        }
    }

    /// Local channel number
    pub(crate) fn num(&self) -> ChanNum {
        ChanNum(self.recv.num)
    }

    /// Remote channel number, fails if channel is in progress opening
    ///
    /// Returned as a plain `u32` since it is a different namespace than `ChanNum`.
    /// This is the channel number included in most sent packets.
    pub(crate) fn send_num(&self) -> Result<u32> {
        Ok(self.send.as_ref().trap()?.num)
    }

    pub fn set_read_waker(&mut self, dt: ChanData, is_client: bool, waker: &Waker) {
        match dt {
            ChanData::Normal => {
                set_waker(&mut self.read_waker, waker);
            }
            ChanData::Stderr => {
                if is_client {
                    set_waker(&mut self.ext_waker, waker);
                } else {
                    debug_assert!(false, "server ext read waker");
                }
            }
        }
    }

    pub fn set_write_waker(&mut self, dt: ChanData, is_client: bool, waker: &Waker) {
        match dt {
            ChanData::Normal => {
                set_waker(&mut self.write_waker, waker);
            }
            ChanData::Stderr => {
                if !is_client {
                    set_waker(&mut self.ext_waker, waker);
                } else {
                    debug_assert!(false, "client ext write waker");
                }
            }
        }
    }

    pub fn wake_read(&mut self, dt: ChanData, is_client: bool) {
        match dt {
            ChanData::Normal => {
                if let Some(w) = self.read_waker.take() {
                    w.wake()
                }
            }
            ChanData::Stderr => {
                if is_client {
                    if let Some(w) = self.ext_waker.take() {
                        w.wake()
                    }
                }
            }
        }
    }

    pub fn wake_write(&mut self, dt: Option<ChanData>, is_client: bool) {
        if dt == Some(ChanData::Normal) || dt.is_none() {
            if let Some(w) = self.read_waker.take() {
                w.wake()
            }
        }
        if !is_client && (dt == Some(ChanData::Normal) || dt.is_none()) {
            if let Some(w) = self.ext_waker.take() {
                w.wake()
            }
        }
    }

    /// Returns an open confirmation reply packet to send.
    /// Must be called with state of `InOpen`.
    fn open_done<'p>(&mut self) -> Result<Packet<'p>> {
        debug_assert!(matches!(self.state, ChanState::InOpen));

        self.state = ChanState::Normal;
        let p = packets::ChannelOpenConfirmation {
            num: self.send_num()?,
            sender_num: self.recv.num,
            initial_window: self.recv.window as u32,
            max_packet: self.recv.max_packet as u32,
        }
        .into();
        Ok(p)
    }

    fn dispatch_request(
        &mut self,
        p: &packets::ChannelRequest,
        s: &mut TrafSend,
        is_client: bool,
    ) -> DispatchEvent {
        let r = match (is_client, self.app_done) {
            // Reject requests if the application has closed
            // the channel. ChannelEOF is arbitrary.
            (_, true) => Err(Error::ChannelEOF),
            (true, _) => self.dispatch_client_request(p, s),
            (false, _) => self.dispatch_server_request(p, s),
        };

        r.unwrap_or_else(|_| {
            // All errors just send an error response, no failure.
            if p.want_reply {
                let num = self.send_num();
                debug_assert!(num.is_ok());
                if let Ok(num) = num {
                    let _ = s.send(packets::ChannelFailure { num });
                }
            }
            DispatchEvent::None
        })
    }

    fn dispatch_server_request(
        &self,
        p: &packets::ChannelRequest,
        _s: &mut TrafSend,
    ) -> Result<DispatchEvent> {
        if !matches!(self.ty, ChanType::Session) {
            return Err(Error::SSHProtoUnsupported);
        }

        let num = self.num();
        match &p.req {
            ChannelReqType::Shell => {
                Ok(DispatchEvent::ServEvent(ServEventId::SessionShell { num }))
            }
            ChannelReqType::Exec(_) => {
                Ok(DispatchEvent::ServEvent(ServEventId::SessionExec { num }))
            }
            ChannelReqType::Subsystem(_) => {
                Ok(DispatchEvent::ServEvent(ServEventId::SessionSubsystem { num }))
            }
            ChannelReqType::Pty(_) => {
                Ok(DispatchEvent::ServEvent(ServEventId::SessionPty { num }))
            }
            ChannelReqType::Environment(_) => {
                Ok(DispatchEvent::ServEvent(ServEventId::Environment { num }))
            }
            _ => {
                if let ChannelReqType::Unknown(u) = &p.req {
                    warn!("Unknown channel req type \"{}\"", u)
                } else {
                    // OK unwrap: tested for Unknown
                    warn!(
                        "Unhandled channel req \"{}\"",
                        p.req.variant_name().unwrap()
                    )
                };
                Err(Error::SSHProtoUnsupported)
            }
        }
    }

    /// Returns Ok(want_reply: bool) on success
    fn dispatch_client_request(
        &mut self,
        p: &packets::ChannelRequest,
        _s: &mut TrafSend,
    ) -> Result<DispatchEvent> {
        if !matches!(self.ty, ChanType::Session) {
            return Err(Error::SSHProtoUnsupported);
        }

        match &p.req {
            ChannelReqType::ExitStatus(_) => {
                Ok(DispatchEvent::CliEvent(CliEventId::SessionExit))
            }
            ChannelReqType::ExitSignal(_sig) => {
                Ok(DispatchEvent::CliEvent(CliEventId::SessionExit))
            }
            _ => {
                if let ChannelReqType::Unknown(u) = &p.req {
                    warn!("Unknown channel req type \"{}\"", u)
                } else {
                    // OK unwrap: tested for Unknown
                    warn!(
                        "Unhandled channel req \"{}\"",
                        p.req.variant_name().unwrap()
                    )
                };
                Err(Error::SSHProtoUnsupported)
            }
        }
    }

    fn handle_eof(&mut self, s: &mut TrafSend, is_client: bool) -> Result<()> {
        //TODO: check existing state?
        if !self.sent_eof {
            s.send(packets::ChannelEof { num: self.send_num()? })?;
            self.sent_eof = true;
        }

        // Wake readers on EOF
        self.wake_read(ChanData::Normal, is_client);
        if is_client {
            self.wake_read(ChanData::Stderr, is_client);
        }

        self.state = ChanState::RecvEof;
        // todo!();
        Ok(())
    }

    fn handle_close(&mut self, s: &mut TrafSend, is_client: bool) -> Result<()> {
        //TODO: check existing state?
        if !self.sent_close {
            s.send(packets::ChannelClose { num: self.send_num()? })?;
            self.sent_close = true;
        }

        // Wake readers and writers on EOF
        self.wake_read(ChanData::Normal, is_client);
        if is_client {
            self.wake_read(ChanData::Stderr, is_client);
        }
        self.wake_write(None, is_client);

        self.state = ChanState::RecvClose;
        Ok(())
    }

    fn finished_input(&mut self, len: usize) {
        self.pending_adjust = self.pending_adjust.saturating_add(len)
    }

    fn have_recv_eof(&self) -> bool {
        matches!(self.state, ChanState::RecvEof | ChanState::RecvClose)
    }

    fn is_closed(&self) -> bool {
        matches!(self.state, ChanState::RecvClose)
    }

    // None on close
    fn send_allowed(&self) -> Option<usize> {
        let r = self.send.as_ref().map(|s| usize::min(s.window, s.max_packet));
        trace!("send_allowed {r:?}");
        r
    }

    pub(crate) fn valid_send(&self, _dt: ChanData) -> bool {
        // TODO: later we should only allow non-pty "session" channels
        // to have dt, for stderr only.
        true
    }

    /// Returns a window adjustment packet if required
    fn check_window_adjust(&mut self) -> Result<Option<Packet<'_>>> {
        let num = self.send.as_mut().trap()?.num;
        if self.pending_adjust > self.full_window / 2 {
            let adjust = self.pending_adjust as u32;
            self.pending_adjust = 0;
            let p = packets::ChannelWindowAdjust { num, adjust }.into();
            Ok(Some(p))
        } else {
            Ok(None)
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct DataIn {
    pub num: ChanNum,
    pub dt: ChanData,
    // Zero length data does nothing.
    pub len: NonZeroUsize,
}

/// The result of a channel open request.
pub enum ChanOpened {
    Success,
    /// A channel open response will be sent later (for eg TCP open)
    Defer,
    /// A SSH failure code, as well as returning the passed channel handle
    Failure((ChanFail, ChanHandle)),
}

/// A SSH protocol local channel number
///
/// The number will always be in the range `0 <= num < MAX_CHANNELS`
/// and can be used as an index by applications.
/// Most external application API methods take a `ChanHandle` instead.
#[derive(Debug, PartialEq, Clone, Copy, Eq, Hash, Ord, PartialOrd)]
pub struct ChanNum(pub u32);

impl core::fmt::Display for ChanNum {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.0.fmt(f)
    }
}

/// Channel data type, normal or stderr
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum ChanData {
    /// `SSH_MSG_CHANNEL_DATA`
    Normal,
    /// `SSH_MSG_CHANNEL_EXTENDED_DATA`. Only `Stderr` is implemented by Sunset,
    /// other types are not widely used.
    Stderr,
    // Future API:
    // Other(u32),
}

impl ChanData {
    pub(crate) fn validate_send(&self, is_client: bool) -> Result<()> {
        if matches!(self, ChanData::Stderr) && is_client {
            error::BadChannelData.fail()
        } else {
            Ok(())
        }
    }

    pub(crate) fn validate_receive(&self, is_client: bool) -> Result<()> {
        if matches!(self, ChanData::Stderr) && !is_client {
            error::BadChannelData.fail()
        } else {
            Ok(())
        }
    }

    pub(crate) fn packet_offset(&self) -> usize {
        match self {
            ChanData::Normal => ChannelData::DATA_OFFSET,
            ChanData::Stderr => ChannelDataExt::DATA_OFFSET,
        }
    }
}

// for dispatch_open_inner()
enum DispatchOpenError {
    /// A program error
    Error(Error),
    /// A SSH failure response
    Failure(ChanFail),
}

impl From<Error> for DispatchOpenError {
    fn from(e: Error) -> Self {
        match e {
            Error::NoChannels => Self::Failure(ChanFail::SSH_OPEN_RESOURCE_SHORTAGE),
            e => Self::Error(e),
        }
    }
}

impl From<ChanFail> for DispatchOpenError {
    fn from(f: ChanFail) -> Self {
        Self::Failure(f)
    }
}

// constructed from runner::cli_session_opener()
/// Sends shell, command, or other requests to a newly opened session channel
pub struct CliSessionOpener<'g, 'a> {
    pub(crate) ch: &'g Channel,
    pub(crate) s: TrafSend<'g, 'a>,
}

impl<'g, 'a> CliSessionOpener<'g, 'a> {
    /// Returns the channel associated with this session.
    ///
    /// This will match that previously returned from [`Runner::cli_session_opener`]
    /// or `SSHClient::open_session_pty()` (or `_nopty()`)
    pub fn channel(&self) -> ChanNum {
        self.ch.num()
    }

    /// Requests a Pseudo-TTY for the channel.
    ///
    /// This must be sent prior to requesting a shell or command.
    /// Shells using a PTY will only receive data on the stdin FD, not stderr.
    // TODO: set a flag in the channel so that it drops data on stderr, to
    // avoid waiting forever for a consumer?
    pub fn pty(&mut self, pty: channel::Pty) -> Result<()> {
        self.send(Req::Pty(pty))
    }

    /// Requests a particular command or shell for a channel
    pub fn cmd<S: AsRef<str>>(&mut self, cmd: &SessionCommand<S>) -> Result<()> {
        self.send(cmd.into())
    }

    pub fn shell(&mut self) -> Result<()> {
        self.send(Req::Shell)
    }

    pub fn exec(&mut self, cmd: impl AsRef<str>) -> Result<()> {
        self.send(Req::Exec(cmd.as_ref()))
    }

    pub fn subsystem(&mut self, cmd: impl AsRef<str>) -> Result<()> {
        self.send(Req::Subsystem(cmd.as_ref()))
    }

    fn send(&mut self, req: Req) -> Result<()> {
        req.send(self.ch, &mut self.s)
    }
}

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

#[derive(Debug)]
pub enum CliSessionExit<'g> {
    /// Remote process exited with an exit status code
    Status(u32),
    /// Remote process exited by signal
    Signal(ExitSignal<'g>),
}

impl<'g> CliSessionExit<'g> {
    pub fn new(p: &Packet<'g>) -> Result<Self> {
        match p {
            Packet::ChannelRequest(ChannelRequest {
                req: ChannelReqType::ExitStatus(e),
                ..
            }) => Ok(Self::Status(e.status)),
            Packet::ChannelRequest(ChannelRequest {
                req: ChannelReqType::ExitSignal(e),
                ..
            }) => Ok(Self::Signal(e.clone())),
            _ => Err(Error::bug()),
        }
    }
}