-
Notifications
You must be signed in to change notification settings - Fork 386
/
Copy pathlib.rs
741 lines (649 loc) · 23.7 KB
/
lib.rs
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
#[cfg(target_os = "android")]
use futures::channel::mpsc;
use futures::Stream;
use hyper::Method;
#[cfg(target_os = "android")]
use mullvad_types::account::{PlayPurchase, PlayPurchasePaymentToken};
use mullvad_types::{
account::{AccountData, AccountToken, VoucherSubmission},
version::AppVersion,
};
use proxy::ApiConnectionMode;
use std::{
cell::Cell,
collections::BTreeMap,
future::Future,
net::{IpAddr, Ipv4Addr, SocketAddr},
ops::Deref,
path::Path,
sync::OnceLock,
};
use talpid_types::ErrorExt;
pub mod availability;
use availability::{ApiAvailability, ApiAvailabilityHandle};
pub mod rest;
mod abortable_stream;
mod https_client_with_sni;
pub mod proxy;
mod tls_stream;
#[cfg(target_os = "android")]
pub use crate::https_client_with_sni::SocketBypassRequest;
mod access;
mod address_cache;
pub mod device;
mod relay_list;
#[cfg(target_os = "ios")]
pub mod ffi;
pub use address_cache::AddressCache;
pub use device::DevicesProxy;
pub use hyper::StatusCode;
pub use relay_list::RelayListProxy;
/// Error code returned by the Mullvad API if the voucher has alreaby been used.
pub const VOUCHER_USED: &str = "VOUCHER_USED";
/// Error code returned by the Mullvad API if the voucher code is invalid.
pub const INVALID_VOUCHER: &str = "INVALID_VOUCHER";
/// Error code returned by the Mullvad API if the account token is invalid.
pub const INVALID_ACCOUNT: &str = "INVALID_ACCOUNT";
/// Error code returned by the Mullvad API if the device does not exist.
pub const DEVICE_NOT_FOUND: &str = "DEVICE_NOT_FOUND";
/// Error code returned by the Mullvad API if the access token is invalid.
pub const INVALID_ACCESS_TOKEN: &str = "INVALID_ACCESS_TOKEN";
pub const MAX_DEVICES_REACHED: &str = "MAX_DEVICES_REACHED";
pub const PUBKEY_IN_USE: &str = "PUBKEY_IN_USE";
pub const API_IP_CACHE_FILENAME: &str = "api-ip-address.txt";
const ACCOUNTS_URL_PREFIX: &str = "accounts/v1";
const APP_URL_PREFIX: &str = "app/v1";
#[cfg(target_os = "android")]
const GOOGLE_PAYMENTS_URL_PREFIX: &str = "payments/google-play/v1";
pub static API: LazyManual<ApiEndpoint> = LazyManual::new(ApiEndpoint::from_env_vars);
unsafe impl<T, F: Send> Sync for LazyManual<T, F> where OnceLock<T>: Sync {}
/// A value that is either initialized on access or explicitly.
pub struct LazyManual<T, F = fn() -> T> {
cell: OnceLock<T>,
lazy_fn: Cell<Option<F>>,
}
impl<T, F> LazyManual<T, F> {
const fn new(lazy_fn: F) -> Self {
Self {
cell: OnceLock::new(),
lazy_fn: Cell::new(Some(lazy_fn)),
}
}
/// Tries to initialize the object. An error is returned if it is
/// already initialized.
#[cfg(feature = "api-override")]
pub fn override_init(&self, val: T) -> Result<(), T> {
let _ = self.lazy_fn.take();
self.cell.set(val)
}
}
impl<T> Deref for LazyManual<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.cell.get_or_init(|| (self.lazy_fn.take().unwrap())())
}
}
/// A hostname and socketaddr to reach the Mullvad REST API over.
#[derive(Debug)]
pub struct ApiEndpoint {
/// An overriden API hostname. Initialized with the value of the environment
/// variable `MULLVAD_API_HOST` if it has been set.
///
/// Use the associated function [`Self::host`] to read this value with a
/// default fallback if `MULLVAD_API_HOST` was not set.
pub host: Option<String>,
/// An overriden API address. Initialized with the value of the environment
/// variable `MULLVAD_API_ADDR` if it has been set.
///
/// Use the associated function [`Self::address()`] to read this value with
/// a default fallback if `MULLVAD_API_ADDR` was not set.
///
/// # Note
///
/// If [`Self::address`] is populated with [`Some(SocketAddr)`], it should
/// always be respected when establishing API connections.
pub address: Option<SocketAddr>,
#[cfg(feature = "api-override")]
pub disable_address_cache: bool,
#[cfg(feature = "api-override")]
pub disable_tls: bool,
}
impl ApiEndpoint {
const API_HOST_DEFAULT: &'static str = "api.mullvad.net";
const API_IP_DEFAULT: IpAddr = IpAddr::V4(Ipv4Addr::new(45, 83, 223, 196));
const API_PORT_DEFAULT: u16 = 443;
const API_HOST_VAR: &'static str = "MULLVAD_API_HOST";
const API_ADDR_VAR: &'static str = "MULLVAD_API_ADDR";
const DISABLE_TLS_VAR: &'static str = "MULLVAD_API_DISABLE_TLS";
/// Returns the endpoint to connect to the API over.
///
/// # Panics
///
/// Panics if `MULLVAD_API_ADDR`, `MULLVAD_API_HOST` or
/// `MULLVAD_API_DISABLE_TLS` has invalid contents.
#[cfg(feature = "api-override")]
pub fn from_env_vars() -> ApiEndpoint {
let host_var = Self::read_var(ApiEndpoint::API_HOST_VAR);
let address_var = Self::read_var(ApiEndpoint::API_ADDR_VAR);
let disable_tls_var = Self::read_var(ApiEndpoint::DISABLE_TLS_VAR);
let mut api = ApiEndpoint {
host: None,
address: None,
disable_address_cache: true,
disable_tls: false,
};
match (host_var, address_var) {
(None, None) => {}
(Some(host), None) => {
use std::net::ToSocketAddrs;
log::debug!(
"{api_addr} not found. Resolving API IP address from {api_host}={host}",
api_addr = ApiEndpoint::API_ADDR_VAR,
api_host = ApiEndpoint::API_HOST_VAR
);
api.address = format!("{}:{}", host, ApiEndpoint::API_PORT_DEFAULT)
.to_socket_addrs()
.unwrap_or_else(|_| {
panic!(
"Unable to resolve API IP address from host {host}:{port}",
port = ApiEndpoint::API_PORT_DEFAULT,
)
})
.next();
}
(host, Some(address)) => {
let addr = address.parse().unwrap_or_else(|_| {
panic!(
"{api_addr}={address} is not a valid socketaddr",
api_addr = ApiEndpoint::API_ADDR_VAR,
)
});
api.address = Some(addr);
api.host = host;
}
}
if api.host.is_none() && api.address.is_none() {
if disable_tls_var.is_some() {
log::warn!(
"{disable_tls} is ignored since {api_host} and {api_addr} are not set",
disable_tls = ApiEndpoint::DISABLE_TLS_VAR,
api_host = ApiEndpoint::API_HOST_VAR,
api_addr = ApiEndpoint::API_ADDR_VAR,
);
}
} else {
api.disable_tls = disable_tls_var
.as_ref()
.map(|disable_tls| disable_tls != "0")
.unwrap_or(api.disable_tls);
log::debug!(
"Overriding API. Using {host} at {scheme}{addr}",
host = api.host(),
addr = api.address(),
scheme = if api.disable_tls {
"http://"
} else {
"https://"
}
);
}
api
}
/// Returns the endpoint to connect to the API over.
///
/// # Panics
///
/// Panics if `MULLVAD_API_ADDR`, `MULLVAD_API_HOST` or
/// `MULLVAD_API_DISABLE_TLS` has invalid contents.
#[cfg(not(feature = "api-override"))]
pub fn from_env_vars() -> ApiEndpoint {
let host_var = Self::read_var(ApiEndpoint::API_HOST_VAR);
let address_var = Self::read_var(ApiEndpoint::API_ADDR_VAR);
let disable_tls_var = Self::read_var(ApiEndpoint::DISABLE_TLS_VAR);
if host_var.is_some() || address_var.is_some() || disable_tls_var.is_some() {
log::warn!(
"These variables are ignored in production builds: {api_host}, {api_addr}, {disable_tls}",
api_host = ApiEndpoint::API_HOST_VAR,
api_addr = ApiEndpoint::API_ADDR_VAR,
disable_tls = ApiEndpoint::DISABLE_TLS_VAR
);
}
ApiEndpoint {
host: None,
address: None,
}
}
/// Read the [`Self::host`] value, falling back to
/// [`Self::API_HOST_DEFAULT`] as default value if it does not exist.
pub fn host(&self) -> &str {
self.host
.as_deref()
.unwrap_or(ApiEndpoint::API_HOST_DEFAULT)
}
/// Read the [`Self::address`] value, falling back to
/// [`Self::API_IP_DEFAULT`]:[`Self::API_PORT_DEFAULT`] as default if it
/// does not exist.
pub fn address(&self) -> SocketAddr {
self.address.unwrap_or(SocketAddr::new(
ApiEndpoint::API_IP_DEFAULT,
ApiEndpoint::API_PORT_DEFAULT,
))
}
/// Try to read the value of an environment variable. Returns `None` if the
/// environment variable has not been set.
///
/// # Panics
///
/// Panics if the environment variable was found, but it did not contain
/// valid unicode data.
fn read_var(key: &'static str) -> Option<String> {
use std::env;
match env::var(key) {
Ok(v) => Some(v),
Err(env::VarError::NotPresent) => None,
Err(env::VarError::NotUnicode(_)) => panic!("{key} does not contain valid UTF-8"),
}
}
}
/// A type that helps with the creation of API connections.
pub struct Runtime {
handle: tokio::runtime::Handle,
pub address_cache: AddressCache,
api_availability: availability::ApiAvailability,
#[cfg(target_os = "android")]
socket_bypass_tx: Option<mpsc::Sender<SocketBypassRequest>>,
}
#[derive(err_derive::Error, Debug)]
pub enum Error {
#[error(display = "Failed to construct a rest client")]
RestError(#[error(source)] rest::Error),
#[error(display = "Failed to load address cache")]
AddressCacheError(#[error(source)] address_cache::Error),
#[error(display = "API availability check failed")]
ApiCheckError(#[error(source)] availability::Error),
}
impl Runtime {
/// Create a new `Runtime`.
pub fn new(handle: tokio::runtime::Handle) -> Result<Self, Error> {
Self::new_inner(
handle,
#[cfg(target_os = "android")]
None,
)
}
#[cfg(target_os = "ios")]
pub fn with_static_addr(handle: tokio::runtime::Handle, address: SocketAddr) -> Self {
Runtime {
handle,
address_cache: AddressCache::with_static_addr(address),
api_availability: ApiAvailability::new(availability::State::default()),
}
}
fn new_inner(
handle: tokio::runtime::Handle,
#[cfg(target_os = "android")] socket_bypass_tx: Option<mpsc::Sender<SocketBypassRequest>>,
) -> Result<Self, Error> {
Ok(Runtime {
handle,
address_cache: AddressCache::new(None)?,
api_availability: ApiAvailability::new(availability::State::default()),
#[cfg(target_os = "android")]
socket_bypass_tx,
})
}
/// Create a new `Runtime` using the specified directories.
/// Try to use the cache directory first, and fall back on the bundled address otherwise.
pub async fn with_cache(
cache_dir: &Path,
write_changes: bool,
#[cfg(target_os = "android")] socket_bypass_tx: Option<mpsc::Sender<SocketBypassRequest>>,
) -> Result<Self, Error> {
let handle = tokio::runtime::Handle::current();
#[cfg(feature = "api-override")]
if API.disable_address_cache {
return Self::new_inner(
handle,
#[cfg(target_os = "android")]
socket_bypass_tx,
);
}
let cache_file = cache_dir.join(API_IP_CACHE_FILENAME);
let write_file = if write_changes {
Some(cache_file.clone().into_boxed_path())
} else {
None
};
let address_cache = match AddressCache::from_file(&cache_file, write_file.clone()).await {
Ok(cache) => cache,
Err(error) => {
if cache_file.exists() {
log::error!(
"{}",
error.display_chain_with_msg(
"Failed to load cached API addresses. Falling back on bundled address"
)
);
}
AddressCache::new(write_file)?
}
};
Ok(Runtime {
handle,
address_cache,
api_availability: ApiAvailability::new(availability::State::default()),
#[cfg(target_os = "android")]
socket_bypass_tx,
})
}
/// Creates a new request service and returns a handle to it.
fn new_request_service<T: Stream<Item = ApiConnectionMode> + Unpin + Send + 'static>(
&self,
sni_hostname: Option<String>,
initial_connection_mode: ApiConnectionMode,
proxy_provider: T,
#[cfg(target_os = "android")] socket_bypass_tx: Option<mpsc::Sender<SocketBypassRequest>>,
) -> rest::RequestServiceHandle {
rest::RequestService::spawn(
sni_hostname,
self.api_availability.handle(),
self.address_cache.clone(),
initial_connection_mode,
proxy_provider,
#[cfg(target_os = "android")]
socket_bypass_tx,
)
}
/// Returns a request factory initialized to create requests for the master API
pub fn mullvad_rest_handle<T: Stream<Item = ApiConnectionMode> + Unpin + Send + 'static>(
&self,
initial_connection_mode: ApiConnectionMode,
proxy_provider: T,
) -> rest::MullvadRestHandle {
let service = self.new_request_service(
Some(API.host().to_string()),
initial_connection_mode,
proxy_provider,
#[cfg(target_os = "android")]
self.socket_bypass_tx.clone(),
);
let token_store = access::AccessTokenStore::new(service.clone());
let factory = rest::RequestFactory::new(API.host(), Some(token_store));
rest::MullvadRestHandle::new(
service,
factory,
self.address_cache.clone(),
self.availability_handle(),
)
}
/// This is only to be used in test code
pub fn static_mullvad_rest_handle(&self, hostname: String) -> rest::MullvadRestHandle {
let service = self.new_request_service(
Some(hostname.clone()),
ApiConnectionMode::Direct,
futures::stream::repeat(ApiConnectionMode::Direct),
#[cfg(target_os = "android")]
self.socket_bypass_tx.clone(),
);
let token_store = access::AccessTokenStore::new(service.clone());
let factory = rest::RequestFactory::new(hostname, Some(token_store));
rest::MullvadRestHandle::new(
service,
factory,
self.address_cache.clone(),
self.availability_handle(),
)
}
/// Returns a new request service handle
pub fn rest_handle(&self) -> rest::RequestServiceHandle {
self.new_request_service(
None,
ApiConnectionMode::Direct,
ApiConnectionMode::Direct.into_repeat(),
#[cfg(target_os = "android")]
None,
)
}
pub fn handle(&mut self) -> &mut tokio::runtime::Handle {
&mut self.handle
}
pub fn availability_handle(&self) -> ApiAvailabilityHandle {
self.api_availability.handle()
}
}
#[derive(Clone)]
pub struct AccountsProxy {
handle: rest::MullvadRestHandle,
}
impl AccountsProxy {
pub fn new(handle: rest::MullvadRestHandle) -> Self {
Self { handle }
}
pub fn get_data(
&self,
account: AccountToken,
) -> impl Future<Output = Result<AccountData, rest::Error>> {
let service = self.handle.service.clone();
let factory = self.handle.factory.clone();
async move {
let request = factory
.get(&format!("{ACCOUNTS_URL_PREFIX}/accounts/me"))?
.expected_status(&[StatusCode::OK])
.account(account)?;
let response = service.request(request).await?;
response.deserialize().await
}
}
pub fn create_account(&self) -> impl Future<Output = Result<AccountToken, rest::Error>> {
#[derive(serde::Deserialize)]
struct AccountCreationResponse {
number: AccountToken,
}
let service = self.handle.service.clone();
let factory = self.handle.factory.clone();
async move {
let request = factory
.post(&format!("{ACCOUNTS_URL_PREFIX}/accounts"))?
.expected_status(&[StatusCode::CREATED]);
let response = service.request(request).await?;
let account: AccountCreationResponse = response.deserialize().await?;
Ok(account.number)
}
}
pub fn submit_voucher(
&self,
account: AccountToken,
voucher_code: String,
) -> impl Future<Output = Result<VoucherSubmission, rest::Error>> {
#[derive(serde::Serialize)]
struct VoucherSubmission {
voucher_code: String,
}
let service = self.handle.service.clone();
let factory = self.handle.factory.clone();
let submission = VoucherSubmission { voucher_code };
async move {
let request = factory
.post_json(&format!("{APP_URL_PREFIX}/submit-voucher"), &submission)?
.account(account)?
.expected_status(&[StatusCode::OK]);
service.request(request).await?.deserialize().await
}
}
#[cfg(target_os = "ios")]
pub fn delete_account(
&self,
account: AccountToken,
) -> impl Future<Output = Result<(), rest::Error>> {
let service = self.handle.service.clone();
let factory = self.handle.factory.clone();
async move {
let request = factory
.delete(&format!("{ACCOUNTS_URL_PREFIX}/accounts/me"))?
.account(account.clone())?
.header("Mullvad-Account-Number", &account)?
.expected_status(&[StatusCode::NO_CONTENT]);
let _ = service.request(request).await?;
Ok(())
}
}
#[cfg(target_os = "android")]
pub fn init_play_purchase(
&mut self,
account: AccountToken,
) -> impl Future<Output = Result<PlayPurchasePaymentToken, rest::Error>> {
#[derive(serde::Deserialize)]
struct PlayPurchaseInitResponse {
obfuscated_id: String,
}
let service = self.handle.service.clone();
let factory = self.handle.factory.clone();
async move {
let request = factory
.post_json(&format!("{GOOGLE_PAYMENTS_URL_PREFIX}/init"), &())?
.account(account)?
.expected_status(&[StatusCode::OK]);
let response = service.request(request).await?;
let PlayPurchaseInitResponse { obfuscated_id } = response.deserialize().await?;
Ok(obfuscated_id)
}
}
#[cfg(target_os = "android")]
pub fn verify_play_purchase(
&mut self,
account: AccountToken,
play_purchase: PlayPurchase,
) -> impl Future<Output = Result<(), rest::Error>> {
let service = self.handle.service.clone();
let factory = self.handle.factory.clone();
async move {
let request = factory
.post_json(
&format!("{GOOGLE_PAYMENTS_URL_PREFIX}/acknowledge"),
&play_purchase,
)?
.account(account)?
.expected_status(&[StatusCode::ACCEPTED]);
service.request(request).await?;
Ok(())
}
}
pub fn get_www_auth_token(
&self,
account: AccountToken,
) -> impl Future<Output = Result<String, rest::Error>> {
#[derive(serde::Deserialize)]
struct AuthTokenResponse {
auth_token: String,
}
let service = self.handle.service.clone();
let factory = self.handle.factory.clone();
async move {
let request = factory
.post(&format!("{APP_URL_PREFIX}/www-auth-token"))?
.account(account)?
.expected_status(&[StatusCode::OK]);
let response = service.request(request).await?;
let response: AuthTokenResponse = response.deserialize().await?;
Ok(response.auth_token)
}
}
}
pub struct ProblemReportProxy {
handle: rest::MullvadRestHandle,
}
impl ProblemReportProxy {
pub fn new(handle: rest::MullvadRestHandle) -> Self {
Self { handle }
}
pub fn problem_report(
&self,
email: &str,
message: &str,
log: &str,
metadata: &BTreeMap<String, String>,
) -> impl Future<Output = Result<(), rest::Error>> {
#[derive(serde::Serialize)]
struct ProblemReport {
address: String,
message: String,
log: String,
metadata: BTreeMap<String, String>,
}
let report = ProblemReport {
address: email.to_owned(),
message: message.to_owned(),
log: log.to_owned(),
metadata: metadata.clone(),
};
let service = self.handle.service.clone();
let factory = self.handle.factory.clone();
async move {
let request = factory
.post_json(&format!("{APP_URL_PREFIX}/problem-report"), &report)?
.expected_status(&[StatusCode::NO_CONTENT]);
service.request(request).await?;
Ok(())
}
}
}
#[derive(Clone)]
pub struct AppVersionProxy {
handle: rest::MullvadRestHandle,
}
#[derive(serde::Deserialize, Debug)]
pub struct AppVersionResponse {
pub supported: bool,
pub latest: AppVersion,
pub latest_stable: Option<AppVersion>,
pub latest_beta: AppVersion,
}
impl AppVersionProxy {
pub fn new(handle: rest::MullvadRestHandle) -> Self {
Self { handle }
}
pub fn version_check(
&self,
app_version: AppVersion,
platform: &str,
platform_version: String,
) -> impl Future<Output = Result<AppVersionResponse, rest::Error>> {
let service = self.handle.service.clone();
let path = format!("{APP_URL_PREFIX}/releases/{platform}/{app_version}");
let request = self.handle.factory.request(&path, Method::GET);
async move {
let request = request?
.expected_status(&[StatusCode::OK])
.header("M-Platform-Version", &platform_version)?;
let response = service.request(request).await?;
response.deserialize().await
}
}
}
#[derive(Clone)]
pub struct ApiProxy {
handle: rest::MullvadRestHandle,
}
impl ApiProxy {
pub fn new(handle: rest::MullvadRestHandle) -> Self {
Self { handle }
}
pub async fn get_api_addrs(&self) -> Result<Vec<SocketAddr>, rest::Error> {
let request = self
.handle
.factory
.get(&format!("{APP_URL_PREFIX}/api-addrs"))?
.expected_status(&[StatusCode::OK]);
let response = self.handle.service.request(request).await?;
response.deserialize().await
}
/// Check the availablility of `{APP_URL_PREFIX}/api-addrs`.
pub async fn api_addrs_available(&self) -> Result<bool, rest::Error> {
let request = self
.handle
.factory
.head(&format!("{APP_URL_PREFIX}/api-addrs"))?
.expected_status(&[StatusCode::OK]);
let response = self.handle.service.request(request).await?;
Ok(response.status().is_success())
}
}