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