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