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