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