]> git.proxmox.com Git - proxmox-backup.git/blobdiff - src/bin/proxmox-backup-client.rs
BackupEnvironment: do not set finished flag prematurely
[proxmox-backup.git] / src / bin / proxmox-backup-client.rs
index 356813c9e9d159fa33e27bca5fab510ac6383914..123ab2b5dbbeefa38c6a9c18c9cce18db26ace98 100644 (file)
@@ -1,15 +1,28 @@
-use failure::*;
-use nix::unistd::{fork, ForkResult, pipe};
-use std::os::unix::io::RawFd;
-use chrono::{Local, DateTime, Utc, TimeZone};
-use std::path::{Path, PathBuf};
 use std::collections::{HashSet, HashMap};
 use std::ffi::OsStr;
-use std::io::{Write, Seek, SeekFrom};
+use std::io::{self, Write, Seek, SeekFrom};
 use std::os::unix::fs::OpenOptionsExt;
+use std::os::unix::io::RawFd;
+use std::path::{Path, PathBuf};
+use std::pin::Pin;
+use std::sync::{Arc, Mutex};
+use std::task::{Context, Poll};
+
+use anyhow::{bail, format_err, Error};
+use chrono::{Local, DateTime, Utc, TimeZone};
+use futures::future::FutureExt;
+use futures::select;
+use futures::stream::{StreamExt, TryStreamExt};
+use nix::unistd::{fork, ForkResult, pipe};
+use serde_json::{json, Value};
+use tokio::signal::unix::{signal, SignalKind};
+use tokio::sync::mpsc;
+use xdg::BaseDirectories;
 
+use pathpatterns::{MatchEntry, MatchType, PatternFlag};
 use proxmox::{sortable, identity};
 use proxmox::tools::fs::{file_get_contents, file_get_json, replace_file, CreateOptions, image_size};
+use proxmox::sys::linux::tty;
 use proxmox::api::{ApiHandler, ApiMethod, RpcEnvironment};
 use proxmox::api::schema::*;
 use proxmox::api::cli::*;
@@ -19,36 +32,17 @@ use proxmox_backup::tools;
 use proxmox_backup::api2::types::*;
 use proxmox_backup::client::*;
 use proxmox_backup::backup::*;
-use proxmox_backup::pxar::{ self, catalog::* };
-
-//use proxmox_backup::backup::image_index::*;
-//use proxmox_backup::config::datastore;
-//use proxmox_backup::pxar::encoder::*;
-//use proxmox_backup::backup::datastore::*;
-
-use serde_json::{json, Value};
-//use hyper::Body;
-use std::sync::{Arc, Mutex};
-//use regex::Regex;
-use xdg::BaseDirectories;
+use proxmox_backup::pxar::catalog::*;
 
-use futures::*;
-use tokio::sync::mpsc;
+const ENV_VAR_PBS_FINGERPRINT: &str = "PBS_FINGERPRINT";
+const ENV_VAR_PBS_PASSWORD: &str = "PBS_PASSWORD";
 
-proxmox::api::const_regex! {
-    BACKUPSPEC_REGEX = r"^([a-zA-Z0-9_-]+\.(?:pxar|img|conf|log)):(.+)$";
-}
 
 const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.")
     .format(&BACKUP_REPO_URL)
     .max_length(256)
     .schema();
 
-const BACKUP_SOURCE_SCHEMA: Schema = StringSchema::new(
-    "Backup source specification ([<label>:<path>]).")
-    .format(&ApiStringFormat::Pattern(&BACKUPSPEC_REGEX))
-    .schema();
-
 const KEYFILE_SCHEMA: Schema = StringSchema::new(
     "Path to encryption key. All data will be encrypted using this key.")
     .schema();
@@ -163,6 +157,28 @@ fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<Stri
     result
 }
 
+fn connect(server: &str, userid: &str) -> Result<HttpClient, Error> {
+
+    let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
+
+    use std::env::VarError::*;
+    let password = match std::env::var(ENV_VAR_PBS_PASSWORD) {
+        Ok(p) => Some(p),
+        Err(NotUnicode(_)) => bail!(format!("{} contains bad characters", ENV_VAR_PBS_PASSWORD)),
+        Err(NotPresent) => None,
+    };
+
+    let options = HttpClientOptions::new()
+        .prefix(Some("proxmox-backup".to_string()))
+        .password(password)
+        .interactive(true)
+        .fingerprint(fingerprint)
+        .fingerprint_cache(true)
+        .ticket_cache(true);
+
+    HttpClient::new(server, userid, options)
+}
+
 async fn view_task_result(
     client: HttpClient,
     result: Value,
@@ -184,7 +200,7 @@ async fn api_datastore_list_snapshots(
     client: &HttpClient,
     store: &str,
     group: Option<BackupGroup>,
-) -> Result<Vec<SnapshotListItem>, Error> {
+) -> Result<Value, Error> {
 
     let path = format!("api2/json/admin/datastore/{}/snapshots", store);
 
@@ -196,9 +212,7 @@ async fn api_datastore_list_snapshots(
 
     let mut result = client.get(&path, Some(args)).await?;
 
-    let list: Vec<SnapshotListItem> = serde_json::from_value(result["data"].take())?;
-
-    Ok(list)
+    Ok(result["data"].take())
 }
 
 async fn api_datastore_latest_snapshot(
@@ -207,7 +221,8 @@ async fn api_datastore_latest_snapshot(
     group: BackupGroup,
 ) -> Result<(String, String, DateTime<Utc>), Error> {
 
-    let mut list = api_datastore_list_snapshots(client, store, Some(group.clone())).await?;
+    let list = api_datastore_list_snapshots(client, store, Some(group.clone())).await?;
+    let mut list: Vec<SnapshotListItem> = serde_json::from_value(list)?;
 
     if list.is_empty() {
         bail!("backup group {:?} does not contain any snapshots.", group.group_path());
@@ -230,7 +245,8 @@ async fn backup_directory<P: AsRef<Path>>(
     verbose: bool,
     skip_lost_and_found: bool,
     crypt_config: Option<Arc<CryptConfig>>,
-    catalog: Arc<Mutex<CatalogWriter<SenderWriter>>>,
+    catalog: Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>,
+    exclude_pattern: Vec<MatchEntry>,
     entries_max: usize,
 ) -> Result<BackupStats, Error> {
 
@@ -240,6 +256,7 @@ async fn backup_directory<P: AsRef<Path>>(
         verbose,
         skip_lost_and_found,
         catalog,
+        exclude_pattern,
         entries_max,
     )?;
     let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size);
@@ -289,15 +306,6 @@ async fn backup_image<P: AsRef<Path>>(
     Ok(stats)
 }
 
-fn strip_server_file_expenstion(name: &str) -> String {
-
-    if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") {
-        name[..name.len()-5].to_owned()
-    } else {
-        name.to_owned() // should not happen
-    }
-}
-
 #[api(
    input: {
         properties: {
@@ -315,9 +323,11 @@ fn strip_server_file_expenstion(name: &str) -> String {
 /// List backup groups.
 async fn list_backup_groups(param: Value) -> Result<Value, Error> {
 
+    let output_format = get_output_format(&param);
+
     let repo = extract_repository_from_value(&param)?;
 
-    let client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let client = connect(repo.host(), repo.user())?;
 
     let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
 
@@ -325,62 +335,41 @@ async fn list_backup_groups(param: Value) -> Result<Value, Error> {
 
     record_repository(&repo);
 
-    // fixme: implement and use output formatter instead ..
-    let list = result["data"].as_array_mut().unwrap();
-
-    list.sort_unstable_by(|a, b| {
-        let a_id = a["backup-id"].as_str().unwrap();
-        let a_backup_type = a["backup-type"].as_str().unwrap();
-        let b_id = b["backup-id"].as_str().unwrap();
-        let b_backup_type = b["backup-type"].as_str().unwrap();
-
-        let type_order = a_backup_type.cmp(b_backup_type);
-        if type_order == std::cmp::Ordering::Equal {
-            a_id.cmp(b_id)
-        } else {
-            type_order
-        }
-    });
-
-    let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
-
-    let mut result = vec![];
-
-    for item in list {
+    let render_group_path = |_v: &Value, record: &Value| -> Result<String, Error> {
+        let item: GroupListItem = serde_json::from_value(record.to_owned())?;
+        let group = BackupGroup::new(item.backup_type, item.backup_id);
+        Ok(group.group_path().to_str().unwrap().to_owned())
+    };
 
-        let id = item["backup-id"].as_str().unwrap();
-        let btype = item["backup-type"].as_str().unwrap();
-        let epoch = item["last-backup"].as_i64().unwrap();
-        let last_backup = Utc.timestamp(epoch, 0);
-        let backup_count = item["backup-count"].as_u64().unwrap();
+    let render_last_backup = |_v: &Value, record: &Value| -> Result<String, Error> {
+        let item: GroupListItem = serde_json::from_value(record.to_owned())?;
+        let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.last_backup);
+        Ok(snapshot.relative_path().to_str().unwrap().to_owned())
+    };
 
-        let group = BackupGroup::new(btype, id);
+    let render_files = |_v: &Value, record: &Value| -> Result<String, Error> {
+        let item: GroupListItem = serde_json::from_value(record.to_owned())?;
+        Ok(tools::format::render_backup_file_list(&item.files))
+    };
 
-        let path = group.group_path().to_str().unwrap().to_owned();
+    let options = default_table_format_options()
+        .sortby("backup-type", false)
+        .sortby("backup-id", false)
+        .column(ColumnConfig::new("backup-id").renderer(render_group_path).header("group"))
+        .column(
+            ColumnConfig::new("last-backup")
+                .renderer(render_last_backup)
+                .header("last snapshot")
+                .right_align(false)
+        )
+        .column(ColumnConfig::new("backup-count"))
+        .column(ColumnConfig::new("files").renderer(render_files));
 
-        let files = item["files"].as_array().unwrap().iter()
-            .map(|v| strip_server_file_expenstion(v.as_str().unwrap())).collect();
+    let mut data: Value = result["data"].take();
 
-        if output_format == "text" {
-            println!(
-                "{:20} | {} | {:5} | {}",
-                path,
-                BackupDir::backup_time_to_string(last_backup),
-                backup_count,
-                tools::join(&files, ' '),
-            );
-        } else {
-            result.push(json!({
-                "backup-type": btype,
-                "backup-id": id,
-                "last-backup": epoch,
-                "backup-count": backup_count,
-                "files": files,
-            }));
-        }
-    }
+    let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_GROUPS;
 
-    if output_format != "text" { format_and_print_result(&result.into(), &output_format); }
+    format_and_print_result_full(&mut data, info, &output_format, &options);
 
     Ok(Value::Null)
 }
@@ -409,9 +398,9 @@ async fn list_snapshots(param: Value) -> Result<Value, Error> {
 
     let repo = extract_repository_from_value(&param)?;
 
-    let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
+    let output_format = get_output_format(&param);
 
-    let client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let client = connect(repo.host(), repo.user())?;
 
     let group = if let Some(path) = param["group"].as_str() {
         Some(BackupGroup::parse(path)?)
@@ -419,34 +408,33 @@ async fn list_snapshots(param: Value) -> Result<Value, Error> {
         None
     };
 
-    let mut list = api_datastore_list_snapshots(&client, repo.store(), group).await?;
-
-    list.sort_unstable_by(|a, b| a.backup_time.cmp(&b.backup_time));
+    let mut data = api_datastore_list_snapshots(&client, repo.store(), group).await?;
 
     record_repository(&repo);
 
-    if output_format != "text" {
-        format_and_print_result(&serde_json::to_value(list)?, &output_format);
-        return Ok(Value::Null);
-    }
-
-    for item in list {
-
+    let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> {
+        let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
         let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time);
+        Ok(snapshot.relative_path().to_str().unwrap().to_owned())
+    };
 
-        let path = snapshot.relative_path().to_str().unwrap().to_owned();
+    let render_files = |_v: &Value, record: &Value| -> Result<String, Error> {
+        let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
+        Ok(tools::format::render_backup_file_list(&item.files))
+    };
 
-        let files = item.files.iter()
-            .map(|v| strip_server_file_expenstion(&v))
-            .collect();
+    let options = default_table_format_options()
+        .sortby("backup-type", false)
+        .sortby("backup-id", false)
+        .sortby("backup-time", false)
+        .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot"))
+        .column(ColumnConfig::new("size"))
+        .column(ColumnConfig::new("files").renderer(render_files))
+        ;
 
-        let size_str = if let Some(size) = item.size {
-            size.to_string()
-        } else {
-            String::from("-")
-        };
-        println!("{} | {} | {}", path, size_str, tools::join(&files, ' '));
-    }
+    let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOTS;
+
+    format_and_print_result_full(&mut data, info, &output_format, &options);
 
     Ok(Value::Null)
 }
@@ -473,7 +461,7 @@ async fn forget_snapshots(param: Value) -> Result<Value, Error> {
     let path = tools::required_string_param(&param, "snapshot")?;
     let snapshot = BackupDir::parse(path)?;
 
-    let mut client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let mut client = connect(repo.host(), repo.user())?;
 
     let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
 
@@ -503,7 +491,7 @@ async fn api_login(param: Value) -> Result<Value, Error> {
 
     let repo = extract_repository_from_value(&param)?;
 
-    let client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let client = connect(repo.host(), repo.user())?;
     client.login().await?;
 
     record_repository(&repo);
@@ -526,7 +514,7 @@ fn api_logout(param: Value) -> Result<Value, Error> {
 
     let repo = extract_repository_from_value(&param)?;
 
-    delete_ticket_info(repo.host(), repo.user())?;
+    delete_ticket_info("proxmox-backup", repo.host(), repo.user())?;
 
     Ok(Value::Null)
 }
@@ -558,12 +546,12 @@ async fn dump_catalog(param: Value) -> Result<Value, Error> {
     let crypt_config = match keyfile {
         None => None,
         Some(path) => {
-            let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
+            let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
             Some(Arc::new(CryptConfig::new(key)?))
         }
     };
 
-    let client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let client = connect(repo.host(), repo.user())?;
 
     let client = BackupReader::start(
         client,
@@ -631,9 +619,9 @@ async fn list_snapshot_files(param: Value) -> Result<Value, Error> {
     let path = tools::required_string_param(&param, "snapshot")?;
     let snapshot = BackupDir::parse(path)?;
 
-    let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
+    let output_format = get_output_format(&param);
 
-    let client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let client = connect(repo.host(), repo.user())?;
 
     let path = format!("api2/json/admin/datastore/{}/files", repo.store());
 
@@ -645,19 +633,13 @@ async fn list_snapshot_files(param: Value) -> Result<Value, Error> {
 
     record_repository(&repo);
 
-    let list: Value = result["data"].take();
+    let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOT_FILES;
 
-    if output_format == "text" {
-        for item in list.as_array().unwrap().iter() {
-            println!(
-                "{} {}",
-                strip_server_file_expenstion(item["filename"].as_str().unwrap()),
-                item["size"].as_u64().unwrap_or(0),
-            );
-        }
-    } else {
-        format_and_print_result(&list, &output_format);
-    }
+    let mut data: Value = result["data"].take();
+
+    let options = default_table_format_options();
+
+    format_and_print_result_full(&mut data, info, &output_format, &options);
 
     Ok(Value::Null)
 }
@@ -680,9 +662,10 @@ async fn list_snapshot_files(param: Value) -> Result<Value, Error> {
 async fn start_garbage_collection(param: Value) -> Result<Value, Error> {
 
     let repo = extract_repository_from_value(&param)?;
-    let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
 
-    let mut client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let output_format = get_output_format(&param);
+
+    let mut client = connect(repo.host(), repo.user())?;
 
     let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
 
@@ -695,29 +678,21 @@ async fn start_garbage_collection(param: Value) -> Result<Value, Error> {
     Ok(Value::Null)
 }
 
-fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> {
-
-    if let Some(caps) = (BACKUPSPEC_REGEX.regex_obj)().captures(value) {
-        return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str()));
-    }
-    bail!("unable to parse directory specification '{}'", value);
-}
-
 fn spawn_catalog_upload(
     client: Arc<BackupWriter>,
     crypt_config: Option<Arc<CryptConfig>>,
 ) -> Result<
         (
-            Arc<Mutex<CatalogWriter<SenderWriter>>>,
+            Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>,
             tokio::sync::oneshot::Receiver<Result<BackupStats, Error>>
         ), Error>
 {
-    let (catalog_tx, catalog_rx) = mpsc::channel(10); // allow to buffer 10 writes
-    let catalog_stream = catalog_rx.map_err(Error::from);
+    let (catalog_tx, catalog_rx) = std::sync::mpsc::sync_channel(10); // allow to buffer 10 writes
+    let catalog_stream = crate::tools::StdChannelStream(catalog_rx);
     let catalog_chunk_size = 512*1024;
     let catalog_chunk_stream = ChunkStream::new(catalog_stream, Some(catalog_chunk_size));
 
-    let catalog = Arc::new(Mutex::new(CatalogWriter::new(SenderWriter::new(catalog_tx))?));
+    let catalog = Arc::new(Mutex::new(CatalogWriter::new(crate::tools::StdChannelWriter::new(catalog_tx))?));
 
     let (catalog_result_tx, catalog_result_rx) = tokio::sync::oneshot::channel();
 
@@ -784,11 +759,25 @@ fn spawn_catalog_upload(
                schema: CHUNK_SIZE_SCHEMA,
                optional: true,
            },
+           "exclude": {
+               type: Array,
+               description: "List of paths or patterns for matching files to exclude.",
+               optional: true,
+               items: {
+                   type: String,
+                   description: "Path or match pattern.",
+                }
+           },
            "entries-max": {
                type: Integer,
                description: "Max number of entries to hold in memory.",
                optional: true,
-               default: pxar::ENCODER_MAX_ENTRIES as isize,
+               default: proxmox_backup::pxar::ENCODER_MAX_ENTRIES as isize,
+           },
+           "verbose": {
+               type: Boolean,
+               description: "Verbose output.",
+               optional: true,
            },
        }
    }
@@ -826,7 +815,20 @@ async fn create_backup(
 
     let include_dev = param["include-dev"].as_array();
 
-    let entries_max = param["entries-max"].as_u64().unwrap_or(pxar::ENCODER_MAX_ENTRIES as u64);
+    let entries_max = param["entries-max"].as_u64()
+        .unwrap_or(proxmox_backup::pxar::ENCODER_MAX_ENTRIES as u64);
+
+    let empty = Vec::new();
+    let exclude_args = param["exclude"].as_array().unwrap_or(&empty);
+
+    let mut pattern_list = Vec::with_capacity(exclude_args.len());
+    for entry in exclude_args {
+        let entry = entry.as_str().ok_or_else(|| format_err!("Invalid pattern string slice"))?;
+        pattern_list.push(
+            MatchEntry::parse_pattern(entry, PatternFlag::PATH_NAME, MatchType::Exclude)
+                .map_err(|err| format_err!("invalid exclude pattern entry: {}", err))?
+        );
+    }
 
     let mut devices = if all_file_systems { None } else { Some(HashSet::new()) };
 
@@ -847,12 +849,12 @@ async fn create_backup(
 
     let mut upload_list = vec![];
 
-    enum BackupType { PXAR, IMAGE, CONFIG, LOGFILE };
-
     let mut upload_catalog = false;
 
     for backupspec in backupspec_list {
-        let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?;
+        let spec = parse_backup_specification(backupspec.as_str().unwrap())?;
+        let filename = &spec.config_string;
+        let target = &spec.archive_name;
 
         use std::os::unix::fs::FileTypeExt;
 
@@ -860,19 +862,15 @@ async fn create_backup(
             .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?;
         let file_type = metadata.file_type();
 
-        let extension = target.rsplit('.').next()
-            .ok_or_else(|| format_err!("missing target file extenion '{}'", target))?;
-
-        match extension {
-            "pxar" => {
+        match spec.spec_type {
+            BackupSpecificationType::PXAR => {
                 if !file_type.is_dir() {
                     bail!("got unexpected file type (expected directory)");
                 }
-                upload_list.push((BackupType::PXAR, filename.to_owned(), format!("{}.didx", target), 0));
+                upload_list.push((BackupSpecificationType::PXAR, filename.to_owned(), format!("{}.didx", target), 0));
                 upload_catalog = true;
             }
-            "img" => {
-
+            BackupSpecificationType::IMAGE => {
                 if !(file_type.is_file() || file_type.is_block_device()) {
                     bail!("got unexpected file type (expected file or block device)");
                 }
@@ -881,29 +879,26 @@ async fn create_backup(
 
                 if size == 0 { bail!("got zero-sized file '{}'", filename); }
 
-                upload_list.push((BackupType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size));
+                upload_list.push((BackupSpecificationType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size));
             }
-            "conf" => {
+            BackupSpecificationType::CONFIG => {
                 if !file_type.is_file() {
                     bail!("got unexpected file type (expected regular file)");
                 }
-                upload_list.push((BackupType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len()));
+                upload_list.push((BackupSpecificationType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len()));
             }
-            "log" => {
+            BackupSpecificationType::LOGFILE => {
                 if !file_type.is_file() {
                     bail!("got unexpected file type (expected regular file)");
                 }
-                upload_list.push((BackupType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len()));
-            }
-            _ => {
-                bail!("got unknown archive extension '{}'", extension);
+                upload_list.push((BackupSpecificationType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len()));
             }
         }
     }
 
     let backup_time = Utc.timestamp(backup_time_opt.unwrap_or_else(|| Utc::now().timestamp()), 0);
 
-    let client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let client = connect(repo.host(), repo.user())?;
     record_repository(&repo);
 
     println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time));
@@ -917,7 +912,7 @@ async fn create_backup(
     let (crypt_config, rsa_encrypted_key) = match keyfile {
         None => (None, None),
         Some(path) => {
-            let (key, created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
+            let (key, created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
 
             let crypt_config = CryptConfig::new(key)?;
 
@@ -949,21 +944,21 @@ async fn create_backup(
 
     for (backup_type, filename, target, size) in upload_list {
         match backup_type {
-            BackupType::CONFIG => {
+            BackupSpecificationType::CONFIG => {
                 println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target);
                 let stats = client
                     .upload_blob_from_file(&filename, &target, crypt_config.clone(), true)
                     .await?;
                 manifest.add_file(target, stats.size, stats.csum)?;
             }
-            BackupType::LOGFILE => { // fixme: remove - not needed anymore ?
+            BackupSpecificationType::LOGFILE => { // fixme: remove - not needed anymore ?
                 println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target);
                 let stats = client
                     .upload_blob_from_file(&filename, &target, crypt_config.clone(), true)
                     .await?;
                 manifest.add_file(target, stats.size, stats.csum)?;
             }
-            BackupType::PXAR => {
+            BackupSpecificationType::PXAR => {
                 println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target);
                 catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?;
                 let stats = backup_directory(
@@ -976,12 +971,13 @@ async fn create_backup(
                     skip_lost_and_found,
                     crypt_config.clone(),
                     catalog.clone(),
+                    pattern_list.clone(),
                     entries_max as usize,
                 ).await?;
                 manifest.add_file(target, stats.size, stats.csum)?;
                 catalog.lock().unwrap().end_directory()?;
             }
-            BackupType::IMAGE => {
+            BackupSpecificationType::IMAGE => {
                 println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
                 let stats = backup_image(
                     &client,
@@ -1116,6 +1112,18 @@ fn dump_image<W: Write>(
     Ok(())
 }
 
+fn parse_archive_type(name: &str) -> (String, ArchiveType) {
+    if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") {
+        (name.into(), archive_type(name).unwrap())
+    } else if name.ends_with(".pxar") {
+        (format!("{}.didx", name), ArchiveType::DynamicIndex)
+    } else if name.ends_with(".img") {
+        (format!("{}.fidx", name), ArchiveType::FixedIndex)
+    } else {
+        (format!("{}.blob", name), ArchiveType::Blob)
+    }
+}
+
 #[api(
    input: {
        properties: {
@@ -1133,9 +1141,9 @@ fn dump_image<W: Write>(
            },
            target: {
                type: String,
-               description: r###"Target directory path. Use '-' to write to stdandard output.
+               description: r###"Target directory path. Use '-' to write to standard output.
 
-We do not extraxt '.pxar' archives when writing to stdandard output.
+We do not extraxt '.pxar' archives when writing to standard output.
 
 "###
            },
@@ -1161,7 +1169,7 @@ async fn restore(param: Value) -> Result<Value, Error> {
 
     let archive_name = tools::required_string_param(&param, "archive-name")?;
 
-    let client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let client = connect(repo.host(), repo.user())?;
 
     record_repository(&repo);
 
@@ -1183,19 +1191,11 @@ async fn restore(param: Value) -> Result<Value, Error> {
     let crypt_config = match keyfile {
         None => None,
         Some(path) => {
-            let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
+            let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
             Some(Arc::new(CryptConfig::new(key)?))
         }
     };
 
-    let server_archive_name = if archive_name.ends_with(".pxar") {
-        format!("{}.didx", archive_name)
-    } else if archive_name.ends_with(".img") {
-        format!("{}.fidx", archive_name)
-    } else {
-        format!("{}.blob", archive_name)
-    };
-
     let client = BackupReader::start(
         client,
         crypt_config.clone(),
@@ -1208,7 +1208,9 @@ async fn restore(param: Value) -> Result<Value, Error> {
 
     let manifest = client.download_manifest().await?;
 
-    if server_archive_name == MANIFEST_BLOB_NAME {
+    let (archive_name, archive_type) = parse_archive_type(archive_name);
+
+    if archive_name == MANIFEST_BLOB_NAME {
         let backup_index_data = manifest.into_json().to_string();
         if let Some(target) = target {
             replace_file(target, backup_index_data.as_bytes(), CreateOptions::new())?;
@@ -1219,9 +1221,9 @@ async fn restore(param: Value) -> Result<Value, Error> {
                 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
         }
 
-    } else if server_archive_name.ends_with(".blob") {
+    } else if archive_type == ArchiveType::Blob {
 
-        let mut reader = client.download_blob(&manifest, &server_archive_name).await?;
+        let mut reader = client.download_blob(&manifest, &archive_name).await?;
 
         if let Some(target) = target {
            let mut writer = std::fs::OpenOptions::new()
@@ -1238,9 +1240,9 @@ async fn restore(param: Value) -> Result<Value, Error> {
                 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
         }
 
-    } else if server_archive_name.ends_with(".didx") {
+    } else if archive_type == ArchiveType::DynamicIndex {
 
-        let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
+        let index = client.download_dynamic_index(&manifest, &archive_name).await?;
 
         let most_used = index.find_most_used_chunks(8);
 
@@ -1249,18 +1251,19 @@ async fn restore(param: Value) -> Result<Value, Error> {
         let mut reader = BufferedDynamicReader::new(index, chunk_reader);
 
         if let Some(target) = target {
-
-            let feature_flags = pxar::flags::DEFAULT;
-            let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags);
-            decoder.set_callback(move |path| {
-                if verbose {
-                    eprintln!("{:?}", path);
-                }
-                Ok(())
-            });
-            decoder.set_allow_existing_dirs(allow_existing_dirs);
-
-            decoder.restore(Path::new(target), &Vec::new())?;
+            proxmox_backup::pxar::extract_archive(
+                pxar::decoder::Decoder::from_std(reader)?,
+                Path::new(target),
+                &[],
+                proxmox_backup::pxar::Flags::DEFAULT,
+                allow_existing_dirs,
+                |path| {
+                    if verbose {
+                        println!("{:?}", path);
+                    }
+                },
+            )
+            .map_err(|err| format_err!("error extracting archive - {}", err))?;
         } else {
             let mut writer = std::fs::OpenOptions::new()
                 .write(true)
@@ -1270,9 +1273,9 @@ async fn restore(param: Value) -> Result<Value, Error> {
             std::io::copy(&mut reader, &mut writer)
                 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
         }
-    } else if server_archive_name.ends_with(".fidx") {
+    } else if archive_type == ArchiveType::FixedIndex {
 
-        let index = client.download_fixed_index(&manifest, &server_archive_name).await?;
+        let index = client.download_fixed_index(&manifest, &archive_name).await?;
 
         let mut writer = if let Some(target) = target {
             std::fs::OpenOptions::new()
@@ -1289,9 +1292,6 @@ async fn restore(param: Value) -> Result<Value, Error> {
         };
 
         dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose)?;
-
-     } else {
-        bail!("unknown archive file extension (expected .pxar of .img)");
     }
 
     Ok(Value::Null)
@@ -1328,14 +1328,14 @@ async fn upload_log(param: Value) -> Result<Value, Error> {
     let snapshot = tools::required_string_param(&param, "snapshot")?;
     let snapshot = BackupDir::parse(snapshot)?;
 
-    let mut client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let mut client = connect(repo.host(), repo.user())?;
 
     let keyfile = param["keyfile"].as_str().map(PathBuf::from);
 
     let crypt_config = match keyfile {
         None => None,
         Some(path) => {
-            let (key, _created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
+            let (key, _created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
             let crypt_config = CryptConfig::new(key)?;
             Some(Arc::new(crypt_config))
         }
@@ -1360,54 +1360,99 @@ async fn upload_log(param: Value) -> Result<Value, Error> {
     client.upload("application/octet-stream", body, &path, Some(args)).await
 }
 
-#[api(
-   input: {
-       properties: {
-           repository: {
-               schema: REPO_URL_SCHEMA,
-               optional: true,
-           },
-           group: {
-               type: String,
-               description: "Backup group.",
-           },
-           "output-format": {
-               schema: OUTPUT_FORMAT,
-               optional: true,
-           },
-           "dry-run": {
-               type: Boolean,
-               description: "Just show what prune would do, but do not delete anything.",
-               optional: true,
-           },
-       }
-   }
-)]
-/// Prune a backup repository.
-async fn prune(mut param: Value) -> Result<Value, Error> {
+const API_METHOD_PRUNE: ApiMethod = ApiMethod::new(
+    &ApiHandler::Async(&prune),
+    &ObjectSchema::new(
+        "Prune a backup repository.",
+        &proxmox_backup::add_common_prune_prameters!([
+            ("dry-run", true, &BooleanSchema::new(
+                "Just show what prune would do, but do not delete anything.")
+             .schema()),
+            ("group", false, &StringSchema::new("Backup group.").schema()),
+        ], [
+            ("output-format", true, &OUTPUT_FORMAT),
+            (
+                "quiet",
+                true,
+                &BooleanSchema::new("Minimal output - only show removals.")
+                    .schema()
+            ),
+            ("repository", true, &REPO_URL_SCHEMA),
+        ])
+    )
+);
+
+fn prune<'a>(
+    param: Value,
+    _info: &ApiMethod,
+    _rpcenv: &'a mut dyn RpcEnvironment,
+) -> proxmox::api::ApiFuture<'a> {
+    async move {
+        prune_async(param).await
+    }.boxed()
+}
 
+async fn prune_async(mut param: Value) -> Result<Value, Error> {
     let repo = extract_repository_from_value(&param)?;
 
-    let mut client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let mut client = connect(repo.host(), repo.user())?;
 
     let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
 
     let group = tools::required_string_param(&param, "group")?;
     let group = BackupGroup::parse(group)?;
-    let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
+
+    let output_format = get_output_format(&param);
+
+    let quiet = param["quiet"].as_bool().unwrap_or(false);
 
     param.as_object_mut().unwrap().remove("repository");
     param.as_object_mut().unwrap().remove("group");
     param.as_object_mut().unwrap().remove("output-format");
+    param.as_object_mut().unwrap().remove("quiet");
 
     param["backup-type"] = group.backup_type().into();
     param["backup-id"] = group.backup_id().into();
 
-    let result = client.post(&path, Some(param)).await?;
+    let mut result = client.post(&path, Some(param)).await?;
 
     record_repository(&repo);
 
-    view_task_result(client, result, &output_format).await?;
+    let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> {
+        let item: PruneListItem = serde_json::from_value(record.to_owned())?;
+        let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time);
+        Ok(snapshot.relative_path().to_str().unwrap().to_owned())
+    };
+
+    let render_prune_action = |v: &Value, _record: &Value| -> Result<String, Error> {
+        Ok(match v.as_bool() {
+            Some(true) => "keep",
+            Some(false) => "remove",
+            None => "unknown",
+        }.to_string())
+    };
+
+    let options = default_table_format_options()
+        .sortby("backup-type", false)
+        .sortby("backup-id", false)
+        .sortby("backup-time", false)
+        .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot"))
+        .column(ColumnConfig::new("backup-time").renderer(tools::format::render_epoch).header("date"))
+        .column(ColumnConfig::new("keep").renderer(render_prune_action).header("action"))
+        ;
+
+    let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_PRUNE;
+
+    let mut data = result["data"].take();
+
+    if quiet {
+        let list: Vec<Value> = data.as_array().unwrap().iter().filter(|item| {
+            item["keep"].as_bool() == Some(false)
+        }).map(|v| v.clone()).collect();
+        data = list.into();
+    }
+
+    format_and_print_result_full(&mut data, info, &output_format, &options);
 
     Ok(Value::Null)
 }
@@ -1431,33 +1476,35 @@ async fn status(param: Value) -> Result<Value, Error> {
 
     let repo = extract_repository_from_value(&param)?;
 
-    let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
+    let output_format = get_output_format(&param);
 
-    let client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let client = connect(repo.host(), repo.user())?;
 
     let path = format!("api2/json/admin/datastore/{}/status", repo.store());
 
-    let result = client.get(&path, None).await?;
-    let data = &result["data"];
+    let mut result = client.get(&path, None).await?;
+    let mut data = result["data"].take();
 
     record_repository(&repo);
 
-    if output_format == "text" {
-        let total = data["total"].as_u64().unwrap();
-        let used = data["used"].as_u64().unwrap();
-        let avail = data["avail"].as_u64().unwrap();
+    let render_total_percentage = |v: &Value, record: &Value| -> Result<String, Error> {
+        let v = v.as_u64().unwrap();
+        let total = record["total"].as_u64().unwrap();
         let roundup = total/200;
+        let per = ((v+roundup)*100)/total;
+        let info = format!(" ({} %)", per);
+        Ok(format!("{} {:>8}", v, info))
+    };
 
-        println!(
-            "total: {} used: {} ({} %) available: {}",
-            total,
-            used,
-            ((used+roundup)*100)/total,
-            avail,
-        );
-    } else {
-        format_and_print_result(data, &output_format);
-    }
+    let options = default_table_format_options()
+        .noheader(true)
+        .column(ColumnConfig::new("total").renderer(render_total_percentage))
+        .column(ColumnConfig::new("used").renderer(render_total_percentage))
+        .column(ColumnConfig::new("avail").renderer(render_total_percentage));
+
+    let schema = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_STATUS;
+
+    format_and_print_result_full(&mut data, schema, &output_format, &options);
 
     Ok(Value::Null)
 }
@@ -1465,7 +1512,18 @@ async fn status(param: Value) -> Result<Value, Error> {
 // like get, but simply ignore errors and return Null instead
 async fn try_get(repo: &BackupRepository, url: &str) -> Value {
 
-    let client = match HttpClient::new(repo.host(), repo.user(), None) {
+    let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
+    let password = std::env::var(ENV_VAR_PBS_PASSWORD).ok();
+
+    let options = HttpClientOptions::new()
+        .prefix(Some("proxmox-backup".to_string()))
+        .password(password)
+        .interactive(false)
+        .fingerprint(fingerprint)
+        .fingerprint_cache(true)
+        .ticket_cache(true);
+
+    let client = match HttpClient::new(repo.host(), repo.user(), options) {
         Ok(v) => v,
         _ => return Value::Null,
     };
@@ -1484,7 +1542,7 @@ async fn try_get(repo: &BackupRepository, url: &str) -> Value {
 }
 
 fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
-    async_main(async { complete_backup_group_do(param).await })
+    proxmox_backup::tools::runtime::main(async { complete_backup_group_do(param).await })
 }
 
 async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> {
@@ -1514,7 +1572,7 @@ async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String
 }
 
 fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
-    async_main(async { complete_group_or_snapshot_do(arg, param).await })
+    proxmox_backup::tools::runtime::main(async { complete_group_or_snapshot_do(arg, param).await })
 }
 
 async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
@@ -1533,7 +1591,7 @@ async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String
 }
 
 fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
-    async_main(async { complete_backup_snapshot_do(param).await })
+    proxmox_backup::tools::runtime::main(async { complete_backup_snapshot_do(param).await })
 }
 
 async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> {
@@ -1564,7 +1622,7 @@ async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<Str
 }
 
 fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
-    async_main(async { complete_server_file_name_do(param).await })
+    proxmox_backup::tools::runtime::main(async { complete_server_file_name_do(param).await })
 }
 
 async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> {
@@ -1610,7 +1668,7 @@ async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<St
 fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
     complete_server_file_name(arg, param)
         .iter()
-        .map(|v| strip_server_file_expenstion(&v))
+        .map(|v| tools::format::strip_server_file_expenstion(&v))
         .collect()
 }
 
@@ -1618,7 +1676,7 @@ fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec
     complete_server_file_name(arg, param)
         .iter()
         .filter_map(|v| {
-            let name = strip_server_file_expenstion(&v);
+            let name = tools::format::strip_server_file_expenstion(&v);
             if name.ends_with(".pxar") {
                 Some(name)
             } else {
@@ -1656,8 +1714,8 @@ fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
     }
 
     // If we're on a TTY, query the user for a password
-    if crate::tools::tty::stdin_isatty() {
-        return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?);
+    if tty::stdin_isatty() {
+        return Ok(tty::read_password("Encryption Key Password: ")?);
     }
 
     bail!("no password input mechanism available");
@@ -1678,11 +1736,11 @@ fn key_create(
 
     if kdf == "scrypt" {
         // always read passphrase from tty
-        if !crate::tools::tty::stdin_isatty() {
+        if !tty::stdin_isatty() {
             bail!("unable to read passphrase - no tty");
         }
 
-        let password = crate::tools::tty::read_password("Encryption Key Password: ")?;
+        let password = tty::read_and_verify_password("Encryption Key Password: ")?;
 
         let key_config = encrypt_key_with_passphrase(&key, &password)?;
 
@@ -1745,23 +1803,15 @@ fn key_create_master_key(
 ) -> Result<Value, Error> {
 
     // we need a TTY to query the new password
-    if !crate::tools::tty::stdin_isatty() {
+    if !tty::stdin_isatty() {
         bail!("unable to create master key - no tty");
     }
 
     let rsa = openssl::rsa::Rsa::generate(4096)?;
     let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
 
-    let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?;
-    let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
 
-    if new_pw != verify_pw {
-        bail!("Password verification fail!");
-    }
-
-    if new_pw.len() < 5 {
-        bail!("Password is too short!");
-    }
+    let password = String::from_utf8(tty::read_and_verify_password("Master Key Password: ")?)?;
 
     let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
     let filename_pub = "master-public.pem";
@@ -1769,7 +1819,7 @@ fn key_create_master_key(
     replace_file(filename_pub, pub_key.as_slice(), CreateOptions::new())?;
 
     let cipher = openssl::symm::Cipher::aes_256_cbc();
-    let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?;
+    let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, password.as_bytes())?;
 
     let filename_priv = "master-private.pem";
     println!("Writing private master key to {}", filename_priv);
@@ -1790,26 +1840,17 @@ fn key_change_passphrase(
     let kdf = param["kdf"].as_str().unwrap_or("scrypt");
 
     // we need a TTY to query the new password
-    if !crate::tools::tty::stdin_isatty() {
+    if !tty::stdin_isatty() {
         bail!("unable to change passphrase - no tty");
     }
 
-    let (key, created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
+    let (key, created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
 
     if kdf == "scrypt" {
 
-        let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?;
-        let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
-
-        if new_pw != verify_pw {
-            bail!("Password verification fail!");
-        }
-
-        if new_pw.len() < 5 {
-            bail!("Password is too short!");
-        }
+        let password = tty::read_and_verify_password("New Password: ")?;
 
-        let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?;
+        let mut new_key_config = encrypt_key_with_passphrase(&key, &password)?;
         new_key_config.created = created; // keep original value
 
         store_key_config(&path, true, new_key_config)?;
@@ -1835,7 +1876,9 @@ fn key_mgmt_cli() -> CliCommandMap {
 
     const KDF_SCHEMA: Schema =
         StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.")
-        .format(&ApiStringFormat::Enum(&["scrypt", "none"]))
+        .format(&ApiStringFormat::Enum(&[
+            EnumEntry::new("scrypt", "SCrypt"),
+            EnumEntry::new("none", "Do not encrypt the key")]))
         .default("scrypt")
         .schema();
 
@@ -1907,7 +1950,7 @@ fn mount(
     if verbose {
         // This will stay in foreground with debug output enabled as None is
         // passed for the RawFd.
-        return async_main(mount_do(param, None));
+        return proxmox_backup::tools::runtime::main(mount_do(param, None));
     }
 
     // Process should be deamonized.
@@ -1923,17 +1966,52 @@ fn mount(
         Ok(ForkResult::Child) => {
             nix::unistd::close(pipe.0).unwrap();
             nix::unistd::setsid().unwrap();
-            async_main(mount_do(param, Some(pipe.1)))
+            proxmox_backup::tools::runtime::main(mount_do(param, Some(pipe.1)))
         }
         Err(_) => bail!("failed to daemonize process"),
     }
 }
 
+use proxmox_backup::client::RemoteChunkReader;
+/// This is a workaround until we have cleaned up the chunk/reader/... infrastructure for better
+/// async use!
+///
+/// Ideally BufferedDynamicReader gets replaced so the LruCache maps to `BroadcastFuture<Chunk>`,
+/// so that we can properly access it from multiple threads simultaneously while not issuing
+/// duplicate simultaneous reads over http.
+struct BufferedDynamicReadAt {
+    inner: Mutex<BufferedDynamicReader<RemoteChunkReader>>,
+}
+
+impl BufferedDynamicReadAt {
+    fn new(inner: BufferedDynamicReader<RemoteChunkReader>) -> Self {
+        Self {
+            inner: Mutex::new(inner),
+        }
+    }
+}
+
+impl pxar::accessor::ReadAt for BufferedDynamicReadAt {
+    fn poll_read_at(
+        self: Pin<&Self>,
+        _cx: &mut Context,
+        buf: &mut [u8],
+        offset: u64,
+    ) -> Poll<io::Result<usize>> {
+        use std::io::Read;
+        tokio::task::block_in_place(move || {
+            let mut reader = self.inner.lock().unwrap();
+            reader.seek(SeekFrom::Start(offset))?;
+            Poll::Ready(Ok(reader.read(buf)?))
+        })
+    }
+}
+
 async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
     let repo = extract_repository_from_value(&param)?;
     let archive_name = tools::required_string_param(&param, "archive-name")?;
     let target = tools::required_string_param(&param, "target")?;
-    let client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let client = connect(repo.host(), repo.user())?;
 
     record_repository(&repo);
 
@@ -1950,7 +2028,7 @@ async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
     let crypt_config = match keyfile {
         None => None,
         Some(path) => {
-            let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
+            let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
             Some(Arc::new(CryptConfig::new(key)?))
         }
     };
@@ -1978,19 +2056,23 @@ async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
         let most_used = index.find_most_used_chunks(8);
         let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
         let reader = BufferedDynamicReader::new(index, chunk_reader);
-        let decoder = pxar::Decoder::new(reader)?;
+        let archive_size = reader.archive_size();
+        let reader: proxmox_backup::pxar::fuse::Reader =
+            Arc::new(BufferedDynamicReadAt::new(reader));
+        let decoder = proxmox_backup::pxar::fuse::Accessor::new(reader, archive_size).await?;
         let options = OsStr::new("ro,default_permissions");
-        let mut session = pxar::fuse::Session::new(decoder, &options, pipe.is_none())
-            .map_err(|err| format_err!("pxar mount failed: {}", err))?;
 
-        // Mount the session but not call fuse deamonize as this will cause
-        // issues with the runtime after the fork
-        let deamonize = false;
-        session.mount(&Path::new(target), deamonize)?;
+        let session = proxmox_backup::pxar::fuse::Session::mount(
+            decoder,
+            &options,
+            false,
+            Path::new(target),
+        )
+        .map_err(|err| format_err!("pxar mount failed: {}", err))?;
 
         if let Some(pipe) = pipe {
             nix::unistd::chdir(Path::new("/")).unwrap();
-            // Finish creation of deamon by redirecting filedescriptors.
+            // Finish creation of daemon by redirecting filedescriptors.
             let nullfd = nix::fcntl::open(
                 "/dev/null",
                 nix::fcntl::OFlag::O_RDWR,
@@ -2008,8 +2090,13 @@ async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
             nix::unistd::close(pipe).unwrap();
         }
 
-        let multithreaded = true;
-        session.run_loop(multithreaded)?;
+        let mut interrupt = signal(SignalKind::interrupt())?;
+        select! {
+            res = session.fuse() => res?,
+            _ = interrupt.recv().fuse() => {
+                // exit on interrupted
+            }
+        }
     } else {
         bail!("unknown archive file extension (expected .pxar)");
     }
@@ -2043,7 +2130,7 @@ async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
 /// Shell to interactively inspect and restore snapshots.
 async fn catalog_shell(param: Value) -> Result<(), Error> {
     let repo = extract_repository_from_value(&param)?;
-    let client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let client = connect(repo.host(), repo.user())?;
     let path = tools::required_string_param(&param, "snapshot")?;
     let archive_name = tools::required_string_param(&param, "archive-name")?;
 
@@ -2059,7 +2146,7 @@ async fn catalog_shell(param: Value) -> Result<(), Error> {
     let crypt_config = match keyfile {
         None => None,
         Some(path) => {
-            let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
+            let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
             Some(Arc::new(CryptConfig::new(key)?))
         }
     };
@@ -2092,11 +2179,10 @@ async fn catalog_shell(param: Value) -> Result<(), Error> {
     let most_used = index.find_most_used_chunks(8);
     let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config.clone(), most_used);
     let reader = BufferedDynamicReader::new(index, chunk_reader);
-    let mut decoder = pxar::Decoder::new(reader)?;
-    decoder.set_callback(|path| {
-        println!("{:?}", path);
-        Ok(())
-    });
+    let archive_size = reader.archive_size();
+    let reader: proxmox_backup::pxar::fuse::Reader =
+        Arc::new(BufferedDynamicReadAt::new(reader));
+    let decoder = proxmox_backup::pxar::fuse::Accessor::new(reader, archive_size).await?;
 
     let tmpfile = client.download(CATALOG_NAME, tmpfile).await?;
     let index = DynamicIndexReader::new(tmpfile)
@@ -2124,10 +2210,10 @@ async fn catalog_shell(param: Value) -> Result<(), Error> {
         catalog_reader,
         &server_archive_name,
         decoder,
-    )?;
+    ).await?;
 
     println!("Starting interactive shell");
-    state.shell()?;
+    state.shell().await?;
 
     record_repository(&repo);
 
@@ -2170,40 +2256,45 @@ fn catalog_mgmt_cli() -> CliCommandMap {
                 schema: OUTPUT_FORMAT,
                 optional: true,
             },
+            all: {
+                type: Boolean,
+                description: "Also list stopped tasks.",
+                optional: true,
+            },
         }
     }
 )]
 /// List running server tasks for this repo user
 async fn task_list(param: Value) -> Result<Value, Error> {
 
-    let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
+    let output_format = get_output_format(&param);
+
     let repo = extract_repository_from_value(&param)?;
-    let client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let client = connect(repo.host(), repo.user())?;
 
     let limit = param["limit"].as_u64().unwrap_or(50) as usize;
+    let running = !param["all"].as_bool().unwrap_or(false);
 
     let args = json!({
-        "running": true,
+        "running": running,
         "start": 0,
         "limit": limit,
         "userfilter": repo.user(),
         "store": repo.store(),
     });
-    let result = client.get("api2/json/nodes/localhost/tasks", Some(args)).await?;
 
-    let data = &result["data"];
+    let mut result = client.get("api2/json/nodes/localhost/tasks", Some(args)).await?;
+    let mut data = result["data"].take();
 
-    if output_format == "text" {
-        for item in data.as_array().unwrap() {
-            println!(
-                "{} {}",
-                item["upid"].as_str().unwrap(),
-                item["status"].as_str().unwrap_or("running"),
-            );
-        }
-    } else {
-        format_and_print_result(data, &output_format);
-    }
+    let schema = &proxmox_backup::api2::node::tasks::API_RETURN_SCHEMA_LIST_TASKS;
+
+    let options = default_table_format_options()
+        .column(ColumnConfig::new("starttime").right_align(false).renderer(tools::format::render_epoch))
+        .column(ColumnConfig::new("endtime").right_align(false).renderer(tools::format::render_epoch))
+        .column(ColumnConfig::new("upid"))
+        .column(ColumnConfig::new("status").renderer(tools::format::render_task_status));
+
+    format_and_print_result_full(&mut data, schema, &output_format, &options);
 
     Ok(Value::Null)
 }
@@ -2227,7 +2318,7 @@ async fn task_log(param: Value) -> Result<Value, Error> {
     let repo = extract_repository_from_value(&param)?;
     let upid =  tools::required_string_param(&param, "upid")?;
 
-    let client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let client = connect(repo.host(), repo.user())?;
 
     display_task_log(client, upid, true).await?;
 
@@ -2253,7 +2344,7 @@ async fn task_stop(param: Value) -> Result<Value, Error> {
     let repo = extract_repository_from_value(&param)?;
     let upid_str =  tools::required_string_param(&param, "upid")?;
 
-    let mut client = HttpClient::new(repo.host(), repo.user(), None)?;
+    let mut client = connect(repo.host(), repo.user())?;
 
     let path = format!("api2/json/nodes/localhost/tasks/{}", upid_str);
     let _ = client.delete(&path, None).await?;
@@ -2378,13 +2469,8 @@ fn main() {
         .insert("catalog", catalog_mgmt_cli())
         .insert("task", task_mgmt_cli());
 
-    run_cli_command(cmd_def);
-}
-
-fn async_main<F: Future>(fut: F) -> <F as Future>::Output {
-    let mut rt = tokio::runtime::Runtime::new().unwrap();
-    let ret = rt.block_on(fut);
-    // This does not exist anymore. We need to actually stop our runaways instead...
-    // rt.shutdown_now();
-    ret
+    let rpcenv = CliEnvironment::new();
+    run_cli_command(cmd_def, rpcenv, Some(|future| {
+        proxmox_backup::tools::runtime::main(future)
+    }));
 }