]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-client.rs
pxar: add support for storing/restoring the quota project id on ZFS
[proxmox-backup.git] / src / bin / proxmox-backup-client.rs
CommitLineData
826f309b 1//#[macro_use]
fe0e04c6 2extern crate proxmox_backup;
ff5d3707 3
4use failure::*;
728797d0 5//use std::os::unix::io::AsRawFd;
fa5d6977 6use chrono::{Local, Utc, TimeZone};
e9c9409a 7use std::path::{Path, PathBuf};
2eeaacb9 8use std::collections::{HashSet, HashMap};
bf125261 9use std::io::Write;
ff5d3707 10
fe0e04c6 11use proxmox_backup::tools;
4de0e142 12use proxmox_backup::cli::*;
bbf9e7e9 13use proxmox_backup::api2::types::*;
ef2f2efb 14use proxmox_backup::api_schema::*;
dc9a007b 15use proxmox_backup::api_schema::router::*;
151c6ce2 16use proxmox_backup::client::*;
247cdbce 17use proxmox_backup::backup::*;
86eda3eb
DM
18use proxmox_backup::pxar;
19
fe0e04c6
DM
20//use proxmox_backup::backup::image_index::*;
21//use proxmox_backup::config::datastore;
8968258b 22//use proxmox_backup::pxar::encoder::*;
728797d0 23//use proxmox_backup::backup::datastore::*;
23bb8780 24
f5f13ebc 25use serde_json::{json, Value};
1c0472e8 26//use hyper::Body;
33d64b81 27use std::sync::Arc;
ae0be2dd 28use regex::Regex;
d0a03d40 29use xdg::BaseDirectories;
ae0be2dd
DM
30
31use lazy_static::lazy_static;
5a2df000 32use futures::*;
c4ff3dce 33use tokio::sync::mpsc;
ae0be2dd
DM
34
35lazy_static! {
79679c2d 36 static ref BACKUPSPEC_REGEX: Regex = Regex::new(r"^([a-zA-Z0-9_-]+\.(?:pxar|img|conf|log)):(.+)$").unwrap();
f2401311
DM
37
38 static ref REPO_URL_SCHEMA: Arc<Schema> = Arc::new(
39 StringSchema::new("Repository URL.")
40 .format(BACKUP_REPO_URL.clone())
41 .max_length(256)
42 .into()
43 );
ae0be2dd 44}
33d64b81 45
d0a03d40 46
2665cef7
DM
47fn get_default_repository() -> Option<String> {
48 std::env::var("PBS_REPOSITORY").ok()
49}
50
51fn extract_repository_from_value(
52 param: &Value,
53) -> Result<BackupRepository, Error> {
54
55 let repo_url = param["repository"]
56 .as_str()
57 .map(String::from)
58 .or_else(get_default_repository)
59 .ok_or_else(|| format_err!("unable to get (default) repository"))?;
60
61 let repo: BackupRepository = repo_url.parse()?;
62
63 Ok(repo)
64}
65
66fn extract_repository_from_map(
67 param: &HashMap<String, String>,
68) -> Option<BackupRepository> {
69
70 param.get("repository")
71 .map(String::from)
72 .or_else(get_default_repository)
73 .and_then(|repo_url| repo_url.parse::<BackupRepository>().ok())
74}
75
d0a03d40
DM
76fn record_repository(repo: &BackupRepository) {
77
78 let base = match BaseDirectories::with_prefix("proxmox-backup") {
79 Ok(v) => v,
80 _ => return,
81 };
82
83 // usually $HOME/.cache/proxmox-backup/repo-list
84 let path = match base.place_cache_file("repo-list") {
85 Ok(v) => v,
86 _ => return,
87 };
88
49cf9f3d 89 let mut data = tools::file_get_json(&path, None).unwrap_or(json!({}));
d0a03d40
DM
90
91 let repo = repo.to_string();
92
93 data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 };
94
95 let mut map = serde_json::map::Map::new();
96
97 loop {
98 let mut max_used = 0;
99 let mut max_repo = None;
100 for (repo, count) in data.as_object().unwrap() {
101 if map.contains_key(repo) { continue; }
102 if let Some(count) = count.as_i64() {
103 if count > max_used {
104 max_used = count;
105 max_repo = Some(repo);
106 }
107 }
108 }
109 if let Some(repo) = max_repo {
110 map.insert(repo.to_owned(), json!(max_used));
111 } else {
112 break;
113 }
114 if map.len() > 10 { // store max. 10 repos
115 break;
116 }
117 }
118
119 let new_data = json!(map);
120
121 let _ = tools::file_set_contents(path, new_data.to_string().as_bytes(), None);
122}
123
49811347 124fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
d0a03d40
DM
125
126 let mut result = vec![];
127
128 let base = match BaseDirectories::with_prefix("proxmox-backup") {
129 Ok(v) => v,
130 _ => return result,
131 };
132
133 // usually $HOME/.cache/proxmox-backup/repo-list
134 let path = match base.place_cache_file("repo-list") {
135 Ok(v) => v,
136 _ => return result,
137 };
138
49cf9f3d 139 let data = tools::file_get_json(&path, None).unwrap_or(json!({}));
d0a03d40
DM
140
141 if let Some(map) = data.as_object() {
49811347 142 for (repo, _count) in map {
d0a03d40
DM
143 result.push(repo.to_owned());
144 }
145 }
146
147 result
148}
149
17d6979a 150fn backup_directory<P: AsRef<Path>>(
c4ff3dce 151 client: &BackupClient,
17d6979a 152 dir_path: P,
247cdbce 153 archive_name: &str,
36898ffc 154 chunk_size: Option<usize>,
2eeaacb9 155 device_set: Option<HashSet<u64>>,
219ef0e6 156 verbose: bool,
5b72c9b4 157 skip_lost_and_found: bool,
f98ac774 158 crypt_config: Option<Arc<CryptConfig>>,
247cdbce 159) -> Result<(), Error> {
33d64b81 160
5b72c9b4 161 let pxar_stream = PxarBackupStream::open(dir_path.as_ref(), device_set, verbose, skip_lost_and_found)?;
36898ffc 162 let chunk_stream = ChunkStream::new(pxar_stream, chunk_size);
ff3d3100 163
c4ff3dce 164 let (tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks
5e7a09be 165
c4ff3dce
DM
166 let stream = rx
167 .map_err(Error::from)
168 .and_then(|x| x); // flatten
17d6979a 169
c4ff3dce
DM
170 // spawn chunker inside a separate task so that it can run parallel
171 tokio::spawn(
172 tx.send_all(chunk_stream.then(|r| Ok(r)))
1c0472e8 173 .map_err(|_| {}).map(|_| ())
c4ff3dce 174 );
17d6979a 175
f98ac774 176 client.upload_stream(archive_name, stream, "dynamic", None, crypt_config).wait()?;
bcd879cf
DM
177
178 Ok(())
179}
180
6af905c1
DM
181fn backup_image<P: AsRef<Path>>(
182 client: &BackupClient,
183 image_path: P,
184 archive_name: &str,
185 image_size: u64,
36898ffc 186 chunk_size: Option<usize>,
1c0472e8 187 _verbose: bool,
f98ac774 188 crypt_config: Option<Arc<CryptConfig>>,
6af905c1
DM
189) -> Result<(), Error> {
190
6af905c1
DM
191 let path = image_path.as_ref().to_owned();
192
193 let file = tokio::fs::File::open(path).wait()?;
194
195 let stream = tokio::codec::FramedRead::new(file, tokio::codec::BytesCodec::new())
196 .map_err(Error::from);
197
36898ffc 198 let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024));
6af905c1 199
f98ac774 200 client.upload_stream(archive_name, stream, "fixed", Some(image_size), crypt_config).wait()?;
6af905c1
DM
201
202 Ok(())
203}
204
6899dbfb 205fn strip_server_file_expenstions(list: Vec<String>) -> Vec<String> {
8e39232a
DM
206
207 let mut result = vec![];
208
209 for file in list.into_iter() {
210 if file.ends_with(".didx") {
211 result.push(file[..file.len()-5].to_owned());
212 } else if file.ends_with(".fidx") {
213 result.push(file[..file.len()-5].to_owned());
6899dbfb
DM
214 } else if file.ends_with(".blob") {
215 result.push(file[..file.len()-5].to_owned());
8e39232a
DM
216 } else {
217 result.push(file); // should not happen
218 }
219 }
220
221 result
222}
223
812c6f87
DM
224fn list_backup_groups(
225 param: Value,
226 _info: &ApiMethod,
dd5495d6 227 _rpcenv: &mut dyn RpcEnvironment,
812c6f87
DM
228) -> Result<Value, Error> {
229
2665cef7 230 let repo = extract_repository_from_value(&param)?;
812c6f87 231
45cdce06 232 let client = HttpClient::new(repo.host(), repo.user())?;
812c6f87 233
d0a03d40 234 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
812c6f87 235
9e391bb7 236 let mut result = client.get(&path, None).wait()?;
812c6f87 237
d0a03d40
DM
238 record_repository(&repo);
239
812c6f87 240 // fixme: implement and use output formatter instead ..
80822b95
DM
241 let list = result["data"].as_array_mut().unwrap();
242
243 list.sort_unstable_by(|a, b| {
244 let a_id = a["backup-id"].as_str().unwrap();
245 let a_backup_type = a["backup-type"].as_str().unwrap();
246 let b_id = b["backup-id"].as_str().unwrap();
247 let b_backup_type = b["backup-type"].as_str().unwrap();
248
249 let type_order = a_backup_type.cmp(b_backup_type);
250 if type_order == std::cmp::Ordering::Equal {
251 a_id.cmp(b_id)
252 } else {
253 type_order
254 }
255 });
812c6f87 256
34a816cc
DM
257 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
258
259 let mut result = vec![];
260
812c6f87
DM
261 for item in list {
262
ad20d198
DM
263 let id = item["backup-id"].as_str().unwrap();
264 let btype = item["backup-type"].as_str().unwrap();
265 let epoch = item["last-backup"].as_i64().unwrap();
fa5d6977 266 let last_backup = Utc.timestamp(epoch, 0);
ad20d198 267 let backup_count = item["backup-count"].as_u64().unwrap();
812c6f87 268
1e9a94e5 269 let group = BackupGroup::new(btype, id);
812c6f87
DM
270
271 let path = group.group_path().to_str().unwrap().to_owned();
ad20d198 272
8e39232a 273 let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect();
6899dbfb 274 let files = strip_server_file_expenstions(files);
ad20d198 275
34a816cc 276 if output_format == "text" {
fa5d6977
DM
277 println!(
278 "{:20} | {} | {:5} | {}",
279 path,
280 BackupDir::backup_time_to_string(last_backup),
281 backup_count,
282 tools::join(&files, ' '),
283 );
34a816cc
DM
284 } else {
285 result.push(json!({
286 "backup-type": btype,
287 "backup-id": id,
288 "last-backup": epoch,
289 "backup-count": backup_count,
290 "files": files,
291 }));
292 }
812c6f87
DM
293 }
294
9aa3f682 295 if output_format != "text" { format_and_print_result(&result.into(), &output_format); }
34a816cc 296
812c6f87
DM
297 Ok(Value::Null)
298}
299
184f17af
DM
300fn list_snapshots(
301 param: Value,
302 _info: &ApiMethod,
dd5495d6 303 _rpcenv: &mut dyn RpcEnvironment,
184f17af
DM
304) -> Result<Value, Error> {
305
2665cef7 306 let repo = extract_repository_from_value(&param)?;
184f17af 307
34a816cc
DM
308 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
309
45cdce06 310 let client = HttpClient::new(repo.host(), repo.user())?;
184f17af 311
9e391bb7 312 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
184f17af 313
15c847f1
DM
314 let mut args = json!({});
315 if let Some(path) = param["group"].as_str() {
316 let group = BackupGroup::parse(path)?;
317 args["backup-type"] = group.backup_type().into();
318 args["backup-id"] = group.backup_id().into();
319 }
320
321 let result = client.get(&path, Some(args)).wait()?;
184f17af 322
d0a03d40
DM
323 record_repository(&repo);
324
184f17af
DM
325 let list = result["data"].as_array().unwrap();
326
34a816cc
DM
327 let mut result = vec![];
328
184f17af
DM
329 for item in list {
330
331 let id = item["backup-id"].as_str().unwrap();
332 let btype = item["backup-type"].as_str().unwrap();
333 let epoch = item["backup-time"].as_i64().unwrap();
184f17af 334
391d3107 335 let snapshot = BackupDir::new(btype, id, epoch);
184f17af
DM
336
337 let path = snapshot.relative_path().to_str().unwrap().to_owned();
338
8e39232a 339 let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect();
6899dbfb 340 let files = strip_server_file_expenstions(files);
184f17af 341
34a816cc 342 if output_format == "text" {
fa5d6977 343 println!("{} | {}", path, tools::join(&files, ' '));
34a816cc
DM
344 } else {
345 result.push(json!({
346 "backup-type": btype,
347 "backup-id": id,
348 "backup-time": epoch,
349 "files": files,
350 }));
351 }
184f17af
DM
352 }
353
f6ede796 354 if output_format != "text" { format_and_print_result(&result.into(), &output_format); }
34a816cc 355
184f17af
DM
356 Ok(Value::Null)
357}
358
6f62c924
DM
359fn forget_snapshots(
360 param: Value,
361 _info: &ApiMethod,
dd5495d6 362 _rpcenv: &mut dyn RpcEnvironment,
6f62c924
DM
363) -> Result<Value, Error> {
364
2665cef7 365 let repo = extract_repository_from_value(&param)?;
6f62c924
DM
366
367 let path = tools::required_string_param(&param, "snapshot")?;
368 let snapshot = BackupDir::parse(path)?;
369
45cdce06 370 let mut client = HttpClient::new(repo.host(), repo.user())?;
6f62c924 371
9e391bb7 372 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
6f62c924 373
9e391bb7
DM
374 let result = client.delete(&path, Some(json!({
375 "backup-type": snapshot.group().backup_type(),
376 "backup-id": snapshot.group().backup_id(),
377 "backup-time": snapshot.backup_time().timestamp(),
378 }))).wait()?;
6f62c924 379
d0a03d40
DM
380 record_repository(&repo);
381
6f62c924
DM
382 Ok(result)
383}
384
8cc0d6af
DM
385fn start_garbage_collection(
386 param: Value,
387 _info: &ApiMethod,
dd5495d6 388 _rpcenv: &mut dyn RpcEnvironment,
8cc0d6af
DM
389) -> Result<Value, Error> {
390
2665cef7 391 let repo = extract_repository_from_value(&param)?;
8cc0d6af 392
45cdce06 393 let mut client = HttpClient::new(repo.host(), repo.user())?;
8cc0d6af 394
d0a03d40 395 let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
8cc0d6af 396
5a2df000 397 let result = client.post(&path, None).wait()?;
8cc0d6af 398
d0a03d40
DM
399 record_repository(&repo);
400
8cc0d6af
DM
401 Ok(result)
402}
33d64b81 403
ae0be2dd
DM
404fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> {
405
406 if let Some(caps) = BACKUPSPEC_REGEX.captures(value) {
407 return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str()));
408 }
409 bail!("unable to parse directory specification '{}'", value);
410}
411
6049b71f
DM
412fn create_backup(
413 param: Value,
414 _info: &ApiMethod,
dd5495d6 415 _rpcenv: &mut dyn RpcEnvironment,
6049b71f 416) -> Result<Value, Error> {
ff5d3707 417
2665cef7 418 let repo = extract_repository_from_value(&param)?;
ae0be2dd
DM
419
420 let backupspec_list = tools::required_array_param(&param, "backupspec")?;
a914a774 421
eed6db39
DM
422 let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false);
423
5b72c9b4
DM
424 let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false);
425
219ef0e6
DM
426 let verbose = param["verbose"].as_bool().unwrap_or(false);
427
ca5d0b61
DM
428 let backup_time_opt = param["backup-time"].as_i64();
429
36898ffc 430 let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize);
2d9d143a 431
247cdbce
DM
432 if let Some(size) = chunk_size_opt {
433 verify_chunk_size(size)?;
2d9d143a
DM
434 }
435
6d0983db
DM
436 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
437
bbf9e7e9 438 let backup_id = param["backup-id"].as_str().unwrap_or(&tools::nodename());
fba30411 439
bbf9e7e9 440 let backup_type = param["backup-type"].as_str().unwrap_or("host");
ca5d0b61 441
2eeaacb9
DM
442 let include_dev = param["include-dev"].as_array();
443
444 let mut devices = if all_file_systems { None } else { Some(HashSet::new()) };
445
446 if let Some(include_dev) = include_dev {
447 if all_file_systems {
448 bail!("option 'all-file-systems' conflicts with option 'include-dev'");
449 }
450
451 let mut set = HashSet::new();
452 for path in include_dev {
453 let path = path.as_str().unwrap();
454 let stat = nix::sys::stat::stat(path)
455 .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?;
456 set.insert(stat.st_dev);
457 }
458 devices = Some(set);
459 }
460
ae0be2dd 461 let mut upload_list = vec![];
a914a774 462
79679c2d 463 enum BackupType { PXAR, IMAGE, CONFIG, LOGFILE };
6af905c1 464
ae0be2dd
DM
465 for backupspec in backupspec_list {
466 let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?;
bcd879cf 467
eb1804c5
DM
468 use std::os::unix::fs::FileTypeExt;
469
470 let metadata = match std::fs::metadata(filename) {
471 Ok(m) => m,
ae0be2dd
DM
472 Err(err) => bail!("unable to access '{}' - {}", filename, err),
473 };
eb1804c5 474 let file_type = metadata.file_type();
23bb8780 475
ec8a9bb9 476 let extension = Path::new(target).extension().map(|s| s.to_str().unwrap()).unwrap();
bcd879cf 477
ec8a9bb9
DM
478 match extension {
479 "pxar" => {
480 if !file_type.is_dir() {
481 bail!("got unexpected file type (expected directory)");
482 }
483 upload_list.push((BackupType::PXAR, filename.to_owned(), target.to_owned(), 0));
484 }
485 "img" => {
eb1804c5 486
ec8a9bb9
DM
487 if !(file_type.is_file() || file_type.is_block_device()) {
488 bail!("got unexpected file type (expected file or block device)");
489 }
eb1804c5 490
ec8a9bb9 491 let size = tools::image_size(&PathBuf::from(filename))?;
23bb8780 492
ec8a9bb9 493 if size == 0 { bail!("got zero-sized file '{}'", filename); }
ae0be2dd 494
ec8a9bb9
DM
495 upload_list.push((BackupType::IMAGE, filename.to_owned(), target.to_owned(), size));
496 }
497 "conf" => {
498 if !file_type.is_file() {
499 bail!("got unexpected file type (expected regular file)");
500 }
501 upload_list.push((BackupType::CONFIG, filename.to_owned(), target.to_owned(), metadata.len()));
502 }
79679c2d
DM
503 "log" => {
504 if !file_type.is_file() {
505 bail!("got unexpected file type (expected regular file)");
506 }
507 upload_list.push((BackupType::LOGFILE, filename.to_owned(), target.to_owned(), metadata.len()));
508 }
ec8a9bb9
DM
509 _ => {
510 bail!("got unknown archive extension '{}'", extension);
511 }
ae0be2dd
DM
512 }
513 }
514
ca5d0b61 515 let backup_time = Utc.timestamp(backup_time_opt.unwrap_or(Utc::now().timestamp()), 0);
ae0be2dd 516
c4ff3dce 517 let client = HttpClient::new(repo.host(), repo.user())?;
d0a03d40
DM
518 record_repository(&repo);
519
ca5d0b61
DM
520 println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time));
521
cdebd467 522 println!("Client name: {}", tools::nodename());
ca5d0b61
DM
523
524 let start_time = Local::now();
525
7a6cfbd9 526 println!("Starting protocol: {}", start_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
51144821 527
bb823140
DM
528 let (crypt_config, rsa_encrypted_key) = match keyfile {
529 None => (None, None),
6d0983db 530 Some(path) => {
bb823140
DM
531 let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
532
533 let crypt_config = CryptConfig::new(key)?;
534
535 let path = master_pubkey_path()?;
536 if path.exists() {
537 let pem_data = proxmox_backup::tools::file_get_contents(&path)?;
538 let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
539 let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?;
540 (Some(Arc::new(crypt_config)), Some(enc_key))
541 } else {
542 (Some(Arc::new(crypt_config)), None)
543 }
6d0983db
DM
544 }
545 };
f98ac774 546
ca5d0b61 547 let client = client.start_backup(repo.store(), backup_type, &backup_id, backup_time, verbose).wait()?;
c4ff3dce 548
6af905c1
DM
549 for (backup_type, filename, target, size) in upload_list {
550 match backup_type {
ec8a9bb9
DM
551 BackupType::CONFIG => {
552 println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target);
9f46c7de 553 client.upload_blob_from_file(&filename, &target, crypt_config.clone(), true).wait()?;
ec8a9bb9 554 }
ca5d0b61 555 BackupType::LOGFILE => { // fixme: remove - not needed anymore ?
79679c2d
DM
556 println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target);
557 client.upload_blob_from_file(&filename, &target, crypt_config.clone(), true).wait()?;
558 }
6af905c1
DM
559 BackupType::PXAR => {
560 println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target);
f98ac774
DM
561 backup_directory(
562 &client,
563 &filename,
564 &target,
565 chunk_size_opt,
2eeaacb9 566 devices.clone(),
f98ac774 567 verbose,
5b72c9b4 568 skip_lost_and_found,
f98ac774
DM
569 crypt_config.clone(),
570 )?;
6af905c1
DM
571 }
572 BackupType::IMAGE => {
573 println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
f98ac774
DM
574 backup_image(
575 &client,
576 &filename,
577 &target,
578 size,
579 chunk_size_opt,
580 verbose,
581 crypt_config.clone(),
582 )?;
6af905c1
DM
583 }
584 }
4818c8b6
DM
585 }
586
bb823140
DM
587 if let Some(rsa_encrypted_key) = rsa_encrypted_key {
588 let target = "rsa-encrypted.key";
589 println!("Upload RSA encoded key to '{:?}' as {}", repo, target);
590 client.upload_blob_from_data(rsa_encrypted_key, target, None, false).wait()?;
591
592 // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t
593 /*
594 let mut buffer2 = vec![0u8; rsa.size() as usize];
595 let pem_data = proxmox_backup::tools::file_get_contents("master-private.pem")?;
596 let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?;
597 let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?;
598 println!("TEST {} {:?}", len, buffer2);
599 */
9f46c7de
DM
600 }
601
c4ff3dce
DM
602 client.finish().wait()?;
603
7a6cfbd9 604 let end_time = Local::now();
ca5d0b61 605 let elapsed = end_time.signed_duration_since(start_time);
3ec3ec3f
DM
606 println!("Duration: {}", elapsed);
607
7a6cfbd9 608 println!("End Time: {}", end_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
3d5c11e5 609
ff5d3707 610 Ok(Value::Null)
f98ea63d
DM
611}
612
d0a03d40 613fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
f98ea63d
DM
614
615 let mut result = vec![];
616
617 let data: Vec<&str> = arg.splitn(2, ':').collect();
618
bff11030 619 if data.len() != 2 {
8968258b
DM
620 result.push(String::from("root.pxar:/"));
621 result.push(String::from("etc.pxar:/etc"));
bff11030
DM
622 return result;
623 }
f98ea63d 624
496a6784 625 let files = tools::complete_file_name(data[1], param);
f98ea63d
DM
626
627 for file in files {
628 result.push(format!("{}:{}", data[0], file));
629 }
630
631 result
ff5d3707 632}
633
9f912493
DM
634fn restore(
635 param: Value,
636 _info: &ApiMethod,
dd5495d6 637 _rpcenv: &mut dyn RpcEnvironment,
9f912493
DM
638) -> Result<Value, Error> {
639
2665cef7 640 let repo = extract_repository_from_value(&param)?;
9f912493 641
86eda3eb
DM
642 let verbose = param["verbose"].as_bool().unwrap_or(false);
643
46d5aa0a
DM
644 let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false);
645
d5c34d98
DM
646 let archive_name = tools::required_string_param(&param, "archive-name")?;
647
86eda3eb 648 let client = HttpClient::new(repo.host(), repo.user())?;
d0a03d40 649
d0a03d40 650 record_repository(&repo);
d5c34d98 651
9f912493 652 let path = tools::required_string_param(&param, "snapshot")?;
9f912493 653
86eda3eb 654 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
d5c34d98 655 let group = BackupGroup::parse(path)?;
9f912493 656
9e391bb7
DM
657 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
658 let result = client.get(&path, Some(json!({
d5c34d98
DM
659 "backup-type": group.backup_type(),
660 "backup-id": group.backup_id(),
9e391bb7 661 }))).wait()?;
9f912493 662
d5c34d98
DM
663 let list = result["data"].as_array().unwrap();
664 if list.len() == 0 {
665 bail!("backup group '{}' does not contain any snapshots:", path);
666 }
9f912493 667
86eda3eb 668 let epoch = list[0]["backup-time"].as_i64().unwrap();
fa5d6977 669 let backup_time = Utc.timestamp(epoch, 0);
86eda3eb 670 (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time)
d5c34d98
DM
671 } else {
672 let snapshot = BackupDir::parse(path)?;
86eda3eb
DM
673 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
674 };
9f912493 675
d5c34d98 676 let target = tools::required_string_param(&param, "target")?;
bf125261 677 let target = if target == "-" { None } else { Some(target) };
2ae7d196 678
86eda3eb 679 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
2ae7d196 680
86eda3eb
DM
681 let crypt_config = match keyfile {
682 None => None,
683 Some(path) => {
684 let (key, _) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
685 Some(Arc::new(CryptConfig::new(key)?))
686 }
687 };
d5c34d98 688
afb4cd28
DM
689 let server_archive_name = if archive_name.ends_with(".pxar") {
690 format!("{}.didx", archive_name)
691 } else if archive_name.ends_with(".img") {
692 format!("{}.fidx", archive_name)
693 } else {
f8100e96 694 format!("{}.blob", archive_name)
afb4cd28 695 };
9f912493 696
86eda3eb
DM
697 let client = client.start_backup_reader(repo.store(), &backup_type, &backup_id, backup_time, true).wait()?;
698
699 use std::os::unix::fs::OpenOptionsExt;
700
701 let tmpfile = std::fs::OpenOptions::new()
702 .write(true)
703 .read(true)
704 .custom_flags(libc::O_TMPFILE)
705 .open("/tmp")?;
706
f8100e96
DM
707 if server_archive_name.ends_with(".blob") {
708
709 let writer = Vec::with_capacity(1024*1024);
710 let blob_data = client.download(&server_archive_name, writer).wait()?;
711 let blob = DataBlob::from_raw(blob_data)?;
712 blob.verify_crc()?;
713
714 let raw_data = match crypt_config {
715 Some(ref crypt_config) => blob.decode(Some(crypt_config))?,
716 None => blob.decode(None)?,
717 };
718
bf125261
DM
719 if let Some(target) = target {
720 crate::tools::file_set_contents(target, &raw_data, None)?;
721 } else {
722 let stdout = std::io::stdout();
723 let mut writer = stdout.lock();
724 writer.write_all(&raw_data)
725 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
726 }
f8100e96
DM
727
728 } else if server_archive_name.ends_with(".didx") {
afb4cd28 729 let tmpfile = client.download(&server_archive_name, tmpfile).wait()?;
86eda3eb 730
afb4cd28
DM
731 let index = DynamicIndexReader::new(tmpfile)
732 .map_err(|err| format_err!("unable to read dynamic index '{}' - {}", archive_name, err))?;
86eda3eb 733
f4bf7dfc
DM
734 let most_used = index.find_most_used_chunks(8);
735
736 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
737
afb4cd28 738 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
86eda3eb 739
bf125261 740 if let Some(target) = target {
86eda3eb 741
bf125261
DM
742 let feature_flags = pxar::CA_FORMAT_DEFAULT;
743 let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags, |path| {
744 if verbose {
745 println!("{:?}", path);
746 }
747 Ok(())
748 });
6a879109
CE
749 decoder.set_allow_existing_dirs(allow_existing_dirs);
750
bf125261 751
fa7e957c 752 decoder.restore(Path::new(target), &Vec::new())?;
bf125261
DM
753 } else {
754 let stdout = std::io::stdout();
755 let mut writer = stdout.lock();
afb4cd28 756
bf125261
DM
757 std::io::copy(&mut reader, &mut writer)
758 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
759 }
afb4cd28
DM
760 } else if server_archive_name.ends_with(".fidx") {
761 let tmpfile = client.download(&server_archive_name, tmpfile).wait()?;
762
763 let index = FixedIndexReader::new(tmpfile)
764 .map_err(|err| format_err!("unable to read fixed index '{}' - {}", archive_name, err))?;
7dcbe051 765
f4bf7dfc
DM
766 let most_used = index.find_most_used_chunks(8);
767
768 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
769
afb4cd28
DM
770 let mut reader = BufferedFixedReader::new(index, chunk_reader);
771
bf125261
DM
772 if let Some(target) = target {
773 let mut writer = std::fs::OpenOptions::new()
774 .write(true)
775 .create(true)
776 .create_new(true)
777 .open(target)
778 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
779
780 std::io::copy(&mut reader, &mut writer)
781 .map_err(|err| format_err!("unable to store data - {}", err))?;
782 } else {
783 let stdout = std::io::stdout();
784 let mut writer = stdout.lock();
afb4cd28 785
bf125261
DM
786 std::io::copy(&mut reader, &mut writer)
787 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
788 }
45db6f89 789 } else {
f8100e96 790 bail!("unknown archive file extension (expected .pxar of .img)");
3031e44c 791 }
fef44d4f
DM
792
793 Ok(Value::Null)
45db6f89
DM
794}
795
ec34f7eb
DM
796fn upload_log(
797 param: Value,
798 _info: &ApiMethod,
799 _rpcenv: &mut dyn RpcEnvironment,
800) -> Result<Value, Error> {
801
802 let logfile = tools::required_string_param(&param, "logfile")?;
803 let repo = extract_repository_from_value(&param)?;
804
805 let snapshot = tools::required_string_param(&param, "snapshot")?;
806 let snapshot = BackupDir::parse(snapshot)?;
807
808 let mut client = HttpClient::new(repo.host(), repo.user())?;
809
810 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
811
812 let crypt_config = match keyfile {
813 None => None,
814 Some(path) => {
815 let (key, _created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
816 let crypt_config = CryptConfig::new(key)?;
817 Some(crypt_config)
818 }
819 };
820
821 let data = crate::tools::file_get_contents(logfile)?;
822
823 let blob = if let Some(ref crypt_config) = crypt_config {
824 DataBlob::encode(&data, Some(crypt_config), true)?
825 } else {
826 DataBlob::encode(&data, None, true)?
827 };
828
829 let raw_data = blob.into_inner();
830
831 let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store());
832
833 let args = json!({
834 "backup-type": snapshot.group().backup_type(),
835 "backup-id": snapshot.group().backup_id(),
836 "backup-time": snapshot.backup_time().timestamp(),
837 });
838
839 let body = hyper::Body::from(raw_data);
840
841 let result = client.upload("application/octet-stream", body, &path, Some(args)).wait()?;
842
843 Ok(result)
844}
845
83b7db02 846fn prune(
ea7a7ef2 847 mut param: Value,
83b7db02 848 _info: &ApiMethod,
dd5495d6 849 _rpcenv: &mut dyn RpcEnvironment,
83b7db02
DM
850) -> Result<Value, Error> {
851
2665cef7 852 let repo = extract_repository_from_value(&param)?;
83b7db02 853
45cdce06 854 let mut client = HttpClient::new(repo.host(), repo.user())?;
83b7db02 855
d0a03d40 856 let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
83b7db02 857
9fdc3ef4
DM
858 let group = tools::required_string_param(&param, "group")?;
859 let group = BackupGroup::parse(group)?;
860
ea7a7ef2
DM
861 param.as_object_mut().unwrap().remove("repository");
862 param.as_object_mut().unwrap().remove("group");
863
864 param["backup-type"] = group.backup_type().into();
865 param["backup-id"] = group.backup_id().into();
83b7db02 866
ea7a7ef2 867 let result = client.post(&path, Some(param)).wait()?;
83b7db02 868
d0a03d40
DM
869 record_repository(&repo);
870
83b7db02
DM
871 Ok(result)
872}
873
34a816cc
DM
874fn status(
875 param: Value,
876 _info: &ApiMethod,
877 _rpcenv: &mut dyn RpcEnvironment,
878) -> Result<Value, Error> {
879
880 let repo = extract_repository_from_value(&param)?;
881
882 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
883
884 let client = HttpClient::new(repo.host(), repo.user())?;
885
886 let path = format!("api2/json/admin/datastore/{}/status", repo.store());
887
888 let result = client.get(&path, None).wait()?;
889 let data = &result["data"];
890
891 record_repository(&repo);
892
893 if output_format == "text" {
894 let total = data["total"].as_u64().unwrap();
895 let used = data["used"].as_u64().unwrap();
896 let avail = data["avail"].as_u64().unwrap();
897 let roundup = total/200;
898
899 println!(
900 "total: {} used: {} ({} %) available: {}",
901 total,
902 used,
903 ((used+roundup)*100)/total,
904 avail,
905 );
906 } else {
f6ede796 907 format_and_print_result(data, &output_format);
34a816cc
DM
908 }
909
910 Ok(Value::Null)
911}
912
5a2df000 913// like get, but simply ignore errors and return Null instead
b2388518 914fn try_get(repo: &BackupRepository, url: &str) -> Value {
024f11bb 915
45cdce06
DM
916 let client = match HttpClient::new(repo.host(), repo.user()) {
917 Ok(v) => v,
918 _ => return Value::Null,
919 };
b2388518 920
9e391bb7 921 let mut resp = match client.get(url, None).wait() {
b2388518
DM
922 Ok(v) => v,
923 _ => return Value::Null,
924 };
925
926 if let Some(map) = resp.as_object_mut() {
927 if let Some(data) = map.remove("data") {
928 return data;
929 }
930 }
931 Value::Null
932}
933
b2388518 934fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
024f11bb 935
b2388518
DM
936 let mut result = vec![];
937
2665cef7 938 let repo = match extract_repository_from_map(param) {
b2388518 939 Some(v) => v,
024f11bb
DM
940 _ => return result,
941 };
942
b2388518
DM
943 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
944
945 let data = try_get(&repo, &path);
946
947 if let Some(list) = data.as_array() {
024f11bb 948 for item in list {
98f0b972
DM
949 if let (Some(backup_id), Some(backup_type)) =
950 (item["backup-id"].as_str(), item["backup-type"].as_str())
951 {
952 result.push(format!("{}/{}", backup_type, backup_id));
024f11bb
DM
953 }
954 }
955 }
956
957 result
958}
959
b2388518
DM
960fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
961
962 let mut result = vec![];
963
2665cef7 964 let repo = match extract_repository_from_map(param) {
b2388518
DM
965 Some(v) => v,
966 _ => return result,
967 };
968
969 if arg.matches('/').count() < 2 {
970 let groups = complete_backup_group(arg, param);
971 for group in groups {
972 result.push(group.to_string());
973 result.push(format!("{}/", group));
974 }
975 return result;
976 }
977
978 let mut parts = arg.split('/');
979 let query = tools::json_object_to_query(json!({
980 "backup-type": parts.next().unwrap(),
981 "backup-id": parts.next().unwrap(),
982 })).unwrap();
983
984 let path = format!("api2/json/admin/datastore/{}/snapshots?{}", repo.store(), query);
985
986 let data = try_get(&repo, &path);
987
988 if let Some(list) = data.as_array() {
989 for item in list {
990 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
991 (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
992 {
993 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
994 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
995 }
996 }
997 }
998
999 result
1000}
1001
45db6f89 1002fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
08dc340a
DM
1003
1004 let mut result = vec![];
1005
2665cef7 1006 let repo = match extract_repository_from_map(param) {
08dc340a
DM
1007 Some(v) => v,
1008 _ => return result,
1009 };
1010
1011 let snapshot = match param.get("snapshot") {
1012 Some(path) => {
1013 match BackupDir::parse(path) {
1014 Ok(v) => v,
1015 _ => return result,
1016 }
1017 }
1018 _ => return result,
1019 };
1020
1021 let query = tools::json_object_to_query(json!({
1022 "backup-type": snapshot.group().backup_type(),
1023 "backup-id": snapshot.group().backup_id(),
1024 "backup-time": snapshot.backup_time().timestamp(),
1025 })).unwrap();
1026
1027 let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
1028
1029 let data = try_get(&repo, &path);
1030
1031 if let Some(list) = data.as_array() {
1032 for item in list {
1033 if let Some(filename) = item.as_str() {
1034 result.push(filename.to_owned());
1035 }
1036 }
1037 }
1038
45db6f89
DM
1039 result
1040}
1041
1042fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1043
1044 let result = complete_server_file_name(arg, param);
1045
6899dbfb 1046 strip_server_file_expenstions(result)
08dc340a
DM
1047}
1048
49811347
DM
1049fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
1050
1051 let mut result = vec![];
1052
1053 let mut size = 64;
1054 loop {
1055 result.push(size.to_string());
1056 size = size * 2;
1057 if size > 4096 { break; }
1058 }
1059
1060 result
1061}
1062
826f309b 1063fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
ff5d3707 1064
f2401311
DM
1065 // fixme: implement other input methods
1066
1067 use std::env::VarError::*;
1068 match std::env::var("PBS_ENCRYPTION_PASSWORD") {
826f309b 1069 Ok(p) => return Ok(p.as_bytes().to_vec()),
f2401311
DM
1070 Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
1071 Err(NotPresent) => {
1072 // Try another method
1073 }
1074 }
1075
1076 // If we're on a TTY, query the user for a password
1077 if crate::tools::tty::stdin_isatty() {
826f309b 1078 return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?);
f2401311
DM
1079 }
1080
1081 bail!("no password input mechanism available");
1082}
1083
ac716234
DM
1084fn key_create(
1085 param: Value,
1086 _info: &ApiMethod,
1087 _rpcenv: &mut dyn RpcEnvironment,
1088) -> Result<Value, Error> {
1089
9b06db45
DM
1090 let path = tools::required_string_param(&param, "path")?;
1091 let path = PathBuf::from(path);
ac716234 1092
181f097a 1093 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
ac716234
DM
1094
1095 let key = proxmox::sys::linux::random_data(32)?;
1096
181f097a
DM
1097 if kdf == "scrypt" {
1098 // always read passphrase from tty
1099 if !crate::tools::tty::stdin_isatty() {
1100 bail!("unable to read passphrase - no tty");
1101 }
ac716234 1102
181f097a
DM
1103 let password = crate::tools::tty::read_password("Encryption Key Password: ")?;
1104
ab44acff 1105 let key_config = encrypt_key_with_passphrase(&key, &password)?;
37c5a175 1106
ab44acff 1107 store_key_config(&path, false, key_config)?;
181f097a
DM
1108
1109 Ok(Value::Null)
1110 } else if kdf == "none" {
1111 let created = Local.timestamp(Local::now().timestamp(), 0);
1112
1113 store_key_config(&path, false, KeyConfig {
1114 kdf: None,
1115 created,
ab44acff 1116 modified: created,
181f097a
DM
1117 data: key,
1118 })?;
1119
1120 Ok(Value::Null)
1121 } else {
1122 unreachable!();
1123 }
ac716234
DM
1124}
1125
9f46c7de
DM
1126fn master_pubkey_path() -> Result<PathBuf, Error> {
1127 let base = BaseDirectories::with_prefix("proxmox-backup")?;
1128
1129 // usually $HOME/.config/proxmox-backup/master-public.pem
1130 let path = base.place_config_file("master-public.pem")?;
1131
1132 Ok(path)
1133}
1134
3ea8bfc9
DM
1135fn key_import_master_pubkey(
1136 param: Value,
1137 _info: &ApiMethod,
1138 _rpcenv: &mut dyn RpcEnvironment,
1139) -> Result<Value, Error> {
1140
1141 let path = tools::required_string_param(&param, "path")?;
1142 let path = PathBuf::from(path);
1143
1144 let pem_data = proxmox_backup::tools::file_get_contents(&path)?;
1145
1146 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
1147 bail!("Unable to decode PEM data - {}", err);
1148 }
1149
9f46c7de 1150 let target_path = master_pubkey_path()?;
3ea8bfc9
DM
1151
1152 proxmox_backup::tools::file_set_contents(&target_path, &pem_data, None)?;
1153
1154 println!("Imported public master key to {:?}", target_path);
1155
1156 Ok(Value::Null)
1157}
1158
37c5a175
DM
1159fn key_create_master_key(
1160 _param: Value,
1161 _info: &ApiMethod,
1162 _rpcenv: &mut dyn RpcEnvironment,
1163) -> Result<Value, Error> {
1164
1165 // we need a TTY to query the new password
1166 if !crate::tools::tty::stdin_isatty() {
1167 bail!("unable to create master key - no tty");
1168 }
1169
1170 let rsa = openssl::rsa::Rsa::generate(4096)?;
1171 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
1172
1173 let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?;
1174 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
1175
1176 if new_pw != verify_pw {
1177 bail!("Password verification fail!");
1178 }
1179
1180 if new_pw.len() < 5 {
1181 bail!("Password is too short!");
1182 }
1183
1184 let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
1185 let filename_pub = "master-public.pem";
1186 println!("Writing public master key to {}", filename_pub);
1187 proxmox_backup::tools::file_set_contents(filename_pub, pub_key.as_slice(), None)?;
1188
1189 let cipher = openssl::symm::Cipher::aes_256_cbc();
1190 let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?;
1191
1192 let filename_priv = "master-private.pem";
1193 println!("Writing private master key to {}", filename_priv);
1194 proxmox_backup::tools::file_set_contents(filename_priv, priv_key.as_slice(), None)?;
1195
1196 Ok(Value::Null)
1197}
ac716234
DM
1198
1199fn key_change_passphrase(
1200 param: Value,
1201 _info: &ApiMethod,
1202 _rpcenv: &mut dyn RpcEnvironment,
1203) -> Result<Value, Error> {
1204
9b06db45
DM
1205 let path = tools::required_string_param(&param, "path")?;
1206 let path = PathBuf::from(path);
ac716234 1207
181f097a
DM
1208 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
1209
ac716234
DM
1210 // we need a TTY to query the new password
1211 if !crate::tools::tty::stdin_isatty() {
1212 bail!("unable to change passphrase - no tty");
1213 }
1214
ab44acff 1215 let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
ac716234 1216
181f097a 1217 if kdf == "scrypt" {
ac716234 1218
181f097a
DM
1219 let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?;
1220 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
ac716234 1221
181f097a
DM
1222 if new_pw != verify_pw {
1223 bail!("Password verification fail!");
1224 }
1225
1226 if new_pw.len() < 5 {
1227 bail!("Password is too short!");
1228 }
ac716234 1229
ab44acff
DM
1230 let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?;
1231 new_key_config.created = created; // keep original value
1232
1233 store_key_config(&path, true, new_key_config)?;
ac716234 1234
181f097a
DM
1235 Ok(Value::Null)
1236 } else if kdf == "none" {
ab44acff 1237 let modified = Local.timestamp(Local::now().timestamp(), 0);
181f097a
DM
1238
1239 store_key_config(&path, true, KeyConfig {
1240 kdf: None,
ab44acff
DM
1241 created, // keep original value
1242 modified,
6d0983db 1243 data: key.to_vec(),
181f097a
DM
1244 })?;
1245
1246 Ok(Value::Null)
1247 } else {
1248 unreachable!();
1249 }
f2401311
DM
1250}
1251
1252fn key_mgmt_cli() -> CliCommandMap {
1253
181f097a
DM
1254 let kdf_schema: Arc<Schema> = Arc::new(
1255 StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.")
1256 .format(Arc::new(ApiStringFormat::Enum(&["scrypt", "none"])))
1257 .default("scrypt")
1258 .into()
1259 );
1260
f2401311
DM
1261 let key_create_cmd_def = CliCommand::new(
1262 ApiMethod::new(
1263 key_create,
1264 ObjectSchema::new("Create a new encryption key.")
9b06db45 1265 .required("path", StringSchema::new("File system path."))
181f097a 1266 .optional("kdf", kdf_schema.clone())
f2401311 1267 ))
9b06db45
DM
1268 .arg_param(vec!["path"])
1269 .completion_cb("path", tools::complete_file_name);
f2401311 1270
ac716234
DM
1271 let key_change_passphrase_cmd_def = CliCommand::new(
1272 ApiMethod::new(
1273 key_change_passphrase,
1274 ObjectSchema::new("Change the passphrase required to decrypt the key.")
9b06db45 1275 .required("path", StringSchema::new("File system path."))
181f097a 1276 .optional("kdf", kdf_schema.clone())
9b06db45
DM
1277 ))
1278 .arg_param(vec!["path"])
1279 .completion_cb("path", tools::complete_file_name);
ac716234 1280
37c5a175
DM
1281 let key_create_master_key_cmd_def = CliCommand::new(
1282 ApiMethod::new(
1283 key_create_master_key,
1284 ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.")
1285 ));
1286
3ea8bfc9
DM
1287 let key_import_master_pubkey_cmd_def = CliCommand::new(
1288 ApiMethod::new(
1289 key_import_master_pubkey,
1290 ObjectSchema::new("Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.")
1291 .required("path", StringSchema::new("File system path."))
1292 ))
1293 .arg_param(vec!["path"])
1294 .completion_cb("path", tools::complete_file_name);
1295
f2401311 1296 let cmd_def = CliCommandMap::new()
ac716234 1297 .insert("create".to_owned(), key_create_cmd_def.into())
37c5a175 1298 .insert("create-master-key".to_owned(), key_create_master_key_cmd_def.into())
3ea8bfc9 1299 .insert("import-master-pubkey".to_owned(), key_import_master_pubkey_cmd_def.into())
ac716234 1300 .insert("change-passphrase".to_owned(), key_change_passphrase_cmd_def.into());
f2401311
DM
1301
1302 cmd_def
1303}
1304
f2401311 1305fn main() {
33d64b81 1306
25f1650b
DM
1307 let backup_source_schema: Arc<Schema> = Arc::new(
1308 StringSchema::new("Backup source specification ([<label>:<path>]).")
1309 .format(Arc::new(ApiStringFormat::Pattern(&BACKUPSPEC_REGEX)))
1310 .into()
1311 );
1312
597a9203 1313 let backup_cmd_def = CliCommand::new(
ff5d3707 1314 ApiMethod::new(
bcd879cf 1315 create_backup,
597a9203 1316 ObjectSchema::new("Create (host) backup.")
ae0be2dd
DM
1317 .required(
1318 "backupspec",
1319 ArraySchema::new(
74cdb521 1320 "List of backup source specifications ([<label.ext>:<path>] ...)",
25f1650b 1321 backup_source_schema,
ae0be2dd
DM
1322 ).min_length(1)
1323 )
2665cef7 1324 .optional("repository", REPO_URL_SCHEMA.clone())
2eeaacb9
DM
1325 .optional(
1326 "include-dev",
1327 ArraySchema::new(
1328 "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.",
1329 StringSchema::new("Path to file.").into()
1330 )
1331 )
6d0983db
DM
1332 .optional(
1333 "keyfile",
1334 StringSchema::new("Path to encryption key. All data will be encrypted using this key."))
219ef0e6
DM
1335 .optional(
1336 "verbose",
1337 BooleanSchema::new("Verbose output.").default(false))
5b72c9b4
DM
1338 .optional(
1339 "skip-lost-and-found",
1340 BooleanSchema::new("Skip lost+found directory").default(false))
fba30411 1341 .optional(
bbf9e7e9
DM
1342 "backup-type",
1343 BACKUP_TYPE_SCHEMA.clone()
1344 )
1345 .optional(
1346 "backup-id",
1347 BACKUP_ID_SCHEMA.clone()
1348 )
ca5d0b61
DM
1349 .optional(
1350 "backup-time",
bbf9e7e9 1351 BACKUP_TIME_SCHEMA.clone()
ca5d0b61 1352 )
2d9d143a
DM
1353 .optional(
1354 "chunk-size",
1355 IntegerSchema::new("Chunk size in KB. Must be a power of 2.")
1356 .minimum(64)
1357 .maximum(4096)
1358 .default(4096)
1359 )
ff5d3707 1360 ))
2665cef7 1361 .arg_param(vec!["backupspec"])
d0a03d40 1362 .completion_cb("repository", complete_repository)
49811347 1363 .completion_cb("backupspec", complete_backup_source)
6d0983db 1364 .completion_cb("keyfile", tools::complete_file_name)
49811347 1365 .completion_cb("chunk-size", complete_chunk_size);
f8838fe9 1366
ec34f7eb
DM
1367 let upload_log_cmd_def = CliCommand::new(
1368 ApiMethod::new(
1369 upload_log,
1370 ObjectSchema::new("Upload backup log file.")
1371 .required("snapshot", StringSchema::new("Snapshot path."))
1372 .required("logfile", StringSchema::new("The path to the log file you want to upload."))
1373 .optional("repository", REPO_URL_SCHEMA.clone())
1374 .optional(
1375 "keyfile",
1376 StringSchema::new("Path to encryption key. All data will be encrypted using this key."))
1377 ))
1378 .arg_param(vec!["snapshot", "logfile"])
1379 .completion_cb("snapshot", complete_group_or_snapshot)
1380 .completion_cb("logfile", tools::complete_file_name)
1381 .completion_cb("keyfile", tools::complete_file_name)
1382 .completion_cb("repository", complete_repository);
1383
41c039e1
DM
1384 let list_cmd_def = CliCommand::new(
1385 ApiMethod::new(
812c6f87
DM
1386 list_backup_groups,
1387 ObjectSchema::new("List backup groups.")
2665cef7 1388 .optional("repository", REPO_URL_SCHEMA.clone())
34a816cc 1389 .optional("output-format", OUTPUT_FORMAT.clone())
41c039e1 1390 ))
d0a03d40 1391 .completion_cb("repository", complete_repository);
41c039e1 1392
184f17af
DM
1393 let snapshots_cmd_def = CliCommand::new(
1394 ApiMethod::new(
1395 list_snapshots,
1396 ObjectSchema::new("List backup snapshots.")
15c847f1 1397 .optional("group", StringSchema::new("Backup group."))
2665cef7 1398 .optional("repository", REPO_URL_SCHEMA.clone())
34a816cc 1399 .optional("output-format", OUTPUT_FORMAT.clone())
184f17af 1400 ))
2665cef7 1401 .arg_param(vec!["group"])
024f11bb 1402 .completion_cb("group", complete_backup_group)
d0a03d40 1403 .completion_cb("repository", complete_repository);
184f17af 1404
6f62c924
DM
1405 let forget_cmd_def = CliCommand::new(
1406 ApiMethod::new(
1407 forget_snapshots,
1408 ObjectSchema::new("Forget (remove) backup snapshots.")
6f62c924 1409 .required("snapshot", StringSchema::new("Snapshot path."))
2665cef7 1410 .optional("repository", REPO_URL_SCHEMA.clone())
6f62c924 1411 ))
2665cef7 1412 .arg_param(vec!["snapshot"])
b2388518
DM
1413 .completion_cb("repository", complete_repository)
1414 .completion_cb("snapshot", complete_group_or_snapshot);
6f62c924 1415
8cc0d6af
DM
1416 let garbage_collect_cmd_def = CliCommand::new(
1417 ApiMethod::new(
1418 start_garbage_collection,
1419 ObjectSchema::new("Start garbage collection for a specific repository.")
2665cef7 1420 .optional("repository", REPO_URL_SCHEMA.clone())
8cc0d6af 1421 ))
d0a03d40 1422 .completion_cb("repository", complete_repository);
8cc0d6af 1423
9f912493
DM
1424 let restore_cmd_def = CliCommand::new(
1425 ApiMethod::new(
1426 restore,
1427 ObjectSchema::new("Restore backup repository.")
d5c34d98
DM
1428 .required("snapshot", StringSchema::new("Group/Snapshot path."))
1429 .required("archive-name", StringSchema::new("Backup archive name."))
bf125261
DM
1430 .required("target", StringSchema::new(r###"Target directory path. Use '-' to write to stdandard output.
1431
1432We do not extraxt '.pxar' archives when writing to stdandard output.
1433
1434"###
1435 ))
46d5aa0a
DM
1436 .optional(
1437 "allow-existing-dirs",
1438 BooleanSchema::new("Do not fail if directories already exists.").default(false))
2665cef7 1439 .optional("repository", REPO_URL_SCHEMA.clone())
86eda3eb
DM
1440 .optional("keyfile", StringSchema::new("Path to encryption key."))
1441 .optional(
1442 "verbose",
1443 BooleanSchema::new("Verbose output.").default(false)
1444 )
9f912493 1445 ))
2665cef7 1446 .arg_param(vec!["snapshot", "archive-name", "target"])
b2388518 1447 .completion_cb("repository", complete_repository)
08dc340a
DM
1448 .completion_cb("snapshot", complete_group_or_snapshot)
1449 .completion_cb("archive-name", complete_archive_name)
1450 .completion_cb("target", tools::complete_file_name);
9f912493 1451
83b7db02
DM
1452 let prune_cmd_def = CliCommand::new(
1453 ApiMethod::new(
1454 prune,
1455 proxmox_backup::api2::admin::datastore::add_common_prune_prameters(
1456 ObjectSchema::new("Prune backup repository.")
9fdc3ef4 1457 .required("group", StringSchema::new("Backup group."))
2665cef7 1458 .optional("repository", REPO_URL_SCHEMA.clone())
83b7db02
DM
1459 )
1460 ))
9fdc3ef4
DM
1461 .arg_param(vec!["group"])
1462 .completion_cb("group", complete_backup_group)
d0a03d40 1463 .completion_cb("repository", complete_repository);
9f912493 1464
34a816cc
DM
1465 let status_cmd_def = CliCommand::new(
1466 ApiMethod::new(
1467 status,
1468 ObjectSchema::new("Get repository status.")
1469 .optional("repository", REPO_URL_SCHEMA.clone())
1470 .optional("output-format", OUTPUT_FORMAT.clone())
1471 ))
1472 .completion_cb("repository", complete_repository);
1473
41c039e1 1474 let cmd_def = CliCommandMap::new()
597a9203 1475 .insert("backup".to_owned(), backup_cmd_def.into())
ec34f7eb 1476 .insert("upload-log".to_owned(), upload_log_cmd_def.into())
6f62c924 1477 .insert("forget".to_owned(), forget_cmd_def.into())
8cc0d6af 1478 .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into())
83b7db02 1479 .insert("list".to_owned(), list_cmd_def.into())
184f17af 1480 .insert("prune".to_owned(), prune_cmd_def.into())
9f912493 1481 .insert("restore".to_owned(), restore_cmd_def.into())
f2401311 1482 .insert("snapshots".to_owned(), snapshots_cmd_def.into())
34a816cc 1483 .insert("status".to_owned(), status_cmd_def.into())
f2401311 1484 .insert("key".to_owned(), key_mgmt_cli().into());
a914a774 1485
5a2df000
DM
1486 hyper::rt::run(futures::future::lazy(move || {
1487 run_cli_command(cmd_def.into());
1488 Ok(())
1489 }));
496a6784 1490
ff5d3707 1491}