]>
Commit | Line | Data |
---|---|---|
553610b4 | 1 | use std::collections::HashSet; |
c2b94534 | 2 | use std::io::Write; |
7a57cb77 WB |
3 | use std::sync::atomic::{AtomicUsize, Ordering}; |
4 | use std::sync::{Arc, Mutex}; | |
597641fd | 5 | |
7a57cb77 WB |
6 | use chrono::{DateTime, Utc}; |
7 | use failure::*; | |
82ab7230 | 8 | use futures::*; |
1fdb4c6f | 9 | use futures::stream::Stream; |
7a57cb77 WB |
10 | use http::Uri; |
11 | use http::header::HeaderValue; | |
12 | use http::{Request, Response}; | |
13 | use hyper::Body; | |
1434f4f8 | 14 | use hyper::client::{Client, HttpConnector}; |
6d1f61b2 | 15 | use openssl::ssl::{SslConnector, SslMethod}; |
ba3a60b2 | 16 | use serde_json::{json, Value}; |
a6782ca1 WB |
17 | use tokio::io::AsyncReadExt; |
18 | use tokio::sync::{mpsc, oneshot}; | |
0dffe3f9 | 19 | use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET}; |
7a57cb77 | 20 | use xdg::BaseDirectories; |
1fdb4c6f | 21 | |
e18a6c9e DM |
22 | use proxmox::tools::{ |
23 | digest_to_hex, | |
24 | fs::{file_get_json, file_set_contents}, | |
25 | }; | |
26 | ||
7a57cb77 WB |
27 | use super::merge_known_chunks::{MergedChunkInfo, MergeKnownChunks}; |
28 | use super::pipe_to_stream::PipeToSendStream; | |
986bef16 | 29 | use crate::backup::*; |
1434f4f8 | 30 | use crate::tools::async_io::EitherStream; |
7a57cb77 | 31 | use crate::tools::futures::{cancellable, Canceller}; |
1434f4f8 | 32 | use crate::tools::{self, tty, BroadcastFuture}; |
986bef16 | 33 | |
5a2df000 | 34 | #[derive(Clone)] |
e240d8be | 35 | pub struct AuthInfo { |
5a2df000 DM |
36 | username: String, |
37 | ticket: String, | |
38 | token: String, | |
39 | } | |
56458d97 | 40 | |
151c6ce2 | 41 | /// HTTP(S) API client |
597641fd | 42 | pub struct HttpClient { |
1434f4f8 | 43 | client: Client<HttpsConnector>, |
597641fd | 44 | server: String, |
5a2df000 | 45 | auth: BroadcastFuture<AuthInfo>, |
597641fd DM |
46 | } |
47 | ||
e240d8be DM |
48 | /// Delete stored ticket data (logout) |
49 | pub fn delete_ticket_info(server: &str, username: &str) -> Result<(), Error> { | |
50 | ||
51 | let base = BaseDirectories::with_prefix("proxmox-backup")?; | |
52 | ||
53 | // usually /run/user/<uid>/... | |
54 | let path = base.place_runtime_file("tickets")?; | |
55 | ||
56 | let mode = nix::sys::stat::Mode::from_bits_truncate(0o0600); | |
57 | ||
58 | let mut data = file_get_json(&path, Some(json!({})))?; | |
59 | ||
60 | if let Some(map) = data[server].as_object_mut() { | |
61 | map.remove(username); | |
62 | } | |
63 | ||
64 | file_set_contents(path, data.to_string().as_bytes(), Some(mode))?; | |
65 | ||
66 | Ok(()) | |
67 | } | |
68 | ||
ba3a60b2 DM |
69 | fn store_ticket_info(server: &str, username: &str, ticket: &str, token: &str) -> Result<(), Error> { |
70 | ||
71 | let base = BaseDirectories::with_prefix("proxmox-backup")?; | |
72 | ||
73 | // usually /run/user/<uid>/... | |
74 | let path = base.place_runtime_file("tickets")?; | |
75 | ||
76 | let mode = nix::sys::stat::Mode::from_bits_truncate(0o0600); | |
77 | ||
e18a6c9e | 78 | let mut data = file_get_json(&path, Some(json!({})))?; |
ba3a60b2 DM |
79 | |
80 | let now = Utc::now().timestamp(); | |
81 | ||
82 | data[server][username] = json!({ "timestamp": now, "ticket": ticket, "token": token}); | |
83 | ||
84 | let mut new_data = json!({}); | |
85 | ||
86 | let ticket_lifetime = tools::ticket::TICKET_LIFETIME - 60; | |
87 | ||
88 | let empty = serde_json::map::Map::new(); | |
89 | for (server, info) in data.as_object().unwrap_or(&empty) { | |
90 | for (_user, uinfo) in info.as_object().unwrap_or(&empty) { | |
91 | if let Some(timestamp) = uinfo["timestamp"].as_i64() { | |
92 | let age = now - timestamp; | |
93 | if age < ticket_lifetime { | |
94 | new_data[server][username] = uinfo.clone(); | |
95 | } | |
96 | } | |
97 | } | |
98 | } | |
99 | ||
e18a6c9e | 100 | file_set_contents(path, new_data.to_string().as_bytes(), Some(mode))?; |
ba3a60b2 DM |
101 | |
102 | Ok(()) | |
103 | } | |
104 | ||
105 | fn load_ticket_info(server: &str, username: &str) -> Option<(String, String)> { | |
66c8eb93 | 106 | let base = BaseDirectories::with_prefix("proxmox-backup").ok()?; |
ba3a60b2 DM |
107 | |
108 | // usually /run/user/<uid>/... | |
66c8eb93 CE |
109 | let path = base.place_runtime_file("tickets").ok()?; |
110 | let data = file_get_json(&path, None).ok()?; | |
ba3a60b2 | 111 | let now = Utc::now().timestamp(); |
ba3a60b2 | 112 | let ticket_lifetime = tools::ticket::TICKET_LIFETIME - 60; |
66c8eb93 CE |
113 | let uinfo = data[server][username].as_object()?; |
114 | let timestamp = uinfo["timestamp"].as_i64()?; | |
115 | let age = now - timestamp; | |
116 | ||
117 | if age < ticket_lifetime { | |
118 | let ticket = uinfo["ticket"].as_str()?; | |
119 | let token = uinfo["token"].as_str()?; | |
120 | Some((ticket.to_owned(), token.to_owned())) | |
121 | } else { | |
122 | None | |
ba3a60b2 | 123 | } |
ba3a60b2 DM |
124 | } |
125 | ||
597641fd DM |
126 | impl HttpClient { |
127 | ||
45cdce06 | 128 | pub fn new(server: &str, username: &str) -> Result<Self, Error> { |
5a2df000 | 129 | let client = Self::build_client(); |
5a2df000 | 130 | |
45cdce06 DM |
131 | let password = if let Some((ticket, _token)) = load_ticket_info(server, username) { |
132 | ticket | |
133 | } else { | |
134 | Self::get_password(&username)? | |
135 | }; | |
136 | ||
9d35dbbb | 137 | let login_future = Self::credentials(client.clone(), server.to_owned(), username.to_owned(), password); |
45cdce06 DM |
138 | |
139 | Ok(Self { | |
5a2df000 | 140 | client, |
597641fd | 141 | server: String::from(server), |
9d35dbbb | 142 | auth: BroadcastFuture::new(Box::new(login)), |
45cdce06 | 143 | }) |
597641fd DM |
144 | } |
145 | ||
e240d8be DM |
146 | /// Login future |
147 | /// | |
148 | /// Login is done on demand, so this is onyl required if you need | |
149 | /// access to authentication data in 'AuthInfo'. | |
a6782ca1 | 150 | pub fn login(&self) -> impl Future<Output = Result<AuthInfo, Error>> { |
e240d8be DM |
151 | self.auth.listen() |
152 | } | |
153 | ||
5a2df000 | 154 | fn get_password(_username: &str) -> Result<String, Error> { |
56458d97 WB |
155 | use std::env::VarError::*; |
156 | match std::env::var("PBS_PASSWORD") { | |
157 | Ok(p) => return Ok(p), | |
158 | Err(NotUnicode(_)) => bail!("PBS_PASSWORD contains bad characters"), | |
159 | Err(NotPresent) => { | |
160 | // Try another method | |
161 | } | |
162 | } | |
163 | ||
164 | // If we're on a TTY, query the user for a password | |
165 | if tty::stdin_isatty() { | |
166 | return Ok(String::from_utf8(tty::read_password("Password: ")?)?); | |
167 | } | |
168 | ||
169 | bail!("no password input mechanism available"); | |
170 | } | |
171 | ||
1434f4f8 | 172 | fn build_client() -> Client<HttpsConnector> { |
6d1f61b2 DM |
173 | |
174 | let mut ssl_connector_builder = SslConnector::builder(SslMethod::tls()).unwrap(); | |
175 | ||
176 | ssl_connector_builder.set_verify(openssl::ssl::SslVerifyMode::NONE); // fixme! | |
177 | ||
1434f4f8 | 178 | let mut httpc = hyper::client::HttpConnector::new(); |
fcf5dea5 | 179 | httpc.set_nodelay(true); // important for h2 download performance! |
99168f43 | 180 | httpc.set_recv_buffer_size(Some(1024*1024)); //important for h2 download performance! |
4a3f6517 | 181 | httpc.enforce_http(false); // we want https... |
6d1f61b2 | 182 | |
1434f4f8 | 183 | let https = HttpsConnector::with_connector(httpc, ssl_connector_builder.build()); |
6d1f61b2 | 184 | |
adec8ea2 DM |
185 | Client::builder() |
186 | //.http2_initial_stream_window_size( (1 << 31) - 2) | |
187 | //.http2_initial_connection_window_size( (1 << 31) - 2) | |
188 | .build::<_, Body>(https) | |
a6b75513 DM |
189 | } |
190 | ||
a6782ca1 | 191 | pub fn request(&self, mut req: Request<Body>) -> impl Future<Output = Result<Value, Error>> { |
597641fd | 192 | |
5a2df000 | 193 | let login = self.auth.listen(); |
597641fd | 194 | |
5a2df000 | 195 | let client = self.client.clone(); |
597641fd | 196 | |
5a2df000 | 197 | login.and_then(move |auth| { |
597641fd | 198 | |
5a2df000 DM |
199 | let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)); |
200 | req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap()); | |
201 | req.headers_mut().insert("CSRFPreventionToken", HeaderValue::from_str(&auth.token).unwrap()); | |
597641fd | 202 | |
5a2df000 | 203 | let request = Self::api_request(client, req); |
597641fd | 204 | |
5a2df000 DM |
205 | request |
206 | }) | |
1fdb4c6f DM |
207 | } |
208 | ||
a6782ca1 WB |
209 | pub fn get( |
210 | &self, | |
211 | path: &str, | |
212 | data: Option<Value>, | |
213 | ) -> impl Future<Output = Result<Value, Error>> { | |
9e391bb7 | 214 | let req = Self::request_builder(&self.server, "GET", path, data).unwrap(); |
5a2df000 | 215 | self.request(req) |
a6b75513 DM |
216 | } |
217 | ||
a6782ca1 WB |
218 | pub fn delete( |
219 | &mut self, | |
220 | path: &str, | |
221 | data: Option<Value>, | |
222 | ) -> impl Future<Output = Result<Value, Error>> { | |
9e391bb7 | 223 | let req = Self::request_builder(&self.server, "DELETE", path, data).unwrap(); |
5a2df000 | 224 | self.request(req) |
a6b75513 DM |
225 | } |
226 | ||
a6782ca1 WB |
227 | pub fn post( |
228 | &mut self, | |
229 | path: &str, | |
230 | data: Option<Value>, | |
231 | ) -> impl Future<Output = Result<Value, Error>> { | |
5a2df000 DM |
232 | let req = Self::request_builder(&self.server, "POST", path, data).unwrap(); |
233 | self.request(req) | |
024f11bb DM |
234 | } |
235 | ||
a6782ca1 WB |
236 | pub fn download<W: Write + Send + 'static>( |
237 | &mut self, | |
238 | path: &str, | |
239 | output: W, | |
240 | ) -> impl Future<Output = Result<W, Error>> { | |
5a2df000 | 241 | let mut req = Self::request_builder(&self.server, "GET", path, None).unwrap(); |
024f11bb | 242 | |
5a2df000 | 243 | let login = self.auth.listen(); |
024f11bb | 244 | |
5a2df000 | 245 | let client = self.client.clone(); |
1fdb4c6f | 246 | |
5a2df000 | 247 | login.and_then(move |auth| { |
81da38c1 | 248 | |
5a2df000 DM |
249 | let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)); |
250 | req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap()); | |
6f62c924 | 251 | |
5a2df000 DM |
252 | client.request(req) |
253 | .map_err(Error::from) | |
254 | .and_then(|resp| { | |
81820b0d DM |
255 | let status = resp.status(); |
256 | if !status.is_success() { | |
a6782ca1 | 257 | future::Either::Left( |
81820b0d | 258 | HttpClient::api_response(resp) |
a6782ca1 | 259 | .map(|_| Err(format_err!("unknown error"))) |
81820b0d DM |
260 | ) |
261 | } else { | |
a6782ca1 | 262 | future::Either::Right( |
81820b0d DM |
263 | resp.into_body() |
264 | .map_err(Error::from) | |
a6782ca1 | 265 | .try_fold(output, move |mut acc, chunk| async move { |
c2b94534 DM |
266 | acc.write_all(&chunk)?; |
267 | Ok::<_, Error>(acc) | |
81820b0d DM |
268 | }) |
269 | ) | |
270 | } | |
5a2df000 DM |
271 | }) |
272 | }) | |
6f62c924 DM |
273 | } |
274 | ||
04512d30 DM |
275 | pub fn upload( |
276 | &mut self, | |
277 | content_type: &str, | |
278 | body: Body, | |
279 | path: &str, | |
280 | data: Option<Value>, | |
a6782ca1 | 281 | ) -> impl Future<Output = Result<Value, Error>> { |
81da38c1 DM |
282 | |
283 | let path = path.trim_matches('/'); | |
04512d30 DM |
284 | let mut url = format!("https://{}:8007/{}", &self.server, path); |
285 | ||
286 | if let Some(data) = data { | |
287 | let query = tools::json_object_to_query(data).unwrap(); | |
288 | url.push('?'); | |
289 | url.push_str(&query); | |
290 | } | |
291 | ||
292 | let url: Uri = url.parse().unwrap(); | |
81da38c1 | 293 | |
5a2df000 | 294 | let req = Request::builder() |
81da38c1 DM |
295 | .method("POST") |
296 | .uri(url) | |
297 | .header("User-Agent", "proxmox-backup-client/1.0") | |
5a2df000 DM |
298 | .header("Content-Type", content_type) |
299 | .body(body).unwrap(); | |
81da38c1 | 300 | |
5a2df000 | 301 | self.request(req) |
1fdb4c6f DM |
302 | } |
303 | ||
6ab34afa DM |
304 | pub fn start_backup( |
305 | &self, | |
306 | datastore: &str, | |
307 | backup_type: &str, | |
308 | backup_id: &str, | |
ca5d0b61 | 309 | backup_time: DateTime<Utc>, |
39e60bd6 | 310 | debug: bool, |
a6782ca1 | 311 | ) -> impl Future<Output = Result<Arc<BackupClient>, Error>> { |
cf639a47 | 312 | |
ca5d0b61 DM |
313 | let param = json!({ |
314 | "backup-type": backup_type, | |
315 | "backup-id": backup_id, | |
316 | "backup-time": backup_time.timestamp(), | |
317 | "store": datastore, | |
318 | "debug": debug | |
319 | }); | |
320 | ||
fb047083 | 321 | let req = Self::request_builder(&self.server, "GET", "/api2/json/backup", Some(param)).unwrap(); |
cf639a47 | 322 | |
fb047083 | 323 | self.start_h2_connection(req, String::from(PROXMOX_BACKUP_PROTOCOL_ID_V1!())) |
a6782ca1 | 324 | .map_ok(|(h2, canceller)| BackupClient::new(h2, canceller)) |
fb047083 DM |
325 | } |
326 | ||
dd066d28 DM |
327 | pub fn start_backup_reader( |
328 | &self, | |
329 | datastore: &str, | |
330 | backup_type: &str, | |
331 | backup_id: &str, | |
fa5d6977 | 332 | backup_time: DateTime<Utc>, |
dd066d28 | 333 | debug: bool, |
a6782ca1 | 334 | ) -> impl Future<Output = Result<Arc<BackupReader>, Error>> { |
dd066d28 DM |
335 | |
336 | let param = json!({ | |
337 | "backup-type": backup_type, | |
338 | "backup-id": backup_id, | |
339 | "backup-time": backup_time.timestamp(), | |
340 | "store": datastore, | |
341 | "debug": debug, | |
342 | }); | |
343 | let req = Self::request_builder(&self.server, "GET", "/api2/json/reader", Some(param)).unwrap(); | |
344 | ||
345 | self.start_h2_connection(req, String::from(PROXMOX_BACKUP_READER_PROTOCOL_ID_V1!())) | |
a6782ca1 | 346 | .map_ok(|(h2, canceller)| BackupReader::new(h2, canceller)) |
dd066d28 DM |
347 | } |
348 | ||
fb047083 DM |
349 | pub fn start_h2_connection( |
350 | &self, | |
351 | mut req: Request<Body>, | |
352 | protocol_name: String, | |
a6782ca1 | 353 | ) -> impl Future<Output = Result<(H2Client, Canceller), Error>> { |
cf639a47 | 354 | |
fb047083 | 355 | let login = self.auth.listen(); |
cf639a47 DM |
356 | let client = self.client.clone(); |
357 | ||
358 | login.and_then(move |auth| { | |
359 | ||
360 | let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)); | |
361 | req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap()); | |
fb047083 | 362 | req.headers_mut().insert("UPGRADE", HeaderValue::from_str(&protocol_name).unwrap()); |
cf639a47 DM |
363 | |
364 | client.request(req) | |
365 | .map_err(Error::from) | |
366 | .and_then(|resp| { | |
367 | ||
368 | let status = resp.status(); | |
369 | if status != http::StatusCode::SWITCHING_PROTOCOLS { | |
a6782ca1 WB |
370 | future::Either::Left( |
371 | Self::api_response(resp) | |
372 | .map(|_| Err(format_err!("unknown error"))) | |
373 | ) | |
9af37c8f | 374 | } else { |
a6782ca1 WB |
375 | future::Either::Right( |
376 | resp | |
377 | .into_body() | |
378 | .on_upgrade() | |
379 | .map_err(Error::from) | |
380 | ) | |
cf639a47 | 381 | } |
cf639a47 | 382 | }) |
cf639a47 | 383 | .and_then(|upgraded| { |
a2b29b68 | 384 | let max_window_size = (1 << 31) - 2; |
fcf5dea5 DM |
385 | |
386 | h2::client::Builder::new() | |
a2b29b68 DM |
387 | .initial_connection_window_size(max_window_size) |
388 | .initial_window_size(max_window_size) | |
fcf5dea5 | 389 | .max_frame_size(4*1024*1024) |
fcf5dea5 DM |
390 | .handshake(upgraded) |
391 | .map_err(Error::from) | |
cf639a47 | 392 | }) |
a6782ca1 | 393 | .and_then(|(h2, connection)| async move { |
cf639a47 DM |
394 | let connection = connection |
395 | .map_err(|_| panic!("HTTP/2.0 connection failed")); | |
396 | ||
cb4426b3 WB |
397 | let (connection, canceller) = cancellable(connection)?; |
398 | // A cancellable future returns an Option which is None when cancelled and | |
399 | // Some when it finished instead, since we don't care about the return type we | |
400 | // need to map it away: | |
401 | let connection = connection.map(|_| ()); | |
402 | ||
cf639a47 DM |
403 | // Spawn a new task to drive the connection state |
404 | hyper::rt::spawn(connection); | |
405 | ||
406 | // Wait until the `SendRequest` handle has available capacity. | |
a6782ca1 WB |
407 | let c = h2.ready().await?; |
408 | Ok((H2Client::new(c), canceller)) | |
409 | }.boxed()) | |
cf639a47 DM |
410 | }) |
411 | } | |
412 | ||
9d35dbbb | 413 | async fn credentials( |
1434f4f8 | 414 | client: Client<HttpsConnector>, |
45cdce06 DM |
415 | server: String, |
416 | username: String, | |
417 | password: String, | |
9d35dbbb DM |
418 | ) -> Result<AuthInfo, Error> { |
419 | let data = json!({ "username": username, "password": password }); | |
420 | let req = Self::request_builder(&server, "POST", "/api2/json/access/ticket", Some(data)).unwrap(); | |
421 | let cred = Self::api_request(client, req).await?; | |
422 | let auth = AuthInfo { | |
423 | username: cred["data"]["username"].as_str().unwrap().to_owned(), | |
424 | ticket: cred["data"]["ticket"].as_str().unwrap().to_owned(), | |
425 | token: cred["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(), | |
426 | }; | |
427 | ||
428 | let _ = store_ticket_info(&server, &auth.username, &auth.ticket, &auth.token); | |
429 | ||
430 | Ok(auth) | |
ba3a60b2 DM |
431 | } |
432 | ||
a6782ca1 | 433 | async fn api_response(response: Response<Body>) -> Result<Value, Error> { |
d2c48afc | 434 | let status = response.status(); |
a6782ca1 | 435 | let data = response |
d2c48afc | 436 | .into_body() |
a6782ca1 WB |
437 | .try_concat() |
438 | .await?; | |
439 | ||
440 | let text = String::from_utf8(data.to_vec()).unwrap(); | |
441 | if status.is_success() { | |
442 | if text.len() > 0 { | |
443 | let value: Value = serde_json::from_str(&text)?; | |
444 | Ok(value) | |
445 | } else { | |
446 | Ok(Value::Null) | |
447 | } | |
448 | } else { | |
449 | bail!("HTTP Error {}: {}", status, text); | |
450 | } | |
d2c48afc DM |
451 | } |
452 | ||
5a2df000 | 453 | fn api_request( |
1434f4f8 | 454 | client: Client<HttpsConnector>, |
5a2df000 | 455 | req: Request<Body> |
a6782ca1 | 456 | ) -> impl Future<Output = Result<Value, Error>> { |
ba3a60b2 | 457 | |
5a2df000 DM |
458 | client.request(req) |
459 | .map_err(Error::from) | |
d2c48afc | 460 | .and_then(Self::api_response) |
0dffe3f9 DM |
461 | } |
462 | ||
5a2df000 | 463 | pub fn request_builder(server: &str, method: &str, path: &str, data: Option<Value>) -> Result<Request<Body>, Error> { |
591f570b | 464 | let path = path.trim_matches('/'); |
5a2df000 DM |
465 | let url: Uri = format!("https://{}:8007/{}", server, path).parse()?; |
466 | ||
467 | if let Some(data) = data { | |
468 | if method == "POST" { | |
469 | let request = Request::builder() | |
470 | .method(method) | |
471 | .uri(url) | |
472 | .header("User-Agent", "proxmox-backup-client/1.0") | |
473 | .header(hyper::header::CONTENT_TYPE, "application/json") | |
474 | .body(Body::from(data.to_string()))?; | |
475 | return Ok(request); | |
476 | } else { | |
9e391bb7 DM |
477 | let query = tools::json_object_to_query(data)?; |
478 | let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?; | |
479 | let request = Request::builder() | |
480 | .method(method) | |
481 | .uri(url) | |
482 | .header("User-Agent", "proxmox-backup-client/1.0") | |
483 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
484 | .body(Body::empty())?; | |
485 | return Ok(request); | |
5a2df000 | 486 | } |
5a2df000 | 487 | } |
0dffe3f9 | 488 | |
1fdb4c6f | 489 | let request = Request::builder() |
5a2df000 | 490 | .method(method) |
1fdb4c6f DM |
491 | .uri(url) |
492 | .header("User-Agent", "proxmox-backup-client/1.0") | |
5a2df000 DM |
493 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") |
494 | .body(Body::empty())?; | |
1fdb4c6f | 495 | |
5a2df000 | 496 | Ok(request) |
597641fd DM |
497 | } |
498 | } | |
b57cb264 | 499 | |
dd066d28 DM |
500 | |
501 | pub struct BackupReader { | |
502 | h2: H2Client, | |
3467cd91 | 503 | canceller: Canceller, |
dd066d28 DM |
504 | } |
505 | ||
506 | impl Drop for BackupReader { | |
507 | ||
508 | fn drop(&mut self) { | |
3467cd91 | 509 | self.canceller.cancel(); |
dd066d28 DM |
510 | } |
511 | } | |
512 | ||
513 | impl BackupReader { | |
514 | ||
3467cd91 DM |
515 | pub fn new(h2: H2Client, canceller: Canceller) -> Arc<Self> { |
516 | Arc::new(Self { h2, canceller: canceller }) | |
dd066d28 DM |
517 | } |
518 | ||
a6782ca1 WB |
519 | pub fn get( |
520 | &self, | |
521 | path: &str, | |
522 | param: Option<Value>, | |
523 | ) -> impl Future<Output = Result<Value, Error>> { | |
dd066d28 DM |
524 | self.h2.get(path, param) |
525 | } | |
526 | ||
a6782ca1 WB |
527 | pub fn put( |
528 | &self, | |
529 | path: &str, | |
530 | param: Option<Value>, | |
531 | ) -> impl Future<Output = Result<Value, Error>> { | |
dd066d28 DM |
532 | self.h2.put(path, param) |
533 | } | |
534 | ||
a6782ca1 WB |
535 | pub fn post( |
536 | &self, | |
537 | path: &str, | |
538 | param: Option<Value>, | |
539 | ) -> impl Future<Output = Result<Value, Error>> { | |
dd066d28 DM |
540 | self.h2.post(path, param) |
541 | } | |
542 | ||
a6782ca1 | 543 | pub fn download<W: Write + Send + 'static>( |
dd066d28 DM |
544 | &self, |
545 | file_name: &str, | |
546 | output: W, | |
a6782ca1 | 547 | ) -> impl Future<Output = Result<W, Error>> { |
dd066d28 DM |
548 | let path = "download"; |
549 | let param = json!({ "file-name": file_name }); | |
550 | self.h2.download(path, Some(param), output) | |
551 | } | |
552 | ||
a6782ca1 | 553 | pub fn speedtest<W: Write + Send + 'static>( |
17243003 DM |
554 | &self, |
555 | output: W, | |
a6782ca1 | 556 | ) -> impl Future<Output = Result<W, Error>> { |
17243003 DM |
557 | self.h2.download("speedtest", None, output) |
558 | } | |
559 | ||
a6782ca1 | 560 | pub fn download_chunk<W: Write + Send + 'static>( |
fcf5dea5 DM |
561 | &self, |
562 | digest: &[u8; 32], | |
563 | output: W, | |
a6782ca1 | 564 | ) -> impl Future<Output = Result<W, Error>> { |
fcf5dea5 | 565 | let path = "chunk"; |
e18a6c9e | 566 | let param = json!({ "digest": digest_to_hex(digest) }); |
fcf5dea5 DM |
567 | self.h2.download(path, Some(param), output) |
568 | } | |
569 | ||
4f6aaf54 | 570 | pub fn force_close(self) { |
3467cd91 | 571 | self.canceller.cancel(); |
dd066d28 DM |
572 | } |
573 | } | |
574 | ||
6ab34afa | 575 | pub struct BackupClient { |
9af37c8f | 576 | h2: H2Client, |
3467cd91 | 577 | canceller: Canceller, |
b57cb264 DM |
578 | } |
579 | ||
dd066d28 DM |
580 | impl Drop for BackupClient { |
581 | ||
582 | fn drop(&mut self) { | |
3467cd91 | 583 | self.canceller.cancel(); |
dd066d28 DM |
584 | } |
585 | } | |
91320f08 | 586 | |
2c3891d1 DM |
587 | pub struct BackupStats { |
588 | pub size: u64, | |
c807d231 | 589 | pub csum: [u8; 32], |
2c3891d1 DM |
590 | } |
591 | ||
6ab34afa | 592 | impl BackupClient { |
3467cd91 DM |
593 | pub fn new(h2: H2Client, canceller: Canceller) -> Arc<Self> { |
594 | Arc::new(Self { h2, canceller }) | |
cb4426b3 WB |
595 | } |
596 | ||
a6782ca1 WB |
597 | pub fn get( |
598 | &self, | |
599 | path: &str, | |
600 | param: Option<Value>, | |
601 | ) -> impl Future<Output = Result<Value, Error>> { | |
9af37c8f | 602 | self.h2.get(path, param) |
b57cb264 DM |
603 | } |
604 | ||
a6782ca1 WB |
605 | pub fn put( |
606 | &self, | |
607 | path: &str, | |
608 | param: Option<Value>, | |
609 | ) -> impl Future<Output = Result<Value, Error>> { | |
9af37c8f | 610 | self.h2.put(path, param) |
82ab7230 DM |
611 | } |
612 | ||
a6782ca1 WB |
613 | pub fn post( |
614 | &self, | |
615 | path: &str, | |
616 | param: Option<Value>, | |
617 | ) -> impl Future<Output = Result<Value, Error>> { | |
9af37c8f | 618 | self.h2.post(path, param) |
97f22ce5 DM |
619 | } |
620 | ||
a6782ca1 | 621 | pub fn finish(self: Arc<Self>) -> impl Future<Output = Result<(), Error>> { |
9cc88a7c DM |
622 | self.h2.clone() |
623 | .post("finish", None) | |
a6782ca1 | 624 | .map_ok(move |_| { |
9cc88a7c DM |
625 | self.canceller.cancel(); |
626 | }) | |
4247fccb DM |
627 | } |
628 | ||
3467cd91 DM |
629 | pub fn force_close(self) { |
630 | self.canceller.cancel(); | |
d6f204ed DM |
631 | } |
632 | ||
9d135fe6 DM |
633 | pub fn upload_blob<R: std::io::Read>( |
634 | &self, | |
635 | mut reader: R, | |
636 | file_name: &str, | |
a6782ca1 | 637 | ) -> impl Future<Output = Result<BackupStats, Error>> { |
9d135fe6 DM |
638 | |
639 | let h2 = self.h2.clone(); | |
640 | let file_name = file_name.to_owned(); | |
641 | ||
a6782ca1 WB |
642 | async move { |
643 | let mut raw_data = Vec::new(); | |
644 | // fixme: avoid loading into memory | |
645 | reader.read_to_end(&mut raw_data)?; | |
646 | ||
647 | let csum = openssl::sha::sha256(&raw_data); | |
648 | let param = json!({"encoded-size": raw_data.len(), "file-name": file_name }); | |
649 | let size = raw_data.len() as u64; // fixme: should be decoded size instead?? | |
650 | let _value = h2.upload("blob", Some(param), raw_data).await?; | |
651 | Ok(BackupStats { size, csum }) | |
652 | } | |
9d135fe6 DM |
653 | } |
654 | ||
9f46c7de DM |
655 | pub fn upload_blob_from_data( |
656 | &self, | |
657 | data: Vec<u8>, | |
658 | file_name: &str, | |
659 | crypt_config: Option<Arc<CryptConfig>>, | |
660 | compress: bool, | |
b335f5b7 | 661 | sign_only: bool, |
a6782ca1 | 662 | ) -> impl Future<Output = Result<BackupStats, Error>> { |
9f46c7de DM |
663 | |
664 | let h2 = self.h2.clone(); | |
665 | let file_name = file_name.to_owned(); | |
2c3891d1 | 666 | let size = data.len() as u64; |
9f46c7de | 667 | |
a6782ca1 WB |
668 | async move { |
669 | let blob = if let Some(crypt_config) = crypt_config { | |
670 | if sign_only { | |
671 | DataBlob::create_signed(&data, crypt_config, compress)? | |
9f46c7de | 672 | } else { |
a6782ca1 WB |
673 | DataBlob::encode(&data, Some(crypt_config.clone()), compress)? |
674 | } | |
675 | } else { | |
676 | DataBlob::encode(&data, None, compress)? | |
677 | }; | |
9f46c7de | 678 | |
a6782ca1 WB |
679 | let raw_data = blob.into_inner(); |
680 | ||
681 | let csum = openssl::sha::sha256(&raw_data); | |
682 | let param = json!({"encoded-size": raw_data.len(), "file-name": file_name }); | |
683 | let _value = h2.upload("blob", Some(param), raw_data).await?; | |
684 | Ok(BackupStats { size, csum }) | |
685 | } | |
9f46c7de DM |
686 | } |
687 | ||
688 | pub fn upload_blob_from_file<P: AsRef<std::path::Path>>( | |
39d6846e | 689 | &self, |
ec8a9bb9 | 690 | src_path: P, |
39d6846e | 691 | file_name: &str, |
cb08ac3e DM |
692 | crypt_config: Option<Arc<CryptConfig>>, |
693 | compress: bool, | |
a6782ca1 | 694 | ) -> impl Future<Output = Result<BackupStats, Error>> { |
39d6846e DM |
695 | |
696 | let h2 = self.h2.clone(); | |
697 | let file_name = file_name.to_owned(); | |
ec8a9bb9 | 698 | let src_path = src_path.as_ref().to_owned(); |
39d6846e | 699 | |
a6782ca1 WB |
700 | async move { |
701 | let mut file = tokio::fs::File::open(src_path.clone()) | |
702 | .await | |
703 | .map_err(move |err| format_err!("unable to open file {:?} - {}", src_path, err))?; | |
704 | ||
705 | let mut contents = Vec::new(); | |
706 | file.read_to_end(&mut contents).await.map_err(Error::from)?; | |
707 | ||
708 | let size: u64 = contents.len() as u64; | |
709 | let blob = DataBlob::encode(&contents, crypt_config, compress)?; | |
710 | let raw_data = blob.into_inner(); | |
711 | let csum = openssl::sha::sha256(&raw_data); | |
712 | let param = json!({ | |
713 | "encoded-size": raw_data.len(), | |
714 | "file-name": file_name, | |
39d6846e | 715 | }); |
a6782ca1 WB |
716 | h2.upload("blob", Some(param), raw_data).await?; |
717 | Ok(BackupStats { size, csum }) | |
718 | } | |
39d6846e DM |
719 | } |
720 | ||
a42fa400 | 721 | pub fn upload_stream( |
d6f204ed DM |
722 | &self, |
723 | archive_name: &str, | |
a6782ca1 | 724 | stream: impl Stream<Item = Result<bytes::BytesMut, Error>>, |
a42fa400 DM |
725 | prefix: &str, |
726 | fixed_size: Option<u64>, | |
f98ac774 | 727 | crypt_config: Option<Arc<CryptConfig>>, |
a6782ca1 | 728 | ) -> impl Future<Output = Result<BackupStats, Error>> { |
d6f204ed DM |
729 | let known_chunks = Arc::new(Mutex::new(HashSet::new())); |
730 | ||
a42fa400 DM |
731 | let mut param = json!({ "archive-name": archive_name }); |
732 | if let Some(size) = fixed_size { | |
733 | param["size"] = size.into(); | |
734 | } | |
735 | ||
736 | let index_path = format!("{}_index", prefix); | |
a42fa400 | 737 | let close_path = format!("{}_close", prefix); |
d6f204ed | 738 | |
642322b4 DM |
739 | let prefix = prefix.to_owned(); |
740 | ||
a6782ca1 WB |
741 | let h2 = self.h2.clone(); |
742 | ||
743 | let download_future = | |
744 | Self::download_chunk_list(h2.clone(), &index_path, archive_name, known_chunks.clone()); | |
745 | ||
746 | async move { | |
747 | download_future.await?; | |
748 | ||
749 | let wid = h2.post(&index_path, Some(param)).await?.as_u64().unwrap(); | |
750 | ||
751 | let (chunk_count, size, _speed, csum) = Self::upload_chunk_info_stream( | |
752 | h2.clone(), | |
753 | wid, | |
754 | stream, | |
755 | &prefix, | |
756 | known_chunks.clone(), | |
757 | crypt_config, | |
758 | ) | |
759 | .await?; | |
760 | ||
761 | let param = json!({ | |
762 | "wid": wid , | |
763 | "chunk-count": chunk_count, | |
764 | "size": size, | |
765 | }); | |
766 | let _value = h2.post(&close_path, Some(param)).await?; | |
767 | Ok(BackupStats { | |
768 | size: size as u64, | |
769 | csum, | |
d6f204ed | 770 | }) |
a6782ca1 | 771 | } |
d6f204ed DM |
772 | } |
773 | ||
6ab34afa | 774 | fn response_queue() -> ( |
82ab7230 | 775 | mpsc::Sender<h2::client::ResponseFuture>, |
a6782ca1 | 776 | oneshot::Receiver<Result<(), Error>> |
82ab7230 DM |
777 | ) { |
778 | let (verify_queue_tx, verify_queue_rx) = mpsc::channel(100); | |
a6782ca1 | 779 | let (verify_result_tx, verify_result_rx) = oneshot::channel(); |
adec8ea2 | 780 | |
82ab7230 DM |
781 | hyper::rt::spawn( |
782 | verify_queue_rx | |
a6782ca1 WB |
783 | .map(Ok::<_, Error>) |
784 | .try_for_each(|response: h2::client::ResponseFuture| { | |
82ab7230 DM |
785 | response |
786 | .map_err(Error::from) | |
9af37c8f | 787 | .and_then(H2Client::h2api_response) |
a6782ca1 | 788 | .map_ok(|result| println!("RESPONSE: {:?}", result)) |
82ab7230 DM |
789 | .map_err(|err| format_err!("pipelined request failed: {}", err)) |
790 | }) | |
a6782ca1 WB |
791 | .map(|result| { |
792 | let _ignore_closed_channel = verify_result_tx.send(result); | |
793 | }) | |
82ab7230 | 794 | ); |
adec8ea2 | 795 | |
82ab7230 DM |
796 | (verify_queue_tx, verify_result_rx) |
797 | } | |
798 | ||
642322b4 | 799 | fn append_chunk_queue(h2: H2Client, wid: u64, path: String) -> ( |
174ad378 | 800 | mpsc::Sender<(MergedChunkInfo, Option<h2::client::ResponseFuture>)>, |
a6782ca1 | 801 | oneshot::Receiver<Result<(), Error>> |
05cba08c | 802 | ) { |
771953f9 | 803 | let (verify_queue_tx, verify_queue_rx) = mpsc::channel(64); |
a6782ca1 | 804 | let (verify_result_tx, verify_result_rx) = oneshot::channel(); |
05cba08c DM |
805 | |
806 | let h2_2 = h2.clone(); | |
807 | ||
808 | hyper::rt::spawn( | |
809 | verify_queue_rx | |
a6782ca1 | 810 | .map(Ok::<_, Error>) |
174ad378 DM |
811 | .and_then(move |(merged_chunk_info, response): (MergedChunkInfo, Option<h2::client::ResponseFuture>)| { |
812 | match (response, merged_chunk_info) { | |
813 | (Some(response), MergedChunkInfo::Known(list)) => { | |
a6782ca1 | 814 | future::Either::Left( |
174ad378 DM |
815 | response |
816 | .map_err(Error::from) | |
817 | .and_then(H2Client::h2api_response) | |
771953f9 | 818 | .and_then(move |_result| { |
a6782ca1 | 819 | future::ok(MergedChunkInfo::Known(list)) |
05cba08c | 820 | }) |
05cba08c DM |
821 | ) |
822 | } | |
174ad378 | 823 | (None, MergedChunkInfo::Known(list)) => { |
a6782ca1 | 824 | future::Either::Right(future::ok(MergedChunkInfo::Known(list))) |
05cba08c | 825 | } |
174ad378 | 826 | _ => unreachable!(), |
05cba08c DM |
827 | } |
828 | }) | |
62436222 | 829 | .merge_known_chunks() |
05cba08c DM |
830 | .and_then(move |merged_chunk_info| { |
831 | match merged_chunk_info { | |
832 | MergedChunkInfo::Known(chunk_list) => { | |
833 | let mut digest_list = vec![]; | |
834 | let mut offset_list = vec![]; | |
835 | for (offset, digest) in chunk_list { | |
bffd40d6 | 836 | //println!("append chunk {} (offset {})", proxmox::tools::digest_to_hex(&digest), offset); |
e18a6c9e | 837 | digest_list.push(digest_to_hex(&digest)); |
05cba08c DM |
838 | offset_list.push(offset); |
839 | } | |
840 | println!("append chunks list len ({})", digest_list.len()); | |
841 | let param = json!({ "wid": wid, "digest-list": digest_list, "offset-list": offset_list }); | |
a42fa400 | 842 | let mut request = H2Client::request_builder("localhost", "PUT", &path, None).unwrap(); |
05cba08c DM |
843 | request.headers_mut().insert(hyper::header::CONTENT_TYPE, HeaderValue::from_static("application/json")); |
844 | let param_data = bytes::Bytes::from(param.to_string().as_bytes()); | |
845 | let upload_data = Some(param_data); | |
846 | h2_2.send_request(request, upload_data) | |
847 | .and_then(move |response| { | |
848 | response | |
849 | .map_err(Error::from) | |
850 | .and_then(H2Client::h2api_response) | |
a6782ca1 | 851 | .map_ok(|_| ()) |
05cba08c DM |
852 | }) |
853 | .map_err(|err| format_err!("pipelined request failed: {}", err)) | |
854 | } | |
855 | _ => unreachable!(), | |
856 | } | |
857 | }) | |
a6782ca1 WB |
858 | .try_for_each(|_| future::ok(())) |
859 | .map(|result| { | |
860 | let _ignore_closed_channel = verify_result_tx.send(result); | |
861 | }) | |
05cba08c DM |
862 | ); |
863 | ||
864 | (verify_queue_tx, verify_result_rx) | |
865 | } | |
866 | ||
6ab34afa | 867 | fn download_chunk_list( |
9af37c8f | 868 | h2: H2Client, |
553610b4 DM |
869 | path: &str, |
870 | archive_name: &str, | |
871 | known_chunks: Arc<Mutex<HashSet<[u8;32]>>>, | |
a6782ca1 | 872 | ) -> impl Future<Output = Result<(), Error>> { |
553610b4 DM |
873 | |
874 | let param = json!({ "archive-name": archive_name }); | |
9af37c8f | 875 | let request = H2Client::request_builder("localhost", "GET", path, Some(param)).unwrap(); |
553610b4 | 876 | |
9af37c8f | 877 | h2.send_request(request, None) |
553610b4 DM |
878 | .and_then(move |response| { |
879 | response | |
880 | .map_err(Error::from) | |
881 | .and_then(move |resp| { | |
882 | let status = resp.status(); | |
7dd1bcac | 883 | |
553610b4 | 884 | if !status.is_success() { |
a6782ca1 WB |
885 | future::Either::Left( |
886 | H2Client::h2api_response(resp) | |
887 | .map(|_| Err(format_err!("unknown error"))) | |
888 | ) | |
7dd1bcac | 889 | } else { |
a6782ca1 | 890 | future::Either::Right(future::ok(resp.into_body())) |
553610b4 | 891 | } |
553610b4 DM |
892 | }) |
893 | .and_then(move |mut body| { | |
894 | ||
895 | let mut release_capacity = body.release_capacity().clone(); | |
896 | ||
986bef16 | 897 | DigestListDecoder::new(body.map_err(Error::from)) |
a6782ca1 | 898 | .try_for_each(move |chunk| { |
553610b4 | 899 | let _ = release_capacity.release_capacity(chunk.len()); |
e18a6c9e | 900 | println!("GOT DOWNLOAD {}", digest_to_hex(&chunk)); |
553610b4 | 901 | known_chunks.lock().unwrap().insert(chunk); |
a6782ca1 | 902 | futures::future::ok(()) |
553610b4 DM |
903 | }) |
904 | }) | |
905 | }) | |
906 | } | |
907 | ||
a42fa400 | 908 | fn upload_chunk_info_stream( |
9af37c8f | 909 | h2: H2Client, |
82ab7230 | 910 | wid: u64, |
a6782ca1 | 911 | stream: impl Stream<Item = Result<bytes::BytesMut, Error>>, |
642322b4 | 912 | prefix: &str, |
553610b4 | 913 | known_chunks: Arc<Mutex<HashSet<[u8;32]>>>, |
f98ac774 | 914 | crypt_config: Option<Arc<CryptConfig>>, |
a6782ca1 | 915 | ) -> impl Future<Output = Result<(usize, usize, usize, [u8; 32]), Error>> { |
adec8ea2 | 916 | |
a6782ca1 | 917 | let repeat = Arc::new(AtomicUsize::new(0)); |
82ab7230 | 918 | let repeat2 = repeat.clone(); |
adec8ea2 | 919 | |
a6782ca1 | 920 | let stream_len = Arc::new(AtomicUsize::new(0)); |
82ab7230 | 921 | let stream_len2 = stream_len.clone(); |
9c9ad941 | 922 | |
642322b4 DM |
923 | let append_chunk_path = format!("{}_index", prefix); |
924 | let upload_chunk_path = format!("{}_chunk", prefix); | |
925 | ||
a6782ca1 WB |
926 | let (upload_queue, upload_result) = |
927 | Self::append_chunk_queue(h2.clone(), wid, append_chunk_path.to_owned()); | |
9c9ad941 | 928 | |
82ab7230 | 929 | let start_time = std::time::Instant::now(); |
9c9ad941 | 930 | |
dbed4c8c DM |
931 | let index_csum = Arc::new(Mutex::new(Some(openssl::sha::Sha256::new()))); |
932 | let index_csum_2 = index_csum.clone(); | |
933 | ||
82ab7230 | 934 | stream |
f98ac774 DM |
935 | .and_then(move |data| { |
936 | ||
937 | let chunk_len = data.len(); | |
938 | ||
82ab7230 | 939 | repeat.fetch_add(1, Ordering::SeqCst); |
f98ac774 DM |
940 | let offset = stream_len.fetch_add(chunk_len, Ordering::SeqCst) as u64; |
941 | ||
942 | let mut chunk_builder = DataChunkBuilder::new(data.as_ref()) | |
943 | .compress(true); | |
944 | ||
945 | if let Some(ref crypt_config) = crypt_config { | |
946 | chunk_builder = chunk_builder.crypt_config(crypt_config); | |
947 | } | |
62436222 DM |
948 | |
949 | let mut known_chunks = known_chunks.lock().unwrap(); | |
f98ac774 | 950 | let digest = chunk_builder.digest(); |
dbed4c8c DM |
951 | |
952 | let mut guard = index_csum.lock().unwrap(); | |
953 | let csum = guard.as_mut().unwrap(); | |
a3e032b7 DM |
954 | |
955 | let chunk_end = offset + chunk_len as u64; | |
956 | ||
957 | csum.update(&chunk_end.to_le_bytes()); | |
dbed4c8c DM |
958 | csum.update(digest); |
959 | ||
f98ac774 | 960 | let chunk_is_known = known_chunks.contains(digest); |
62436222 | 961 | if chunk_is_known { |
a6782ca1 | 962 | future::ok(MergedChunkInfo::Known(vec![(offset, *digest)])) |
62436222 | 963 | } else { |
f98ac774 | 964 | known_chunks.insert(*digest); |
a6782ca1 WB |
965 | future::ready(chunk_builder |
966 | .build() | |
967 | .map(move |chunk| MergedChunkInfo::New(ChunkInfo { | |
968 | chunk, | |
969 | chunk_len: chunk_len as u64, | |
970 | offset, | |
971 | })) | |
972 | ) | |
62436222 | 973 | } |
aa1b2e04 | 974 | }) |
62436222 | 975 | .merge_known_chunks() |
a6782ca1 | 976 | .try_for_each(move |merged_chunk_info| { |
174ad378 DM |
977 | |
978 | if let MergedChunkInfo::New(chunk_info) = merged_chunk_info { | |
979 | let offset = chunk_info.offset; | |
f98ac774 | 980 | let digest = *chunk_info.chunk.digest(); |
e18a6c9e | 981 | let digest_str = digest_to_hex(&digest); |
174ad378 | 982 | |
f98ac774 DM |
983 | println!("upload new chunk {} ({} bytes, offset {})", digest_str, |
984 | chunk_info.chunk_len, offset); | |
985 | ||
986 | let chunk_data = chunk_info.chunk.raw_data(); | |
987 | let param = json!({ | |
988 | "wid": wid, | |
989 | "digest": digest_str, | |
990 | "size": chunk_info.chunk_len, | |
991 | "encoded-size": chunk_data.len(), | |
992 | }); | |
174ad378 | 993 | |
642322b4 | 994 | let request = H2Client::request_builder("localhost", "POST", &upload_chunk_path, Some(param)).unwrap(); |
f98ac774 | 995 | let upload_data = Some(bytes::Bytes::from(chunk_data)); |
174ad378 | 996 | |
8de20e5c | 997 | let new_info = MergedChunkInfo::Known(vec![(offset, digest)]); |
174ad378 | 998 | |
a6782ca1 WB |
999 | let mut upload_queue = upload_queue.clone(); |
1000 | future::Either::Left(h2 | |
1001 | .send_request(request, upload_data) | |
1002 | .and_then(move |response| async move { | |
1003 | upload_queue | |
1004 | .send((new_info, Some(response))) | |
1005 | .await | |
1006 | .map_err(Error::from) | |
1007 | }) | |
174ad378 DM |
1008 | ) |
1009 | } else { | |
a6782ca1 WB |
1010 | let mut upload_queue = upload_queue.clone(); |
1011 | future::Either::Right(async move { | |
1012 | upload_queue | |
1013 | .send((merged_chunk_info, None)) | |
1014 | .await | |
1015 | .map_err(Error::from) | |
1016 | }) | |
174ad378 | 1017 | } |
82ab7230 | 1018 | }) |
a6782ca1 WB |
1019 | .then(move |result| async move { |
1020 | upload_result.await?.and(result) | |
1021 | }.boxed()) | |
82ab7230 DM |
1022 | .and_then(move |_| { |
1023 | let repeat = repeat2.load(Ordering::SeqCst); | |
1024 | let stream_len = stream_len2.load(Ordering::SeqCst); | |
1025 | let speed = ((stream_len*1000000)/(1024*1024))/(start_time.elapsed().as_micros() as usize); | |
1026 | println!("Uploaded {} chunks in {} seconds ({} MB/s).", repeat, start_time.elapsed().as_secs(), speed); | |
1027 | if repeat > 0 { | |
1028 | println!("Average chunk size was {} bytes.", stream_len/repeat); | |
1029 | println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128)); | |
1030 | } | |
dbed4c8c DM |
1031 | |
1032 | let mut guard = index_csum_2.lock().unwrap(); | |
1033 | let csum = guard.take().unwrap().finish(); | |
1034 | ||
a6782ca1 | 1035 | futures::future::ok((repeat, stream_len, speed, csum)) |
82ab7230 DM |
1036 | }) |
1037 | } | |
1038 | ||
a6782ca1 | 1039 | pub fn upload_speedtest(&self) -> impl Future<Output = Result<usize, Error>> { |
82ab7230 DM |
1040 | |
1041 | let mut data = vec![]; | |
1042 | // generate pseudo random byte sequence | |
1043 | for i in 0..1024*1024 { | |
1044 | for j in 0..4 { | |
1045 | let byte = ((i >> (j<<3))&0xff) as u8; | |
1046 | data.push(byte); | |
1047 | } | |
1048 | } | |
1049 | ||
1050 | let item_len = data.len(); | |
1051 | ||
a6782ca1 | 1052 | let repeat = Arc::new(AtomicUsize::new(0)); |
82ab7230 DM |
1053 | let repeat2 = repeat.clone(); |
1054 | ||
6ab34afa | 1055 | let (upload_queue, upload_result) = Self::response_queue(); |
82ab7230 DM |
1056 | |
1057 | let start_time = std::time::Instant::now(); | |
1058 | ||
6ab34afa | 1059 | let h2 = self.h2.clone(); |
82ab7230 DM |
1060 | |
1061 | futures::stream::repeat(data) | |
1062 | .take_while(move |_| { | |
a6782ca1 WB |
1063 | let repeat = Arc::clone(&repeat); |
1064 | async move { | |
1065 | repeat.fetch_add(1, Ordering::SeqCst); | |
1066 | start_time.elapsed().as_secs() < 5 | |
1067 | } | |
82ab7230 | 1068 | }) |
a6782ca1 WB |
1069 | .map(Ok) |
1070 | .try_for_each(move |data| { | |
6ab34afa | 1071 | let h2 = h2.clone(); |
82ab7230 | 1072 | |
a6782ca1 | 1073 | let mut upload_queue = upload_queue.clone(); |
82ab7230 DM |
1074 | |
1075 | println!("send test data ({} bytes)", data.len()); | |
9af37c8f DM |
1076 | let request = H2Client::request_builder("localhost", "POST", "speedtest", None).unwrap(); |
1077 | h2.send_request(request, Some(bytes::Bytes::from(data))) | |
a6782ca1 WB |
1078 | .and_then(move |response| async move { |
1079 | upload_queue | |
1080 | .send(response) | |
1081 | .await | |
1082 | .map_err(Error::from) | |
adec8ea2 DM |
1083 | }) |
1084 | }) | |
a6782ca1 | 1085 | .then(move |result| async move { |
82ab7230 | 1086 | println!("RESULT {:?}", result); |
a6782ca1 | 1087 | upload_result.await?.and(result) |
82ab7230 | 1088 | }) |
82ab7230 DM |
1089 | .and_then(move |_| { |
1090 | let repeat = repeat2.load(Ordering::SeqCst); | |
1091 | println!("Uploaded {} chunks in {} seconds.", repeat, start_time.elapsed().as_secs()); | |
1092 | let speed = ((item_len*1000000*(repeat as usize))/(1024*1024))/(start_time.elapsed().as_micros() as usize); | |
1093 | if repeat > 0 { | |
1094 | println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128)); | |
1095 | } | |
a6782ca1 | 1096 | futures::future::ok(speed) |
82ab7230 | 1097 | }) |
adec8ea2 | 1098 | } |
9af37c8f DM |
1099 | } |
1100 | ||
1101 | #[derive(Clone)] | |
1102 | pub struct H2Client { | |
1103 | h2: h2::client::SendRequest<bytes::Bytes>, | |
1104 | } | |
1105 | ||
1106 | impl H2Client { | |
1107 | ||
1108 | pub fn new(h2: h2::client::SendRequest<bytes::Bytes>) -> Self { | |
1109 | Self { h2 } | |
1110 | } | |
1111 | ||
a6782ca1 | 1112 | pub fn get(&self, path: &str, param: Option<Value>) -> impl Future<Output = Result<Value, Error>> { |
9af37c8f DM |
1113 | let req = Self::request_builder("localhost", "GET", path, param).unwrap(); |
1114 | self.request(req) | |
1115 | } | |
1116 | ||
a6782ca1 | 1117 | pub fn put(&self, path: &str, param: Option<Value>) -> impl Future<Output = Result<Value, Error>> { |
9af37c8f DM |
1118 | let req = Self::request_builder("localhost", "PUT", path, param).unwrap(); |
1119 | self.request(req) | |
1120 | } | |
1121 | ||
a6782ca1 | 1122 | pub fn post(&self, path: &str, param: Option<Value>) -> impl Future<Output = Result<Value, Error>> { |
9af37c8f DM |
1123 | let req = Self::request_builder("localhost", "POST", path, param).unwrap(); |
1124 | self.request(req) | |
1125 | } | |
1126 | ||
a6782ca1 WB |
1127 | pub fn download<W: Write + Send + 'static>( |
1128 | &self, | |
1129 | path: &str, | |
1130 | param: Option<Value>, | |
1131 | output: W, | |
1132 | ) -> impl Future<Output = Result<W, Error>> { | |
dd066d28 DM |
1133 | let request = Self::request_builder("localhost", "GET", path, param).unwrap(); |
1134 | ||
1135 | self.send_request(request, None) | |
1136 | .and_then(move |response| { | |
1137 | response | |
1138 | .map_err(Error::from) | |
1139 | .and_then(move |resp| { | |
1140 | let status = resp.status(); | |
1141 | if !status.is_success() { | |
a6782ca1 | 1142 | future::Either::Left( |
dd066d28 | 1143 | H2Client::h2api_response(resp) |
a6782ca1 | 1144 | .map(|_| Err(format_err!("unknown error"))) |
dd066d28 DM |
1145 | ) |
1146 | } else { | |
984a7c35 | 1147 | let mut body = resp.into_body(); |
a6782ca1 | 1148 | let release_capacity = body.release_capacity().clone(); |
984a7c35 | 1149 | |
a6782ca1 | 1150 | future::Either::Right( |
984a7c35 | 1151 | body |
dd066d28 | 1152 | .map_err(Error::from) |
a6782ca1 WB |
1153 | .try_fold(output, move |mut acc, chunk| { |
1154 | let mut release_capacity = release_capacity.clone(); | |
1155 | async move { | |
1156 | let _ = release_capacity.release_capacity(chunk.len()); | |
1157 | acc.write_all(&chunk)?; | |
1158 | Ok::<_, Error>(acc) | |
1159 | } | |
dd066d28 DM |
1160 | }) |
1161 | ) | |
1162 | } | |
1163 | }) | |
1164 | }) | |
1165 | } | |
1166 | ||
a6782ca1 WB |
1167 | pub fn upload( |
1168 | &self, | |
1169 | path: &str, | |
1170 | param: Option<Value>, | |
1171 | data: Vec<u8>, | |
1172 | ) -> impl Future<Output = Result<Value, Error>> { | |
9af37c8f DM |
1173 | let request = Self::request_builder("localhost", "POST", path, param).unwrap(); |
1174 | ||
9af37c8f DM |
1175 | self.h2.clone() |
1176 | .ready() | |
1177 | .map_err(Error::from) | |
1178 | .and_then(move |mut send_request| { | |
1179 | let (response, stream) = send_request.send_request(request, false).unwrap(); | |
1180 | PipeToSendStream::new(bytes::Bytes::from(data), stream) | |
1181 | .and_then(|_| { | |
1182 | response | |
1183 | .map_err(Error::from) | |
1184 | .and_then(Self::h2api_response) | |
1185 | }) | |
1186 | }) | |
1187 | } | |
adec8ea2 | 1188 | |
b57cb264 | 1189 | fn request( |
9af37c8f | 1190 | &self, |
b57cb264 | 1191 | request: Request<()>, |
a6782ca1 | 1192 | ) -> impl Future<Output = Result<Value, Error>> { |
b57cb264 | 1193 | |
9af37c8f | 1194 | self.send_request(request, None) |
82ab7230 DM |
1195 | .and_then(move |response| { |
1196 | response | |
1197 | .map_err(Error::from) | |
1198 | .and_then(Self::h2api_response) | |
1199 | }) | |
1200 | } | |
1201 | ||
1202 | fn send_request( | |
9af37c8f | 1203 | &self, |
82ab7230 DM |
1204 | request: Request<()>, |
1205 | data: Option<bytes::Bytes>, | |
a6782ca1 | 1206 | ) -> impl Future<Output = Result<h2::client::ResponseFuture, Error>> { |
82ab7230 | 1207 | |
9af37c8f | 1208 | self.h2.clone() |
10130cf4 DM |
1209 | .ready() |
1210 | .map_err(Error::from) | |
1211 | .and_then(move |mut send_request| { | |
82ab7230 DM |
1212 | if let Some(data) = data { |
1213 | let (response, stream) = send_request.send_request(request, false).unwrap(); | |
a6782ca1 | 1214 | future::Either::Left(PipeToSendStream::new(data, stream) |
82ab7230 DM |
1215 | .and_then(move |_| { |
1216 | future::ok(response) | |
1217 | })) | |
1218 | } else { | |
1219 | let (response, _stream) = send_request.send_request(request, true).unwrap(); | |
a6782ca1 | 1220 | future::Either::Right(future::ok(response)) |
82ab7230 | 1221 | } |
b57cb264 DM |
1222 | }) |
1223 | } | |
1224 | ||
a6782ca1 WB |
1225 | fn h2api_response( |
1226 | response: Response<h2::RecvStream>, | |
1227 | ) -> impl Future<Output = Result<Value, Error>> { | |
b57cb264 DM |
1228 | let status = response.status(); |
1229 | ||
1230 | let (_head, mut body) = response.into_parts(); | |
1231 | ||
1232 | // The `release_capacity` handle allows the caller to manage | |
1233 | // flow control. | |
1234 | // | |
1235 | // Whenever data is received, the caller is responsible for | |
1236 | // releasing capacity back to the server once it has freed | |
1237 | // the data from memory. | |
1238 | let mut release_capacity = body.release_capacity().clone(); | |
1239 | ||
1240 | body | |
a6782ca1 | 1241 | .map_ok(move |chunk| { |
b57cb264 DM |
1242 | // Let the server send more data. |
1243 | let _ = release_capacity.release_capacity(chunk.len()); | |
1244 | chunk | |
1245 | }) | |
a6782ca1 | 1246 | .try_concat() |
b57cb264 | 1247 | .map_err(Error::from) |
a6782ca1 | 1248 | .and_then(move |data| async move { |
b57cb264 DM |
1249 | let text = String::from_utf8(data.to_vec()).unwrap(); |
1250 | if status.is_success() { | |
1251 | if text.len() > 0 { | |
1252 | let mut value: Value = serde_json::from_str(&text)?; | |
1253 | if let Some(map) = value.as_object_mut() { | |
1254 | if let Some(data) = map.remove("data") { | |
1255 | return Ok(data); | |
1256 | } | |
1257 | } | |
1258 | bail!("got result without data property"); | |
1259 | } else { | |
1260 | Ok(Value::Null) | |
1261 | } | |
1262 | } else { | |
1263 | bail!("HTTP Error {}: {}", status, text); | |
1264 | } | |
a6782ca1 | 1265 | }.boxed()) |
b57cb264 DM |
1266 | } |
1267 | ||
eb2bdd1b | 1268 | // Note: We always encode parameters with the url |
b57cb264 DM |
1269 | pub fn request_builder(server: &str, method: &str, path: &str, data: Option<Value>) -> Result<Request<()>, Error> { |
1270 | let path = path.trim_matches('/'); | |
b57cb264 DM |
1271 | |
1272 | if let Some(data) = data { | |
1273 | let query = tools::json_object_to_query(data)?; | |
eb2bdd1b DM |
1274 | // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side |
1275 | if query.len() > 4096 { bail!("h2 query data too large ({} bytes) - please encode data inside body", query.len()); } | |
b57cb264 | 1276 | let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?; |
eb2bdd1b | 1277 | let request = Request::builder() |
b57cb264 DM |
1278 | .method(method) |
1279 | .uri(url) | |
1280 | .header("User-Agent", "proxmox-backup-client/1.0") | |
1281 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
1282 | .body(())?; | |
1283 | return Ok(request); | |
eb2bdd1b DM |
1284 | } else { |
1285 | let url: Uri = format!("https://{}:8007/{}", server, path).parse()?; | |
1286 | let request = Request::builder() | |
1287 | .method(method) | |
1288 | .uri(url) | |
1289 | .header("User-Agent", "proxmox-backup-client/1.0") | |
1290 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
1291 | .body(())?; | |
b57cb264 | 1292 | |
eb2bdd1b DM |
1293 | Ok(request) |
1294 | } | |
b57cb264 DM |
1295 | } |
1296 | } | |
1434f4f8 WB |
1297 | |
1298 | pub struct HttpsConnector { | |
1299 | http: HttpConnector, | |
1300 | ssl_connector: SslConnector, | |
1301 | } | |
1302 | ||
1303 | impl HttpsConnector { | |
1304 | pub fn with_connector(mut http: HttpConnector, ssl_connector: SslConnector) -> Self { | |
1305 | http.enforce_http(false); | |
1306 | ||
1307 | Self { | |
1308 | http, | |
1309 | ssl_connector, | |
1310 | } | |
1311 | } | |
1312 | } | |
1313 | ||
1314 | type MaybeTlsStream = EitherStream< | |
1315 | tokio::net::TcpStream, | |
1316 | tokio_openssl::SslStream<tokio::net::TcpStream>, | |
1317 | >; | |
1318 | ||
1319 | impl hyper::client::connect::Connect for HttpsConnector { | |
1320 | type Transport = MaybeTlsStream; | |
1321 | type Error = Error; | |
1322 | type Future = Box<dyn Future<Output = Result<( | |
1323 | Self::Transport, | |
1324 | hyper::client::connect::Connected, | |
1325 | ), Error>> + Send + Unpin + 'static>; | |
1326 | ||
1327 | fn connect(&self, dst: hyper::client::connect::Destination) -> Self::Future { | |
1328 | let is_https = dst.scheme() == "https"; | |
1329 | let host = dst.host().to_string(); | |
1330 | ||
1331 | let config = self.ssl_connector.configure(); | |
1332 | let conn = self.http.connect(dst); | |
1333 | ||
1334 | Box::new(Box::pin(async move { | |
1335 | let (conn, connected) = conn.await?; | |
1336 | if is_https { | |
1337 | let conn = tokio_openssl::connect(config?, &host, conn).await?; | |
1338 | Ok((MaybeTlsStream::Right(conn), connected)) | |
1339 | } else { | |
1340 | Ok((MaybeTlsStream::Left(conn), connected)) | |
1341 | } | |
1342 | })) | |
1343 | } | |
1344 | } |