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