]> git.proxmox.com Git - proxmox-backup.git/blame - src/client/http_client.rs
backup writer api: verify checksum inside close
[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
614 pub async fn upload_put(
15bb1bba
DM
615 &self,
616 path: &str,
617 param: Option<Value>,
792a70b9 618 content_type: &str,
15bb1bba
DM
619 data: Vec<u8>,
620 ) -> Result<Value, Error> {
c8c4051a 621 self.h2.upload("PUT", path, param, content_type, data).await
15bb1bba
DM
622 }
623
2a1e6d7d
DM
624 pub async fn finish(self: Arc<Self>) -> Result<(), Error> {
625 let h2 = self.h2.clone();
626
627 h2.post("finish", None)
a6782ca1 628 .map_ok(move |_| {
9cc88a7c
DM
629 self.canceller.cancel();
630 })
2a1e6d7d 631 .await
4247fccb
DM
632 }
633
3467cd91
DM
634 pub fn force_close(self) {
635 self.canceller.cancel();
d6f204ed
DM
636 }
637
2f831bae 638 pub async fn upload_blob<R: std::io::Read>(
9d135fe6
DM
639 &self,
640 mut reader: R,
641 file_name: &str,
2f831bae
DM
642 ) -> Result<BackupStats, Error> {
643 let mut raw_data = Vec::new();
644 // fixme: avoid loading into memory
645 reader.read_to_end(&mut raw_data)?;
9d135fe6 646
2f831bae
DM
647 let csum = openssl::sha::sha256(&raw_data);
648 let param = json!({"encoded-size": raw_data.len(), "file-name": file_name });
649 let size = raw_data.len() as u64; // fixme: should be decoded size instead??
c8c4051a 650 let _value = self.h2.upload("POST", "blob", Some(param), "application/octet-stream", raw_data).await?;
2f831bae 651 Ok(BackupStats { size, csum })
9d135fe6
DM
652 }
653
2f831bae 654 pub async fn upload_blob_from_data(
9f46c7de
DM
655 &self,
656 data: Vec<u8>,
657 file_name: &str,
658 crypt_config: Option<Arc<CryptConfig>>,
659 compress: bool,
b335f5b7 660 sign_only: bool,
2f831bae 661 ) -> Result<BackupStats, Error> {
9f46c7de 662
2c3891d1 663 let size = data.len() as u64;
9f46c7de 664
2f831bae
DM
665 let blob = if let Some(crypt_config) = crypt_config {
666 if sign_only {
667 DataBlob::create_signed(&data, crypt_config, compress)?
a6782ca1 668 } else {
2f831bae
DM
669 DataBlob::encode(&data, Some(crypt_config.clone()), compress)?
670 }
671 } else {
672 DataBlob::encode(&data, None, compress)?
673 };
9f46c7de 674
2f831bae 675 let raw_data = blob.into_inner();
a6782ca1 676
2f831bae
DM
677 let csum = openssl::sha::sha256(&raw_data);
678 let param = json!({"encoded-size": raw_data.len(), "file-name": file_name });
c8c4051a 679 let _value = self.h2.upload("POST", "blob", Some(param), "application/octet-stream", raw_data).await?;
2f831bae 680 Ok(BackupStats { size, csum })
9f46c7de
DM
681 }
682
2f831bae 683 pub async fn upload_blob_from_file<P: AsRef<std::path::Path>>(
39d6846e 684 &self,
ec8a9bb9 685 src_path: P,
39d6846e 686 file_name: &str,
cb08ac3e
DM
687 crypt_config: Option<Arc<CryptConfig>>,
688 compress: bool,
2f831bae 689 ) -> Result<BackupStats, Error> {
39d6846e 690
2f831bae
DM
691 let src_path = src_path.as_ref();
692
34a3845b 693 let mut file = tokio::fs::File::open(src_path)
2f831bae
DM
694 .await
695 .map_err(|err| format_err!("unable to open file {:?} - {}", src_path, err))?;
696
697 let mut contents = Vec::new();
698
699 file.read_to_end(&mut contents)
700 .await
701 .map_err(|err| format_err!("unable to read file {:?} - {}", src_path, err))?;
702
703 let size: u64 = contents.len() as u64;
704 let blob = DataBlob::encode(&contents, crypt_config, compress)?;
705 let raw_data = blob.into_inner();
706 let csum = openssl::sha::sha256(&raw_data);
707 let param = json!({
708 "encoded-size": raw_data.len(),
709 "file-name": file_name,
710 });
c8c4051a 711 self.h2.upload("POST", "blob", Some(param), "application/octet-stream", raw_data).await?;
2f831bae 712 Ok(BackupStats { size, csum })
39d6846e
DM
713 }
714
2f831bae 715 pub async fn upload_stream(
d6f204ed
DM
716 &self,
717 archive_name: &str,
a6782ca1 718 stream: impl Stream<Item = Result<bytes::BytesMut, Error>>,
a42fa400
DM
719 prefix: &str,
720 fixed_size: Option<u64>,
f98ac774 721 crypt_config: Option<Arc<CryptConfig>>,
2f831bae 722 ) -> Result<BackupStats, Error> {
d6f204ed
DM
723 let known_chunks = Arc::new(Mutex::new(HashSet::new()));
724
a42fa400
DM
725 let mut param = json!({ "archive-name": archive_name });
726 if let Some(size) = fixed_size {
727 param["size"] = size.into();
728 }
729
730 let index_path = format!("{}_index", prefix);
a42fa400 731 let close_path = format!("{}_close", prefix);
d6f204ed 732
6d4df36c 733 self.download_chunk_list(&index_path, archive_name, known_chunks.clone()).await?;
a6782ca1 734
2f831bae 735 let wid = self.h2.post(&index_path, Some(param)).await?.as_u64().unwrap();
a6782ca1 736
2f831bae
DM
737 let (chunk_count, size, _speed, csum) =
738 Self::upload_chunk_info_stream(
739 self.h2.clone(),
a6782ca1
WB
740 wid,
741 stream,
742 &prefix,
743 known_chunks.clone(),
744 crypt_config,
745 )
746 .await?;
747
2f831bae
DM
748 let param = json!({
749 "wid": wid ,
750 "chunk-count": chunk_count,
751 "size": size,
fb6026b6 752 "csum": proxmox::tools::digest_to_hex(&csum),
2f831bae
DM
753 });
754 let _value = self.h2.post(&close_path, Some(param)).await?;
755 Ok(BackupStats {
756 size: size as u64,
757 csum,
758 })
d6f204ed
DM
759 }
760
6ab34afa 761 fn response_queue() -> (
82ab7230 762 mpsc::Sender<h2::client::ResponseFuture>,
a6782ca1 763 oneshot::Receiver<Result<(), Error>>
82ab7230
DM
764 ) {
765 let (verify_queue_tx, verify_queue_rx) = mpsc::channel(100);
a6782ca1 766 let (verify_result_tx, verify_result_rx) = oneshot::channel();
adec8ea2 767
82ab7230
DM
768 hyper::rt::spawn(
769 verify_queue_rx
a6782ca1
WB
770 .map(Ok::<_, Error>)
771 .try_for_each(|response: h2::client::ResponseFuture| {
82ab7230
DM
772 response
773 .map_err(Error::from)
9af37c8f 774 .and_then(H2Client::h2api_response)
a6782ca1 775 .map_ok(|result| println!("RESPONSE: {:?}", result))
82ab7230
DM
776 .map_err(|err| format_err!("pipelined request failed: {}", err))
777 })
a6782ca1
WB
778 .map(|result| {
779 let _ignore_closed_channel = verify_result_tx.send(result);
780 })
82ab7230 781 );
adec8ea2 782
82ab7230
DM
783 (verify_queue_tx, verify_result_rx)
784 }
785
642322b4 786 fn append_chunk_queue(h2: H2Client, wid: u64, path: String) -> (
174ad378 787 mpsc::Sender<(MergedChunkInfo, Option<h2::client::ResponseFuture>)>,
a6782ca1 788 oneshot::Receiver<Result<(), Error>>
05cba08c 789 ) {
771953f9 790 let (verify_queue_tx, verify_queue_rx) = mpsc::channel(64);
a6782ca1 791 let (verify_result_tx, verify_result_rx) = oneshot::channel();
05cba08c
DM
792
793 let h2_2 = h2.clone();
794
795 hyper::rt::spawn(
796 verify_queue_rx
a6782ca1 797 .map(Ok::<_, Error>)
174ad378
DM
798 .and_then(move |(merged_chunk_info, response): (MergedChunkInfo, Option<h2::client::ResponseFuture>)| {
799 match (response, merged_chunk_info) {
800 (Some(response), MergedChunkInfo::Known(list)) => {
a6782ca1 801 future::Either::Left(
174ad378
DM
802 response
803 .map_err(Error::from)
804 .and_then(H2Client::h2api_response)
771953f9 805 .and_then(move |_result| {
a6782ca1 806 future::ok(MergedChunkInfo::Known(list))
05cba08c 807 })
05cba08c
DM
808 )
809 }
174ad378 810 (None, MergedChunkInfo::Known(list)) => {
a6782ca1 811 future::Either::Right(future::ok(MergedChunkInfo::Known(list)))
05cba08c 812 }
174ad378 813 _ => unreachable!(),
05cba08c
DM
814 }
815 })
62436222 816 .merge_known_chunks()
05cba08c
DM
817 .and_then(move |merged_chunk_info| {
818 match merged_chunk_info {
819 MergedChunkInfo::Known(chunk_list) => {
820 let mut digest_list = vec![];
821 let mut offset_list = vec![];
822 for (offset, digest) in chunk_list {
bffd40d6 823 //println!("append chunk {} (offset {})", proxmox::tools::digest_to_hex(&digest), offset);
e18a6c9e 824 digest_list.push(digest_to_hex(&digest));
05cba08c
DM
825 offset_list.push(offset);
826 }
827 println!("append chunks list len ({})", digest_list.len());
828 let param = json!({ "wid": wid, "digest-list": digest_list, "offset-list": offset_list });
792a70b9 829 let request = H2Client::request_builder("localhost", "PUT", &path, None, Some("application/json")).unwrap();
05cba08c
DM
830 let param_data = bytes::Bytes::from(param.to_string().as_bytes());
831 let upload_data = Some(param_data);
832 h2_2.send_request(request, upload_data)
833 .and_then(move |response| {
834 response
835 .map_err(Error::from)
836 .and_then(H2Client::h2api_response)
a6782ca1 837 .map_ok(|_| ())
05cba08c
DM
838 })
839 .map_err(|err| format_err!("pipelined request failed: {}", err))
840 }
841 _ => unreachable!(),
842 }
843 })
a6782ca1
WB
844 .try_for_each(|_| future::ok(()))
845 .map(|result| {
846 let _ignore_closed_channel = verify_result_tx.send(result);
847 })
05cba08c
DM
848 );
849
850 (verify_queue_tx, verify_result_rx)
851 }
852
6d4df36c
DM
853 pub async fn download_chunk_list(
854 &self,
553610b4
DM
855 path: &str,
856 archive_name: &str,
857 known_chunks: Arc<Mutex<HashSet<[u8;32]>>>,
c2a5a9f3 858 ) -> Result<(), Error> {
553610b4
DM
859
860 let param = json!({ "archive-name": archive_name });
792a70b9 861 let request = H2Client::request_builder("localhost", "GET", path, Some(param), None).unwrap();
553610b4 862
6d4df36c 863 let h2request = self.h2.send_request(request, None).await?;
c2a5a9f3 864 let resp = h2request.await?;
7dd1bcac 865
c2a5a9f3
DM
866 let status = resp.status();
867
868 if !status.is_success() {
869 H2Client::h2api_response(resp).await?; // raise error
870 unreachable!();
871 }
872
873 let mut body = resp.into_body();
874 let mut release_capacity = body.release_capacity().clone();
875
c18fddf8
DM
876 let mut stream = DigestListDecoder::new(body.map_err(Error::from));
877
878 while let Some(chunk) = stream.try_next().await? {
879 let _ = release_capacity.release_capacity(chunk.len());
880 println!("GOT DOWNLOAD {}", digest_to_hex(&chunk));
881 known_chunks.lock().unwrap().insert(chunk);
882 }
883
884 Ok(())
553610b4
DM
885 }
886
a42fa400 887 fn upload_chunk_info_stream(
9af37c8f 888 h2: H2Client,
82ab7230 889 wid: u64,
a6782ca1 890 stream: impl Stream<Item = Result<bytes::BytesMut, Error>>,
642322b4 891 prefix: &str,
553610b4 892 known_chunks: Arc<Mutex<HashSet<[u8;32]>>>,
f98ac774 893 crypt_config: Option<Arc<CryptConfig>>,
a6782ca1 894 ) -> impl Future<Output = Result<(usize, usize, usize, [u8; 32]), Error>> {
adec8ea2 895
a6782ca1 896 let repeat = Arc::new(AtomicUsize::new(0));
82ab7230 897 let repeat2 = repeat.clone();
adec8ea2 898
a6782ca1 899 let stream_len = Arc::new(AtomicUsize::new(0));
82ab7230 900 let stream_len2 = stream_len.clone();
9c9ad941 901
642322b4
DM
902 let append_chunk_path = format!("{}_index", prefix);
903 let upload_chunk_path = format!("{}_chunk", prefix);
904
a6782ca1
WB
905 let (upload_queue, upload_result) =
906 Self::append_chunk_queue(h2.clone(), wid, append_chunk_path.to_owned());
9c9ad941 907
82ab7230 908 let start_time = std::time::Instant::now();
9c9ad941 909
dbed4c8c
DM
910 let index_csum = Arc::new(Mutex::new(Some(openssl::sha::Sha256::new())));
911 let index_csum_2 = index_csum.clone();
912
82ab7230 913 stream
f98ac774
DM
914 .and_then(move |data| {
915
916 let chunk_len = data.len();
917
82ab7230 918 repeat.fetch_add(1, Ordering::SeqCst);
f98ac774
DM
919 let offset = stream_len.fetch_add(chunk_len, Ordering::SeqCst) as u64;
920
921 let mut chunk_builder = DataChunkBuilder::new(data.as_ref())
922 .compress(true);
923
924 if let Some(ref crypt_config) = crypt_config {
925 chunk_builder = chunk_builder.crypt_config(crypt_config);
926 }
62436222
DM
927
928 let mut known_chunks = known_chunks.lock().unwrap();
f98ac774 929 let digest = chunk_builder.digest();
dbed4c8c
DM
930
931 let mut guard = index_csum.lock().unwrap();
932 let csum = guard.as_mut().unwrap();
a3e032b7
DM
933
934 let chunk_end = offset + chunk_len as u64;
1a7a0e74 935
a3e032b7 936 csum.update(&chunk_end.to_le_bytes());
dbed4c8c
DM
937 csum.update(digest);
938
f98ac774 939 let chunk_is_known = known_chunks.contains(digest);
62436222 940 if chunk_is_known {
a6782ca1 941 future::ok(MergedChunkInfo::Known(vec![(offset, *digest)]))
62436222 942 } else {
f98ac774 943 known_chunks.insert(*digest);
a6782ca1
WB
944 future::ready(chunk_builder
945 .build()
946 .map(move |chunk| MergedChunkInfo::New(ChunkInfo {
947 chunk,
948 chunk_len: chunk_len as u64,
949 offset,
950 }))
951 )
62436222 952 }
aa1b2e04 953 })
62436222 954 .merge_known_chunks()
a6782ca1 955 .try_for_each(move |merged_chunk_info| {
174ad378
DM
956
957 if let MergedChunkInfo::New(chunk_info) = merged_chunk_info {
958 let offset = chunk_info.offset;
f98ac774 959 let digest = *chunk_info.chunk.digest();
e18a6c9e 960 let digest_str = digest_to_hex(&digest);
174ad378 961
f98ac774
DM
962 println!("upload new chunk {} ({} bytes, offset {})", digest_str,
963 chunk_info.chunk_len, offset);
964
965 let chunk_data = chunk_info.chunk.raw_data();
966 let param = json!({
967 "wid": wid,
968 "digest": digest_str,
969 "size": chunk_info.chunk_len,
970 "encoded-size": chunk_data.len(),
971 });
174ad378 972
792a70b9
DM
973 let ct = "application/octet-stream";
974 let request = H2Client::request_builder("localhost", "POST", &upload_chunk_path, Some(param), Some(ct)).unwrap();
f98ac774 975 let upload_data = Some(bytes::Bytes::from(chunk_data));
174ad378 976
8de20e5c 977 let new_info = MergedChunkInfo::Known(vec![(offset, digest)]);
174ad378 978
a6782ca1
WB
979 let mut upload_queue = upload_queue.clone();
980 future::Either::Left(h2
981 .send_request(request, upload_data)
982 .and_then(move |response| async move {
983 upload_queue
984 .send((new_info, Some(response)))
985 .await
986 .map_err(Error::from)
987 })
174ad378
DM
988 )
989 } else {
a6782ca1
WB
990 let mut upload_queue = upload_queue.clone();
991 future::Either::Right(async move {
992 upload_queue
993 .send((merged_chunk_info, None))
994 .await
995 .map_err(Error::from)
996 })
174ad378 997 }
82ab7230 998 })
a6782ca1
WB
999 .then(move |result| async move {
1000 upload_result.await?.and(result)
1001 }.boxed())
82ab7230
DM
1002 .and_then(move |_| {
1003 let repeat = repeat2.load(Ordering::SeqCst);
1004 let stream_len = stream_len2.load(Ordering::SeqCst);
1005 let speed = ((stream_len*1000000)/(1024*1024))/(start_time.elapsed().as_micros() as usize);
1006 println!("Uploaded {} chunks in {} seconds ({} MB/s).", repeat, start_time.elapsed().as_secs(), speed);
1007 if repeat > 0 {
1008 println!("Average chunk size was {} bytes.", stream_len/repeat);
1009 println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128));
1010 }
dbed4c8c
DM
1011
1012 let mut guard = index_csum_2.lock().unwrap();
1013 let csum = guard.take().unwrap().finish();
1014
a6782ca1 1015 futures::future::ok((repeat, stream_len, speed, csum))
82ab7230
DM
1016 })
1017 }
1018
54a5a885 1019 pub async fn upload_speedtest(&self) -> Result<usize, Error> {
82ab7230
DM
1020
1021 let mut data = vec![];
1022 // generate pseudo random byte sequence
1023 for i in 0..1024*1024 {
1024 for j in 0..4 {
1025 let byte = ((i >> (j<<3))&0xff) as u8;
1026 data.push(byte);
1027 }
1028 }
1029
1030 let item_len = data.len();
1031
54a5a885 1032 let mut repeat = 0;
82ab7230 1033
6ab34afa 1034 let (upload_queue, upload_result) = Self::response_queue();
82ab7230
DM
1035
1036 let start_time = std::time::Instant::now();
1037
54a5a885
DM
1038 loop {
1039 repeat += 1;
1040 if start_time.elapsed().as_secs() >= 5 {
1041 break;
1042 }
82ab7230 1043
54a5a885 1044 let mut upload_queue = upload_queue.clone();
82ab7230 1045
54a5a885 1046 println!("send test data ({} bytes)", data.len());
792a70b9 1047 let request = H2Client::request_builder("localhost", "POST", "speedtest", None, None).unwrap();
54a5a885 1048 let request_future = self.h2.send_request(request, Some(bytes::Bytes::from(data.clone()))).await?;
82ab7230 1049
54a5a885
DM
1050 upload_queue.send(request_future).await?;
1051 }
1052
1053 drop(upload_queue); // close queue
1054
1055 let _ = upload_result.await?;
1056
1057 println!("Uploaded {} chunks in {} seconds.", repeat, start_time.elapsed().as_secs());
1058 let speed = ((item_len*1000000*(repeat as usize))/(1024*1024))/(start_time.elapsed().as_micros() as usize);
1059 println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128));
1060
1061 Ok(speed)
adec8ea2 1062 }
9af37c8f
DM
1063}
1064
1065#[derive(Clone)]
1066pub struct H2Client {
1067 h2: h2::client::SendRequest<bytes::Bytes>,
1068}
1069
1070impl H2Client {
1071
1072 pub fn new(h2: h2::client::SendRequest<bytes::Bytes>) -> Self {
1073 Self { h2 }
1074 }
1075
2a1e6d7d
DM
1076 pub async fn get(
1077 &self,
1078 path: &str,
1079 param: Option<Value>
1080 ) -> Result<Value, Error> {
792a70b9 1081 let req = Self::request_builder("localhost", "GET", path, param, None).unwrap();
2a1e6d7d 1082 self.request(req).await
9af37c8f
DM
1083 }
1084
2a1e6d7d
DM
1085 pub async fn put(
1086 &self,
1087 path: &str,
1088 param: Option<Value>
1089 ) -> Result<Value, Error> {
792a70b9 1090 let req = Self::request_builder("localhost", "PUT", path, param, None).unwrap();
2a1e6d7d 1091 self.request(req).await
9af37c8f
DM
1092 }
1093
2a1e6d7d
DM
1094 pub async fn post(
1095 &self,
1096 path: &str,
1097 param: Option<Value>
1098 ) -> Result<Value, Error> {
792a70b9 1099 let req = Self::request_builder("localhost", "POST", path, param, None).unwrap();
2a1e6d7d 1100 self.request(req).await
9af37c8f
DM
1101 }
1102
d4a085e5 1103 pub async fn download<W: Write + Send>(
a6782ca1
WB
1104 &self,
1105 path: &str,
1106 param: Option<Value>,
2a1e6d7d 1107 mut output: W,
d4a085e5 1108 ) -> Result<W, Error> {
792a70b9 1109 let request = Self::request_builder("localhost", "GET", path, param, None).unwrap();
dd066d28 1110
2a1e6d7d 1111 let response_future = self.send_request(request, None).await?;
984a7c35 1112
2a1e6d7d
DM
1113 let resp = response_future.await?;
1114
1115 let status = resp.status();
1116 if !status.is_success() {
44f59dc7
DM
1117 H2Client::h2api_response(resp).await?; // raise error
1118 unreachable!();
2a1e6d7d
DM
1119 }
1120
1121 let mut body = resp.into_body();
1122 let mut release_capacity = body.release_capacity().clone();
1123
1124 while let Some(chunk) = body.try_next().await? {
1125 let _ = release_capacity.release_capacity(chunk.len());
1126 output.write_all(&chunk)?;
1127 }
1128
1129 Ok(output)
dd066d28
DM
1130 }
1131
2a1e6d7d 1132 pub async fn upload(
a6782ca1 1133 &self,
f011dba0 1134 method: &str, // POST or PUT
a6782ca1
WB
1135 path: &str,
1136 param: Option<Value>,
792a70b9 1137 content_type: &str,
a6782ca1 1138 data: Vec<u8>,
2a1e6d7d 1139 ) -> Result<Value, Error> {
f011dba0 1140 let request = Self::request_builder("localhost", method, path, param, Some(content_type)).unwrap();
9af37c8f 1141
2a1e6d7d
DM
1142 let mut send_request = self.h2.clone().ready().await?;
1143
1144 let (response, stream) = send_request.send_request(request, false).unwrap();
2a05048b
DM
1145
1146 PipeToSendStream::new(bytes::Bytes::from(data), stream).await?;
1147
1148 response
1149 .map_err(Error::from)
1150 .and_then(Self::h2api_response)
2a1e6d7d 1151 .await
9af37c8f 1152 }
adec8ea2 1153
2a1e6d7d 1154 async fn request(
9af37c8f 1155 &self,
b57cb264 1156 request: Request<()>,
2a1e6d7d 1157 ) -> Result<Value, Error> {
b57cb264 1158
9af37c8f 1159 self.send_request(request, None)
82ab7230
DM
1160 .and_then(move |response| {
1161 response
1162 .map_err(Error::from)
1163 .and_then(Self::h2api_response)
1164 })
2a1e6d7d 1165 .await
82ab7230
DM
1166 }
1167
1168 fn send_request(
9af37c8f 1169 &self,
82ab7230
DM
1170 request: Request<()>,
1171 data: Option<bytes::Bytes>,
a6782ca1 1172 ) -> impl Future<Output = Result<h2::client::ResponseFuture, Error>> {
82ab7230 1173
9af37c8f 1174 self.h2.clone()
10130cf4
DM
1175 .ready()
1176 .map_err(Error::from)
2a05048b 1177 .and_then(move |mut send_request| async move {
82ab7230
DM
1178 if let Some(data) = data {
1179 let (response, stream) = send_request.send_request(request, false).unwrap();
2a05048b
DM
1180 PipeToSendStream::new(data, stream).await?;
1181 Ok(response)
82ab7230
DM
1182 } else {
1183 let (response, _stream) = send_request.send_request(request, true).unwrap();
2a05048b 1184 Ok(response)
82ab7230 1185 }
b57cb264
DM
1186 })
1187 }
1188
9edd3bf1 1189 async fn h2api_response(
a6782ca1 1190 response: Response<h2::RecvStream>,
9edd3bf1 1191 ) -> Result<Value, Error> {
b57cb264
DM
1192 let status = response.status();
1193
1194 let (_head, mut body) = response.into_parts();
1195
1196 // The `release_capacity` handle allows the caller to manage
1197 // flow control.
1198 //
1199 // Whenever data is received, the caller is responsible for
1200 // releasing capacity back to the server once it has freed
1201 // the data from memory.
1202 let mut release_capacity = body.release_capacity().clone();
1203
9edd3bf1
DM
1204 let mut data = Vec::new();
1205 while let Some(chunk) = body.try_next().await? {
1206 // Let the server send more data.
1207 let _ = release_capacity.release_capacity(chunk.len());
1208 data.extend(chunk);
1209 }
1210
1211 let text = String::from_utf8(data.to_vec()).unwrap();
1212 if status.is_success() {
1213 if text.len() > 0 {
1214 let mut value: Value = serde_json::from_str(&text)?;
1215 if let Some(map) = value.as_object_mut() {
1216 if let Some(data) = map.remove("data") {
1217 return Ok(data);
b57cb264 1218 }
b57cb264 1219 }
9edd3bf1
DM
1220 bail!("got result without data property");
1221 } else {
1222 Ok(Value::Null)
1223 }
1224 } else {
1225 bail!("HTTP Error {}: {}", status, text);
1226 }
b57cb264
DM
1227 }
1228
eb2bdd1b 1229 // Note: We always encode parameters with the url
792a70b9
DM
1230 pub fn request_builder(
1231 server: &str,
1232 method: &str,
1233 path: &str,
1234 param: Option<Value>,
1235 content_type: Option<&str>,
1236 ) -> Result<Request<()>, Error> {
b57cb264 1237 let path = path.trim_matches('/');
b57cb264 1238
792a70b9
DM
1239 let content_type = content_type.unwrap_or("application/x-www-form-urlencoded");
1240
a55b2975
DM
1241 if let Some(param) = param {
1242 let query = tools::json_object_to_query(param)?;
eb2bdd1b
DM
1243 // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side
1244 if query.len() > 4096 { bail!("h2 query data too large ({} bytes) - please encode data inside body", query.len()); }
b57cb264 1245 let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?;
eb2bdd1b 1246 let request = Request::builder()
b57cb264
DM
1247 .method(method)
1248 .uri(url)
1249 .header("User-Agent", "proxmox-backup-client/1.0")
792a70b9 1250 .header(hyper::header::CONTENT_TYPE, content_type)
b57cb264
DM
1251 .body(())?;
1252 return Ok(request);
eb2bdd1b
DM
1253 } else {
1254 let url: Uri = format!("https://{}:8007/{}", server, path).parse()?;
1255 let request = Request::builder()
1256 .method(method)
1257 .uri(url)
1258 .header("User-Agent", "proxmox-backup-client/1.0")
792a70b9 1259 .header(hyper::header::CONTENT_TYPE, content_type)
eb2bdd1b 1260 .body(())?;
b57cb264 1261
eb2bdd1b
DM
1262 Ok(request)
1263 }
b57cb264
DM
1264 }
1265}
1434f4f8
WB
1266
1267pub struct HttpsConnector {
1268 http: HttpConnector,
1269 ssl_connector: SslConnector,
1270}
1271
1272impl HttpsConnector {
1273 pub fn with_connector(mut http: HttpConnector, ssl_connector: SslConnector) -> Self {
1274 http.enforce_http(false);
1275
1276 Self {
1277 http,
1278 ssl_connector,
1279 }
1280 }
1281}
1282
1283type MaybeTlsStream = EitherStream<
1284 tokio::net::TcpStream,
1285 tokio_openssl::SslStream<tokio::net::TcpStream>,
1286>;
1287
1288impl hyper::client::connect::Connect for HttpsConnector {
1289 type Transport = MaybeTlsStream;
1290 type Error = Error;
1291 type Future = Box<dyn Future<Output = Result<(
1292 Self::Transport,
1293 hyper::client::connect::Connected,
1294 ), Error>> + Send + Unpin + 'static>;
1295
1296 fn connect(&self, dst: hyper::client::connect::Destination) -> Self::Future {
1297 let is_https = dst.scheme() == "https";
1298 let host = dst.host().to_string();
1299
1300 let config = self.ssl_connector.configure();
1301 let conn = self.http.connect(dst);
1302
1303 Box::new(Box::pin(async move {
1304 let (conn, connected) = conn.await?;
1305 if is_https {
1306 let conn = tokio_openssl::connect(config?, &host, conn).await?;
1307 Ok((MaybeTlsStream::Right(conn), connected))
1308 } else {
1309 Ok((MaybeTlsStream::Left(conn), connected))
1310 }
1311 }))
1312 }
1313}