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
|
use std::{
collections::HashMap,
path::Path,
time::{Duration, SystemTime},
};
use crate::mullvad_daemon::ServiceStatus;
use super::*;
const INSTALL_TIMEOUT: Duration = Duration::from_secs(300);
const REBOOT_TIMEOUT: Duration = Duration::from_secs(30);
const LOG_LEVEL_TIMEOUT: Duration = Duration::from_secs(60);
#[derive(Debug, Clone)]
pub struct ServiceClient {
connection_handle: transport::ConnectionHandle,
client: service::ServiceClient,
}
impl ServiceClient {
pub fn new(
connection_handle: transport::ConnectionHandle,
transport: tarpc::transport::channel::UnboundedChannel<
tarpc::Response<service::ServiceResponse>,
tarpc::ClientMessage<service::ServiceRequest>,
>,
) -> Self {
Self {
connection_handle,
client: super::service::ServiceClient::new(tarpc::client::Config::default(), transport)
.spawn(),
}
}
/// Install app package.
pub async fn install_app(&self, package_path: package::Package) -> Result<(), Error> {
let mut ctx = tarpc::context::current();
ctx.deadline = SystemTime::now().checked_add(INSTALL_TIMEOUT).unwrap();
self.client
.install_app(ctx, package_path)
.await
.map_err(Error::Tarpc)?
}
/// Remove app package.
pub async fn uninstall_app(&self, env: HashMap<String, String>) -> Result<(), Error> {
let mut ctx = tarpc::context::current();
ctx.deadline = SystemTime::now().checked_add(INSTALL_TIMEOUT).unwrap();
self.client.uninstall_app(ctx, env).await?
}
/// Execute a program with additional environment-variables set.
pub async fn exec_env<
I: IntoIterator<Item = T>,
M: IntoIterator<Item = (K, T)>,
T: AsRef<str>,
K: AsRef<str>,
>(
&self,
path: T,
args: I,
env: M,
) -> Result<ExecResult, Error> {
let mut ctx = tarpc::context::current();
ctx.deadline = SystemTime::now().checked_add(INSTALL_TIMEOUT).unwrap();
self.client
.exec(
ctx,
path.as_ref().to_string(),
args.into_iter().map(|v| v.as_ref().to_string()).collect(),
env.into_iter()
.map(|(k, v)| (k.as_ref().to_string(), v.as_ref().to_string()))
.collect(),
)
.await?
}
/// Execute a program.
pub async fn exec<I: IntoIterator<Item = T>, T: AsRef<str>>(
&self,
path: T,
args: I,
) -> Result<ExecResult, Error> {
let env: [(&str, T); 0] = [];
self.exec_env(path, args, env).await
}
/// Get the output of the runners stdout logs since the last time this function was called.
/// Block if there is no output until some output is provided by the runner.
pub async fn poll_output(&self) -> Result<Vec<logging::Output>, Error> {
self.client.poll_output(tarpc::context::current()).await?
}
/// Get the output of the runners stdout logs since the last time this function was called.
/// Block if there is no output until some output is provided by the runner.
pub async fn try_poll_output(&self) -> Result<Vec<logging::Output>, Error> {
self.client
.try_poll_output(tarpc::context::current())
.await?
}
pub async fn get_mullvad_app_logs(&self) -> Result<logging::LogOutput, Error> {
self.client
.get_mullvad_app_logs(tarpc::context::current())
.await
.map_err(Error::Tarpc)
}
/// Return the OS of the guest.
pub async fn get_os(&self) -> Result<meta::Os, Error> {
self.client
.get_os(tarpc::context::current())
.await
.map_err(Error::Tarpc)
}
/// Wait for the Mullvad service to enter a specified state. The state is inferred from the presence
/// of a named pipe or UDS, not the actual system service state.
pub async fn mullvad_daemon_wait_for_state(
&self,
accept_state_fn: impl Fn(ServiceStatus) -> bool,
) -> Result<mullvad_daemon::ServiceStatus, Error> {
const MAX_ATTEMPTS: usize = 10;
const POLL_INTERVAL: Duration = Duration::from_secs(3);
for _ in 0..MAX_ATTEMPTS {
let last_state = self.mullvad_daemon_get_status().await?;
match accept_state_fn(last_state) {
true => return Ok(last_state),
false => tokio::time::sleep(POLL_INTERVAL).await,
}
}
Err(Error::Timeout)
}
/// Return status of the system service. The state is inferred from the presence of
/// a named pipe or UDS, not the actual system service state.
pub async fn mullvad_daemon_get_status(&self) -> Result<mullvad_daemon::ServiceStatus, Error> {
self.client
.mullvad_daemon_get_status(tarpc::context::current())
.await
.map_err(Error::Tarpc)
}
/// Returns all Mullvad app files, directories, and other data found on the system.
pub async fn find_mullvad_app_traces(&self) -> Result<Vec<AppTrace>, Error> {
self.client
.find_mullvad_app_traces(tarpc::context::current())
.await?
}
/// Returns path of Mullvad app cache directorie on the test runner.
pub async fn find_mullvad_app_cache_dir(&self) -> Result<PathBuf, Error> {
self.client
.get_mullvad_app_cache_dir(tarpc::context::current())
.await?
}
/// Send TCP packet
pub async fn send_tcp(
&self,
interface: Option<String>,
bind_addr: SocketAddr,
destination: SocketAddr,
) -> Result<(), Error> {
self.client
.send_tcp(tarpc::context::current(), interface, bind_addr, destination)
.await?
}
/// Send UDP packet
pub async fn send_udp(
&self,
interface: Option<String>,
bind_addr: SocketAddr,
destination: SocketAddr,
) -> Result<(), Error> {
self.client
.send_udp(tarpc::context::current(), interface, bind_addr, destination)
.await?
}
/// Send ICMP
pub async fn send_ping(
&self,
interface: Option<String>,
destination: IpAddr,
) -> Result<(), Error> {
self.client
.send_ping(tarpc::context::current(), interface, destination)
.await?
}
/// Fetch the current location.
pub async fn geoip_lookup(&self, mullvad_host: String) -> Result<AmIMullvad, Error> {
self.client
.geoip_lookup(tarpc::context::current(), mullvad_host)
.await?
}
/// Returns the IP of the given interface.
pub async fn get_interface_ip(&self, interface: String) -> Result<IpAddr, Error> {
self.client
.get_interface_ip(tarpc::context::current(), interface)
.await?
}
/// Returns the name of the default non-tunnel interface
pub async fn get_default_interface(&self) -> Result<String, Error> {
self.client
.get_default_interface(tarpc::context::current())
.await?
}
pub async fn resolve_hostname(&self, hostname: String) -> Result<Vec<SocketAddr>, Error> {
self.client
.resolve_hostname(tarpc::context::current(), hostname)
.await?
}
/// Restarts the app.
///
/// Shuts down a running app, making it disconnect from any current tunnel
/// connection before starting the app again.
///
/// # Note
/// This function will return *after* the app is running again, thus
/// blocking execution until then.
pub async fn restart_mullvad_daemon(&self) -> Result<(), Error> {
let _ = self
.client
.restart_mullvad_daemon(tarpc::context::current())
.await?;
Ok(())
}
/// Stop the app.
///
/// Shuts down a running app, making it disconnect from any current tunnel
/// connection and making it write to caches.
///
/// # Note
/// This function will return *after* the app has been stopped, thus
/// blocking execution until then.
pub async fn stop_mullvad_daemon(&self) -> Result<(), Error> {
let _ = self
.client
.stop_mullvad_daemon(tarpc::context::current())
.await?;
Ok(())
}
/// Start the app.
///
/// # Note
/// This function will return *after* the app has been started, thus
/// blocking execution until then.
pub async fn start_mullvad_daemon(&self) -> Result<(), Error> {
let _ = self
.client
.start_mullvad_daemon(tarpc::context::current())
.await?;
Ok(())
}
pub async fn set_daemon_log_level(
&self,
verbosity_level: mullvad_daemon::Verbosity,
) -> Result<(), Error> {
let mut ctx = tarpc::context::current();
ctx.deadline = SystemTime::now().checked_add(LOG_LEVEL_TIMEOUT).unwrap();
self.client
.set_daemon_log_level(ctx, verbosity_level)
.await??;
self.mullvad_daemon_wait_for_state(|state| state == ServiceStatus::Running)
.await?;
Ok(())
}
pub async fn set_daemon_environment(&self, env: HashMap<String, String>) -> Result<(), Error> {
let mut ctx = tarpc::context::current();
ctx.deadline = SystemTime::now().checked_add(LOG_LEVEL_TIMEOUT).unwrap();
self.client.set_daemon_environment(ctx, env).await??;
self.mullvad_daemon_wait_for_state(|state| state == ServiceStatus::Running)
.await?;
Ok(())
}
pub async fn copy_file(&self, src: String, dest: String) -> Result<(), Error> {
log::debug!("Copying \"{src}\" to \"{dest}\"");
self.client
.copy_file(tarpc::context::current(), src, dest)
.await?
}
pub async fn write_file(&self, dest: impl AsRef<Path>, bytes: Vec<u8>) -> Result<(), Error> {
log::debug!(
"Writing {bytes} bytes to \"{file}\"",
bytes = bytes.len(),
file = dest.as_ref().display()
);
self.client
.write_file(
tarpc::context::current(),
dest.as_ref().to_path_buf(),
bytes,
)
.await?
}
pub async fn reboot(&mut self) -> Result<(), Error> {
log::debug!("Rebooting server");
let mut ctx = tarpc::context::current();
ctx.deadline = SystemTime::now().checked_add(REBOOT_TIMEOUT).unwrap();
self.client.reboot(ctx).await??;
self.connection_handle.reset_connected_state().await;
self.connection_handle.wait_for_server().await?;
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
Ok(())
}
pub async fn make_device_json_old(&self) -> Result<(), Error> {
self.client
.make_device_json_old(tarpc::context::current())
.await?
}
}
|