1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
#![deny(missing_docs)]
#![warn(noop_method_call)]
#![deny(unreachable_pub)]
#![deny(clippy::all)]
#![deny(clippy::await_holding_lock)]
#![deny(clippy::cargo_common_metadata)]
#![deny(clippy::cast_lossless)]
#![deny(clippy::checked_conversions)]
#![warn(clippy::clone_on_ref_ptr)]
#![warn(clippy::cognitive_complexity)]
#![deny(clippy::debug_assert_with_mut_call)]
#![deny(clippy::exhaustive_enums)]
#![deny(clippy::exhaustive_structs)]
#![deny(clippy::expl_impl_clone_on_copy)]
#![deny(clippy::fallible_impl_from)]
#![deny(clippy::implicit_clone)]
#![deny(clippy::large_stack_arrays)]
#![warn(clippy::manual_ok_or)]
#![deny(clippy::missing_docs_in_private_items)]
#![deny(clippy::missing_panics_doc)]
#![warn(clippy::needless_borrow)]
#![warn(clippy::needless_pass_by_value)]
#![warn(clippy::option_option)]
#![warn(clippy::rc_buffer)]
#![deny(clippy::ref_option_ref)]
#![warn(clippy::semicolon_if_nothing_returned)]
#![warn(clippy::trait_duplication_in_bounds)]
#![deny(clippy::unnecessary_wraps)]
#![warn(clippy::unseparated_literal_suffix)]
#![deny(clippy::unwrap_used)]
mod err;
pub mod request;
mod response;
mod util;
use tor_circmgr::{CircMgr, DirInfo};
use tor_rtcompat::{Runtime, SleepProvider, SleepProviderExt};
#[cfg(feature = "xz")]
use async_compression::futures::bufread::XzDecoder;
use async_compression::futures::bufread::ZlibDecoder;
#[cfg(feature = "zstd")]
use async_compression::futures::bufread::ZstdDecoder;
use futures::io::{
AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader,
};
use futures::FutureExt;
use memchr::memchr;
use std::sync::Arc;
use std::time::Duration;
use tracing::info;
pub use err::Error;
pub use response::{DirResponse, SourceInfo};
pub type Result<T> = std::result::Result<T, Error>;
pub async fn get_resource<CR, R, SP>(
req: &CR,
dirinfo: DirInfo<'_>,
runtime: &SP,
circ_mgr: Arc<CircMgr<R>>,
) -> Result<DirResponse>
where
CR: request::Requestable + ?Sized,
R: Runtime,
SP: SleepProvider,
{
let circuit = circ_mgr.get_or_launch_dir(dirinfo).await?;
let begin_timeout = Duration::from_secs(5);
let source = SourceInfo::new(circuit.unique_id());
let mut stream = runtime
.timeout(begin_timeout, circuit.begin_dir_stream())
.await??;
let r = download(runtime, req, &mut stream, Some(source.clone())).await;
let retire = match &r {
Err(e) => e.should_retire_circ(),
Ok(dr) => dr.error().map(Error::should_retire_circ) == Some(true),
};
if retire {
retire_circ(&circ_mgr, &source, "Partial response");
}
Ok(r?)
}
pub async fn download<R, S, SP>(
runtime: &SP,
req: &R,
stream: &mut S,
source: Option<SourceInfo>,
) -> Result<DirResponse>
where
R: request::Requestable + ?Sized,
S: AsyncRead + AsyncWrite + Send + Unpin,
SP: SleepProvider,
{
let partial_ok = req.partial_docs_ok();
let maxlen = req.max_response_len();
let req = req.make_request()?;
let encoded = util::encode_request(&req);
stream.write_all(encoded.as_bytes()).await?;
stream.flush().await?;
let mut buffered = BufReader::new(stream);
let header = read_headers(&mut buffered).await?;
if header.status != Some(200) {
return Err(Error::HttpStatus(header.status));
}
let mut decoder = get_decoder(buffered, header.encoding.as_deref())?;
let mut result = Vec::new();
let ok = read_and_decompress(runtime, &mut decoder, maxlen, &mut result).await;
let ok = match (partial_ok, ok, result.len()) {
(true, Err(e), n) if n > 0 => {
Err(e)
}
(_, Err(e), _) => {
return Err(e);
}
(_, Ok(()), _) => Ok(()),
};
Ok(DirResponse::new(200, ok.err(), result, source))
}
async fn read_headers<S>(stream: &mut S) -> Result<HeaderStatus>
where
S: AsyncBufRead + Unpin,
{
let mut buf = Vec::with_capacity(1024);
loop {
let n = read_until_limited(stream, b'\n', 2048, &mut buf).await?;
let mut headers = [httparse::EMPTY_HEADER; 32];
let mut response = httparse::Response::new(&mut headers);
match response.parse(&buf[..])? {
httparse::Status::Partial => {
if n == 0 {
return Err(Error::TruncatedHeaders);
}
if buf.len() >= 16384 {
return Err(httparse::Error::TooManyHeaders.into());
}
}
httparse::Status::Complete(n_parsed) => {
if response.code != Some(200) {
return Ok(HeaderStatus {
status: response.code,
encoding: None,
});
}
let encoding = if let Some(enc) = response
.headers
.iter()
.find(|h| h.name == "Content-Encoding")
{
Some(String::from_utf8(enc.value.to_vec())?)
} else {
None
};
assert!(n_parsed == buf.len());
return Ok(HeaderStatus {
status: Some(200),
encoding,
});
}
}
if n == 0 {
return Err(Error::TruncatedHeaders);
}
}
}
#[derive(Debug, Clone)]
struct HeaderStatus {
status: Option<u16>,
encoding: Option<String>,
}
async fn read_and_decompress<S, SP>(
runtime: &SP,
mut stream: S,
maxlen: usize,
result: &mut Vec<u8>,
) -> Result<()>
where
S: AsyncRead + Unpin,
SP: SleepProvider,
{
let buffer_window_size = 1024;
let mut written_total: usize = 0;
let read_timeout = Duration::from_secs(10);
let timer = runtime.sleep(read_timeout).fuse();
futures::pin_mut!(timer);
loop {
result.resize(written_total + buffer_window_size, 0);
let buf: &mut [u8] = &mut result[written_total..written_total + buffer_window_size];
let status = futures::select! {
status = stream.read(buf).fuse() => status,
_ = timer => {
return Err(Error::DirTimeout);
}
};
let written_in_this_loop = match status {
Ok(n) => n,
Err(other) => {
return Err(other.into());
}
};
written_total += written_in_this_loop;
if written_in_this_loop == 0 {
if written_total < result.len() {
result.resize(written_total, 0);
}
return Ok(());
}
if written_total > maxlen {
result.resize(maxlen, 0);
return Err(Error::ResponseTooLong(written_total));
}
}
}
fn retire_circ<R, E>(circ_mgr: &Arc<CircMgr<R>>, source_info: &SourceInfo, error: &E)
where
R: Runtime,
E: std::fmt::Display + ?Sized,
{
let id = source_info.unique_circ_id();
info!(
"{}: Retiring circuit because of directory failure: {}",
&id, &error
);
circ_mgr.retire_circ(id);
}
async fn read_until_limited<S>(
stream: &mut S,
byte: u8,
max: usize,
buf: &mut Vec<u8>,
) -> std::io::Result<usize>
where
S: AsyncBufRead + Unpin,
{
let mut n_added = 0;
loop {
let data = stream.fill_buf().await?;
if data.is_empty() {
return Ok(n_added);
}
debug_assert!(n_added < max);
let remaining_space = max - n_added;
let (available, found_byte) = match memchr(byte, data) {
Some(idx) => (idx + 1, true),
None => (data.len(), false),
};
debug_assert!(available >= 1);
let n_to_copy = std::cmp::min(remaining_space, available);
buf.extend(&data[..n_to_copy]);
stream.consume_unpin(n_to_copy);
n_added += n_to_copy;
if found_byte || n_added == max {
return Ok(n_added);
}
}
}
macro_rules! decoder {
($dec:ident, $s:expr) => {{
let mut decoder = $dec::new($s);
decoder.multiple_members(true);
Ok(Box::new(decoder))
}};
}
fn get_decoder<'a, S: AsyncBufRead + Unpin + Send + 'a>(
stream: S,
encoding: Option<&str>,
) -> Result<Box<dyn AsyncRead + Unpin + Send + 'a>> {
match encoding {
None | Some("identity") => Ok(Box::new(stream)),
Some("deflate") => decoder!(ZlibDecoder, stream),
#[cfg(feature = "xz")]
Some("x-tor-lzma") => decoder!(XzDecoder, stream),
#[cfg(feature = "zstd")]
Some("x-zstd") => decoder!(ZstdDecoder, stream),
Some(other) => Err(Error::ContentEncoding(other.into())),
}
}
#[cfg(test)]
mod test {
#![allow(clippy::unwrap_used)]
use super::*;
use tor_rtmock::{io::stream_pair, time::MockSleepProvider};
use futures_await_test::async_test;
#[async_test]
async fn test_read_until_limited() -> Result<()> {
let mut out = Vec::new();
let bytes = b"This line eventually ends\nthen comes another\n";
let mut s = &bytes[..];
let res = read_until_limited(&mut s, b'\n', 100, &mut out).await;
assert_eq!(res?, 26);
assert_eq!(&out[..], b"This line eventually ends\n");
let mut s = &bytes[..];
out.clear();
let res = read_until_limited(&mut s, b'\n', 10, &mut out).await;
assert_eq!(res?, 10);
assert_eq!(&out[..], b"This line ");
let mut s = &bytes[..];
out.clear();
let res = read_until_limited(&mut s, b'Z', 100, &mut out).await;
assert_eq!(res?, 45);
assert_eq!(&out[..], &bytes[..]);
Ok(())
}
async fn decomp_basic(
encoding: Option<&str>,
data: &[u8],
maxlen: usize,
) -> (Result<()>, Vec<u8>) {
let mock_time = MockSleepProvider::new(std::time::SystemTime::now());
let mut output = Vec::new();
let mut stream = match get_decoder(data, encoding) {
Ok(s) => s,
Err(e) => return (Err(e), output),
};
let r = read_and_decompress(&mock_time, &mut stream, maxlen, &mut output).await;
(r, output)
}
#[async_test]
async fn decompress_identity() -> Result<()> {
let mut text = Vec::new();
for _ in 0..1000 {
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.");
}
let limit = 10 << 20;
let (s, r) = decomp_basic(None, &text[..], limit).await;
s?;
assert_eq!(r, text);
let (s, r) = decomp_basic(Some("identity"), &text[..], limit).await;
s?;
assert_eq!(r, text);
let limit = 100;
let (s, r) = decomp_basic(Some("identity"), &text[..], limit).await;
assert!(s.is_err());
assert_eq!(r, &text[..100]);
Ok(())
}
#[async_test]
async fn decomp_zlib() -> Result<()> {
let compressed =
hex::decode("789cf3cf4b5548cb2cce500829cf8730825253200ca79c52881c00e5970c88").unwrap();
let limit = 10 << 20;
let (s, r) = decomp_basic(Some("deflate"), &compressed, limit).await;
s?;
assert_eq!(r, b"One fish Two fish Red fish Blue fish");
Ok(())
}
#[cfg(feature = "zstd")]
#[async_test]
async fn decomp_zstd() -> Result<()> {
let compressed = hex::decode("28b52ffd24250d0100c84f6e6520666973682054776f526564426c756520666973680a0200600c0e2509478352cb").unwrap();
let limit = 10 << 20;
let (s, r) = decomp_basic(Some("x-zstd"), &compressed, limit).await;
s?;
assert_eq!(r, b"One fish Two fish Red fish Blue fish\n");
Ok(())
}
#[cfg(feature = "xz")]
#[async_test]
async fn decomp_xz2() -> Result<()> {
let compressed = hex::decode("fd377a585a000004e6d6b446020021011c00000010cf58cce00024001d5d00279b88a202ca8612cfb3c19c87c34248a570451e4851d3323d34ab8000000000000901af64854c91f600013925d6ec06651fb6f37d010000000004595a").unwrap();
let limit = 10 << 20;
let (s, r) = decomp_basic(Some("x-tor-lzma"), &compressed, limit).await;
s?;
assert_eq!(r, b"One fish Two fish Red fish Blue fish\n");
Ok(())
}
#[async_test]
async fn headers_ok() -> Result<()> {
let text = b"HTTP/1.0 200 OK\r\nDate: ignored\r\nContent-Encoding: Waffles\r\n\r\n";
let mut s = &text[..];
let h = read_headers(&mut s).await?;
assert_eq!(h.status, Some(200));
assert_eq!(h.encoding.as_deref(), Some("Waffles"));
let mut s = &text[..15];
let h = read_headers(&mut s).await;
assert!(matches!(h, Err(Error::TruncatedHeaders)));
let text = b"HTTP/1.0 404 Not found\r\n\r\n";
let mut s = &text[..];
let h = read_headers(&mut s).await?;
assert_eq!(h.status, Some(404));
assert!(h.encoding.is_none());
Ok(())
}
#[async_test]
async fn headers_bogus() -> Result<()> {
let text = b"HTTP/999.0 WHAT EVEN\r\n\r\n";
let mut s = &text[..];
let h = read_headers(&mut s).await;
assert!(h.is_err());
assert!(matches!(h, Err(Error::HttparseError(_))));
Ok(())
}
#[async_test]
async fn test_download() -> Result<()> {
let (mut s1, s2) = stream_pair();
let (mut s2_r, mut s2_w) = s2.split();
let mock_time = MockSleepProvider::new(std::time::SystemTime::now());
let req: request::MicrodescRequest = vec![[9; 32]].into_iter().collect();
let (v1, v2, v3): (Result<DirResponse>, Result<Vec<u8>>, Result<()>) = futures::join!(
async {
let r = download(&mock_time, &req, &mut s1, None).await?;
s1.close().await?;
Ok(r)
},
async {
let mut v = Vec::new();
s2_r.read_to_end(&mut v).await?;
Ok(v)
},
async {
s2_w.write_all(b"HTTP/1.0 200 OK\r\n\r\n").await?;
s2_w.write_all(b"This is where the descs would go.").await?;
s2_w.close().await?;
Ok(())
}
);
let response = v1?;
v3?;
let request = v2?;
assert!(request[..].starts_with(
b"GET /tor/micro/d/CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk.z HTTP/1.0\r\n"
));
assert_eq!(response.status_code(), 200);
assert!(!response.is_partial());
assert!(response.error().is_none());
assert!(response.source().is_none());
let out = response.into_output();
assert_eq!(&out, b"This is where the descs would go.");
Ok(())
}
}