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