]> git.proxmox.com Git - proxmox-backup.git/blame - src/client/http_client.rs
src/bin/proxmox-backup-client.rs: pass verbose flag to dump_image
[proxmox-backup.git] / src / client / http_client.rs
CommitLineData
553610b4 1use std::collections::HashSet;
c2b94534 2use std::io::Write;
7a57cb77
WB
3use std::sync::atomic::{AtomicUsize, Ordering};
4use std::sync::{Arc, Mutex};
597641fd 5
7a57cb77
WB
6use chrono::{DateTime, Utc};
7use failure::*;
82ab7230 8use futures::*;
1fdb4c6f 9use futures::stream::Stream;
7a57cb77
WB
10use http::Uri;
11use http::header::HeaderValue;
12use http::{Request, Response};
13use hyper::Body;
1434f4f8 14use hyper::client::{Client, HttpConnector};
6d1f61b2 15use openssl::ssl::{SslConnector, SslMethod};
ba3a60b2 16use serde_json::{json, Value};
a6782ca1
WB
17use tokio::io::AsyncReadExt;
18use tokio::sync::{mpsc, oneshot};
0dffe3f9 19use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
7a57cb77 20use xdg::BaseDirectories;
1fdb4c6f 21
e18a6c9e
DM
22use proxmox::tools::{
23 digest_to_hex,
24 fs::{file_get_json, file_set_contents},
25};
26
7a57cb77
WB
27use super::merge_known_chunks::{MergedChunkInfo, MergeKnownChunks};
28use super::pipe_to_stream::PipeToSendStream;
986bef16 29use crate::backup::*;
1434f4f8 30use crate::tools::async_io::EitherStream;
7a57cb77 31use crate::tools::futures::{cancellable, Canceller};
1434f4f8 32use crate::tools::{self, tty, BroadcastFuture};
986bef16 33
5a2df000 34#[derive(Clone)]
e240d8be 35pub struct AuthInfo {
5a2df000
DM
36 username: String,
37 ticket: String,
38 token: String,
39}
56458d97 40
151c6ce2 41/// HTTP(S) API client
597641fd 42pub 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)
49pub 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
69fn 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
105fn 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
126impl 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_backup_reader(
dd066d28
DM
319 &self,
320 datastore: &str,
321 backup_type: &str,
322 backup_id: &str,
fa5d6977 323 backup_time: DateTime<Utc>,
dd066d28 324 debug: bool,
1a7a0e74 325 ) -> Result<Arc<BackupReader>, Error> {
dd066d28
DM
326
327 let param = json!({
328 "backup-type": backup_type,
329 "backup-id": backup_id,
330 "backup-time": backup_time.timestamp(),
331 "store": datastore,
332 "debug": debug,
333 });
334 let req = Self::request_builder(&self.server, "GET", "/api2/json/reader", Some(param)).unwrap();
335
1a7a0e74
DM
336 let (h2, canceller) = self.start_h2_connection(req, String::from(PROXMOX_BACKUP_READER_PROTOCOL_ID_V1!())).await?;
337
338 Ok(BackupReader::new(h2, canceller))
dd066d28
DM
339 }
340
1a7a0e74 341 pub async fn start_h2_connection(
fb047083
DM
342 &self,
343 mut req: Request<Body>,
344 protocol_name: String,
1a7a0e74 345 ) -> Result<(H2Client, Canceller), Error> {
cf639a47 346
1a7a0e74 347 let auth = self.login().await?;
cf639a47
DM
348 let client = self.client.clone();
349
1a7a0e74
DM
350 let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
351 req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
352 req.headers_mut().insert("UPGRADE", HeaderValue::from_str(&protocol_name).unwrap());
cf639a47 353
1a7a0e74
DM
354 let resp = client.request(req).await?;
355 let status = resp.status();
cf639a47 356
1a7a0e74
DM
357 if status != http::StatusCode::SWITCHING_PROTOCOLS {
358 Self::api_response(resp)
359 .map(|_| Err(format_err!("unknown error")))
360 .await?;
361 unreachable!();
362 }
363
364 let upgraded = resp
365 .into_body()
366 .on_upgrade()
367 .await?;
368
369 let max_window_size = (1 << 31) - 2;
370
371 let (h2, connection) = h2::client::Builder::new()
372 .initial_connection_window_size(max_window_size)
373 .initial_window_size(max_window_size)
374 .max_frame_size(4*1024*1024)
375 .handshake(upgraded)
376 .await?;
377
378 let connection = connection
379 .map_err(|_| panic!("HTTP/2.0 connection failed"));
380
381 let (connection, canceller) = cancellable(connection)?;
382 // A cancellable future returns an Option which is None when cancelled and
383 // Some when it finished instead, since we don't care about the return type we
384 // need to map it away:
385 let connection = connection.map(|_| ());
386
387 // Spawn a new task to drive the connection state
388 hyper::rt::spawn(connection);
389
390 // Wait until the `SendRequest` handle has available capacity.
391 let c = h2.ready().await?;
392 Ok((H2Client::new(c), canceller))
cf639a47
DM
393 }
394
9d35dbbb 395 async fn credentials(
1434f4f8 396 client: Client<HttpsConnector>,
45cdce06
DM
397 server: String,
398 username: String,
399 password: String,
9d35dbbb
DM
400 ) -> Result<AuthInfo, Error> {
401 let data = json!({ "username": username, "password": password });
402 let req = Self::request_builder(&server, "POST", "/api2/json/access/ticket", Some(data)).unwrap();
403 let cred = Self::api_request(client, req).await?;
404 let auth = AuthInfo {
405 username: cred["data"]["username"].as_str().unwrap().to_owned(),
406 ticket: cred["data"]["ticket"].as_str().unwrap().to_owned(),
407 token: cred["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
408 };
409
410 let _ = store_ticket_info(&server, &auth.username, &auth.ticket, &auth.token);
411
412 Ok(auth)
ba3a60b2
DM
413 }
414
a6782ca1 415 async fn api_response(response: Response<Body>) -> Result<Value, Error> {
d2c48afc 416 let status = response.status();
a6782ca1 417 let data = response
d2c48afc 418 .into_body()
a6782ca1
WB
419 .try_concat()
420 .await?;
421
422 let text = String::from_utf8(data.to_vec()).unwrap();
423 if status.is_success() {
424 if text.len() > 0 {
425 let value: Value = serde_json::from_str(&text)?;
426 Ok(value)
427 } else {
428 Ok(Value::Null)
429 }
430 } else {
431 bail!("HTTP Error {}: {}", status, text);
432 }
d2c48afc
DM
433 }
434
1a7a0e74 435 async fn api_request(
1434f4f8 436 client: Client<HttpsConnector>,
5a2df000 437 req: Request<Body>
1a7a0e74 438 ) -> Result<Value, Error> {
ba3a60b2 439
5a2df000
DM
440 client.request(req)
441 .map_err(Error::from)
d2c48afc 442 .and_then(Self::api_response)
1a7a0e74 443 .await
0dffe3f9
DM
444 }
445
5a2df000 446 pub fn request_builder(server: &str, method: &str, path: &str, data: Option<Value>) -> Result<Request<Body>, Error> {
591f570b 447 let path = path.trim_matches('/');
5a2df000
DM
448 let url: Uri = format!("https://{}:8007/{}", server, path).parse()?;
449
450 if let Some(data) = data {
451 if method == "POST" {
452 let request = Request::builder()
453 .method(method)
454 .uri(url)
455 .header("User-Agent", "proxmox-backup-client/1.0")
456 .header(hyper::header::CONTENT_TYPE, "application/json")
457 .body(Body::from(data.to_string()))?;
458 return Ok(request);
459 } else {
9e391bb7
DM
460 let query = tools::json_object_to_query(data)?;
461 let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?;
462 let request = Request::builder()
463 .method(method)
464 .uri(url)
465 .header("User-Agent", "proxmox-backup-client/1.0")
466 .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
467 .body(Body::empty())?;
468 return Ok(request);
5a2df000 469 }
5a2df000 470 }
0dffe3f9 471
1fdb4c6f 472 let request = Request::builder()
5a2df000 473 .method(method)
1fdb4c6f
DM
474 .uri(url)
475 .header("User-Agent", "proxmox-backup-client/1.0")
5a2df000
DM
476 .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
477 .body(Body::empty())?;
1fdb4c6f 478
5a2df000 479 Ok(request)
597641fd
DM
480 }
481}
b57cb264 482
dd066d28
DM
483
484pub struct BackupReader {
485 h2: H2Client,
3467cd91 486 canceller: Canceller,
dd066d28
DM
487}
488
489impl Drop for BackupReader {
490
491 fn drop(&mut self) {
3467cd91 492 self.canceller.cancel();
dd066d28
DM
493 }
494}
495
496impl BackupReader {
497
3467cd91 498 pub fn new(h2: H2Client, canceller: Canceller) -> Arc<Self> {
44fed91e 499 Arc::new(Self { h2, canceller })
dd066d28
DM
500 }
501
d4a085e5 502 pub async fn get(
a6782ca1
WB
503 &self,
504 path: &str,
505 param: Option<Value>,
d4a085e5
DM
506 ) -> Result<Value, Error> {
507 self.h2.get(path, param).await
dd066d28
DM
508 }
509
d4a085e5 510 pub async fn put(
a6782ca1
WB
511 &self,
512 path: &str,
513 param: Option<Value>,
d4a085e5
DM
514 ) -> Result<Value, Error> {
515 self.h2.put(path, param).await
dd066d28
DM
516 }
517
d4a085e5 518 pub async fn post(
a6782ca1
WB
519 &self,
520 path: &str,
521 param: Option<Value>,
d4a085e5
DM
522 ) -> Result<Value, Error> {
523 self.h2.post(path, param).await
dd066d28
DM
524 }
525
d4a085e5 526 pub async fn download<W: Write + Send>(
dd066d28
DM
527 &self,
528 file_name: &str,
529 output: W,
d4a085e5 530 ) -> Result<W, Error> {
dd066d28
DM
531 let path = "download";
532 let param = json!({ "file-name": file_name });
d4a085e5 533 self.h2.download(path, Some(param), output).await
dd066d28
DM
534 }
535
d4a085e5 536 pub async fn speedtest<W: Write + Send>(
17243003
DM
537 &self,
538 output: W,
d4a085e5
DM
539 ) -> Result<W, Error> {
540 self.h2.download("speedtest", None, output).await
17243003
DM
541 }
542
d4a085e5 543 pub async fn download_chunk<W: Write + Send>(
fcf5dea5
DM
544 &self,
545 digest: &[u8; 32],
546 output: W,
d4a085e5 547 ) -> Result<W, Error> {
fcf5dea5 548 let path = "chunk";
e18a6c9e 549 let param = json!({ "digest": digest_to_hex(digest) });
d4a085e5 550 self.h2.download(path, Some(param), output).await
fcf5dea5
DM
551 }
552
4f6aaf54 553 pub fn force_close(self) {
3467cd91 554 self.canceller.cancel();
dd066d28
DM
555 }
556}
557
6ab34afa 558pub struct BackupClient {
9af37c8f 559 h2: H2Client,
3467cd91 560 canceller: Canceller,
b57cb264
DM
561}
562
dd066d28
DM
563impl Drop for BackupClient {
564
565 fn drop(&mut self) {
3467cd91 566 self.canceller.cancel();
dd066d28
DM
567 }
568}
91320f08 569
2c3891d1
DM
570pub struct BackupStats {
571 pub size: u64,
c807d231 572 pub csum: [u8; 32],
2c3891d1
DM
573}
574
6ab34afa 575impl BackupClient {
3467cd91
DM
576 pub fn new(h2: H2Client, canceller: Canceller) -> Arc<Self> {
577 Arc::new(Self { h2, canceller })
cb4426b3
WB
578 }
579
2a1e6d7d 580 pub async fn get(
a6782ca1
WB
581 &self,
582 path: &str,
583 param: Option<Value>,
2a1e6d7d
DM
584 ) -> Result<Value, Error> {
585 self.h2.get(path, param).await
b57cb264
DM
586 }
587
2a1e6d7d 588 pub async fn put(
a6782ca1
WB
589 &self,
590 path: &str,
591 param: Option<Value>,
2a1e6d7d
DM
592 ) -> Result<Value, Error> {
593 self.h2.put(path, param).await
82ab7230
DM
594 }
595
2a1e6d7d 596 pub async fn post(
a6782ca1
WB
597 &self,
598 path: &str,
599 param: Option<Value>,
2a1e6d7d
DM
600 ) -> Result<Value, Error> {
601 self.h2.post(path, param).await
97f22ce5
DM
602 }
603
f011dba0
DM
604 pub async fn upload_post(
605 &self,
606 path: &str,
607 param: Option<Value>,
608 content_type: &str,
609 data: Vec<u8>,
610 ) -> Result<Value, Error> {
c8c4051a 611 self.h2.upload("POST", path, param, content_type, data).await
f011dba0
DM
612 }
613
f16aea68
DM
614 pub async fn send_upload_request(
615 &self,
616 method: &str,
617 path: &str,
618 param: Option<Value>,
619 content_type: &str,
620 data: Vec<u8>,
621 ) -> Result<h2::client::ResponseFuture, Error> {
622
623 let request = H2Client::request_builder("localhost", method, path, param, Some(content_type)).unwrap();
624 let response_future = self.h2.send_request(request, Some(bytes::Bytes::from(data.clone()))).await?;
625 Ok(response_future)
626 }
627
f011dba0 628 pub async fn upload_put(
15bb1bba
DM
629 &self,
630 path: &str,
631 param: Option<Value>,
792a70b9 632 content_type: &str,
15bb1bba
DM
633 data: Vec<u8>,
634 ) -> Result<Value, Error> {
c8c4051a 635 self.h2.upload("PUT", path, param, content_type, data).await
15bb1bba
DM
636 }
637
2a1e6d7d
DM
638 pub async fn finish(self: Arc<Self>) -> Result<(), Error> {
639 let h2 = self.h2.clone();
640
641 h2.post("finish", None)
a6782ca1 642 .map_ok(move |_| {
9cc88a7c
DM
643 self.canceller.cancel();
644 })
2a1e6d7d 645 .await
4247fccb
DM
646 }
647
3467cd91
DM
648 pub fn force_close(self) {
649 self.canceller.cancel();
d6f204ed
DM
650 }
651
2f831bae 652 pub async fn upload_blob<R: std::io::Read>(
9d135fe6
DM
653 &self,
654 mut reader: R,
655 file_name: &str,
2f831bae
DM
656 ) -> Result<BackupStats, Error> {
657 let mut raw_data = Vec::new();
658 // fixme: avoid loading into memory
659 reader.read_to_end(&mut raw_data)?;
9d135fe6 660
2f831bae
DM
661 let csum = openssl::sha::sha256(&raw_data);
662 let param = json!({"encoded-size": raw_data.len(), "file-name": file_name });
ff01c1e3 663 let size = raw_data.len() as u64;
c8c4051a 664 let _value = self.h2.upload("POST", "blob", Some(param), "application/octet-stream", raw_data).await?;
2f831bae 665 Ok(BackupStats { size, csum })
9d135fe6
DM
666 }
667
2f831bae 668 pub async fn upload_blob_from_data(
9f46c7de
DM
669 &self,
670 data: Vec<u8>,
671 file_name: &str,
672 crypt_config: Option<Arc<CryptConfig>>,
673 compress: bool,
b335f5b7 674 sign_only: bool,
2f831bae 675 ) -> Result<BackupStats, Error> {
9f46c7de 676
7123ff7d 677 let blob = if let Some(ref crypt_config) = crypt_config {
2f831bae
DM
678 if sign_only {
679 DataBlob::create_signed(&data, crypt_config, compress)?
a6782ca1 680 } else {
4ee8f53d 681 DataBlob::encode(&data, Some(crypt_config), compress)?
2f831bae
DM
682 }
683 } else {
684 DataBlob::encode(&data, None, compress)?
685 };
9f46c7de 686
2f831bae 687 let raw_data = blob.into_inner();
ff01c1e3 688 let size = raw_data.len() as u64;
a6782ca1 689
2f831bae 690 let csum = openssl::sha::sha256(&raw_data);
ff01c1e3 691 let param = json!({"encoded-size": size, "file-name": file_name });
c8c4051a 692 let _value = self.h2.upload("POST", "blob", Some(param), "application/octet-stream", raw_data).await?;
2f831bae 693 Ok(BackupStats { size, csum })
9f46c7de
DM
694 }
695
2f831bae 696 pub async fn upload_blob_from_file<P: AsRef<std::path::Path>>(
39d6846e 697 &self,
ec8a9bb9 698 src_path: P,
39d6846e 699 file_name: &str,
cb08ac3e
DM
700 crypt_config: Option<Arc<CryptConfig>>,
701 compress: bool,
2f831bae 702 ) -> Result<BackupStats, Error> {
39d6846e 703
2f831bae
DM
704 let src_path = src_path.as_ref();
705
34a3845b 706 let mut file = tokio::fs::File::open(src_path)
2f831bae
DM
707 .await
708 .map_err(|err| format_err!("unable to open file {:?} - {}", src_path, err))?;
709
710 let mut contents = Vec::new();
711
712 file.read_to_end(&mut contents)
713 .await
714 .map_err(|err| format_err!("unable to read file {:?} - {}", src_path, err))?;
715
7123ff7d 716 let blob = DataBlob::encode(&contents, crypt_config.as_ref().map(AsRef::as_ref), compress)?;
2f831bae 717 let raw_data = blob.into_inner();
ff01c1e3 718 let size = raw_data.len() as u64;
2f831bae
DM
719 let csum = openssl::sha::sha256(&raw_data);
720 let param = json!({
ff01c1e3 721 "encoded-size": size,
2f831bae
DM
722 "file-name": file_name,
723 });
c8c4051a 724 self.h2.upload("POST", "blob", Some(param), "application/octet-stream", raw_data).await?;
2f831bae 725 Ok(BackupStats { size, csum })
39d6846e
DM
726 }
727
2f831bae 728 pub async fn upload_stream(
d6f204ed
DM
729 &self,
730 archive_name: &str,
a6782ca1 731 stream: impl Stream<Item = Result<bytes::BytesMut, Error>>,
a42fa400
DM
732 prefix: &str,
733 fixed_size: Option<u64>,
f98ac774 734 crypt_config: Option<Arc<CryptConfig>>,
2f831bae 735 ) -> Result<BackupStats, Error> {
d6f204ed
DM
736 let known_chunks = Arc::new(Mutex::new(HashSet::new()));
737
a42fa400
DM
738 let mut param = json!({ "archive-name": archive_name });
739 if let Some(size) = fixed_size {
740 param["size"] = size.into();
741 }
742
743 let index_path = format!("{}_index", prefix);
a42fa400 744 let close_path = format!("{}_close", prefix);
d6f204ed 745
6d4df36c 746 self.download_chunk_list(&index_path, archive_name, known_chunks.clone()).await?;
a6782ca1 747
2f831bae 748 let wid = self.h2.post(&index_path, Some(param)).await?.as_u64().unwrap();
a6782ca1 749
2f831bae
DM
750 let (chunk_count, size, _speed, csum) =
751 Self::upload_chunk_info_stream(
752 self.h2.clone(),
a6782ca1
WB
753 wid,
754 stream,
755 &prefix,
756 known_chunks.clone(),
757 crypt_config,
758 )
759 .await?;
760
2f831bae
DM
761 let param = json!({
762 "wid": wid ,
763 "chunk-count": chunk_count,
764 "size": size,
fb6026b6 765 "csum": proxmox::tools::digest_to_hex(&csum),
2f831bae
DM
766 });
767 let _value = self.h2.post(&close_path, Some(param)).await?;
768 Ok(BackupStats {
769 size: size as u64,
770 csum,
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 });
792a70b9 842 let request = H2Client::request_builder("localhost", "PUT", &path, None, Some("application/json")).unwrap();
05cba08c
DM
843 let param_data = bytes::Bytes::from(param.to_string().as_bytes());
844 let upload_data = Some(param_data);
845 h2_2.send_request(request, upload_data)
846 .and_then(move |response| {
847 response
848 .map_err(Error::from)
849 .and_then(H2Client::h2api_response)
a6782ca1 850 .map_ok(|_| ())
05cba08c
DM
851 })
852 .map_err(|err| format_err!("pipelined request failed: {}", err))
853 }
854 _ => unreachable!(),
855 }
856 })
a6782ca1
WB
857 .try_for_each(|_| future::ok(()))
858 .map(|result| {
859 let _ignore_closed_channel = verify_result_tx.send(result);
860 })
05cba08c
DM
861 );
862
863 (verify_queue_tx, verify_result_rx)
864 }
865
6d4df36c
DM
866 pub async fn download_chunk_list(
867 &self,
553610b4
DM
868 path: &str,
869 archive_name: &str,
870 known_chunks: Arc<Mutex<HashSet<[u8;32]>>>,
c2a5a9f3 871 ) -> Result<(), Error> {
553610b4
DM
872
873 let param = json!({ "archive-name": archive_name });
792a70b9 874 let request = H2Client::request_builder("localhost", "GET", path, Some(param), None).unwrap();
553610b4 875
6d4df36c 876 let h2request = self.h2.send_request(request, None).await?;
c2a5a9f3 877 let resp = h2request.await?;
7dd1bcac 878
c2a5a9f3
DM
879 let status = resp.status();
880
881 if !status.is_success() {
882 H2Client::h2api_response(resp).await?; // raise error
883 unreachable!();
884 }
885
886 let mut body = resp.into_body();
887 let mut release_capacity = body.release_capacity().clone();
888
c18fddf8
DM
889 let mut stream = DigestListDecoder::new(body.map_err(Error::from));
890
891 while let Some(chunk) = stream.try_next().await? {
892 let _ = release_capacity.release_capacity(chunk.len());
893 println!("GOT DOWNLOAD {}", digest_to_hex(&chunk));
894 known_chunks.lock().unwrap().insert(chunk);
895 }
896
897 Ok(())
553610b4
DM
898 }
899
a42fa400 900 fn upload_chunk_info_stream(
9af37c8f 901 h2: H2Client,
82ab7230 902 wid: u64,
a6782ca1 903 stream: impl Stream<Item = Result<bytes::BytesMut, Error>>,
642322b4 904 prefix: &str,
553610b4 905 known_chunks: Arc<Mutex<HashSet<[u8;32]>>>,
f98ac774 906 crypt_config: Option<Arc<CryptConfig>>,
a6782ca1 907 ) -> impl Future<Output = Result<(usize, usize, usize, [u8; 32]), Error>> {
adec8ea2 908
a6782ca1 909 let repeat = Arc::new(AtomicUsize::new(0));
82ab7230 910 let repeat2 = repeat.clone();
adec8ea2 911
a6782ca1 912 let stream_len = Arc::new(AtomicUsize::new(0));
82ab7230 913 let stream_len2 = stream_len.clone();
9c9ad941 914
642322b4
DM
915 let append_chunk_path = format!("{}_index", prefix);
916 let upload_chunk_path = format!("{}_chunk", prefix);
9e603e25 917 let is_fixed_chunk_size = prefix == "fixed";
642322b4 918
a6782ca1
WB
919 let (upload_queue, upload_result) =
920 Self::append_chunk_queue(h2.clone(), wid, append_chunk_path.to_owned());
9c9ad941 921
82ab7230 922 let start_time = std::time::Instant::now();
9c9ad941 923
dbed4c8c
DM
924 let index_csum = Arc::new(Mutex::new(Some(openssl::sha::Sha256::new())));
925 let index_csum_2 = index_csum.clone();
926
82ab7230 927 stream
f98ac774
DM
928 .and_then(move |data| {
929
930 let chunk_len = data.len();
931
82ab7230 932 repeat.fetch_add(1, Ordering::SeqCst);
f98ac774
DM
933 let offset = stream_len.fetch_add(chunk_len, Ordering::SeqCst) as u64;
934
935 let mut chunk_builder = DataChunkBuilder::new(data.as_ref())
936 .compress(true);
937
938 if let Some(ref crypt_config) = crypt_config {
7123ff7d 939 chunk_builder = chunk_builder.crypt_config(crypt_config);
f98ac774 940 }
62436222
DM
941
942 let mut known_chunks = known_chunks.lock().unwrap();
f98ac774 943 let digest = chunk_builder.digest();
dbed4c8c
DM
944
945 let mut guard = index_csum.lock().unwrap();
946 let csum = guard.as_mut().unwrap();
a3e032b7
DM
947
948 let chunk_end = offset + chunk_len as u64;
1a7a0e74 949
9e603e25 950 if !is_fixed_chunk_size { csum.update(&chunk_end.to_le_bytes()); }
dbed4c8c
DM
951 csum.update(digest);
952
f98ac774 953 let chunk_is_known = known_chunks.contains(digest);
62436222 954 if chunk_is_known {
a6782ca1 955 future::ok(MergedChunkInfo::Known(vec![(offset, *digest)]))
62436222 956 } else {
f98ac774 957 known_chunks.insert(*digest);
a6782ca1
WB
958 future::ready(chunk_builder
959 .build()
4ee8f53d 960 .map(move |(chunk, digest)| MergedChunkInfo::New(ChunkInfo {
a6782ca1 961 chunk,
4ee8f53d 962 digest,
a6782ca1
WB
963 chunk_len: chunk_len as u64,
964 offset,
965 }))
966 )
62436222 967 }
aa1b2e04 968 })
62436222 969 .merge_known_chunks()
a6782ca1 970 .try_for_each(move |merged_chunk_info| {
174ad378
DM
971
972 if let MergedChunkInfo::New(chunk_info) = merged_chunk_info {
973 let offset = chunk_info.offset;
4ee8f53d 974 let digest = chunk_info.digest;
e18a6c9e 975 let digest_str = digest_to_hex(&digest);
174ad378 976
f98ac774
DM
977 println!("upload new chunk {} ({} bytes, offset {})", digest_str,
978 chunk_info.chunk_len, offset);
979
980 let chunk_data = chunk_info.chunk.raw_data();
981 let param = json!({
982 "wid": wid,
983 "digest": digest_str,
984 "size": chunk_info.chunk_len,
985 "encoded-size": chunk_data.len(),
986 });
174ad378 987
792a70b9
DM
988 let ct = "application/octet-stream";
989 let request = H2Client::request_builder("localhost", "POST", &upload_chunk_path, Some(param), Some(ct)).unwrap();
f98ac774 990 let upload_data = Some(bytes::Bytes::from(chunk_data));
174ad378 991
8de20e5c 992 let new_info = MergedChunkInfo::Known(vec![(offset, digest)]);
174ad378 993
a6782ca1
WB
994 let mut upload_queue = upload_queue.clone();
995 future::Either::Left(h2
996 .send_request(request, upload_data)
997 .and_then(move |response| async move {
998 upload_queue
999 .send((new_info, Some(response)))
1000 .await
1001 .map_err(Error::from)
1002 })
174ad378
DM
1003 )
1004 } else {
a6782ca1
WB
1005 let mut upload_queue = upload_queue.clone();
1006 future::Either::Right(async move {
1007 upload_queue
1008 .send((merged_chunk_info, None))
1009 .await
1010 .map_err(Error::from)
1011 })
174ad378 1012 }
82ab7230 1013 })
a6782ca1
WB
1014 .then(move |result| async move {
1015 upload_result.await?.and(result)
1016 }.boxed())
82ab7230
DM
1017 .and_then(move |_| {
1018 let repeat = repeat2.load(Ordering::SeqCst);
1019 let stream_len = stream_len2.load(Ordering::SeqCst);
1020 let speed = ((stream_len*1000000)/(1024*1024))/(start_time.elapsed().as_micros() as usize);
1021 println!("Uploaded {} chunks in {} seconds ({} MB/s).", repeat, start_time.elapsed().as_secs(), speed);
1022 if repeat > 0 {
1023 println!("Average chunk size was {} bytes.", stream_len/repeat);
1024 println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128));
1025 }
dbed4c8c
DM
1026
1027 let mut guard = index_csum_2.lock().unwrap();
1028 let csum = guard.take().unwrap().finish();
1029
a6782ca1 1030 futures::future::ok((repeat, stream_len, speed, csum))
82ab7230
DM
1031 })
1032 }
1033
54a5a885 1034 pub async fn upload_speedtest(&self) -> Result<usize, Error> {
82ab7230
DM
1035
1036 let mut data = vec![];
1037 // generate pseudo random byte sequence
1038 for i in 0..1024*1024 {
1039 for j in 0..4 {
1040 let byte = ((i >> (j<<3))&0xff) as u8;
1041 data.push(byte);
1042 }
1043 }
1044
1045 let item_len = data.len();
1046
54a5a885 1047 let mut repeat = 0;
82ab7230 1048
6ab34afa 1049 let (upload_queue, upload_result) = Self::response_queue();
82ab7230
DM
1050
1051 let start_time = std::time::Instant::now();
1052
54a5a885
DM
1053 loop {
1054 repeat += 1;
1055 if start_time.elapsed().as_secs() >= 5 {
1056 break;
1057 }
82ab7230 1058
54a5a885 1059 let mut upload_queue = upload_queue.clone();
82ab7230 1060
54a5a885 1061 println!("send test data ({} bytes)", data.len());
792a70b9 1062 let request = H2Client::request_builder("localhost", "POST", "speedtest", None, None).unwrap();
54a5a885 1063 let request_future = self.h2.send_request(request, Some(bytes::Bytes::from(data.clone()))).await?;
82ab7230 1064
54a5a885
DM
1065 upload_queue.send(request_future).await?;
1066 }
1067
1068 drop(upload_queue); // close queue
1069
1070 let _ = upload_result.await?;
1071
1072 println!("Uploaded {} chunks in {} seconds.", repeat, start_time.elapsed().as_secs());
1073 let speed = ((item_len*1000000*(repeat as usize))/(1024*1024))/(start_time.elapsed().as_micros() as usize);
1074 println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128));
1075
1076 Ok(speed)
adec8ea2 1077 }
9af37c8f
DM
1078}
1079
1080#[derive(Clone)]
1081pub struct H2Client {
1082 h2: h2::client::SendRequest<bytes::Bytes>,
1083}
1084
1085impl H2Client {
1086
1087 pub fn new(h2: h2::client::SendRequest<bytes::Bytes>) -> Self {
1088 Self { h2 }
1089 }
1090
2a1e6d7d
DM
1091 pub async fn get(
1092 &self,
1093 path: &str,
1094 param: Option<Value>
1095 ) -> Result<Value, Error> {
792a70b9 1096 let req = Self::request_builder("localhost", "GET", path, param, None).unwrap();
2a1e6d7d 1097 self.request(req).await
9af37c8f
DM
1098 }
1099
2a1e6d7d
DM
1100 pub async fn put(
1101 &self,
1102 path: &str,
1103 param: Option<Value>
1104 ) -> Result<Value, Error> {
792a70b9 1105 let req = Self::request_builder("localhost", "PUT", path, param, None).unwrap();
2a1e6d7d 1106 self.request(req).await
9af37c8f
DM
1107 }
1108
2a1e6d7d
DM
1109 pub async fn post(
1110 &self,
1111 path: &str,
1112 param: Option<Value>
1113 ) -> Result<Value, Error> {
792a70b9 1114 let req = Self::request_builder("localhost", "POST", path, param, None).unwrap();
2a1e6d7d 1115 self.request(req).await
9af37c8f
DM
1116 }
1117
d4a085e5 1118 pub async fn download<W: Write + Send>(
a6782ca1
WB
1119 &self,
1120 path: &str,
1121 param: Option<Value>,
2a1e6d7d 1122 mut output: W,
d4a085e5 1123 ) -> Result<W, Error> {
792a70b9 1124 let request = Self::request_builder("localhost", "GET", path, param, None).unwrap();
dd066d28 1125
2a1e6d7d 1126 let response_future = self.send_request(request, None).await?;
984a7c35 1127
2a1e6d7d
DM
1128 let resp = response_future.await?;
1129
1130 let status = resp.status();
1131 if !status.is_success() {
44f59dc7
DM
1132 H2Client::h2api_response(resp).await?; // raise error
1133 unreachable!();
2a1e6d7d
DM
1134 }
1135
1136 let mut body = resp.into_body();
1137 let mut release_capacity = body.release_capacity().clone();
1138
1139 while let Some(chunk) = body.try_next().await? {
1140 let _ = release_capacity.release_capacity(chunk.len());
1141 output.write_all(&chunk)?;
1142 }
1143
1144 Ok(output)
dd066d28
DM
1145 }
1146
2a1e6d7d 1147 pub async fn upload(
a6782ca1 1148 &self,
f011dba0 1149 method: &str, // POST or PUT
a6782ca1
WB
1150 path: &str,
1151 param: Option<Value>,
792a70b9 1152 content_type: &str,
a6782ca1 1153 data: Vec<u8>,
2a1e6d7d 1154 ) -> Result<Value, Error> {
f011dba0 1155 let request = Self::request_builder("localhost", method, path, param, Some(content_type)).unwrap();
9af37c8f 1156
2a1e6d7d
DM
1157 let mut send_request = self.h2.clone().ready().await?;
1158
1159 let (response, stream) = send_request.send_request(request, false).unwrap();
2a05048b
DM
1160
1161 PipeToSendStream::new(bytes::Bytes::from(data), stream).await?;
1162
1163 response
1164 .map_err(Error::from)
1165 .and_then(Self::h2api_response)
2a1e6d7d 1166 .await
9af37c8f 1167 }
adec8ea2 1168
2a1e6d7d 1169 async fn request(
9af37c8f 1170 &self,
b57cb264 1171 request: Request<()>,
2a1e6d7d 1172 ) -> Result<Value, Error> {
b57cb264 1173
9af37c8f 1174 self.send_request(request, None)
82ab7230
DM
1175 .and_then(move |response| {
1176 response
1177 .map_err(Error::from)
1178 .and_then(Self::h2api_response)
1179 })
2a1e6d7d 1180 .await
82ab7230
DM
1181 }
1182
1183 fn send_request(
9af37c8f 1184 &self,
82ab7230
DM
1185 request: Request<()>,
1186 data: Option<bytes::Bytes>,
a6782ca1 1187 ) -> impl Future<Output = Result<h2::client::ResponseFuture, Error>> {
82ab7230 1188
9af37c8f 1189 self.h2.clone()
10130cf4
DM
1190 .ready()
1191 .map_err(Error::from)
2a05048b 1192 .and_then(move |mut send_request| async move {
82ab7230
DM
1193 if let Some(data) = data {
1194 let (response, stream) = send_request.send_request(request, false).unwrap();
2a05048b
DM
1195 PipeToSendStream::new(data, stream).await?;
1196 Ok(response)
82ab7230
DM
1197 } else {
1198 let (response, _stream) = send_request.send_request(request, true).unwrap();
2a05048b 1199 Ok(response)
82ab7230 1200 }
b57cb264
DM
1201 })
1202 }
1203
f16aea68 1204 pub async fn h2api_response(
a6782ca1 1205 response: Response<h2::RecvStream>,
9edd3bf1 1206 ) -> Result<Value, Error> {
b57cb264
DM
1207 let status = response.status();
1208
1209 let (_head, mut body) = response.into_parts();
1210
1211 // The `release_capacity` handle allows the caller to manage
1212 // flow control.
1213 //
1214 // Whenever data is received, the caller is responsible for
1215 // releasing capacity back to the server once it has freed
1216 // the data from memory.
1217 let mut release_capacity = body.release_capacity().clone();
1218
9edd3bf1
DM
1219 let mut data = Vec::new();
1220 while let Some(chunk) = body.try_next().await? {
1221 // Let the server send more data.
1222 let _ = release_capacity.release_capacity(chunk.len());
1223 data.extend(chunk);
1224 }
1225
1226 let text = String::from_utf8(data.to_vec()).unwrap();
1227 if status.is_success() {
1228 if text.len() > 0 {
1229 let mut value: Value = serde_json::from_str(&text)?;
1230 if let Some(map) = value.as_object_mut() {
1231 if let Some(data) = map.remove("data") {
1232 return Ok(data);
b57cb264 1233 }
b57cb264 1234 }
9edd3bf1
DM
1235 bail!("got result without data property");
1236 } else {
1237 Ok(Value::Null)
1238 }
1239 } else {
1240 bail!("HTTP Error {}: {}", status, text);
1241 }
b57cb264
DM
1242 }
1243
eb2bdd1b 1244 // Note: We always encode parameters with the url
792a70b9
DM
1245 pub fn request_builder(
1246 server: &str,
1247 method: &str,
1248 path: &str,
1249 param: Option<Value>,
1250 content_type: Option<&str>,
1251 ) -> Result<Request<()>, Error> {
b57cb264 1252 let path = path.trim_matches('/');
b57cb264 1253
792a70b9
DM
1254 let content_type = content_type.unwrap_or("application/x-www-form-urlencoded");
1255
a55b2975
DM
1256 if let Some(param) = param {
1257 let query = tools::json_object_to_query(param)?;
eb2bdd1b
DM
1258 // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side
1259 if query.len() > 4096 { bail!("h2 query data too large ({} bytes) - please encode data inside body", query.len()); }
b57cb264 1260 let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?;
eb2bdd1b 1261 let request = Request::builder()
b57cb264
DM
1262 .method(method)
1263 .uri(url)
1264 .header("User-Agent", "proxmox-backup-client/1.0")
792a70b9 1265 .header(hyper::header::CONTENT_TYPE, content_type)
b57cb264
DM
1266 .body(())?;
1267 return Ok(request);
eb2bdd1b
DM
1268 } else {
1269 let url: Uri = format!("https://{}:8007/{}", server, path).parse()?;
1270 let request = Request::builder()
1271 .method(method)
1272 .uri(url)
1273 .header("User-Agent", "proxmox-backup-client/1.0")
792a70b9 1274 .header(hyper::header::CONTENT_TYPE, content_type)
eb2bdd1b 1275 .body(())?;
b57cb264 1276
eb2bdd1b
DM
1277 Ok(request)
1278 }
b57cb264
DM
1279 }
1280}
1434f4f8
WB
1281
1282pub struct HttpsConnector {
1283 http: HttpConnector,
1284 ssl_connector: SslConnector,
1285}
1286
1287impl HttpsConnector {
1288 pub fn with_connector(mut http: HttpConnector, ssl_connector: SslConnector) -> Self {
1289 http.enforce_http(false);
1290
1291 Self {
1292 http,
1293 ssl_connector,
1294 }
1295 }
1296}
1297
1298type MaybeTlsStream = EitherStream<
1299 tokio::net::TcpStream,
1300 tokio_openssl::SslStream<tokio::net::TcpStream>,
1301>;
1302
1303impl hyper::client::connect::Connect for HttpsConnector {
1304 type Transport = MaybeTlsStream;
1305 type Error = Error;
1306 type Future = Box<dyn Future<Output = Result<(
1307 Self::Transport,
1308 hyper::client::connect::Connected,
1309 ), Error>> + Send + Unpin + 'static>;
1310
1311 fn connect(&self, dst: hyper::client::connect::Destination) -> Self::Future {
1312 let is_https = dst.scheme() == "https";
1313 let host = dst.host().to_string();
1314
1315 let config = self.ssl_connector.configure();
1316 let conn = self.http.connect(dst);
1317
1318 Box::new(Box::pin(async move {
1319 let (conn, connected) = conn.await?;
1320 if is_https {
1321 let conn = tokio_openssl::connect(config?, &host, conn).await?;
1322 Ok((MaybeTlsStream::Right(conn), connected))
1323 } else {
1324 Ok((MaybeTlsStream::Left(conn), connected))
1325 }
1326 }))
1327 }
1328}