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