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