Skip to main content

tor_dirclient/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3// @@ begin lint list maintained by maint/add_warning @@
4#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6#![warn(missing_docs)]
7#![warn(noop_method_call)]
8#![warn(unreachable_pub)]
9#![warn(clippy::all)]
10#![deny(clippy::await_holding_lock)]
11#![deny(clippy::cargo_common_metadata)]
12#![deny(clippy::cast_lossless)]
13#![deny(clippy::checked_conversions)]
14#![allow(clippy::cognitive_complexity)] // See arti#2556
15#![deny(clippy::debug_assert_with_mut_call)]
16#![deny(clippy::exhaustive_enums)]
17#![deny(clippy::exhaustive_structs)]
18#![deny(clippy::expl_impl_clone_on_copy)]
19#![deny(clippy::fallible_impl_from)]
20#![deny(clippy::implicit_clone)]
21#![deny(clippy::large_stack_arrays)]
22#![warn(clippy::manual_ok_or)]
23#![deny(clippy::missing_docs_in_private_items)]
24#![warn(clippy::needless_borrow)]
25#![warn(clippy::needless_pass_by_value)]
26#![warn(clippy::option_option)]
27#![deny(clippy::print_stderr)]
28#![deny(clippy::print_stdout)]
29#![warn(clippy::rc_buffer)]
30#![deny(clippy::ref_option_ref)]
31#![warn(clippy::semicolon_if_nothing_returned)]
32#![warn(clippy::trait_duplication_in_bounds)]
33#![deny(clippy::unchecked_time_subtraction)]
34#![deny(clippy::unnecessary_wraps)]
35#![warn(clippy::unseparated_literal_suffix)]
36#![deny(clippy::unwrap_used)]
37#![deny(clippy::mod_module_files)]
38#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39#![allow(clippy::uninlined_format_args)]
40#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43#![allow(clippy::needless_lifetimes)] // See arti#1765
44#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45#![allow(clippy::collapsible_if)] // See arti#2342
46#![deny(clippy::unused_async)]
47#![deny(clippy::string_slice)] // See arti#2571
48//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
49
50// TODO probably remove this at some point - see tpo/core/arti#1060
51#![cfg_attr(
52    not(all(feature = "full", feature = "experimental")),
53    allow(unused_imports)
54)]
55
56mod body;
57mod err;
58pub mod request;
59mod response;
60mod util;
61
62use tor_circmgr::{CircMgr, DirInfo};
63use tor_error::bad_api_usage;
64use tor_rtcompat::{Runtime, SleepProvider, SleepProviderExt};
65
66// Zlib is required; the others are optional.
67#[cfg(feature = "xz")]
68use async_compression::futures::bufread::XzDecoder;
69use async_compression::futures::bufread::ZlibDecoder;
70#[cfg(feature = "zstd")]
71use async_compression::futures::bufread::ZstdDecoder;
72
73use futures::FutureExt;
74use futures::io::{
75    AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader,
76};
77use std::sync::Arc;
78use std::time::Duration;
79use tracing::{info, instrument};
80
81pub use err::{Error, RequestError, RequestFailedError};
82pub use response::{DirResponse, SourceInfo};
83
84/// Type for results returned in this crate.
85pub type Result<T> = std::result::Result<T, Error>;
86
87/// Type for internal results  containing a RequestError.
88pub type RequestResult<T> = std::result::Result<T, RequestError>;
89
90/// Flag to declare whether a request is always anonymized or not.
91///
92/// This is used by tor-dirclient to control whether *other* deanonymizing metadata
93/// might be added to the request (eg in request headers):
94/// Some requests (like those to download onion service descriptors) are always
95/// anonymized, and should never be sent in a way that leaks information about
96/// our settings or configuration.
97///
98/// It is up to the *caller* of `tor-dirclient` to ensure that
99///
100///   - every request whose anonymization status is `AnonymizedRequest::Direct`
101///     is sent only over non-anonymous connections.
102///
103///     (Sending an `AnonymizedRequest::Direct` request over an anonymized connection
104///     would weaken the connection's anonymity, and can therefore weaken the anonymity
105///     of user traffic sharing the same circuit.)
106///
107///   - every request whose anonymization status is `AnonymizedRequest::Anonymized`
108///     is sent over only anonymous connections (ie, multi-hop circuits).
109///
110///     (Sending an `AnonymizedRequest::Anonymized` request over a direct connection
111///     would directly reveal user behaviour data to the directory server.)
112///
113/// TODO the calling code cannot easily be sure to get this right this because
114/// the anonymization status is a run-time property and the choice of connection kind
115/// is statically defined in the calling code.  (Perhaps this could be checked in tests?)
116#[derive(Copy, Clone, Debug, Eq, PartialEq)]
117#[non_exhaustive]
118pub enum AnonymizedRequest {
119    /// This request's content or semantics reveals or is correlated with sensitive information.
120    ///
121    /// For example, requests for hidden service descriptors reveal which hidden services
122    /// the client is connecting to.
123    ///
124    /// The request must be sent over an anonymous circuit by the caller
125    /// and no additional deanonymizing information should be added to it by `tor-dirclient`.
126    /// (For example, no client-version-specific information should be
127    /// sent in HTTP headers when the request is made.)
128    Anonymized,
129
130    /// Making this request does not reveal anything sensitive, nor any user behaviour.
131    ///
132    /// The request body is uncorrelated with such things as the websites the user might visit,
133    /// the onion services the user is visiting or running, etc.
134    ///
135    /// For example, requests for all router microdescriptors are made by all clients,
136    /// so which microdescriptor(s) are requested reveals nothing to any attacker.
137    ///
138    /// tor-dirclient is allowed to add include information about our capabilities
139    /// when sending this request.
140    /// The request must *not* be sent over an anonymous circuit by the caller
141    /// (at least, not one used for anything else).
142    Direct,
143}
144
145/// Fetch the resource described by `req` over the Tor network.
146///
147/// Circuits are built or found using `circ_mgr`, using paths
148/// constructed using `dirinfo`.
149///
150/// For more fine-grained control over the circuit and stream used,
151/// construct them yourself, and then call [`send_request`] instead.
152///
153/// # TODO
154///
155/// This is the only function in this crate that knows about CircMgr and
156/// DirInfo.  Perhaps this function should move up a level into DirMgr?
157#[instrument(level = "trace", skip_all)]
158pub async fn get_resource<CR, R, SP>(
159    req: &CR,
160    dirinfo: DirInfo<'_>,
161    runtime: &SP,
162    circ_mgr: Arc<CircMgr<R>>,
163) -> Result<DirResponse>
164where
165    CR: request::Requestable + ?Sized,
166    R: Runtime,
167    SP: SleepProvider,
168{
169    let tunnel = circ_mgr.get_or_launch_dir(dirinfo).await?;
170
171    if req.anonymized() == AnonymizedRequest::Anonymized {
172        return Err(bad_api_usage!("Tried to use get_resource for an anonymized request").into());
173    }
174
175    // TODO(nickm) This should be an option, and is too long.
176    let begin_timeout = Duration::from_secs(5);
177    let source = match SourceInfo::from_tunnel(&tunnel) {
178        Ok(source) => source,
179        Err(e) => {
180            return Err(Error::RequestFailed(RequestFailedError {
181                source: None,
182                error: e.into(),
183            }));
184        }
185    };
186
187    let wrap_err = |error| {
188        Error::RequestFailed(RequestFailedError {
189            source: source.clone(),
190            error,
191        })
192    };
193
194    req.check_circuit(&tunnel).await.map_err(wrap_err)?;
195
196    // Launch the stream.
197    let mut stream = runtime
198        .timeout(begin_timeout, tunnel.begin_dir_stream())
199        .await
200        .map_err(RequestError::from)
201        .map_err(wrap_err)?
202        .map_err(RequestError::from)
203        .map_err(wrap_err)?; // TODO(nickm) handle fatalities here too
204
205    // TODO: Perhaps we want separate timeouts for each phase of this.
206    // For now, we just use higher-level timeouts in `dirmgr`.
207    let r = send_request(runtime, req, &mut stream, source.clone()).await;
208
209    if should_retire_circ(&r) {
210        retire_circ(&circ_mgr, &tunnel.unique_id(), "Partial response");
211    }
212
213    r
214}
215
216/// Return true if `result` holds an error indicating that we should retire the
217/// circuit used for the corresponding request.
218fn should_retire_circ(result: &Result<DirResponse>) -> bool {
219    match result {
220        Err(e) => e.should_retire_circ(),
221        Ok(dr) => dr.error().map(RequestError::should_retire_circ) == Some(true),
222    }
223}
224
225/// Fetch a Tor directory object from a provided stream.
226#[deprecated(since = "0.8.1", note = "Use send_request instead.")]
227pub async fn download<R, S, SP>(
228    runtime: &SP,
229    req: &R,
230    stream: &mut S,
231    source: Option<SourceInfo>,
232) -> Result<DirResponse>
233where
234    R: request::Requestable + ?Sized,
235    S: AsyncRead + AsyncWrite + Send + Unpin,
236    SP: SleepProvider,
237{
238    send_request(runtime, req, stream, source).await
239}
240
241/// Fetch or upload a Tor directory object using the provided stream.
242///
243/// To do this, we send a simple HTTP/1.0 request for the described
244/// object in `req` over `stream`, and then wait for a response.  In
245/// log messages, we describe the origin of the data as coming from
246/// `source`.
247///
248/// # Notes
249///
250/// It's kind of bogus to have a 'source' field here at all; we may
251/// eventually want to remove it.
252///
253/// This function doesn't close the stream; you may want to do that
254/// yourself.
255///
256/// The only error variant returned is [`Error::RequestFailed`].
257// TODO: should the error return type change to `RequestFailedError`?
258// If so, that would simplify some code in_dirmgr::bridgedesc.
259pub async fn send_request<R, S, SP>(
260    runtime: &SP,
261    req: &R,
262    stream: &mut S,
263    source: Option<SourceInfo>,
264) -> Result<DirResponse>
265where
266    R: request::Requestable + ?Sized,
267    S: AsyncRead + AsyncWrite + Send + Unpin,
268    SP: SleepProvider,
269{
270    let wrap_err = |error| {
271        Error::RequestFailed(RequestFailedError {
272            source: source.clone(),
273            error,
274        })
275    };
276
277    let partial_ok = req.partial_response_body_ok();
278    let maxlen = req.max_response_len();
279    let anonymized = req.anonymized();
280    let req = req.make_request().map_err(wrap_err)?;
281    let method = req.method().clone();
282    let encoded = util::encode_request(&req);
283
284    // Write the request.
285    for chunk in encoded.iter() {
286        stream
287            .write_all(chunk)
288            .await
289            .map_err(RequestError::from)
290            .map_err(wrap_err)?;
291    }
292    stream
293        .flush()
294        .await
295        .map_err(RequestError::from)
296        .map_err(wrap_err)?;
297
298    let mut buffered = BufReader::new(stream);
299
300    // Handle the response
301    let header = read_headers(runtime, &mut buffered)
302        .await
303        .map_err(wrap_err)?;
304    if header.status != Some(200) {
305        return Ok(DirResponse::new(
306            method,
307            header.status.unwrap_or(0),
308            header.status_message,
309            None,
310            vec![],
311            source,
312        ));
313    }
314
315    let mut decoder =
316        get_decoder(buffered, header.encoding.as_deref(), anonymized).map_err(wrap_err)?;
317
318    let mut result = Vec::new();
319    let ok = read_and_decompress(runtime, &mut decoder, maxlen, &mut result).await;
320
321    let ok = match (partial_ok, ok, result.len()) {
322        (true, Err(e), n) if n > 0 => {
323            // Note that we _don't_ return here: we want the partial response.
324            Err(e)
325        }
326        (_, Err(e), _) => {
327            return Err(wrap_err(e));
328        }
329        (_, Ok(()), _) => Ok(()),
330    };
331
332    Ok(DirResponse::new(
333        method,
334        200,
335        None,
336        ok.err(),
337        result,
338        source,
339    ))
340}
341
342/// Maximum length for the HTTP headers in a single request or response.
343///
344/// Chosen more or less arbitrarily.
345const MAX_HEADERS_LEN: usize = 16384;
346
347/// Read and parse HTTP/1 headers from `stream`.
348///
349/// Wraps around [`read_headers_internal()`] with a timeout.
350async fn read_headers<S, SP>(runtime: &SP, stream: &mut S) -> RequestResult<HeaderStatus>
351where
352    S: AsyncBufRead + Unpin,
353    SP: SleepProvider,
354{
355    // Just like with the other timeouts in this code, this should probably be
356    // configurable and may even be too much.
357    let read_timeout = Duration::from_secs(10);
358    runtime
359        .timeout(read_timeout, read_headers_internal(stream))
360        .await
361        .map_err(|_| RequestError::DirTimeout)
362        .flatten()
363}
364
365/// Internal version of [`read_headers()`] without a timeout.
366async fn read_headers_internal<S>(stream: &mut S) -> RequestResult<HeaderStatus>
367where
368    S: AsyncBufRead + Unpin,
369{
370    let mut buf = Vec::with_capacity(1024);
371
372    // Note: Using `take` here will ensure that we will get an EOF if the header length
373    // would exceed the maximum.  No extra bytes will actually be extracted.
374    let mut limited_stream = stream.take(MAX_HEADERS_LEN as u64);
375
376    loop {
377        // TODO: it's inefficient to do this a line at a time; it would
378        // probably be better to read until the CRLF CRLF ending of the
379        // response.  But this should be fast enough.
380        let n = limited_stream.read_until(b'\n', &mut buf).await?;
381
382        // TODO(nickm): Better maximum and/or let this expand.
383        let mut headers = [httparse::EMPTY_HEADER; 32];
384        let mut response = httparse::Response::new(&mut headers);
385
386        match response.parse(&buf[..])? {
387            httparse::Status::Partial => {
388                // We didn't get a whole response; we may need to try again.
389
390                if n == 0 {
391                    // We hit an EOF; no more progress can be made.
392                    return Err(RequestError::TruncatedHeaders);
393                }
394
395                if buf.len() >= MAX_HEADERS_LEN {
396                    return Err(RequestError::HeadersTooLong(buf.len()));
397                }
398            }
399            httparse::Status::Complete(n_parsed) => {
400                if response.code != Some(200) {
401                    return Ok(HeaderStatus {
402                        status: response.code,
403                        status_message: response.reason.map(str::to_owned),
404                        encoding: None,
405                    });
406                }
407                let encoding = if let Some(enc) = response
408                    .headers
409                    .iter()
410                    .find(|h| h.name == "Content-Encoding")
411                {
412                    Some(String::from_utf8(enc.value.to_vec())?)
413                } else {
414                    None
415                };
416                /*
417                if let Some(clen) = response.headers.iter().find(|h| h.name == "Content-Length") {
418                    let clen = std::str::from_utf8(clen.value)?;
419                    length = Some(clen.parse()?);
420                }
421                 */
422                assert!(n_parsed == buf.len());
423                return Ok(HeaderStatus {
424                    status: Some(200),
425                    status_message: None,
426                    encoding,
427                });
428            }
429        }
430        if n == 0 {
431            return Err(RequestError::TruncatedHeaders);
432        }
433    }
434}
435
436/// Return value from read_headers
437#[derive(Debug, Clone)]
438struct HeaderStatus {
439    /// HTTP status code.
440    status: Option<u16>,
441    /// HTTP status message associated with the status code.
442    status_message: Option<String>,
443    /// The Content-Encoding header, if any.
444    encoding: Option<String>,
445}
446
447/// Helper: download directory information from `stream` and
448/// decompress it into a result buffer.  Assumes that `buf` is empty.
449///
450/// If we get more than maxlen bytes after decompression, give an error.
451///
452/// Returns the status of our download attempt, stores any data that
453/// we were able to download into `result`.  Existing contents of
454/// `result` are overwritten.
455async fn read_and_decompress<S, SP>(
456    runtime: &SP,
457    mut stream: S,
458    maxlen: usize,
459    result: &mut Vec<u8>,
460) -> RequestResult<()>
461where
462    S: AsyncRead + Unpin,
463    SP: SleepProvider,
464{
465    let buffer_window_size = 1024;
466    let mut written_total: usize = 0;
467    // TODO(nickm): This should be an option, and is maybe too long.
468    // Though for some users it may be too short?
469    let read_timeout = Duration::from_secs(10);
470    let timer = runtime.sleep(read_timeout).fuse();
471    futures::pin_mut!(timer);
472
473    loop {
474        // allocate buffer for next read
475        result.resize(written_total + buffer_window_size, 0);
476        let buf: &mut [u8] = &mut result[written_total..written_total + buffer_window_size];
477
478        let status = futures::select! {
479            status = stream.read(buf).fuse() => status,
480            _ = timer => {
481                result.resize(written_total, 0); // truncate as needed
482                return Err(RequestError::DirTimeout);
483            }
484        };
485        let written_in_this_loop = match status {
486            Ok(n) => n,
487            Err(other) => {
488                result.resize(written_total, 0); // truncate as needed
489                return Err(other.into());
490            }
491        };
492
493        written_total += written_in_this_loop;
494
495        // exit conditions below
496
497        if written_in_this_loop == 0 {
498            /*
499            in case we read less than `buffer_window_size` in last `read`
500            we need to shrink result because otherwise we'll return those
501            un-read 0s
502            */
503            if written_total < result.len() {
504                result.resize(written_total, 0);
505            }
506            return Ok(());
507        }
508
509        // TODO: It would be good to detect compression bombs, but
510        // that would require access to the internal stream, which
511        // would in turn require some tricky programming.  For now, we
512        // use the maximum length here to prevent an attacker from
513        // filling our RAM.
514        if written_total > maxlen {
515            result.resize(maxlen, 0);
516            return Err(RequestError::ResponseTooLong(written_total));
517        }
518    }
519}
520
521/// Retire a directory circuit because of an error we've encountered on it.
522fn retire_circ<R>(circ_mgr: &Arc<CircMgr<R>>, id: &tor_proto::circuit::UniqId, error: &str)
523where
524    R: Runtime,
525{
526    info!(
527        "{}: Retiring circuit because of directory failure: {}",
528        &id, &error
529    );
530    circ_mgr.retire_circ(id);
531}
532
533/// Memory limit of the LZMA dictionary we are willing to allocate.
534///
535/// Without it, it may lead to an allocation of 4GiB, which is a bit overkill.
536///
537/// Right now, we use 16 MiB, as the spec limits the compression quality to
538/// "6", meaning 9 MiB of decompression memory, which rounds up to 16 MiB in
539/// terms of base 2.
540///
541/// From the xz(1) manual page:
542/// ```text
543/// Preset   DictSize   CompCPU   CompMem   DecMem
544///  -0e     256 KiB       8        4 MiB    1 MiB
545///  -1e       1 MiB       8       13 MiB    2 MiB
546///  -2e       2 MiB       8       25 MiB    3 MiB
547///  -3e       4 MiB       7       48 MiB    5 MiB
548///  -4e       4 MiB       8       48 MiB    5 MiB
549///  -5e       8 MiB       7       94 MiB    9 MiB
550///  -6e       8 MiB       8       94 MiB    9 MiB
551///  -7e      16 MiB       8      186 MiB   17 MiB
552///  -8e      32 MiB       8      370 MiB   33 MiB
553///  -9e      64 MiB       8      674 MiB   65 MiB
554/// ```
555const LZMA_DICT_MEM_LIMIT: u64 = 1 << 24; // 16 MiB
556
557/// Helper: Return a boxed decoder object that wraps the stream  $s.
558macro_rules! decoder {
559    (XzDecoder, $s:expr) => {{
560        let mut decoder = XzDecoder::with_mem_limit($s, LZMA_DICT_MEM_LIMIT);
561        decoder.multiple_members(true);
562        Ok(Box::new(decoder))
563    }};
564    ($dec:ident, $s:expr) => {{
565        let mut decoder = $dec::new($s);
566        decoder.multiple_members(true);
567        Ok(Box::new(decoder))
568    }};
569}
570
571/// Wrap `stream` in an appropriate type to undo the content encoding
572/// as described in `encoding`.
573fn get_decoder<'a, S: AsyncBufRead + Unpin + Send + 'a>(
574    stream: S,
575    encoding: Option<&str>,
576    anonymized: AnonymizedRequest,
577) -> RequestResult<Box<dyn AsyncRead + Unpin + Send + 'a>> {
578    use AnonymizedRequest::Direct;
579    match (encoding, anonymized) {
580        (None | Some("identity"), _) => Ok(Box::new(stream)),
581        (Some("deflate"), _) => decoder!(ZlibDecoder, stream),
582        // We only admit to supporting these on a direct connection; otherwise,
583        // a hostile directory could send them back even though we hadn't
584        // requested them.
585        #[cfg(feature = "xz")]
586        (Some("x-tor-lzma"), Direct) => decoder!(XzDecoder, stream),
587        #[cfg(feature = "zstd")]
588        (Some("x-zstd"), Direct) => decoder!(ZstdDecoder, stream),
589        (Some(other), _) => Err(RequestError::ContentEncoding(other.into())),
590    }
591}
592
593#[cfg(test)]
594mod test {
595    // @@ begin test lint list maintained by maint/add_warning @@
596    #![allow(clippy::bool_assert_comparison)]
597    #![allow(clippy::clone_on_copy)]
598    #![allow(clippy::dbg_macro)]
599    #![allow(clippy::mixed_attributes_style)]
600    #![allow(clippy::print_stderr)]
601    #![allow(clippy::print_stdout)]
602    #![allow(clippy::single_char_pattern)]
603    #![allow(clippy::unwrap_used)]
604    #![allow(clippy::unchecked_time_subtraction)]
605    #![allow(clippy::useless_vec)]
606    #![allow(clippy::needless_pass_by_value)]
607    #![allow(clippy::string_slice)] // See arti#2571
608    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
609    use super::*;
610    use tor_rtmock::io::stream_pair;
611
612    use tor_rtmock::simple_time::SimpleMockTimeProvider;
613    use web_time_compat::{SystemTime, SystemTimeExt};
614
615    use futures_await_test::async_test;
616
617    // Basic decompression wrapper.
618    async fn decomp_basic(
619        encoding: Option<&str>,
620        data: &[u8],
621        maxlen: usize,
622    ) -> (RequestResult<()>, Vec<u8>) {
623        // We don't need to do anything fancy here, since we aren't simulating
624        // a timeout.
625        #[allow(deprecated)] // TODO #1885
626        let mock_time = SimpleMockTimeProvider::from_wallclock(SystemTime::get());
627
628        let mut output = Vec::new();
629        let mut stream = match get_decoder(data, encoding, AnonymizedRequest::Direct) {
630            Ok(s) => s,
631            Err(e) => return (Err(e), output),
632        };
633
634        let r = read_and_decompress(&mock_time, &mut stream, maxlen, &mut output).await;
635
636        (r, output)
637    }
638
639    #[async_test]
640    async fn decompress_identity() -> RequestResult<()> {
641        let mut text = Vec::new();
642        for _ in 0..1000 {
643            text.extend(b"This is a string with a nontrivial length that we'll use to make sure that the loop is executed more than once.");
644        }
645
646        let limit = 10 << 20;
647        let (s, r) = decomp_basic(None, &text[..], limit).await;
648        s?;
649        assert_eq!(r, text);
650
651        let (s, r) = decomp_basic(Some("identity"), &text[..], limit).await;
652        s?;
653        assert_eq!(r, text);
654
655        // Try truncated result
656        let limit = 100;
657        let (s, r) = decomp_basic(Some("identity"), &text[..], limit).await;
658        assert!(s.is_err());
659        assert_eq!(r, &text[..100]);
660
661        Ok(())
662    }
663
664    #[async_test]
665    async fn decomp_zlib() -> RequestResult<()> {
666        let compressed =
667            hex::decode("789cf3cf4b5548cb2cce500829cf8730825253200ca79c52881c00e5970c88").unwrap();
668
669        let limit = 10 << 20;
670        let (s, r) = decomp_basic(Some("deflate"), &compressed, limit).await;
671        s?;
672        assert_eq!(r, b"One fish Two fish Red fish Blue fish");
673
674        Ok(())
675    }
676
677    #[cfg(feature = "zstd")]
678    #[async_test]
679    async fn decomp_zstd() -> RequestResult<()> {
680        let compressed = hex::decode("28b52ffd24250d0100c84f6e6520666973682054776f526564426c756520666973680a0200600c0e2509478352cb").unwrap();
681        let limit = 10 << 20;
682        let (s, r) = decomp_basic(Some("x-zstd"), &compressed, limit).await;
683        s?;
684        assert_eq!(r, b"One fish Two fish Red fish Blue fish\n");
685
686        Ok(())
687    }
688
689    #[cfg(feature = "xz")]
690    #[async_test]
691    async fn decomp_xz() -> RequestResult<()> {
692        // echo "One fish Two fish Red fish Blue fish" | xz -6 | xxd -p
693        let compressed = hex::decode("fd377a585a000004e6d6b44604c02525210116000000000000000000bfdbca33e00024001d5d00279b88a202ca8612cfb3c19c87c34248a570451e4851d3323d34ab8000000000000901af64854c91f600014125281fe0821fb6f37d010000000004595a").unwrap();
694        let limit = LZMA_DICT_MEM_LIMIT as usize;
695        let (s, r) = decomp_basic(Some("x-tor-lzma"), &compressed, limit).await;
696        s?;
697        assert_eq!(r, b"One fish Two fish Red fish Blue fish\n");
698
699        Ok(())
700    }
701
702    #[cfg(feature = "xz")]
703    #[async_test]
704    async fn decomp_xz_bad() -> RequestResult<()> {
705        // Not so good at tiny files...
706        let compressed = hex::decode("fd377a585a000004e6d6b446020021011c00000010cf58cce00024001d5d00279b88a202ca8612cfb3c19c87c34248a570451e4851d3323d34ab8000000000000901af64854c91f600013925d6ec06651fb6f37d010000000004595a").unwrap();
707        let limit = 10 << 20;
708        let (s, _) = decomp_basic(Some("x-tor-lzma"), &compressed, limit).await;
709        assert!(matches!(s, Err(RequestError::IoError(_))));
710
711        Ok(())
712    }
713
714    #[async_test]
715    async fn decomp_unknown() {
716        let compressed = hex::decode("28b52ffd24250d0100c84f6e6520666973682054776f526564426c756520666973680a0200600c0e2509478352cb").unwrap();
717        let limit = 10 << 20;
718        let (s, _r) = decomp_basic(Some("x-proprietary-rle"), &compressed, limit).await;
719
720        assert!(matches!(s, Err(RequestError::ContentEncoding(_))));
721    }
722
723    #[async_test]
724    async fn decomp_bad_data() {
725        let compressed = b"This is not good zlib data";
726        let limit = 10 << 20;
727        let (s, _r) = decomp_basic(Some("deflate"), compressed, limit).await;
728
729        // This should possibly be a different type in the future.
730        assert!(matches!(s, Err(RequestError::IoError(_))));
731    }
732
733    #[test]
734    fn headers_ok() -> RequestResult<()> {
735        let text = b"HTTP/1.0 200 OK\r\nDate: ignored\r\nContent-Encoding: Waffles\r\n\r\n";
736
737        let mut s = &text[..];
738        let h = tor_rtcompat::test_with_one_runtime!(async |rt| read_headers(&rt, &mut s).await)?;
739
740        assert_eq!(h.status, Some(200));
741        assert_eq!(h.encoding.as_deref(), Some("Waffles"));
742
743        // now try truncated
744        let mut s = &text[..15];
745        let h = tor_rtcompat::test_with_one_runtime!(async |rt| read_headers(&rt, &mut s).await);
746        assert!(matches!(h, Err(RequestError::TruncatedHeaders)));
747
748        // now try with no encoding.
749        let text = b"HTTP/1.0 404 Not found\r\n\r\n";
750        let mut s = &text[..];
751        let h = tor_rtcompat::test_with_one_runtime!(async |rt| read_headers(&rt, &mut s).await)?;
752
753        assert_eq!(h.status, Some(404));
754        assert!(h.encoding.is_none());
755
756        Ok(())
757    }
758
759    #[test]
760    fn headers_bogus() {
761        let text = b"HTTP/999.0 WHAT EVEN\r\n\r\n";
762        let mut s = &text[..];
763        let h = tor_rtcompat::test_with_one_runtime!(async |rt| read_headers(&rt, &mut s).await);
764
765        assert!(h.is_err());
766        assert!(matches!(h, Err(RequestError::HttparseError(_))));
767    }
768
769    /// Run a trivial download example with a response provided as a binary
770    /// string.
771    ///
772    /// Return the directory response (if any) and the request as encoded (if
773    /// any.)
774    fn run_download_test<Req: request::Requestable>(
775        req: Req,
776        response: &[u8],
777    ) -> (Result<DirResponse>, RequestResult<Vec<u8>>) {
778        let (mut s1, s2) = stream_pair();
779        let (mut s2_r, mut s2_w) = s2.split();
780
781        tor_rtcompat::test_with_one_runtime!(|rt| async move {
782            let rt2 = rt.clone();
783            let (v1, v2, v3): (
784                Result<DirResponse>,
785                RequestResult<Vec<u8>>,
786                RequestResult<()>,
787            ) = futures::join!(
788                async {
789                    // Run the download function.
790                    let r = send_request(&rt, &req, &mut s1, None).await;
791                    s1.close().await.map_err(|error| {
792                        Error::RequestFailed(RequestFailedError {
793                            source: None,
794                            error: error.into(),
795                        })
796                    })?;
797                    r
798                },
799                async {
800                    // Take the request from the client, and return it in "v2"
801                    let mut v = Vec::new();
802                    s2_r.read_to_end(&mut v).await?;
803                    Ok(v)
804                },
805                async {
806                    // Send back a response.
807                    s2_w.write_all(response).await?;
808                    // We wait a moment to give the other side time to notice it
809                    // has data.
810                    //
811                    // (Tentative diagnosis: The `async-compress` crate seems to
812                    // be behave differently depending on whether the "close"
813                    // comes right after the incomplete data or whether it comes
814                    // after a delay.  If there's a delay, it notices the
815                    // truncated data and tells us about it. But when there's
816                    // _no_delay, it treats the data as an error and doesn't
817                    // tell our code.)
818
819                    // TODO: sleeping in tests is not great.
820                    rt2.sleep(Duration::from_millis(50)).await;
821                    s2_w.close().await?;
822                    Ok(())
823                }
824            );
825
826            assert!(v3.is_ok());
827
828            (v1, v2)
829        })
830    }
831
832    #[test]
833    fn test_send_request() -> RequestResult<()> {
834        let req: request::MicrodescRequest = vec![[9; 32]].into_iter().collect();
835
836        let (response, request) = run_download_test(
837            req,
838            b"HTTP/1.0 200 OK\r\n\r\nThis is where the descs would go.",
839        );
840
841        let request = request?;
842        assert!(request[..].starts_with(
843            b"GET /tor/micro/d/CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk HTTP/1.0\r\n"
844        ));
845
846        let response = response.unwrap();
847        assert_eq!(response.status_code(), 200);
848        assert!(!response.is_partial());
849        assert!(response.error().is_none());
850        assert!(response.source().is_none());
851        let out_ref = response.output_unchecked();
852        assert_eq!(out_ref, b"This is where the descs would go.");
853        let out = response.into_output_unchecked();
854        assert_eq!(&out, b"This is where the descs would go.");
855
856        Ok(())
857    }
858
859    #[test]
860    fn test_download_truncated() {
861        // Request only one md, so "partial ok" will not be set.
862        let req: request::MicrodescRequest = vec![[9; 32]].into_iter().collect();
863        let mut response_text: Vec<u8> =
864            (*b"HTTP/1.0 200 OK\r\nContent-Encoding: deflate\r\n\r\n").into();
865        // "One fish two fish" as above twice, but truncated the second time
866        response_text.extend(
867            hex::decode("789cf3cf4b5548cb2cce500829cf8730825253200ca79c52881c00e5970c88").unwrap(),
868        );
869        response_text.extend(
870            hex::decode("789cf3cf4b5548cb2cce500829cf8730825253200ca79c52881c00e5").unwrap(),
871        );
872        let (response, request) = run_download_test(req, &response_text);
873        assert!(request.is_ok());
874        assert!(response.is_err()); // The whole download should fail, since partial_ok wasn't set.
875
876        // request two microdescs, so "partial_ok" will be set.
877        let req: request::MicrodescRequest = vec![[9; 32]; 2].into_iter().collect();
878
879        let (response, request) = run_download_test(req, &response_text);
880        assert!(request.is_ok());
881
882        let response = response.unwrap();
883        assert_eq!(response.status_code(), 200);
884        assert!(response.error().is_some());
885        assert!(response.is_partial());
886        assert!(response.output_unchecked().len() < 37 * 2);
887        assert!(response.output_unchecked().starts_with(b"One fish"));
888    }
889
890    #[test]
891    fn test_404() {
892        let req: request::MicrodescRequest = vec![[9; 32]].into_iter().collect();
893        let response_text = b"HTTP/1.0 418 I'm a teapot\r\n\r\n";
894        let (response, _request) = run_download_test(req, response_text);
895
896        assert_eq!(response.unwrap().status_code(), 418);
897    }
898
899    #[test]
900    fn test_headers_truncated() {
901        let req: request::MicrodescRequest = vec![[9; 32]].into_iter().collect();
902        let response_text = b"HTTP/1.0 404 truncation happens here\r\n";
903        let (response, _request) = run_download_test(req, response_text);
904
905        assert!(matches!(
906            response,
907            Err(Error::RequestFailed(RequestFailedError {
908                error: RequestError::TruncatedHeaders,
909                ..
910            }))
911        ));
912
913        // Try a completely empty response.
914        let req: request::MicrodescRequest = vec![[9; 32]].into_iter().collect();
915        let response_text = b"";
916        let (response, _request) = run_download_test(req, response_text);
917
918        assert!(matches!(
919            response,
920            Err(Error::RequestFailed(RequestFailedError {
921                error: RequestError::TruncatedHeaders,
922                ..
923            }))
924        ));
925    }
926
927    #[test]
928    fn test_headers_too_long() {
929        let req: request::MicrodescRequest = vec![[9; 32]].into_iter().collect();
930        let mut response_text: Vec<u8> = (*b"HTTP/1.0 418 I'm a teapot\r\nX-Too-Many-As: ").into();
931        response_text.resize(16384, b'A');
932        let (response, _request) = run_download_test(req, &response_text);
933
934        assert!(response.as_ref().unwrap_err().should_retire_circ());
935        assert!(matches!(
936            response,
937            Err(Error::RequestFailed(RequestFailedError {
938                error: RequestError::HeadersTooLong(_),
939                ..
940            }))
941        ));
942    }
943
944    #[test]
945    fn test_bad_utf8() {
946        let req: request::MicrodescRequest = vec![[9; 32]].into_iter().collect();
947        let faulty_utf8 = vec![0, 159, 146, 150];
948
949        let mut response_text: Vec<u8> = b"HTTP/1.0 200 OK\r\n\r\n".into();
950        response_text.extend(faulty_utf8);
951
952        let (response, _request) = run_download_test(req, &response_text);
953
954        assert!(matches!(
955            response.unwrap().into_output_string().unwrap_err(),
956            RequestFailedError {
957                error: RequestError::Utf8Encoding(_),
958                ..
959            }
960        ));
961    }
962}