Skip to main content

stem/
socket.rs

1use std::net::{IpAddr, SocketAddr};
2use std::path::{Path, PathBuf};
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::{Arc, Mutex};
5use std::time::SystemTime;
6
7use tokio::io::{
8    AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader,
9    ReadHalf, WriteHalf,
10};
11use tokio::net::TcpStream;
12use tokio::sync::Notify;
13
14use crate::error::{Error, Result};
15use crate::response::{
16    ControlMessage, MAX_LINE_LENGTH, MessageBuilder, format_for_sending,
17};
18
19const SECRET_COMMANDS: [&str; 4] = [
20    "AUTHENTICATE",
21    "ADD_ONION",
22    "ONION_CLIENT_AUTH_ADD",
23    "AUTHCHALLENGE",
24];
25
26type BoxedStream = Box<dyn AsyncStream>;
27
28trait AsyncStream: AsyncRead + AsyncWrite + Send + Unpin {}
29
30impl<T: AsyncRead + AsyncWrite + Send + Unpin> AsyncStream for T {}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum ControlTarget {
34    Port(SocketAddr),
35    File(PathBuf),
36}
37
38struct Connection {
39    reader: tokio::sync::Mutex<BufReader<ReadHalf<BoxedStream>>>,
40    writer: tokio::sync::Mutex<WriteHalf<BoxedStream>>,
41    closed: Notify,
42    alive: AtomicBool,
43}
44
45pub struct ControlSocket {
46    target: ControlTarget,
47    connection: Mutex<Option<Arc<Connection>>>,
48    connection_time: Mutex<SystemTime>,
49}
50
51impl ControlSocket {
52    pub fn port(address: IpAddr, port: u16) -> Self {
53        Self::new(ControlTarget::Port(SocketAddr::new(address, port)))
54    }
55
56    pub fn file(path: impl Into<PathBuf>) -> Self {
57        Self::new(ControlTarget::File(path.into()))
58    }
59
60    fn new(target: ControlTarget) -> Self {
61        Self {
62            target,
63            connection: Mutex::new(None),
64            connection_time: Mutex::new(SystemTime::now()),
65        }
66    }
67
68    pub async fn connect_to(target: ControlTarget) -> Result<Self> {
69        let socket = Self::new(target);
70        socket.connect().await?;
71        Ok(socket)
72    }
73
74    pub fn target(&self) -> &ControlTarget {
75        &self.target
76    }
77
78    pub fn socket_path(&self) -> Option<&Path> {
79        match &self.target {
80            ControlTarget::File(path) => Some(path),
81            ControlTarget::Port(_) => None,
82        }
83    }
84
85    pub fn control_port(&self) -> Option<SocketAddr> {
86        match &self.target {
87            ControlTarget::Port(address) => Some(*address),
88            ControlTarget::File(_) => None,
89        }
90    }
91
92    pub fn is_localhost(&self) -> bool {
93        match &self.target {
94            ControlTarget::Port(address) => address.ip().is_loopback(),
95            ControlTarget::File(_) => true,
96        }
97    }
98
99    pub fn is_alive(&self) -> bool {
100        self.current()
101            .is_some_and(|connection| connection.alive.load(Ordering::SeqCst))
102    }
103
104    pub fn connection_time(&self) -> SystemTime {
105        *self.connection_time.lock().unwrap()
106    }
107
108    fn current(&self) -> Option<Arc<Connection>> {
109        self.connection.lock().unwrap().clone()
110    }
111
112    async fn open_stream(&self) -> Result<BoxedStream> {
113        match &self.target {
114            ControlTarget::Port(address) => {
115                let stream = TcpStream::connect(address)
116                    .await
117                    .map_err(|error| Error::Socket(error.to_string()))?;
118                Ok(Box::new(stream))
119            }
120            #[cfg(unix)]
121            ControlTarget::File(path) => {
122                let stream = tokio::net::UnixStream::connect(path)
123                    .await
124                    .map_err(|error| Error::Socket(error.to_string()))?;
125                Ok(Box::new(stream))
126            }
127            #[cfg(not(unix))]
128            ControlTarget::File(_) => Err(Error::Socket(
129                "Unix domain sockets aren't supported on this platform".to_string(),
130            )),
131        }
132    }
133
134    pub async fn connect(&self) -> Result<()> {
135        self.close().await;
136        let stream = self.open_stream().await?;
137        let (reader, writer) = tokio::io::split(stream);
138        let connection = Arc::new(Connection {
139            reader: tokio::sync::Mutex::new(BufReader::new(reader)),
140            writer: tokio::sync::Mutex::new(writer),
141            closed: Notify::new(),
142            alive: AtomicBool::new(true),
143        });
144        *self.connection.lock().unwrap() = Some(connection);
145        *self.connection_time.lock().unwrap() = SystemTime::now();
146        Ok(())
147    }
148
149    pub fn abort(&self) {
150        if let Some(connection) = self.connection.lock().unwrap().take() {
151            connection.alive.store(false, Ordering::SeqCst);
152            connection.closed.notify_one();
153        }
154    }
155
156    pub async fn close(&self) {
157        let Some(connection) = self.connection.lock().unwrap().take() else {
158            return;
159        };
160        connection.alive.store(false, Ordering::SeqCst);
161        connection.closed.notify_one();
162        let _ = connection.writer.lock().await.shutdown().await;
163        *self.connection_time.lock().unwrap() = SystemTime::now();
164    }
165
166    fn drop_connection(&self, dead: &Arc<Connection>) {
167        dead.alive.store(false, Ordering::SeqCst);
168        let mut current = self.connection.lock().unwrap();
169        if current
170            .as_ref()
171            .is_some_and(|active| Arc::ptr_eq(active, dead))
172        {
173            *current = None;
174            *self.connection_time.lock().unwrap() = SystemTime::now();
175        }
176    }
177
178    pub async fn send(&self, message: &str) -> Result<()> {
179        self.send_raw(&format_for_sending(message)).await?;
180        log_sent(message);
181        Ok(())
182    }
183
184    pub async fn send_raw(&self, wire_content: &str) -> Result<()> {
185        if wire_content.contains('\0') {
186            return Err(Error::invalid_input(
187                "Control messages can't contain NUL bytes",
188            ));
189        }
190        let Some(connection) = self.current() else {
191            return Err(Error::SocketClosed);
192        };
193        let mut writer = connection.writer.lock().await;
194        let result = async {
195            writer.write_all(wire_content.as_bytes()).await?;
196            writer.flush().await
197        }
198        .await;
199        drop(writer);
200        result.map_err(|error| {
201            log::info!("Failed to send: {error}");
202            self.drop_connection(&connection);
203            match error.kind() {
204                std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset => {
205                    Error::SocketClosed
206                }
207                _ => Error::Socket(error.to_string()),
208            }
209        })
210    }
211
212    pub async fn recv(&self) -> Result<ControlMessage> {
213        let Some(connection) = self.current() else {
214            return Err(Error::SocketClosed);
215        };
216        let mut reader = connection.reader.lock().await;
217        let outcome = tokio::select! {
218            biased;
219            () = connection.closed.notified() => Err(Error::SocketClosed),
220            message = receive_message(&mut *reader) => message,
221        };
222        drop(reader);
223        if matches!(outcome, Err(Error::SocketClosed) | Err(Error::Io(_))) {
224            self.drop_connection(&connection);
225        }
226        outcome.map_err(|error| match error {
227            Error::Io(io_error) => Error::Socket(io_error.to_string()),
228            other => other,
229        })
230    }
231}
232
233impl Drop for ControlSocket {
234    fn drop(&mut self) {
235        if let Some(connection) = self.connection.lock().unwrap().take() {
236            connection.alive.store(false, Ordering::SeqCst);
237            connection.closed.notify_one();
238        }
239    }
240}
241
242fn log_sent(message: &str) {
243    if !log::log_enabled!(log::Level::Trace) {
244        return;
245    }
246    let keyword = message.split_whitespace().next().unwrap_or_default();
247    let is_secret = SECRET_COMMANDS
248        .iter()
249        .any(|secret| keyword.eq_ignore_ascii_case(secret));
250    match is_secret {
251        true => log::trace!("Sent to tor: {keyword} <redacted>"),
252        false => log::trace!("Sent to tor: {}", message.replace("\r\n", "\n").trim_end()),
253    }
254}
255
256async fn read_bounded_line<R: AsyncBufReadExt + Unpin>(
257    reader: &mut R,
258) -> Result<Vec<u8>> {
259    let mut line = Vec::new();
260    let limit = (MAX_LINE_LENGTH + 1) as u64;
261    let read = (&mut *reader)
262        .take(limit)
263        .read_until(b'\n', &mut line)
264        .await;
265    match read {
266        Ok(0) => {
267            log::debug!(
268                "Error while receiving a control message (SocketClosed): empty socket \
269                content"
270            );
271            Err(Error::SocketClosed)
272        }
273        Ok(_) if line.last() == Some(&b'\n') => Ok(line),
274        Ok(_) if line.len() > MAX_LINE_LENGTH => Err(Error::protocol(
275            "Control message line exceeded the length limit",
276        )),
277        Ok(_) => Err(Error::SocketClosed),
278        Err(error) => {
279            log::debug!(
280                "Error while receiving a control message (SocketClosed): {error}"
281            );
282            Err(Error::SocketClosed)
283        }
284    }
285}
286
287pub async fn receive_message<R: AsyncBufReadExt + Unpin>(
288    reader: &mut R,
289) -> Result<ControlMessage> {
290    let mut builder = MessageBuilder::default();
291    loop {
292        let line = read_bounded_line(reader).await?;
293        if let Some(message) = builder.push_line(&line)? {
294            log_received(&message);
295            return Ok(message);
296        }
297    }
298}
299
300fn redact_line(line: &str) -> String {
301    let words: Vec<String> = line
302        .split(' ')
303        .map(|word| match word.split_once('=') {
304            Some((key @ ("PrivateKey" | "ClientAuth"), _)) => format!("{key}=<redacted>"),
305            _ => match word.starts_with("x25519:") {
306                true => "x25519:<redacted>".to_string(),
307                false => word.to_string(),
308            },
309        })
310        .collect();
311    let body = words.join(" ");
312    match body.split_once('=') {
313        Some((key @ ("250-PrivateKey" | "250-ClientAuth"), _)) => {
314            format!("{key}=<redacted>")
315        }
316        _ => body,
317    }
318}
319
320fn log_received(message: &ControlMessage) {
321    if !log::log_enabled!(log::Level::Trace) {
322        return;
323    }
324    let content = message.raw_content().replace("\r\n", "\n");
325    let redacted: Vec<String> = content.trim_end().split('\n').map(redact_line).collect();
326    let lines: Vec<&str> = redacted.iter().map(String::as_str).collect();
327    match lines.len() {
328        0..=2 => log::trace!("Received from tor: {}", lines.join("\\n")),
329        count if count > 10 => log::trace!(
330            "Received from tor:\n{}\n... {} more lines...",
331            lines[..10].join("\n"),
332            count - 10
333        ),
334        _ => log::trace!("Received from tor:\n{}", lines.join("\n")),
335    }
336}