]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-client.rs
src/api2/admin/datastore.rs: backup logs may not be written twice
[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
36898ffc 427 let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize);
2d9d143a 428
247cdbce
DM
429 if let Some(size) = chunk_size_opt {
430 verify_chunk_size(size)?;
2d9d143a
DM
431 }
432
6d0983db
DM
433 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
434
fba30411
DM
435 let backup_id = param["host-id"].as_str().unwrap_or(&tools::nodename());
436
2eeaacb9
DM
437 let include_dev = param["include-dev"].as_array();
438
439 let mut devices = if all_file_systems { None } else { Some(HashSet::new()) };
440
441 if let Some(include_dev) = include_dev {
442 if all_file_systems {
443 bail!("option 'all-file-systems' conflicts with option 'include-dev'");
444 }
445
446 let mut set = HashSet::new();
447 for path in include_dev {
448 let path = path.as_str().unwrap();
449 let stat = nix::sys::stat::stat(path)
450 .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?;
451 set.insert(stat.st_dev);
452 }
453 devices = Some(set);
454 }
455
ae0be2dd 456 let mut upload_list = vec![];
a914a774 457
79679c2d 458 enum BackupType { PXAR, IMAGE, CONFIG, LOGFILE };
6af905c1 459
ae0be2dd
DM
460 for backupspec in backupspec_list {
461 let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?;
bcd879cf 462
eb1804c5
DM
463 use std::os::unix::fs::FileTypeExt;
464
465 let metadata = match std::fs::metadata(filename) {
466 Ok(m) => m,
ae0be2dd
DM
467 Err(err) => bail!("unable to access '{}' - {}", filename, err),
468 };
eb1804c5 469 let file_type = metadata.file_type();
23bb8780 470
ec8a9bb9 471 let extension = Path::new(target).extension().map(|s| s.to_str().unwrap()).unwrap();
bcd879cf 472
ec8a9bb9
DM
473 match extension {
474 "pxar" => {
475 if !file_type.is_dir() {
476 bail!("got unexpected file type (expected directory)");
477 }
478 upload_list.push((BackupType::PXAR, filename.to_owned(), target.to_owned(), 0));
479 }
480 "img" => {
eb1804c5 481
ec8a9bb9
DM
482 if !(file_type.is_file() || file_type.is_block_device()) {
483 bail!("got unexpected file type (expected file or block device)");
484 }
eb1804c5 485
ec8a9bb9 486 let size = tools::image_size(&PathBuf::from(filename))?;
23bb8780 487
ec8a9bb9 488 if size == 0 { bail!("got zero-sized file '{}'", filename); }
ae0be2dd 489
ec8a9bb9
DM
490 upload_list.push((BackupType::IMAGE, filename.to_owned(), target.to_owned(), size));
491 }
492 "conf" => {
493 if !file_type.is_file() {
494 bail!("got unexpected file type (expected regular file)");
495 }
496 upload_list.push((BackupType::CONFIG, filename.to_owned(), target.to_owned(), metadata.len()));
497 }
79679c2d
DM
498 "log" => {
499 if !file_type.is_file() {
500 bail!("got unexpected file type (expected regular file)");
501 }
502 upload_list.push((BackupType::LOGFILE, filename.to_owned(), target.to_owned(), metadata.len()));
503 }
ec8a9bb9
DM
504 _ => {
505 bail!("got unknown archive extension '{}'", extension);
506 }
ae0be2dd
DM
507 }
508 }
509
fa5d6977 510 let backup_time = Utc.timestamp(Utc::now().timestamp(), 0);
ae0be2dd 511
c4ff3dce 512 let client = HttpClient::new(repo.host(), repo.user())?;
d0a03d40
DM
513 record_repository(&repo);
514
cdebd467
DM
515 println!("Starting backup");
516 println!("Client name: {}", tools::nodename());
517 println!("Start Time: {}", backup_time.to_rfc3339());
51144821 518
bb823140
DM
519 let (crypt_config, rsa_encrypted_key) = match keyfile {
520 None => (None, None),
6d0983db 521 Some(path) => {
bb823140
DM
522 let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
523
524 let crypt_config = CryptConfig::new(key)?;
525
526 let path = master_pubkey_path()?;
527 if path.exists() {
528 let pem_data = proxmox_backup::tools::file_get_contents(&path)?;
529 let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
530 let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?;
531 (Some(Arc::new(crypt_config)), Some(enc_key))
532 } else {
533 (Some(Arc::new(crypt_config)), None)
534 }
6d0983db
DM
535 }
536 };
f98ac774 537
39e60bd6 538 let client = client.start_backup(repo.store(), "host", &backup_id, verbose).wait()?;
c4ff3dce 539
6af905c1
DM
540 for (backup_type, filename, target, size) in upload_list {
541 match backup_type {
ec8a9bb9
DM
542 BackupType::CONFIG => {
543 println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target);
9f46c7de 544 client.upload_blob_from_file(&filename, &target, crypt_config.clone(), true).wait()?;
ec8a9bb9 545 }
79679c2d
DM
546 BackupType::LOGFILE => {
547 println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target);
548 client.upload_blob_from_file(&filename, &target, crypt_config.clone(), true).wait()?;
549 }
6af905c1
DM
550 BackupType::PXAR => {
551 println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target);
f98ac774
DM
552 backup_directory(
553 &client,
554 &filename,
555 &target,
556 chunk_size_opt,
2eeaacb9 557 devices.clone(),
f98ac774 558 verbose,
5b72c9b4 559 skip_lost_and_found,
f98ac774
DM
560 crypt_config.clone(),
561 )?;
6af905c1
DM
562 }
563 BackupType::IMAGE => {
564 println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
f98ac774
DM
565 backup_image(
566 &client,
567 &filename,
568 &target,
569 size,
570 chunk_size_opt,
571 verbose,
572 crypt_config.clone(),
573 )?;
6af905c1
DM
574 }
575 }
4818c8b6
DM
576 }
577
bb823140
DM
578 if let Some(rsa_encrypted_key) = rsa_encrypted_key {
579 let target = "rsa-encrypted.key";
580 println!("Upload RSA encoded key to '{:?}' as {}", repo, target);
581 client.upload_blob_from_data(rsa_encrypted_key, target, None, false).wait()?;
582
583 // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t
584 /*
585 let mut buffer2 = vec![0u8; rsa.size() as usize];
586 let pem_data = proxmox_backup::tools::file_get_contents("master-private.pem")?;
587 let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?;
588 let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?;
589 println!("TEST {} {:?}", len, buffer2);
590 */
9f46c7de
DM
591 }
592
c4ff3dce
DM
593 client.finish().wait()?;
594
fa5d6977 595 let end_time = Utc.timestamp(Utc::now().timestamp(), 0);
3ec3ec3f
DM
596 let elapsed = end_time.signed_duration_since(backup_time);
597 println!("Duration: {}", elapsed);
598
cdebd467 599 println!("End Time: {}", end_time.to_rfc3339());
3d5c11e5 600
ff5d3707 601 Ok(Value::Null)
f98ea63d
DM
602}
603
d0a03d40 604fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
f98ea63d
DM
605
606 let mut result = vec![];
607
608 let data: Vec<&str> = arg.splitn(2, ':').collect();
609
bff11030 610 if data.len() != 2 {
8968258b
DM
611 result.push(String::from("root.pxar:/"));
612 result.push(String::from("etc.pxar:/etc"));
bff11030
DM
613 return result;
614 }
f98ea63d 615
496a6784 616 let files = tools::complete_file_name(data[1], param);
f98ea63d
DM
617
618 for file in files {
619 result.push(format!("{}:{}", data[0], file));
620 }
621
622 result
ff5d3707 623}
624
9f912493
DM
625fn restore(
626 param: Value,
627 _info: &ApiMethod,
dd5495d6 628 _rpcenv: &mut dyn RpcEnvironment,
9f912493
DM
629) -> Result<Value, Error> {
630
2665cef7 631 let repo = extract_repository_from_value(&param)?;
9f912493 632
86eda3eb
DM
633 let verbose = param["verbose"].as_bool().unwrap_or(false);
634
d5c34d98
DM
635 let archive_name = tools::required_string_param(&param, "archive-name")?;
636
86eda3eb 637 let client = HttpClient::new(repo.host(), repo.user())?;
d0a03d40 638
d0a03d40 639 record_repository(&repo);
d5c34d98 640
9f912493 641 let path = tools::required_string_param(&param, "snapshot")?;
9f912493 642
86eda3eb 643 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
d5c34d98 644 let group = BackupGroup::parse(path)?;
9f912493 645
9e391bb7
DM
646 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
647 let result = client.get(&path, Some(json!({
d5c34d98
DM
648 "backup-type": group.backup_type(),
649 "backup-id": group.backup_id(),
9e391bb7 650 }))).wait()?;
9f912493 651
d5c34d98
DM
652 let list = result["data"].as_array().unwrap();
653 if list.len() == 0 {
654 bail!("backup group '{}' does not contain any snapshots:", path);
655 }
9f912493 656
86eda3eb 657 let epoch = list[0]["backup-time"].as_i64().unwrap();
fa5d6977 658 let backup_time = Utc.timestamp(epoch, 0);
86eda3eb 659 (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time)
d5c34d98
DM
660 } else {
661 let snapshot = BackupDir::parse(path)?;
86eda3eb
DM
662 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
663 };
9f912493 664
d5c34d98 665 let target = tools::required_string_param(&param, "target")?;
bf125261 666 let target = if target == "-" { None } else { Some(target) };
2ae7d196 667
86eda3eb 668 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
2ae7d196 669
86eda3eb
DM
670 let crypt_config = match keyfile {
671 None => None,
672 Some(path) => {
673 let (key, _) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
674 Some(Arc::new(CryptConfig::new(key)?))
675 }
676 };
d5c34d98 677
afb4cd28
DM
678 let server_archive_name = if archive_name.ends_with(".pxar") {
679 format!("{}.didx", archive_name)
680 } else if archive_name.ends_with(".img") {
681 format!("{}.fidx", archive_name)
682 } else {
f8100e96 683 format!("{}.blob", archive_name)
afb4cd28 684 };
9f912493 685
86eda3eb
DM
686 let client = client.start_backup_reader(repo.store(), &backup_type, &backup_id, backup_time, true).wait()?;
687
688 use std::os::unix::fs::OpenOptionsExt;
689
690 let tmpfile = std::fs::OpenOptions::new()
691 .write(true)
692 .read(true)
693 .custom_flags(libc::O_TMPFILE)
694 .open("/tmp")?;
695
f8100e96
DM
696 if server_archive_name.ends_with(".blob") {
697
698 let writer = Vec::with_capacity(1024*1024);
699 let blob_data = client.download(&server_archive_name, writer).wait()?;
700 let blob = DataBlob::from_raw(blob_data)?;
701 blob.verify_crc()?;
702
703 let raw_data = match crypt_config {
704 Some(ref crypt_config) => blob.decode(Some(crypt_config))?,
705 None => blob.decode(None)?,
706 };
707
bf125261
DM
708 if let Some(target) = target {
709 crate::tools::file_set_contents(target, &raw_data, None)?;
710 } else {
711 let stdout = std::io::stdout();
712 let mut writer = stdout.lock();
713 writer.write_all(&raw_data)
714 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
715 }
f8100e96
DM
716
717 } else if server_archive_name.ends_with(".didx") {
afb4cd28 718 let tmpfile = client.download(&server_archive_name, tmpfile).wait()?;
86eda3eb 719
afb4cd28
DM
720 let index = DynamicIndexReader::new(tmpfile)
721 .map_err(|err| format_err!("unable to read dynamic index '{}' - {}", archive_name, err))?;
86eda3eb 722
f4bf7dfc
DM
723 let most_used = index.find_most_used_chunks(8);
724
725 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
726
afb4cd28 727 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
86eda3eb 728
bf125261 729 if let Some(target) = target {
86eda3eb 730
bf125261
DM
731 let feature_flags = pxar::CA_FORMAT_DEFAULT;
732 let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags, |path| {
733 if verbose {
734 println!("{:?}", path);
735 }
736 Ok(())
737 });
738
fa7e957c 739 decoder.restore(Path::new(target), &Vec::new())?;
bf125261
DM
740 } else {
741 let stdout = std::io::stdout();
742 let mut writer = stdout.lock();
afb4cd28 743
bf125261
DM
744 std::io::copy(&mut reader, &mut writer)
745 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
746 }
afb4cd28
DM
747 } else if server_archive_name.ends_with(".fidx") {
748 let tmpfile = client.download(&server_archive_name, tmpfile).wait()?;
749
750 let index = FixedIndexReader::new(tmpfile)
751 .map_err(|err| format_err!("unable to read fixed index '{}' - {}", archive_name, err))?;
7dcbe051 752
f4bf7dfc
DM
753 let most_used = index.find_most_used_chunks(8);
754
755 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
756
afb4cd28
DM
757 let mut reader = BufferedFixedReader::new(index, chunk_reader);
758
bf125261
DM
759 if let Some(target) = target {
760 let mut writer = std::fs::OpenOptions::new()
761 .write(true)
762 .create(true)
763 .create_new(true)
764 .open(target)
765 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
766
767 std::io::copy(&mut reader, &mut writer)
768 .map_err(|err| format_err!("unable to store data - {}", err))?;
769 } else {
770 let stdout = std::io::stdout();
771 let mut writer = stdout.lock();
afb4cd28 772
bf125261
DM
773 std::io::copy(&mut reader, &mut writer)
774 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
775 }
45db6f89 776 } else {
f8100e96 777 bail!("unknown archive file extension (expected .pxar of .img)");
3031e44c 778 }
fef44d4f
DM
779
780 Ok(Value::Null)
45db6f89
DM
781}
782
ec34f7eb
DM
783fn upload_log(
784 param: Value,
785 _info: &ApiMethod,
786 _rpcenv: &mut dyn RpcEnvironment,
787) -> Result<Value, Error> {
788
789 let logfile = tools::required_string_param(&param, "logfile")?;
790 let repo = extract_repository_from_value(&param)?;
791
792 let snapshot = tools::required_string_param(&param, "snapshot")?;
793 let snapshot = BackupDir::parse(snapshot)?;
794
795 let mut client = HttpClient::new(repo.host(), repo.user())?;
796
797 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
798
799 let crypt_config = match keyfile {
800 None => None,
801 Some(path) => {
802 let (key, _created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
803 let crypt_config = CryptConfig::new(key)?;
804 Some(crypt_config)
805 }
806 };
807
808 let data = crate::tools::file_get_contents(logfile)?;
809
810 let blob = if let Some(ref crypt_config) = crypt_config {
811 DataBlob::encode(&data, Some(crypt_config), true)?
812 } else {
813 DataBlob::encode(&data, None, true)?
814 };
815
816 let raw_data = blob.into_inner();
817
818 let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store());
819
820 let args = json!({
821 "backup-type": snapshot.group().backup_type(),
822 "backup-id": snapshot.group().backup_id(),
823 "backup-time": snapshot.backup_time().timestamp(),
824 });
825
826 let body = hyper::Body::from(raw_data);
827
828 let result = client.upload("application/octet-stream", body, &path, Some(args)).wait()?;
829
830 Ok(result)
831}
832
83b7db02
DM
833fn prune(
834 mut param: Value,
835 _info: &ApiMethod,
dd5495d6 836 _rpcenv: &mut dyn RpcEnvironment,
83b7db02
DM
837) -> Result<Value, Error> {
838
2665cef7 839 let repo = extract_repository_from_value(&param)?;
83b7db02 840
45cdce06 841 let mut client = HttpClient::new(repo.host(), repo.user())?;
83b7db02 842
d0a03d40 843 let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
83b7db02
DM
844
845 param.as_object_mut().unwrap().remove("repository");
846
5a2df000 847 let result = client.post(&path, Some(param)).wait()?;
83b7db02 848
d0a03d40
DM
849 record_repository(&repo);
850
83b7db02
DM
851 Ok(result)
852}
853
34a816cc
DM
854fn status(
855 param: Value,
856 _info: &ApiMethod,
857 _rpcenv: &mut dyn RpcEnvironment,
858) -> Result<Value, Error> {
859
860 let repo = extract_repository_from_value(&param)?;
861
862 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
863
864 let client = HttpClient::new(repo.host(), repo.user())?;
865
866 let path = format!("api2/json/admin/datastore/{}/status", repo.store());
867
868 let result = client.get(&path, None).wait()?;
869 let data = &result["data"];
870
871 record_repository(&repo);
872
873 if output_format == "text" {
874 let total = data["total"].as_u64().unwrap();
875 let used = data["used"].as_u64().unwrap();
876 let avail = data["avail"].as_u64().unwrap();
877 let roundup = total/200;
878
879 println!(
880 "total: {} used: {} ({} %) available: {}",
881 total,
882 used,
883 ((used+roundup)*100)/total,
884 avail,
885 );
886 } else {
f6ede796 887 format_and_print_result(data, &output_format);
34a816cc
DM
888 }
889
890 Ok(Value::Null)
891}
892
5a2df000 893// like get, but simply ignore errors and return Null instead
b2388518 894fn try_get(repo: &BackupRepository, url: &str) -> Value {
024f11bb 895
45cdce06
DM
896 let client = match HttpClient::new(repo.host(), repo.user()) {
897 Ok(v) => v,
898 _ => return Value::Null,
899 };
b2388518 900
9e391bb7 901 let mut resp = match client.get(url, None).wait() {
b2388518
DM
902 Ok(v) => v,
903 _ => return Value::Null,
904 };
905
906 if let Some(map) = resp.as_object_mut() {
907 if let Some(data) = map.remove("data") {
908 return data;
909 }
910 }
911 Value::Null
912}
913
b2388518 914fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
024f11bb 915
b2388518
DM
916 let mut result = vec![];
917
2665cef7 918 let repo = match extract_repository_from_map(param) {
b2388518 919 Some(v) => v,
024f11bb
DM
920 _ => return result,
921 };
922
b2388518
DM
923 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
924
925 let data = try_get(&repo, &path);
926
927 if let Some(list) = data.as_array() {
024f11bb 928 for item in list {
98f0b972
DM
929 if let (Some(backup_id), Some(backup_type)) =
930 (item["backup-id"].as_str(), item["backup-type"].as_str())
931 {
932 result.push(format!("{}/{}", backup_type, backup_id));
024f11bb
DM
933 }
934 }
935 }
936
937 result
938}
939
b2388518
DM
940fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
941
942 let mut result = vec![];
943
2665cef7 944 let repo = match extract_repository_from_map(param) {
b2388518
DM
945 Some(v) => v,
946 _ => return result,
947 };
948
949 if arg.matches('/').count() < 2 {
950 let groups = complete_backup_group(arg, param);
951 for group in groups {
952 result.push(group.to_string());
953 result.push(format!("{}/", group));
954 }
955 return result;
956 }
957
958 let mut parts = arg.split('/');
959 let query = tools::json_object_to_query(json!({
960 "backup-type": parts.next().unwrap(),
961 "backup-id": parts.next().unwrap(),
962 })).unwrap();
963
964 let path = format!("api2/json/admin/datastore/{}/snapshots?{}", repo.store(), query);
965
966 let data = try_get(&repo, &path);
967
968 if let Some(list) = data.as_array() {
969 for item in list {
970 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
971 (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
972 {
973 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
974 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
975 }
976 }
977 }
978
979 result
980}
981
45db6f89 982fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
08dc340a
DM
983
984 let mut result = vec![];
985
2665cef7 986 let repo = match extract_repository_from_map(param) {
08dc340a
DM
987 Some(v) => v,
988 _ => return result,
989 };
990
991 let snapshot = match param.get("snapshot") {
992 Some(path) => {
993 match BackupDir::parse(path) {
994 Ok(v) => v,
995 _ => return result,
996 }
997 }
998 _ => return result,
999 };
1000
1001 let query = tools::json_object_to_query(json!({
1002 "backup-type": snapshot.group().backup_type(),
1003 "backup-id": snapshot.group().backup_id(),
1004 "backup-time": snapshot.backup_time().timestamp(),
1005 })).unwrap();
1006
1007 let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
1008
1009 let data = try_get(&repo, &path);
1010
1011 if let Some(list) = data.as_array() {
1012 for item in list {
1013 if let Some(filename) = item.as_str() {
1014 result.push(filename.to_owned());
1015 }
1016 }
1017 }
1018
45db6f89
DM
1019 result
1020}
1021
1022fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1023
1024 let result = complete_server_file_name(arg, param);
1025
6899dbfb 1026 strip_server_file_expenstions(result)
08dc340a
DM
1027}
1028
49811347
DM
1029fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
1030
1031 let mut result = vec![];
1032
1033 let mut size = 64;
1034 loop {
1035 result.push(size.to_string());
1036 size = size * 2;
1037 if size > 4096 { break; }
1038 }
1039
1040 result
1041}
1042
826f309b 1043fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
ff5d3707 1044
f2401311
DM
1045 // fixme: implement other input methods
1046
1047 use std::env::VarError::*;
1048 match std::env::var("PBS_ENCRYPTION_PASSWORD") {
826f309b 1049 Ok(p) => return Ok(p.as_bytes().to_vec()),
f2401311
DM
1050 Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
1051 Err(NotPresent) => {
1052 // Try another method
1053 }
1054 }
1055
1056 // If we're on a TTY, query the user for a password
1057 if crate::tools::tty::stdin_isatty() {
826f309b 1058 return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?);
f2401311
DM
1059 }
1060
1061 bail!("no password input mechanism available");
1062}
1063
ac716234
DM
1064fn key_create(
1065 param: Value,
1066 _info: &ApiMethod,
1067 _rpcenv: &mut dyn RpcEnvironment,
1068) -> Result<Value, Error> {
1069
9b06db45
DM
1070 let path = tools::required_string_param(&param, "path")?;
1071 let path = PathBuf::from(path);
ac716234 1072
181f097a 1073 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
ac716234
DM
1074
1075 let key = proxmox::sys::linux::random_data(32)?;
1076
181f097a
DM
1077 if kdf == "scrypt" {
1078 // always read passphrase from tty
1079 if !crate::tools::tty::stdin_isatty() {
1080 bail!("unable to read passphrase - no tty");
1081 }
ac716234 1082
181f097a
DM
1083 let password = crate::tools::tty::read_password("Encryption Key Password: ")?;
1084
ab44acff 1085 let key_config = encrypt_key_with_passphrase(&key, &password)?;
37c5a175 1086
ab44acff 1087 store_key_config(&path, false, key_config)?;
181f097a
DM
1088
1089 Ok(Value::Null)
1090 } else if kdf == "none" {
1091 let created = Local.timestamp(Local::now().timestamp(), 0);
1092
1093 store_key_config(&path, false, KeyConfig {
1094 kdf: None,
1095 created,
ab44acff 1096 modified: created,
181f097a
DM
1097 data: key,
1098 })?;
1099
1100 Ok(Value::Null)
1101 } else {
1102 unreachable!();
1103 }
ac716234
DM
1104}
1105
9f46c7de
DM
1106fn master_pubkey_path() -> Result<PathBuf, Error> {
1107 let base = BaseDirectories::with_prefix("proxmox-backup")?;
1108
1109 // usually $HOME/.config/proxmox-backup/master-public.pem
1110 let path = base.place_config_file("master-public.pem")?;
1111
1112 Ok(path)
1113}
1114
3ea8bfc9
DM
1115fn key_import_master_pubkey(
1116 param: Value,
1117 _info: &ApiMethod,
1118 _rpcenv: &mut dyn RpcEnvironment,
1119) -> Result<Value, Error> {
1120
1121 let path = tools::required_string_param(&param, "path")?;
1122 let path = PathBuf::from(path);
1123
1124 let pem_data = proxmox_backup::tools::file_get_contents(&path)?;
1125
1126 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
1127 bail!("Unable to decode PEM data - {}", err);
1128 }
1129
9f46c7de 1130 let target_path = master_pubkey_path()?;
3ea8bfc9
DM
1131
1132 proxmox_backup::tools::file_set_contents(&target_path, &pem_data, None)?;
1133
1134 println!("Imported public master key to {:?}", target_path);
1135
1136 Ok(Value::Null)
1137}
1138
37c5a175
DM
1139fn key_create_master_key(
1140 _param: Value,
1141 _info: &ApiMethod,
1142 _rpcenv: &mut dyn RpcEnvironment,
1143) -> Result<Value, Error> {
1144
1145 // we need a TTY to query the new password
1146 if !crate::tools::tty::stdin_isatty() {
1147 bail!("unable to create master key - no tty");
1148 }
1149
1150 let rsa = openssl::rsa::Rsa::generate(4096)?;
1151 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
1152
1153 let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?;
1154 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
1155
1156 if new_pw != verify_pw {
1157 bail!("Password verification fail!");
1158 }
1159
1160 if new_pw.len() < 5 {
1161 bail!("Password is too short!");
1162 }
1163
1164 let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
1165 let filename_pub = "master-public.pem";
1166 println!("Writing public master key to {}", filename_pub);
1167 proxmox_backup::tools::file_set_contents(filename_pub, pub_key.as_slice(), None)?;
1168
1169 let cipher = openssl::symm::Cipher::aes_256_cbc();
1170 let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?;
1171
1172 let filename_priv = "master-private.pem";
1173 println!("Writing private master key to {}", filename_priv);
1174 proxmox_backup::tools::file_set_contents(filename_priv, priv_key.as_slice(), None)?;
1175
1176 Ok(Value::Null)
1177}
ac716234
DM
1178
1179fn key_change_passphrase(
1180 param: Value,
1181 _info: &ApiMethod,
1182 _rpcenv: &mut dyn RpcEnvironment,
1183) -> Result<Value, Error> {
1184
9b06db45
DM
1185 let path = tools::required_string_param(&param, "path")?;
1186 let path = PathBuf::from(path);
ac716234 1187
181f097a
DM
1188 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
1189
ac716234
DM
1190 // we need a TTY to query the new password
1191 if !crate::tools::tty::stdin_isatty() {
1192 bail!("unable to change passphrase - no tty");
1193 }
1194
ab44acff 1195 let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
ac716234 1196
181f097a 1197 if kdf == "scrypt" {
ac716234 1198
181f097a
DM
1199 let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?;
1200 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
ac716234 1201
181f097a
DM
1202 if new_pw != verify_pw {
1203 bail!("Password verification fail!");
1204 }
1205
1206 if new_pw.len() < 5 {
1207 bail!("Password is too short!");
1208 }
ac716234 1209
ab44acff
DM
1210 let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?;
1211 new_key_config.created = created; // keep original value
1212
1213 store_key_config(&path, true, new_key_config)?;
ac716234 1214
181f097a
DM
1215 Ok(Value::Null)
1216 } else if kdf == "none" {
ab44acff 1217 let modified = Local.timestamp(Local::now().timestamp(), 0);
181f097a
DM
1218
1219 store_key_config(&path, true, KeyConfig {
1220 kdf: None,
ab44acff
DM
1221 created, // keep original value
1222 modified,
6d0983db 1223 data: key.to_vec(),
181f097a
DM
1224 })?;
1225
1226 Ok(Value::Null)
1227 } else {
1228 unreachable!();
1229 }
f2401311
DM
1230}
1231
1232fn key_mgmt_cli() -> CliCommandMap {
1233
181f097a
DM
1234 let kdf_schema: Arc<Schema> = Arc::new(
1235 StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.")
1236 .format(Arc::new(ApiStringFormat::Enum(&["scrypt", "none"])))
1237 .default("scrypt")
1238 .into()
1239 );
1240
f2401311
DM
1241 let key_create_cmd_def = CliCommand::new(
1242 ApiMethod::new(
1243 key_create,
1244 ObjectSchema::new("Create a new encryption key.")
9b06db45 1245 .required("path", StringSchema::new("File system path."))
181f097a 1246 .optional("kdf", kdf_schema.clone())
f2401311 1247 ))
9b06db45
DM
1248 .arg_param(vec!["path"])
1249 .completion_cb("path", tools::complete_file_name);
f2401311 1250
ac716234
DM
1251 let key_change_passphrase_cmd_def = CliCommand::new(
1252 ApiMethod::new(
1253 key_change_passphrase,
1254 ObjectSchema::new("Change the passphrase required to decrypt the key.")
9b06db45 1255 .required("path", StringSchema::new("File system path."))
181f097a 1256 .optional("kdf", kdf_schema.clone())
9b06db45
DM
1257 ))
1258 .arg_param(vec!["path"])
1259 .completion_cb("path", tools::complete_file_name);
ac716234 1260
37c5a175
DM
1261 let key_create_master_key_cmd_def = CliCommand::new(
1262 ApiMethod::new(
1263 key_create_master_key,
1264 ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.")
1265 ));
1266
3ea8bfc9
DM
1267 let key_import_master_pubkey_cmd_def = CliCommand::new(
1268 ApiMethod::new(
1269 key_import_master_pubkey,
1270 ObjectSchema::new("Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.")
1271 .required("path", StringSchema::new("File system path."))
1272 ))
1273 .arg_param(vec!["path"])
1274 .completion_cb("path", tools::complete_file_name);
1275
f2401311 1276 let cmd_def = CliCommandMap::new()
ac716234 1277 .insert("create".to_owned(), key_create_cmd_def.into())
37c5a175 1278 .insert("create-master-key".to_owned(), key_create_master_key_cmd_def.into())
3ea8bfc9 1279 .insert("import-master-pubkey".to_owned(), key_import_master_pubkey_cmd_def.into())
ac716234 1280 .insert("change-passphrase".to_owned(), key_change_passphrase_cmd_def.into());
f2401311
DM
1281
1282 cmd_def
1283}
1284
f2401311 1285fn main() {
33d64b81 1286
25f1650b
DM
1287 let backup_source_schema: Arc<Schema> = Arc::new(
1288 StringSchema::new("Backup source specification ([<label>:<path>]).")
1289 .format(Arc::new(ApiStringFormat::Pattern(&BACKUPSPEC_REGEX)))
1290 .into()
1291 );
1292
597a9203 1293 let backup_cmd_def = CliCommand::new(
ff5d3707 1294 ApiMethod::new(
bcd879cf 1295 create_backup,
597a9203 1296 ObjectSchema::new("Create (host) backup.")
ae0be2dd
DM
1297 .required(
1298 "backupspec",
1299 ArraySchema::new(
74cdb521 1300 "List of backup source specifications ([<label.ext>:<path>] ...)",
25f1650b 1301 backup_source_schema,
ae0be2dd
DM
1302 ).min_length(1)
1303 )
2665cef7 1304 .optional("repository", REPO_URL_SCHEMA.clone())
2eeaacb9
DM
1305 .optional(
1306 "include-dev",
1307 ArraySchema::new(
1308 "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.",
1309 StringSchema::new("Path to file.").into()
1310 )
1311 )
6d0983db
DM
1312 .optional(
1313 "keyfile",
1314 StringSchema::new("Path to encryption key. All data will be encrypted using this key."))
219ef0e6
DM
1315 .optional(
1316 "verbose",
1317 BooleanSchema::new("Verbose output.").default(false))
5b72c9b4
DM
1318 .optional(
1319 "skip-lost-and-found",
1320 BooleanSchema::new("Skip lost+found directory").default(false))
fba30411
DM
1321 .optional(
1322 "host-id",
1323 StringSchema::new("Use specified ID for the backup group name ('host/<id>'). The default is the system hostname."))
2d9d143a
DM
1324 .optional(
1325 "chunk-size",
1326 IntegerSchema::new("Chunk size in KB. Must be a power of 2.")
1327 .minimum(64)
1328 .maximum(4096)
1329 .default(4096)
1330 )
ff5d3707 1331 ))
2665cef7 1332 .arg_param(vec!["backupspec"])
d0a03d40 1333 .completion_cb("repository", complete_repository)
49811347 1334 .completion_cb("backupspec", complete_backup_source)
6d0983db 1335 .completion_cb("keyfile", tools::complete_file_name)
49811347 1336 .completion_cb("chunk-size", complete_chunk_size);
f8838fe9 1337
ec34f7eb
DM
1338 let upload_log_cmd_def = CliCommand::new(
1339 ApiMethod::new(
1340 upload_log,
1341 ObjectSchema::new("Upload backup log file.")
1342 .required("snapshot", StringSchema::new("Snapshot path."))
1343 .required("logfile", StringSchema::new("The path to the log file you want to upload."))
1344 .optional("repository", REPO_URL_SCHEMA.clone())
1345 .optional(
1346 "keyfile",
1347 StringSchema::new("Path to encryption key. All data will be encrypted using this key."))
1348 ))
1349 .arg_param(vec!["snapshot", "logfile"])
1350 .completion_cb("snapshot", complete_group_or_snapshot)
1351 .completion_cb("logfile", tools::complete_file_name)
1352 .completion_cb("keyfile", tools::complete_file_name)
1353 .completion_cb("repository", complete_repository);
1354
41c039e1
DM
1355 let list_cmd_def = CliCommand::new(
1356 ApiMethod::new(
812c6f87
DM
1357 list_backup_groups,
1358 ObjectSchema::new("List backup groups.")
2665cef7 1359 .optional("repository", REPO_URL_SCHEMA.clone())
34a816cc 1360 .optional("output-format", OUTPUT_FORMAT.clone())
41c039e1 1361 ))
d0a03d40 1362 .completion_cb("repository", complete_repository);
41c039e1 1363
184f17af
DM
1364 let snapshots_cmd_def = CliCommand::new(
1365 ApiMethod::new(
1366 list_snapshots,
1367 ObjectSchema::new("List backup snapshots.")
15c847f1 1368 .optional("group", StringSchema::new("Backup group."))
2665cef7 1369 .optional("repository", REPO_URL_SCHEMA.clone())
34a816cc 1370 .optional("output-format", OUTPUT_FORMAT.clone())
184f17af 1371 ))
2665cef7 1372 .arg_param(vec!["group"])
024f11bb 1373 .completion_cb("group", complete_backup_group)
d0a03d40 1374 .completion_cb("repository", complete_repository);
184f17af 1375
6f62c924
DM
1376 let forget_cmd_def = CliCommand::new(
1377 ApiMethod::new(
1378 forget_snapshots,
1379 ObjectSchema::new("Forget (remove) backup snapshots.")
6f62c924 1380 .required("snapshot", StringSchema::new("Snapshot path."))
2665cef7 1381 .optional("repository", REPO_URL_SCHEMA.clone())
6f62c924 1382 ))
2665cef7 1383 .arg_param(vec!["snapshot"])
b2388518
DM
1384 .completion_cb("repository", complete_repository)
1385 .completion_cb("snapshot", complete_group_or_snapshot);
6f62c924 1386
8cc0d6af
DM
1387 let garbage_collect_cmd_def = CliCommand::new(
1388 ApiMethod::new(
1389 start_garbage_collection,
1390 ObjectSchema::new("Start garbage collection for a specific repository.")
2665cef7 1391 .optional("repository", REPO_URL_SCHEMA.clone())
8cc0d6af 1392 ))
d0a03d40 1393 .completion_cb("repository", complete_repository);
8cc0d6af 1394
9f912493
DM
1395 let restore_cmd_def = CliCommand::new(
1396 ApiMethod::new(
1397 restore,
1398 ObjectSchema::new("Restore backup repository.")
d5c34d98
DM
1399 .required("snapshot", StringSchema::new("Group/Snapshot path."))
1400 .required("archive-name", StringSchema::new("Backup archive name."))
bf125261
DM
1401 .required("target", StringSchema::new(r###"Target directory path. Use '-' to write to stdandard output.
1402
1403We do not extraxt '.pxar' archives when writing to stdandard output.
1404
1405"###
1406 ))
2665cef7 1407 .optional("repository", REPO_URL_SCHEMA.clone())
86eda3eb
DM
1408 .optional("keyfile", StringSchema::new("Path to encryption key."))
1409 .optional(
1410 "verbose",
1411 BooleanSchema::new("Verbose output.").default(false)
1412 )
9f912493 1413 ))
2665cef7 1414 .arg_param(vec!["snapshot", "archive-name", "target"])
b2388518 1415 .completion_cb("repository", complete_repository)
08dc340a
DM
1416 .completion_cb("snapshot", complete_group_or_snapshot)
1417 .completion_cb("archive-name", complete_archive_name)
1418 .completion_cb("target", tools::complete_file_name);
9f912493 1419
83b7db02
DM
1420 let prune_cmd_def = CliCommand::new(
1421 ApiMethod::new(
1422 prune,
1423 proxmox_backup::api2::admin::datastore::add_common_prune_prameters(
1424 ObjectSchema::new("Prune backup repository.")
2665cef7 1425 .optional("repository", REPO_URL_SCHEMA.clone())
83b7db02
DM
1426 )
1427 ))
d0a03d40 1428 .completion_cb("repository", complete_repository);
9f912493 1429
34a816cc
DM
1430 let status_cmd_def = CliCommand::new(
1431 ApiMethod::new(
1432 status,
1433 ObjectSchema::new("Get repository status.")
1434 .optional("repository", REPO_URL_SCHEMA.clone())
1435 .optional("output-format", OUTPUT_FORMAT.clone())
1436 ))
1437 .completion_cb("repository", complete_repository);
1438
41c039e1 1439 let cmd_def = CliCommandMap::new()
597a9203 1440 .insert("backup".to_owned(), backup_cmd_def.into())
ec34f7eb 1441 .insert("upload-log".to_owned(), upload_log_cmd_def.into())
6f62c924 1442 .insert("forget".to_owned(), forget_cmd_def.into())
8cc0d6af 1443 .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into())
83b7db02 1444 .insert("list".to_owned(), list_cmd_def.into())
184f17af 1445 .insert("prune".to_owned(), prune_cmd_def.into())
9f912493 1446 .insert("restore".to_owned(), restore_cmd_def.into())
f2401311 1447 .insert("snapshots".to_owned(), snapshots_cmd_def.into())
34a816cc 1448 .insert("status".to_owned(), status_cmd_def.into())
f2401311 1449 .insert("key".to_owned(), key_mgmt_cli().into());
a914a774 1450
5a2df000
DM
1451 hyper::rt::run(futures::future::lazy(move || {
1452 run_cli_command(cmd_def.into());
1453 Ok(())
1454 }));
496a6784 1455
ff5d3707 1456}