1use safelog::Sensitive;
3use std::{sync::Arc, time::Duration};
4use thiserror::Error;
5use tor_cell::relaycell::{StreamId, msg::EndReason};
6use tor_error::{Bug, ErrorKind, HasKind};
7use tor_linkspec::RelayIdType;
8
9use crate::HopNum;
10use crate::client::circuit::PathEntry;
11
12#[derive(Error, Debug, Clone)]
18#[non_exhaustive]
19pub enum Error {
20 #[error("Unable to parse {object}")]
23 BytesErr {
24 object: &'static str,
26 #[source]
28 err: tor_bytes::Error,
29 },
30 #[error("IO error on channel with peer")]
33 ChanIoErr(#[source] Arc<std::io::Error>),
34 #[error("IO error while handshaking with peer")]
36 HandshakeIoErr(#[source] Arc<std::io::Error>),
37 #[error("Unable to generate or encode {object}")]
39 CellEncodeErr {
40 object: &'static str,
42 #[source]
44 err: tor_cell::Error,
45 },
46 #[error("Error while parsing {object}")]
48 CellDecodeErr {
49 object: &'static str,
51 #[source]
53 err: tor_cell::Error,
54 },
55 #[error("Problem while encoding {object}")]
61 EncodeErr {
62 object: &'static str,
64 #[source]
66 err: tor_bytes::EncodeError,
67 },
68 #[error("Error while parsing {object}")]
70 #[cfg(feature = "relay")]
71 LinkspecDecodeErr {
72 object: &'static str,
74 #[source]
76 err: tor_linkspec::decode::ChanTargetDecodeError,
77 },
78 #[error("Problem with certificate on handshake")]
81 HandshakeCertErr(#[source] tor_cert::CertError),
82 #[error("Tried to extract too many bytes from a KDF")]
84 InvalidKDFOutputLength,
85 #[error("Tried to encrypt a cell for a nonexistent hop")]
87 NoSuchHop,
88 #[error("Bad relay cell authentication")]
91 BadCellAuth,
92 #[error("Circuit-extension handshake authentication failed")]
95 BadCircHandshakeAuth,
96 #[error("Handshake protocol violation: {0}")]
98 HandshakeProto(String),
99 #[error("Handshake failed due to expired certificates (possible clock skew)")]
104 HandshakeCertsExpired {
105 expired_by: Duration,
107 },
108 #[error("Channel protocol violation: {0}")]
111 ChanProto(String),
112 #[error("Circuit protocol violation: {0}")]
114 CircProto(String),
115 #[error("Channel closed")]
118 ChannelClosed(#[from] ChannelClosed),
119 #[error("Circuit closed")]
122 CircuitClosed,
123 #[error("Too many entries in map: can't allocate ID")]
125 IdRangeFull,
126 #[error("Stream ID {0} is already in use")]
128 IdUnavailable(StreamId),
129 #[error("Received a cell with a stream ID of zero")]
131 StreamIdZero,
132 #[error(
134 "Received a cell from {} on a closed or non-existent stream {}. \
135 Either they are violating the protocol, or we are expiring streams too aggressively",
136 src,
137 streamid
138 )]
139 UnknownStream {
140 src: Sensitive<PathEntry>,
142 streamid: StreamId,
144 },
145 #[error("Circuit extension refused: {0}")]
148 CircRefused(&'static str),
149 #[error("Invalid stream target address")]
151 BadStreamAddress,
152 #[error("Received an END cell with reason {0}")]
154 EndReceived(EndReason),
155 #[error("Stream not connected")]
157 NotConnected,
158 #[error("Stream protocol violation: {0}")]
160 StreamProto(String),
161
162 #[error("Received too many inbound cells")]
164 ExcessInboundCells,
165 #[error("Tried to send too many outbound cells")]
167 ExcessOutboundCells,
168
169 #[error("Received unexpected or excessive circuit padding from {}", _1.display())]
171 ExcessPadding(#[source] ExcessPadding, HopNum),
172
173 #[error("Peer identity mismatch: {0}")]
175 ChanMismatch(String),
176 #[error("Programming error")]
178 Bug(#[from] tor_error::Bug),
179 #[error("Remote resolve failed")]
181 ResolveError(#[source] ResolveError),
182 #[error("Relay has no {0} identity")]
185 MissingId(RelayIdType),
186 #[error("memory quota error")]
188 Memquota(#[from] tor_memquota::Error),
189}
190
191#[derive(Error, Debug, Clone)]
193#[error("Channel closed")]
194pub struct ChannelClosed;
195
196impl HasKind for ChannelClosed {
197 fn kind(&self) -> ErrorKind {
198 ErrorKind::CircuitCollapse
199 }
200}
201
202#[derive(Error, Debug, Clone)]
204#[non_exhaustive]
205pub enum ResolveError {
206 #[error("Received retriable transient error")]
208 Transient,
209 #[error("Received non-retriable error")]
211 Nontransient,
212 #[error("Received unrecognized result")]
214 Unrecognized,
215}
216
217impl Error {
218 pub(crate) fn from_cell_enc(err: tor_cell::Error, object: &'static str) -> Error {
221 Error::CellEncodeErr { object, err }
222 }
223
224 pub(crate) fn from_bytes_err(err: tor_bytes::Error, object: &'static str) -> Error {
227 Error::BytesErr { err, object }
228 }
229
230 pub(crate) fn from_bytes_enc(err: tor_bytes::EncodeError, object: &'static str) -> Error {
233 Error::EncodeErr { err, object }
234 }
235}
236
237impl From<std::io::Error> for Error {
238 fn from(err: std::io::Error) -> Self {
239 Self::ChanIoErr(Arc::new(err))
240 }
241}
242
243impl From<Error> for std::io::Error {
244 fn from(err: Error) -> std::io::Error {
245 use Error::*;
246 use std::io::ErrorKind;
247 let kind = match err {
248 ChanIoErr(e) | HandshakeIoErr(e) => match Arc::try_unwrap(e) {
249 Ok(e) => return e,
250 Err(arc) => return std::io::Error::new(arc.kind(), arc),
251 },
252
253 InvalidKDFOutputLength | NoSuchHop | BadStreamAddress => ErrorKind::InvalidInput,
254
255 NotConnected => ErrorKind::NotConnected,
256
257 EndReceived(end_reason) => end_reason.into(),
258
259 CircuitClosed => ErrorKind::ConnectionReset,
260
261 Memquota { .. } => ErrorKind::OutOfMemory,
262
263 BytesErr { .. }
264 | BadCellAuth
265 | BadCircHandshakeAuth
266 | HandshakeProto(_)
267 | HandshakeCertErr(_)
268 | ChanProto(_)
269 | HandshakeCertsExpired { .. }
270 | ChannelClosed(_)
271 | CircProto(_)
272 | CellDecodeErr { .. }
273 | CellEncodeErr { .. }
274 | EncodeErr { .. }
275 | ChanMismatch(_)
276 | StreamProto(_)
277 | MissingId(_)
278 | IdUnavailable(_)
279 | StreamIdZero
280 | UnknownStream { .. }
281 | ExcessInboundCells
282 | ExcessOutboundCells
283 | ExcessPadding(_, _) => ErrorKind::InvalidData,
284
285 #[cfg(feature = "relay")]
286 LinkspecDecodeErr { .. } => ErrorKind::InvalidData,
287
288 Bug(ref e) if e.kind() == tor_error::ErrorKind::BadApiUsage => ErrorKind::InvalidData,
289
290 IdRangeFull | CircRefused(_) | ResolveError(_) | Bug(_) => ErrorKind::Other,
291 };
292 std::io::Error::new(kind, err)
293 }
294}
295
296impl HasKind for Error {
297 fn kind(&self) -> ErrorKind {
298 use Error as E;
299 use ErrorKind as EK;
300 use tor_bytes::Error as BytesError;
301 match self {
302 E::BytesErr {
303 err: BytesError::Bug(e),
304 ..
305 } => e.kind(),
306 E::BytesErr { .. } => EK::TorProtocolViolation,
307 E::ChanIoErr(_) => EK::LocalNetworkError,
308 E::HandshakeIoErr(_) => EK::TorAccessFailed,
309 E::HandshakeCertErr(_) => EK::TorProtocolViolation,
310 E::CellEncodeErr { err, .. } => err.kind(),
311 E::CellDecodeErr { err, .. } => err.kind(),
312 #[cfg(feature = "relay")]
313 E::LinkspecDecodeErr { .. } => EK::TorProtocolViolation,
314 E::EncodeErr { .. } => EK::BadApiUsage,
315 E::InvalidKDFOutputLength => EK::Internal,
316 E::NoSuchHop => EK::BadApiUsage,
317 E::BadCellAuth => EK::TorProtocolViolation,
318 E::BadCircHandshakeAuth => EK::TorProtocolViolation,
319 E::HandshakeProto(_) => EK::TorAccessFailed,
320 E::HandshakeCertsExpired { .. } => EK::ClockSkew,
321 E::ChanProto(_) => EK::TorProtocolViolation,
322 E::CircProto(_) => EK::TorProtocolViolation,
323 E::ChannelClosed(e) => e.kind(),
324 E::CircuitClosed => EK::CircuitCollapse,
325 E::IdRangeFull => EK::BadApiUsage,
326 E::CircRefused(_) => EK::CircuitRefused,
327 E::BadStreamAddress => EK::BadApiUsage,
328 E::EndReceived(reason) => reason.kind(),
329 E::NotConnected => EK::BadApiUsage,
330 E::StreamProto(_) => EK::TorProtocolViolation,
331 E::ChanMismatch(_) => EK::RelayIdMismatch,
332 E::ResolveError(ResolveError::Nontransient) => EK::RemoteHostNotFound,
333 E::ResolveError(ResolveError::Transient) => EK::RemoteHostResolutionFailed,
334 E::ResolveError(ResolveError::Unrecognized) => EK::RemoteHostResolutionFailed,
335 E::MissingId(_) => EK::BadApiUsage,
336 E::IdUnavailable(_) => EK::BadApiUsage,
337 E::StreamIdZero => EK::BadApiUsage,
338 E::UnknownStream { .. } => EK::TorProtocolViolation,
339 E::ExcessInboundCells => EK::TorProtocolViolation,
340 E::ExcessOutboundCells => EK::Internal,
341 E::ExcessPadding(_, _) => EK::TorProtocolViolation,
342 E::Memquota(err) => err.kind(),
343 E::Bug(e) => e.kind(),
344 }
345 }
346}
347
348#[derive(Debug)]
351pub(crate) enum ReactorError {
352 Err(Error),
354 Shutdown,
356}
357
358impl From<Error> for ReactorError {
359 fn from(e: Error) -> ReactorError {
360 ReactorError::Err(e)
361 }
362}
363
364impl From<ChannelClosed> for ReactorError {
365 fn from(e: ChannelClosed) -> ReactorError {
366 ReactorError::Err(e.into())
367 }
368}
369
370impl From<Bug> for ReactorError {
371 fn from(e: Bug) -> ReactorError {
372 ReactorError::Err(e.into())
373 }
374}
375
376#[cfg(test)]
377impl ReactorError {
378 pub(crate) fn unwrap_err(self) -> Error {
380 match self {
381 ReactorError::Shutdown => panic!(),
382 ReactorError::Err(e) => e,
383 }
384 }
385}
386
387#[derive(Debug)]
389#[cfg(feature = "conflux")]
390#[allow(unused)] pub(crate) enum ConfluxHandshakeError {
392 Timeout,
394 Link(Error),
396 ChannelClosed,
398}
399
400#[derive(Debug, Clone, Error)]
402#[non_exhaustive]
403pub enum ExcessPadding {
404 #[error("Padding received when not negotiated with given hop")]
406 NoPaddingNegotiated,
407 #[error("Received padding in excess of negotiated framework's limit")]
409 PaddingExceedsLimit,
410}