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