]> 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 e524dcfa03748a51d9d6340be23136c945ae4de6..76ab039158510829626b2508c9f35dae6e5dbc6f 100644 (file)
-use std::collections::HashSet;
 use std::io::Write;
-use std::sync::atomic::{AtomicUsize, Ordering};
-use std::sync::{Arc, Mutex};
+use std::sync::{Arc, Mutex, RwLock};
+use std::time::Duration;
 
-use chrono::{DateTime, Utc};
-use failure::*;
+use anyhow::{bail, format_err, Error};
 use futures::*;
-use futures::stream::Stream;
 use http::Uri;
 use http::header::HeaderValue;
 use http::{Request, Response};
 use hyper::Body;
 use hyper::client::{Client, HttpConnector};
-use openssl::ssl::{SslConnector, SslMethod};
+use openssl::{ssl::{SslConnector, SslMethod}, x509::X509StoreContextRef};
 use serde_json::{json, Value};
-use tokio::io::AsyncReadExt;
-use tokio::sync::{mpsc, oneshot};
-use url::percent_encoding::{percent_encode,  DEFAULT_ENCODE_SET};
+use percent_encoding::percent_encode;
 use xdg::BaseDirectories;
 
-use proxmox::tools::{
-    digest_to_hex,
-    fs::{file_get_json, file_set_contents},
+use proxmox::{
+    api::error::HttpError,
+    sys::linux::tty,
+    tools::fs::{file_get_json, replace_file, CreateOptions},
 };
 
-use super::merge_known_chunks::{MergedChunkInfo, MergeKnownChunks};
 use super::pipe_to_stream::PipeToSendStream;
-use crate::backup::*;
-use crate::tools::async_io::EitherStream;
-use crate::tools::futures::{cancellable, Canceller};
-use crate::tools::{self, tty, BroadcastFuture};
+use crate::api2::types::{Authid, Userid};
+use crate::tools::{
+    self,
+    BroadcastFuture,
+    DEFAULT_ENCODE_SET,
+    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 {
-    username: String,
-    ticket: String,
-    token: String,
+    pub auth_id: Authid,
+    pub ticket: String,
+    pub token: String,
+}
+
+pub struct HttpClientOptions {
+    prefix: Option<String>,
+    password: Option<String>,
+    fingerprint: Option<String>,
+    interactive: bool,
+    ticket_cache: bool,
+    fingerprint_cache: bool,
+    verify_cert: bool,
+}
+
+impl HttpClientOptions {
+
+    pub fn new_interactive(password: Option<String>, fingerprint: Option<String>) -> Self {
+        Self {
+            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()
+        }
+    }
+
+    pub fn prefix(mut self, prefix: Option<String>) -> Self {
+        self.prefix = prefix;
+        self
+    }
+
+    pub fn password(mut self, password: Option<String>) -> Self {
+        self.password = password;
+        self
+    }
+
+    pub fn fingerprint(mut self, fingerprint: Option<String>) -> Self {
+        self.fingerprint = fingerprint;
+        self
+    }
+
+    pub fn interactive(mut self, interactive: bool) -> Self {
+        self.interactive = interactive;
+        self
+    }
+
+    pub fn ticket_cache(mut self, ticket_cache: bool) -> Self {
+        self.ticket_cache = ticket_cache;
+        self
+    }
+
+    pub fn fingerprint_cache(mut self, fingerprint_cache: bool) -> Self {
+        self.fingerprint_cache = fingerprint_cache;
+        self
+    }
+
+    pub fn verify_cert(mut self, verify_cert: bool) -> Self {
+        self.verify_cert = verify_cert;
+        self
+    }
+}
+
+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>,
     server: String,
-    auth: BroadcastFuture<AuthInfo>,
+    port: u16,
+    fingerprint: Arc<Mutex<Option<String>>>,
+    first_auth: Option<BroadcastFuture<()>>,
+    auth: Arc<RwLock<AuthInfo>>,
+    ticket_abort: futures::future::AbortHandle,
+    _options: HttpClientOptions,
 }
 
 /// Delete stored ticket data (logout)
-pub fn delete_ticket_info(server: &str, username: &str) -> Result<(), Error> {
+pub fn delete_ticket_info(prefix: &str, server: &str, username: &Userid) -> Result<(), Error> {
 
-    let base = BaseDirectories::with_prefix("proxmox-backup")?;
+    let base = BaseDirectories::with_prefix(prefix)?;
 
     // usually /run/user/<uid>/...
     let path = base.place_runtime_file("tickets")?;
@@ -58,17 +147,78 @@ pub fn delete_ticket_info(server: &str, username: &str) -> Result<(), Error> {
     let mut data = file_get_json(&path, Some(json!({})))?;
 
     if let Some(map) = data[server].as_object_mut() {
-        map.remove(username);
+        map.remove(username.as_str());
     }
 
-    file_set_contents(path, data.to_string().as_bytes(), Some(mode))?;
+    replace_file(path, data.to_string().as_bytes(), CreateOptions::new().perm(mode))?;
 
     Ok(())
 }
 
-fn store_ticket_info(server: &str, username: &str, ticket: &str, token: &str) -> Result<(), Error> {
+fn store_fingerprint(prefix: &str, server: &str, fingerprint: &str) -> Result<(), Error> {
+
+    let base = BaseDirectories::with_prefix(prefix)?;
+
+    // usually ~/.config/<prefix>/fingerprints
+    let path = base.place_config_file("fingerprints")?;
+
+    let raw = match std::fs::read_to_string(&path) {
+        Ok(v) => v,
+        Err(err) => {
+            if err.kind() == std::io::ErrorKind::NotFound {
+                String::new()
+            } else {
+                bail!("unable to read fingerprints from {:?} - {}", path, err);
+            }
+        }
+    };
+
+    let mut result = String::new();
+
+    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 {
+                // found, add later with new fingerprint
+            } else {
+                result.push_str(line);
+                result.push('\n');
+            }
+        }
+    });
+
+    result.push_str(server);
+    result.push(' ');
+    result.push_str(fingerprint);
+    result.push('\n');
+
+    replace_file(path, result.as_bytes(), CreateOptions::new())?;
+
+    Ok(())
+}
+
+fn load_fingerprint(prefix: &str, server: &str) -> Option<String> {
+
+    let base = BaseDirectories::with_prefix(prefix).ok()?;
+
+    // usually ~/.config/<prefix>/fingerprints
+    let path = base.place_config_file("fingerprints").ok()?;
+
+    let raw = std::fs::read_to_string(&path).ok()?;
+
+    for line in raw.split('\n') {
+        let items: Vec<String> = line.split_whitespace().map(String::from).collect();
+        if items.len() == 2 && items[0] == server {
+            return Some(items[1].clone());
+        }
+    }
+
+    None
+}
+
+fn store_ticket_info(prefix: &str, server: &str, username: &str, ticket: &str, token: &str) -> Result<(), Error> {
 
-    let base = BaseDirectories::with_prefix("proxmox-backup")?;
+    let base = BaseDirectories::with_prefix(prefix)?;
 
     // usually /run/user/<uid>/...
     let path = base.place_runtime_file("tickets")?;
@@ -77,7 +227,7 @@ fn store_ticket_info(server: &str, username: &str, ticket: &str, token: &str) ->
 
     let mut data = file_get_json(&path, Some(json!({})))?;
 
-    let now = Utc::now().timestamp();
+    let now = proxmox::tools::time::epoch_i64();
 
     data[server][username] = json!({ "timestamp": now, "ticket": ticket, "token": token});
 
@@ -87,30 +237,30 @@ fn store_ticket_info(server: &str, username: &str, ticket: &str, token: &str) ->
 
     let empty = serde_json::map::Map::new();
     for (server, info) in data.as_object().unwrap_or(&empty) {
-        for (_user, uinfo) in info.as_object().unwrap_or(&empty) {
+        for (user, uinfo) in info.as_object().unwrap_or(&empty) {
             if let Some(timestamp) = uinfo["timestamp"].as_i64() {
                 let age = now - timestamp;
                 if age < ticket_lifetime {
-                    new_data[server][username] = uinfo.clone();
+                    new_data[server][user] = uinfo.clone();
                 }
             }
         }
     }
 
-    file_set_contents(path, new_data.to_string().as_bytes(), Some(mode))?;
+    replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new().perm(mode))?;
 
     Ok(())
 }
 
-fn load_ticket_info(server: &str, username: &str) -> Option<(String, String)> {
-    let base = BaseDirectories::with_prefix("proxmox-backup").ok()?;
+fn load_ticket_info(prefix: &str, server: &str, userid: &Userid) -> Option<(String, String)> {
+    let base = BaseDirectories::with_prefix(prefix).ok()?;
 
     // usually /run/user/<uid>/...
     let path = base.place_runtime_file("tickets").ok()?;
     let data = file_get_json(&path, None).ok()?;
-    let now = Utc::now().timestamp();
+    let now = proxmox::tools::time::epoch_i64();
     let ticket_lifetime = tools::ticket::TICKET_LIFETIME - 60;
-    let uinfo = data[server][username].as_object()?;
+    let uinfo = data[server][userid.as_str()].as_object()?;
     let timestamp = uinfo["timestamp"].as_i64()?;
     let age = now - timestamp;
 
@@ -124,70 +274,246 @@ fn load_ticket_info(server: &str, username: &str) -> Option<(String, String)> {
 }
 
 impl HttpClient {
+    pub fn new(
+        server: &str,
+        port: u16,
+        auth_id: &Authid,
+        mut options: HttpClientOptions,
+    ) -> Result<Self, Error> {
+
+        let verified_fingerprint = Arc::new(Mutex::new(None));
+
+        let mut fingerprint = options.fingerprint.take();
+
+        if fingerprint.is_some() {
+            // do not store fingerprints passed via options in cache
+            options.fingerprint_cache = false;
+        } else if options.fingerprint_cache && options.prefix.is_some() {
+            fingerprint = load_fingerprint(options.prefix.as_ref().unwrap(), server);
+        }
+
+        let mut ssl_connector_builder = SslConnector::builder(SslMethod::tls()).unwrap();
+
+        if options.verify_cert {
+            let server = server.to_string();
+            let verified_fingerprint = verified_fingerprint.clone();
+            let interactive = options.interactive;
+            let fingerprint_cache = options.fingerprint_cache;
+            let prefix = options.prefix.clone();
+            ssl_connector_builder.set_verify_callback(openssl::ssl::SslVerifyMode::PEER, move |valid, ctx| {
+                let (valid, fingerprint) = Self::verify_callback(valid, ctx, fingerprint.clone(), interactive);
+                if valid {
+                    if let Some(fingerprint) = fingerprint {
+                        if fingerprint_cache && prefix.is_some() {
+                            if let Err(err) = store_fingerprint(
+                                prefix.as_ref().unwrap(), &server, &fingerprint) {
+                                eprintln!("{}", err);
+                            }
+                        }
+                        *verified_fingerprint.lock().unwrap() = Some(fingerprint);
+                    }
+                }
+                valid
+            });
+        } else {
+            ssl_connector_builder.set_verify(openssl::ssl::SslVerifyMode::NONE);
+        }
+
+        let mut httpc = HttpConnector::new();
+        httpc.set_nodelay(true); // important for h2 download performance!
+        httpc.enforce_http(false); // we want https...
+
+        httpc.set_connect_timeout(Some(std::time::Duration::new(10, 0)));
+        let https = HttpsConnector::with_connector(httpc, ssl_connector_builder.build());
+
+        let client = Client::builder()
+        //.http2_initial_stream_window_size( (1 << 31) - 2)
+        //.http2_initial_connection_window_size( (1 << 31) - 2)
+            .build::<_, Body>(https);
 
-    pub fn new(server: &str, username: &str, password: Option<String>) -> Result<Self, Error> {
-        let client = Self::build_client();
+        let password = options.password.take();
+        let use_ticket_cache = options.ticket_cache && options.prefix.is_some();
 
         let password = if let Some(password) = password {
             password
-        } else if let Some((ticket, _token)) = load_ticket_info(server, username) {
-            ticket
         } else {
-            Self::get_password(&username)?
+            let userid = if auth_id.is_token() {
+                bail!("API token secret must be provided!");
+            } else {
+                auth_id.user()
+            };
+            let mut ticket_info = None;
+            if use_ticket_cache {
+                ticket_info = load_ticket_info(options.prefix.as_ref().unwrap(), server, userid);
+            }
+            if let Some((ticket, _token)) = ticket_info {
+                ticket
+            } else {
+                Self::get_password(userid, options.interactive)?
+            }
         };
 
-        let login_future = Self::credentials(client.clone(), server.to_owned(), username.to_owned(), password);
+        let auth = Arc::new(RwLock::new(AuthInfo {
+            auth_id: auth_id.clone(),
+            ticket: password.clone(),
+            token: "".to_string(),
+        }));
+
+        let server2 = server.to_string();
+        let client2 = client.clone();
+        let auth2 = auth.clone();
+        let prefix2 = options.prefix.clone();
+
+        let renewal_future = async move {
+            loop {
+                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() {
+                            let _ = store_ticket_info(prefix2.as_ref().unwrap(), &server2, &auth.auth_id.to_string(), &auth.ticket, &auth.token);
+                        }
+                        *auth2.write().unwrap() = auth;
+                    },
+                    Err(err) => {
+                        eprintln!("re-authentication failed: {}", err);
+                        return;
+                    }
+                }
+            }
+        };
+
+        let (renewal_future, ticket_abort) = futures::future::abortable(renewal_future);
+
+        let login_future = Self::credentials(
+            client.clone(),
+            server.to_owned(),
+            port,
+            auth_id.user().clone(),
+            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() {
+                    let _ = store_ticket_info(prefix.as_ref().unwrap(), &server, &auth.auth_id.to_string(), &auth.ticket, &auth.token);
+                }
+                *authinfo.write().unwrap() = auth;
+                tokio::spawn(renewal_future);
+            }
+        });
+
+        let first_auth = if auth_id.is_token() {
+            // TODO check access here?
+            None
+        } else {
+            Some(BroadcastFuture::new(Box::new(login_future)))
+        };
 
         Ok(Self {
             client,
             server: String::from(server),
-            auth: BroadcastFuture::new(Box::new(login_future)),
+            port,
+            fingerprint: verified_fingerprint,
+            auth,
+            ticket_abort,
+            first_auth,
+            _options: options,
         })
     }
 
     /// Login
     ///
-    /// Login is done on demand, so this is onyl required if you need
+    /// Login is done on demand, so this is only required if you need
     /// access to authentication data in 'AuthInfo'.
+    ///
+    /// Note: tickets a periodially re-newed, so one can use this
+    /// to query changed ticket.
     pub async fn login(&self) -> Result<AuthInfo, Error> {
-        self.auth.listen().await
+        if let Some(future) = &self.first_auth {
+            future.listen().await?;
+        }
+
+        let authinfo = self.auth.read().unwrap();
+        Ok(authinfo.clone())
     }
 
-    fn get_password(_username: &str) -> Result<String, Error> {
-        use std::env::VarError::*;
-        match std::env::var("PBS_PASSWORD") {
-            Ok(p) => return Ok(p),
-            Err(NotUnicode(_)) => bail!("PBS_PASSWORD contains bad characters"),
-            Err(NotPresent) => {
-                // Try another method
-            }
-        }
+    /// Returns the optional fingerprint passed to the new() constructor.
+    pub fn fingerprint(&self) -> Option<String> {
+        (*self.fingerprint.lock().unwrap()).clone()
+    }
 
+    fn get_password(username: &Userid, interactive: bool) -> Result<String, Error> {
         // If we're on a TTY, query the user for a password
-        if tty::stdin_isatty() {
-            return Ok(String::from_utf8(tty::read_password("Password: ")?)?);
+        if interactive && tty::stdin_isatty() {
+            let msg = format!("Password for \"{}\": ", username);
+            return Ok(String::from_utf8(tty::read_password(&msg)?)?);
         }
 
         bail!("no password input mechanism available");
     }
 
-    fn build_client() -> Client<HttpsConnector> {
+    fn verify_callback(
+        valid: bool, ctx:
+        &mut X509StoreContextRef,
+        expected_fingerprint: Option<String>,
+        interactive: bool,
+    ) -> (bool, Option<String>) {
+        if valid { return (true, None); }
 
-        let mut ssl_connector_builder = SslConnector::builder(SslMethod::tls()).unwrap();
+        let cert = match ctx.current_cert() {
+            Some(cert) => cert,
+            None => return (false, None),
+        };
 
-        ssl_connector_builder.set_verify(openssl::ssl::SslVerifyMode::NONE); // fixme!
+        let depth = ctx.error_depth();
+        if depth != 0 { return (false, None); }
 
-        let mut httpc = hyper::client::HttpConnector::new();
-        httpc.set_nodelay(true); // important for h2 download performance!
-        httpc.set_recv_buffer_size(Some(1024*1024)); //important for h2 download performance!
-        httpc.enforce_http(false); // we want https...
+        let fp = match cert.digest(openssl::hash::MessageDigest::sha256()) {
+            Ok(fp) => fp,
+            Err(_) => return (false, None), // should not happen
+        };
+        let fp_string = proxmox::tools::digest_to_hex(&fp);
+        let fp_string = fp_string.as_bytes().chunks(2).map(|v| std::str::from_utf8(v).unwrap())
+            .collect::<Vec<&str>>().join(":");
 
-        let https = HttpsConnector::with_connector(httpc, ssl_connector_builder.build());
+        if let Some(expected_fingerprint) = expected_fingerprint {
+            if expected_fingerprint.to_lowercase() == fp_string {
+                return (true, Some(fp_string));
+            } else {
+                return (false, None);
+            }
+        }
 
-        Client::builder()
-        //.http2_initial_stream_window_size( (1 << 31) - 2)
-        //.http2_initial_connection_window_size( (1 << 31) - 2)
-            .build::<_, Body>(https)
+        // If we're on a TTY, query the user
+        if interactive && tty::stdin_isatty() {
+            println!("fingerprint: {}", fp_string);
+            loop {
+                print!("Are you sure you want to continue connecting? (y/n): ");
+                let _ = std::io::stdout().flush();
+                use std::io::{BufRead, BufReader};
+                let mut line = String::new();
+                match BufReader::new(std::io::stdin()).read_line(&mut line) {
+                    Ok(_) => {
+                        let trimmed = line.trim();
+                        if trimmed == "y" || trimmed == "Y" {
+                            return (true, Some(fp_string));
+                        } else if trimmed == "n" || trimmed == "N" {
+                            return (false, None);
+                        } else {
+                            continue;
+                        }
+                    }
+                    Err(_) => return (false, None),
+                }
+            }
+        }
+        (false, None)
     }
 
     pub async fn request(&self, mut req: Request<Body>) -> Result<Value, Error> {
@@ -195,10 +521,14 @@ impl HttpClient {
         let client = self.client.clone();
 
         let auth =  self.login().await?;
-
-        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());
-        req.headers_mut().insert("CSRFPreventionToken", HeaderValue::from_str(&auth.token).unwrap());
+        if auth.auth_id.is_token() {
+            let enc_api_token = format!("PBSAPIToken {}:{}", auth.auth_id, percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
+            req.headers_mut().insert("Authorization", HeaderValue::from_str(&enc_api_token).unwrap());
+        } else {
+            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());
+            req.headers_mut().insert("CSRFPreventionToken", HeaderValue::from_str(&auth.token).unwrap());
+        }
 
         Self::api_request(client, req).await
     }
@@ -208,7 +538,7 @@ impl HttpClient {
         path: &str,
         data: Option<Value>,
     ) -> Result<Value, Error> {
-        let req = Self::request_builder(&self.server, "GET", path, data).unwrap();
+        let req = Self::request_builder(&self.server, self.port, "GET", path, data)?;
         self.request(req).await
     }
 
@@ -217,7 +547,7 @@ impl HttpClient {
         path: &str,
         data: Option<Value>,
     ) -> Result<Value, Error> {
-        let req = Self::request_builder(&self.server, "DELETE", path, data).unwrap();
+        let req = Self::request_builder(&self.server, self.port, "DELETE", path, data)?;
         self.request(req).await
     }
 
@@ -226,7 +556,16 @@ impl HttpClient {
         path: &str,
         data: Option<Value>,
     ) -> Result<Value, Error> {
-        let req = Self::request_builder(&self.server, "POST", path, data).unwrap();
+        let req = Self::request_builder(&self.server, self.port, "POST", path, data)?;
+        self.request(req).await
+    }
+
+    pub async fn put(
+        &mut self,
+        path: &str,
+        data: Option<Value>,
+    ) -> Result<Value, Error> {
+        let req = Self::request_builder(&self.server, self.port, "PUT", path, data)?;
         self.request(req).await
     }
 
@@ -234,8 +573,8 @@ impl HttpClient {
         &mut self,
         path: &str,
         output: &mut (dyn Write + Send),
-    ) ->  Result<(), Error> {
-        let mut req = Self::request_builder(&self.server, "GET", path, None).unwrap();
+    ) -> Result<(), Error> {
+        let mut req = Self::request_builder(&self.server, self.port, "GET", path, None)?;
 
         let client = self.client.clone();
 
@@ -244,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)
@@ -271,7 +615,7 @@ impl HttpClient {
     ) -> Result<Value, Error> {
 
         let path = path.trim_matches('/');
-        let mut url = format!("https://{}:8007/{}", &self.server, path);
+        let mut url = format!("https://{}:{}/{}", &self.server, self.port, path);
 
         if let Some(data) = data {
             let query = tools::json_object_to_query(data).unwrap();
@@ -291,80 +635,40 @@ impl HttpClient {
         self.request(req).await
     }
 
-    pub async fn start_backup(
-        &self,
-        datastore: &str,
-        backup_type: &str,
-        backup_id: &str,
-        backup_time: DateTime<Utc>,
-        debug: bool,
-    ) -> Result<Arc<BackupClient>, Error> {
-
-        let param = json!({
-            "backup-type": backup_type,
-            "backup-id": backup_id,
-            "backup-time": backup_time.timestamp(),
-            "store": datastore,
-            "debug": debug
-        });
-
-        let req = Self::request_builder(&self.server, "GET", "/api2/json/backup", Some(param)).unwrap();
-
-        let (h2, canceller) = self.start_h2_connection(req, String::from(PROXMOX_BACKUP_PROTOCOL_ID_V1!())).await?;
-
-        Ok(BackupClient::new(h2, canceller))
-    }
-
-    pub async fn start_backup_reader(
-        &self,
-        datastore: &str,
-        backup_type: &str,
-        backup_id: &str,
-        backup_time: DateTime<Utc>,
-        debug: bool,
-    ) -> Result<Arc<BackupReader>, Error> {
-
-        let param = json!({
-            "backup-type": backup_type,
-            "backup-id": backup_id,
-            "backup-time": backup_time.timestamp(),
-            "store": datastore,
-            "debug": debug,
-        });
-        let req = Self::request_builder(&self.server, "GET", "/api2/json/reader", Some(param)).unwrap();
-
-        let (h2, canceller) = self.start_h2_connection(req, String::from(PROXMOX_BACKUP_READER_PROTOCOL_ID_V1!())).await?;
-
-        Ok(BackupReader::new(h2, canceller))
-    }
-
     pub async fn start_h2_connection(
         &self,
         mut req: Request<Body>,
         protocol_name: String,
-    ) -> Result<(H2Client, Canceller), Error> {
+    ) -> Result<(H2Client, futures::future::AbortHandle), Error> {
 
-        let auth = self.login().await?;
         let client = self.client.clone();
+        let auth =  self.login().await?;
+
+        if auth.auth_id.is_token() {
+            let enc_api_token = format!("PBSAPIToken {}:{}", auth.auth_id, percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
+            req.headers_mut().insert("Authorization", HeaderValue::from_str(&enc_api_token).unwrap());
+        } else {
+            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());
+            req.headers_mut().insert("CSRFPreventionToken", HeaderValue::from_str(&auth.token).unwrap());
+        }
 
-        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());
         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 {
-            Self::api_response(resp)
-                .map(|_| Err(format_err!("unknown error")))
-                .await?;
-            unreachable!();
+            Self::api_response(resp).await?;
+            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;
 
@@ -376,59 +680,55 @@ impl HttpClient {
             .await?;
 
         let connection = connection
-            .map_err(|_| panic!("HTTP/2.0 connection failed"));
+            .map_err(|_| eprintln!("HTTP/2.0 connection failed"));
 
-        let (connection, canceller) = cancellable(connection)?;
+        let (connection, abort) = futures::future::abortable(connection);
         // A cancellable future returns an Option which is None when cancelled and
         // Some when it finished instead, since we don't care about the return type we
         // need to map it away:
         let connection = connection.map(|_| ());
 
         // Spawn a new task to drive the connection state
-        hyper::rt::spawn(connection);
+        tokio::spawn(connection);
 
         // Wait until the `SendRequest` handle has available capacity.
         let c = h2.ready().await?;
-        Ok((H2Client::new(c), canceller))
+        Ok((H2Client::new(c), abort))
     }
 
     async fn credentials(
         client: Client<HttpsConnector>,
         server: String,
-        username: String,
+        port: u16,
+        username: Userid,
         password: String,
     ) -> Result<AuthInfo, Error> {
         let data = json!({ "username": username, "password": password });
-        let req = Self::request_builder(&server, "POST", "/api2/json/access/ticket", Some(data)).unwrap();
+        let req = Self::request_builder(&server, port, "POST", "/api2/json/access/ticket", Some(data))?;
         let cred = Self::api_request(client, req).await?;
         let auth = AuthInfo {
-            username: cred["data"]["username"].as_str().unwrap().to_owned(),
+            auth_id: cred["data"]["username"].as_str().unwrap().parse()?,
             ticket: cred["data"]["ticket"].as_str().unwrap().to_owned(),
             token: cred["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
         };
 
-        let _ = store_ticket_info(&server, &auth.username, &auth.ticket, &auth.token);
-
         Ok(auth)
     }
 
     async fn api_response(response: Response<Body>) -> Result<Value, Error> {
         let status = response.status();
-        let data = response
-            .into_body()
-            .try_concat()
-            .await?;
+        let data = hyper::body::to_bytes(response.into_body()).await?;
 
         let text = String::from_utf8(data.to_vec()).unwrap();
         if status.is_success() {
-            if text.len() > 0 {
+            if text.is_empty() {
+                Ok(Value::Null)
+            } else {
                 let value: Value = serde_json::from_str(&text)?;
                 Ok(value)
-            } else {
-                Ok(Value::Null)
             }
         } else {
-            bail!("HTTP Error {}: {}", status, text);
+            Err(Error::from(HttpError::new(status, text)))
         }
     }
 
@@ -437,15 +737,28 @@ 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
+    pub fn server(&self) -> &str {
+        &self.server
     }
 
-    pub fn request_builder(server: &str, method: &str, path: &str, data: Option<Value>) -> Result<Request<Body>, Error> {
+    pub fn port(&self) -> u16 {
+        self.port
+    }
+
+    pub fn request_builder(server: &str, port: u16, method: &str, path: &str, data: Option<Value>) -> Result<Request<Body>, Error> {
         let path = path.trim_matches('/');
-        let url: Uri = format!("https://{}:8007/{}", server, path).parse()?;
+        let url: Uri = format!("https://{}:{}/{}", server, port, path).parse()?;
 
         if let Some(data) = data {
             if method == "POST" {
@@ -458,7 +771,7 @@ impl HttpClient {
                 return Ok(request);
             } else {
                 let query = tools::json_object_to_query(data)?;
-                let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?;
+                let url: Uri = format!("https://{}:{}/{}?{}", server, port, path, query).parse()?;
                 let request = Request::builder()
                     .method(method)
                     .uri(url)
@@ -480,575 +793,12 @@ impl HttpClient {
     }
 }
 
-
-pub struct BackupReader {
-    h2: H2Client,
-    canceller: Canceller,
-}
-
-impl Drop for BackupReader {
-
+impl Drop for HttpClient {
     fn drop(&mut self) {
-        self.canceller.cancel();
+        self.ticket_abort.abort();
     }
 }
 
-impl BackupReader {
-
-    pub fn new(h2: H2Client, canceller: Canceller) -> Arc<Self> {
-        Arc::new(Self { h2, canceller })
-    }
-
-    pub async fn get(
-        &self,
-        path: &str,
-        param: Option<Value>,
-    ) -> Result<Value, Error> {
-        self.h2.get(path, param).await
-    }
-
-    pub async fn put(
-        &self,
-        path: &str,
-        param: Option<Value>,
-    ) -> Result<Value, Error> {
-        self.h2.put(path, param).await
-    }
-
-    pub async fn post(
-        &self,
-        path: &str,
-        param: Option<Value>,
-    ) -> Result<Value, Error> {
-        self.h2.post(path, param).await
-    }
-
-    pub async fn download<W: Write + Send>(
-        &self,
-        file_name: &str,
-        output: W,
-    ) -> Result<W, Error> {
-        let path = "download";
-        let param = json!({ "file-name": file_name });
-        self.h2.download(path, Some(param), output).await
-    }
-
-    pub async fn speedtest<W: Write + Send>(
-        &self,
-        output: W,
-    ) -> Result<W, Error> {
-        self.h2.download("speedtest", None, output).await
-    }
-
-    pub async fn download_chunk<W: Write + Send>(
-        &self,
-        digest: &[u8; 32],
-        output: W,
-    ) -> Result<W, Error> {
-        let path = "chunk";
-        let param = json!({ "digest": digest_to_hex(digest) });
-        self.h2.download(path, Some(param), output).await
-    }
-
-    pub fn force_close(self) {
-        self.canceller.cancel();
-    }
-}
-
-pub struct BackupClient {
-    h2: H2Client,
-    canceller: Canceller,
-}
-
-impl Drop for BackupClient {
-
-    fn drop(&mut self) {
-        self.canceller.cancel();
-    }
-}
-
-pub struct BackupStats {
-    pub size: u64,
-    pub csum: [u8; 32],
-}
-
-impl BackupClient {
-    pub fn new(h2: H2Client, canceller: Canceller) -> Arc<Self> {
-        Arc::new(Self { h2, canceller })
-    }
-
-    pub async fn get(
-        &self,
-        path: &str,
-        param: Option<Value>,
-    ) -> Result<Value, Error> {
-        self.h2.get(path, param).await
-    }
-
-    pub async fn put(
-        &self,
-        path: &str,
-        param: Option<Value>,
-    ) -> Result<Value, Error> {
-        self.h2.put(path, param).await
-    }
-
-    pub async fn post(
-        &self,
-        path: &str,
-        param: Option<Value>,
-    ) -> Result<Value, Error> {
-        self.h2.post(path, param).await
-    }
-
-    pub async fn upload(
-        &self,
-        path: &str,
-        param: Option<Value>,
-        data: Vec<u8>,
-    ) -> Result<Value, Error> {
-        self.h2.upload(path, param, data).await
-    }
-
-    pub async fn finish(self: Arc<Self>) -> Result<(), Error> {
-        let h2 = self.h2.clone();
-
-        h2.post("finish", None)
-            .map_ok(move |_| {
-                self.canceller.cancel();
-            })
-            .await
-    }
-
-    pub fn force_close(self) {
-        self.canceller.cancel();
-    }
-
-    pub async fn upload_blob<R: std::io::Read>(
-        &self,
-        mut reader: R,
-        file_name: &str,
-     ) -> Result<BackupStats, Error> {
-        let mut raw_data = Vec::new();
-        // fixme: avoid loading into memory
-        reader.read_to_end(&mut raw_data)?;
-
-        let csum = openssl::sha::sha256(&raw_data);
-        let param = json!({"encoded-size": raw_data.len(), "file-name": file_name });
-        let size = raw_data.len() as u64; // fixme: should be decoded size instead??
-        let _value = self.h2.upload("blob", Some(param), raw_data).await?;
-        Ok(BackupStats { size, csum })
-    }
-
-    pub async fn upload_blob_from_data(
-        &self,
-        data: Vec<u8>,
-        file_name: &str,
-        crypt_config: Option<Arc<CryptConfig>>,
-        compress: bool,
-        sign_only: bool,
-     ) -> Result<BackupStats, Error> {
-
-        let size = data.len() as u64;
-
-        let blob = if let Some(crypt_config) = crypt_config {
-            if sign_only {
-                DataBlob::create_signed(&data, crypt_config, compress)?
-            } else {
-                DataBlob::encode(&data, Some(crypt_config.clone()), compress)?
-            }
-        } else {
-            DataBlob::encode(&data, None, compress)?
-        };
-
-        let raw_data = blob.into_inner();
-
-        let csum = openssl::sha::sha256(&raw_data);
-        let param = json!({"encoded-size": raw_data.len(), "file-name": file_name });
-        let _value = self.h2.upload("blob", Some(param), raw_data).await?;
-        Ok(BackupStats { size, csum })
-    }
-
-    pub async fn upload_blob_from_file<P: AsRef<std::path::Path>>(
-        &self,
-        src_path: P,
-        file_name: &str,
-        crypt_config: Option<Arc<CryptConfig>>,
-        compress: bool,
-     ) -> Result<BackupStats, Error> {
-
-        let src_path = src_path.as_ref();
-
-        let mut file = tokio::fs::File::open(src_path)
-            .await
-            .map_err(|err| format_err!("unable to open file {:?} - {}", src_path, err))?;
-
-        let mut contents = Vec::new();
-
-        file.read_to_end(&mut contents)
-            .await
-            .map_err(|err| format_err!("unable to read file {:?} - {}", src_path, err))?;
-
-        let size: u64 = contents.len() as u64;
-        let blob = DataBlob::encode(&contents, crypt_config, compress)?;
-        let raw_data = blob.into_inner();
-        let csum = openssl::sha::sha256(&raw_data);
-        let param = json!({
-            "encoded-size": raw_data.len(),
-            "file-name": file_name,
-        });
-        self.h2.upload("blob", Some(param), raw_data).await?;
-        Ok(BackupStats { size, csum })
-    }
-
-    pub async fn upload_stream(
-        &self,
-        archive_name: &str,
-        stream: impl Stream<Item = Result<bytes::BytesMut, Error>>,
-        prefix: &str,
-        fixed_size: Option<u64>,
-        crypt_config: Option<Arc<CryptConfig>>,
-    ) -> Result<BackupStats, Error> {
-        let known_chunks = Arc::new(Mutex::new(HashSet::new()));
-
-        let mut param = json!({ "archive-name": archive_name });
-        if let Some(size) = fixed_size {
-            param["size"] = size.into();
-        }
-
-        let index_path = format!("{}_index", prefix);
-        let close_path = format!("{}_close", prefix);
-
-        self.download_chunk_list(&index_path, archive_name, known_chunks.clone()).await?;
-
-        let wid = self.h2.post(&index_path, Some(param)).await?.as_u64().unwrap();
-
-        let (chunk_count, size, _speed, csum) =
-            Self::upload_chunk_info_stream(
-                self.h2.clone(),
-                wid,
-                stream,
-                &prefix,
-                known_chunks.clone(),
-                crypt_config,
-            )
-            .await?;
-
-        let param = json!({
-            "wid": wid ,
-            "chunk-count": chunk_count,
-            "size": size,
-        });
-        let _value = self.h2.post(&close_path, Some(param)).await?;
-        Ok(BackupStats {
-            size: size as u64,
-            csum,
-        })
-    }
-
-    fn response_queue() -> (
-        mpsc::Sender<h2::client::ResponseFuture>,
-        oneshot::Receiver<Result<(), Error>>
-    ) {
-        let (verify_queue_tx, verify_queue_rx) = mpsc::channel(100);
-        let (verify_result_tx, verify_result_rx) = oneshot::channel();
-
-        hyper::rt::spawn(
-            verify_queue_rx
-                .map(Ok::<_, Error>)
-                .try_for_each(|response: h2::client::ResponseFuture| {
-                    response
-                        .map_err(Error::from)
-                        .and_then(H2Client::h2api_response)
-                        .map_ok(|result| println!("RESPONSE: {:?}", result))
-                        .map_err(|err| format_err!("pipelined request failed: {}", err))
-                })
-                .map(|result| {
-                      let _ignore_closed_channel = verify_result_tx.send(result);
-                })
-        );
-
-        (verify_queue_tx, verify_result_rx)
-    }
-
-    fn append_chunk_queue(h2: H2Client, wid: u64, path: String) -> (
-        mpsc::Sender<(MergedChunkInfo, Option<h2::client::ResponseFuture>)>,
-        oneshot::Receiver<Result<(), Error>>
-    ) {
-        let (verify_queue_tx, verify_queue_rx) = mpsc::channel(64);
-        let (verify_result_tx, verify_result_rx) = oneshot::channel();
-
-        let h2_2 = h2.clone();
-
-        hyper::rt::spawn(
-            verify_queue_rx
-                .map(Ok::<_, Error>)
-                .and_then(move |(merged_chunk_info, response): (MergedChunkInfo, Option<h2::client::ResponseFuture>)| {
-                    match (response, merged_chunk_info) {
-                        (Some(response), MergedChunkInfo::Known(list)) => {
-                            future::Either::Left(
-                                response
-                                    .map_err(Error::from)
-                                    .and_then(H2Client::h2api_response)
-                                    .and_then(move |_result| {
-                                        future::ok(MergedChunkInfo::Known(list))
-                                    })
-                            )
-                        }
-                        (None, MergedChunkInfo::Known(list)) => {
-                            future::Either::Right(future::ok(MergedChunkInfo::Known(list)))
-                        }
-                        _ => unreachable!(),
-                    }
-                })
-                .merge_known_chunks()
-                .and_then(move |merged_chunk_info| {
-                    match merged_chunk_info {
-                        MergedChunkInfo::Known(chunk_list) => {
-                            let mut digest_list = vec![];
-                            let mut offset_list = vec![];
-                            for (offset, digest) in chunk_list {
-                                //println!("append chunk {} (offset {})", proxmox::tools::digest_to_hex(&digest), offset);
-                                digest_list.push(digest_to_hex(&digest));
-                                offset_list.push(offset);
-                            }
-                            println!("append chunks list len ({})", digest_list.len());
-                            let param = json!({ "wid": wid, "digest-list": digest_list, "offset-list": offset_list });
-                            let mut request = H2Client::request_builder("localhost", "PUT", &path, None).unwrap();
-                            request.headers_mut().insert(hyper::header::CONTENT_TYPE,  HeaderValue::from_static("application/json"));
-                            let param_data = bytes::Bytes::from(param.to_string().as_bytes());
-                            let upload_data = Some(param_data);
-                            h2_2.send_request(request, upload_data)
-                                .and_then(move |response| {
-                                    response
-                                        .map_err(Error::from)
-                                        .and_then(H2Client::h2api_response)
-                                        .map_ok(|_| ())
-                                })
-                                .map_err(|err| format_err!("pipelined request failed: {}", err))
-                        }
-                        _ => unreachable!(),
-                    }
-                })
-                .try_for_each(|_| future::ok(()))
-                .map(|result| {
-                      let _ignore_closed_channel = verify_result_tx.send(result);
-                })
-        );
-
-        (verify_queue_tx, verify_result_rx)
-    }
-
-    pub async fn download_chunk_list(
-        &self,
-        path: &str,
-        archive_name: &str,
-        known_chunks: Arc<Mutex<HashSet<[u8;32]>>>,
-    ) -> Result<(), Error> {
-
-        let param = json!({ "archive-name": archive_name });
-        let request = H2Client::request_builder("localhost", "GET", path, Some(param)).unwrap();
-
-        let h2request = self.h2.send_request(request, None).await?;
-        let resp = h2request.await?;
-
-        let status = resp.status();
-
-        if !status.is_success() {
-            H2Client::h2api_response(resp).await?; // raise error
-            unreachable!();
-        }
-
-        let mut body = resp.into_body();
-        let mut release_capacity = body.release_capacity().clone();
-
-        let mut stream = DigestListDecoder::new(body.map_err(Error::from));
-
-        while let Some(chunk) = stream.try_next().await? {
-            let _ = release_capacity.release_capacity(chunk.len());
-            println!("GOT DOWNLOAD {}", digest_to_hex(&chunk));
-            known_chunks.lock().unwrap().insert(chunk);
-        }
-
-        Ok(())
-    }
-
-    fn upload_chunk_info_stream(
-        h2: H2Client,
-        wid: u64,
-        stream: impl Stream<Item = Result<bytes::BytesMut, Error>>,
-        prefix: &str,
-        known_chunks: Arc<Mutex<HashSet<[u8;32]>>>,
-        crypt_config: Option<Arc<CryptConfig>>,
-    ) -> impl Future<Output = Result<(usize, usize, usize, [u8; 32]), Error>> {
-
-        let repeat = Arc::new(AtomicUsize::new(0));
-        let repeat2 = repeat.clone();
-
-        let stream_len = Arc::new(AtomicUsize::new(0));
-        let stream_len2 = stream_len.clone();
-
-        let append_chunk_path = format!("{}_index", prefix);
-        let upload_chunk_path = format!("{}_chunk", prefix);
-
-        let (upload_queue, upload_result) =
-            Self::append_chunk_queue(h2.clone(), wid, append_chunk_path.to_owned());
-
-        let start_time = std::time::Instant::now();
-
-        let index_csum = Arc::new(Mutex::new(Some(openssl::sha::Sha256::new())));
-        let index_csum_2 = index_csum.clone();
-
-        stream
-            .and_then(move |data| {
-
-                let chunk_len = data.len();
-
-                repeat.fetch_add(1, Ordering::SeqCst);
-                let offset = stream_len.fetch_add(chunk_len, Ordering::SeqCst) as u64;
-
-                let mut chunk_builder = DataChunkBuilder::new(data.as_ref())
-                    .compress(true);
-
-                if let Some(ref crypt_config) = crypt_config {
-                    chunk_builder = chunk_builder.crypt_config(crypt_config);
-                }
-
-                let mut known_chunks = known_chunks.lock().unwrap();
-                let digest = chunk_builder.digest();
-
-                let mut guard = index_csum.lock().unwrap();
-                let csum = guard.as_mut().unwrap();
-
-                let chunk_end = offset + chunk_len as u64;
-
-                csum.update(&chunk_end.to_le_bytes());
-                csum.update(digest);
-
-                let chunk_is_known = known_chunks.contains(digest);
-                if chunk_is_known {
-                    future::ok(MergedChunkInfo::Known(vec![(offset, *digest)]))
-                } else {
-                    known_chunks.insert(*digest);
-                    future::ready(chunk_builder
-                        .build()
-                        .map(move |chunk| MergedChunkInfo::New(ChunkInfo {
-                            chunk,
-                            chunk_len: chunk_len as u64,
-                            offset,
-                        }))
-                    )
-                }
-            })
-            .merge_known_chunks()
-            .try_for_each(move |merged_chunk_info| {
-
-                if let MergedChunkInfo::New(chunk_info) = merged_chunk_info {
-                    let offset = chunk_info.offset;
-                    let digest = *chunk_info.chunk.digest();
-                    let digest_str = digest_to_hex(&digest);
-
-                    println!("upload new chunk {} ({} bytes, offset {})", digest_str,
-                             chunk_info.chunk_len, offset);
-
-                    let chunk_data = chunk_info.chunk.raw_data();
-                    let param = json!({
-                        "wid": wid,
-                        "digest": digest_str,
-                        "size": chunk_info.chunk_len,
-                        "encoded-size": chunk_data.len(),
-                    });
-
-                    let request = H2Client::request_builder("localhost", "POST", &upload_chunk_path, Some(param)).unwrap();
-                    let upload_data = Some(bytes::Bytes::from(chunk_data));
-
-                    let new_info = MergedChunkInfo::Known(vec![(offset, digest)]);
-
-                    let mut upload_queue = upload_queue.clone();
-                    future::Either::Left(h2
-                        .send_request(request, upload_data)
-                        .and_then(move |response| async move {
-                            upload_queue
-                                .send((new_info, Some(response)))
-                                .await
-                                .map_err(Error::from)
-                        })
-                    )
-                } else {
-                    let mut upload_queue = upload_queue.clone();
-                    future::Either::Right(async move {
-                        upload_queue
-                            .send((merged_chunk_info, None))
-                            .await
-                            .map_err(Error::from)
-                    })
-                }
-            })
-            .then(move |result| async move {
-                upload_result.await?.and(result)
-            }.boxed())
-            .and_then(move |_| {
-                let repeat = repeat2.load(Ordering::SeqCst);
-                let stream_len = stream_len2.load(Ordering::SeqCst);
-                let speed = ((stream_len*1000000)/(1024*1024))/(start_time.elapsed().as_micros() as usize);
-                println!("Uploaded {} chunks in {} seconds ({} MB/s).", repeat, start_time.elapsed().as_secs(), speed);
-                if repeat > 0 {
-                    println!("Average chunk size was {} bytes.", stream_len/repeat);
-                    println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128));
-                }
-
-                let mut guard = index_csum_2.lock().unwrap();
-                let csum = guard.take().unwrap().finish();
-
-                futures::future::ok((repeat, stream_len, speed, csum))
-            })
-    }
-
-    pub async fn upload_speedtest(&self) -> Result<usize, Error> {
-
-        let mut data = vec![];
-        // generate pseudo random byte sequence
-        for i in 0..1024*1024 {
-            for j in 0..4 {
-                let byte = ((i >> (j<<3))&0xff) as u8;
-                data.push(byte);
-            }
-        }
-
-        let item_len = data.len();
-
-        let mut repeat = 0;
-
-        let (upload_queue, upload_result) = Self::response_queue();
-
-        let start_time = std::time::Instant::now();
-
-        loop {
-            repeat += 1;
-            if start_time.elapsed().as_secs() >= 5 {
-                break;
-            }
-
-            let mut upload_queue = upload_queue.clone();
-
-            println!("send test data ({} bytes)", data.len());
-            let request = H2Client::request_builder("localhost", "POST", "speedtest", None).unwrap();
-            let request_future = self.h2.send_request(request, Some(bytes::Bytes::from(data.clone()))).await?;
-
-            upload_queue.send(request_future).await?;
-        }
-
-        drop(upload_queue); // close queue
-
-        let _ = upload_result.await?;
-
-        println!("Uploaded {} chunks in {} seconds.", repeat, start_time.elapsed().as_secs());
-        let speed = ((item_len*1000000*(repeat as usize))/(1024*1024))/(start_time.elapsed().as_micros() as usize);
-        println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128));
-
-        Ok(speed)
-    }
-}
 
 #[derive(Clone)]
 pub struct H2Client {
@@ -1066,7 +816,7 @@ impl H2Client {
         path: &str,
         param: Option<Value>
     ) -> Result<Value, Error> {
-        let req = Self::request_builder("localhost", "GET", path, param).unwrap();
+        let req = Self::request_builder("localhost", "GET", path, param, None).unwrap();
         self.request(req).await
     }
 
@@ -1075,7 +825,7 @@ impl H2Client {
         path: &str,
         param: Option<Value>
     ) -> Result<Value, Error> {
-        let req = Self::request_builder("localhost", "PUT", path, param).unwrap();
+        let req = Self::request_builder("localhost", "PUT", path, param, None).unwrap();
         self.request(req).await
     }
 
@@ -1084,7 +834,7 @@ impl H2Client {
         path: &str,
         param: Option<Value>
     ) -> Result<Value, Error> {
-        let req = Self::request_builder("localhost", "POST", path, param).unwrap();
+        let req = Self::request_builder("localhost", "POST", path, param, None).unwrap();
         self.request(req).await
     }
 
@@ -1093,8 +843,8 @@ impl H2Client {
         path: &str,
         param: Option<Value>,
         mut output: W,
-    ) -> Result<W, Error> {
-        let request = Self::request_builder("localhost", "GET", path, param).unwrap();
+    ) -> Result<(), Error> {
+        let request = Self::request_builder("localhost", "GET", path, param, None).unwrap();
 
         let response_future = self.send_request(request, None).await?;
 
@@ -1107,23 +857,24 @@ impl H2Client {
         }
 
         let mut body = resp.into_body();
-        let mut release_capacity = body.release_capacity().clone();
-
-        while let Some(chunk) = body.try_next().await? {
-            let _ = release_capacity.release_capacity(chunk.len());
+        while let Some(chunk) = body.data().await {
+            let chunk = chunk?;
+            body.flow_control().release_capacity(chunk.len())?;
             output.write_all(&chunk)?;
         }
 
-        Ok(output)
+        Ok(())
     }
 
     pub async fn upload(
         &self,
+        method: &str, // POST or PUT
         path: &str,
         param: Option<Value>,
+        content_type: &str,
         data: Vec<u8>,
     ) -> Result<Value, Error> {
-        let request = Self::request_builder("localhost", "POST", path, param).unwrap();
+        let request = Self::request_builder("localhost", method, path, param, Some(content_type)).unwrap();
 
         let mut send_request = self.h2.clone().ready().await?;
 
@@ -1151,7 +902,7 @@ impl H2Client {
             .await
     }
 
-    fn send_request(
+    pub fn send_request(
         &self,
         request: Request<()>,
         data: Option<bytes::Bytes>,
@@ -1172,31 +923,29 @@ impl H2Client {
             })
     }
 
-    async fn h2api_response(
+    pub async fn h2api_response(
         response: Response<h2::RecvStream>,
     ) -> Result<Value, Error> {
         let status = response.status();
 
         let (_head, mut body) = response.into_parts();
 
-        // The `release_capacity` handle allows the caller to manage
-        // flow control.
-        //
-        // Whenever data is received, the caller is responsible for
-        // releasing capacity back to the server once it has freed
-        // the data from memory.
-        let mut release_capacity = body.release_capacity().clone();
-
         let mut data = Vec::new();
-        while let Some(chunk) = body.try_next().await? {
+        while let Some(chunk) = body.data().await {
+            let chunk = chunk?;
+            // Whenever data is received, the caller is responsible for
+            // releasing capacity back to the server once it has freed
+            // the data from memory.
             // Let the server send more data.
-            let _ = release_capacity.release_capacity(chunk.len());
+            body.flow_control().release_capacity(chunk.len())?;
             data.extend(chunk);
         }
 
         let text = String::from_utf8(data.to_vec()).unwrap();
         if status.is_success() {
-            if text.len() > 0 {
+            if text.is_empty() {
+                Ok(Value::Null)
+            } else {
                 let mut value: Value = serde_json::from_str(&text)?;
                 if let Some(map) = value.as_object_mut() {
                     if let Some(data) = map.remove("data") {
@@ -1204,20 +953,26 @@ impl H2Client {
                     }
                 }
                 bail!("got result without data property");
-            } else {
-                Ok(Value::Null)
             }
         } else {
-            bail!("HTTP Error {}: {}", status, text);
+            Err(Error::from(HttpError::new(status, text)))
         }
     }
 
     // Note: We always encode parameters with the url
-    pub fn request_builder(server: &str, method: &str, path: &str, data: Option<Value>) -> Result<Request<()>, Error> {
+    pub fn request_builder(
+        server: &str,
+        method: &str,
+        path: &str,
+        param: Option<Value>,
+        content_type: Option<&str>,
+    ) -> Result<Request<()>, Error> {
         let path = path.trim_matches('/');
 
-        if let Some(data) = data {
-            let query = tools::json_object_to_query(data)?;
+        let content_type = content_type.unwrap_or("application/x-www-form-urlencoded");
+
+        if let Some(param) = param {
+            let query = tools::json_object_to_query(param)?;
             // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side
             if query.len() > 4096 { bail!("h2 query data too large ({} bytes) - please encode data inside body", query.len()); }
             let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?;
@@ -1225,67 +980,19 @@ impl H2Client {
                 .method(method)
                 .uri(url)
                 .header("User-Agent", "proxmox-backup-client/1.0")
-                .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
+                .header(hyper::header::CONTENT_TYPE, content_type)
                 .body(())?;
-            return Ok(request);
+            Ok(request)
         } else {
             let url: Uri = format!("https://{}:8007/{}", server, path).parse()?;
             let request = Request::builder()
                 .method(method)
                 .uri(url)
                 .header("User-Agent", "proxmox-backup-client/1.0")
-                .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
+                .header(hyper::header::CONTENT_TYPE, content_type)
                 .body(())?;
 
             Ok(request)
         }
     }
 }
-
-pub struct HttpsConnector {
-    http: HttpConnector,
-    ssl_connector: SslConnector,
-}
-
-impl HttpsConnector {
-    pub fn with_connector(mut http: HttpConnector, ssl_connector: SslConnector) -> Self {
-        http.enforce_http(false);
-
-        Self {
-            http,
-            ssl_connector,
-        }
-    }
-}
-
-type MaybeTlsStream = EitherStream<
-    tokio::net::TcpStream,
-    tokio_openssl::SslStream<tokio::net::TcpStream>,
->;
-
-impl hyper::client::connect::Connect for HttpsConnector {
-    type Transport = MaybeTlsStream;
-    type Error = Error;
-    type Future = Box<dyn Future<Output = Result<(
-        Self::Transport,
-        hyper::client::connect::Connected,
-    ), Error>> + Send + Unpin + 'static>;
-
-    fn connect(&self, dst: hyper::client::connect::Destination) -> Self::Future {
-        let is_https = dst.scheme() == "https";
-        let host = dst.host().to_string();
-
-        let config = self.ssl_connector.configure();
-        let conn = self.http.connect(dst);
-
-        Box::new(Box::pin(async move {
-            let (conn, connected) = conn.await?;
-            if is_https {
-                let conn = tokio_openssl::connect(config?, &host, conn).await?;
-                Ok((MaybeTlsStream::Right(conn), connected))
-            } else {
-                Ok((MaybeTlsStream::Left(conn), connected))
-            }
-        }))
-    }
-}