]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-client.rs
src/bin/proxmox-backup-client.rs: correctly compute duration
[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
DM
842fn prune(
843 mut param: Value,
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
DM
853
854 param.as_object_mut().unwrap().remove("repository");
855
5a2df000 856 let result = client.post(&path, Some(param)).wait()?;
83b7db02 857
d0a03d40
DM
858 record_repository(&repo);
859
83b7db02
DM
860 Ok(result)
861}
862
34a816cc
DM
863fn status(
864 param: Value,
865 _info: &ApiMethod,
866 _rpcenv: &mut dyn RpcEnvironment,
867) -> Result<Value, Error> {
868
869 let repo = extract_repository_from_value(&param)?;
870
871 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
872
873 let client = HttpClient::new(repo.host(), repo.user())?;
874
875 let path = format!("api2/json/admin/datastore/{}/status", repo.store());
876
877 let result = client.get(&path, None).wait()?;
878 let data = &result["data"];
879
880 record_repository(&repo);
881
882 if output_format == "text" {
883 let total = data["total"].as_u64().unwrap();
884 let used = data["used"].as_u64().unwrap();
885 let avail = data["avail"].as_u64().unwrap();
886 let roundup = total/200;
887
888 println!(
889 "total: {} used: {} ({} %) available: {}",
890 total,
891 used,
892 ((used+roundup)*100)/total,
893 avail,
894 );
895 } else {
f6ede796 896 format_and_print_result(data, &output_format);
34a816cc
DM
897 }
898
899 Ok(Value::Null)
900}
901
5a2df000 902// like get, but simply ignore errors and return Null instead
b2388518 903fn try_get(repo: &BackupRepository, url: &str) -> Value {
024f11bb 904
45cdce06
DM
905 let client = match HttpClient::new(repo.host(), repo.user()) {
906 Ok(v) => v,
907 _ => return Value::Null,
908 };
b2388518 909
9e391bb7 910 let mut resp = match client.get(url, None).wait() {
b2388518
DM
911 Ok(v) => v,
912 _ => return Value::Null,
913 };
914
915 if let Some(map) = resp.as_object_mut() {
916 if let Some(data) = map.remove("data") {
917 return data;
918 }
919 }
920 Value::Null
921}
922
b2388518 923fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
024f11bb 924
b2388518
DM
925 let mut result = vec![];
926
2665cef7 927 let repo = match extract_repository_from_map(param) {
b2388518 928 Some(v) => v,
024f11bb
DM
929 _ => return result,
930 };
931
b2388518
DM
932 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
933
934 let data = try_get(&repo, &path);
935
936 if let Some(list) = data.as_array() {
024f11bb 937 for item in list {
98f0b972
DM
938 if let (Some(backup_id), Some(backup_type)) =
939 (item["backup-id"].as_str(), item["backup-type"].as_str())
940 {
941 result.push(format!("{}/{}", backup_type, backup_id));
024f11bb
DM
942 }
943 }
944 }
945
946 result
947}
948
b2388518
DM
949fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
950
951 let mut result = vec![];
952
2665cef7 953 let repo = match extract_repository_from_map(param) {
b2388518
DM
954 Some(v) => v,
955 _ => return result,
956 };
957
958 if arg.matches('/').count() < 2 {
959 let groups = complete_backup_group(arg, param);
960 for group in groups {
961 result.push(group.to_string());
962 result.push(format!("{}/", group));
963 }
964 return result;
965 }
966
967 let mut parts = arg.split('/');
968 let query = tools::json_object_to_query(json!({
969 "backup-type": parts.next().unwrap(),
970 "backup-id": parts.next().unwrap(),
971 })).unwrap();
972
973 let path = format!("api2/json/admin/datastore/{}/snapshots?{}", repo.store(), query);
974
975 let data = try_get(&repo, &path);
976
977 if let Some(list) = data.as_array() {
978 for item in list {
979 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
980 (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
981 {
982 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
983 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
984 }
985 }
986 }
987
988 result
989}
990
45db6f89 991fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
08dc340a
DM
992
993 let mut result = vec![];
994
2665cef7 995 let repo = match extract_repository_from_map(param) {
08dc340a
DM
996 Some(v) => v,
997 _ => return result,
998 };
999
1000 let snapshot = match param.get("snapshot") {
1001 Some(path) => {
1002 match BackupDir::parse(path) {
1003 Ok(v) => v,
1004 _ => return result,
1005 }
1006 }
1007 _ => return result,
1008 };
1009
1010 let query = tools::json_object_to_query(json!({
1011 "backup-type": snapshot.group().backup_type(),
1012 "backup-id": snapshot.group().backup_id(),
1013 "backup-time": snapshot.backup_time().timestamp(),
1014 })).unwrap();
1015
1016 let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
1017
1018 let data = try_get(&repo, &path);
1019
1020 if let Some(list) = data.as_array() {
1021 for item in list {
1022 if let Some(filename) = item.as_str() {
1023 result.push(filename.to_owned());
1024 }
1025 }
1026 }
1027
45db6f89
DM
1028 result
1029}
1030
1031fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1032
1033 let result = complete_server_file_name(arg, param);
1034
6899dbfb 1035 strip_server_file_expenstions(result)
08dc340a
DM
1036}
1037
49811347
DM
1038fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
1039
1040 let mut result = vec![];
1041
1042 let mut size = 64;
1043 loop {
1044 result.push(size.to_string());
1045 size = size * 2;
1046 if size > 4096 { break; }
1047 }
1048
1049 result
1050}
1051
826f309b 1052fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
ff5d3707 1053
f2401311
DM
1054 // fixme: implement other input methods
1055
1056 use std::env::VarError::*;
1057 match std::env::var("PBS_ENCRYPTION_PASSWORD") {
826f309b 1058 Ok(p) => return Ok(p.as_bytes().to_vec()),
f2401311
DM
1059 Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
1060 Err(NotPresent) => {
1061 // Try another method
1062 }
1063 }
1064
1065 // If we're on a TTY, query the user for a password
1066 if crate::tools::tty::stdin_isatty() {
826f309b 1067 return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?);
f2401311
DM
1068 }
1069
1070 bail!("no password input mechanism available");
1071}
1072
ac716234
DM
1073fn key_create(
1074 param: Value,
1075 _info: &ApiMethod,
1076 _rpcenv: &mut dyn RpcEnvironment,
1077) -> Result<Value, Error> {
1078
9b06db45
DM
1079 let path = tools::required_string_param(&param, "path")?;
1080 let path = PathBuf::from(path);
ac716234 1081
181f097a 1082 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
ac716234
DM
1083
1084 let key = proxmox::sys::linux::random_data(32)?;
1085
181f097a
DM
1086 if kdf == "scrypt" {
1087 // always read passphrase from tty
1088 if !crate::tools::tty::stdin_isatty() {
1089 bail!("unable to read passphrase - no tty");
1090 }
ac716234 1091
181f097a
DM
1092 let password = crate::tools::tty::read_password("Encryption Key Password: ")?;
1093
ab44acff 1094 let key_config = encrypt_key_with_passphrase(&key, &password)?;
37c5a175 1095
ab44acff 1096 store_key_config(&path, false, key_config)?;
181f097a
DM
1097
1098 Ok(Value::Null)
1099 } else if kdf == "none" {
1100 let created = Local.timestamp(Local::now().timestamp(), 0);
1101
1102 store_key_config(&path, false, KeyConfig {
1103 kdf: None,
1104 created,
ab44acff 1105 modified: created,
181f097a
DM
1106 data: key,
1107 })?;
1108
1109 Ok(Value::Null)
1110 } else {
1111 unreachable!();
1112 }
ac716234
DM
1113}
1114
9f46c7de
DM
1115fn master_pubkey_path() -> Result<PathBuf, Error> {
1116 let base = BaseDirectories::with_prefix("proxmox-backup")?;
1117
1118 // usually $HOME/.config/proxmox-backup/master-public.pem
1119 let path = base.place_config_file("master-public.pem")?;
1120
1121 Ok(path)
1122}
1123
3ea8bfc9
DM
1124fn key_import_master_pubkey(
1125 param: Value,
1126 _info: &ApiMethod,
1127 _rpcenv: &mut dyn RpcEnvironment,
1128) -> Result<Value, Error> {
1129
1130 let path = tools::required_string_param(&param, "path")?;
1131 let path = PathBuf::from(path);
1132
1133 let pem_data = proxmox_backup::tools::file_get_contents(&path)?;
1134
1135 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
1136 bail!("Unable to decode PEM data - {}", err);
1137 }
1138
9f46c7de 1139 let target_path = master_pubkey_path()?;
3ea8bfc9
DM
1140
1141 proxmox_backup::tools::file_set_contents(&target_path, &pem_data, None)?;
1142
1143 println!("Imported public master key to {:?}", target_path);
1144
1145 Ok(Value::Null)
1146}
1147
37c5a175
DM
1148fn key_create_master_key(
1149 _param: Value,
1150 _info: &ApiMethod,
1151 _rpcenv: &mut dyn RpcEnvironment,
1152) -> Result<Value, Error> {
1153
1154 // we need a TTY to query the new password
1155 if !crate::tools::tty::stdin_isatty() {
1156 bail!("unable to create master key - no tty");
1157 }
1158
1159 let rsa = openssl::rsa::Rsa::generate(4096)?;
1160 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
1161
1162 let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?;
1163 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
1164
1165 if new_pw != verify_pw {
1166 bail!("Password verification fail!");
1167 }
1168
1169 if new_pw.len() < 5 {
1170 bail!("Password is too short!");
1171 }
1172
1173 let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
1174 let filename_pub = "master-public.pem";
1175 println!("Writing public master key to {}", filename_pub);
1176 proxmox_backup::tools::file_set_contents(filename_pub, pub_key.as_slice(), None)?;
1177
1178 let cipher = openssl::symm::Cipher::aes_256_cbc();
1179 let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?;
1180
1181 let filename_priv = "master-private.pem";
1182 println!("Writing private master key to {}", filename_priv);
1183 proxmox_backup::tools::file_set_contents(filename_priv, priv_key.as_slice(), None)?;
1184
1185 Ok(Value::Null)
1186}
ac716234
DM
1187
1188fn key_change_passphrase(
1189 param: Value,
1190 _info: &ApiMethod,
1191 _rpcenv: &mut dyn RpcEnvironment,
1192) -> Result<Value, Error> {
1193
9b06db45
DM
1194 let path = tools::required_string_param(&param, "path")?;
1195 let path = PathBuf::from(path);
ac716234 1196
181f097a
DM
1197 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
1198
ac716234
DM
1199 // we need a TTY to query the new password
1200 if !crate::tools::tty::stdin_isatty() {
1201 bail!("unable to change passphrase - no tty");
1202 }
1203
ab44acff 1204 let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
ac716234 1205
181f097a 1206 if kdf == "scrypt" {
ac716234 1207
181f097a
DM
1208 let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?;
1209 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
ac716234 1210
181f097a
DM
1211 if new_pw != verify_pw {
1212 bail!("Password verification fail!");
1213 }
1214
1215 if new_pw.len() < 5 {
1216 bail!("Password is too short!");
1217 }
ac716234 1218
ab44acff
DM
1219 let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?;
1220 new_key_config.created = created; // keep original value
1221
1222 store_key_config(&path, true, new_key_config)?;
ac716234 1223
181f097a
DM
1224 Ok(Value::Null)
1225 } else if kdf == "none" {
ab44acff 1226 let modified = Local.timestamp(Local::now().timestamp(), 0);
181f097a
DM
1227
1228 store_key_config(&path, true, KeyConfig {
1229 kdf: None,
ab44acff
DM
1230 created, // keep original value
1231 modified,
6d0983db 1232 data: key.to_vec(),
181f097a
DM
1233 })?;
1234
1235 Ok(Value::Null)
1236 } else {
1237 unreachable!();
1238 }
f2401311
DM
1239}
1240
1241fn key_mgmt_cli() -> CliCommandMap {
1242
181f097a
DM
1243 let kdf_schema: Arc<Schema> = Arc::new(
1244 StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.")
1245 .format(Arc::new(ApiStringFormat::Enum(&["scrypt", "none"])))
1246 .default("scrypt")
1247 .into()
1248 );
1249
f2401311
DM
1250 let key_create_cmd_def = CliCommand::new(
1251 ApiMethod::new(
1252 key_create,
1253 ObjectSchema::new("Create a new encryption key.")
9b06db45 1254 .required("path", StringSchema::new("File system path."))
181f097a 1255 .optional("kdf", kdf_schema.clone())
f2401311 1256 ))
9b06db45
DM
1257 .arg_param(vec!["path"])
1258 .completion_cb("path", tools::complete_file_name);
f2401311 1259
ac716234
DM
1260 let key_change_passphrase_cmd_def = CliCommand::new(
1261 ApiMethod::new(
1262 key_change_passphrase,
1263 ObjectSchema::new("Change the passphrase required to decrypt the key.")
9b06db45 1264 .required("path", StringSchema::new("File system path."))
181f097a 1265 .optional("kdf", kdf_schema.clone())
9b06db45
DM
1266 ))
1267 .arg_param(vec!["path"])
1268 .completion_cb("path", tools::complete_file_name);
ac716234 1269
37c5a175
DM
1270 let key_create_master_key_cmd_def = CliCommand::new(
1271 ApiMethod::new(
1272 key_create_master_key,
1273 ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.")
1274 ));
1275
3ea8bfc9
DM
1276 let key_import_master_pubkey_cmd_def = CliCommand::new(
1277 ApiMethod::new(
1278 key_import_master_pubkey,
1279 ObjectSchema::new("Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.")
1280 .required("path", StringSchema::new("File system path."))
1281 ))
1282 .arg_param(vec!["path"])
1283 .completion_cb("path", tools::complete_file_name);
1284
f2401311 1285 let cmd_def = CliCommandMap::new()
ac716234 1286 .insert("create".to_owned(), key_create_cmd_def.into())
37c5a175 1287 .insert("create-master-key".to_owned(), key_create_master_key_cmd_def.into())
3ea8bfc9 1288 .insert("import-master-pubkey".to_owned(), key_import_master_pubkey_cmd_def.into())
ac716234 1289 .insert("change-passphrase".to_owned(), key_change_passphrase_cmd_def.into());
f2401311
DM
1290
1291 cmd_def
1292}
1293
f2401311 1294fn main() {
33d64b81 1295
25f1650b
DM
1296 let backup_source_schema: Arc<Schema> = Arc::new(
1297 StringSchema::new("Backup source specification ([<label>:<path>]).")
1298 .format(Arc::new(ApiStringFormat::Pattern(&BACKUPSPEC_REGEX)))
1299 .into()
1300 );
1301
597a9203 1302 let backup_cmd_def = CliCommand::new(
ff5d3707 1303 ApiMethod::new(
bcd879cf 1304 create_backup,
597a9203 1305 ObjectSchema::new("Create (host) backup.")
ae0be2dd
DM
1306 .required(
1307 "backupspec",
1308 ArraySchema::new(
74cdb521 1309 "List of backup source specifications ([<label.ext>:<path>] ...)",
25f1650b 1310 backup_source_schema,
ae0be2dd
DM
1311 ).min_length(1)
1312 )
2665cef7 1313 .optional("repository", REPO_URL_SCHEMA.clone())
2eeaacb9
DM
1314 .optional(
1315 "include-dev",
1316 ArraySchema::new(
1317 "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.",
1318 StringSchema::new("Path to file.").into()
1319 )
1320 )
6d0983db
DM
1321 .optional(
1322 "keyfile",
1323 StringSchema::new("Path to encryption key. All data will be encrypted using this key."))
219ef0e6
DM
1324 .optional(
1325 "verbose",
1326 BooleanSchema::new("Verbose output.").default(false))
5b72c9b4
DM
1327 .optional(
1328 "skip-lost-and-found",
1329 BooleanSchema::new("Skip lost+found directory").default(false))
fba30411 1330 .optional(
bbf9e7e9
DM
1331 "backup-type",
1332 BACKUP_TYPE_SCHEMA.clone()
1333 )
1334 .optional(
1335 "backup-id",
1336 BACKUP_ID_SCHEMA.clone()
1337 )
ca5d0b61
DM
1338 .optional(
1339 "backup-time",
bbf9e7e9 1340 BACKUP_TIME_SCHEMA.clone()
ca5d0b61 1341 )
2d9d143a
DM
1342 .optional(
1343 "chunk-size",
1344 IntegerSchema::new("Chunk size in KB. Must be a power of 2.")
1345 .minimum(64)
1346 .maximum(4096)
1347 .default(4096)
1348 )
ff5d3707 1349 ))
2665cef7 1350 .arg_param(vec!["backupspec"])
d0a03d40 1351 .completion_cb("repository", complete_repository)
49811347 1352 .completion_cb("backupspec", complete_backup_source)
6d0983db 1353 .completion_cb("keyfile", tools::complete_file_name)
49811347 1354 .completion_cb("chunk-size", complete_chunk_size);
f8838fe9 1355
ec34f7eb
DM
1356 let upload_log_cmd_def = CliCommand::new(
1357 ApiMethod::new(
1358 upload_log,
1359 ObjectSchema::new("Upload backup log file.")
1360 .required("snapshot", StringSchema::new("Snapshot path."))
1361 .required("logfile", StringSchema::new("The path to the log file you want to upload."))
1362 .optional("repository", REPO_URL_SCHEMA.clone())
1363 .optional(
1364 "keyfile",
1365 StringSchema::new("Path to encryption key. All data will be encrypted using this key."))
1366 ))
1367 .arg_param(vec!["snapshot", "logfile"])
1368 .completion_cb("snapshot", complete_group_or_snapshot)
1369 .completion_cb("logfile", tools::complete_file_name)
1370 .completion_cb("keyfile", tools::complete_file_name)
1371 .completion_cb("repository", complete_repository);
1372
41c039e1
DM
1373 let list_cmd_def = CliCommand::new(
1374 ApiMethod::new(
812c6f87
DM
1375 list_backup_groups,
1376 ObjectSchema::new("List backup groups.")
2665cef7 1377 .optional("repository", REPO_URL_SCHEMA.clone())
34a816cc 1378 .optional("output-format", OUTPUT_FORMAT.clone())
41c039e1 1379 ))
d0a03d40 1380 .completion_cb("repository", complete_repository);
41c039e1 1381
184f17af
DM
1382 let snapshots_cmd_def = CliCommand::new(
1383 ApiMethod::new(
1384 list_snapshots,
1385 ObjectSchema::new("List backup snapshots.")
15c847f1 1386 .optional("group", StringSchema::new("Backup group."))
2665cef7 1387 .optional("repository", REPO_URL_SCHEMA.clone())
34a816cc 1388 .optional("output-format", OUTPUT_FORMAT.clone())
184f17af 1389 ))
2665cef7 1390 .arg_param(vec!["group"])
024f11bb 1391 .completion_cb("group", complete_backup_group)
d0a03d40 1392 .completion_cb("repository", complete_repository);
184f17af 1393
6f62c924
DM
1394 let forget_cmd_def = CliCommand::new(
1395 ApiMethod::new(
1396 forget_snapshots,
1397 ObjectSchema::new("Forget (remove) backup snapshots.")
6f62c924 1398 .required("snapshot", StringSchema::new("Snapshot path."))
2665cef7 1399 .optional("repository", REPO_URL_SCHEMA.clone())
6f62c924 1400 ))
2665cef7 1401 .arg_param(vec!["snapshot"])
b2388518
DM
1402 .completion_cb("repository", complete_repository)
1403 .completion_cb("snapshot", complete_group_or_snapshot);
6f62c924 1404
8cc0d6af
DM
1405 let garbage_collect_cmd_def = CliCommand::new(
1406 ApiMethod::new(
1407 start_garbage_collection,
1408 ObjectSchema::new("Start garbage collection for a specific repository.")
2665cef7 1409 .optional("repository", REPO_URL_SCHEMA.clone())
8cc0d6af 1410 ))
d0a03d40 1411 .completion_cb("repository", complete_repository);
8cc0d6af 1412
9f912493
DM
1413 let restore_cmd_def = CliCommand::new(
1414 ApiMethod::new(
1415 restore,
1416 ObjectSchema::new("Restore backup repository.")
d5c34d98
DM
1417 .required("snapshot", StringSchema::new("Group/Snapshot path."))
1418 .required("archive-name", StringSchema::new("Backup archive name."))
bf125261
DM
1419 .required("target", StringSchema::new(r###"Target directory path. Use '-' to write to stdandard output.
1420
1421We do not extraxt '.pxar' archives when writing to stdandard output.
1422
1423"###
1424 ))
2665cef7 1425 .optional("repository", REPO_URL_SCHEMA.clone())
86eda3eb
DM
1426 .optional("keyfile", StringSchema::new("Path to encryption key."))
1427 .optional(
1428 "verbose",
1429 BooleanSchema::new("Verbose output.").default(false)
1430 )
9f912493 1431 ))
2665cef7 1432 .arg_param(vec!["snapshot", "archive-name", "target"])
b2388518 1433 .completion_cb("repository", complete_repository)
08dc340a
DM
1434 .completion_cb("snapshot", complete_group_or_snapshot)
1435 .completion_cb("archive-name", complete_archive_name)
1436 .completion_cb("target", tools::complete_file_name);
9f912493 1437
83b7db02
DM
1438 let prune_cmd_def = CliCommand::new(
1439 ApiMethod::new(
1440 prune,
1441 proxmox_backup::api2::admin::datastore::add_common_prune_prameters(
1442 ObjectSchema::new("Prune backup repository.")
2665cef7 1443 .optional("repository", REPO_URL_SCHEMA.clone())
83b7db02
DM
1444 )
1445 ))
d0a03d40 1446 .completion_cb("repository", complete_repository);
9f912493 1447
34a816cc
DM
1448 let status_cmd_def = CliCommand::new(
1449 ApiMethod::new(
1450 status,
1451 ObjectSchema::new("Get repository status.")
1452 .optional("repository", REPO_URL_SCHEMA.clone())
1453 .optional("output-format", OUTPUT_FORMAT.clone())
1454 ))
1455 .completion_cb("repository", complete_repository);
1456
41c039e1 1457 let cmd_def = CliCommandMap::new()
597a9203 1458 .insert("backup".to_owned(), backup_cmd_def.into())
ec34f7eb 1459 .insert("upload-log".to_owned(), upload_log_cmd_def.into())
6f62c924 1460 .insert("forget".to_owned(), forget_cmd_def.into())
8cc0d6af 1461 .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into())
83b7db02 1462 .insert("list".to_owned(), list_cmd_def.into())
184f17af 1463 .insert("prune".to_owned(), prune_cmd_def.into())
9f912493 1464 .insert("restore".to_owned(), restore_cmd_def.into())
f2401311 1465 .insert("snapshots".to_owned(), snapshots_cmd_def.into())
34a816cc 1466 .insert("status".to_owned(), status_cmd_def.into())
f2401311 1467 .insert("key".to_owned(), key_mgmt_cli().into());
a914a774 1468
5a2df000
DM
1469 hyper::rt::run(futures::future::lazy(move || {
1470 run_cli_command(cmd_def.into());
1471 Ok(())
1472 }));
496a6784 1473
ff5d3707 1474}