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
use core::str::Utf8Error;
#[allow(unused_imports)]
use log::{debug, error, info, log, trace, warn};
use core::fmt::Arguments;
use snafu::prelude::*;
use crate::channel::ChanNum;
#[allow(unused_imports)]
use snafu::{Backtrace, Location};
// TODO: can we make Snafu not require Debug?
/// The Sunset error type.
#[non_exhaustive]
#[derive(Snafu, Debug)]
#[snafu(context(suffix(false)))]
// TODO: maybe split this into a list of public vs private errors?
#[snafu(visibility(pub))]
pub enum Error {
/// Output buffer ran out of room
NoRoom {
#[cfg(feature = "backtrace")]
backtrace: Backtrace,
},
/// Input buffer ran out
RanOut {
#[cfg(feature = "backtrace")]
backtrace: Backtrace,
},
/// Not a UTF-8 string
BadString,
/// Not a valid SSH ASCII string
BadName,
/// Key exchange incorrect
BadKex,
/// Packet integrity failed
BadDecrypt,
/// Signature is incorrect
BadSig,
/// Integer overflow in packet
BadNumber,
/// Error in received SSH protocol. Will disconnect.
SSHProto {
#[cfg(feature = "backtrace")]
backtrace: Backtrace,
},
/// Peer sent something we don't handle. Will disconnect.
///
/// This differs to `SSHProtoError`. In this case the peer may be
/// behaved within the SSH specifications, but Sunset doesn't
/// support it.
// TODO: 'static disconnect message to return?
SSHProtoUnsupported,
/// Received a key with invalid structure, or too large.
BadKeyFormat,
/// Remote peer isn't SSH 2.0
NotSSH,
/// Bad key format
BadKey,
/// Ran out of channels
NoChannels,
#[snafu(display("Bad channel number {num}"))]
BadChannel { num: ChanNum },
/// Bad channel data type
///
/// Returned from an API call that would imply ChanData::Stderr
/// being sent to a server. This error will not be returned for
/// network data in the incorrect direction, instead that data is dropped.
BadChannelData,
/// Bad application usage
///
/// Returned from an API call when the API is used incorrectly.
/// Examples could include:
/// - A `ChanHandle` is used incorrectly, for example being cloned
/// (millions of times) and not released.
// TODO: /// #[snafu(display("Failure from application: {msg}"))]
BadUsage {
#[cfg(feature = "backtrace")]
backtrace: snafu::Backtrace,
// TODO
// msg: &'static str,
},
/// SSH packet contents doesn't match length
WrongPacketLength,
/// Channel EOF
///
/// This is an expected error when a SSH channel completes. Can be returned
/// by channel read/write functions. Any further calls in the same direction
/// will fail similarly.
ChannelEOF,
/// Session EOF
///
/// This is an expected error when the SSH session has finished.
SessionEOF,
// Used for unknown key types etc.
#[snafu(display("{what} is not available"))]
NotAvailable { what: &'static str },
#[snafu(display("Unknown packet type {number}"))]
UnknownPacket { number: u8 },
/// Received packet at a disallowed time.
// TODO: this is kind of a subset of SSHProtoError, maybe not needed
PacketWrong {
#[cfg(feature = "backtrace")]
backtrace: Backtrace,
},
// #[snafu(display("Program bug {location}"))]
// Bug { location: snafu::Location },
#[snafu(display("No matching {algo} algorithm"))]
AlgoNoMatch { algo: &'static str },
#[snafu(display("Packet size {size} too large (or bad decrypt)"))]
BigPacket { size: usize },
/// Ran out of authentication methods to try (as a client)
NoAuthMethods,
/// An unknown SSH name is provided, for a key type, signature type,
/// channel name etc.
#[snafu(display("Unknown {kind} method"))]
UnknownMethod { kind: &'static str },
#[snafu(display("{msg}"))]
// TODO: these could eventually get categorised
Custom { msg: &'static str },
/// IO Error
#[cfg(feature = "std")]
IoError { source: std::io::Error },
// This state should not be reached, previous logic should have prevented it.
// Create this using [`Error::bug()`] or [`.trap()`](TrapBug::trap).
// Location is currently disabled due to bloat.
// #[snafu(display("Program bug {location}"))]
// Bug { location: snafu::Location },
/// Program bug
Bug,
}
impl Error {
pub fn msg(m: &'static str) -> Error {
Error::Custom { msg: m }
}
#[cold]
#[track_caller]
/// Panics in debug builds, returns [`Error::Bug`] in release.
// TODO: this should return a Result since it's always used as Err(Error::bug())
pub fn bug() -> Error {
// Easier to track the source of errors in development,
// but release builds shouldn't panic.
if cfg!(debug_assertions) {
panic!("Hit a bug");
} else {
// let caller = core::panic::Location::caller();
Error::Bug
// {
// location: snafu::Location::new(
// caller.file(),
// caller.line(),
// caller.column(),
// ),
// }
}
}
/// Like [`bug()`](Error::bug) but with a message
///
/// The message can be used instead of a code comment, is logged at `trace` level.
#[cold]
pub fn bug_fmt(args: Arguments) -> Error {
// Easier to track the source of errors in development,
// but release builds shouldn't panic.
if cfg!(debug_assertions) {
panic!("Hit a bug: {args}");
} else {
trace!("Hit a bug: {args}");
// TODO: this bloats binaries with full paths
// https://github.com/rust-lang/rust/issues/95529 is having function
// let caller = core::panic::Location::caller();
Error::Bug
// {
// location: snafu::Location::new(
// caller.file(),
// caller.line(),
// caller.column(),
// ),
// }
}
}
#[cold]
/// TODO: is the generic `T` going to make it bloat?
pub fn bug_msg<T>(msg: &str) -> Result<T, Error> {
Err(Self::bug_fmt(format_args!("{}", msg)))
}
#[cold]
pub fn bug_err_msg(msg: &str) -> Error {
Self::bug_fmt(format_args!("{}", msg))
}
}
#[cfg(feature = "embedded-io")]
impl embedded_io::Error for Error {
fn kind(&self) -> embedded_io::ErrorKind {
embedded_io::ErrorKind::Other
}
}
/// A Sunset-specific Result type.
pub type Result<T, E = Error> = core::result::Result<T, E>;
pub trait TrapBug<T> {
/// `.trap()` should be used like `.unwrap()`, in situations
/// never expected to fail. Instead it calls [`Error::bug()`].
/// (or debug builds may panic)
fn trap(self) -> Result<T, Error>;
/// Like `trap()` but with a message, calls [`Error::bug_msg()`]
/// The message can be used instead of a comment.
fn trap_msg(self, args: Arguments) -> Result<T, Error>;
}
impl<T, E> TrapBug<T> for Result<T, E> {
fn trap(self) -> Result<T, Error> {
// call directly so that Location::caller() works
if let Ok(i) = self {
Ok(i)
} else {
Err(Error::bug())
}
}
fn trap_msg(self, args: Arguments) -> Result<T, Error> {
// call directly so that Location::caller() works
if let Ok(i) = self {
Ok(i)
} else {
Err(Error::bug_fmt(args))
}
}
}
impl<T> TrapBug<T> for Option<T> {
#[track_caller]
fn trap(self) -> Result<T, Error> {
// call directly so that Location::caller() works
if let Some(i) = self {
Ok(i)
} else {
Err(Error::bug())
}
}
fn trap_msg(self, args: Arguments) -> Result<T, Error> {
// call directly so that Location::caller() works
if let Some(i) = self {
Ok(i)
} else {
Err(Error::bug_fmt(args))
}
}
}
impl From<Utf8Error> for Error {
fn from(_e: Utf8Error) -> Error {
Error::BadString
}
}
#[cfg(feature = "std")]
impl From<std::io::Error> for Error {
fn from(value: std::io::Error) -> Self {
Self::IoError { source: value }
}
}
#[cfg(test)]
pub(crate) mod tests {}