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