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