1
//! Stream handling logic
2

            
3
mod directory;
4
pub(crate) mod dns;
5
mod exit;
6

            
7
use dns::resolver::DnsResolver;
8

            
9
use tor_error::warn_report;
10
use tor_proto::circuit::{CircHopSyncView, UniqId};
11
use tor_proto::relay::CircuitIncomingStreamReceiver;
12
use tor_proto::stream::{
13
    IncomingStream, IncomingStreamRequest, IncomingStreamRequestContext,
14
    IncomingStreamRequestDisposition, IncomingStreamRequestFilter,
15
};
16
use tor_rtcompat::{Runtime, SpawnExt as _};
17

            
18
use futures::channel::mpsc;
19
use futures::{Stream, StreamExt as _};
20
use tracing::debug;
21

            
22
// TODO(#2570): once we dust settles on the implementation,
23
// we need to factor this out of the client module.
24
use tor_proto::client::stream::DataStream;
25

            
26
/// Filter callback used to enforce early requirements on streams,
27
/// acting as an [`IncomingStreamRequestFilter`].
28
#[derive(Clone, Debug, Default)]
29
pub(crate) struct RequestFilter {
30
    // TODO(relay): implement
31
}
32

            
33
impl IncomingStreamRequestFilter for RequestFilter {
34
    fn disposition(
35
        &mut self,
36
        _ctx: &IncomingStreamRequestContext<'_>,
37
        _circ: &CircHopSyncView<'_>,
38
    ) -> tor_proto::Result<IncomingStreamRequestDisposition> {
39
        // TODO(relay): enforce the checks mentioned in relay-streams.md,
40
        // especially DoSStreamCreationRate
41
        Ok(IncomingStreamRequestDisposition::Accept)
42
    }
43
}
44

            
45
/// Handle all the incoming streams arriving on all the circuits
46
pub(crate) async fn handle_incoming_streams<R: Runtime>(
47
    runtime: R,
48
    begin_dir_tx: mpsc::Sender<tor_proto::Result<DataStream>>,
49
    mut stream_rx: CircuitIncomingStreamReceiver,
50
    resolver: DnsResolver,
51
) -> anyhow::Result<void::Void> {
52
    while let Some((circ_uniq_id, stream)) = stream_rx.next().await {
53
        // Each circuit gets its own stream-handling task
54
        let rt = runtime.clone();
55
        let begin_dir_tx = begin_dir_tx.clone();
56
        runtime.spawn(handle_circuit_incoming_streams(
57
            rt,
58
            circ_uniq_id,
59
            stream,
60
            begin_dir_tx,
61
            resolver.clone(),
62
        ))?;
63
    }
64

            
65
    Err(anyhow::anyhow!("stream handling task exited"))
66
}
67

            
68
/// Handle all the incoming stream requests (BEGIN, BEGIN_DIR, or RESOLVE)
69
/// arriving on a particular circuit.
70
async fn handle_circuit_incoming_streams<R: Runtime>(
71
    runtime: R,
72
    circ_uniq_id: UniqId,
73
    mut stream: impl Stream<Item = IncomingStream> + Unpin,
74
    begin_dir_tx: mpsc::Sender<tor_proto::Result<DataStream>>,
75
    resolver: DnsResolver,
76
) {
77
    while let Some(tor_stream) = stream.next().await {
78
        let begin_dir_tx = begin_dir_tx.clone();
79

            
80
        let resolver = resolver.clone();
81
        // Spawn a new task for each individual stream
82
        let runtime_clone = runtime.clone();
83
        if let Err(e) = runtime.spawn(async move {
84
            let res = match tor_stream.request() {
85
                IncomingStreamRequest::Begin(_) => {
86
                    debug!(%circ_uniq_id, stream_id = %tor_stream.stream_id(), "Incoming BEGIN stream request");
87
                    exit::handle_begin(runtime_clone, tor_stream, resolver.clone()).await
88
                }
89
                IncomingStreamRequest::BeginDir(_) => {
90
                    debug!(%circ_uniq_id, stream_id = %tor_stream.stream_id(), "Incoming BEGIN_DIR stream request");
91
                    directory::handle_begin_dir(tor_stream, begin_dir_tx).await
92
                }
93
                IncomingStreamRequest::Resolve(_) => {
94
                    debug!(%circ_uniq_id, stream_id = %tor_stream.stream_id(), "Incoming RESOLVE stream request");
95
                    dns::handle_resolve(tor_stream, resolver.clone()).await
96
                }
97
                s => Err(anyhow::anyhow!("unknown stream request kind {s:?}")),
98
            };
99

            
100
            if let Err(e) = res {
101
                warn_report!(e, "Could not handle incoming stream");
102
            }
103
        }) {
104
            warn_report!(e, "Failed to launch incoming stream handler task");
105
        }
106
    }
107
}