1
//! Descriptions objects for different kinds of directory requests
2
//! that we can make.
3

            
4
use tor_llcrypto::pk::rsa::RsaIdentity;
5
use tor_netdoc::doc::authcert::AuthCertKeyIds;
6
use tor_netdoc::doc::microdesc::MdDigest;
7
use tor_netdoc::doc::netstatus::ConsensusFlavor;
8
#[cfg(feature = "routerdesc")]
9
use tor_netdoc::doc::routerdesc::RdDigest;
10
use tor_proto::circuit::ClientCirc;
11

            
12
#[cfg(feature = "hs-client")]
13
use tor_hscrypto::pk::HsBlindId;
14

            
15
/// Alias for a result with a `RequestError`.
16
type Result<T> = std::result::Result<T, crate::err::RequestError>;
17

            
18
use base64ct::{Base64Unpadded, Encoding as _};
19
use std::borrow::Cow;
20
use std::future::Future;
21
use std::iter::FromIterator;
22
use std::pin::Pin;
23
use std::time::{Duration, SystemTime};
24

            
25
use itertools::Itertools;
26

            
27
use crate::err::RequestError;
28
use crate::AnonymizedRequest;
29

            
30
/// Declare an inaccessible public type.
31
pub(crate) mod sealed {
32
    use super::{AnonymizedRequest, ClientCirc, Result};
33

            
34
    use std::future::Future;
35
    use std::pin::Pin;
36

            
37
    /// Sealed trait to help implement [`Requestable`](super::Requestable): not
38
    /// visible outside this crate, so we can change its methods however we like.
39
    pub trait RequestableInner: Send + Sync {
40
        /// Build an [`http::Request`] from this Requestable, if
41
        /// it is well-formed.
42
        //
43
        // TODO: This API is a bit troublesome in how it takes &self and
44
        // returns a Request<String>.  First, most Requestables don't actually have
45
        // a body to send, and for them having an empty String in their body is a
46
        // bit silly.  Second, taking a reference to self but returning an owned
47
        // String means that we will often have to clone an internal string owned by
48
        // this Requestable instance.
49
        fn make_request(&self) -> Result<http::Request<String>>;
50

            
51
        /// Return true if partial response bodies are potentially useful.
52
        ///
53
        /// This is true for request types where we're going to be downloading
54
        /// multiple documents, and we know how to parse out the ones we wanted
55
        /// if the answer is truncated.
56
        fn partial_response_body_ok(&self) -> bool;
57

            
58
        /// Return the maximum allowable response length we'll accept for this
59
        /// request.
60
2
        fn max_response_len(&self) -> usize {
61
2
            (16 * 1024 * 1024) - 1
62
2
        }
63

            
64
        /// Return an error if there is some problem with the provided circuit that
65
        /// would keep it from being used for this request.
66
        fn check_circuit<'a>(
67
            &self,
68
            circ: &'a ClientCirc,
69
        ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a + Send>> {
70
            let _ = circ;
71
            Box::pin(async { Ok(()) })
72
        }
73

            
74
        /// Return a value to say whether this request must be anonymized.
75
        fn anonymized(&self) -> AnonymizedRequest;
76
    }
77
}
78

            
79
/// A request for an object that can be served over the Tor directory system.
80
pub trait Requestable: sealed::RequestableInner {
81
    /// Return a wrapper around this [`Requestable`] that implements `Debug`,
82
    /// and whose output shows the actual HTTP request that will be generated.
83
    ///
84
    /// The format is not guaranteed to  be stable.
85
2
    fn debug_request(&self) -> DisplayRequestable<'_, Self>
86
2
    where
87
2
        Self: Sized,
88
2
    {
89
2
        DisplayRequestable(self)
90
2
    }
91
}
92
impl<T: sealed::RequestableInner> Requestable for T {}
93

            
94
/// A wrapper to implement [`Requestable::debug_request`].
95
pub struct DisplayRequestable<'a, R: Requestable>(&'a R);
96

            
97
impl<'a, R: Requestable> std::fmt::Debug for DisplayRequestable<'a, R> {
98
2
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99
2
        write!(f, "{:?}", self.0.make_request())
100
2
    }
101
}
102

            
103
/// How much clock skew do we allow in the distance between the directory
104
/// cache's clock and our own?
105
///
106
///  If we find more skew than this, we end the
107
/// request early, on the theory that the directory will not tell us any
108
/// information we'd accept.
109
#[derive(Clone, Debug)]
110
struct SkewLimit {
111
    /// We refuse to proceed if the directory says we are more fast than this.
112
    ///
113
    /// (This is equivalent to deciding that, from our perspective, the
114
    /// directory is at least this slow.)
115
    max_fast: Duration,
116

            
117
    /// We refuse to proceed if the directory says that we are more slow than
118
    /// this.
119
    ///
120
    /// (This is equivalent to deciding that, from our perspective, the
121
    /// directory is at least this fast.)
122
    max_slow: Duration,
123
}
124

            
125
/// A Request for a consensus directory.
126
#[derive(Debug, Clone)]
127
pub struct ConsensusRequest {
128
    /// What flavor of consensus are we asking for?  Right now, only
129
    /// "microdesc" and "ns" are supported.
130
    flavor: ConsensusFlavor,
131
    /// A list of the authority identities that we believe in.  We tell the
132
    /// directory cache only to give us a consensus if it is signed by enough
133
    /// of these authorities.
134
    authority_ids: Vec<RsaIdentity>,
135
    /// The publication time of the most recent consensus we have.  Used to
136
    /// generate an If-Modified-Since header so that we don't get a document
137
    /// we already have.
138
    last_consensus_published: Option<SystemTime>,
139
    /// A set of SHA3-256 digests of the _signed portion_ of consensuses we have.
140
    /// Used to declare what diffs we would accept.
141
    ///
142
    /// (Currently we don't send this, since we can't handle diffs.)
143
    last_consensus_sha3_256: Vec<[u8; 32]>,
144
    /// If present, the largest amount of clock skew to allow between ourself and a directory cache.
145
    skew_limit: Option<SkewLimit>,
146
}
147

            
148
impl ConsensusRequest {
149
    /// Create a new request for a consensus directory document.
150
277
    pub fn new(flavor: ConsensusFlavor) -> Self {
151
277
        ConsensusRequest {
152
277
            flavor,
153
277
            authority_ids: Vec::new(),
154
277
            last_consensus_published: None,
155
277
            last_consensus_sha3_256: Vec::new(),
156
277
            skew_limit: None,
157
277
        }
158
277
    }
159

            
160
    /// Add `id` to the list of authorities that this request should
161
    /// say we believe in.
162
2
    pub fn push_authority_id(&mut self, id: RsaIdentity) {
163
2
        self.authority_ids.push(id);
164
2
    }
165

            
166
    /// Add `d` to the list of consensus digests this request should
167
    /// say we already have.
168
80
    pub fn push_old_consensus_digest(&mut self, d: [u8; 32]) {
169
80
        self.last_consensus_sha3_256.push(d);
170
80
    }
171

            
172
    /// Set the publication time we should say we have for our last
173
    /// consensus to `when`.
174
158
    pub fn set_last_consensus_date(&mut self, when: SystemTime) {
175
158
        self.last_consensus_published = Some(when);
176
158
    }
177

            
178
    /// Return a slice of the consensus digests that we're saying we
179
    /// already have.
180
158
    pub fn old_consensus_digests(&self) -> impl Iterator<Item = &[u8; 32]> {
181
158
        self.last_consensus_sha3_256.iter()
182
158
    }
183

            
184
    /// Return an iterator of the authority identities that this request
185
    /// is saying we believe in.
186
2
    pub fn authority_ids(&self) -> impl Iterator<Item = &RsaIdentity> {
187
2
        self.authority_ids.iter()
188
2
    }
189

            
190
    /// Return the date we're reporting for our most recent consensus.
191
279
    pub fn last_consensus_date(&self) -> Option<SystemTime> {
192
279
        self.last_consensus_published
193
279
    }
194

            
195
    /// Tell the directory client that we should abort the request early if the
196
    /// directory's clock skew exceeds certain limits.
197
    ///
198
    /// The `max_fast` parameter is the most fast that we're willing to be with
199
    /// respect to the directory (or in other words, the most slow that we're
200
    /// willing to let the directory be with respect to us).
201
    ///
202
    /// The `max_slow` parameter is the most _slow_ that we're willing to be with
203
    /// respect to the directory ((or in other words, the most slow that we're
204
    /// willing to let the directory be with respect to us).
205
156
    pub fn set_skew_limit(&mut self, max_fast: Duration, max_slow: Duration) {
206
156
        self.skew_limit = Some(SkewLimit { max_fast, max_slow });
207
156
    }
208
}
209

            
210
/// Convert a list of digests in some format to a string, for use in a request
211
///
212
/// The digests `DL` will be sorted, converted to strings with `EF`,
213
/// separated with `sep`, and returned as an fresh `String`.
214
///
215
/// If the digests list is empty, returns None instead.
216
//
217
// In principle this ought to be doable with much less allocating,
218
// starting with hex::encode etc.
219
30
fn digest_list_stringify<'d, D, DL, EF>(digests: DL, encode: EF, sep: &str) -> Option<String>
220
30
where
221
30
    DL: IntoIterator<Item = &'d D> + 'd,
222
30
    D: PartialOrd + Ord + 'd,
223
30
    EF: Fn(&'d D) -> String,
224
30
{
225
30
    let mut digests = digests.into_iter().collect_vec();
226
30
    if digests.is_empty() {
227
4
        return None;
228
26
    }
229
26
    digests.sort_unstable();
230
26
    let ids = digests.into_iter().map(encode).map(Cow::Owned);
231
26
    // name collision with unstable Iterator::intersperse
232
26
    // https://github.com/rust-lang/rust/issues/48919
233
26
    let ids = Itertools::intersperse(ids, Cow::Borrowed(sep)).collect::<String>();
234
26
    Some(ids)
235
30
}
236

            
237
impl Default for ConsensusRequest {
238
4
    fn default() -> Self {
239
4
        Self::new(ConsensusFlavor::Microdesc)
240
4
    }
241
}
242

            
243
impl sealed::RequestableInner for ConsensusRequest {
244
4
    fn make_request(&self) -> Result<http::Request<String>> {
245
4
        // Build the URL.
246
4
        let mut uri = "/tor/status-vote/current/consensus".to_string();
247
4
        match self.flavor {
248
            ConsensusFlavor::Ns => {}
249
4
            flav => {
250
4
                uri.push('-');
251
4
                uri.push_str(flav.name());
252
4
            }
253
        }
254
5
        let d_encode_hex = |id: &RsaIdentity| hex::encode(id.as_bytes());
255
4
        if let Some(ids) = digest_list_stringify(&self.authority_ids, d_encode_hex, "+") {
256
2
            // With authorities, "../consensus/<F1>+<F2>+<F3>.z"
257
2
            uri.push('/');
258
2
            uri.push_str(&ids);
259
2
        }
260
        // Without authorities, "../consensus-microdesc.z"
261
4
        uri.push_str(".z");
262
4

            
263
4
        let mut req = http::Request::builder().method("GET").uri(uri);
264
4
        req = add_common_headers(req, self.anonymized());
265

            
266
        // Possibly, add an if-modified-since header.
267
4
        if let Some(when) = self.last_consensus_date() {
268
2
            req = req.header(
269
2
                http::header::IF_MODIFIED_SINCE,
270
2
                httpdate::fmt_http_date(when),
271
2
            );
272
2
        }
273

            
274
        // Possibly, add an X-Or-Diff-From-Consensus header.
275
4
        if let Some(ids) = digest_list_stringify(&self.last_consensus_sha3_256, hex::encode, ", ") {
276
2
            req = req.header("X-Or-Diff-From-Consensus", &ids);
277
2
        }
278

            
279
4
        Ok(req.body(String::new())?)
280
4
    }
281

            
282
2
    fn partial_response_body_ok(&self) -> bool {
283
2
        false
284
2
    }
285

            
286
    fn check_circuit<'a>(
287
        &self,
288
        circ: &'a ClientCirc,
289
    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a + Send>> {
290
        let skew_limit = self.skew_limit.clone();
291
        Box::pin(async move {
292
            use tor_proto::ClockSkew::*;
293
            // This is the clock skew _according to the directory_.
294
            let skew = circ.first_hop_clock_skew().await?;
295
            match (&skew_limit, &skew) {
296
                (Some(SkewLimit { max_slow, .. }), Slow(slow)) if slow > max_slow => {
297
                    Err(RequestError::TooMuchClockSkew)
298
                }
299
                (Some(SkewLimit { max_fast, .. }), Fast(fast)) if fast > max_fast => {
300
                    Err(RequestError::TooMuchClockSkew)
301
                }
302
                (_, _) => Ok(()),
303
            }
304
        })
305
    }
306

            
307
4
    fn anonymized(&self) -> AnonymizedRequest {
308
4
        AnonymizedRequest::Direct
309
4
    }
310
}
311

            
312
/// A request for one or more authority certificates.
313
#[derive(Debug, Clone, Default)]
314
pub struct AuthCertRequest {
315
    /// The identity/signing keys of the certificates we want.
316
    ids: Vec<AuthCertKeyIds>,
317
}
318

            
319
impl AuthCertRequest {
320
    /// Create a new request, asking for no authority certificates.
321
119
    pub fn new() -> Self {
322
119
        AuthCertRequest::default()
323
119
    }
324

            
325
    /// Add `ids` to the list of certificates we're asking for.
326
125
    pub fn push(&mut self, ids: AuthCertKeyIds) {
327
125
        self.ids.push(ids);
328
125
    }
329

            
330
    /// Return a list of the keys that we're asking for.
331
119
    pub fn keys(&self) -> impl Iterator<Item = &AuthCertKeyIds> {
332
119
        self.ids.iter()
333
119
    }
334
}
335

            
336
impl sealed::RequestableInner for AuthCertRequest {
337
4
    fn make_request(&self) -> Result<http::Request<String>> {
338
4
        if self.ids.is_empty() {
339
            return Err(RequestError::EmptyRequest);
340
4
        }
341
4
        let mut ids = self.ids.clone();
342
4
        ids.sort_unstable();
343
4

            
344
4
        let ids: Vec<String> = ids
345
4
            .iter()
346
10
            .map(|id| {
347
8
                format!(
348
8
                    "{}-{}",
349
8
                    hex::encode(id.id_fingerprint.as_bytes()),
350
8
                    hex::encode(id.sk_fingerprint.as_bytes())
351
8
                )
352
10
            })
353
4
            .collect();
354
4

            
355
4
        let uri = format!("/tor/keys/fp-sk/{}.z", &ids.join("+"));
356
4

            
357
4
        let req = http::Request::builder().method("GET").uri(uri);
358
4
        let req = add_common_headers(req, self.anonymized());
359
4

            
360
4
        Ok(req.body(String::new())?)
361
4
    }
362

            
363
4
    fn partial_response_body_ok(&self) -> bool {
364
4
        self.ids.len() > 1
365
4
    }
366

            
367
2
    fn max_response_len(&self) -> usize {
368
2
        // TODO: Pick a more principled number; I just made this one up.
369
2
        self.ids.len().saturating_mul(16 * 1024)
370
2
    }
371

            
372
4
    fn anonymized(&self) -> AnonymizedRequest {
373
4
        AnonymizedRequest::Direct
374
4
    }
375
}
376

            
377
impl FromIterator<AuthCertKeyIds> for AuthCertRequest {
378
4
    fn from_iter<I: IntoIterator<Item = AuthCertKeyIds>>(iter: I) -> Self {
379
4
        let mut req = Self::new();
380
10
        for i in iter {
381
6
            req.push(i);
382
6
        }
383
4
        req
384
4
    }
385
}
386

            
387
/// A request for one or more microdescriptors
388
#[derive(Debug, Clone, Default)]
389
pub struct MicrodescRequest {
390
    /// The SHA256 digests of the microdescriptors we want.
391
    digests: Vec<MdDigest>,
392
}
393

            
394
impl MicrodescRequest {
395
    /// Construct a request for no microdescriptors.
396
211
    pub fn new() -> Self {
397
211
        MicrodescRequest::default()
398
211
    }
399
    /// Add `d` to the list of microdescriptors we want to request.
400
39258
    pub fn push(&mut self, d: MdDigest) {
401
39258
        self.digests.push(d);
402
39258
    }
403

            
404
    /// Return a list of the microdescriptor digests that we're asking for.
405
41
    pub fn digests(&self) -> impl Iterator<Item = &MdDigest> {
406
41
        self.digests.iter()
407
41
    }
408
}
409

            
410
impl sealed::RequestableInner for MicrodescRequest {
411
18
    fn make_request(&self) -> Result<http::Request<String>> {
412
33
        let d_encode_b64 = |d: &[u8; 32]| Base64Unpadded::encode_string(&d[..]);
413
18
        let ids = digest_list_stringify(&self.digests, d_encode_b64, "-")
414
18
            .ok_or(RequestError::EmptyRequest)?;
415
18
        let uri = format!("/tor/micro/d/{}.z", &ids);
416
18
        let req = http::Request::builder().method("GET").uri(uri);
417
18

            
418
18
        let req = add_common_headers(req, self.anonymized());
419
18

            
420
18
        Ok(req.body(String::new())?)
421
18
    }
422

            
423
18
    fn partial_response_body_ok(&self) -> bool {
424
18
        self.digests.len() > 1
425
18
    }
426

            
427
16
    fn max_response_len(&self) -> usize {
428
16
        // TODO: Pick a more principled number; I just made this one up.
429
16
        self.digests.len().saturating_mul(8 * 1024)
430
16
    }
431

            
432
32
    fn anonymized(&self) -> AnonymizedRequest {
433
32
        AnonymizedRequest::Direct
434
32
    }
435
}
436

            
437
impl FromIterator<MdDigest> for MicrodescRequest {
438
24
    fn from_iter<I: IntoIterator<Item = MdDigest>>(iter: I) -> Self {
439
24
        let mut req = Self::new();
440
2050
        for i in iter {
441
2026
            req.push(i);
442
2026
        }
443
24
        req
444
24
    }
445
}
446

            
447
/// A request for one, many or all router descriptors.
448
#[derive(Debug, Clone)]
449
#[cfg(feature = "routerdesc")]
450
pub struct RouterDescRequest {
451
    /// The descriptors to request.
452
    requested_descriptors: RequestedDescs,
453
}
454

            
455
/// Tracks the different router descriptor types.
456
#[derive(Debug, Clone)]
457
#[cfg(feature = "routerdesc")]
458
enum RequestedDescs {
459
    /// If this is set, we just ask for all the descriptors.
460
    AllDescriptors,
461
    /// A list of digests to download.
462
    Digests(Vec<RdDigest>),
463
}
464

            
465
#[cfg(feature = "routerdesc")]
466
impl Default for RouterDescRequest {
467
2
    fn default() -> Self {
468
2
        RouterDescRequest {
469
2
            requested_descriptors: RequestedDescs::Digests(Vec::new()),
470
2
        }
471
2
    }
472
}
473

            
474
#[cfg(feature = "routerdesc")]
475
impl RouterDescRequest {
476
    /// Construct a request for all router descriptors.
477
2
    pub fn all() -> Self {
478
2
        RouterDescRequest {
479
2
            requested_descriptors: RequestedDescs::AllDescriptors,
480
2
        }
481
2
    }
482
    /// Construct a new empty request.
483
    pub fn new() -> Self {
484
        RouterDescRequest::default()
485
    }
486
}
487

            
488
#[cfg(feature = "routerdesc")]
489
impl sealed::RequestableInner for RouterDescRequest {
490
6
    fn make_request(&self) -> Result<http::Request<String>> {
491
6
        let mut uri = "/tor/server/".to_string();
492
6

            
493
6
        match self.requested_descriptors {
494
4
            RequestedDescs::Digests(ref digests) => {
495
4
                uri.push_str("d/");
496
4
                let ids = digest_list_stringify(digests, hex::encode, "+")
497
4
                    .ok_or(RequestError::EmptyRequest)?;
498
4
                uri.push_str(&ids);
499
            }
500
2
            RequestedDescs::AllDescriptors => {
501
2
                uri.push_str("all");
502
2
            }
503
        }
504

            
505
6
        uri.push_str(".z");
506
6

            
507
6
        let req = http::Request::builder().method("GET").uri(uri);
508
6
        let req = add_common_headers(req, self.anonymized());
509
6

            
510
6
        Ok(req.body(String::new())?)
511
6
    }
512

            
513
6
    fn partial_response_body_ok(&self) -> bool {
514
6
        match self.requested_descriptors {
515
4
            RequestedDescs::Digests(ref digests) => digests.len() > 1,
516
2
            RequestedDescs::AllDescriptors => true,
517
        }
518
6
    }
519

            
520
4
    fn max_response_len(&self) -> usize {
521
4
        // TODO: Pick a more principled number; I just made these up.
522
4
        match self.requested_descriptors {
523
2
            RequestedDescs::Digests(ref digests) => digests.len().saturating_mul(8 * 1024),
524
2
            RequestedDescs::AllDescriptors => 64 * 1024 * 1024, // big but not impossible
525
        }
526
4
    }
527

            
528
6
    fn anonymized(&self) -> AnonymizedRequest {
529
6
        AnonymizedRequest::Direct
530
6
    }
531
}
532

            
533
#[cfg(feature = "routerdesc")]
534
impl FromIterator<RdDigest> for RouterDescRequest {
535
6
    fn from_iter<I: IntoIterator<Item = RdDigest>>(iter: I) -> Self {
536
6
        let digests = iter.into_iter().collect();
537
6

            
538
6
        RouterDescRequest {
539
6
            requested_descriptors: RequestedDescs::Digests(digests),
540
6
        }
541
6
    }
542
}
543

            
544
/// A request for the descriptor of whatever relay we are making the request to
545
#[derive(Debug, Clone, Default)]
546
#[cfg(feature = "routerdesc")]
547
#[non_exhaustive]
548
pub struct RoutersOwnDescRequest {}
549

            
550
#[cfg(feature = "routerdesc")]
551
impl RoutersOwnDescRequest {
552
    /// Construct a new request.
553
    pub fn new() -> Self {
554
        RoutersOwnDescRequest::default()
555
    }
556
}
557

            
558
#[cfg(feature = "routerdesc")]
559
impl sealed::RequestableInner for RoutersOwnDescRequest {
560
    fn make_request(&self) -> Result<http::Request<String>> {
561
        let uri = "/tor/server/authority.z";
562
        let req = http::Request::builder().method("GET").uri(uri);
563
        let req = add_common_headers(req, self.anonymized());
564

            
565
        Ok(req.body(String::new())?)
566
    }
567

            
568
    fn partial_response_body_ok(&self) -> bool {
569
        false
570
    }
571

            
572
    fn anonymized(&self) -> AnonymizedRequest {
573
        AnonymizedRequest::Direct
574
    }
575
}
576

            
577
/// A request to download a hidden service descriptor
578
///
579
/// rend-spec-v3 2.2.6
580
#[derive(Debug, Clone)]
581
#[cfg(feature = "hs-client")]
582
pub struct HsDescDownloadRequest {
583
    /// What hidden service?
584
    hsid: HsBlindId,
585
    /// What's the largest acceptable response length?
586
    max_len: usize,
587
}
588

            
589
#[cfg(feature = "hs-client")]
590
impl HsDescDownloadRequest {
591
    /// Construct a request for a single onion service descriptor by its
592
    /// blinded ID.
593
41
    pub fn new(hsid: HsBlindId) -> Self {
594
        /// Default maximum length to use when we have no other information.
595
        const DEFAULT_HSDESC_MAX_LEN: usize = 50_000;
596
41
        HsDescDownloadRequest {
597
41
            hsid,
598
41
            max_len: DEFAULT_HSDESC_MAX_LEN,
599
41
        }
600
41
    }
601

            
602
    /// Set the maximum acceptable response length.
603
39
    pub fn set_max_len(&mut self, max_len: usize) {
604
39
        self.max_len = max_len;
605
39
    }
606
}
607

            
608
#[cfg(feature = "hs-client")]
609
impl sealed::RequestableInner for HsDescDownloadRequest {
610
80
    fn make_request(&self) -> Result<http::Request<String>> {
611
80
        let hsid = Base64Unpadded::encode_string(self.hsid.as_ref());
612
80
        // We hardcode version 3 here; if we ever have a v4 onion service
613
80
        // descriptor, it will need a different kind of Request.
614
80
        let uri = format!("/tor/hs/3/{}", hsid);
615
80
        let req = http::Request::builder().method("GET").uri(uri);
616
80
        let req = add_common_headers(req, self.anonymized());
617
80
        Ok(req.body(String::new())?)
618
80
    }
619

            
620
41
    fn partial_response_body_ok(&self) -> bool {
621
41
        false
622
41
    }
623

            
624
41
    fn max_response_len(&self) -> usize {
625
41
        self.max_len
626
41
    }
627

            
628
119
    fn anonymized(&self) -> AnonymizedRequest {
629
119
        AnonymizedRequest::Anonymized
630
119
    }
631
}
632

            
633
/// A request to upload a hidden service descriptor
634
///
635
/// rend-spec-v3 2.2.6
636
#[derive(Debug, Clone)]
637
#[cfg(feature = "hs-service")]
638
pub struct HsDescUploadRequest(String);
639

            
640
#[cfg(feature = "hs-service")]
641
impl HsDescUploadRequest {
642
    /// Construct a request for uploading a single onion service descriptor.
643
3432
    pub fn new(hsdesc: String) -> Self {
644
3432
        HsDescUploadRequest(hsdesc)
645
3432
    }
646
}
647

            
648
#[cfg(feature = "hs-service")]
649
impl sealed::RequestableInner for HsDescUploadRequest {
650
3432
    fn make_request(&self) -> Result<http::Request<String>> {
651
        /// The upload URI.
652
        const URI: &str = "/tor/hs/3/publish";
653

            
654
3432
        let req = http::Request::builder().method("POST").uri(URI);
655
3432
        let req = add_common_headers(req, self.anonymized());
656
3432
        Ok(req.body(self.0.clone())?)
657
3432
    }
658

            
659
3432
    fn partial_response_body_ok(&self) -> bool {
660
3432
        false
661
3432
    }
662

            
663
3432
    fn max_response_len(&self) -> usize {
664
3432
        // We expect the response _body_ to be empty, but the max_response_len
665
3432
        // is not zero because it represents the _total_ length of the response
666
3432
        // (which includes the length of the status line and headers).
667
3432
        //
668
3432
        // A real Tor POST response will always be less than that length, which
669
3432
        // will fit into 3 DATA messages at most. (The reply will be a single
670
3432
        // HTTP line, followed by a Date header.)
671
3432
        1024
672
3432
    }
673

            
674
6864
    fn anonymized(&self) -> AnonymizedRequest {
675
6864
        AnonymizedRequest::Anonymized
676
6864
    }
677
}
678

            
679
/// Encodings that all Tor clients support.
680
const UNIVERSAL_ENCODINGS: &str = "deflate, identity";
681

            
682
/// List all the encodings we accept
683
44
fn all_encodings() -> String {
684
44
    #[allow(unused_mut)]
685
44
    let mut encodings = UNIVERSAL_ENCODINGS.to_string();
686
44
    #[cfg(feature = "xz")]
687
44
    {
688
44
        encodings += ", x-tor-lzma";
689
44
    }
690
44
    #[cfg(feature = "zstd")]
691
44
    {
692
44
        encodings += ", x-zstd";
693
44
    }
694
44

            
695
44
    encodings
696
44
}
697

            
698
/// Add commonly used headers to the HTTP request.
699
///
700
/// (Right now, this is only Accept-Encoding.)
701
3544
fn add_common_headers(
702
3544
    req: http::request::Builder,
703
3544
    anon: AnonymizedRequest,
704
3544
) -> http::request::Builder {
705
3544
    // TODO: gzip, brotli
706
3544
    match anon {
707
        AnonymizedRequest::Anonymized => {
708
            // In an anonymized request, we do not admit to supporting any
709
            // encoding besides those that are always available.
710
3512
            req.header(http::header::ACCEPT_ENCODING, UNIVERSAL_ENCODINGS)
711
        }
712
32
        AnonymizedRequest::Direct => req.header(http::header::ACCEPT_ENCODING, all_encodings()),
713
    }
714
3544
}
715

            
716
#[cfg(test)]
717
mod test {
718
    // @@ begin test lint list maintained by maint/add_warning @@
719
    #![allow(clippy::bool_assert_comparison)]
720
    #![allow(clippy::clone_on_copy)]
721
    #![allow(clippy::dbg_macro)]
722
    #![allow(clippy::mixed_attributes_style)]
723
    #![allow(clippy::print_stderr)]
724
    #![allow(clippy::print_stdout)]
725
    #![allow(clippy::single_char_pattern)]
726
    #![allow(clippy::unwrap_used)]
727
    #![allow(clippy::unchecked_duration_subtraction)]
728
    #![allow(clippy::useless_vec)]
729
    #![allow(clippy::needless_pass_by_value)]
730
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
731
    use super::sealed::RequestableInner;
732
    use super::*;
733

            
734
    #[test]
735
    fn test_md_request() -> Result<()> {
736
        let d1 = b"This is a testing digest. it isn";
737
        let d2 = b"'t actually SHA-256.............";
738

            
739
        let mut req = MicrodescRequest::default();
740
        req.push(*d1);
741
        assert!(!req.partial_response_body_ok());
742
        req.push(*d2);
743
        assert!(req.partial_response_body_ok());
744
        assert_eq!(req.max_response_len(), 16 << 10);
745

            
746
        let req = crate::util::encode_request(&req.make_request()?);
747

            
748
        assert_eq!(req,
749
                   format!("GET /tor/micro/d/J3QgYWN0dWFsbHkgU0hBLTI1Ni4uLi4uLi4uLi4uLi4-VGhpcyBpcyBhIHRlc3RpbmcgZGlnZXN0LiBpdCBpc24.z HTTP/1.0\r\naccept-encoding: {}\r\n\r\n", all_encodings()));
750

            
751
        // Try it with FromIterator, and use some accessors.
752
        let req2: MicrodescRequest = vec![*d1, *d2].into_iter().collect();
753
        let ds: Vec<_> = req2.digests().collect();
754
        assert_eq!(ds, vec![d1, d2]);
755
        let req2 = crate::util::encode_request(&req2.make_request()?);
756
        assert_eq!(req, req2);
757

            
758
        Ok(())
759
    }
760

            
761
    #[test]
762
    fn test_cert_request() -> Result<()> {
763
        let d1 = b"This is a testing dn";
764
        let d2 = b"'t actually SHA-256.";
765
        let key1 = AuthCertKeyIds {
766
            id_fingerprint: (*d1).into(),
767
            sk_fingerprint: (*d2).into(),
768
        };
769

            
770
        let d3 = b"blah blah blah 1 2 3";
771
        let d4 = b"I like pizza from Na";
772
        let key2 = AuthCertKeyIds {
773
            id_fingerprint: (*d3).into(),
774
            sk_fingerprint: (*d4).into(),
775
        };
776

            
777
        let mut req = AuthCertRequest::default();
778
        req.push(key1);
779
        assert!(!req.partial_response_body_ok());
780
        req.push(key2);
781
        assert!(req.partial_response_body_ok());
782
        assert_eq!(req.max_response_len(), 32 << 10);
783

            
784
        let keys: Vec<_> = req.keys().collect();
785
        assert_eq!(keys, vec![&key1, &key2]);
786

            
787
        let req = crate::util::encode_request(&req.make_request()?);
788

            
789
        assert_eq!(req,
790
                   format!("GET /tor/keys/fp-sk/5468697320697320612074657374696e6720646e-27742061637475616c6c79205348412d3235362e+626c616820626c616820626c6168203120322033-49206c696b652070697a7a612066726f6d204e61.z HTTP/1.0\r\naccept-encoding: {}\r\n\r\n", all_encodings()));
791

            
792
        let req2: AuthCertRequest = vec![key1, key2].into_iter().collect();
793
        let req2 = crate::util::encode_request(&req2.make_request()?);
794
        assert_eq!(req, req2);
795

            
796
        Ok(())
797
    }
798

            
799
    #[test]
800
    fn test_consensus_request() -> Result<()> {
801
        let d1 = RsaIdentity::from_bytes(
802
            &hex::decode("03479E93EBF3FF2C58C1C9DBF2DE9DE9C2801B3E").unwrap(),
803
        )
804
        .unwrap();
805

            
806
        let d2 = b"blah blah blah 12 blah blah blah";
807
        let d3 = SystemTime::now();
808
        let mut req = ConsensusRequest::default();
809

            
810
        let when = httpdate::fmt_http_date(d3);
811

            
812
        req.push_authority_id(d1);
813
        req.push_old_consensus_digest(*d2);
814
        req.set_last_consensus_date(d3);
815
        assert!(!req.partial_response_body_ok());
816
        assert_eq!(req.max_response_len(), (16 << 20) - 1);
817
        assert_eq!(req.old_consensus_digests().next(), Some(d2));
818
        assert_eq!(req.authority_ids().next(), Some(&d1));
819
        assert_eq!(req.last_consensus_date(), Some(d3));
820

            
821
        let req = crate::util::encode_request(&req.make_request()?);
822

            
823
        assert_eq!(req,
824
                   format!("GET /tor/status-vote/current/consensus-microdesc/03479e93ebf3ff2c58c1c9dbf2de9de9c2801b3e.z HTTP/1.0\r\naccept-encoding: {}\r\nif-modified-since: {}\r\nx-or-diff-from-consensus: 626c616820626c616820626c616820313220626c616820626c616820626c6168\r\n\r\n", all_encodings(), when));
825

            
826
        // Request without authorities
827
        let req = ConsensusRequest::default();
828
        let req = crate::util::encode_request(&req.make_request()?);
829
        assert_eq!(req,
830
                   format!("GET /tor/status-vote/current/consensus-microdesc.z HTTP/1.0\r\naccept-encoding: {}\r\n\r\n", all_encodings()));
831

            
832
        Ok(())
833
    }
834

            
835
    #[test]
836
    #[cfg(feature = "routerdesc")]
837
    fn test_rd_request_all() -> Result<()> {
838
        let req = RouterDescRequest::all();
839
        assert!(req.partial_response_body_ok());
840
        assert_eq!(req.max_response_len(), 1 << 26);
841

            
842
        let req = crate::util::encode_request(&req.make_request()?);
843

            
844
        assert_eq!(
845
            req,
846
            format!(
847
                "GET /tor/server/all.z HTTP/1.0\r\naccept-encoding: {}\r\n\r\n",
848
                all_encodings()
849
            )
850
        );
851

            
852
        Ok(())
853
    }
854

            
855
    #[test]
856
    #[cfg(feature = "routerdesc")]
857
    fn test_rd_request() -> Result<()> {
858
        let d1 = b"at some point I got ";
859
        let d2 = b"of writing in hex...";
860

            
861
        let mut req = RouterDescRequest::default();
862

            
863
        if let RequestedDescs::Digests(ref mut digests) = req.requested_descriptors {
864
            digests.push(*d1);
865
        }
866
        assert!(!req.partial_response_body_ok());
867
        if let RequestedDescs::Digests(ref mut digests) = req.requested_descriptors {
868
            digests.push(*d2);
869
        }
870
        assert!(req.partial_response_body_ok());
871
        assert_eq!(req.max_response_len(), 16 << 10);
872

            
873
        let req = crate::util::encode_request(&req.make_request()?);
874

            
875
        assert_eq!(req,
876
                   format!("GET /tor/server/d/617420736f6d6520706f696e74204920676f7420+6f662077726974696e6720696e206865782e2e2e.z HTTP/1.0\r\naccept-encoding: {}\r\n\r\n", all_encodings()));
877

            
878
        // Try it with FromIterator, and use some accessors.
879
        let req2: RouterDescRequest = vec![*d1, *d2].into_iter().collect();
880
        let ds: Vec<_> = match req2.requested_descriptors {
881
            RequestedDescs::Digests(ref digests) => digests.iter().collect(),
882
            RequestedDescs::AllDescriptors => Vec::new(),
883
        };
884
        assert_eq!(ds, vec![d1, d2]);
885
        let req2 = crate::util::encode_request(&req2.make_request()?);
886
        assert_eq!(req, req2);
887
        Ok(())
888
    }
889

            
890
    #[test]
891
    #[cfg(feature = "hs-client")]
892
    fn test_hs_desc_download_request() -> Result<()> {
893
        use tor_llcrypto::pk::ed25519::Ed25519Identity;
894
        let hsid = [1, 2, 3, 4].iter().cycle().take(32).cloned().collect_vec();
895
        let hsid = Ed25519Identity::new(hsid[..].try_into().unwrap());
896
        let hsid = HsBlindId::from(hsid);
897
        let req = HsDescDownloadRequest::new(hsid);
898
        assert!(!req.partial_response_body_ok());
899
        assert_eq!(req.max_response_len(), 50 * 1000);
900

            
901
        let req = crate::util::encode_request(&req.make_request()?);
902

            
903
        assert_eq!(
904
            req,
905
            format!("GET /tor/hs/3/AQIDBAECAwQBAgMEAQIDBAECAwQBAgMEAQIDBAECAwQ HTTP/1.0\r\naccept-encoding: {}\r\n\r\n", UNIVERSAL_ENCODINGS)
906
        );
907

            
908
        Ok(())
909
    }
910
}