]> git.proxmox.com Git - proxmox-backup.git/blobdiff - src/client/http_client.rs
client: raise HTTP_TIMEOUT to 120s
[proxmox-backup.git] / src / client / http_client.rs
index a9b9c06c1433b946980fbd253ea4892aa3c0a08d..76ab039158510829626b2508c9f35dae6e5dbc6f 100644 (file)
@@ -29,6 +29,10 @@ use crate::tools::{
     http::HttpsConnector,
 };
 
+/// Timeout used for several HTTP operations that are expected to finish quickly but may block in
+/// certain error conditions. Keep it generous, to avoid false-positive under high load.
+const HTTP_TIMEOUT: Duration = Duration::from_secs(2 * 60);
+
 #[derive(Clone)]
 pub struct AuthInfo {
     pub auth_id: Authid,
@@ -48,15 +52,23 @@ pub struct HttpClientOptions {
 
 impl HttpClientOptions {
 
-    pub fn new() -> Self {
+    pub fn new_interactive(password: Option<String>, fingerprint: Option<String>) -> Self {
         Self {
-            prefix: None,
-            password: None,
-            fingerprint: None,
-            interactive: false,
-            ticket_cache: false,
-            fingerprint_cache: false,
-            verify_cert: true,
+            password,
+            fingerprint,
+            fingerprint_cache: true,
+            ticket_cache: true,
+            interactive: true,
+            prefix: Some("proxmox-backup".to_string()),
+            ..Self::default()
+        }
+    }
+
+    pub fn new_non_interactive(password: String, fingerprint: Option<String>) -> Self {
+        Self {
+            password: Some(password),
+            fingerprint,
+            ..Self::default()
         }
     }
 
@@ -96,6 +108,20 @@ impl HttpClientOptions {
     }
 }
 
+impl Default for HttpClientOptions {
+    fn default() -> Self {
+        Self {
+            prefix: None,
+            password: None,
+            fingerprint: None,
+            interactive: false,
+            ticket_cache: false,
+            fingerprint_cache: false,
+            verify_cert: true,
+        }
+    }
+}
+
 /// HTTP(S) API client
 pub struct HttpClient {
     client: Client<HttpsConnector>,
@@ -152,7 +178,7 @@ fn store_fingerprint(prefix: &str, server: &str, fingerprint: &str) -> Result<()
     raw.split('\n').for_each(|line| {
         let items: Vec<String> = line.split_whitespace().map(String::from).collect();
         if items.len() == 2 {
-            if &items[0] == server {
+            if items[0] == server {
                 // found, add later with new fingerprint
             } else {
                 result.push_str(line);
@@ -182,7 +208,7 @@ fn load_fingerprint(prefix: &str, server: &str) -> Option<String> {
 
     for line in raw.split('\n') {
         let items: Vec<String> = line.split_whitespace().map(String::from).collect();
-        if items.len() == 2 && &items[0] == server {
+        if items.len() == 2 && items[0] == server {
             return Some(items[1].clone());
         }
     }
@@ -340,14 +366,14 @@ impl HttpClient {
 
         let renewal_future = async move {
             loop {
-                tokio::time::delay_for(Duration::new(60*15,  0)).await; // 15 minutes
+                tokio::time::sleep(Duration::new(60*15,  0)).await; // 15 minutes
                 let (auth_id, ticket) = {
                     let authinfo = auth2.read().unwrap().clone();
                     (authinfo.auth_id, authinfo.ticket)
                 };
                 match Self::credentials(client2.clone(), server2.clone(), port, auth_id.user().clone(), ticket).await {
                     Ok(auth) => {
-                        if use_ticket_cache & &prefix2.is_some() {
+                        if use_ticket_cache &prefix2.is_some() {
                             let _ = store_ticket_info(prefix2.as_ref().unwrap(), &server2, &auth.auth_id.to_string(), &auth.ticket, &auth.token);
                         }
                         *auth2.write().unwrap() = auth;
@@ -367,14 +393,14 @@ impl HttpClient {
             server.to_owned(),
             port,
             auth_id.user().clone(),
-            password.to_owned(),
+            password,
         ).map_ok({
             let server = server.to_string();
             let prefix = options.prefix.clone();
             let authinfo = auth.clone();
 
             move |auth| {
-                if use_ticket_cache & &prefix.is_some() {
+                if use_ticket_cache &prefix.is_some() {
                     let _ = store_ticket_info(prefix.as_ref().unwrap(), &server, &auth.auth_id.to_string(), &auth.ticket, &auth.token);
                 }
                 *authinfo.write().unwrap() = auth;
@@ -557,7 +583,12 @@ impl HttpClient {
         let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
         req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
 
-        let resp = client.request(req).await?;
+        let resp = tokio::time::timeout(
+            HTTP_TIMEOUT,
+            client.request(req)
+        )
+            .await
+            .map_err(|_| format_err!("http download request timed out"))??;
         let status = resp.status();
         if !status.is_success() {
             HttpClient::api_response(resp)
@@ -624,7 +655,12 @@ impl HttpClient {
 
         req.headers_mut().insert("UPGRADE", HeaderValue::from_str(&protocol_name).unwrap());
 
-        let resp = client.request(req).await?;
+        let resp = tokio::time::timeout(
+            HTTP_TIMEOUT,
+            client.request(req)
+        )
+            .await
+            .map_err(|_| format_err!("http upgrade request timed out"))??;
         let status = resp.status();
 
         if status != http::StatusCode::SWITCHING_PROTOCOLS {
@@ -632,10 +668,7 @@ impl HttpClient {
             bail!("unknown error");
         }
 
-        let upgraded = resp
-            .into_body()
-            .on_upgrade()
-            .await?;
+        let upgraded = hyper::upgrade::on(resp).await?;
 
         let max_window_size = (1 << 31) - 2;
 
@@ -704,10 +737,14 @@ impl HttpClient {
         req: Request<Body>
     ) -> Result<Value, Error> {
 
-        client.request(req)
-            .map_err(Error::from)
-            .and_then(Self::api_response)
-            .await
+        Self::api_response(
+            tokio::time::timeout(
+                HTTP_TIMEOUT,
+                client.request(req)
+            )
+                .await
+                .map_err(|_| format_err!("http request timed out"))??
+        ).await
     }
 
     // Read-only access to server property