tor_interface/
arti_process.rs

1// standard
2use std::fs;
3#[cfg(unix)]
4use std::os::unix::fs::PermissionsExt;
5use std::fs::File;
6use std::io::{BufRead, BufReader, Write};
7use std::ops::Drop;
8use std::process::{Child, ChildStdout, Command, Stdio};
9use std::path::Path;
10use std::sync::{Mutex, Weak};
11
12#[derive(thiserror::Error, Debug)]
13pub enum Error {
14    #[error("provided arti bin path '{0}' must be an absolute path")]
15    ArtiBinPathNotAbsolute(String),
16
17    #[error("provided data directory '{0}' must be an absolute path")]
18    ArtiDataDirectoryPathNotAbsolute(String),
19
20    #[error("failed to create data directory: {0}")]
21    ArtiDataDirectoryCreationFailed(#[source] std::io::Error),
22
23    #[error("file exists in provided data directory path '{0}'")]
24    ArtiDataDirectoryPathExistsAsFile(String),
25
26    #[error("unable to set permissions for data directory: {0}")]
27    ArtiDataDirectorySetPermissionsFailed(#[source] std::io::Error),
28
29    #[error("failed to create arti.toml file: {0}")]
30    ArtiTomlFileCreationFailed(#[source] std::io::Error),
31
32    #[error("failed to write arti.toml file: {0}")]
33    ArtiTomlFileWriteFailed(#[source] std::io::Error),
34
35    #[error("failed to create rpc.toml file: {0}")]
36    RpcTomlFileCreationFailed(#[source] std::io::Error),
37
38    #[error("failed to write rpc.toml file: {0}")]
39    RpcTomlFileWriteFailed(#[source] std::io::Error),
40
41    #[error("failed to start arti process: {0}")]
42    ArtiProcessStartFailed(#[source] std::io::Error),
43
44    #[error("unable to take arti process stdout")]
45    ArtiProcessStdoutTakeFailed(),
46
47    #[error("failed to spawn arti process stdout read thread: {0}")]
48    ArtiStdoutReadThreadSpawnFailed(#[source] std::io::Error),
49}
50
51pub(crate) struct ArtiProcess {
52    process: Child,
53    connect_string: String,
54}
55
56impl ArtiProcess {
57    pub fn new(arti_bin_path: &Path, data_directory: &Path, stdout_lines: Weak<Mutex<Vec<String>>>) -> Result<Self, Error> {
58        // verify provided paths are absolute
59        if arti_bin_path.is_relative() {
60            return Err(Error::ArtiBinPathNotAbsolute(format!(
61                "{}",
62                arti_bin_path.display()
63            )));
64        }
65        if data_directory.is_relative() {
66            return Err(Error::ArtiDataDirectoryPathNotAbsolute(format!(
67                "{}",
68                data_directory.display()
69            )));
70        }
71
72        // create data directory if it doesn't exist
73        if !data_directory.exists() {
74            fs::create_dir_all(data_directory).map_err(Error::ArtiDataDirectoryCreationFailed)?;
75        } else if data_directory.is_file() {
76            return Err(Error::ArtiDataDirectoryPathExistsAsFile(format!(
77                "{}",
78                data_directory.display()
79            )));
80        }
81
82        // arti data directory must not be world-writable on unix platforms when using a unix domain socket endpoint
83        if cfg!(unix) {
84            let perms = PermissionsExt::from_mode(0o700);
85            fs::set_permissions(data_directory, perms).map_err(Error::ArtiDataDirectorySetPermissionsFailed)?;
86        }
87
88        // construct paths to arti files file
89        let arti_toml = data_directory.join("arti.toml").display().to_string();
90        let cache_dir = data_directory.join("cache").display().to_string();
91        let state_dir = data_directory.join("state").display().to_string();
92
93        let mut arti_toml_content = format!("\
94        [rpc]\n\
95        enable = true\n\n\
96        [rpc.listen.user-default]\n\
97        enable = false\n\n\
98        [rpc.listen.system-default]\n\
99        enable = false\n\n\
100        [storage]\n\
101        cache_dir = \"{cache_dir}\"\n\
102        state_dir = \"{state_dir}\"\n\n\
103        [storage.keystore]\n\
104        enabled = true\n\n\
105        [storage.keystore.primary]\n\
106        kind = \"ephemeral\"\n\n\
107        [storage.permissions]\n\
108        dangerously_trust_everyone = true\n\n\
109        ");
110
111        let connect_string = if cfg!(unix) {
112            // use domain socket for unix
113            let unix_rpc_toml_path = data_directory.join("rpc.toml").display().to_string();
114
115            arti_toml_content.push_str(format!("\
116            [rpc.listen.unix-point]\n\
117            enable = true\n\
118            file = \"{unix_rpc_toml_path}\"\n\n\
119            ").as_str());
120
121            let socket_path = data_directory.join("rpc.socket").display().to_string();
122
123            let unix_rpc_toml_content = format!("\
124            [connect]\n\
125            socket = \"unix:{socket_path}\"\n\
126            auth = \"none\"\n\
127            ");
128
129            let mut unix_rpc_toml_file =
130                File::create(&unix_rpc_toml_path).map_err(Error::RpcTomlFileCreationFailed)?;
131            unix_rpc_toml_file
132                .write_all(unix_rpc_toml_content.as_bytes())
133                .map_err(Error::RpcTomlFileWriteFailed)?;
134
135            unix_rpc_toml_path
136        } else {
137            // use tcp socket everywhere else
138            let tcp_rpc_toml_path = data_directory.join("rpc.toml").display().to_string();
139
140            arti_toml_content.push_str(format!("\
141            [rpc.listen.tcp-point]\n\
142            enable = true\n\
143            file = \"{tcp_rpc_toml_path}\"\n\n\
144            ").as_str());
145
146            let cookie_path = data_directory.join("rpc.cookie").display().to_string();
147
148            const RPC_PORT: u16 = 18929;
149
150            let tcp_rpc_toml_content = format!("\
151            [connect]\n\
152            socket = \"inet:127.0.0.1:{RPC_PORT}\"\n\
153            auth = {{ cookie = {{ path = \"{cookie_path}\" }} }}\n\
154            ");
155
156            let mut tcp_rpc_toml_file =
157                File::create(&tcp_rpc_toml_path).map_err(Error::RpcTomlFileCreationFailed)?;
158            tcp_rpc_toml_file
159                .write_all(tcp_rpc_toml_content.as_bytes())
160                .map_err(Error::RpcTomlFileWriteFailed)?;
161
162            tcp_rpc_toml_path
163        };
164
165        let mut arti_toml_file =
166            File::create(&arti_toml).map_err(Error::ArtiTomlFileCreationFailed)?;
167        arti_toml_file
168            .write_all(arti_toml_content.as_bytes())
169            .map_err(Error::ArtiTomlFileWriteFailed)?;
170
171        let mut process = Command::new(arti_bin_path.as_os_str())
172            .stdout(Stdio::piped())
173            .stdin(Stdio::null())
174            .stderr(Stdio::null())
175            // set working directory to data directory
176            .current_dir(data_directory)
177            // proxy subcommand
178            .arg("proxy")
179            // point to our above written arti.toml file
180            .arg("--config")
181            .arg(arti_toml)
182            .spawn()
183            .map_err(Error::ArtiProcessStartFailed)?;
184
185        // spawn a task to read stdout lines and forward to list
186        let stdout = BufReader::new(match process.stdout.take() {
187            Some(stdout) => stdout,
188            None => return Err(Error::ArtiProcessStdoutTakeFailed()),
189        });
190        std::thread::Builder::new()
191            .name("arti_stdout_reader".to_string())
192            .spawn(move || {
193                ArtiProcess::read_stdout_task(&stdout_lines, stdout);
194            })
195            .map_err(Error::ArtiStdoutReadThreadSpawnFailed)?;
196
197        Ok(ArtiProcess { process, connect_string })
198    }
199
200    pub fn connect_string(&self) -> &str {
201        self.connect_string.as_str()
202    }
203
204    fn read_stdout_task(
205        stdout_lines: &std::sync::Weak<Mutex<Vec<String>>>,
206        mut stdout: BufReader<ChildStdout>,
207    ) {
208        while let Some(stdout_lines) = stdout_lines.upgrade() {
209            let mut line = String::default();
210            // read line
211            if stdout.read_line(&mut line).is_ok() {
212                // remove trailing '\n'
213                line.pop();
214                // then acquire the lock on the line buffer
215                let mut stdout_lines = match stdout_lines.lock() {
216                    Ok(stdout_lines) => stdout_lines,
217                    Err(_) => unreachable!(),
218                };
219                stdout_lines.push(line);
220            }
221        }
222    }
223}
224
225impl Drop for ArtiProcess {
226    fn drop(&mut self) {
227        let _ = self.process.kill();
228    }
229}