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
use std::convert::TryInto;
use std::error::Error;
use std::str::Utf8Error;

use cookie::Cookie;
use cookie::CookieJar;
use serde::Serialize;

pub mod auth;
use auth::AuthData;
use auth::AuthStatus;
use auth::GetNonceResponse;
pub mod backups;
use backups::BackupWrapper;
pub mod progress;
use progress::ProgressState;
pub mod util;

pub struct Client {
	host: String,
	port: u16,
	tls: bool,
	base_url: String,
	password: String,
	auth: Option<AuthData>,
	cookies: CookieJar,
	http: reqwest::Client
}

impl Client {
	pub fn new(host: &str, port: u16, tls: bool, password: &str) -> Result<Self, Box<dyn Error>> {
		let mut headers = reqwest::header::HeaderMap::new();
		headers.insert(reqwest::header::USER_AGENT, "reqwest/0.10.8".try_into()?);
		headers.insert(reqwest::header::CONNECTION, "keep-alive".try_into()?);
		headers.insert(reqwest::header::ACCEPT, "*/*".try_into()?);
		/*
		headers.insert(reqwest::header::CACHE_CONTROL, "no-cache".try_into()?);
		headers.insert(reqwest::header::PRAGMA, "no-cache".try_into()?);
		headers.insert(reqwest::header::ACCEPT_LANGUAGE, "en-US,en;q=0.5".try_into()?);
		*/
		let mut client = Self{
			host: host.to_string(),
			port: port,
			tls: tls,
			base_url: "".to_string(),
			password: password.to_string(),
			auth: None,
			cookies: CookieJar::new(),
			http: reqwest::Client::builder()
				//.cookie_store(true)
				//.http1_title_case_headers()
				.gzip(true)
				.default_headers(headers)
				.build()?
		};
		client.build_base_url();
		Ok(client)
	}

	fn build_base_url(&mut self) {
		let protocol = match self.tls {
			true => "https",
			false => "http"
		};
		self.base_url = format!("{}://{}:{}", protocol, self.host, self.port);
	}

	fn build_url(&self, path: impl AsRef<str>) -> String {
		format!("{}/{}", self.base_url, path.as_ref()).to_string()
	}

	fn add_cookies(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
		let cookies = self.cookies.iter().map(|c| c.to_string()).collect::<Vec<String>>();
		if(cookies.len() == 0) {
			request
		} else {
			request.header(reqwest::header::COOKIE, cookies.join("; "))
		}
	}

	pub fn get(&self, path: impl AsRef<str>) -> reqwest::RequestBuilder {
		let url = self.build_url(path);
		let mut request = self.http.get(&url);
		request = match &self.auth {
			Some(auth) => request.header("X-XSRF-Token", &auth.token),
			None => request
		};
		self.add_cookies(request)
	}

	pub async fn get_short(&self, path: impl AsRef<str>) -> Result<reqwest::Response, Box<dyn Error>> {
		Ok(self.get(path).send().await?.error_for_status()?)
	}

	pub fn post(&self, path: impl AsRef<str>) -> reqwest::RequestBuilder {
		let url = self.build_url(path);
		let mut request = self.http.post(&url);
		request = match &self.auth {
			Some(auth) => request.header("X-XSRF-Token", &auth.token),
			None => request
		};
		self.add_cookies(request)
	}

	pub async fn post_short<T: Serialize + ?Sized>(&self, path: impl AsRef<str>, form: &T) -> Result<reqwest::Response, Box<dyn Error>> {
		Ok(self.post(path)
			.header("Content-Type", "application/x-www-form-urlencoded")
			.form(form)
			.send()
			.await?
			.error_for_status()?
		)
	}

	pub async fn check_auth(&self) -> Result<AuthStatus, Box<dyn Error>> {
		let response = self.get_short("").await?;
		if(response.headers().contains_key("WWW-Authenticate")) {
			return Ok(AuthStatus::BasicRequired)
		}
		if(response.url().path() == "/login.html") {
			return Ok(AuthStatus::PasswordWrong)
		}
		Ok(AuthStatus::OK)
	}

	fn save_cookie(&mut self, cookie: reqwest::cookie::Cookie) -> Result<(), Utf8Error> {
		let name = cookie.name().to_string();
		let value = percent_encoding::percent_decode_str(cookie.value()).decode_utf8()?.to_string();
		self.cookies.add(Cookie::new(name, value));
		Ok(())
	}

	fn save_cookies_from_response(&mut self, response: &reqwest::Response) -> Result<(), Utf8Error> {
		for cookie in response.cookies() {
			self.save_cookie(cookie)?;
		}
		Ok(())
	}

	pub async fn login(&mut self) -> Result<(), Box<dyn Error + '_>> {
		match self.check_auth().await? {
			AuthStatus::OK => return Ok(()),
			_ => ()
		};
		let response = self.http.post(&self.build_url("login.cgi"))
			.header("Content-Type", "application/x-www-form-urlencoded")
			.body("get-nonce=1")
			.send()
			.await?
			.error_for_status()?;

		self.save_cookies_from_response(&response)?;
		let token = match self.cookies.get("xsrf-token") {
			Some(v) => v,
			None => return Err(std::io::Error::from(std::io::ErrorKind::NotFound).into())
		};

		// TODO:  Why are the first 3 bytes of the response body invalid?
		let body = &response.bytes().await?;
		self.auth = Some(GetNonceResponse::from_bytes(&body[3..])?.try_into()?);

		let mut auth = self.auth.as_mut().unwrap();
		auth.token = token.value().to_string();
		let login_form = auth.obfuscate_password(&self.password);

		let response = self.post_short("login.cgi", &login_form).await?;
		self.save_cookies_from_response(&response)?;
		if(self.cookies.get("session-auth").is_none()) {
			return Err(std::io::Error::from(std::io::ErrorKind::NotFound).into());
		}

		Ok(())
	}

	pub async fn fetch_backups(&self) -> Result<Vec<BackupWrapper>, Box<dyn Error>> {
		let body = self.get_short("api/v1/backups")
			.await?
			.bytes()
			.await?;
		let mut response: Vec<BackupWrapper> = serde_json::from_slice(&body[3..])?;
		match self.fetch_progress_state().await? {
			Some(progress) => {
				for backup in response.iter_mut() {
					if(backup.backup.id == progress.backup_id) {
						backup.backup.progress = Some(progress);
						break;
					}
				}
			},
			None => ()
		};
		Ok(response)
	}

	pub async fn fetch_progress_state(&self) -> Result<Option<ProgressState>, Box<dyn Error>> {
		let body = match self.get_short("api/v1/progressstate").await {
			Ok(v) => v.bytes().await?,
			// TODO:  Only Ok(None) if this 404s; other errors are still real errors
			Err(_) => return Ok(None)
		};
		let response = serde_json::from_slice(&body[3..])?;
		Ok(response)
	}
}