1
//! Module for helping with dirserver's HTTP interface.
2
//!
3
//! This module is unfortunately necessary as a middleware due to some obscure
4
//! things in Tor, most notably the ".z" extensions.
5

            
6
use cache::StoreCache;
7
use r2d2::Pool;
8
use r2d2_sqlite::SqliteConnectionManager;
9
#[cfg(feature = "dir-plugin-backend")]
10
use tor_dircommon::dir_plugin_backend::DirBackendPlugin;
11
use tor_error::{internal, warn_report};
12

            
13
use std::{
14
    collections::VecDeque,
15
    convert::Infallible,
16
    panic::{AssertUnwindSafe, catch_unwind},
17
    str::FromStr,
18
    sync::Arc,
19
    task::{Context, Poll},
20
    time::Duration,
21
};
22

            
23
use bytes::Bytes;
24
use futures::{Stream, StreamExt};
25
use http::{Method, Request, Response, StatusCode, header};
26
use http_body::{Body, Frame};
27
use hyper::{
28
    body::Incoming,
29
    server::conn::http1::{self},
30
    service::service_fn,
31
};
32
use hyper_util::rt::TokioIo;
33
use rusqlite::{Transaction, params};
34
use tokio::{
35
    io::{AsyncRead, AsyncWrite},
36
    task::JoinSet,
37
    time,
38
};
39
use tracing::{debug, warn};
40

            
41
#[cfg(feature = "dir-plugin-backend")]
42
use http_body_util::Full;
43
#[cfg(feature = "dir-plugin-backend")]
44
use std::io::Cursor;
45

            
46
use crate::database::{self, ContentEncoding, DocumentId, sql};
47

            
48
mod cache;
49

            
50
/// A type alias for the functions implementing endpoint logic.
51
///
52
/// An endpoint function is a function of the following form:
53
/// ```rust,ignore
54
/// fn get_consensus(
55
///     tx: &Transaction<'_>,
56
///     requ: &Request<Incoming>
57
/// ) -> Result<Response<Vec<DocumentId>>, Box<dyn std::error::Error + Send>>;
58
/// ```
59
///
60
/// The arguments give the endpoint function access to fixed state of the
61
/// database ([`Transaction`]) and the incoming [`Request`].  The return type is
62
/// a [`Result`] with an arbitrary error that implements [`Send`] and gets logged
63
/// but not returned to the client, which will just receive an `Internal Server Error`.
64
/// The [`Ok`] type of the [`Result`] is a [`Vec`] consisting of [`DocumentId`]
65
/// hashsums identifying (uncompressed) objects in the `store` table.
66
///
67
/// Changes to the database within the [`Transaction`] will (for now) get rolled
68
/// back, thereby giving the endpoint functions just read-only access to the
69
/// database.
70
///
71
/// TODO DIRMIRROR: Document the responsibilities here.
72
///
73
/// TODO DIRMIRROR: The error handling of endpoint functions may need further
74
/// discussions.  Maybe take a look at what other frameworks do?
75
type EndpointFn = fn(
76
    &Transaction,
77
    &Request<Incoming>,
78
) -> Result<Response<Vec<DocumentId>>, Box<dyn std::error::Error + Send>>;
79

            
80
/// A type that implements [`Body`] for a list of [`Arc<[u8]>`] data.
81
///
82
/// This is required because we use the reference counts as first-level return
83
/// types in order to avoid duplicate entries of the same data in memory.
84
/// See the documentation of [`StoreCache`] for more information on that.
85
struct DocumentBody(VecDeque<Arc<[u8]>>);
86

            
87
/// Representation of an endpoint, uniquely identified by a [`Method`] and path
88
/// pair followed by an appropriate [`EndpointFn`].
89
///
90
/// The path itself is a special string that refers to the endpoint at which this
91
/// resource should be available.  It supports a pattern-matching like syntax
92
/// through the use of the asterisk `*` character.
93
///
94
/// For example:
95
/// `/tor/status-vote/current/consensus` will match the URL exactly, whereas
96
/// `/tor/status-vote/current/*` will match every string that is in the
97
/// fourth component; such as `/tor/status-vote/current/consensus` or
98
/// `/tor/status-vote/current/consensus-microdesc`; it will however not
99
/// match in a prefix-like syntax, such as
100
/// `/tor/status-vote/current/consensus-microdesc/diff`.
101
///
102
/// In the case of non-unique matches, the first match wins.  Also, because
103
/// of wildcards, matching takes place in a `O(n)` fashion, so be sure to
104
/// to keep the `n` at a reasonable size.  This should not be much of a
105
/// problem for Tor applications though, because the list of endpoints is
106
/// reasonable (less than 30).
107
///
108
/// TODO: The entire asterisk matching is not so super nice, primarily because
109
/// it removes compile-time semantic checks; however, I cannot really think
110
/// of a much cleaner way that would not involve lots of boilerplate.
111
/// The most minimal "clean" way could be to do `path: &Option<&'static str>`
112
/// but I am not sure if this overhead is worth it, i.e.:
113
/// * `/tor/status-vote/current/*/diff/*/*`
114
/// * `[Some(""), Some("tor"), Some("status-vote"), Some("current"), None, ...]`
115
///   Maybe a macro could help here though ...
116
type Endpoint = (Method, &'static str, EndpointFn);
117

            
118
/// Representation of the core HTTP server.
119
#[derive(Debug)]
120
pub(crate) struct HttpServer {
121
    /// List of [`Endpoint`] entries.
122
    endpoints: Vec<Endpoint>,
123
    /// Access to the database pool.
124
    pool: Pool<SqliteConnectionManager>,
125
}
126

            
127
impl Body for DocumentBody {
128
    type Data = Bytes;
129
    type Error = Infallible;
130

            
131
    fn poll_frame(
132
        mut self: std::pin::Pin<&mut Self>,
133
        _cx: &mut Context<'_>,
134
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
135
        Poll::Ready(
136
            self.0
137
                .pop_front()
138
                .map(|bytes| Ok(Frame::data(Bytes::from_owner(bytes)))),
139
        )
140
    }
141
}
142

            
143
impl HttpServer {
144
    /// Creates a new [`HttpServer`] with a given [`Vec`] of [`Endpoint`] entries
145
    /// alongside access to the database [`Pool`].
146
    pub(crate) fn new(endpoints: Vec<Endpoint>, pool: Pool<SqliteConnectionManager>) -> Self {
147
        Self { endpoints, pool }
148
    }
149

            
150
    /// Bluntly launches an HTTP server only serving from the given backend.
151
    ///
152
    /// Absolutely not suited for anything in production as it comes with
153
    /// various limitations.  Primarily intended as an intermediate abstraction
154
    /// for relay development.
155
    #[cfg(feature = "dir-plugin-backend")]
156
    pub(crate) async fn serve_backend<I, S, E, B>(
157
        mut listener: I,
158
        backend: B,
159
    ) -> Result<(), tor_error::Bug>
160
    where
161
        I: Stream<Item = Result<S, E>> + Unpin,
162
        S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
163
        E: std::error::Error + 'static,
164
        B: DirBackendPlugin,
165
    {
166
        // Creates a failing HTTP resposne while satisfying the hyper requirements.
167
        let failure = |code| -> _ {
168
            Response::builder()
169
                .status(code)
170
                .body(Default::default())
171
                .expect("response builder should not fail")
172
        };
173

            
174
        // We need to wrap the backend as an Arc, as the value would otherwise
175
        // not live long enough.
176
        let backend = Arc::new(backend);
177
        let mut tasks: JoinSet<Result<(), hyper::Error>> = JoinSet::new();
178
        loop {
179
            tokio::select! {
180
                res = listener.next() => match res {
181
                    // Connection successfully accepted.
182
                    Some(Ok(s)) => {
183
                        let stream = TokioIo::new(s);
184

            
185
                        // Two Arc clones required.  First is to be able to run
186
                        // this in an endless loop and second one is required
187
                        // because hyper requires the function to be Fn, i.e.
188
                        // meaning it may not capture from it's surrounding
189
                        // state.
190
                        let backend = backend.clone();
191
                        let service = service_fn(move |requ: Request<Incoming>| {
192
                            let backend = backend.clone();
193
                            async move {
194
                                if requ.method() != Method::GET {
195
                                    warn!("Unsupported method: {}", requ.method());
196
                                    // dir-spec does not allow StatusCode::METHOD_NOT_ALLOWED.
197
                                    return Ok(failure(StatusCode::BAD_REQUEST));
198
                                }
199
                                if !requ.body().is_end_stream() {
200
                                    warn!("HTTP GET with non-empty body?");
201
                                    return Ok(failure(StatusCode::BAD_REQUEST));
202
                                }
203
                                // Convert Request::<Incoming> to Request::<()>.
204
                                let requ = requ.map(|_| ());
205
                                debug!(
206
                                    uri = %requ.uri(),
207
                                    "Incoming directory GET request"
208
                                );
209

            
210
                                // Convert the Box<[u8]> to something hyper accepts.
211
                                backend
212
                                    .get(&requ)
213
                                    .map(|resp| resp.map(|body| Full::new(Cursor::new(body))))
214
                            }
215
                        });
216
                        tasks.spawn(http1::Builder::new().serve_connection(stream, service));
217
                    },
218

            
219
                    // There has been an error in accepting the connection.
220
                    Some(Err(e)) => {
221
                        warn_report!(e, "listener accept failure");
222
                        continue;
223
                    }
224

            
225
                    // This should not happen due to ownership.
226
                    None => return Err(internal!("listener was closed externally?")),
227
                },
228
                // A hyper task we monitored in our tasks has exiteed.
229
                Some(res) = tasks.join_next() => match res {
230
                    Ok(Ok(())) => {},
231
                    Ok(Err(e)) => warn_report!(e, "client task encountered an error"),
232
                    Err(e) => warn_report!(e, "client task exited ungracefully"),
233
                },
234

            
235
            }
236
        }
237
    }
238

            
239
    /// Runs the server endlessly in the current task.
240
    ///
241
    /// This function does not fail, because all errors that could potentially
242
    /// occur, occur in further sub-tasks spawned by it and handled appropriately,
243
    /// that is usually logging the error and continuing the execution.
244
    pub(crate) async fn serve<I, S, E>(self, mut listener: I) -> Result<(), tor_error::Bug>
245
    where
246
        I: Stream<Item = Result<S, E>> + Unpin,
247
        S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
248
        E: std::error::Error,
249
    {
250
        let cache = Arc::new(StoreCache::new());
251
        let endpoints: Arc<[Endpoint]> = self.endpoints.into();
252
        let pool = self.pool;
253

            
254
        // We operate exclusively in JoinSets so that everything gets aborted
255
        // nicely in order without causing any sort of leaks.
256
        let mut hyper_tasks: JoinSet<Result<(), hyper::Error>> = JoinSet::new();
257
        let mut misc_tasks: JoinSet<()> = JoinSet::new();
258

            
259
        // Spawn a simple garbage collection task that periodically removes
260
        // dead references, just in case, from the StoreCache.
261
        misc_tasks.spawn({
262
            let cache = cache.clone();
263
            async move {
264
                loop {
265
                    cache.gc();
266
                    time::sleep(Duration::from_secs(60)).await;
267
                }
268
            }
269
        });
270

            
271
        loop {
272
            tokio::select! {
273
                res = listener.next() => match res {
274
                    // Connection successfully accepted.
275
                    Some(Ok(s)) => Self::dispatch_stream(&cache, &endpoints, &pool, &mut hyper_tasks, s),
276

            
277
                    // There has been an error in accepting the connection.
278
                    Some(Err(e)) => {
279
                        warn!("listener accept failure: {e}");
280
                        continue;
281
                    }
282

            
283
                    // This should not happen due to ownership.
284
                    None => return Err(internal!("listener was closed externally?")),
285
                },
286

            
287
                // A hyper task we monitored in our tasks has exiteed.
288
                //
289
                // We distinguish between graceful and ungraceful errors, with
290
                // the latter one being errors related to a failure in tokio's
291
                // joining itself, such as if the underlying task panic'ed;
292
                // whereas graceful errors are logical application level errors.
293
                Some(res) = hyper_tasks.join_next() => match res {
294
                    Ok(Ok(())) => {},
295
                    Ok(Err(e)) => warn!("client task encountered an error: {e}"),
296
                    Err(e) => warn!("client task exited ungracefully: {e}"),
297
                },
298

            
299
            }
300
        }
301
    }
302

            
303
    /// Dispatches a new [`Stream`] into an existing [`JoinSet`].
304
    fn dispatch_stream<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
305
        cache: &Arc<StoreCache>,
306
        endpoints: &Arc<[Endpoint]>,
307
        pool: &Pool<SqliteConnectionManager>,
308
        tasks: &mut JoinSet<Result<(), hyper::Error>>,
309
        stream: S,
310
    ) {
311
        let stream = TokioIo::new(stream);
312

            
313
        // Create the `service_fn` to pass to `hyper`.
314
        //
315
        // Unfortunately, we have to clone the reference counter of all shared
316
        // objects two times here.  The first clone is required to not move
317
        // it into the `service_fn`, the second one is required to
318
        // circumvent a hyper limitation, namely that a service function
319
        // requires a `Fn`, not an `FnMut`, which would allow capturing values
320
        // from the environment natively.
321
        let cache = cache.clone();
322
        let endpoints = endpoints.clone();
323
        let pool = pool.clone();
324
        let service = service_fn(move |requ| {
325
            let cache = cache.clone();
326
            let endpoints = endpoints.clone();
327
            let pool = pool.clone();
328
            async move { Self::handler(cache, endpoints, pool, requ).await }
329
        });
330

            
331
        tasks.spawn(http1::Builder::new().serve_connection(stream, service));
332
    }
333

            
334
    /// A small wrapper function that creates a read-only or read-write
335
    /// [`Transaction`] based upon the [`Method`] and continues execution in
336
    /// [`Self::handler_tx`].
337
    #[allow(clippy::unused_async)] // TODO
338
    async fn handler(
339
        cache: Arc<StoreCache>,
340
        endpoints: Arc<[Endpoint]>,
341
        pool: Pool<SqliteConnectionManager>,
342
        requ: Request<Incoming>,
343
    ) -> Result<Response<DocumentBody>, Infallible> {
344
        // TODO: This would be the place to either use read_tx or rw_tx depending
345
        // on the method, but given that this is all GET at the moment, just go
346
        // with read_tx.
347
        Ok(
348
            database::read_tx(&pool, |tx| Self::handler_tx(&cache, &endpoints, tx, &requ))
349
                .unwrap_or_else(|e| {
350
                    warn!("database error: {e}");
351
                    Self::empty_response(StatusCode::INTERNAL_SERVER_ERROR)
352
                }),
353
        )
354
    }
355

            
356
    /// A big monolithic function that handles incoming request with a consist
357
    /// view upon the database.
358
    ///
359
    /// The function works in eight steps which are documented with more detail
360
    /// within the code:
361
    /// 1. Determine the compression algorithm
362
    /// 2. Select an [`EndpointFn`] by matching the path component
363
    /// 3. Call the [`EndpointFn`] to obtain various [`DocumentId`]s
364
    /// 4. Map the [`DocumentId`]s to their compressed counterpart
365
    /// 5. Query the [`StoreCache`] with the [`DocumentId`] and [`Transaction`]
366
    ///    handle to store the document ref
367
    /// 6. Compose the [`Response`]
368
    ///
369
    /// TODO DIRMIRROR: Implement [`Method::HEAD`].
370
    fn handler_tx(
371
        cache: &Arc<StoreCache>,
372
        endpoints: &[Endpoint],
373
        tx: &Transaction,
374
        requ: &Request<Incoming>,
375
    ) -> Response<DocumentBody> {
376
        // (1) Determine the compression algorithm
377
        //
378
        // This step determines the compression algorithm, according to:
379
        // https://spec.torproject.org/dir-spec/standards-compliance.html#http-headers.
380
        let (encoding, advertise_encoding) = Self::determine_encoding(requ);
381

            
382
        // (2) Select an `EndpointFn` by matching the path component
383
        let endpoint_fn = match Self::match_endpoint(endpoints, requ) {
384
            Some((_, _, endpoint_fn)) => endpoint_fn,
385
            None => return Self::empty_response(StatusCode::NOT_FOUND),
386
        };
387

            
388
        // (3) Call the `EndpointFn` to obtain various `DocumentId`s
389
        let endpoint_fn_resp = match catch_unwind(AssertUnwindSafe(|| endpoint_fn(tx, requ))) {
390
            // Everything went successful.
391
            Ok(Ok(r)) => r,
392

            
393
            // The endpoint function gracefully failed with an error.
394
            Ok(Err(e)) => {
395
                warn!(
396
                    "{} {}: endpoint function failed: {e}",
397
                    requ.method(),
398
                    requ.uri()
399
                );
400
                return Self::empty_response(StatusCode::INTERNAL_SERVER_ERROR);
401
            }
402

            
403
            // The endpoint function unexpectedly crashed.
404
            Err(_) => {
405
                warn!(
406
                    "{} {}: endpoint function crashed",
407
                    requ.method(),
408
                    requ.uri()
409
                );
410
                return Self::empty_response(StatusCode::INTERNAL_SERVER_ERROR);
411
            }
412
        };
413
        let (endpoint_fn_parts, docids) = endpoint_fn_resp.into_parts();
414

            
415
        // (4) Map the docids to their compressed counterpart
416
        let docids = docids
417
            .into_iter()
418
            .map(|docid| Self::map_encoding(tx, docid, encoding))
419
            .collect::<Result<Vec<_>, _>>();
420
        let docids = match docids {
421
            Ok(s) => s,
422
            Err(e) => {
423
                warn!(
424
                    "{} {}: unable to find compressed document: {e}",
425
                    requ.method(),
426
                    requ.uri()
427
                );
428
                return Self::empty_response(StatusCode::INTERNAL_SERVER_ERROR);
429
            }
430
        };
431

            
432
        // (5) Query the [`StoreCache`] with the [`DocumentId`] and
433
        //     [`Transaction`] handle to store the document ref.
434
        let mut documents = VecDeque::new();
435
        for docid in docids {
436
            let document = match cache.get(tx, docid) {
437
                Ok(document) => document,
438
                Err(e) => {
439
                    warn!(
440
                        "{} {}: unable to access the cache: {e}",
441
                        requ.method(),
442
                        requ.uri()
443
                    );
444
                    return Self::empty_response(StatusCode::INTERNAL_SERVER_ERROR);
445
                }
446
            };
447

            
448
            documents.push_back(document);
449
        }
450

            
451
        // (6) Compose the `Response`.
452
        //
453
        // The composing primarily consists of building a response from the parts
454
        // of the intermediate response plus optionally adding a Content-Encoding
455
        // header.
456
        let mut resp = Response::from_parts(endpoint_fn_parts, DocumentBody(documents));
457
        if advertise_encoding {
458
            // Add the Content-Encoding header, if necessary.
459
            resp.headers_mut().insert(
460
                header::CONTENT_ENCODING,
461
                encoding
462
                    .to_string()
463
                    .try_into()
464
                    .expect("strum serialized a non-valid header?!?"),
465
            );
466
        }
467

            
468
        resp
469
    }
470

            
471
    /// Determines the [`ContentEncoding`] based on the path and the value of [`header::ACCEPT_ENCODING`].
472
    ///
473
    /// This function returns a tuple containing the determined [`ContentEncoding`]
474
    /// alongside a boolean that indicates whether [`header::CONTENT_ENCODING`]
475
    /// should be set or not with the value of the just determined
476
    /// [`ContentEncoding`].
477
6
    fn determine_encoding<B: Body>(requ: &Request<B>) -> (ContentEncoding, bool) {
478
6
        let z_suffix = requ.uri().path().ends_with(".z");
479

            
480
        // TODO: Refactor this in a flat fashion once we get stable If-Let-Chains
481
        // by upgrading MSVC to 1.88.
482
        //
483
        // This works by branching the parameters into the following four branches:
484
        // 1. Accept-Encoding && ".z" URL
485
        // 2. Accept-Encoding && No ".z" URL
486
        // 3. No Accept-Encoding && ".z" URL
487
        // 4. No Accept-Encoding && No "z" URL
488

            
489
        // Technically we could use an else-if here, but given the branching
490
        // I explained above, I would like to keep it in the nested fashion
491
        // once we got stable If-Let.
492
        #[allow(clippy::collapsible_else_if)]
493
6
        if let Some(accept_encoding) = requ.headers().get(header::ACCEPT_ENCODING) {
494
            // Parse the accept_encoding value by splitting it at "," and then
495
            // parse each trimmed component as a ContentEncoding.  Unsupported
496
            // ContentEncodings are ignored.
497
4
            let encodings = accept_encoding
498
4
                .to_str()
499
4
                .unwrap_or("")
500
4
                .split(",")
501
7
                .filter_map(|encoding| ContentEncoding::from_str(encoding.trim()).ok())
502
                .collect::<Vec<_>>();
503

            
504
4
            if z_suffix {
505
                // (1) Accept-Encoding && ".z" URL
506
                //
507
                // From the specification:
508
                // > If the client does send an Accept-Encoding header along with
509
                // > a .z URL, the server SHOULD treat the request the same way
510
                // > as for the URL without the .z.  If deflate is included in the
511
                // > Accept-Encoding, the response MUST be encoded, once, with
512
                // > an encoding advertised by the client, and be accompanied by
513
                // > an appropriate Content-Encoding.
514

            
515
                // We do not check whether Accept-Encoding contains deflate,
516
                // because the specification gives us the assurance.
517
                // TODO: Maybe we should?
518
1
                (ContentEncoding::Deflate, true)
519
            } else {
520
                // (2) Accept-Encoding && No ".z" URL
521
3
                if let Some(encoding) = encodings.first() {
522
                    // Pick the first found encoding and include it in the header,
523
                    // if it is not the identity encoding.
524
2
                    let include_in_header = *encoding != ContentEncoding::Identity;
525
2
                    (*encoding, include_in_header)
526
                } else {
527
                    // No supported encodings were found, fallback to identity
528
                    // and do not provide a Content-Encoding header.
529
                    // This is effectively equivalent to (4).
530
1
                    (ContentEncoding::Identity, false)
531
                }
532
            }
533
        } else {
534
2
            if z_suffix {
535
                // (3) No Accept-Encoding && ".z" URL
536
                //
537
                // From the specification:
538
                // > If the client does not send an Accept-Encoding header along
539
                // > with a .z URL, the server MUST send the response compressed
540
                // > with deflate and SHOULD NOT send a Content-Encoding header.
541
1
                (ContentEncoding::Deflate, false)
542
            } else {
543
                // (4) No Accept-Encoding && No ".z" URL
544
1
                (ContentEncoding::Identity, false)
545
            }
546
        }
547
6
    }
548

            
549
    /// Matches an incoming request to an existing endpoint.
550
    ///
551
    /// The matching works in a first-match wins fashion.
552
    /// An endpoint is said to be matched when the following two properties for
553
    /// the incoming request hold true:
554
    /// * Both [`Method`] values are the same.
555
    /// * Each component of the URL path is equal at the respective position or,
556
    ///   in the case of the endpoint path, is a wildcard.
557
18
    fn match_endpoint<'a, B: Body>(
558
18
        endpoints: &'a [Endpoint],
559
18
        requ: &Request<B>,
560
18
    ) -> Option<&'a Endpoint> {
561
18
        let requ_path = requ.uri().path();
562
18
        let requ_path = requ_path.strip_suffix(".z").unwrap_or(requ_path);
563
18
        let requ_path = requ_path.split('/').collect::<Vec<_>>();
564
18
        let mut res = None;
565
18
        for tuple in endpoints.iter() {
566
56
            let (method, path, _endpoint_fn) = tuple;
567
56
            let path = path.split('/').collect::<Vec<_>>();
568

            
569
            // Filter the method out first.
570
56
            if requ.method() != method {
571
                continue;
572
56
            }
573

            
574
            // Now that the method is filtered out, perform the path matching
575
            // algorithm.
576
            //
577
            // The path algorithm works as follows:
578
            // 1. Check whether `path.len() == requ_path.len()`, for a match,
579
            //    two paths must have the same number of path components.
580
            // 2. Initialize `is_match = true`.
581
            // 3. Walk over the path components in pairs (i.e. compare first
582
            //    component of `path` with the first component of `requ_path`, ...)
583
            //    and check for each component tuple, whether they are equal or
584
            //    whether the component at the current position in path is a
585
            //    wildcard component, that is, a component that equals `*`.
586
            //
587
            //    Stop immediately the moment
588
            //    `path[i] == requ_path[i] || path[i] == "*"` yields `false`;
589
            //     set `is_match = false`.
590
            // 4. Check the result of `is_match`.
591

            
592
            // Paths must have the same number of components in order to match.
593
            // An inequality here means instant disqualification.
594
56
            if path.len() != requ_path.len() {
595
32
                continue;
596
24
            }
597

            
598
            // Iterate over the path component for component until we disqualify
599
            // for a match.
600
24
            let mut is_match = true;
601
24
            for (this, incoming) in path.iter().zip(&requ_path) {
602
72
                if this == incoming || *this == "*" {
603
59
                    continue;
604
                } else {
605
13
                    is_match = false;
606
13
                    break;
607
                }
608
            }
609

            
610
            // Stop on the first match, propagate the match to the outside.
611
24
            if is_match {
612
11
                res = Some(tuple);
613
11
                break;
614
13
            }
615
        }
616

            
617
18
        res
618
18
    }
619

            
620
    /// Looks up the corresponding [`DocumentId`] for a given [`DocumentId`] and
621
    /// a [`ContentEncoding`].
622
    fn map_encoding(
623
        tx: &Transaction,
624
        docid: DocumentId,
625
        encoding: ContentEncoding,
626
    ) -> Result<DocumentId, rusqlite::Error> {
627
        // If the encoding is the identity, do not bother about it any further.
628
        if encoding == ContentEncoding::Identity {
629
            return Ok(docid);
630
        }
631

            
632
        let mut stmt = tx.prepare_cached(sql!(
633
            "
634
            SELECT compressed_docid
635
            FROM compressed_document
636
              WHERE identity_docid = ?1
637
                AND algorithm = ?2
638
            "
639
        ))?;
640
        let compressed_docid =
641
            stmt.query_one(params![docid, encoding.to_string()], |row| row.get(0))?;
642

            
643
        Ok(compressed_docid)
644
    }
645

            
646
    /// Generates an empty response with a given [`StatusCode`].
647
    fn empty_response(status: StatusCode) -> Response<DocumentBody> {
648
        // TODO DIRMIRROR: Statically assert that.
649
        Response::builder()
650
            .status(status)
651
            .body(DocumentBody(VecDeque::new()))
652
            .expect("response builder for empty response failed?!?")
653
    }
654
}
655

            
656
#[cfg(test)]
657
pub(in crate::http) mod test {
658
    // @@ begin test lint list maintained by maint/add_warning @@
659
    #![allow(clippy::bool_assert_comparison)]
660
    #![allow(clippy::clone_on_copy)]
661
    #![allow(clippy::dbg_macro)]
662
    #![allow(clippy::mixed_attributes_style)]
663
    #![allow(clippy::print_stderr)]
664
    #![allow(clippy::print_stdout)]
665
    #![allow(clippy::single_char_pattern)]
666
    #![allow(clippy::unwrap_used)]
667
    #![allow(clippy::unchecked_time_subtraction)]
668
    #![allow(clippy::useless_vec)]
669
    #![allow(clippy::needless_pass_by_value)]
670
    #![allow(clippy::string_slice)] // See arti#2571
671
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
672
    use crate::database;
673

            
674
    use super::*;
675

            
676
    use std::{
677
        io::{Cursor, Write},
678
        str::FromStr,
679
    };
680

            
681
    use flate2::{
682
        Compression,
683
        write::{DeflateDecoder, DeflateEncoder, GzEncoder},
684
    };
685
    use http::Version;
686
    use http_body_util::{BodyExt, Empty};
687
    use lazy_static::lazy_static;
688
    use tokio::{
689
        net::{TcpListener, TcpStream},
690
        task,
691
    };
692
    use tokio_stream::wrappers::TcpListenerStream;
693

            
694
    pub(in crate::http) const IDENTITY: &str = "Lorem ipsum dolor sit amet.";
695

            
696
    lazy_static! {
697
        pub(in crate::http) static ref IDENTITY_DOCID: DocumentId =
698
            hex_to_docid("DD14CBBF0E74909AAC7F248A85D190AFD8DA98265CEF95FC90DFDDABEA7C2E66");
699
        // TODO DIRMIRROR compression algorithms do not necessarily produce stable output
700
        pub(in crate::http) static ref DEFLATE_DOCID: DocumentId =
701
            hex_to_docid("07564DD13A7F4A6AD98B997F2938B1CEE11F8C7F358C444374521BA54D50D05E");
702
        // TODO DIRMIRROR compression algorithms do not necessarily produce stable output
703
        pub(in crate::http) static ref GZIP_DOCID: DocumentId =
704
            hex_to_docid("1518107D3EF1EC6EAC3F3249DF26B2F845BC8226C326309F4822CAEF2E664104");
705
        // TODO DIRMIRROR compression algorithms do not necessarily produce stable output
706
        pub(in crate::http) static ref XZ_STD_DOCID: DocumentId =
707
            hex_to_docid("17416948501F8E627CC9A8F7EFE7A2F32788D53CB84A5F67AC8FD4C1B59184CF");
708
        // TODO DIRMIRROR compression algorithms do not necessarily produce stable output
709
        pub(in crate::http) static ref X_TOR_LZMA_DOCID: DocumentId =
710
            hex_to_docid("B5549F79A69113BDAF3EF0AD1D7D339D0083BC31400ECEE1B673F331CF26E239");
711
    }
712

            
713
    pub(in crate::http) fn create_test_db_pool() -> Pool<SqliteConnectionManager> {
714
        let pool = database::open("").unwrap();
715
        database::rw_tx(&pool, init_test_db).unwrap();
716
        pool
717
    }
718

            
719
    fn hex_to_docid(s: &str) -> DocumentId {
720
        let data: [u8; 32] = hex::decode(s).unwrap().try_into().unwrap();
721
        data.into()
722
    }
723

            
724
    fn init_test_db(tx: &Transaction) {
725
        assert_eq!(DocumentId::digest(IDENTITY.as_bytes()), *IDENTITY_DOCID);
726

            
727
        let deflate = {
728
            let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
729
            encoder.write_all(IDENTITY.as_bytes()).unwrap();
730
            encoder.finish().unwrap()
731
        };
732
        assert_eq!(DocumentId::digest(&deflate), *DEFLATE_DOCID);
733

            
734
        let gzip = {
735
            let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
736
            encoder.write_all(IDENTITY.as_bytes()).unwrap();
737
            encoder.finish().unwrap()
738
        };
739
        assert_eq!(DocumentId::digest(&gzip), *GZIP_DOCID);
740

            
741
        let xz_std = zstd::encode_all(IDENTITY.as_bytes(), 3).unwrap();
742
        assert_eq!(DocumentId::digest(&xz_std), *XZ_STD_DOCID);
743

            
744
        let mut x_tor_lzma = Vec::new();
745
        lzma_rs::lzma_compress(&mut Cursor::new(IDENTITY), &mut x_tor_lzma).unwrap();
746
        assert_eq!(DocumentId::digest(&x_tor_lzma), *X_TOR_LZMA_DOCID);
747

            
748
        tx.execute(
749
            sql!(
750
                "
751
                INSERT INTO store(docid, content) VALUES
752
                (?1, ?2), -- identity
753
                (?3, ?4), -- deflate
754
                (?5, ?6), -- gzip
755
                (?7, ?8), -- xzstd
756
                (?9, ?10) -- lzma
757
                "
758
            ),
759
            params![
760
                *IDENTITY_DOCID,
761
                IDENTITY.as_bytes().to_vec(),
762
                *DEFLATE_DOCID,
763
                deflate,
764
                *GZIP_DOCID,
765
                gzip,
766
                *XZ_STD_DOCID,
767
                xz_std,
768
                *X_TOR_LZMA_DOCID,
769
                x_tor_lzma
770
            ],
771
        )
772
        .unwrap();
773

            
774
        tx.execute(
775
            sql!(
776
                "
777
                INSERT INTO compressed_document(algorithm, identity_docid, compressed_docid) VALUES
778
                ('deflate', ?1, ?2),
779
                ('gzip', ?1, ?3),
780
                ('x-zstd', ?1, ?4),
781
                ('x-tor-lzma', ?1, ?5)
782
                "
783
            ),
784
            params![
785
                *IDENTITY_DOCID,
786
                *DEFLATE_DOCID,
787
                *GZIP_DOCID,
788
                *XZ_STD_DOCID,
789
                *X_TOR_LZMA_DOCID
790
            ],
791
        )
792
        .unwrap();
793
    }
794

            
795
    #[test]
796
1
    fn content_encoding() {
797
1
        assert_eq!(ContentEncoding::Identity.to_string(), "identity");
798
1
        assert_eq!(
799
1
            ContentEncoding::from_str("identity").unwrap(),
800
1
            ContentEncoding::Identity
801
        );
802

            
803
1
        assert_eq!(ContentEncoding::Deflate.to_string(), "deflate");
804
1
        assert_eq!(
805
1
            ContentEncoding::from_str("DeFlaTe").unwrap(),
806
1
            ContentEncoding::Deflate
807
        );
808

            
809
1
        assert_eq!(ContentEncoding::Gzip.to_string(), "gzip");
810
1
        assert_eq!(
811
1
            ContentEncoding::from_str("GzIP").unwrap(),
812
1
            ContentEncoding::Gzip
813
        );
814
1
        assert_eq!(ContentEncoding::XZstd.to_string(), "x-zstd");
815
1
        assert_eq!(
816
1
            ContentEncoding::from_str("x-zStD").unwrap(),
817
1
            ContentEncoding::XZstd
818
        );
819

            
820
1
        assert_eq!(ContentEncoding::XTorLzma.to_string(), "x-tor-lzma");
821
1
        assert_eq!(
822
1
            ContentEncoding::from_str("x-tOr-lzMa").unwrap(),
823
1
            ContentEncoding::XTorLzma
824
        );
825
1
    }
826

            
827
    #[test]
828
1
    fn determine_encoding() {
829
        // 1. Accept-Encoding && ".z" URL.
830
1
        let requ = Request::builder()
831
1
            .header("Accept-Encoding", "deflate,identity  ,  gzip")
832
1
            .uri("/foo.z")
833
1
            .body(String::new())
834
1
            .unwrap();
835
1
        assert_eq!(
836
1
            HttpServer::determine_encoding(&requ),
837
1
            (ContentEncoding::Deflate, true)
838
        );
839

            
840
        // 2a. Valid Accept-Encoding && No ".z" URL.
841
1
        let requ = Request::builder()
842
1
            .header("Accept-Encoding", "  gzip   ")
843
1
            .uri("/foo")
844
1
            .body(String::new())
845
1
            .unwrap();
846
1
        assert_eq!(
847
1
            HttpServer::determine_encoding(&requ),
848
1
            (ContentEncoding::Gzip, true)
849
        );
850

            
851
        // 2b. Identity Accept-Encoding && No ".z" URL.
852
1
        let requ = Request::builder()
853
1
            .header("Accept-Encoding", "identity")
854
1
            .uri("/foo")
855
1
            .body(String::new())
856
1
            .unwrap();
857
1
        assert_eq!(
858
1
            HttpServer::determine_encoding(&requ),
859
1
            (ContentEncoding::Identity, false)
860
        );
861

            
862
        // 2c. Invalid Accept-Encoding && No ".z" URL.
863
1
        let requ = Request::builder()
864
1
            .header("Accept-Encoding", "  unSuppOrtEd_EncODing_SCHEMA , yeah   ")
865
1
            .uri("/foo")
866
1
            .body(String::new())
867
1
            .unwrap();
868
1
        assert_eq!(
869
1
            HttpServer::determine_encoding(&requ),
870
1
            (ContentEncoding::Identity, false)
871
        );
872

            
873
        // 3. No Accept-Encoding && ".z" URL
874
1
        let requ = Request::builder()
875
1
            .uri("/foo.z")
876
1
            .body(String::new())
877
1
            .unwrap();
878
1
        assert_eq!(
879
1
            HttpServer::determine_encoding(&requ),
880
1
            (ContentEncoding::Deflate, false)
881
        );
882

            
883
        // 4. No Accept-Encoding && No ".z" URL
884
1
        let requ = Request::builder().uri("/foo").body(String::new()).unwrap();
885
1
        assert_eq!(
886
1
            HttpServer::determine_encoding(&requ),
887
1
            (ContentEncoding::Identity, false)
888
        );
889
1
    }
890

            
891
    #[test]
892
1
    fn match_endpoint() {
893
        /// Dummy call back that does nothing and is not even called.
894
        fn dummy(
895
            _: &Transaction,
896
            _: &Request<Incoming>,
897
        ) -> Result<Response<Vec<DocumentId>>, Box<dyn std::error::Error + Send>> {
898
            todo!()
899
        }
900

            
901
1
        let endpoints: Vec<Endpoint> = vec![
902
1
            (Method::GET, "/foo/bar/baz", dummy),
903
1
            (Method::GET, "/foo/*/baz", dummy),
904
1
            (Method::GET, "/bar/*", dummy),
905
1
            (Method::GET, "/", dummy),
906
        ];
907

            
908
        /// Basically a domain specific [`assert_eq`] that works by comparing
909
        /// pointers instead of a deep comparison.
910
        macro_rules! check_match {
911
            ($uri:literal, $endpoint:literal) => {
912
                let requ = Request::builder().uri($uri).body(String::new()).unwrap();
913
                let left: *const Endpoint = HttpServer::match_endpoint(&endpoints, &requ).unwrap();
914
                let right: *const Endpoint = &endpoints[$endpoint];
915
                assert_eq!(left, right);
916
            };
917
        }
918

            
919
        macro_rules! check_no_match {
920
            ($uri:literal) => {
921
                let requ = Request::builder().uri($uri).body(String::new()).unwrap();
922
                assert!(HttpServer::match_endpoint(&endpoints, &requ).is_none());
923
            };
924
        }
925

            
926
1
        check_match!("/foo/bar/baz", 0);
927
1
        check_match!("/foo/bar/baz.z", 0);
928
1
        check_no_match!("/foo/bar/baz1");
929
1
        check_no_match!("/foo/bar/baz/");
930

            
931
1
        check_match!("/foo/I_DONT_CARE/baz", 1);
932
1
        check_match!("/foo/I_DONT_CARE/baz.z", 1);
933
1
        check_match!("/foo//baz", 1);
934
1
        check_no_match!("/foo/");
935
1
        check_no_match!("/foo/foo");
936
1
        check_no_match!("/foo/foo/foo");
937

            
938
1
        check_match!("/bar/", 2);
939
1
        check_match!("/bar/.z", 2);
940
1
        check_match!("/bar/foo", 2);
941
1
        check_match!("/bar/foo.z", 2);
942
1
        check_no_match!("/bar/foo/");
943
1
        check_no_match!("/bar/foo/foo");
944

            
945
1
        check_match!("/", 3);
946
1
        check_match!("/.z", 3);
947
1
    }
948

            
949
    #[test]
950
    #[ignore] // // TODO DIRMIRROR test is broken, fails after cargo update
951
    fn map_encoding() {
952
        let pool = create_test_db_pool();
953

            
954
        let data = [
955
            (ContentEncoding::Identity, *IDENTITY_DOCID),
956
            (ContentEncoding::Deflate, *DEFLATE_DOCID),
957
            (ContentEncoding::Gzip, *GZIP_DOCID),
958
            (ContentEncoding::XZstd, *XZ_STD_DOCID),
959
            (ContentEncoding::XTorLzma, *X_TOR_LZMA_DOCID),
960
        ];
961

            
962
        database::read_tx(&pool, |tx| {
963
            for (encoding, compressed_docid) in data {
964
                println!("{encoding}");
965
                assert_eq!(
966
                    HttpServer::map_encoding(tx, *IDENTITY_DOCID, encoding).unwrap(),
967
                    compressed_docid
968
                );
969
            }
970
        })
971
        .unwrap();
972
    }
973

            
974
    #[tokio::test]
975
    #[ignore] // // TODO DIRMIRROR test is broken, fails after cargo update
976
    async fn basic_http_server() {
977
        // This is a stupid clippy false positive.
978
        #[allow(clippy::unnecessary_wraps)]
979
        fn identity(
980
            _tx: &Transaction<'_>,
981
            _requ: &Request<Incoming>,
982
        ) -> Result<Response<Vec<DocumentId>>, Box<dyn std::error::Error + Send>> {
983
            Ok(Response::new(vec![*IDENTITY_DOCID]))
984
        }
985

            
986
        let pool = create_test_db_pool();
987
        let server = HttpServer::new(
988
            vec![(Method::GET, "/tor/status-vote/current/consensus", identity)],
989
            pool,
990
        );
991

            
992
        let listener = TcpListener::bind("[::1]:0").await.unwrap();
993
        let local_addr = listener.local_addr().unwrap();
994
        let listener = TcpListenerStream::new(listener);
995

            
996
        task::spawn(async move {
997
            server.serve(listener).await.unwrap();
998
        });
999

            
        let stream = TcpStream::connect(local_addr).await.unwrap();
        let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
            .await
            .unwrap();
        task::spawn(async move {
            if let Err(e) = conn.await {
                println!("Connection failed: {e:?}");
            }
        });
        // Perform a simple request.
        // TODO: Put this into one function for making requests or use reqwest.
        let requ = Request::builder()
            .version(Version::HTTP_11)
            .uri("/tor/status-vote/current/consensus")
            .body(Empty::<Bytes>::new())
            .unwrap();
        let mut resp = sender.send_request(requ).await.unwrap();
        let mut resp_body: Vec<u8> = Vec::new();
        while let Some(next) = resp.frame().await {
            resp_body.append(&mut next.unwrap().data_ref().unwrap().as_ref().to_vec());
        }
        assert_eq!(IDENTITY, String::from_utf8_lossy(&resp_body));
        // Perform a ".z" request.
        let requ = Request::builder()
            .version(Version::HTTP_11)
            .uri("/tor/status-vote/current/consensus.z")
            .body(Empty::<Bytes>::new())
            .unwrap();
        let mut resp = sender.send_request(requ).await.unwrap();
        let mut resp_body: Vec<u8> = Vec::new();
        while let Some(next) = resp.frame().await {
            resp_body.append(&mut next.unwrap().data_ref().unwrap().as_ref().to_vec());
        }
        let mut decoder = DeflateDecoder::new(Vec::new());
        decoder.write_all(&resp_body).unwrap();
        let decoded_resp = decoder.finish().unwrap();
        assert_eq!(IDENTITY, String::from_utf8_lossy(&decoded_resp));
    }
}