]>
Commit | Line | Data |
---|---|---|
c2b94534 | 1 | use std::io::Write; |
dd4b42ba DC |
2 | use std::sync::{Arc, Mutex, RwLock}; |
3 | use std::time::Duration; | |
597641fd | 4 | |
f7d4e4b5 | 5 | use anyhow::{bail, format_err, Error}; |
82ab7230 | 6 | use futures::*; |
7a57cb77 WB |
7 | use http::Uri; |
8 | use http::header::HeaderValue; | |
9 | use http::{Request, Response}; | |
10 | use hyper::Body; | |
1434f4f8 | 11 | use hyper::client::{Client, HttpConnector}; |
d59dbeca | 12 | use openssl::{ssl::{SslConnector, SslMethod}, x509::X509StoreContextRef}; |
ba3a60b2 | 13 | use serde_json::{json, Value}; |
8a1028e0 | 14 | use percent_encoding::percent_encode; |
7a57cb77 | 15 | use xdg::BaseDirectories; |
1fdb4c6f | 16 | |
501f4fa2 | 17 | use proxmox::{ |
91f5594c | 18 | api::error::HttpError, |
501f4fa2 | 19 | sys::linux::tty, |
5eb9dd0c | 20 | tools::fs::{file_get_json, replace_file, CreateOptions}, |
e18a6c9e DM |
21 | }; |
22 | ||
1d781c5b WB |
23 | use proxmox_http::client::HttpsConnector; |
24 | use proxmox_http::uri::build_authority; | |
8c090937 | 25 | |
be3a0295 | 26 | use pbs_api_types::{Authid, Userid}; |
4805edc4 | 27 | use pbs_tools::broadcast_future::BroadcastFuture; |
9eb78407 WB |
28 | use pbs_tools::json::json_object_to_query; |
29 | use pbs_tools::ticket; | |
4805edc4 | 30 | use pbs_tools::percent_encoding::DEFAULT_ENCODE_SET; |
be3a0295 | 31 | |
7a57cb77 | 32 | use super::pipe_to_stream::PipeToSendStream; |
4805edc4 | 33 | use super::PROXMOX_BACKUP_TCP_KEEPALIVE_TIME; |
986bef16 | 34 | |
4799280c | 35 | /// Timeout used for several HTTP operations that are expected to finish quickly but may block in |
a941bbd0 TL |
36 | /// certain error conditions. Keep it generous, to avoid false-positive under high load. |
37 | const HTTP_TIMEOUT: Duration = Duration::from_secs(2 * 60); | |
4799280c | 38 | |
5a2df000 | 39 | #[derive(Clone)] |
e240d8be | 40 | pub struct AuthInfo { |
34aa8e13 | 41 | pub auth_id: Authid, |
3743dee6 DM |
42 | pub ticket: String, |
43 | pub token: String, | |
5a2df000 | 44 | } |
56458d97 | 45 | |
d59dbeca | 46 | pub struct HttpClientOptions { |
5030b7ce | 47 | prefix: Option<String>, |
d59dbeca DM |
48 | password: Option<String>, |
49 | fingerprint: Option<String>, | |
50 | interactive: bool, | |
51 | ticket_cache: bool, | |
5a74756c | 52 | fingerprint_cache: bool, |
d59dbeca DM |
53 | verify_cert: bool, |
54 | } | |
55 | ||
56 | impl HttpClientOptions { | |
57 | ||
93e3581c | 58 | pub fn new_interactive(password: Option<String>, fingerprint: Option<String>) -> Self { |
d59dbeca | 59 | Self { |
93e3581c FG |
60 | password, |
61 | fingerprint, | |
62 | fingerprint_cache: true, | |
63 | ticket_cache: true, | |
64 | interactive: true, | |
65 | prefix: Some("proxmox-backup".to_string()), | |
66 | ..Self::default() | |
67 | } | |
68 | } | |
69 | ||
70 | pub fn new_non_interactive(password: String, fingerprint: Option<String>) -> Self { | |
71 | Self { | |
72 | password: Some(password), | |
73 | fingerprint, | |
74 | ..Self::default() | |
d59dbeca DM |
75 | } |
76 | } | |
77 | ||
5030b7ce DM |
78 | pub fn prefix(mut self, prefix: Option<String>) -> Self { |
79 | self.prefix = prefix; | |
80 | self | |
81 | } | |
82 | ||
d59dbeca DM |
83 | pub fn password(mut self, password: Option<String>) -> Self { |
84 | self.password = password; | |
85 | self | |
86 | } | |
87 | ||
88 | pub fn fingerprint(mut self, fingerprint: Option<String>) -> Self { | |
89 | self.fingerprint = fingerprint; | |
90 | self | |
91 | } | |
92 | ||
93 | pub fn interactive(mut self, interactive: bool) -> Self { | |
94 | self.interactive = interactive; | |
95 | self | |
96 | } | |
97 | ||
98 | pub fn ticket_cache(mut self, ticket_cache: bool) -> Self { | |
99 | self.ticket_cache = ticket_cache; | |
100 | self | |
101 | } | |
102 | ||
5a74756c DM |
103 | pub fn fingerprint_cache(mut self, fingerprint_cache: bool) -> Self { |
104 | self.fingerprint_cache = fingerprint_cache; | |
105 | self | |
106 | } | |
107 | ||
d59dbeca DM |
108 | pub fn verify_cert(mut self, verify_cert: bool) -> Self { |
109 | self.verify_cert = verify_cert; | |
110 | self | |
111 | } | |
112 | } | |
113 | ||
93e3581c FG |
114 | impl Default for HttpClientOptions { |
115 | fn default() -> Self { | |
116 | Self { | |
117 | prefix: None, | |
118 | password: None, | |
119 | fingerprint: None, | |
120 | interactive: false, | |
121 | ticket_cache: false, | |
122 | fingerprint_cache: false, | |
123 | verify_cert: true, | |
124 | } | |
125 | } | |
126 | } | |
127 | ||
151c6ce2 | 128 | /// HTTP(S) API client |
597641fd | 129 | pub struct HttpClient { |
1434f4f8 | 130 | client: Client<HttpsConnector>, |
597641fd | 131 | server: String, |
ba20987a | 132 | port: u16, |
d59dbeca | 133 | fingerprint: Arc<Mutex<Option<String>>>, |
34aa8e13 | 134 | first_auth: Option<BroadcastFuture<()>>, |
dd4b42ba DC |
135 | auth: Arc<RwLock<AuthInfo>>, |
136 | ticket_abort: futures::future::AbortHandle, | |
d59dbeca | 137 | _options: HttpClientOptions, |
597641fd DM |
138 | } |
139 | ||
e240d8be | 140 | /// Delete stored ticket data (logout) |
e7cb4dc5 | 141 | pub fn delete_ticket_info(prefix: &str, server: &str, username: &Userid) -> Result<(), Error> { |
e240d8be | 142 | |
5030b7ce | 143 | let base = BaseDirectories::with_prefix(prefix)?; |
e240d8be DM |
144 | |
145 | // usually /run/user/<uid>/... | |
146 | let path = base.place_runtime_file("tickets")?; | |
147 | ||
148 | let mode = nix::sys::stat::Mode::from_bits_truncate(0o0600); | |
149 | ||
150 | let mut data = file_get_json(&path, Some(json!({})))?; | |
151 | ||
152 | if let Some(map) = data[server].as_object_mut() { | |
e7cb4dc5 | 153 | map.remove(username.as_str()); |
e240d8be DM |
154 | } |
155 | ||
feaa1ad3 | 156 | replace_file(path, data.to_string().as_bytes(), CreateOptions::new().perm(mode))?; |
e240d8be DM |
157 | |
158 | Ok(()) | |
159 | } | |
160 | ||
5030b7ce | 161 | fn store_fingerprint(prefix: &str, server: &str, fingerprint: &str) -> Result<(), Error> { |
5a74756c | 162 | |
5030b7ce | 163 | let base = BaseDirectories::with_prefix(prefix)?; |
5a74756c | 164 | |
5030b7ce | 165 | // usually ~/.config/<prefix>/fingerprints |
5a74756c DM |
166 | let path = base.place_config_file("fingerprints")?; |
167 | ||
168 | let raw = match std::fs::read_to_string(&path) { | |
169 | Ok(v) => v, | |
170 | Err(err) => { | |
171 | if err.kind() == std::io::ErrorKind::NotFound { | |
172 | String::new() | |
173 | } else { | |
174 | bail!("unable to read fingerprints from {:?} - {}", path, err); | |
175 | } | |
176 | } | |
177 | }; | |
178 | ||
179 | let mut result = String::new(); | |
180 | ||
181 | raw.split('\n').for_each(|line| { | |
182 | let items: Vec<String> = line.split_whitespace().map(String::from).collect(); | |
183 | if items.len() == 2 { | |
29077d95 | 184 | if items[0] == server { |
5a74756c DM |
185 | // found, add later with new fingerprint |
186 | } else { | |
187 | result.push_str(line); | |
188 | result.push('\n'); | |
189 | } | |
190 | } | |
191 | }); | |
192 | ||
193 | result.push_str(server); | |
194 | result.push(' '); | |
195 | result.push_str(fingerprint); | |
196 | result.push('\n'); | |
197 | ||
198 | replace_file(path, result.as_bytes(), CreateOptions::new())?; | |
199 | ||
200 | Ok(()) | |
201 | } | |
202 | ||
5030b7ce | 203 | fn load_fingerprint(prefix: &str, server: &str) -> Option<String> { |
5a74756c | 204 | |
5030b7ce | 205 | let base = BaseDirectories::with_prefix(prefix).ok()?; |
5a74756c | 206 | |
5030b7ce | 207 | // usually ~/.config/<prefix>/fingerprints |
5a74756c DM |
208 | let path = base.place_config_file("fingerprints").ok()?; |
209 | ||
210 | let raw = std::fs::read_to_string(&path).ok()?; | |
211 | ||
212 | for line in raw.split('\n') { | |
213 | let items: Vec<String> = line.split_whitespace().map(String::from).collect(); | |
29077d95 | 214 | if items.len() == 2 && items[0] == server { |
8db14689 | 215 | return Some(items[1].clone()); |
5a74756c DM |
216 | } |
217 | } | |
218 | ||
219 | None | |
220 | } | |
221 | ||
5030b7ce | 222 | fn store_ticket_info(prefix: &str, server: &str, username: &str, ticket: &str, token: &str) -> Result<(), Error> { |
ba3a60b2 | 223 | |
5030b7ce | 224 | let base = BaseDirectories::with_prefix(prefix)?; |
ba3a60b2 DM |
225 | |
226 | // usually /run/user/<uid>/... | |
227 | let path = base.place_runtime_file("tickets")?; | |
228 | ||
229 | let mode = nix::sys::stat::Mode::from_bits_truncate(0o0600); | |
230 | ||
e18a6c9e | 231 | let mut data = file_get_json(&path, Some(json!({})))?; |
ba3a60b2 | 232 | |
6a7be83e | 233 | let now = proxmox::tools::time::epoch_i64(); |
ba3a60b2 DM |
234 | |
235 | data[server][username] = json!({ "timestamp": now, "ticket": ticket, "token": token}); | |
236 | ||
237 | let mut new_data = json!({}); | |
238 | ||
9eb78407 | 239 | let ticket_lifetime = ticket::TICKET_LIFETIME - 60; |
ba3a60b2 DM |
240 | |
241 | let empty = serde_json::map::Map::new(); | |
242 | for (server, info) in data.as_object().unwrap_or(&empty) { | |
afef7f3b | 243 | for (user, uinfo) in info.as_object().unwrap_or(&empty) { |
4e32d1c5 DM |
244 | if let Some(timestamp) = uinfo["timestamp"].as_i64() { |
245 | let age = now - timestamp; | |
246 | if age < ticket_lifetime { | |
247 | new_data[server][user] = uinfo.clone(); | |
ba3a60b2 DM |
248 | } |
249 | } | |
250 | } | |
251 | } | |
252 | ||
feaa1ad3 | 253 | replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new().perm(mode))?; |
ba3a60b2 DM |
254 | |
255 | Ok(()) | |
256 | } | |
257 | ||
e7cb4dc5 | 258 | fn load_ticket_info(prefix: &str, server: &str, userid: &Userid) -> Option<(String, String)> { |
5030b7ce | 259 | let base = BaseDirectories::with_prefix(prefix).ok()?; |
ba3a60b2 DM |
260 | |
261 | // usually /run/user/<uid>/... | |
66c8eb93 CE |
262 | let path = base.place_runtime_file("tickets").ok()?; |
263 | let data = file_get_json(&path, None).ok()?; | |
6a7be83e | 264 | let now = proxmox::tools::time::epoch_i64(); |
9eb78407 | 265 | let ticket_lifetime = ticket::TICKET_LIFETIME - 60; |
e7cb4dc5 | 266 | let uinfo = data[server][userid.as_str()].as_object()?; |
66c8eb93 CE |
267 | let timestamp = uinfo["timestamp"].as_i64()?; |
268 | let age = now - timestamp; | |
269 | ||
270 | if age < ticket_lifetime { | |
271 | let ticket = uinfo["ticket"].as_str()?; | |
272 | let token = uinfo["token"].as_str()?; | |
273 | Some((ticket.to_owned(), token.to_owned())) | |
274 | } else { | |
275 | None | |
ba3a60b2 | 276 | } |
ba3a60b2 DM |
277 | } |
278 | ||
a2daecc2 | 279 | fn build_uri(server: &str, port: u16, path: &str, query: Option<String>) -> Result<Uri, Error> { |
c4e1af30 | 280 | Uri::builder() |
25d78b10 | 281 | .scheme("https") |
c4e1af30 WB |
282 | .authority(build_authority(server, port)?) |
283 | .path_and_query(match query { | |
284 | Some(query) => format!("/{}?{}", path, query), | |
285 | None => format!("/{}", path), | |
286 | }) | |
287 | .build() | |
288 | .map_err(|err| format_err!("error building uri - {}", err)) | |
a2daecc2 DM |
289 | } |
290 | ||
597641fd | 291 | impl HttpClient { |
e7cb4dc5 WB |
292 | pub fn new( |
293 | server: &str, | |
ba20987a | 294 | port: u16, |
34aa8e13 | 295 | auth_id: &Authid, |
e7cb4dc5 WB |
296 | mut options: HttpClientOptions, |
297 | ) -> Result<Self, Error> { | |
d59dbeca DM |
298 | |
299 | let verified_fingerprint = Arc::new(Mutex::new(None)); | |
300 | ||
56d98ba9 | 301 | let mut expected_fingerprint = options.fingerprint.take(); |
a6e3da98 | 302 | |
56d98ba9 | 303 | if expected_fingerprint.is_some() { |
a6e3da98 DM |
304 | // do not store fingerprints passed via options in cache |
305 | options.fingerprint_cache = false; | |
306 | } else if options.fingerprint_cache && options.prefix.is_some() { | |
56d98ba9 | 307 | expected_fingerprint = load_fingerprint(options.prefix.as_ref().unwrap(), server); |
5a74756c DM |
308 | } |
309 | ||
5030b7ce DM |
310 | let mut ssl_connector_builder = SslConnector::builder(SslMethod::tls()).unwrap(); |
311 | ||
312 | if options.verify_cert { | |
313 | let server = server.to_string(); | |
314 | let verified_fingerprint = verified_fingerprint.clone(); | |
315 | let interactive = options.interactive; | |
316 | let fingerprint_cache = options.fingerprint_cache; | |
317 | let prefix = options.prefix.clone(); | |
318 | ssl_connector_builder.set_verify_callback(openssl::ssl::SslVerifyMode::PEER, move |valid, ctx| { | |
065013cc FG |
319 | match Self::verify_callback(valid, ctx, expected_fingerprint.as_ref(), interactive) { |
320 | Ok(None) => true, | |
321 | Ok(Some(fingerprint)) => { | |
5030b7ce DM |
322 | if fingerprint_cache && prefix.is_some() { |
323 | if let Err(err) = store_fingerprint( | |
324 | prefix.as_ref().unwrap(), &server, &fingerprint) { | |
325 | eprintln!("{}", err); | |
326 | } | |
327 | } | |
328 | *verified_fingerprint.lock().unwrap() = Some(fingerprint); | |
065013cc FG |
329 | true |
330 | }, | |
331 | Err(err) => { | |
332 | eprintln!("certificate validation failed - {}", err); | |
333 | false | |
334 | }, | |
5030b7ce | 335 | } |
5030b7ce DM |
336 | }); |
337 | } else { | |
338 | ssl_connector_builder.set_verify(openssl::ssl::SslVerifyMode::NONE); | |
339 | } | |
340 | ||
5eb9dd0c | 341 | let mut httpc = HttpConnector::new(); |
5030b7ce | 342 | httpc.set_nodelay(true); // important for h2 download performance! |
5030b7ce DM |
343 | httpc.enforce_http(false); // we want https... |
344 | ||
bb14d467 | 345 | httpc.set_connect_timeout(Some(std::time::Duration::new(10, 0))); |
3ed7e875 | 346 | let https = HttpsConnector::with_connector(httpc, ssl_connector_builder.build(), PROXMOX_BACKUP_TCP_KEEPALIVE_TIME); |
5030b7ce DM |
347 | |
348 | let client = Client::builder() | |
349 | //.http2_initial_stream_window_size( (1 << 31) - 2) | |
350 | //.http2_initial_connection_window_size( (1 << 31) - 2) | |
351 | .build::<_, Body>(https); | |
d59dbeca DM |
352 | |
353 | let password = options.password.take(); | |
5030b7ce | 354 | let use_ticket_cache = options.ticket_cache && options.prefix.is_some(); |
5a2df000 | 355 | |
cc2ce4a9 DM |
356 | let password = if let Some(password) = password { |
357 | password | |
45cdce06 | 358 | } else { |
34aa8e13 FG |
359 | let userid = if auth_id.is_token() { |
360 | bail!("API token secret must be provided!"); | |
361 | } else { | |
362 | auth_id.user() | |
363 | }; | |
d59dbeca | 364 | let mut ticket_info = None; |
5030b7ce | 365 | if use_ticket_cache { |
e7cb4dc5 | 366 | ticket_info = load_ticket_info(options.prefix.as_ref().unwrap(), server, userid); |
d59dbeca DM |
367 | } |
368 | if let Some((ticket, _token)) = ticket_info { | |
369 | ticket | |
370 | } else { | |
e7cb4dc5 | 371 | Self::get_password(userid, options.interactive)? |
d59dbeca | 372 | } |
45cdce06 DM |
373 | }; |
374 | ||
dd4b42ba | 375 | let auth = Arc::new(RwLock::new(AuthInfo { |
34aa8e13 | 376 | auth_id: auth_id.clone(), |
dd4b42ba DC |
377 | ticket: password.clone(), |
378 | token: "".to_string(), | |
379 | })); | |
380 | ||
381 | let server2 = server.to_string(); | |
382 | let client2 = client.clone(); | |
383 | let auth2 = auth.clone(); | |
384 | let prefix2 = options.prefix.clone(); | |
385 | ||
386 | let renewal_future = async move { | |
387 | loop { | |
0a8d773a | 388 | tokio::time::sleep(Duration::new(60*15, 0)).await; // 15 minutes |
34aa8e13 | 389 | let (auth_id, ticket) = { |
dd4b42ba | 390 | let authinfo = auth2.read().unwrap().clone(); |
34aa8e13 | 391 | (authinfo.auth_id, authinfo.ticket) |
dd4b42ba | 392 | }; |
34aa8e13 | 393 | match Self::credentials(client2.clone(), server2.clone(), port, auth_id.user().clone(), ticket).await { |
dd4b42ba | 394 | Ok(auth) => { |
dbd00a57 | 395 | if use_ticket_cache && prefix2.is_some() { |
34aa8e13 | 396 | let _ = store_ticket_info(prefix2.as_ref().unwrap(), &server2, &auth.auth_id.to_string(), &auth.ticket, &auth.token); |
dd4b42ba DC |
397 | } |
398 | *auth2.write().unwrap() = auth; | |
399 | }, | |
400 | Err(err) => { | |
401 | eprintln!("re-authentication failed: {}", err); | |
402 | return; | |
403 | } | |
404 | } | |
405 | } | |
406 | }; | |
407 | ||
408 | let (renewal_future, ticket_abort) = futures::future::abortable(renewal_future); | |
409 | ||
d59dbeca DM |
410 | let login_future = Self::credentials( |
411 | client.clone(), | |
412 | server.to_owned(), | |
ba20987a | 413 | port, |
34aa8e13 | 414 | auth_id.user().clone(), |
29077d95 | 415 | password, |
5030b7ce DM |
416 | ).map_ok({ |
417 | let server = server.to_string(); | |
418 | let prefix = options.prefix.clone(); | |
dd4b42ba | 419 | let authinfo = auth.clone(); |
5030b7ce DM |
420 | |
421 | move |auth| { | |
dbd00a57 | 422 | if use_ticket_cache && prefix.is_some() { |
34aa8e13 | 423 | let _ = store_ticket_info(prefix.as_ref().unwrap(), &server, &auth.auth_id.to_string(), &auth.ticket, &auth.token); |
5030b7ce | 424 | } |
dd4b42ba DC |
425 | *authinfo.write().unwrap() = auth; |
426 | tokio::spawn(renewal_future); | |
5030b7ce DM |
427 | } |
428 | }); | |
45cdce06 | 429 | |
34aa8e13 FG |
430 | let first_auth = if auth_id.is_token() { |
431 | // TODO check access here? | |
432 | None | |
433 | } else { | |
434 | Some(BroadcastFuture::new(Box::new(login_future))) | |
435 | }; | |
436 | ||
45cdce06 | 437 | Ok(Self { |
5a2df000 | 438 | client, |
597641fd | 439 | server: String::from(server), |
ba20987a | 440 | port, |
d59dbeca | 441 | fingerprint: verified_fingerprint, |
dd4b42ba DC |
442 | auth, |
443 | ticket_abort, | |
34aa8e13 | 444 | first_auth, |
d59dbeca | 445 | _options: options, |
45cdce06 | 446 | }) |
597641fd DM |
447 | } |
448 | ||
1a7a0e74 | 449 | /// Login |
e240d8be | 450 | /// |
add5861e | 451 | /// Login is done on demand, so this is only required if you need |
e240d8be | 452 | /// access to authentication data in 'AuthInfo'. |
0081903f DM |
453 | /// |
454 | /// Note: tickets a periodially re-newed, so one can use this | |
455 | /// to query changed ticket. | |
96f5e80a | 456 | pub async fn login(&self) -> Result<AuthInfo, Error> { |
34aa8e13 FG |
457 | if let Some(future) = &self.first_auth { |
458 | future.listen().await?; | |
459 | } | |
460 | ||
dd4b42ba DC |
461 | let authinfo = self.auth.read().unwrap(); |
462 | Ok(authinfo.clone()) | |
e240d8be DM |
463 | } |
464 | ||
d59dbeca DM |
465 | /// Returns the optional fingerprint passed to the new() constructor. |
466 | pub fn fingerprint(&self) -> Option<String> { | |
467 | (*self.fingerprint.lock().unwrap()).clone() | |
468 | } | |
469 | ||
e7cb4dc5 | 470 | fn get_password(username: &Userid, interactive: bool) -> Result<String, Error> { |
56458d97 | 471 | // If we're on a TTY, query the user for a password |
d59dbeca | 472 | if interactive && tty::stdin_isatty() { |
99d863d7 DM |
473 | let msg = format!("Password for \"{}\": ", username); |
474 | return Ok(String::from_utf8(tty::read_password(&msg)?)?); | |
56458d97 WB |
475 | } |
476 | ||
477 | bail!("no password input mechanism available"); | |
478 | } | |
479 | ||
d59dbeca | 480 | fn verify_callback( |
065013cc | 481 | openssl_valid: bool, |
56d98ba9 FG |
482 | ctx: &mut X509StoreContextRef, |
483 | expected_fingerprint: Option<&String>, | |
d59dbeca | 484 | interactive: bool, |
065013cc FG |
485 | ) -> Result<Option<String>, Error> { |
486 | ||
487 | if openssl_valid { | |
488 | return Ok(None); | |
489 | } | |
d59dbeca DM |
490 | |
491 | let cert = match ctx.current_cert() { | |
492 | Some(cert) => cert, | |
065013cc | 493 | None => bail!("context lacks current certificate."), |
d59dbeca DM |
494 | }; |
495 | ||
496 | let depth = ctx.error_depth(); | |
065013cc | 497 | if depth != 0 { bail!("context depth != 0") } |
d59dbeca DM |
498 | |
499 | let fp = match cert.digest(openssl::hash::MessageDigest::sha256()) { | |
500 | Ok(fp) => fp, | |
065013cc | 501 | Err(err) => bail!("failed to calculate certificate FP - {}", err), // should not happen |
d59dbeca DM |
502 | }; |
503 | let fp_string = proxmox::tools::digest_to_hex(&fp); | |
504 | let fp_string = fp_string.as_bytes().chunks(2).map(|v| std::str::from_utf8(v).unwrap()) | |
505 | .collect::<Vec<&str>>().join(":"); | |
506 | ||
507 | if let Some(expected_fingerprint) = expected_fingerprint { | |
dda1b4fa FG |
508 | let expected_fingerprint = expected_fingerprint.to_lowercase(); |
509 | if expected_fingerprint == fp_string { | |
065013cc | 510 | return Ok(Some(fp_string)); |
d59dbeca | 511 | } else { |
dda1b4fa FG |
512 | eprintln!("WARNING: certificate fingerprint does not match expected fingerprint!"); |
513 | eprintln!("expected: {}", expected_fingerprint); | |
d59dbeca DM |
514 | } |
515 | } | |
516 | ||
517 | // If we're on a TTY, query the user | |
518 | if interactive && tty::stdin_isatty() { | |
85f4e834 | 519 | eprintln!("fingerprint: {}", fp_string); |
d59dbeca | 520 | loop { |
85f4e834 | 521 | eprint!("Are you sure you want to continue connecting? (y/n): "); |
d59dbeca | 522 | let _ = std::io::stdout().flush(); |
a595f0fe WB |
523 | use std::io::{BufRead, BufReader}; |
524 | let mut line = String::new(); | |
525 | match BufReader::new(std::io::stdin()).read_line(&mut line) { | |
526 | Ok(_) => { | |
527 | let trimmed = line.trim(); | |
528 | if trimmed == "y" || trimmed == "Y" { | |
065013cc | 529 | return Ok(Some(fp_string)); |
a595f0fe | 530 | } else if trimmed == "n" || trimmed == "N" { |
065013cc | 531 | bail!("Certificate fingerprint was not confirmed."); |
a595f0fe WB |
532 | } else { |
533 | continue; | |
d59dbeca DM |
534 | } |
535 | } | |
065013cc | 536 | Err(err) => bail!("Certificate fingerprint was not confirmed - {}.", err), |
d59dbeca DM |
537 | } |
538 | } | |
539 | } | |
065013cc FG |
540 | |
541 | bail!("Certificate fingerprint was not confirmed."); | |
a6b75513 DM |
542 | } |
543 | ||
1a7a0e74 | 544 | pub async fn request(&self, mut req: Request<Body>) -> Result<Value, Error> { |
597641fd | 545 | |
5a2df000 | 546 | let client = self.client.clone(); |
597641fd | 547 | |
1a7a0e74 | 548 | let auth = self.login().await?; |
34aa8e13 | 549 | if auth.auth_id.is_token() { |
36273905 | 550 | let enc_api_token = format!("PBSAPIToken {}:{}", auth.auth_id, percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)); |
34aa8e13 FG |
551 | req.headers_mut().insert("Authorization", HeaderValue::from_str(&enc_api_token).unwrap()); |
552 | } else { | |
553 | let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)); | |
554 | req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap()); | |
555 | req.headers_mut().insert("CSRFPreventionToken", HeaderValue::from_str(&auth.token).unwrap()); | |
556 | } | |
597641fd | 557 | |
1a7a0e74 | 558 | Self::api_request(client, req).await |
1fdb4c6f DM |
559 | } |
560 | ||
1a7a0e74 | 561 | pub async fn get( |
a6782ca1 WB |
562 | &self, |
563 | path: &str, | |
564 | data: Option<Value>, | |
1a7a0e74 | 565 | ) -> Result<Value, Error> { |
ba20987a | 566 | let req = Self::request_builder(&self.server, self.port, "GET", path, data)?; |
1a7a0e74 | 567 | self.request(req).await |
a6b75513 DM |
568 | } |
569 | ||
1a7a0e74 | 570 | pub async fn delete( |
a6782ca1 WB |
571 | &mut self, |
572 | path: &str, | |
573 | data: Option<Value>, | |
1a7a0e74 | 574 | ) -> Result<Value, Error> { |
ba20987a | 575 | let req = Self::request_builder(&self.server, self.port, "DELETE", path, data)?; |
1a7a0e74 | 576 | self.request(req).await |
a6b75513 DM |
577 | } |
578 | ||
1a7a0e74 | 579 | pub async fn post( |
a6782ca1 WB |
580 | &mut self, |
581 | path: &str, | |
582 | data: Option<Value>, | |
1a7a0e74 | 583 | ) -> Result<Value, Error> { |
ba20987a | 584 | let req = Self::request_builder(&self.server, self.port, "POST", path, data)?; |
1a7a0e74 | 585 | self.request(req).await |
024f11bb DM |
586 | } |
587 | ||
3c945d73 DC |
588 | pub async fn put( |
589 | &mut self, | |
590 | path: &str, | |
591 | data: Option<Value>, | |
592 | ) -> Result<Value, Error> { | |
593 | let req = Self::request_builder(&self.server, self.port, "PUT", path, data)?; | |
594 | self.request(req).await | |
595 | } | |
596 | ||
1a7a0e74 | 597 | pub async fn download( |
a6782ca1 WB |
598 | &mut self, |
599 | path: &str, | |
1a7a0e74 | 600 | output: &mut (dyn Write + Send), |
3d571d55 | 601 | ) -> Result<(), Error> { |
ba20987a | 602 | let mut req = Self::request_builder(&self.server, self.port, "GET", path, None)?; |
024f11bb | 603 | |
5a2df000 | 604 | let client = self.client.clone(); |
1fdb4c6f | 605 | |
1a7a0e74 | 606 | let auth = self.login().await?; |
81da38c1 | 607 | |
1a7a0e74 DM |
608 | let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)); |
609 | req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap()); | |
6f62c924 | 610 | |
d148958b FG |
611 | let resp = tokio::time::timeout( |
612 | HTTP_TIMEOUT, | |
613 | client.request(req) | |
614 | ) | |
615 | .await | |
616 | .map_err(|_| format_err!("http download request timed out"))??; | |
1a7a0e74 DM |
617 | let status = resp.status(); |
618 | if !status.is_success() { | |
619 | HttpClient::api_response(resp) | |
620 | .map(|_| Err(format_err!("unknown error"))) | |
621 | .await? | |
622 | } else { | |
623 | resp.into_body() | |
5a2df000 | 624 | .map_err(Error::from) |
1a7a0e74 DM |
625 | .try_fold(output, move |acc, chunk| async move { |
626 | acc.write_all(&chunk)?; | |
627 | Ok::<_, Error>(acc) | |
5a2df000 | 628 | }) |
1a7a0e74 DM |
629 | .await?; |
630 | } | |
631 | Ok(()) | |
6f62c924 DM |
632 | } |
633 | ||
1a7a0e74 | 634 | pub async fn upload( |
04512d30 DM |
635 | &mut self, |
636 | content_type: &str, | |
637 | body: Body, | |
638 | path: &str, | |
639 | data: Option<Value>, | |
1a7a0e74 | 640 | ) -> Result<Value, Error> { |
81da38c1 | 641 | |
a2daecc2 | 642 | let query = match data { |
9eb78407 | 643 | Some(data) => Some(json_object_to_query(data)?), |
a2daecc2 DM |
644 | None => None, |
645 | }; | |
646 | let url = build_uri(&self.server, self.port, path, query)?; | |
81da38c1 | 647 | |
5a2df000 | 648 | let req = Request::builder() |
81da38c1 DM |
649 | .method("POST") |
650 | .uri(url) | |
651 | .header("User-Agent", "proxmox-backup-client/1.0") | |
5a2df000 DM |
652 | .header("Content-Type", content_type) |
653 | .body(body).unwrap(); | |
81da38c1 | 654 | |
1a7a0e74 | 655 | self.request(req).await |
1fdb4c6f DM |
656 | } |
657 | ||
1a7a0e74 | 658 | pub async fn start_h2_connection( |
fb047083 DM |
659 | &self, |
660 | mut req: Request<Body>, | |
661 | protocol_name: String, | |
dc089345 | 662 | ) -> Result<(H2Client, futures::future::AbortHandle), Error> { |
cf639a47 DM |
663 | |
664 | let client = self.client.clone(); | |
34aa8e13 FG |
665 | let auth = self.login().await?; |
666 | ||
667 | if auth.auth_id.is_token() { | |
36273905 | 668 | let enc_api_token = format!("PBSAPIToken {}:{}", auth.auth_id, percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)); |
34aa8e13 FG |
669 | req.headers_mut().insert("Authorization", HeaderValue::from_str(&enc_api_token).unwrap()); |
670 | } else { | |
671 | let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)); | |
672 | req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap()); | |
673 | req.headers_mut().insert("CSRFPreventionToken", HeaderValue::from_str(&auth.token).unwrap()); | |
674 | } | |
cf639a47 | 675 | |
1a7a0e74 | 676 | req.headers_mut().insert("UPGRADE", HeaderValue::from_str(&protocol_name).unwrap()); |
cf639a47 | 677 | |
d148958b FG |
678 | let resp = tokio::time::timeout( |
679 | HTTP_TIMEOUT, | |
680 | client.request(req) | |
681 | ) | |
682 | .await | |
683 | .map_err(|_| format_err!("http upgrade request timed out"))??; | |
1a7a0e74 | 684 | let status = resp.status(); |
cf639a47 | 685 | |
1a7a0e74 | 686 | if status != http::StatusCode::SWITCHING_PROTOCOLS { |
ca611955 DM |
687 | Self::api_response(resp).await?; |
688 | bail!("unknown error"); | |
1a7a0e74 DM |
689 | } |
690 | ||
89e9134a | 691 | let upgraded = hyper::upgrade::on(resp).await?; |
1a7a0e74 DM |
692 | |
693 | let max_window_size = (1 << 31) - 2; | |
694 | ||
695 | let (h2, connection) = h2::client::Builder::new() | |
696 | .initial_connection_window_size(max_window_size) | |
697 | .initial_window_size(max_window_size) | |
698 | .max_frame_size(4*1024*1024) | |
699 | .handshake(upgraded) | |
700 | .await?; | |
701 | ||
702 | let connection = connection | |
97168f92 | 703 | .map_err(|_| eprintln!("HTTP/2.0 connection failed")); |
1a7a0e74 | 704 | |
dc089345 | 705 | let (connection, abort) = futures::future::abortable(connection); |
1a7a0e74 DM |
706 | // A cancellable future returns an Option which is None when cancelled and |
707 | // Some when it finished instead, since we don't care about the return type we | |
708 | // need to map it away: | |
709 | let connection = connection.map(|_| ()); | |
710 | ||
711 | // Spawn a new task to drive the connection state | |
db0cb9ce | 712 | tokio::spawn(connection); |
1a7a0e74 DM |
713 | |
714 | // Wait until the `SendRequest` handle has available capacity. | |
715 | let c = h2.ready().await?; | |
dc089345 | 716 | Ok((H2Client::new(c), abort)) |
cf639a47 DM |
717 | } |
718 | ||
9d35dbbb | 719 | async fn credentials( |
1434f4f8 | 720 | client: Client<HttpsConnector>, |
45cdce06 | 721 | server: String, |
ba20987a | 722 | port: u16, |
e7cb4dc5 | 723 | username: Userid, |
45cdce06 | 724 | password: String, |
9d35dbbb DM |
725 | ) -> Result<AuthInfo, Error> { |
726 | let data = json!({ "username": username, "password": password }); | |
ba20987a | 727 | let req = Self::request_builder(&server, port, "POST", "/api2/json/access/ticket", Some(data))?; |
9d35dbbb DM |
728 | let cred = Self::api_request(client, req).await?; |
729 | let auth = AuthInfo { | |
34aa8e13 | 730 | auth_id: cred["data"]["username"].as_str().unwrap().parse()?, |
9d35dbbb DM |
731 | ticket: cred["data"]["ticket"].as_str().unwrap().to_owned(), |
732 | token: cred["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(), | |
733 | }; | |
734 | ||
9d35dbbb | 735 | Ok(auth) |
ba3a60b2 DM |
736 | } |
737 | ||
a6782ca1 | 738 | async fn api_response(response: Response<Body>) -> Result<Value, Error> { |
d2c48afc | 739 | let status = response.status(); |
db0cb9ce | 740 | let data = hyper::body::to_bytes(response.into_body()).await?; |
a6782ca1 WB |
741 | |
742 | let text = String::from_utf8(data.to_vec()).unwrap(); | |
743 | if status.is_success() { | |
11377a47 DM |
744 | if text.is_empty() { |
745 | Ok(Value::Null) | |
746 | } else { | |
a6782ca1 WB |
747 | let value: Value = serde_json::from_str(&text)?; |
748 | Ok(value) | |
a6782ca1 WB |
749 | } |
750 | } else { | |
91f5594c | 751 | Err(Error::from(HttpError::new(status, text))) |
a6782ca1 | 752 | } |
d2c48afc DM |
753 | } |
754 | ||
1a7a0e74 | 755 | async fn api_request( |
1434f4f8 | 756 | client: Client<HttpsConnector>, |
5a2df000 | 757 | req: Request<Body> |
1a7a0e74 | 758 | ) -> Result<Value, Error> { |
ba3a60b2 | 759 | |
d148958b FG |
760 | Self::api_response( |
761 | tokio::time::timeout( | |
762 | HTTP_TIMEOUT, | |
763 | client.request(req) | |
764 | ) | |
765 | .await | |
766 | .map_err(|_| format_err!("http request timed out"))?? | |
767 | ).await | |
0dffe3f9 DM |
768 | } |
769 | ||
9e490a74 DM |
770 | // Read-only access to server property |
771 | pub fn server(&self) -> &str { | |
772 | &self.server | |
773 | } | |
774 | ||
ba20987a DC |
775 | pub fn port(&self) -> u16 { |
776 | self.port | |
777 | } | |
778 | ||
779 | pub fn request_builder(server: &str, port: u16, method: &str, path: &str, data: Option<Value>) -> Result<Request<Body>, Error> { | |
5a2df000 DM |
780 | if let Some(data) = data { |
781 | if method == "POST" { | |
a2daecc2 | 782 | let url = build_uri(server, port, path, None)?; |
5a2df000 DM |
783 | let request = Request::builder() |
784 | .method(method) | |
785 | .uri(url) | |
786 | .header("User-Agent", "proxmox-backup-client/1.0") | |
787 | .header(hyper::header::CONTENT_TYPE, "application/json") | |
788 | .body(Body::from(data.to_string()))?; | |
a2daecc2 | 789 | Ok(request) |
5a2df000 | 790 | } else { |
9eb78407 | 791 | let query = json_object_to_query(data)?; |
a2daecc2 | 792 | let url = build_uri(server, port, path, Some(query))?; |
9e391bb7 DM |
793 | let request = Request::builder() |
794 | .method(method) | |
795 | .uri(url) | |
796 | .header("User-Agent", "proxmox-backup-client/1.0") | |
797 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
798 | .body(Body::empty())?; | |
a2daecc2 | 799 | Ok(request) |
5a2df000 | 800 | } |
a2daecc2 DM |
801 | } else { |
802 | let url = build_uri(server, port, path, None)?; | |
803 | let request = Request::builder() | |
804 | .method(method) | |
805 | .uri(url) | |
806 | .header("User-Agent", "proxmox-backup-client/1.0") | |
807 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
808 | .body(Body::empty())?; | |
1fdb4c6f | 809 | |
a2daecc2 DM |
810 | Ok(request) |
811 | } | |
597641fd DM |
812 | } |
813 | } | |
b57cb264 | 814 | |
dd4b42ba DC |
815 | impl Drop for HttpClient { |
816 | fn drop(&mut self) { | |
817 | self.ticket_abort.abort(); | |
818 | } | |
819 | } | |
820 | ||
9af37c8f DM |
821 | |
822 | #[derive(Clone)] | |
823 | pub struct H2Client { | |
824 | h2: h2::client::SendRequest<bytes::Bytes>, | |
825 | } | |
826 | ||
827 | impl H2Client { | |
828 | ||
829 | pub fn new(h2: h2::client::SendRequest<bytes::Bytes>) -> Self { | |
830 | Self { h2 } | |
831 | } | |
832 | ||
2a1e6d7d DM |
833 | pub async fn get( |
834 | &self, | |
835 | path: &str, | |
836 | param: Option<Value> | |
837 | ) -> Result<Value, Error> { | |
792a70b9 | 838 | let req = Self::request_builder("localhost", "GET", path, param, None).unwrap(); |
2a1e6d7d | 839 | self.request(req).await |
9af37c8f DM |
840 | } |
841 | ||
2a1e6d7d DM |
842 | pub async fn put( |
843 | &self, | |
844 | path: &str, | |
845 | param: Option<Value> | |
846 | ) -> Result<Value, Error> { | |
792a70b9 | 847 | let req = Self::request_builder("localhost", "PUT", path, param, None).unwrap(); |
2a1e6d7d | 848 | self.request(req).await |
9af37c8f DM |
849 | } |
850 | ||
2a1e6d7d DM |
851 | pub async fn post( |
852 | &self, | |
853 | path: &str, | |
854 | param: Option<Value> | |
855 | ) -> Result<Value, Error> { | |
792a70b9 | 856 | let req = Self::request_builder("localhost", "POST", path, param, None).unwrap(); |
2a1e6d7d | 857 | self.request(req).await |
9af37c8f DM |
858 | } |
859 | ||
d4a085e5 | 860 | pub async fn download<W: Write + Send>( |
a6782ca1 WB |
861 | &self, |
862 | path: &str, | |
863 | param: Option<Value>, | |
2a1e6d7d | 864 | mut output: W, |
3d571d55 | 865 | ) -> Result<(), Error> { |
792a70b9 | 866 | let request = Self::request_builder("localhost", "GET", path, param, None).unwrap(); |
dd066d28 | 867 | |
2a1e6d7d | 868 | let response_future = self.send_request(request, None).await?; |
984a7c35 | 869 | |
2a1e6d7d DM |
870 | let resp = response_future.await?; |
871 | ||
872 | let status = resp.status(); | |
873 | if !status.is_success() { | |
44f59dc7 DM |
874 | H2Client::h2api_response(resp).await?; // raise error |
875 | unreachable!(); | |
2a1e6d7d DM |
876 | } |
877 | ||
878 | let mut body = resp.into_body(); | |
db0cb9ce WB |
879 | while let Some(chunk) = body.data().await { |
880 | let chunk = chunk?; | |
881 | body.flow_control().release_capacity(chunk.len())?; | |
2a1e6d7d DM |
882 | output.write_all(&chunk)?; |
883 | } | |
884 | ||
3d571d55 | 885 | Ok(()) |
dd066d28 DM |
886 | } |
887 | ||
2a1e6d7d | 888 | pub async fn upload( |
a6782ca1 | 889 | &self, |
f011dba0 | 890 | method: &str, // POST or PUT |
a6782ca1 WB |
891 | path: &str, |
892 | param: Option<Value>, | |
792a70b9 | 893 | content_type: &str, |
a6782ca1 | 894 | data: Vec<u8>, |
2a1e6d7d | 895 | ) -> Result<Value, Error> { |
f011dba0 | 896 | let request = Self::request_builder("localhost", method, path, param, Some(content_type)).unwrap(); |
9af37c8f | 897 | |
2a1e6d7d DM |
898 | let mut send_request = self.h2.clone().ready().await?; |
899 | ||
900 | let (response, stream) = send_request.send_request(request, false).unwrap(); | |
2a05048b DM |
901 | |
902 | PipeToSendStream::new(bytes::Bytes::from(data), stream).await?; | |
903 | ||
904 | response | |
905 | .map_err(Error::from) | |
906 | .and_then(Self::h2api_response) | |
2a1e6d7d | 907 | .await |
9af37c8f | 908 | } |
adec8ea2 | 909 | |
2a1e6d7d | 910 | async fn request( |
9af37c8f | 911 | &self, |
b57cb264 | 912 | request: Request<()>, |
2a1e6d7d | 913 | ) -> Result<Value, Error> { |
b57cb264 | 914 | |
9af37c8f | 915 | self.send_request(request, None) |
82ab7230 DM |
916 | .and_then(move |response| { |
917 | response | |
918 | .map_err(Error::from) | |
919 | .and_then(Self::h2api_response) | |
920 | }) | |
2a1e6d7d | 921 | .await |
82ab7230 DM |
922 | } |
923 | ||
cf9271e2 | 924 | pub fn send_request( |
9af37c8f | 925 | &self, |
82ab7230 DM |
926 | request: Request<()>, |
927 | data: Option<bytes::Bytes>, | |
a6782ca1 | 928 | ) -> impl Future<Output = Result<h2::client::ResponseFuture, Error>> { |
82ab7230 | 929 | |
9af37c8f | 930 | self.h2.clone() |
10130cf4 DM |
931 | .ready() |
932 | .map_err(Error::from) | |
2a05048b | 933 | .and_then(move |mut send_request| async move { |
82ab7230 DM |
934 | if let Some(data) = data { |
935 | let (response, stream) = send_request.send_request(request, false).unwrap(); | |
2a05048b DM |
936 | PipeToSendStream::new(data, stream).await?; |
937 | Ok(response) | |
82ab7230 DM |
938 | } else { |
939 | let (response, _stream) = send_request.send_request(request, true).unwrap(); | |
2a05048b | 940 | Ok(response) |
82ab7230 | 941 | } |
b57cb264 DM |
942 | }) |
943 | } | |
944 | ||
f16aea68 | 945 | pub async fn h2api_response( |
a6782ca1 | 946 | response: Response<h2::RecvStream>, |
9edd3bf1 | 947 | ) -> Result<Value, Error> { |
b57cb264 DM |
948 | let status = response.status(); |
949 | ||
950 | let (_head, mut body) = response.into_parts(); | |
951 | ||
9edd3bf1 | 952 | let mut data = Vec::new(); |
db0cb9ce WB |
953 | while let Some(chunk) = body.data().await { |
954 | let chunk = chunk?; | |
955 | // Whenever data is received, the caller is responsible for | |
956 | // releasing capacity back to the server once it has freed | |
957 | // the data from memory. | |
9edd3bf1 | 958 | // Let the server send more data. |
db0cb9ce | 959 | body.flow_control().release_capacity(chunk.len())?; |
9edd3bf1 DM |
960 | data.extend(chunk); |
961 | } | |
962 | ||
963 | let text = String::from_utf8(data.to_vec()).unwrap(); | |
964 | if status.is_success() { | |
11377a47 DM |
965 | if text.is_empty() { |
966 | Ok(Value::Null) | |
967 | } else { | |
9edd3bf1 DM |
968 | let mut value: Value = serde_json::from_str(&text)?; |
969 | if let Some(map) = value.as_object_mut() { | |
970 | if let Some(data) = map.remove("data") { | |
971 | return Ok(data); | |
b57cb264 | 972 | } |
b57cb264 | 973 | } |
9edd3bf1 | 974 | bail!("got result without data property"); |
9edd3bf1 DM |
975 | } |
976 | } else { | |
91f5594c | 977 | Err(Error::from(HttpError::new(status, text))) |
9edd3bf1 | 978 | } |
b57cb264 DM |
979 | } |
980 | ||
eb2bdd1b | 981 | // Note: We always encode parameters with the url |
792a70b9 DM |
982 | pub fn request_builder( |
983 | server: &str, | |
984 | method: &str, | |
985 | path: &str, | |
986 | param: Option<Value>, | |
987 | content_type: Option<&str>, | |
988 | ) -> Result<Request<()>, Error> { | |
b57cb264 | 989 | let path = path.trim_matches('/'); |
b57cb264 | 990 | |
792a70b9 | 991 | let content_type = content_type.unwrap_or("application/x-www-form-urlencoded"); |
a2daecc2 DM |
992 | let query = match param { |
993 | Some(param) => { | |
9eb78407 | 994 | let query = json_object_to_query(param)?; |
a2daecc2 DM |
995 | // We detected problem with hyper around 6000 characters - so we try to keep on the safe side |
996 | if query.len() > 4096 { | |
997 | bail!("h2 query data too large ({} bytes) - please encode data inside body", query.len()); | |
998 | } | |
999 | Some(query) | |
1000 | } | |
1001 | None => None, | |
1002 | }; | |
792a70b9 | 1003 | |
a2daecc2 DM |
1004 | let url = build_uri(server, 8007, path, query)?; |
1005 | let request = Request::builder() | |
1006 | .method(method) | |
1007 | .uri(url) | |
1008 | .header("User-Agent", "proxmox-backup-client/1.0") | |
1009 | .header(hyper::header::CONTENT_TYPE, content_type) | |
1010 | .body(())?; | |
1011 | Ok(request) | |
b57cb264 DM |
1012 | } |
1013 | } |