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