summaryrefslogtreecommitdiffhomepage
path: root/mullvad-rpc/src/address_cache.rs
blob: 7c1859173e862e4a8eb6bc8c7410157ff4621065 (plain)
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
use std::{
    io,
    net::{IpAddr, SocketAddr},
    path::Path,
    sync::{Arc, Mutex},
};
use tokio::{
    fs,
    io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
};

const FALLBACK_API_ADDRESS: (IpAddr, u16) = (crate::API_IP, 443);

#[derive(Clone)]
pub struct AddressCache {
    inner: Arc<Mutex<AddressCacheInner>>,
    cache_path: Option<Arc<Path>>,
}

impl AddressCache {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(Default::default())),
            cache_path: None,
        }
    }

    pub async fn with_cache(cache_path: Box<Path>) -> Self {
        let cache = AddressCacheInner::from_cache_file(&cache_path)
            .await
            .unwrap_or_default();
        let inner = Arc::new(Mutex::new(cache));
        let cache_path = Some(cache_path.into());
        Self { inner, cache_path }
    }

    pub fn get_address(&self) -> SocketAddr {
        let mut inner = self.inner.lock().unwrap();
        inner.last_try = Some(inner.choice);

        Self::get_address_inner(&inner)
    }

    fn get_address_inner(inner: &AddressCacheInner) -> SocketAddr {
        if inner.addresses.is_empty() {
            return FALLBACK_API_ADDRESS.into();
        }
        *inner
            .addresses
            .get(inner.choice % inner.addresses.len())
            .unwrap_or(&FALLBACK_API_ADDRESS.into())
    }

    pub fn register_failure(&self, failed_addr: SocketAddr, err: &dyn std::error::Error) {
        let mut inner = self.inner.lock().unwrap();

        let current_address = Self::get_address_inner(&inner);
        // Only choose the next server if the current one has been tried before and it failed
        if failed_addr == current_address
            && inner
                .last_try
                .map(|last_try| last_try == inner.choice)
                .unwrap_or(false)
        {
            log::error!("HTTP request failed: {}, will try next API address", err);
            inner.choice = inner.choice.wrapping_add(1);
        }
    }

    pub async fn set_addresses(&self, addresses: Vec<SocketAddr>) -> io::Result<()> {
        let should_update = {
            let mut inner = self.inner.lock().unwrap();
            if addresses != inner.addresses {
                inner.addresses = addresses.clone();
                inner.choice = 0;
                true
            } else {
                false
            }
        };
        if should_update {
            self.save_to_disk(addresses).await?;
        }
        Ok(())
    }

    async fn save_to_disk(&self, addresses: Vec<SocketAddr>) -> io::Result<()> {
        if let Some(cache_path) = self.cache_path.as_ref() {
            let mut file = fs::File::create(cache_path).await?;
            let mut contents = addresses
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<String>>()
                .join("\n");
            contents += "\n";

            file.write_all(contents.as_bytes()).await?;
            file.sync_data().await?;
        }

        Ok(())
    }
}

impl crate::rest::AddressProvider for AddressCache {
    fn get_address(&self) -> String {
        self.get_address().to_string()
    }

    fn clone_box(&self) -> Box<dyn crate::rest::AddressProvider> {
        Box::new(self.clone())
    }
}


struct AddressCacheInner {
    addresses: Vec<SocketAddr>,
    choice: usize,
    last_try: Option<usize>,
}

impl AddressCacheInner {
    async fn from_cache_file(path: &Path) -> io::Result<Self> {
        let file = fs::File::open(path).await?;
        let mut lines = BufReader::new(file).lines();
        let mut addresses = vec![];
        while let Some(line) = lines.next_line().await? {
            // for line in lines.next_line() {
            match line.trim().parse() {
                Ok(address) => addresses.push(address),
                Err(err) => {
                    log::error!("Failed to parse cached address line: {}", err);
                }
            }
        }

        if !addresses.contains(&FALLBACK_API_ADDRESS.into()) {
            addresses.push(FALLBACK_API_ADDRESS.into());
        }

        Ok(Self {
            addresses,
            ..Default::default()
        })
    }
}

impl Default for AddressCacheInner {
    fn default() -> Self {
        Self {
            addresses: vec![FALLBACK_API_ADDRESS.into()],
            choice: 0,
            last_try: None,
        }
    }
}