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