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