use std::collections::{HashSet, HashMap};
-use std::ffi::OsStr;
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 std::task::Context;
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::*;
use proxmox::api::api;
+use pxar::accessor::{MaybeReady, ReadAt, ReadAtOperation};
use proxmox_backup::tools;
use proxmox_backup::api2::types::*;
use proxmox_backup::pxar::catalog::*;
use proxmox_backup::backup::{
archive_type,
- encrypt_key_with_passphrase,
load_and_decrypt_key,
- store_key_config,
verify_chunk_size,
ArchiveType,
+ AsyncReadChunk,
BackupDir,
BackupGroup,
BackupManifest,
BufferedDynamicReader,
+ CATALOG_NAME,
CatalogReader,
CatalogWriter,
- CATALOG_NAME,
ChunkStream,
CryptConfig,
+ CryptMode,
DataBlob,
DynamicIndexReader,
FixedChunkStream,
FixedIndexReader,
IndexFile,
- KeyConfig,
MANIFEST_BLOB_NAME,
- ReadChunk,
Shell,
};
+mod proxmox_backup_client;
+use proxmox_backup_client::*;
+
const ENV_VAR_PBS_FINGERPRINT: &str = "PBS_FINGERPRINT";
const ENV_VAR_PBS_PASSWORD: &str = "PBS_PASSWORD";
-const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.")
+pub const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.")
.format(&BACKUP_REPO_URL)
.max_length(256)
.schema();
-const KEYFILE_SCHEMA: Schema = StringSchema::new(
+pub const KEYFILE_SCHEMA: Schema = StringSchema::new(
"Path to encryption key. All data will be encrypted using this key.")
.schema();
std::env::var("PBS_REPOSITORY").ok()
}
-fn extract_repository_from_value(
+pub fn extract_repository_from_value(
param: &Value,
) -> Result<BackupRepository, Error> {
let _ = replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new());
}
-fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
+pub fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
let mut result = vec![];
Ok(result["data"].take())
}
-async fn api_datastore_latest_snapshot(
+pub async fn api_datastore_latest_snapshot(
client: &HttpClient,
store: &str,
group: BackupGroup,
Ok((group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time))
}
-
async fn backup_directory<P: AsRef<Path>>(
client: &BackupWriter,
+ crypt_mode: CryptMode,
+ previous_manifest: Option<Arc<BackupManifest>>,
dir_path: P,
archive_name: &str,
chunk_size: Option<usize>,
device_set: Option<HashSet<u64>>,
verbose: bool,
skip_lost_and_found: bool,
- crypt_config: Option<Arc<CryptConfig>>,
catalog: Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>,
exclude_pattern: Vec<MatchEntry>,
entries_max: usize,
});
let stats = client
- .upload_stream(archive_name, stream, "dynamic", None, crypt_config)
+ .upload_stream(crypt_mode, previous_manifest, archive_name, stream, "dynamic", None)
.await?;
Ok(stats)
async fn backup_image<P: AsRef<Path>>(
client: &BackupWriter,
+ crypt_mode: CryptMode,
+ previous_manifest: Option<Arc<BackupManifest>>,
image_path: P,
archive_name: &str,
image_size: u64,
chunk_size: Option<usize>,
_verbose: bool,
- crypt_config: Option<Arc<CryptConfig>>,
) -> Result<BackupStats, Error> {
let path = image_path.as_ref().to_owned();
let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024));
let stats = client
- .upload_stream(archive_name, stream, "fixed", Some(image_size), crypt_config)
+ .upload_stream(crypt_mode, previous_manifest, archive_name, stream, "fixed", Some(image_size))
.await?;
Ok(stats)
let client = connect(repo.host(), repo.user())?;
- let group = if let Some(path) = param["group"].as_str() {
- Some(BackupGroup::parse(path)?)
+ let group: Option<BackupGroup> = if let Some(path) = param["group"].as_str() {
+ Some(path.parse()?)
} else {
None
};
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 mut filenames = Vec::new();
+ for file in &item.files {
+ filenames.push(file.filename.to_string());
+ }
+ Ok(tools::format::render_backup_file_list(&filenames[..]))
};
let options = default_table_format_options()
let repo = extract_repository_from_value(¶m)?;
let path = tools::required_string_param(¶m, "snapshot")?;
- let snapshot = BackupDir::parse(path)?;
+ let snapshot: BackupDir = path.parse()?;
let mut client = connect(repo.host(), repo.user())?;
Ok(Value::Null)
}
-#[api(
- input: {
- properties: {
- repository: {
- schema: REPO_URL_SCHEMA,
- optional: true,
- },
- snapshot: {
- type: String,
- description: "Snapshot path.",
- },
- }
- }
-)]
-/// Dump catalog.
-async fn dump_catalog(param: Value) -> Result<Value, Error> {
-
- let repo = extract_repository_from_value(¶m)?;
-
- let path = tools::required_string_param(¶m, "snapshot")?;
- let snapshot = BackupDir::parse(path)?;
-
- let keyfile = param["keyfile"].as_str().map(PathBuf::from);
-
- let crypt_config = match keyfile {
- None => None,
- Some(path) => {
- let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
- Some(Arc::new(CryptConfig::new(key)?))
- }
- };
-
- let client = connect(repo.host(), repo.user())?;
-
- let client = BackupReader::start(
- client,
- crypt_config.clone(),
- repo.store(),
- &snapshot.group().backup_type(),
- &snapshot.group().backup_id(),
- snapshot.backup_time(),
- true,
- ).await?;
-
- let manifest = client.download_manifest().await?;
-
- let index = client.download_dynamic_index(&manifest, CATALOG_NAME).await?;
-
- let most_used = index.find_most_used_chunks(8);
-
- let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
-
- let mut reader = BufferedDynamicReader::new(index, chunk_reader);
-
- let mut catalogfile = std::fs::OpenOptions::new()
- .write(true)
- .read(true)
- .custom_flags(libc::O_TMPFILE)
- .open("/tmp")?;
-
- std::io::copy(&mut reader, &mut catalogfile)
- .map_err(|err| format_err!("unable to download catalog - {}", err))?;
-
- catalogfile.seek(SeekFrom::Start(0))?;
-
- let mut catalog_reader = CatalogReader::new(catalogfile);
-
- catalog_reader.dump()?;
-
- record_repository(&repo);
-
- Ok(Value::Null)
-}
#[api(
input: {
let repo = extract_repository_from_value(¶m)?;
let path = tools::required_string_param(¶m, "snapshot")?;
- let snapshot = BackupDir::parse(path)?;
+ let snapshot: BackupDir = path.parse()?;
let output_format = get_output_format(¶m);
fn spawn_catalog_upload(
client: Arc<BackupWriter>,
- crypt_config: Option<Arc<CryptConfig>>,
+ crypt_mode: CryptMode,
) -> Result<
(
Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>,
tokio::spawn(async move {
let catalog_upload_result = client
- .upload_stream(CATALOG_NAME, catalog_chunk_stream, "dynamic", None, crypt_config)
+ .upload_stream(crypt_mode, None, CATALOG_NAME, catalog_chunk_stream, "dynamic", None)
.await;
if let Err(ref err) = catalog_upload_result {
Ok((catalog, catalog_result_rx))
}
+fn keyfile_parameters(param: &Value) -> Result<(Option<PathBuf>, CryptMode), Error> {
+ let keyfile = match param.get("keyfile") {
+ Some(Value::String(keyfile)) => Some(keyfile),
+ Some(_) => bail!("bad --keyfile parameter type"),
+ None => None,
+ };
+
+ let crypt_mode: Option<CryptMode> = match param.get("crypt-mode") {
+ Some(mode) => Some(serde_json::from_value(mode.clone())?),
+ None => None,
+ };
+
+ Ok(match (keyfile, crypt_mode) {
+ // no parameters:
+ (None, None) => (key::optional_default_key_path()?, CryptMode::Encrypt),
+
+ // just --crypt-mode=none
+ (None, Some(CryptMode::None)) => (None, CryptMode::None),
+
+ // just --crypt-mode other than none
+ (None, Some(crypt_mode)) => match key::optional_default_key_path()? {
+ None => bail!("--crypt-mode without --keyfile and no default key file available"),
+ Some(path) => (Some(path), crypt_mode),
+ }
+
+ // just --keyfile
+ (Some(keyfile), None) => (Some(PathBuf::from(keyfile)), CryptMode::Encrypt),
+
+ // --keyfile and --crypt-mode=none
+ (Some(_), Some(CryptMode::None)) => {
+ bail!("--keyfile and --crypt-mode=none are mutually exclusive");
+ }
+
+ // --keyfile and --crypt-mode other than none
+ (Some(keyfile), Some(crypt_mode)) => (Some(PathBuf::from(keyfile)), crypt_mode),
+ })
+}
+
#[api(
input: {
properties: {
schema: KEYFILE_SCHEMA,
optional: true,
},
+ "crypt-mode": {
+ type: CryptMode,
+ optional: true,
+ },
"skip-lost-and-found": {
type: Boolean,
description: "Skip lost+found directory.",
verify_chunk_size(size)?;
}
- let keyfile = param["keyfile"].as_str().map(PathBuf::from);
+ let (keyfile, crypt_mode) = keyfile_parameters(¶m)?;
let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename());
let (crypt_config, rsa_encrypted_key) = match keyfile {
None => (None, None),
Some(path) => {
- let (key, created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
+ let (key, created) = load_and_decrypt_key(&path, &key::get_encryption_key_password)?;
let crypt_config = CryptConfig::new(key)?;
let client = BackupWriter::start(
client,
+ crypt_config.clone(),
repo.store(),
backup_type,
&backup_id,
verbose,
).await?;
+ let previous_manifest = if let Ok(previous_manifest) = client.download_previous_manifest().await {
+ Some(Arc::new(previous_manifest))
+ } else {
+ None
+ };
+
let snapshot = BackupDir::new(backup_type, backup_id, backup_time.timestamp());
let mut manifest = BackupManifest::new(snapshot);
BackupSpecificationType::CONFIG => {
println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target);
let stats = client
- .upload_blob_from_file(&filename, &target, crypt_config.clone(), true)
+ .upload_blob_from_file(&filename, &target, true, crypt_mode)
.await?;
- manifest.add_file(target, stats.size, stats.csum)?;
+ manifest.add_file(target, stats.size, stats.csum, crypt_mode)?;
}
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)
+ .upload_blob_from_file(&filename, &target, true, crypt_mode)
.await?;
- manifest.add_file(target, stats.size, stats.csum)?;
+ manifest.add_file(target, stats.size, stats.csum, crypt_mode)?;
}
BackupSpecificationType::PXAR => {
// start catalog upload on first use
if catalog.is_none() {
- let (cat, res) = spawn_catalog_upload(client.clone(), crypt_config.clone())?;
+ let (cat, res) = spawn_catalog_upload(client.clone(), crypt_mode)?;
catalog = Some(cat);
catalog_result_tx = Some(res);
}
catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?;
let stats = backup_directory(
&client,
+ crypt_mode,
+ previous_manifest.clone(),
&filename,
&target,
chunk_size_opt,
devices.clone(),
verbose,
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)?;
+ manifest.add_file(target, stats.size, stats.csum, crypt_mode)?;
catalog.lock().unwrap().end_directory()?;
}
BackupSpecificationType::IMAGE => {
println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
let stats = backup_image(
&client,
- &filename,
+ crypt_mode,
+ previous_manifest.clone(),
+ &filename,
&target,
size,
chunk_size_opt,
verbose,
- crypt_config.clone(),
).await?;
- manifest.add_file(target, stats.size, stats.csum)?;
+ manifest.add_file(target, stats.size, stats.csum, crypt_mode)?;
}
}
}
if let Some(catalog_result_rx) = catalog_result_tx {
let stats = catalog_result_rx.await??;
- manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum)?;
+ manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum, crypt_mode)?;
}
}
let target = "rsa-encrypted.key";
println!("Upload RSA encoded key to '{:?}' as {}", repo, target);
let stats = client
- .upload_blob_from_data(rsa_encrypted_key, target, None, false, false)
+ .upload_blob_from_data(rsa_encrypted_key, target, false, CryptMode::None)
.await?;
- manifest.add_file(format!("{}.blob", target), stats.size, stats.csum)?;
+ manifest.add_file(format!("{}.blob", target), stats.size, stats.csum, crypt_mode)?;
// openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t
/*
println!("Upload index.json to '{:?}'", repo);
let manifest = serde_json::to_string_pretty(&manifest)?.into();
+ // manifests are never encrypted
+ let manifest_crypt_mode = match crypt_mode {
+ CryptMode::None => CryptMode::None,
+ _ => CryptMode::SignOnly,
+ };
client
- .upload_blob_from_data(manifest, MANIFEST_BLOB_NAME, crypt_config.clone(), true, true)
+ .upload_blob_from_data(manifest, MANIFEST_BLOB_NAME, true, manifest_crypt_mode)
.await?;
client.finish().await?;
result
}
-fn dump_image<W: Write>(
+async fn dump_image<W: Write>(
client: Arc<BackupReader>,
crypt_config: Option<Arc<CryptConfig>>,
index: FixedIndexReader,
let most_used = index.find_most_used_chunks(8);
- let mut chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
+ let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
// Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy
// and thus slows down reading. Instead, directly use RemoteChunkReader
for pos in 0..index.index_count() {
let digest = index.index_digest(pos).unwrap();
- let raw_data = chunk_reader.read_chunk(&digest)?;
+ let raw_data = chunk_reader.read_chunk(&digest).await?;
writer.write_all(&raw_data)?;
bytes += raw_data.len();
if verbose {
schema: KEYFILE_SCHEMA,
optional: true,
},
+ "crypt-mode": {
+ type: CryptMode,
+ optional: true,
+ },
}
}
)]
let path = tools::required_string_param(¶m, "snapshot")?;
let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
- let group = BackupGroup::parse(path)?;
+ let group: BackupGroup = path.parse()?;
api_datastore_latest_snapshot(&client, repo.store(), group).await?
} else {
- let snapshot = BackupDir::parse(path)?;
+ let snapshot: BackupDir = path.parse()?;
(snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
};
let target = tools::required_string_param(¶m, "target")?;
let target = if target == "-" { None } else { Some(target) };
- let keyfile = param["keyfile"].as_str().map(PathBuf::from);
+ let (keyfile, _crypt_mode) = keyfile_parameters(¶m)?;
let crypt_config = match keyfile {
None => None,
Some(path) => {
- let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
+ let (key, _) = load_and_decrypt_key(&path, &key::get_encryption_key_password)?;
Some(Arc::new(CryptConfig::new(key)?))
}
};
.map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?
};
- dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose)?;
+ dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose).await?;
}
Ok(Value::Null)
schema: KEYFILE_SCHEMA,
optional: true,
},
+ "crypt-mode": {
+ type: CryptMode,
+ optional: true,
+ },
}
}
)]
let repo = extract_repository_from_value(¶m)?;
let snapshot = tools::required_string_param(¶m, "snapshot")?;
- let snapshot = BackupDir::parse(snapshot)?;
+ let snapshot: BackupDir = snapshot.parse()?;
let mut client = connect(repo.host(), repo.user())?;
- let keyfile = param["keyfile"].as_str().map(PathBuf::from);
+ let (keyfile, crypt_mode) = keyfile_parameters(¶m)?;
let crypt_config = match keyfile {
None => None,
Some(path) => {
- let (key, _created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
+ let (key, _created) = load_and_decrypt_key(&path, &key::get_encryption_key_password)?;
let crypt_config = CryptConfig::new(key)?;
Some(Arc::new(crypt_config))
}
let data = file_get_contents(logfile)?;
- let blob = DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?;
+ let blob = match crypt_mode {
+ CryptMode::None => DataBlob::encode(&data, None, true)?,
+ CryptMode::Encrypt => {
+ DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?
+ }
+ CryptMode::SignOnly => DataBlob::create_signed(
+ &data,
+ crypt_config
+ .ok_or_else(|| format_err!("cannot sign without crypt config"))?
+ .as_ref(),
+ true,
+ )?,
+ };
let raw_data = blob.into_inner();
let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
let group = tools::required_string_param(¶m, "group")?;
- let group = BackupGroup::parse(group)?;
+ let group: BackupGroup = group.parse()?;
let output_format = get_output_format(¶m);
result
}
-fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
+pub fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
proxmox_backup::tools::runtime::main(async { complete_group_or_snapshot_do(arg, param).await })
}
_ => return result,
};
- let snapshot = match param.get("snapshot") {
+ let snapshot: BackupDir = match param.get("snapshot") {
Some(path) => {
- match BackupDir::parse(path) {
+ match path.parse() {
Ok(v) => v,
_ => return result,
}
.collect()
}
-fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
+pub fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
complete_server_file_name(arg, param)
.iter()
.filter_map(|v| {
result
}
-fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
-
- // fixme: implement other input methods
-
- use std::env::VarError::*;
- match std::env::var("PBS_ENCRYPTION_PASSWORD") {
- Ok(p) => return Ok(p.as_bytes().to_vec()),
- Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
- Err(NotPresent) => {
- // Try another method
- }
- }
-
- // If we're on a TTY, query the user for a password
- if tty::stdin_isatty() {
- return Ok(tty::read_password("Encryption Key Password: ")?);
- }
-
- bail!("no password input mechanism available");
-}
-
-fn key_create(
- param: Value,
- _info: &ApiMethod,
- _rpcenv: &mut dyn RpcEnvironment,
-) -> Result<Value, Error> {
-
- let path = tools::required_string_param(¶m, "path")?;
- let path = PathBuf::from(path);
-
- let kdf = param["kdf"].as_str().unwrap_or("scrypt");
-
- let key = proxmox::sys::linux::random_data(32)?;
-
- if kdf == "scrypt" {
- // always read passphrase from tty
- if !tty::stdin_isatty() {
- bail!("unable to read passphrase - no tty");
- }
-
- let password = tty::read_and_verify_password("Encryption Key Password: ")?;
-
- let key_config = encrypt_key_with_passphrase(&key, &password)?;
-
- store_key_config(&path, false, key_config)?;
-
- Ok(Value::Null)
- } else if kdf == "none" {
- let created = Local.timestamp(Local::now().timestamp(), 0);
-
- store_key_config(&path, false, KeyConfig {
- kdf: None,
- created,
- modified: created,
- data: key,
- })?;
-
- Ok(Value::Null)
- } else {
- unreachable!();
- }
-}
-
fn master_pubkey_path() -> Result<PathBuf, Error> {
let base = BaseDirectories::with_prefix("proxmox-backup")?;
Ok(path)
}
-fn key_import_master_pubkey(
- param: Value,
- _info: &ApiMethod,
- _rpcenv: &mut dyn RpcEnvironment,
-) -> Result<Value, Error> {
-
- let path = tools::required_string_param(¶m, "path")?;
- let path = PathBuf::from(path);
-
- let pem_data = file_get_contents(&path)?;
-
- if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
- bail!("Unable to decode PEM data - {}", err);
- }
-
- let target_path = master_pubkey_path()?;
-
- replace_file(&target_path, &pem_data, CreateOptions::new())?;
-
- println!("Imported public master key to {:?}", target_path);
-
- Ok(Value::Null)
-}
-
-fn key_create_master_key(
- _param: Value,
- _info: &ApiMethod,
- _rpcenv: &mut dyn RpcEnvironment,
-) -> Result<Value, Error> {
-
- // we need a TTY to query the new password
- 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 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";
- println!("Writing public master key to {}", filename_pub);
- 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, password.as_bytes())?;
-
- let filename_priv = "master-private.pem";
- println!("Writing private master key to {}", filename_priv);
- replace_file(filename_priv, priv_key.as_slice(), CreateOptions::new())?;
-
- Ok(Value::Null)
-}
-
-fn key_change_passphrase(
- param: Value,
- _info: &ApiMethod,
- _rpcenv: &mut dyn RpcEnvironment,
-) -> Result<Value, Error> {
-
- let path = tools::required_string_param(¶m, "path")?;
- let path = PathBuf::from(path);
-
- let kdf = param["kdf"].as_str().unwrap_or("scrypt");
-
- // we need a TTY to query the new password
- if !tty::stdin_isatty() {
- bail!("unable to change passphrase - no tty");
- }
-
- let (key, created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
-
- if kdf == "scrypt" {
-
- let password = tty::read_and_verify_password("New Password: ")?;
-
- 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)?;
-
- Ok(Value::Null)
- } else if kdf == "none" {
- let modified = Local.timestamp(Local::now().timestamp(), 0);
-
- store_key_config(&path, true, KeyConfig {
- kdf: None,
- created, // keep original value
- modified,
- data: key.to_vec(),
- })?;
-
- Ok(Value::Null)
- } else {
- unreachable!();
- }
-}
-
-fn key_mgmt_cli() -> CliCommandMap {
-
- const KDF_SCHEMA: Schema =
- StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.")
- .format(&ApiStringFormat::Enum(&[
- EnumEntry::new("scrypt", "SCrypt"),
- EnumEntry::new("none", "Do not encrypt the key")]))
- .default("scrypt")
- .schema();
-
- #[sortable]
- const API_METHOD_KEY_CREATE: ApiMethod = ApiMethod::new(
- &ApiHandler::Sync(&key_create),
- &ObjectSchema::new(
- "Create a new encryption key.",
- &sorted!([
- ("path", false, &StringSchema::new("File system path.").schema()),
- ("kdf", true, &KDF_SCHEMA),
- ]),
- )
- );
-
- let key_create_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE)
- .arg_param(&["path"])
- .completion_cb("path", tools::complete_file_name);
-
- #[sortable]
- const API_METHOD_KEY_CHANGE_PASSPHRASE: ApiMethod = ApiMethod::new(
- &ApiHandler::Sync(&key_change_passphrase),
- &ObjectSchema::new(
- "Change the passphrase required to decrypt the key.",
- &sorted!([
- ("path", false, &StringSchema::new("File system path.").schema()),
- ("kdf", true, &KDF_SCHEMA),
- ]),
- )
- );
-
- let key_change_passphrase_cmd_def = CliCommand::new(&API_METHOD_KEY_CHANGE_PASSPHRASE)
- .arg_param(&["path"])
- .completion_cb("path", tools::complete_file_name);
-
- const API_METHOD_KEY_CREATE_MASTER_KEY: ApiMethod = ApiMethod::new(
- &ApiHandler::Sync(&key_create_master_key),
- &ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.", &[])
- );
-
- let key_create_master_key_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE_MASTER_KEY);
-
- #[sortable]
- const API_METHOD_KEY_IMPORT_MASTER_PUBKEY: ApiMethod = ApiMethod::new(
- &ApiHandler::Sync(&key_import_master_pubkey),
- &ObjectSchema::new(
- "Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.",
- &sorted!([ ("path", false, &StringSchema::new("File system path.").schema()) ]),
- )
- );
-
- let key_import_master_pubkey_cmd_def = CliCommand::new(&API_METHOD_KEY_IMPORT_MASTER_PUBKEY)
- .arg_param(&["path"])
- .completion_cb("path", tools::complete_file_name);
-
- CliCommandMap::new()
- .insert("create", key_create_cmd_def)
- .insert("create-master-key", key_create_master_key_cmd_def)
- .insert("import-master-pubkey", key_import_master_pubkey_cmd_def)
- .insert("change-passphrase", key_change_passphrase_cmd_def)
-}
-
-fn mount(
- param: Value,
- _info: &ApiMethod,
- _rpcenv: &mut dyn RpcEnvironment,
-) -> Result<Value, Error> {
- let verbose = param["verbose"].as_bool().unwrap_or(false);
- if verbose {
- // This will stay in foreground with debug output enabled as None is
- // passed for the RawFd.
- return proxmox_backup::tools::runtime::main(mount_do(param, None));
- }
-
- // Process should be deamonized.
- // Make sure to fork before the async runtime is instantiated to avoid troubles.
- let pipe = pipe()?;
- match fork() {
- Ok(ForkResult::Parent { .. }) => {
- nix::unistd::close(pipe.1).unwrap();
- // Blocks the parent process until we are ready to go in the child
- let _res = nix::unistd::read(pipe.0, &mut [0]).unwrap();
- Ok(Value::Null)
- }
- Ok(ForkResult::Child) => {
- nix::unistd::close(pipe.0).unwrap();
- nix::unistd::setsid().unwrap();
- 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 {
+pub struct BufferedDynamicReadAt {
inner: Mutex<BufferedDynamicReader<RemoteChunkReader>>,
}
}
}
-impl pxar::accessor::ReadAt for BufferedDynamicReadAt {
- fn poll_read_at(
- self: Pin<&Self>,
+impl ReadAt for BufferedDynamicReadAt {
+ fn start_read_at<'a>(
+ self: Pin<&'a Self>,
_cx: &mut Context,
- buf: &mut [u8],
+ buf: &'a mut [u8],
offset: u64,
- ) -> Poll<io::Result<usize>> {
+ ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> {
use std::io::Read;
- tokio::task::block_in_place(move || {
+ MaybeReady::Ready(tokio::task::block_in_place(move || {
let mut reader = self.inner.lock().unwrap();
reader.seek(SeekFrom::Start(offset))?;
- Poll::Ready(Ok(reader.read(buf)?))
- })
+ Ok(reader.read(buf)?)
+ }))
}
-}
-
-async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
- let repo = extract_repository_from_value(¶m)?;
- let archive_name = tools::required_string_param(¶m, "archive-name")?;
- let target = tools::required_string_param(¶m, "target")?;
- let client = connect(repo.host(), repo.user())?;
-
- record_repository(&repo);
- let path = tools::required_string_param(¶m, "snapshot")?;
- let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
- let group = BackupGroup::parse(path)?;
- api_datastore_latest_snapshot(&client, repo.store(), group).await?
- } else {
- let snapshot = BackupDir::parse(path)?;
- (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
- };
-
- let keyfile = param["keyfile"].as_str().map(PathBuf::from);
- let crypt_config = match keyfile {
- None => None,
- Some(path) => {
- 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 {
- bail!("Can only mount pxar archives.");
- };
-
- let client = BackupReader::start(
- client,
- crypt_config.clone(),
- repo.store(),
- &backup_type,
- &backup_id,
- backup_time,
- true,
- ).await?;
-
- let manifest = client.download_manifest().await?;
-
- if server_archive_name.ends_with(".didx") {
- let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
- 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 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 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 daemon by redirecting filedescriptors.
- let nullfd = nix::fcntl::open(
- "/dev/null",
- nix::fcntl::OFlag::O_RDWR,
- nix::sys::stat::Mode::empty(),
- ).unwrap();
- nix::unistd::dup2(nullfd, 0).unwrap();
- nix::unistd::dup2(nullfd, 1).unwrap();
- nix::unistd::dup2(nullfd, 2).unwrap();
- if nullfd > 2 {
- nix::unistd::close(nullfd).unwrap();
- }
- // Signal the parent process that we are done with the setup and it can
- // terminate.
- nix::unistd::write(pipe, &[0u8])?;
- nix::unistd::close(pipe).unwrap();
- }
-
- 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)");
- }
-
- Ok(Value::Null)
-}
-
-#[api(
- input: {
- properties: {
- "snapshot": {
- type: String,
- description: "Group/Snapshot path.",
- },
- "archive-name": {
- type: String,
- description: "Backup archive name.",
- },
- "repository": {
- optional: true,
- schema: REPO_URL_SCHEMA,
- },
- "keyfile": {
- optional: true,
- type: String,
- description: "Path to encryption key.",
- },
- },
- },
-)]
-/// Shell to interactively inspect and restore snapshots.
-async fn catalog_shell(param: Value) -> Result<(), Error> {
- let repo = extract_repository_from_value(¶m)?;
- let client = connect(repo.host(), repo.user())?;
- let path = tools::required_string_param(¶m, "snapshot")?;
- let archive_name = tools::required_string_param(¶m, "archive-name")?;
-
- let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
- let group = BackupGroup::parse(path)?;
- api_datastore_latest_snapshot(&client, repo.store(), group).await?
- } else {
- let snapshot = BackupDir::parse(path)?;
- (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
- };
-
- let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
- let crypt_config = match keyfile {
- None => None,
- Some(path) => {
- 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 {
- bail!("Can only mount pxar archives.");
- };
-
- let client = BackupReader::start(
- client,
- crypt_config.clone(),
- repo.store(),
- &backup_type,
- &backup_id,
- backup_time,
- true,
- ).await?;
-
- let tmpfile = std::fs::OpenOptions::new()
- .write(true)
- .read(true)
- .custom_flags(libc::O_TMPFILE)
- .open("/tmp")?;
-
- let manifest = client.download_manifest().await?;
-
- let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
- 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 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)
- .map_err(|err| format_err!("unable to read catalog index - {}", err))?;
-
- // Note: do not use values stored in index (not trusted) - instead, computed them again
- let (csum, size) = index.compute_csum();
- manifest.verify_file(CATALOG_NAME, &csum, size)?;
-
- let most_used = index.find_most_used_chunks(8);
- let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
- let mut reader = BufferedDynamicReader::new(index, chunk_reader);
- let mut catalogfile = std::fs::OpenOptions::new()
- .write(true)
- .read(true)
- .custom_flags(libc::O_TMPFILE)
- .open("/tmp")?;
-
- std::io::copy(&mut reader, &mut catalogfile)
- .map_err(|err| format_err!("unable to download catalog - {}", err))?;
-
- catalogfile.seek(SeekFrom::Start(0))?;
- let catalog_reader = CatalogReader::new(catalogfile);
- let state = Shell::new(
- catalog_reader,
- &server_archive_name,
- decoder,
- ).await?;
-
- println!("Starting interactive shell");
- state.shell().await?;
-
- record_repository(&repo);
-
- Ok(())
-}
-
-fn catalog_mgmt_cli() -> CliCommandMap {
- let catalog_shell_cmd_def = CliCommand::new(&API_METHOD_CATALOG_SHELL)
- .arg_param(&["snapshot", "archive-name"])
- .completion_cb("repository", complete_repository)
- .completion_cb("archive-name", complete_pxar_archive_name)
- .completion_cb("snapshot", complete_group_or_snapshot);
-
- let catalog_dump_cmd_def = CliCommand::new(&API_METHOD_DUMP_CATALOG)
- .arg_param(&["snapshot"])
- .completion_cb("repository", complete_repository)
- .completion_cb("snapshot", complete_backup_snapshot);
-
- CliCommandMap::new()
- .insert("dump", catalog_dump_cmd_def)
- .insert("shell", catalog_shell_cmd_def)
-}
-
-#[api(
- input: {
- properties: {
- repository: {
- schema: REPO_URL_SCHEMA,
- optional: true,
- },
- limit: {
- description: "The maximal number of tasks to list.",
- type: Integer,
- optional: true,
- minimum: 1,
- maximum: 1000,
- default: 50,
- },
- "output-format": {
- 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 = get_output_format(¶m);
-
- let repo = extract_repository_from_value(¶m)?;
- 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": running,
- "start": 0,
- "limit": limit,
- "userfilter": repo.user(),
- "store": repo.store(),
- });
-
- let mut result = client.get("api2/json/nodes/localhost/tasks", Some(args)).await?;
- let mut data = result["data"].take();
-
- 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)
-}
-
-#[api(
- input: {
- properties: {
- repository: {
- schema: REPO_URL_SCHEMA,
- optional: true,
- },
- upid: {
- schema: UPID_SCHEMA,
- },
- }
- }
-)]
-/// Display the task log.
-async fn task_log(param: Value) -> Result<Value, Error> {
-
- let repo = extract_repository_from_value(¶m)?;
- let upid = tools::required_string_param(¶m, "upid")?;
-
- let client = connect(repo.host(), repo.user())?;
-
- display_task_log(client, upid, true).await?;
-
- Ok(Value::Null)
-}
-
-#[api(
- input: {
- properties: {
- repository: {
- schema: REPO_URL_SCHEMA,
- optional: true,
- },
- upid: {
- schema: UPID_SCHEMA,
- },
- }
+ fn poll_complete<'a>(
+ self: Pin<&'a Self>,
+ _op: ReadAtOperation<'a>,
+ ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> {
+ panic!("LocalDynamicReadAt::start_read_at returned Pending");
}
-)]
-/// Try to stop a specific task.
-async fn task_stop(param: Value) -> Result<Value, Error> {
-
- let repo = extract_repository_from_value(¶m)?;
- let upid_str = tools::required_string_param(¶m, "upid")?;
-
- let mut client = connect(repo.host(), repo.user())?;
-
- let path = format!("api2/json/nodes/localhost/tasks/{}", upid_str);
- let _ = client.delete(&path, None).await?;
-
- Ok(Value::Null)
-}
-
-fn task_mgmt_cli() -> CliCommandMap {
-
- let task_list_cmd_def = CliCommand::new(&API_METHOD_TASK_LIST)
- .completion_cb("repository", complete_repository);
-
- let task_log_cmd_def = CliCommand::new(&API_METHOD_TASK_LOG)
- .arg_param(&["upid"]);
-
- let task_stop_cmd_def = CliCommand::new(&API_METHOD_TASK_STOP)
- .arg_param(&["upid"]);
-
- CliCommandMap::new()
- .insert("log", task_log_cmd_def)
- .insert("list", task_list_cmd_def)
- .insert("stop", task_stop_cmd_def)
}
fn main() {
.completion_cb("keyfile", tools::complete_file_name)
.completion_cb("chunk-size", complete_chunk_size);
+ let benchmark_cmd_def = CliCommand::new(&API_METHOD_BENCHMARK)
+ .completion_cb("repository", complete_repository)
+ .completion_cb("keyfile", tools::complete_file_name);
+
let upload_log_cmd_def = CliCommand::new(&API_METHOD_UPLOAD_LOG)
.arg_param(&["snapshot", "logfile"])
.completion_cb("snapshot", complete_backup_snapshot)
let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT)
.completion_cb("repository", complete_repository);
- #[sortable]
- const API_METHOD_MOUNT: ApiMethod = ApiMethod::new(
- &ApiHandler::Sync(&mount),
- &ObjectSchema::new(
- "Mount pxar archive.",
- &sorted!([
- ("snapshot", false, &StringSchema::new("Group/Snapshot path.").schema()),
- ("archive-name", false, &StringSchema::new("Backup archive name.").schema()),
- ("target", false, &StringSchema::new("Target directory path.").schema()),
- ("repository", true, &REPO_URL_SCHEMA),
- ("keyfile", true, &StringSchema::new("Path to encryption key.").schema()),
- ("verbose", true, &BooleanSchema::new("Verbose output.").default(false).schema()),
- ]),
- )
- );
-
- let mount_cmd_def = CliCommand::new(&API_METHOD_MOUNT)
- .arg_param(&["snapshot", "archive-name", "target"])
- .completion_cb("repository", complete_repository)
- .completion_cb("snapshot", complete_group_or_snapshot)
- .completion_cb("archive-name", complete_pxar_archive_name)
- .completion_cb("target", tools::complete_file_name);
-
-
let cmd_def = CliCommandMap::new()
.insert("backup", backup_cmd_def)
.insert("upload-log", upload_log_cmd_def)
.insert("snapshots", snapshots_cmd_def)
.insert("files", files_cmd_def)
.insert("status", status_cmd_def)
- .insert("key", key_mgmt_cli())
- .insert("mount", mount_cmd_def)
+ .insert("key", key::cli())
+ .insert("mount", mount_cmd_def())
.insert("catalog", catalog_mgmt_cli())
- .insert("task", task_mgmt_cli());
+ .insert("task", task_mgmt_cli())
+ .insert("benchmark", benchmark_cmd_def);
let rpcenv = CliEnvironment::new();
run_cli_command(cmd_def, rpcenv, Some(|future| {