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