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
use std::io::{BufRead, BufReader, Read};
use std::marker::PhantomData;
use std::time::Duration;

use log::{debug, trace};

use serde::de::DeserializeOwned;
use serde_json::{from_str, json};
use ureq::{Agent, Request};
use url::Url;

use crate::model::{Config, Connections, Delay, Log, Proxies, Proxy, Rules, Traffic, Version};
use crate::{Error, Result};

trait Convert<T: DeserializeOwned> {
    fn convert(self) -> Result<T>;
}

impl<T: DeserializeOwned> Convert<T> for String {
    fn convert(self) -> Result<T> {
        from_str(&self).map_err(Error::BadResponseFormat)
    }
}

#[derive(Debug, Clone)]
pub struct ClashBuilder {
    url: Url,
    secret: Option<String>,
    timeout: Option<Duration>,
}

impl ClashBuilder {
    pub fn new<S: Into<String>>(url: S) -> Result<Self> {
        let mut url_str = url.into();
        // Handle trailling slash
        if !url_str.ends_with('/') {
            url_str += "/";
        };
        let url = Url::parse(&url_str).map_err(|_| Error::UrlParseError)?;
        Ok(Self {
            url,
            secret: None,
            timeout: None,
        })
    }

    pub fn secret(mut self, secret: Option<String>) -> Self {
        self.secret = secret;
        self
    }

    pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
        self.timeout = timeout;
        self
    }

    pub fn build(self) -> Clash {
        let mut clash = Clash::new(self.url);
        clash.secret = self.secret;
        clash.timeout = self.timeout;
        clash
    }
}

/// # Clash API
///
/// Use struct `Clash` for interacting with Clash RESTful API.
/// For more information, check <https://github.com/Dreamacro/clash/wiki/external-controller-API-reference###Proxies>,
/// or maybe just read source code of clash
#[derive(Debug, Clone)]
pub struct Clash {
    url: Url,
    secret: Option<String>,
    timeout: Option<Duration>,
    agent: Agent,
}

impl Clash {
    pub fn builder<S: Into<String>>(url: S) -> Result<ClashBuilder> {
        ClashBuilder::new(url)
    }

    pub fn new(url: Url) -> Self {
        debug!("Url of clash RESTful API: {}", url);
        Self {
            url,
            secret: None,
            timeout: None,
            agent: Agent::new(),
        }
    }

    fn build_request(&self, endpoint: &str, method: &str) -> Result<Request> {
        let url = self.url.join(endpoint).map_err(|_| Error::UrlParseError)?;
        let mut req = self.agent.request_url(method, &url);

        if let Some(timeout) = self.timeout {
            req = req.timeout(timeout)
        }

        if let Some(ref secret) = self.secret {
            req = req.set("Authorization", &format!("Bearer {}", secret))
        }

        Ok(req)
    }

    fn build_request_without_timeout(&self, endpoint: &str, method: &str) -> Result<Request> {
        let url = self.url.join(endpoint).map_err(|_| Error::UrlParseError)?;
        let mut req = self.agent.request_url(method, &url);

        if let Some(ref secret) = self.secret {
            req = req.set("Authorization", &format!("Bearer {}", secret))
        }

        Ok(req)
    }

    /// Send a oneshot request to the specific endpoint with method, with body
    pub fn oneshot_req_with_body(
        &self,
        endpoint: &str,
        method: &str,
        body: Option<String>,
    ) -> Result<String> {
        trace!("Body: {:#?}", body);
        let resp = if let Some(body) = body {
            self.build_request(endpoint, method)?.send_string(&body)?
        } else {
            self.build_request(endpoint, method)?.call()?
        };

        if resp.status() >= 400 {
            return Err(Error::FailedResponse(resp.status()));
        }

        let text = resp.into_string().map_err(|_| Error::BadResponseEncoding)?;
        trace!("Received response: {}", text);

        Ok(text)
    }

    /// Send a oneshot request to the specific endpoint with method, without body
    pub fn oneshot_req(&self, endpoint: &str, method: &str) -> Result<String> {
        self.oneshot_req_with_body(endpoint, method, None)
    }

    /// Send a longhaul request to the specific endpoint with method,
    /// Underlying is an http stream with chunked-encoding.
    ///
    /// Use [`LongHaul::next_item`], [`LongHaul::next_raw`] or [`Iterator::next`] to retreive data
    ///
    /// # Examplel
    ///
    /// ```rust
    /// # use clashctl_core::{ Clash, model::Traffic }; use std::env;
    /// # fn main() {
    /// # let clash = Clash::builder(env::var("PROXY_ADDR").unwrap()).unwrap().build();
    /// let traffics = clash.longhaul_req::<Traffic>("traffic", "GET").expect("connect failed");
    ///
    /// // LongHaul implements `Iterator` so you can use iterator combinators
    /// for traffic in traffics.take(3) {
    ///     println!("{:#?}", traffic)
    /// }
    /// # }
    /// ```
    pub fn longhaul_req<T: DeserializeOwned>(
        &self,
        endpoint: &str,
        method: &str,
    ) -> Result<LongHaul<T>> {
        let resp = self
            .build_request_without_timeout(endpoint, method)?
            .call()?;

        if resp.status() >= 400 {
            return Err(Error::FailedResponse(resp.status()));
        }

        Ok(LongHaul::new(Box::new(resp.into_reader())))
    }

    /// Helper function for method `GET`
    pub fn get<T: DeserializeOwned>(&self, endpoint: &str) -> Result<T> {
        self.oneshot_req(endpoint, "GET").and_then(Convert::convert)
    }

    /// Helper function for method `DELETE`
    pub fn delete(&self, endpoint: &str) -> Result<()> {
        self.oneshot_req(endpoint, "DELETE").map(|_| ())
    }

    /// Helper function for method `PUT`
    pub fn put<T: DeserializeOwned>(&self, endpoint: &str, body: Option<String>) -> Result<T> {
        self.oneshot_req_with_body(endpoint, "PUT", body)
            .and_then(Convert::convert)
    }

    /// Get clash version
    pub fn get_version(&self) -> Result<Version> {
        self.get("version")
    }

    /// Get base configs
    pub fn get_configs(&self) -> Result<Config> {
        self.get("configs")
    }

    /// Reloading base configs.
    ///
    /// - `force`: will change ports etc.,
    /// - `path`: the absolute path to config file
    ///
    /// This will **NOT** affect `external-controller` & `secret`
    pub fn reload_configs(&self, force: bool, path: &str) -> Result<()> {
        let body = json!({ "path": path }).to_string();
        debug!("{}", body);
        self.put::<String>(if force { "configs?force" } else { "configs" }, Some(body))
            .map(|_| ())
    }

    /// Get proxies information
    pub fn get_proxies(&self) -> Result<Proxies> {
        self.get("proxies")
    }

    /// Get rules information
    pub fn get_rules(&self) -> Result<Rules> {
        self.get("rules")
    }

    /// Get specific proxy information
    pub fn get_proxy(&self, proxy: &str) -> Result<Proxy> {
        self.get(&format!("proxies/{}", proxy))
    }

    /// Get connections information
    pub fn get_connections(&self) -> Result<Connections> {
        self.get("connections")
    }

    /// Close all connections
    pub fn close_connections(&self) -> Result<()> {
        self.delete("connections")
    }

    /// Close specific connection
    pub fn close_one_connection(&self, id: &str) -> Result<()> {
        self.delete(&format!("connections/{}", id))
    }

    /// Get real-time traffic data
    ///
    /// **Note**: This is a longhaul request, which will last forever until interrupted or disconnected.
    ///
    /// See [`longhaul_req`] for more information
    ///
    /// [`longhaul_req`]: Clash::longhaul_req
    pub fn get_traffic(&self) -> Result<LongHaul<Traffic>> {
        self.longhaul_req("traffic", "GET")
    }

    /// Get real-time logs
    ///
    /// **Note**: This is a longhaul request, which will last forever until interrupted or disconnected.
    ///
    /// See [`longhaul_req`] for more information
    ///
    /// [`longhaul_req`]: Clash::longhaul_req
    pub fn get_log(&self) -> Result<LongHaul<Log>> {
        self.longhaul_req("logs", "GET")
    }

    /// Get specific proxy delay test information
    pub fn get_proxy_delay(&self, proxy: &str, test_url: &str, timeout: u64) -> Result<Delay> {
        use urlencoding::encode as e;
        let (proxy, test_url) = (e(proxy), e(test_url));
        self.get(&format!(
            "proxies/{}/delay?url={}&timeout={}",
            proxy, test_url, timeout
        ))
    }

    /// Select specific proxy
    pub fn set_proxygroup_selected(&self, group: &str, proxy: &str) -> Result<()> {
        let body = format!("{{\"name\":\"{}\"}}", proxy);
        self.oneshot_req_with_body(&format!("proxies/{}", group), "PUT", Some(body))?;
        Ok(())
    }
}

pub struct LongHaul<T: DeserializeOwned> {
    reader: BufReader<Box<dyn Read + Send>>,
    ty: PhantomData<T>,
}

impl<T: DeserializeOwned> LongHaul<T> {
    pub fn new(reader: Box<dyn Read + Send>) -> Self {
        Self {
            reader: BufReader::new(reader),
            ty: PhantomData,
        }
    }

    pub fn next_item(&mut self) -> Option<Result<T>> {
        Some(self.next_raw()?.and_then(Convert::convert))
    }

    pub fn next_raw(&mut self) -> Option<Result<String>> {
        let mut buf = String::with_capacity(30);
        match self.reader.read_line(&mut buf) {
            Ok(0) => None,
            Ok(_) => Some(Ok(buf)),
            Err(e) => Some(Err(Error::Other(format!("{:}", e)))),
        }
    }
}

impl<T: DeserializeOwned> Iterator for LongHaul<T> {
    type Item = Result<T>;
    fn next(&mut self) -> Option<Self::Item> {
        self.next_item()
    }
}