]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-client.rs
src/api2/admin/datastore.rs: add new api test_prune()
[proxmox-backup.git] / src / bin / proxmox-backup-client.rs
CommitLineData
ff5d3707 1use failure::*;
70235f72
CE
2use nix::unistd::{fork, ForkResult, pipe};
3use std::os::unix::io::RawFd;
fa5d6977 4use chrono::{Local, Utc, TimeZone};
e9c9409a 5use std::path::{Path, PathBuf};
2eeaacb9 6use std::collections::{HashSet, HashMap};
70235f72 7use std::ffi::OsStr;
bb19af73 8use std::io::{Write, Seek, SeekFrom};
2761d6a4
DM
9use std::os::unix::fs::OpenOptionsExt;
10
552c2259 11use proxmox::{sortable, identity};
e18a6c9e 12use proxmox::tools::fs::{file_get_contents, file_get_json, file_set_contents, image_size};
3d482025
WB
13use proxmox::api::{ApiHandler, ApiMethod, RpcEnvironment};
14use proxmox::api::schema::*;
7eea56ca 15use proxmox::api::cli::*;
ff5d3707 16
fe0e04c6 17use proxmox_backup::tools;
bbf9e7e9 18use proxmox_backup::api2::types::*;
151c6ce2 19use proxmox_backup::client::*;
247cdbce 20use proxmox_backup::backup::*;
7926a3a1 21use proxmox_backup::pxar::{ self, catalog::* };
86eda3eb 22
fe0e04c6
DM
23//use proxmox_backup::backup::image_index::*;
24//use proxmox_backup::config::datastore;
8968258b 25//use proxmox_backup::pxar::encoder::*;
728797d0 26//use proxmox_backup::backup::datastore::*;
23bb8780 27
f5f13ebc 28use serde_json::{json, Value};
1c0472e8 29//use hyper::Body;
2761d6a4 30use std::sync::{Arc, Mutex};
255f378a 31//use regex::Regex;
d0a03d40 32use xdg::BaseDirectories;
ae0be2dd 33
5a2df000 34use futures::*;
c4ff3dce 35use tokio::sync::mpsc;
ae0be2dd 36
3d482025 37proxmox::api::const_regex! {
255f378a 38 BACKUPSPEC_REGEX = r"^([a-zA-Z0-9_-]+\.(?:pxar|img|conf|log)):(.+)$";
ae0be2dd 39}
33d64b81 40
255f378a
DM
41const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.")
42 .format(&BACKUP_REPO_URL)
43 .max_length(256)
44 .schema();
d0a03d40 45
2665cef7
DM
46fn get_default_repository() -> Option<String> {
47 std::env::var("PBS_REPOSITORY").ok()
48}
49
50fn extract_repository_from_value(
51 param: &Value,
52) -> Result<BackupRepository, Error> {
53
54 let repo_url = param["repository"]
55 .as_str()
56 .map(String::from)
57 .or_else(get_default_repository)
58 .ok_or_else(|| format_err!("unable to get (default) repository"))?;
59
60 let repo: BackupRepository = repo_url.parse()?;
61
62 Ok(repo)
63}
64
65fn extract_repository_from_map(
66 param: &HashMap<String, String>,
67) -> Option<BackupRepository> {
68
69 param.get("repository")
70 .map(String::from)
71 .or_else(get_default_repository)
72 .and_then(|repo_url| repo_url.parse::<BackupRepository>().ok())
73}
74
d0a03d40
DM
75fn record_repository(repo: &BackupRepository) {
76
77 let base = match BaseDirectories::with_prefix("proxmox-backup") {
78 Ok(v) => v,
79 _ => return,
80 };
81
82 // usually $HOME/.cache/proxmox-backup/repo-list
83 let path = match base.place_cache_file("repo-list") {
84 Ok(v) => v,
85 _ => return,
86 };
87
11377a47 88 let mut data = file_get_json(&path, None).unwrap_or_else(|_| json!({}));
d0a03d40
DM
89
90 let repo = repo.to_string();
91
92 data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 };
93
94 let mut map = serde_json::map::Map::new();
95
96 loop {
97 let mut max_used = 0;
98 let mut max_repo = None;
99 for (repo, count) in data.as_object().unwrap() {
100 if map.contains_key(repo) { continue; }
101 if let Some(count) = count.as_i64() {
102 if count > max_used {
103 max_used = count;
104 max_repo = Some(repo);
105 }
106 }
107 }
108 if let Some(repo) = max_repo {
109 map.insert(repo.to_owned(), json!(max_used));
110 } else {
111 break;
112 }
113 if map.len() > 10 { // store max. 10 repos
114 break;
115 }
116 }
117
118 let new_data = json!(map);
119
e18a6c9e 120 let _ = file_set_contents(path, new_data.to_string().as_bytes(), None);
d0a03d40
DM
121}
122
49811347 123fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
d0a03d40
DM
124
125 let mut result = vec![];
126
127 let base = match BaseDirectories::with_prefix("proxmox-backup") {
128 Ok(v) => v,
129 _ => return result,
130 };
131
132 // usually $HOME/.cache/proxmox-backup/repo-list
133 let path = match base.place_cache_file("repo-list") {
134 Ok(v) => v,
135 _ => return result,
136 };
137
11377a47 138 let data = file_get_json(&path, None).unwrap_or_else(|_| json!({}));
d0a03d40
DM
139
140 if let Some(map) = data.as_object() {
49811347 141 for (repo, _count) in map {
d0a03d40
DM
142 result.push(repo.to_owned());
143 }
144 }
145
146 result
147}
148
e9722f8b 149async fn backup_directory<P: AsRef<Path>>(
cf9271e2 150 client: &BackupWriter,
17d6979a 151 dir_path: P,
247cdbce 152 archive_name: &str,
36898ffc 153 chunk_size: Option<usize>,
2eeaacb9 154 device_set: Option<HashSet<u64>>,
219ef0e6 155 verbose: bool,
5b72c9b4 156 skip_lost_and_found: bool,
f98ac774 157 crypt_config: Option<Arc<CryptConfig>>,
bf6e3217 158 catalog: Arc<Mutex<CatalogWriter<SenderWriter>>>,
2c3891d1 159) -> Result<BackupStats, Error> {
33d64b81 160
2761d6a4 161 let pxar_stream = PxarBackupStream::open(dir_path.as_ref(), device_set, verbose, skip_lost_and_found, catalog)?;
e9722f8b 162 let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size);
ff3d3100 163
e9722f8b 164 let (mut tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks
5e7a09be 165
c4ff3dce 166 let stream = rx
e9722f8b 167 .map_err(Error::from);
17d6979a 168
c4ff3dce 169 // spawn chunker inside a separate task so that it can run parallel
e9722f8b
WB
170 tokio::spawn(async move {
171 let _ = tx.send_all(&mut chunk_stream).await;
172 });
17d6979a 173
e9722f8b
WB
174 let stats = client
175 .upload_stream(archive_name, stream, "dynamic", None, crypt_config)
176 .await?;
bcd879cf 177
2c3891d1 178 Ok(stats)
bcd879cf
DM
179}
180
e9722f8b 181async fn backup_image<P: AsRef<Path>>(
cf9271e2 182 client: &BackupWriter,
6af905c1
DM
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
e9722f8b 193 let file = tokio::fs::File::open(path).await?;
6af905c1
DM
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
e9722f8b
WB
200 let stats = client
201 .upload_stream(archive_name, stream, "fixed", Some(image_size), crypt_config)
202 .await?;
6af905c1 203
2c3891d1 204 Ok(stats)
6af905c1
DM
205}
206
52c171e4
DM
207fn strip_server_file_expenstion(name: &str) -> String {
208
11377a47
DM
209 if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") {
210 name[..name.len()-5].to_owned()
52c171e4 211 } else {
11377a47 212 name.to_owned() // should not happen
8e39232a 213 }
8e39232a
DM
214}
215
812c6f87
DM
216fn list_backup_groups(
217 param: Value,
218 _info: &ApiMethod,
dd5495d6 219 _rpcenv: &mut dyn RpcEnvironment,
812c6f87
DM
220) -> Result<Value, Error> {
221
2665cef7 222 let repo = extract_repository_from_value(&param)?;
812c6f87 223
cc2ce4a9 224 let client = HttpClient::new(repo.host(), repo.user(), None)?;
812c6f87 225
d0a03d40 226 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
812c6f87 227
e9722f8b
WB
228 let mut result = async_main(async move {
229 client.get(&path, None).await
230 })?;
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
cc2ce4a9 304 let client = HttpClient::new(repo.host(), repo.user(), None)?;
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
e9722f8b
WB
315 let result = async_main(async move {
316 client.get(&path, Some(args)).await
317 })?;
184f17af 318
d0a03d40
DM
319 record_repository(&repo);
320
184f17af
DM
321 let list = result["data"].as_array().unwrap();
322
34a816cc
DM
323 let mut result = vec![];
324
184f17af
DM
325 for item in list {
326
327 let id = item["backup-id"].as_str().unwrap();
328 let btype = item["backup-type"].as_str().unwrap();
329 let epoch = item["backup-time"].as_i64().unwrap();
184f17af 330
391d3107 331 let snapshot = BackupDir::new(btype, id, epoch);
184f17af
DM
332
333 let path = snapshot.relative_path().to_str().unwrap().to_owned();
334
52c171e4
DM
335 let files = item["files"].as_array().unwrap().iter()
336 .map(|v| strip_server_file_expenstion(v.as_str().unwrap())).collect();
184f17af 337
34a816cc 338 if output_format == "text" {
a17a0e7a
DM
339 let size_str = if let Some(size) = item["size"].as_u64() {
340 size.to_string()
341 } else {
342 String::from("-")
343 };
344 println!("{} | {} | {}", path, size_str, tools::join(&files, ' '));
34a816cc 345 } else {
a17a0e7a 346 let mut data = json!({
34a816cc
DM
347 "backup-type": btype,
348 "backup-id": id,
349 "backup-time": epoch,
350 "files": files,
a17a0e7a
DM
351 });
352 if let Some(size) = item["size"].as_u64() {
353 data["size"] = size.into();
354 }
355 result.push(data);
34a816cc 356 }
184f17af
DM
357 }
358
f6ede796 359 if output_format != "text" { format_and_print_result(&result.into(), &output_format); }
34a816cc 360
184f17af
DM
361 Ok(Value::Null)
362}
363
6f62c924
DM
364fn forget_snapshots(
365 param: Value,
366 _info: &ApiMethod,
dd5495d6 367 _rpcenv: &mut dyn RpcEnvironment,
6f62c924
DM
368) -> Result<Value, Error> {
369
2665cef7 370 let repo = extract_repository_from_value(&param)?;
6f62c924
DM
371
372 let path = tools::required_string_param(&param, "snapshot")?;
373 let snapshot = BackupDir::parse(path)?;
374
cc2ce4a9 375 let mut client = HttpClient::new(repo.host(), repo.user(), None)?;
6f62c924 376
9e391bb7 377 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
6f62c924 378
e9722f8b
WB
379 let result = async_main(async move {
380 client.delete(&path, Some(json!({
381 "backup-type": snapshot.group().backup_type(),
382 "backup-id": snapshot.group().backup_id(),
383 "backup-time": snapshot.backup_time().timestamp(),
384 }))).await
385 })?;
6f62c924 386
d0a03d40
DM
387 record_repository(&repo);
388
6f62c924
DM
389 Ok(result)
390}
391
e240d8be
DM
392fn api_login(
393 param: Value,
394 _info: &ApiMethod,
395 _rpcenv: &mut dyn RpcEnvironment,
396) -> Result<Value, Error> {
397
398 let repo = extract_repository_from_value(&param)?;
399
cc2ce4a9 400 let client = HttpClient::new(repo.host(), repo.user(), None)?;
e9722f8b 401 async_main(async move { client.login().await })?;
e240d8be
DM
402
403 record_repository(&repo);
404
405 Ok(Value::Null)
406}
407
408fn api_logout(
409 param: Value,
410 _info: &ApiMethod,
411 _rpcenv: &mut dyn RpcEnvironment,
412) -> Result<Value, Error> {
413
414 let repo = extract_repository_from_value(&param)?;
415
416 delete_ticket_info(repo.host(), repo.user())?;
417
418 Ok(Value::Null)
419}
420
9049a8cf
DM
421fn dump_catalog(
422 param: Value,
423 _info: &ApiMethod,
424 _rpcenv: &mut dyn RpcEnvironment,
425) -> Result<Value, Error> {
426
427 let repo = extract_repository_from_value(&param)?;
428
429 let path = tools::required_string_param(&param, "snapshot")?;
430 let snapshot = BackupDir::parse(path)?;
431
11377a47 432 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
9049a8cf
DM
433
434 let crypt_config = match keyfile {
435 None => None,
436 Some(path) => {
a8f10f84 437 let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
9025312a 438 Some(Arc::new(CryptConfig::new(key)?))
9049a8cf
DM
439 }
440 };
441
cc2ce4a9 442 let client = HttpClient::new(repo.host(), repo.user(), None)?;
9049a8cf 443
e9722f8b 444 async_main(async move {
9e490a74
DM
445 let client = BackupReader::start(
446 client,
296c50ba 447 crypt_config.clone(),
e9722f8b
WB
448 repo.store(),
449 &snapshot.group().backup_type(),
450 &snapshot.group().backup_id(),
9e490a74
DM
451 snapshot.backup_time(),
452 true,
453 ).await?;
9049a8cf 454
f06b820a 455 let manifest = client.download_manifest().await?;
d2267b11 456
c3d84a22 457 let index = client.download_dynamic_index(&manifest, CATALOG_NAME).await?;
bf6e3217
DM
458
459 let most_used = index.find_most_used_chunks(8);
460
461 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
462
463 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
464
465 let mut catalogfile = std::fs::OpenOptions::new()
e9722f8b 466 .write(true)
bf6e3217 467 .read(true)
e9722f8b
WB
468 .custom_flags(libc::O_TMPFILE)
469 .open("/tmp")?;
9049a8cf 470
bf6e3217
DM
471 std::io::copy(&mut reader, &mut catalogfile)
472 .map_err(|err| format_err!("unable to download catalog - {}", err))?;
d2267b11 473
bf6e3217 474 catalogfile.seek(SeekFrom::Start(0))?;
a84ef4c2 475
bf6e3217 476 let mut catalog_reader = CatalogReader::new(catalogfile);
9049a8cf 477
e9722f8b 478 catalog_reader.dump()?;
9049a8cf 479
e9722f8b
WB
480 record_repository(&repo);
481
482 Ok::<(), Error>(())
483 })?;
9049a8cf
DM
484
485 Ok(Value::Null)
486}
487
52c171e4
DM
488fn list_snapshot_files(
489 param: Value,
490 _info: &ApiMethod,
491 _rpcenv: &mut dyn RpcEnvironment,
492) -> Result<Value, Error> {
493
494 let repo = extract_repository_from_value(&param)?;
495
496 let path = tools::required_string_param(&param, "snapshot")?;
497 let snapshot = BackupDir::parse(path)?;
498
499 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
500
cc2ce4a9 501 let client = HttpClient::new(repo.host(), repo.user(), None)?;
52c171e4
DM
502
503 let path = format!("api2/json/admin/datastore/{}/files", repo.store());
504
e9722f8b
WB
505 let mut result = async_main(async move {
506 client.get(&path, Some(json!({
507 "backup-type": snapshot.group().backup_type(),
508 "backup-id": snapshot.group().backup_id(),
509 "backup-time": snapshot.backup_time().timestamp(),
510 }))).await
511 })?;
52c171e4
DM
512
513 record_repository(&repo);
514
8c70e3eb 515 let list: Value = result["data"].take();
52c171e4
DM
516
517 if output_format == "text" {
8c70e3eb
DM
518 for item in list.as_array().unwrap().iter() {
519 println!(
520 "{} {}",
521 strip_server_file_expenstion(item["filename"].as_str().unwrap()),
522 item["size"].as_u64().unwrap_or(0),
523 );
52c171e4
DM
524 }
525 } else {
8c70e3eb 526 format_and_print_result(&list, &output_format);
52c171e4
DM
527 }
528
529 Ok(Value::Null)
530}
531
8cc0d6af
DM
532fn start_garbage_collection(
533 param: Value,
534 _info: &ApiMethod,
dd5495d6 535 _rpcenv: &mut dyn RpcEnvironment,
8cc0d6af
DM
536) -> Result<Value, Error> {
537
2665cef7 538 let repo = extract_repository_from_value(&param)?;
8cc0d6af 539
cc2ce4a9 540 let mut client = HttpClient::new(repo.host(), repo.user(), None)?;
8cc0d6af 541
d0a03d40 542 let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
8cc0d6af 543
e9722f8b 544 let result = async_main(async move { client.post(&path, None).await })?;
8cc0d6af 545
d0a03d40
DM
546 record_repository(&repo);
547
8cc0d6af
DM
548 Ok(result)
549}
33d64b81 550
ae0be2dd
DM
551fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> {
552
255f378a 553 if let Some(caps) = (BACKUPSPEC_REGEX.regex_obj)().captures(value) {
ae0be2dd
DM
554 return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str()));
555 }
556 bail!("unable to parse directory specification '{}'", value);
557}
558
bf6e3217
DM
559fn spawn_catalog_upload(
560 client: Arc<BackupWriter>,
561 crypt_config: Option<Arc<CryptConfig>>,
562) -> Result<
563 (
564 Arc<Mutex<CatalogWriter<SenderWriter>>>,
565 tokio::sync::oneshot::Receiver<Result<BackupStats, Error>>
566 ), Error>
567{
568 let (catalog_tx, catalog_rx) = mpsc::channel(10); // allow to buffer 10 writes
569 let catalog_stream = catalog_rx.map_err(Error::from);
570 let catalog_chunk_size = 512*1024;
571 let catalog_chunk_stream = ChunkStream::new(catalog_stream, Some(catalog_chunk_size));
572
573 let catalog = Arc::new(Mutex::new(CatalogWriter::new(SenderWriter::new(catalog_tx))?));
574
575 let (catalog_result_tx, catalog_result_rx) = tokio::sync::oneshot::channel();
576
577 tokio::spawn(async move {
578 let catalog_upload_result = client
579 .upload_stream(CATALOG_NAME, catalog_chunk_stream, "dynamic", None, crypt_config)
580 .await;
581
582 if let Err(ref err) = catalog_upload_result {
583 eprintln!("catalog upload error - {}", err);
584 client.cancel();
585 }
586
587 let _ = catalog_result_tx.send(catalog_upload_result);
588 });
589
590 Ok((catalog, catalog_result_rx))
591}
592
6049b71f
DM
593fn create_backup(
594 param: Value,
595 _info: &ApiMethod,
dd5495d6 596 _rpcenv: &mut dyn RpcEnvironment,
6049b71f 597) -> Result<Value, Error> {
ff5d3707 598
2665cef7 599 let repo = extract_repository_from_value(&param)?;
ae0be2dd
DM
600
601 let backupspec_list = tools::required_array_param(&param, "backupspec")?;
a914a774 602
eed6db39
DM
603 let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false);
604
5b72c9b4
DM
605 let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false);
606
219ef0e6
DM
607 let verbose = param["verbose"].as_bool().unwrap_or(false);
608
ca5d0b61
DM
609 let backup_time_opt = param["backup-time"].as_i64();
610
36898ffc 611 let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize);
2d9d143a 612
247cdbce
DM
613 if let Some(size) = chunk_size_opt {
614 verify_chunk_size(size)?;
2d9d143a
DM
615 }
616
11377a47 617 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
6d0983db 618
f69adc81 619 let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename());
fba30411 620
bbf9e7e9 621 let backup_type = param["backup-type"].as_str().unwrap_or("host");
ca5d0b61 622
2eeaacb9
DM
623 let include_dev = param["include-dev"].as_array();
624
625 let mut devices = if all_file_systems { None } else { Some(HashSet::new()) };
626
627 if let Some(include_dev) = include_dev {
628 if all_file_systems {
629 bail!("option 'all-file-systems' conflicts with option 'include-dev'");
630 }
631
632 let mut set = HashSet::new();
633 for path in include_dev {
634 let path = path.as_str().unwrap();
635 let stat = nix::sys::stat::stat(path)
636 .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?;
637 set.insert(stat.st_dev);
638 }
639 devices = Some(set);
640 }
641
ae0be2dd 642 let mut upload_list = vec![];
a914a774 643
79679c2d 644 enum BackupType { PXAR, IMAGE, CONFIG, LOGFILE };
6af905c1 645
bf6e3217
DM
646 let mut upload_catalog = false;
647
ae0be2dd
DM
648 for backupspec in backupspec_list {
649 let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?;
bcd879cf 650
eb1804c5
DM
651 use std::os::unix::fs::FileTypeExt;
652
3fa71727
CE
653 let metadata = std::fs::metadata(filename)
654 .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?;
eb1804c5 655 let file_type = metadata.file_type();
23bb8780 656
4af0ee05 657 let extension = target.rsplit('.').next()
11377a47 658 .ok_or_else(|| format_err!("missing target file extenion '{}'", target))?;
bcd879cf 659
ec8a9bb9
DM
660 match extension {
661 "pxar" => {
662 if !file_type.is_dir() {
663 bail!("got unexpected file type (expected directory)");
664 }
4af0ee05 665 upload_list.push((BackupType::PXAR, filename.to_owned(), format!("{}.didx", target), 0));
bf6e3217 666 upload_catalog = true;
ec8a9bb9
DM
667 }
668 "img" => {
eb1804c5 669
ec8a9bb9
DM
670 if !(file_type.is_file() || file_type.is_block_device()) {
671 bail!("got unexpected file type (expected file or block device)");
672 }
eb1804c5 673
e18a6c9e 674 let size = image_size(&PathBuf::from(filename))?;
23bb8780 675
ec8a9bb9 676 if size == 0 { bail!("got zero-sized file '{}'", filename); }
ae0be2dd 677
4af0ee05 678 upload_list.push((BackupType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size));
ec8a9bb9
DM
679 }
680 "conf" => {
681 if !file_type.is_file() {
682 bail!("got unexpected file type (expected regular file)");
683 }
4af0ee05 684 upload_list.push((BackupType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len()));
ec8a9bb9 685 }
79679c2d
DM
686 "log" => {
687 if !file_type.is_file() {
688 bail!("got unexpected file type (expected regular file)");
689 }
4af0ee05 690 upload_list.push((BackupType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len()));
79679c2d 691 }
ec8a9bb9
DM
692 _ => {
693 bail!("got unknown archive extension '{}'", extension);
694 }
ae0be2dd
DM
695 }
696 }
697
11377a47 698 let backup_time = Utc.timestamp(backup_time_opt.unwrap_or_else(|| Utc::now().timestamp()), 0);
ae0be2dd 699
cc2ce4a9 700 let client = HttpClient::new(repo.host(), repo.user(), None)?;
d0a03d40
DM
701 record_repository(&repo);
702
ca5d0b61
DM
703 println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time));
704
f69adc81 705 println!("Client name: {}", proxmox::tools::nodename());
ca5d0b61
DM
706
707 let start_time = Local::now();
708
7a6cfbd9 709 println!("Starting protocol: {}", start_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
51144821 710
bb823140
DM
711 let (crypt_config, rsa_encrypted_key) = match keyfile {
712 None => (None, None),
6d0983db 713 Some(path) => {
a8f10f84 714 let (key, created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
bb823140
DM
715
716 let crypt_config = CryptConfig::new(key)?;
717
718 let path = master_pubkey_path()?;
719 if path.exists() {
e18a6c9e 720 let pem_data = file_get_contents(&path)?;
bb823140
DM
721 let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
722 let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?;
723 (Some(Arc::new(crypt_config)), Some(enc_key))
724 } else {
725 (Some(Arc::new(crypt_config)), None)
726 }
6d0983db
DM
727 }
728 };
f98ac774 729
e9722f8b 730 async_main(async move {
cf9271e2
DM
731 let client = BackupWriter::start(
732 client,
733 repo.store(),
734 backup_type,
735 &backup_id,
736 backup_time,
737 verbose,
738 ).await?;
e9722f8b 739
59e9ba01
DM
740 let snapshot = BackupDir::new(backup_type, backup_id, backup_time.timestamp());
741 let mut manifest = BackupManifest::new(snapshot);
e9722f8b 742
bf6e3217 743 let (catalog, catalog_result_rx) = spawn_catalog_upload(client.clone(), crypt_config.clone())?;
e9722f8b
WB
744
745 for (backup_type, filename, target, size) in upload_list {
746 match backup_type {
747 BackupType::CONFIG => {
748 println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target);
749 let stats = client
750 .upload_blob_from_file(&filename, &target, crypt_config.clone(), true)
751 .await?;
59e9ba01 752 manifest.add_file(target, stats.size, stats.csum);
e9722f8b
WB
753 }
754 BackupType::LOGFILE => { // fixme: remove - not needed anymore ?
755 println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target);
756 let stats = client
757 .upload_blob_from_file(&filename, &target, crypt_config.clone(), true)
758 .await?;
59e9ba01 759 manifest.add_file(target, stats.size, stats.csum);
e9722f8b
WB
760 }
761 BackupType::PXAR => {
e9722f8b
WB
762 println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target);
763 catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?;
764 let stats = backup_directory(
765 &client,
766 &filename,
767 &target,
768 chunk_size_opt,
769 devices.clone(),
770 verbose,
771 skip_lost_and_found,
772 crypt_config.clone(),
773 catalog.clone(),
774 ).await?;
59e9ba01 775 manifest.add_file(target, stats.size, stats.csum);
e9722f8b
WB
776 catalog.lock().unwrap().end_directory()?;
777 }
778 BackupType::IMAGE => {
779 println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
780 let stats = backup_image(
781 &client,
782 &filename,
783 &target,
784 size,
785 chunk_size_opt,
786 verbose,
787 crypt_config.clone(),
788 ).await?;
59e9ba01 789 manifest.add_file(target, stats.size, stats.csum);
e9722f8b 790 }
6af905c1
DM
791 }
792 }
4818c8b6 793
e9722f8b
WB
794 // finalize and upload catalog
795 if upload_catalog {
796 let mutex = Arc::try_unwrap(catalog)
797 .map_err(|_| format_err!("unable to get catalog (still used)"))?;
bf6e3217
DM
798 let mut catalog = mutex.into_inner().unwrap();
799
800 catalog.finish()?;
2761d6a4 801
bf6e3217 802 drop(catalog); // close upload stream
2761d6a4 803
bf6e3217 804 let stats = catalog_result_rx.await??;
9d135fe6 805
bf6e3217 806 manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum);
e9722f8b 807 }
2761d6a4 808
e9722f8b
WB
809 if let Some(rsa_encrypted_key) = rsa_encrypted_key {
810 let target = "rsa-encrypted.key";
811 println!("Upload RSA encoded key to '{:?}' as {}", repo, target);
812 let stats = client
813 .upload_blob_from_data(rsa_encrypted_key, target, None, false, false)
814 .await?;
59e9ba01 815 manifest.add_file(format!("{}.blob", target), stats.size, stats.csum);
e9722f8b
WB
816
817 // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t
818 /*
819 let mut buffer2 = vec![0u8; rsa.size() as usize];
820 let pem_data = file_get_contents("master-private.pem")?;
821 let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?;
822 let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?;
823 println!("TEST {} {:?}", len, buffer2);
824 */
825 }
9f46c7de 826
59e9ba01
DM
827 // create manifest (index.json)
828 let manifest = manifest.into_json();
2c3891d1 829
e9722f8b 830 println!("Upload index.json to '{:?}'", repo);
59e9ba01 831 let manifest = serde_json::to_string_pretty(&manifest)?.into();
e9722f8b 832 client
59e9ba01 833 .upload_blob_from_data(manifest, MANIFEST_BLOB_NAME, crypt_config.clone(), true, true)
e9722f8b 834 .await?;
2c3891d1 835
e9722f8b 836 client.finish().await?;
c4ff3dce 837
e9722f8b
WB
838 let end_time = Local::now();
839 let elapsed = end_time.signed_duration_since(start_time);
840 println!("Duration: {}", elapsed);
3ec3ec3f 841
e9722f8b 842 println!("End Time: {}", end_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
3d5c11e5 843
e9722f8b
WB
844 Ok(Value::Null)
845 })
f98ea63d
DM
846}
847
d0a03d40 848fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
f98ea63d
DM
849
850 let mut result = vec![];
851
852 let data: Vec<&str> = arg.splitn(2, ':').collect();
853
bff11030 854 if data.len() != 2 {
8968258b
DM
855 result.push(String::from("root.pxar:/"));
856 result.push(String::from("etc.pxar:/etc"));
bff11030
DM
857 return result;
858 }
f98ea63d 859
496a6784 860 let files = tools::complete_file_name(data[1], param);
f98ea63d
DM
861
862 for file in files {
863 result.push(format!("{}:{}", data[0], file));
864 }
865
866 result
ff5d3707 867}
868
9f912493
DM
869fn restore(
870 param: Value,
871 _info: &ApiMethod,
dd5495d6 872 _rpcenv: &mut dyn RpcEnvironment,
9f912493 873) -> Result<Value, Error> {
e9722f8b
WB
874 async_main(restore_do(param))
875}
9f912493 876
88892ea8
DM
877fn dump_image<W: Write>(
878 client: Arc<BackupReader>,
879 crypt_config: Option<Arc<CryptConfig>>,
880 index: FixedIndexReader,
881 mut writer: W,
fd04ca7a 882 verbose: bool,
88892ea8
DM
883) -> Result<(), Error> {
884
885 let most_used = index.find_most_used_chunks(8);
886
887 let mut chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
888
889 // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy
890 // and thus slows down reading. Instead, directly use RemoteChunkReader
fd04ca7a
DM
891 let mut per = 0;
892 let mut bytes = 0;
893 let start_time = std::time::Instant::now();
894
88892ea8
DM
895 for pos in 0..index.index_count() {
896 let digest = index.index_digest(pos).unwrap();
897 let raw_data = chunk_reader.read_chunk(&digest)?;
898 writer.write_all(&raw_data)?;
fd04ca7a
DM
899 bytes += raw_data.len();
900 if verbose {
901 let next_per = ((pos+1)*100)/index.index_count();
902 if per != next_per {
903 eprintln!("progress {}% (read {} bytes, duration {} sec)",
904 next_per, bytes, start_time.elapsed().as_secs());
905 per = next_per;
906 }
907 }
88892ea8
DM
908 }
909
fd04ca7a
DM
910 let end_time = std::time::Instant::now();
911 let elapsed = end_time.duration_since(start_time);
912 eprintln!("restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)",
913 bytes,
914 elapsed.as_secs_f64(),
915 bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64())
916 );
917
918
88892ea8
DM
919 Ok(())
920}
921
e9722f8b 922async fn restore_do(param: Value) -> Result<Value, Error> {
2665cef7 923 let repo = extract_repository_from_value(&param)?;
9f912493 924
86eda3eb
DM
925 let verbose = param["verbose"].as_bool().unwrap_or(false);
926
46d5aa0a
DM
927 let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false);
928
d5c34d98
DM
929 let archive_name = tools::required_string_param(&param, "archive-name")?;
930
cc2ce4a9 931 let client = HttpClient::new(repo.host(), repo.user(), None)?;
d0a03d40 932
d0a03d40 933 record_repository(&repo);
d5c34d98 934
9f912493 935 let path = tools::required_string_param(&param, "snapshot")?;
9f912493 936
86eda3eb 937 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
d5c34d98 938 let group = BackupGroup::parse(path)?;
9f912493 939
9e391bb7
DM
940 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
941 let result = client.get(&path, Some(json!({
d5c34d98
DM
942 "backup-type": group.backup_type(),
943 "backup-id": group.backup_id(),
e9722f8b 944 }))).await?;
9f912493 945
d5c34d98 946 let list = result["data"].as_array().unwrap();
11377a47 947 if list.is_empty() {
d5c34d98
DM
948 bail!("backup group '{}' does not contain any snapshots:", path);
949 }
9f912493 950
86eda3eb 951 let epoch = list[0]["backup-time"].as_i64().unwrap();
fa5d6977 952 let backup_time = Utc.timestamp(epoch, 0);
86eda3eb 953 (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time)
d5c34d98
DM
954 } else {
955 let snapshot = BackupDir::parse(path)?;
86eda3eb
DM
956 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
957 };
9f912493 958
d5c34d98 959 let target = tools::required_string_param(&param, "target")?;
bf125261 960 let target = if target == "-" { None } else { Some(target) };
2ae7d196 961
11377a47 962 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
2ae7d196 963
86eda3eb
DM
964 let crypt_config = match keyfile {
965 None => None,
966 Some(path) => {
a8f10f84 967 let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
86eda3eb
DM
968 Some(Arc::new(CryptConfig::new(key)?))
969 }
970 };
d5c34d98 971
afb4cd28
DM
972 let server_archive_name = if archive_name.ends_with(".pxar") {
973 format!("{}.didx", archive_name)
974 } else if archive_name.ends_with(".img") {
975 format!("{}.fidx", archive_name)
976 } else {
f8100e96 977 format!("{}.blob", archive_name)
afb4cd28 978 };
9f912493 979
296c50ba
DM
980 let client = BackupReader::start(
981 client,
982 crypt_config.clone(),
983 repo.store(),
984 &backup_type,
985 &backup_id,
986 backup_time,
987 true,
988 ).await?;
86eda3eb 989
f06b820a 990 let manifest = client.download_manifest().await?;
02fcf372 991
ad6e5a6f 992 if server_archive_name == MANIFEST_BLOB_NAME {
f06b820a 993 let backup_index_data = manifest.into_json().to_string();
02fcf372 994 if let Some(target) = target {
296c50ba 995 file_set_contents(target, backup_index_data.as_bytes(), None)?;
02fcf372
DM
996 } else {
997 let stdout = std::io::stdout();
998 let mut writer = stdout.lock();
296c50ba 999 writer.write_all(backup_index_data.as_bytes())
02fcf372
DM
1000 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1001 }
1002
1003 } else if server_archive_name.ends_with(".blob") {
d2267b11 1004
bb19af73 1005 let mut reader = client.download_blob(&manifest, &server_archive_name).await?;
f8100e96 1006
bf125261 1007 if let Some(target) = target {
0d986280
DM
1008 let mut writer = std::fs::OpenOptions::new()
1009 .write(true)
1010 .create(true)
1011 .create_new(true)
1012 .open(target)
1013 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
1014 std::io::copy(&mut reader, &mut writer)?;
bf125261
DM
1015 } else {
1016 let stdout = std::io::stdout();
1017 let mut writer = stdout.lock();
0d986280 1018 std::io::copy(&mut reader, &mut writer)
bf125261
DM
1019 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1020 }
f8100e96
DM
1021
1022 } else if server_archive_name.ends_with(".didx") {
86eda3eb 1023
c3d84a22 1024 let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
df65bd3d 1025
f4bf7dfc
DM
1026 let most_used = index.find_most_used_chunks(8);
1027
1028 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1029
afb4cd28 1030 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
86eda3eb 1031
bf125261 1032 if let Some(target) = target {
86eda3eb 1033
47651f95 1034 let feature_flags = pxar::flags::DEFAULT;
f701d033
DM
1035 let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags);
1036 decoder.set_callback(move |path| {
bf125261 1037 if verbose {
fd04ca7a 1038 eprintln!("{:?}", path);
bf125261
DM
1039 }
1040 Ok(())
1041 });
6a879109
CE
1042 decoder.set_allow_existing_dirs(allow_existing_dirs);
1043
fa7e957c 1044 decoder.restore(Path::new(target), &Vec::new())?;
bf125261 1045 } else {
88892ea8
DM
1046 let mut writer = std::fs::OpenOptions::new()
1047 .write(true)
1048 .open("/dev/stdout")
1049 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?;
afb4cd28 1050
bf125261
DM
1051 std::io::copy(&mut reader, &mut writer)
1052 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1053 }
afb4cd28 1054 } else if server_archive_name.ends_with(".fidx") {
afb4cd28 1055
72050500 1056 let index = client.download_fixed_index(&manifest, &server_archive_name).await?;
df65bd3d 1057
88892ea8
DM
1058 let mut writer = if let Some(target) = target {
1059 std::fs::OpenOptions::new()
bf125261
DM
1060 .write(true)
1061 .create(true)
1062 .create_new(true)
1063 .open(target)
88892ea8 1064 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?
bf125261 1065 } else {
88892ea8
DM
1066 std::fs::OpenOptions::new()
1067 .write(true)
1068 .open("/dev/stdout")
1069 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?
1070 };
afb4cd28 1071
fd04ca7a 1072 dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose)?;
88892ea8
DM
1073
1074 } else {
f8100e96 1075 bail!("unknown archive file extension (expected .pxar of .img)");
3031e44c 1076 }
fef44d4f
DM
1077
1078 Ok(Value::Null)
45db6f89
DM
1079}
1080
ec34f7eb
DM
1081fn upload_log(
1082 param: Value,
1083 _info: &ApiMethod,
1084 _rpcenv: &mut dyn RpcEnvironment,
1085) -> Result<Value, Error> {
1086
1087 let logfile = tools::required_string_param(&param, "logfile")?;
1088 let repo = extract_repository_from_value(&param)?;
1089
1090 let snapshot = tools::required_string_param(&param, "snapshot")?;
1091 let snapshot = BackupDir::parse(snapshot)?;
1092
cc2ce4a9 1093 let mut client = HttpClient::new(repo.host(), repo.user(), None)?;
ec34f7eb 1094
11377a47 1095 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
ec34f7eb
DM
1096
1097 let crypt_config = match keyfile {
1098 None => None,
1099 Some(path) => {
a8f10f84 1100 let (key, _created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
ec34f7eb 1101 let crypt_config = CryptConfig::new(key)?;
9025312a 1102 Some(Arc::new(crypt_config))
ec34f7eb
DM
1103 }
1104 };
1105
e18a6c9e 1106 let data = file_get_contents(logfile)?;
ec34f7eb 1107
7123ff7d 1108 let blob = DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?;
ec34f7eb
DM
1109
1110 let raw_data = blob.into_inner();
1111
1112 let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store());
1113
1114 let args = json!({
1115 "backup-type": snapshot.group().backup_type(),
1116 "backup-id": snapshot.group().backup_id(),
1117 "backup-time": snapshot.backup_time().timestamp(),
1118 });
1119
1120 let body = hyper::Body::from(raw_data);
1121
e9722f8b
WB
1122 async_main(async move {
1123 client.upload("application/octet-stream", body, &path, Some(args)).await
1124 })
ec34f7eb
DM
1125}
1126
83b7db02 1127fn prune(
ea7a7ef2 1128 mut param: Value,
83b7db02 1129 _info: &ApiMethod,
dd5495d6 1130 _rpcenv: &mut dyn RpcEnvironment,
83b7db02
DM
1131) -> Result<Value, Error> {
1132
2665cef7 1133 let repo = extract_repository_from_value(&param)?;
83b7db02 1134
cc2ce4a9 1135 let mut client = HttpClient::new(repo.host(), repo.user(), None)?;
83b7db02 1136
d0a03d40 1137 let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
83b7db02 1138
9fdc3ef4
DM
1139 let group = tools::required_string_param(&param, "group")?;
1140 let group = BackupGroup::parse(group)?;
1141
ea7a7ef2
DM
1142 param.as_object_mut().unwrap().remove("repository");
1143 param.as_object_mut().unwrap().remove("group");
1144
1145 param["backup-type"] = group.backup_type().into();
1146 param["backup-id"] = group.backup_id().into();
83b7db02 1147
e9722f8b 1148 let _result = async_main(async move { client.post(&path, Some(param)).await })?;
83b7db02 1149
d0a03d40
DM
1150 record_repository(&repo);
1151
43a406fd 1152 Ok(Value::Null)
83b7db02
DM
1153}
1154
34a816cc
DM
1155fn status(
1156 param: Value,
1157 _info: &ApiMethod,
1158 _rpcenv: &mut dyn RpcEnvironment,
1159) -> Result<Value, Error> {
1160
1161 let repo = extract_repository_from_value(&param)?;
1162
1163 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
1164
cc2ce4a9 1165 let client = HttpClient::new(repo.host(), repo.user(), None)?;
34a816cc
DM
1166
1167 let path = format!("api2/json/admin/datastore/{}/status", repo.store());
1168
e9722f8b 1169 let result = async_main(async move { client.get(&path, None).await })?;
34a816cc
DM
1170 let data = &result["data"];
1171
1172 record_repository(&repo);
1173
1174 if output_format == "text" {
1175 let total = data["total"].as_u64().unwrap();
1176 let used = data["used"].as_u64().unwrap();
1177 let avail = data["avail"].as_u64().unwrap();
1178 let roundup = total/200;
1179
1180 println!(
1181 "total: {} used: {} ({} %) available: {}",
1182 total,
1183 used,
1184 ((used+roundup)*100)/total,
1185 avail,
1186 );
1187 } else {
f6ede796 1188 format_and_print_result(data, &output_format);
34a816cc
DM
1189 }
1190
1191 Ok(Value::Null)
1192}
1193
5a2df000 1194// like get, but simply ignore errors and return Null instead
e9722f8b 1195async fn try_get(repo: &BackupRepository, url: &str) -> Value {
024f11bb 1196
cc2ce4a9 1197 let client = match HttpClient::new(repo.host(), repo.user(), None) {
45cdce06
DM
1198 Ok(v) => v,
1199 _ => return Value::Null,
1200 };
b2388518 1201
e9722f8b 1202 let mut resp = match client.get(url, None).await {
b2388518
DM
1203 Ok(v) => v,
1204 _ => return Value::Null,
1205 };
1206
1207 if let Some(map) = resp.as_object_mut() {
1208 if let Some(data) = map.remove("data") {
1209 return data;
1210 }
1211 }
1212 Value::Null
1213}
1214
b2388518 1215fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
e9722f8b
WB
1216 async_main(async { complete_backup_group_do(param).await })
1217}
1218
1219async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> {
024f11bb 1220
b2388518
DM
1221 let mut result = vec![];
1222
2665cef7 1223 let repo = match extract_repository_from_map(param) {
b2388518 1224 Some(v) => v,
024f11bb
DM
1225 _ => return result,
1226 };
1227
b2388518
DM
1228 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
1229
e9722f8b 1230 let data = try_get(&repo, &path).await;
b2388518
DM
1231
1232 if let Some(list) = data.as_array() {
024f11bb 1233 for item in list {
98f0b972
DM
1234 if let (Some(backup_id), Some(backup_type)) =
1235 (item["backup-id"].as_str(), item["backup-type"].as_str())
1236 {
1237 result.push(format!("{}/{}", backup_type, backup_id));
024f11bb
DM
1238 }
1239 }
1240 }
1241
1242 result
1243}
1244
b2388518 1245fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
e9722f8b
WB
1246 async_main(async { complete_group_or_snapshot_do(arg, param).await })
1247}
1248
1249async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
b2388518 1250
b2388518 1251 if arg.matches('/').count() < 2 {
e9722f8b 1252 let groups = complete_backup_group_do(param).await;
543a260f 1253 let mut result = vec![];
b2388518
DM
1254 for group in groups {
1255 result.push(group.to_string());
1256 result.push(format!("{}/", group));
1257 }
1258 return result;
1259 }
1260
e9722f8b 1261 complete_backup_snapshot_do(param).await
543a260f 1262}
b2388518 1263
3fb53e07 1264fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
e9722f8b
WB
1265 async_main(async { complete_backup_snapshot_do(param).await })
1266}
1267
1268async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> {
543a260f
DM
1269
1270 let mut result = vec![];
1271
1272 let repo = match extract_repository_from_map(param) {
1273 Some(v) => v,
1274 _ => return result,
1275 };
1276
1277 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
b2388518 1278
e9722f8b 1279 let data = try_get(&repo, &path).await;
b2388518
DM
1280
1281 if let Some(list) = data.as_array() {
1282 for item in list {
1283 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
1284 (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
1285 {
1286 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
1287 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
1288 }
1289 }
1290 }
1291
1292 result
1293}
1294
45db6f89 1295fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
e9722f8b
WB
1296 async_main(async { complete_server_file_name_do(param).await })
1297}
1298
1299async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> {
08dc340a
DM
1300
1301 let mut result = vec![];
1302
2665cef7 1303 let repo = match extract_repository_from_map(param) {
08dc340a
DM
1304 Some(v) => v,
1305 _ => return result,
1306 };
1307
1308 let snapshot = match param.get("snapshot") {
1309 Some(path) => {
1310 match BackupDir::parse(path) {
1311 Ok(v) => v,
1312 _ => return result,
1313 }
1314 }
1315 _ => return result,
1316 };
1317
1318 let query = tools::json_object_to_query(json!({
1319 "backup-type": snapshot.group().backup_type(),
1320 "backup-id": snapshot.group().backup_id(),
1321 "backup-time": snapshot.backup_time().timestamp(),
1322 })).unwrap();
1323
1324 let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
1325
e9722f8b 1326 let data = try_get(&repo, &path).await;
08dc340a
DM
1327
1328 if let Some(list) = data.as_array() {
1329 for item in list {
c4f025eb 1330 if let Some(filename) = item["filename"].as_str() {
08dc340a
DM
1331 result.push(filename.to_owned());
1332 }
1333 }
1334 }
1335
45db6f89
DM
1336 result
1337}
1338
1339fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
52c171e4 1340 complete_server_file_name(arg, param)
e9722f8b
WB
1341 .iter()
1342 .map(|v| strip_server_file_expenstion(&v))
1343 .collect()
08dc340a
DM
1344}
1345
49811347
DM
1346fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
1347
1348 let mut result = vec![];
1349
1350 let mut size = 64;
1351 loop {
1352 result.push(size.to_string());
11377a47 1353 size *= 2;
49811347
DM
1354 if size > 4096 { break; }
1355 }
1356
1357 result
1358}
1359
826f309b 1360fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
ff5d3707 1361
f2401311
DM
1362 // fixme: implement other input methods
1363
1364 use std::env::VarError::*;
1365 match std::env::var("PBS_ENCRYPTION_PASSWORD") {
826f309b 1366 Ok(p) => return Ok(p.as_bytes().to_vec()),
f2401311
DM
1367 Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
1368 Err(NotPresent) => {
1369 // Try another method
1370 }
1371 }
1372
1373 // If we're on a TTY, query the user for a password
1374 if crate::tools::tty::stdin_isatty() {
826f309b 1375 return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?);
f2401311
DM
1376 }
1377
1378 bail!("no password input mechanism available");
1379}
1380
ac716234
DM
1381fn key_create(
1382 param: Value,
1383 _info: &ApiMethod,
1384 _rpcenv: &mut dyn RpcEnvironment,
1385) -> Result<Value, Error> {
1386
9b06db45
DM
1387 let path = tools::required_string_param(&param, "path")?;
1388 let path = PathBuf::from(path);
ac716234 1389
181f097a 1390 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
ac716234
DM
1391
1392 let key = proxmox::sys::linux::random_data(32)?;
1393
181f097a
DM
1394 if kdf == "scrypt" {
1395 // always read passphrase from tty
1396 if !crate::tools::tty::stdin_isatty() {
1397 bail!("unable to read passphrase - no tty");
1398 }
ac716234 1399
181f097a
DM
1400 let password = crate::tools::tty::read_password("Encryption Key Password: ")?;
1401
ab44acff 1402 let key_config = encrypt_key_with_passphrase(&key, &password)?;
37c5a175 1403
ab44acff 1404 store_key_config(&path, false, key_config)?;
181f097a
DM
1405
1406 Ok(Value::Null)
1407 } else if kdf == "none" {
1408 let created = Local.timestamp(Local::now().timestamp(), 0);
1409
1410 store_key_config(&path, false, KeyConfig {
1411 kdf: None,
1412 created,
ab44acff 1413 modified: created,
181f097a
DM
1414 data: key,
1415 })?;
1416
1417 Ok(Value::Null)
1418 } else {
1419 unreachable!();
1420 }
ac716234
DM
1421}
1422
9f46c7de
DM
1423fn master_pubkey_path() -> Result<PathBuf, Error> {
1424 let base = BaseDirectories::with_prefix("proxmox-backup")?;
1425
1426 // usually $HOME/.config/proxmox-backup/master-public.pem
1427 let path = base.place_config_file("master-public.pem")?;
1428
1429 Ok(path)
1430}
1431
3ea8bfc9
DM
1432fn key_import_master_pubkey(
1433 param: Value,
1434 _info: &ApiMethod,
1435 _rpcenv: &mut dyn RpcEnvironment,
1436) -> Result<Value, Error> {
1437
1438 let path = tools::required_string_param(&param, "path")?;
1439 let path = PathBuf::from(path);
1440
e18a6c9e 1441 let pem_data = file_get_contents(&path)?;
3ea8bfc9
DM
1442
1443 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
1444 bail!("Unable to decode PEM data - {}", err);
1445 }
1446
9f46c7de 1447 let target_path = master_pubkey_path()?;
3ea8bfc9 1448
e18a6c9e 1449 file_set_contents(&target_path, &pem_data, None)?;
3ea8bfc9
DM
1450
1451 println!("Imported public master key to {:?}", target_path);
1452
1453 Ok(Value::Null)
1454}
1455
37c5a175
DM
1456fn key_create_master_key(
1457 _param: Value,
1458 _info: &ApiMethod,
1459 _rpcenv: &mut dyn RpcEnvironment,
1460) -> Result<Value, Error> {
1461
1462 // we need a TTY to query the new password
1463 if !crate::tools::tty::stdin_isatty() {
1464 bail!("unable to create master key - no tty");
1465 }
1466
1467 let rsa = openssl::rsa::Rsa::generate(4096)?;
1468 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
1469
1470 let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?;
1471 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
1472
1473 if new_pw != verify_pw {
1474 bail!("Password verification fail!");
1475 }
1476
1477 if new_pw.len() < 5 {
1478 bail!("Password is too short!");
1479 }
1480
1481 let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
1482 let filename_pub = "master-public.pem";
1483 println!("Writing public master key to {}", filename_pub);
e18a6c9e 1484 file_set_contents(filename_pub, pub_key.as_slice(), None)?;
37c5a175
DM
1485
1486 let cipher = openssl::symm::Cipher::aes_256_cbc();
1487 let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?;
1488
1489 let filename_priv = "master-private.pem";
1490 println!("Writing private master key to {}", filename_priv);
e18a6c9e 1491 file_set_contents(filename_priv, priv_key.as_slice(), None)?;
37c5a175
DM
1492
1493 Ok(Value::Null)
1494}
ac716234
DM
1495
1496fn key_change_passphrase(
1497 param: Value,
1498 _info: &ApiMethod,
1499 _rpcenv: &mut dyn RpcEnvironment,
1500) -> Result<Value, Error> {
1501
9b06db45
DM
1502 let path = tools::required_string_param(&param, "path")?;
1503 let path = PathBuf::from(path);
ac716234 1504
181f097a
DM
1505 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
1506
ac716234
DM
1507 // we need a TTY to query the new password
1508 if !crate::tools::tty::stdin_isatty() {
1509 bail!("unable to change passphrase - no tty");
1510 }
1511
a8f10f84 1512 let (key, created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
ac716234 1513
181f097a 1514 if kdf == "scrypt" {
ac716234 1515
181f097a
DM
1516 let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?;
1517 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
ac716234 1518
181f097a
DM
1519 if new_pw != verify_pw {
1520 bail!("Password verification fail!");
1521 }
1522
1523 if new_pw.len() < 5 {
1524 bail!("Password is too short!");
1525 }
ac716234 1526
ab44acff
DM
1527 let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?;
1528 new_key_config.created = created; // keep original value
1529
1530 store_key_config(&path, true, new_key_config)?;
ac716234 1531
181f097a
DM
1532 Ok(Value::Null)
1533 } else if kdf == "none" {
ab44acff 1534 let modified = Local.timestamp(Local::now().timestamp(), 0);
181f097a
DM
1535
1536 store_key_config(&path, true, KeyConfig {
1537 kdf: None,
ab44acff
DM
1538 created, // keep original value
1539 modified,
6d0983db 1540 data: key.to_vec(),
181f097a
DM
1541 })?;
1542
1543 Ok(Value::Null)
1544 } else {
1545 unreachable!();
1546 }
f2401311
DM
1547}
1548
1549fn key_mgmt_cli() -> CliCommandMap {
1550
255f378a 1551 const KDF_SCHEMA: Schema =
181f097a 1552 StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.")
255f378a
DM
1553 .format(&ApiStringFormat::Enum(&["scrypt", "none"]))
1554 .default("scrypt")
1555 .schema();
1556
552c2259 1557 #[sortable]
255f378a
DM
1558 const API_METHOD_KEY_CREATE: ApiMethod = ApiMethod::new(
1559 &ApiHandler::Sync(&key_create),
1560 &ObjectSchema::new(
1561 "Create a new encryption key.",
552c2259 1562 &sorted!([
255f378a
DM
1563 ("path", false, &StringSchema::new("File system path.").schema()),
1564 ("kdf", true, &KDF_SCHEMA),
552c2259 1565 ]),
255f378a 1566 )
181f097a 1567 );
255f378a
DM
1568
1569 let key_create_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE)
49fddd98 1570 .arg_param(&["path"])
9b06db45 1571 .completion_cb("path", tools::complete_file_name);
f2401311 1572
552c2259 1573 #[sortable]
255f378a
DM
1574 const API_METHOD_KEY_CHANGE_PASSPHRASE: ApiMethod = ApiMethod::new(
1575 &ApiHandler::Sync(&key_change_passphrase),
1576 &ObjectSchema::new(
1577 "Change the passphrase required to decrypt the key.",
552c2259 1578 &sorted!([
255f378a
DM
1579 ("path", false, &StringSchema::new("File system path.").schema()),
1580 ("kdf", true, &KDF_SCHEMA),
552c2259 1581 ]),
255f378a
DM
1582 )
1583 );
1584
1585 let key_change_passphrase_cmd_def = CliCommand::new(&API_METHOD_KEY_CHANGE_PASSPHRASE)
49fddd98 1586 .arg_param(&["path"])
9b06db45 1587 .completion_cb("path", tools::complete_file_name);
ac716234 1588
255f378a
DM
1589 const API_METHOD_KEY_CREATE_MASTER_KEY: ApiMethod = ApiMethod::new(
1590 &ApiHandler::Sync(&key_create_master_key),
1591 &ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.", &[])
1592 );
1593
1594 let key_create_master_key_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE_MASTER_KEY);
1595
552c2259 1596 #[sortable]
255f378a
DM
1597 const API_METHOD_KEY_IMPORT_MASTER_PUBKEY: ApiMethod = ApiMethod::new(
1598 &ApiHandler::Sync(&key_import_master_pubkey),
1599 &ObjectSchema::new(
1600 "Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.",
552c2259 1601 &sorted!([ ("path", false, &StringSchema::new("File system path.").schema()) ]),
255f378a
DM
1602 )
1603 );
1604
1605 let key_import_master_pubkey_cmd_def = CliCommand::new(&API_METHOD_KEY_IMPORT_MASTER_PUBKEY)
49fddd98 1606 .arg_param(&["path"])
3ea8bfc9
DM
1607 .completion_cb("path", tools::complete_file_name);
1608
11377a47 1609 CliCommandMap::new()
ac716234 1610 .insert("create".to_owned(), key_create_cmd_def.into())
37c5a175 1611 .insert("create-master-key".to_owned(), key_create_master_key_cmd_def.into())
3ea8bfc9 1612 .insert("import-master-pubkey".to_owned(), key_import_master_pubkey_cmd_def.into())
11377a47 1613 .insert("change-passphrase".to_owned(), key_change_passphrase_cmd_def.into())
f2401311
DM
1614}
1615
70235f72
CE
1616fn mount(
1617 param: Value,
1618 _info: &ApiMethod,
1619 _rpcenv: &mut dyn RpcEnvironment,
1620) -> Result<Value, Error> {
1621 let verbose = param["verbose"].as_bool().unwrap_or(false);
1622 if verbose {
1623 // This will stay in foreground with debug output enabled as None is
1624 // passed for the RawFd.
1625 return async_main(mount_do(param, None));
1626 }
1627
1628 // Process should be deamonized.
1629 // Make sure to fork before the async runtime is instantiated to avoid troubles.
1630 let pipe = pipe()?;
1631 match fork() {
11377a47 1632 Ok(ForkResult::Parent { .. }) => {
70235f72
CE
1633 nix::unistd::close(pipe.1).unwrap();
1634 // Blocks the parent process until we are ready to go in the child
1635 let _res = nix::unistd::read(pipe.0, &mut [0]).unwrap();
1636 Ok(Value::Null)
1637 }
1638 Ok(ForkResult::Child) => {
1639 nix::unistd::close(pipe.0).unwrap();
1640 nix::unistd::setsid().unwrap();
1641 async_main(mount_do(param, Some(pipe.1)))
1642 }
1643 Err(_) => bail!("failed to daemonize process"),
1644 }
1645}
1646
1647async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
1648 let repo = extract_repository_from_value(&param)?;
1649 let archive_name = tools::required_string_param(&param, "archive-name")?;
1650 let target = tools::required_string_param(&param, "target")?;
1651 let client = HttpClient::new(repo.host(), repo.user(), None)?;
1652
1653 record_repository(&repo);
1654
1655 let path = tools::required_string_param(&param, "snapshot")?;
1656 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
1657 let group = BackupGroup::parse(path)?;
1658
1659 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
1660 let result = client.get(&path, Some(json!({
1661 "backup-type": group.backup_type(),
1662 "backup-id": group.backup_id(),
1663 }))).await?;
1664
1665 let list = result["data"].as_array().unwrap();
11377a47 1666 if list.is_empty() {
70235f72
CE
1667 bail!("backup group '{}' does not contain any snapshots:", path);
1668 }
1669
1670 let epoch = list[0]["backup-time"].as_i64().unwrap();
1671 let backup_time = Utc.timestamp(epoch, 0);
1672 (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time)
1673 } else {
1674 let snapshot = BackupDir::parse(path)?;
1675 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
1676 };
1677
11377a47 1678 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
70235f72
CE
1679 let crypt_config = match keyfile {
1680 None => None,
1681 Some(path) => {
a8f10f84 1682 let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
70235f72
CE
1683 Some(Arc::new(CryptConfig::new(key)?))
1684 }
1685 };
1686
1687 let server_archive_name = if archive_name.ends_with(".pxar") {
1688 format!("{}.didx", archive_name)
1689 } else {
1690 bail!("Can only mount pxar archives.");
1691 };
1692
296c50ba
DM
1693 let client = BackupReader::start(
1694 client,
1695 crypt_config.clone(),
1696 repo.store(),
1697 &backup_type,
1698 &backup_id,
1699 backup_time,
1700 true,
1701 ).await?;
70235f72 1702
f06b820a 1703 let manifest = client.download_manifest().await?;
296c50ba 1704
70235f72 1705 if server_archive_name.ends_with(".didx") {
c3d84a22 1706 let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
70235f72
CE
1707 let most_used = index.find_most_used_chunks(8);
1708 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1709 let reader = BufferedDynamicReader::new(index, chunk_reader);
f701d033 1710 let decoder = pxar::Decoder::new(reader)?;
70235f72 1711 let options = OsStr::new("ro,default_permissions");
2a111910 1712 let mut session = pxar::fuse::Session::new(decoder, &options, pipe.is_none())
70235f72
CE
1713 .map_err(|err| format_err!("pxar mount failed: {}", err))?;
1714
1715 // Mount the session but not call fuse deamonize as this will cause
1716 // issues with the runtime after the fork
1717 let deamonize = false;
1718 session.mount(&Path::new(target), deamonize)?;
1719
1720 if let Some(pipe) = pipe {
1721 nix::unistd::chdir(Path::new("/")).unwrap();
1722 // Finish creation of deamon by redirecting filedescriptors.
1723 let nullfd = nix::fcntl::open(
1724 "/dev/null",
1725 nix::fcntl::OFlag::O_RDWR,
1726 nix::sys::stat::Mode::empty(),
1727 ).unwrap();
1728 nix::unistd::dup2(nullfd, 0).unwrap();
1729 nix::unistd::dup2(nullfd, 1).unwrap();
1730 nix::unistd::dup2(nullfd, 2).unwrap();
1731 if nullfd > 2 {
1732 nix::unistd::close(nullfd).unwrap();
1733 }
1734 // Signal the parent process that we are done with the setup and it can
1735 // terminate.
11377a47 1736 nix::unistd::write(pipe, &[0u8])?;
70235f72
CE
1737 nix::unistd::close(pipe).unwrap();
1738 }
1739
1740 let multithreaded = true;
1741 session.run_loop(multithreaded)?;
1742 } else {
1743 bail!("unknown archive file extension (expected .pxar)");
1744 }
1745
1746 Ok(Value::Null)
1747}
1748
3cf73c4e
CE
1749fn shell(
1750 param: Value,
1751 _info: &ApiMethod,
1752 _rpcenv: &mut dyn RpcEnvironment,
1753) -> Result<Value, Error> {
1754 async_main(catalog_shell(param))
1755}
1756
1757async fn catalog_shell(param: Value) -> Result<Value, Error> {
1758 let repo = extract_repository_from_value(&param)?;
1759 let client = HttpClient::new(repo.host(), repo.user(), None)?;
1760 let path = tools::required_string_param(&param, "snapshot")?;
1761 let archive_name = tools::required_string_param(&param, "archive-name")?;
1762
1763 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
1764 let group = BackupGroup::parse(path)?;
1765
1766 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
1767 let result = client.get(&path, Some(json!({
1768 "backup-type": group.backup_type(),
1769 "backup-id": group.backup_id(),
1770 }))).await?;
1771
1772 let list = result["data"].as_array().unwrap();
314bb358 1773 if list.is_empty() {
3cf73c4e
CE
1774 bail!("backup group '{}' does not contain any snapshots:", path);
1775 }
1776
1777 let epoch = list[0]["backup-time"].as_i64().unwrap();
1778 let backup_time = Utc.timestamp(epoch, 0);
1779 (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time)
1780 } else {
1781 let snapshot = BackupDir::parse(path)?;
1782 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
1783 };
1784
1785 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
1786 let crypt_config = match keyfile {
1787 None => None,
1788 Some(path) => {
1789 let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?;
1790 Some(Arc::new(CryptConfig::new(key)?))
1791 }
1792 };
1793
1794 let server_archive_name = if archive_name.ends_with(".pxar") {
1795 format!("{}.didx", archive_name)
1796 } else {
1797 bail!("Can only mount pxar archives.");
1798 };
1799
1800 let client = BackupReader::start(
1801 client,
1802 crypt_config.clone(),
1803 repo.store(),
1804 &backup_type,
1805 &backup_id,
1806 backup_time,
1807 true,
1808 ).await?;
1809
1810 let tmpfile = std::fs::OpenOptions::new()
1811 .write(true)
1812 .read(true)
1813 .custom_flags(libc::O_TMPFILE)
1814 .open("/tmp")?;
1815
1816 let manifest = client.download_manifest().await?;
1817
1818 let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
1819 let most_used = index.find_most_used_chunks(8);
1820 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config.clone(), most_used);
1821 let reader = BufferedDynamicReader::new(index, chunk_reader);
f701d033
DM
1822 let mut decoder = pxar::Decoder::new(reader)?;
1823 decoder.set_callback(|path| {
1824 println!("{:?}", path);
1825 Ok(())
1826 });
3cf73c4e
CE
1827
1828 let tmpfile = client.download(CATALOG_NAME, tmpfile).await?;
1829 let index = DynamicIndexReader::new(tmpfile)
1830 .map_err(|err| format_err!("unable to read catalog index - {}", err))?;
1831
1832 // Note: do not use values stored in index (not trusted) - instead, computed them again
1833 let (csum, size) = index.compute_csum();
1834 manifest.verify_file(CATALOG_NAME, &csum, size)?;
1835
1836 let most_used = index.find_most_used_chunks(8);
1837 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1838 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
1839 let mut catalogfile = std::fs::OpenOptions::new()
1840 .write(true)
1841 .read(true)
1842 .custom_flags(libc::O_TMPFILE)
1843 .open("/tmp")?;
1844
1845 std::io::copy(&mut reader, &mut catalogfile)
1846 .map_err(|err| format_err!("unable to download catalog - {}", err))?;
1847
1848 catalogfile.seek(SeekFrom::Start(0))?;
1849 let catalog_reader = CatalogReader::new(catalogfile);
1850 let state = Shell::new(
1851 catalog_reader,
1852 &server_archive_name,
1853 decoder,
1854 )?;
1855
1856 println!("Starting interactive shell");
1857 state.shell()?;
1858
1859 record_repository(&repo);
1860
1861 Ok(Value::Null)
1862}
1863
f2401311 1864fn main() {
33d64b81 1865
255f378a
DM
1866 const BACKUP_SOURCE_SCHEMA: Schema = StringSchema::new("Backup source specification ([<label>:<path>]).")
1867 .format(&ApiStringFormat::Pattern(&BACKUPSPEC_REGEX))
1868 .schema();
25f1650b 1869
552c2259 1870 #[sortable]
255f378a
DM
1871 const API_METHOD_CREATE_BACKUP: ApiMethod = ApiMethod::new(
1872 &ApiHandler::Sync(&create_backup),
1873 &ObjectSchema::new(
1874 "Create (host) backup.",
552c2259 1875 &sorted!([
255f378a 1876 (
ae0be2dd 1877 "backupspec",
255f378a
DM
1878 false,
1879 &ArraySchema::new(
74cdb521 1880 "List of backup source specifications ([<label.ext>:<path>] ...)",
255f378a
DM
1881 &BACKUP_SOURCE_SCHEMA,
1882 ).min_length(1).schema()
1883 ),
1884 (
1885 "repository",
1886 true,
1887 &REPO_URL_SCHEMA
1888 ),
1889 (
2eeaacb9 1890 "include-dev",
255f378a
DM
1891 true,
1892 &ArraySchema::new(
2eeaacb9 1893 "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.",
255f378a
DM
1894 &StringSchema::new("Path to file.").schema()
1895 ).schema()
1896 ),
1897 (
6d0983db 1898 "keyfile",
255f378a
DM
1899 true,
1900 &StringSchema::new("Path to encryption key. All data will be encrypted using this key.").schema()
1901 ),
1902 (
219ef0e6 1903 "verbose",
255f378a
DM
1904 true,
1905 &BooleanSchema::new("Verbose output.")
1906 .default(false)
1907 .schema()
1908 ),
1909 (
5b72c9b4 1910 "skip-lost-and-found",
255f378a
DM
1911 true,
1912 &BooleanSchema::new("Skip lost+found directory")
1913 .default(false)
1914 .schema()
1915 ),
1916 (
bbf9e7e9 1917 "backup-type",
255f378a
DM
1918 true,
1919 &BACKUP_TYPE_SCHEMA,
1920 ),
1921 (
bbf9e7e9 1922 "backup-id",
255f378a
DM
1923 true,
1924 &BACKUP_ID_SCHEMA
1925 ),
1926 (
ca5d0b61 1927 "backup-time",
255f378a
DM
1928 true,
1929 &BACKUP_TIME_SCHEMA
1930 ),
1931 (
2d9d143a 1932 "chunk-size",
255f378a
DM
1933 true,
1934 &IntegerSchema::new("Chunk size in KB. Must be a power of 2.")
2d9d143a
DM
1935 .minimum(64)
1936 .maximum(4096)
1937 .default(4096)
255f378a
DM
1938 .schema()
1939 ),
552c2259 1940 ]),
255f378a
DM
1941 )
1942 );
1943
1944 let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP)
49fddd98 1945 .arg_param(&["backupspec"])
d0a03d40 1946 .completion_cb("repository", complete_repository)
49811347 1947 .completion_cb("backupspec", complete_backup_source)
6d0983db 1948 .completion_cb("keyfile", tools::complete_file_name)
49811347 1949 .completion_cb("chunk-size", complete_chunk_size);
f8838fe9 1950
552c2259 1951 #[sortable]
255f378a
DM
1952 const API_METHOD_UPLOAD_LOG: ApiMethod = ApiMethod::new(
1953 &ApiHandler::Sync(&upload_log),
1954 &ObjectSchema::new(
1955 "Upload backup log file.",
552c2259 1956 &sorted!([
255f378a
DM
1957 (
1958 "snapshot",
1959 false,
1960 &StringSchema::new("Snapshot path.").schema()
1961 ),
1962 (
1963 "logfile",
1964 false,
1965 &StringSchema::new("The path to the log file you want to upload.").schema()
1966 ),
1967 (
1968 "repository",
1969 true,
1970 &REPO_URL_SCHEMA
1971 ),
1972 (
ec34f7eb 1973 "keyfile",
255f378a
DM
1974 true,
1975 &StringSchema::new("Path to encryption key. All data will be encrypted using this key.").schema()
1976 ),
552c2259 1977 ]),
255f378a
DM
1978 )
1979 );
1980
1981 let upload_log_cmd_def = CliCommand::new(&API_METHOD_UPLOAD_LOG)
49fddd98 1982 .arg_param(&["snapshot", "logfile"])
543a260f 1983 .completion_cb("snapshot", complete_backup_snapshot)
ec34f7eb
DM
1984 .completion_cb("logfile", tools::complete_file_name)
1985 .completion_cb("keyfile", tools::complete_file_name)
1986 .completion_cb("repository", complete_repository);
1987
552c2259 1988 #[sortable]
255f378a
DM
1989 const API_METHOD_LIST_BACKUP_GROUPS: ApiMethod = ApiMethod::new(
1990 &ApiHandler::Sync(&list_backup_groups),
1991 &ObjectSchema::new(
1992 "List backup groups.",
552c2259 1993 &sorted!([
255f378a
DM
1994 ("repository", true, &REPO_URL_SCHEMA),
1995 ("output-format", true, &OUTPUT_FORMAT),
552c2259 1996 ]),
255f378a
DM
1997 )
1998 );
1999
2000 let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS)
d0a03d40 2001 .completion_cb("repository", complete_repository);
41c039e1 2002
552c2259 2003 #[sortable]
255f378a
DM
2004 const API_METHOD_LIST_SNAPSHOTS: ApiMethod = ApiMethod::new(
2005 &ApiHandler::Sync(&list_snapshots),
2006 &ObjectSchema::new(
2007 "List backup snapshots.",
552c2259 2008 &sorted!([
255f378a
DM
2009 ("group", true, &StringSchema::new("Backup group.").schema()),
2010 ("repository", true, &REPO_URL_SCHEMA),
2011 ("output-format", true, &OUTPUT_FORMAT),
552c2259 2012 ]),
255f378a
DM
2013 )
2014 );
2015
2016 let snapshots_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOTS)
49fddd98 2017 .arg_param(&["group"])
024f11bb 2018 .completion_cb("group", complete_backup_group)
d0a03d40 2019 .completion_cb("repository", complete_repository);
184f17af 2020
552c2259 2021 #[sortable]
255f378a
DM
2022 const API_METHOD_FORGET_SNAPSHOTS: ApiMethod = ApiMethod::new(
2023 &ApiHandler::Sync(&forget_snapshots),
2024 &ObjectSchema::new(
2025 "Forget (remove) backup snapshots.",
552c2259 2026 &sorted!([
255f378a
DM
2027 ("snapshot", false, &StringSchema::new("Snapshot path.").schema()),
2028 ("repository", true, &REPO_URL_SCHEMA),
552c2259 2029 ]),
255f378a
DM
2030 )
2031 );
2032
2033 let forget_cmd_def = CliCommand::new(&API_METHOD_FORGET_SNAPSHOTS)
49fddd98 2034 .arg_param(&["snapshot"])
b2388518 2035 .completion_cb("repository", complete_repository)
543a260f 2036 .completion_cb("snapshot", complete_backup_snapshot);
6f62c924 2037
552c2259 2038 #[sortable]
255f378a
DM
2039 const API_METHOD_START_GARBAGE_COLLECTION: ApiMethod = ApiMethod::new(
2040 &ApiHandler::Sync(&start_garbage_collection),
2041 &ObjectSchema::new(
2042 "Start garbage collection for a specific repository.",
552c2259 2043 &sorted!([ ("repository", true, &REPO_URL_SCHEMA) ]),
255f378a
DM
2044 )
2045 );
2046
2047 let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
d0a03d40 2048 .completion_cb("repository", complete_repository);
8cc0d6af 2049
552c2259 2050 #[sortable]
255f378a
DM
2051 const API_METHOD_RESTORE: ApiMethod = ApiMethod::new(
2052 &ApiHandler::Sync(&restore),
2053 &ObjectSchema::new(
2054 "Restore backup repository.",
552c2259 2055 &sorted!([
255f378a
DM
2056 ("snapshot", false, &StringSchema::new("Group/Snapshot path.").schema()),
2057 ("archive-name", false, &StringSchema::new("Backup archive name.").schema()),
2058 (
2059 "target",
2060 false,
2061 &StringSchema::new(
2062 r###"Target directory path. Use '-' to write to stdandard output.
bf125261
DM
2063
2064We do not extraxt '.pxar' archives when writing to stdandard output.
2065
2066"###
255f378a
DM
2067 ).schema()
2068 ),
2069 (
46d5aa0a 2070 "allow-existing-dirs",
255f378a
DM
2071 true,
2072 &BooleanSchema::new("Do not fail if directories already exists.")
2073 .default(false)
2074 .schema()
2075 ),
2076 ("repository", true, &REPO_URL_SCHEMA),
2077 ("keyfile", true, &StringSchema::new("Path to encryption key.").schema()),
2078 (
86eda3eb 2079 "verbose",
255f378a
DM
2080 true,
2081 &BooleanSchema::new("Verbose output.")
2082 .default(false)
2083 .schema()
2084 ),
552c2259 2085 ]),
255f378a
DM
2086 )
2087 );
2088
2089 let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE)
49fddd98 2090 .arg_param(&["snapshot", "archive-name", "target"])
b2388518 2091 .completion_cb("repository", complete_repository)
08dc340a
DM
2092 .completion_cb("snapshot", complete_group_or_snapshot)
2093 .completion_cb("archive-name", complete_archive_name)
2094 .completion_cb("target", tools::complete_file_name);
9f912493 2095
552c2259 2096 #[sortable]
255f378a
DM
2097 const API_METHOD_LIST_SNAPSHOT_FILES: ApiMethod = ApiMethod::new(
2098 &ApiHandler::Sync(&list_snapshot_files),
2099 &ObjectSchema::new(
2100 "List snapshot files.",
552c2259 2101 &sorted!([
255f378a
DM
2102 ("snapshot", false, &StringSchema::new("Snapshot path.").schema()),
2103 ("repository", true, &REPO_URL_SCHEMA),
2104 ("output-format", true, &OUTPUT_FORMAT),
552c2259 2105 ]),
255f378a
DM
2106 )
2107 );
2108
2109 let files_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOT_FILES)
49fddd98 2110 .arg_param(&["snapshot"])
52c171e4 2111 .completion_cb("repository", complete_repository)
543a260f 2112 .completion_cb("snapshot", complete_backup_snapshot);
52c171e4 2113
552c2259 2114 #[sortable]
255f378a
DM
2115 const API_METHOD_DUMP_CATALOG: ApiMethod = ApiMethod::new(
2116 &ApiHandler::Sync(&dump_catalog),
2117 &ObjectSchema::new(
2118 "Dump catalog.",
552c2259 2119 &sorted!([
255f378a
DM
2120 ("snapshot", false, &StringSchema::new("Snapshot path.").schema()),
2121 ("repository", true, &REPO_URL_SCHEMA),
552c2259 2122 ]),
255f378a
DM
2123 )
2124 );
2125
2126 let catalog_cmd_def = CliCommand::new(&API_METHOD_DUMP_CATALOG)
49fddd98 2127 .arg_param(&["snapshot"])
9049a8cf
DM
2128 .completion_cb("repository", complete_repository)
2129 .completion_cb("snapshot", complete_backup_snapshot);
2130
255f378a
DM
2131 const API_METHOD_PRUNE: ApiMethod = ApiMethod::new(
2132 &ApiHandler::Sync(&prune),
2133 &ObjectSchema::new(
2134 "Prune backup repository.",
552c2259 2135 &proxmox_backup::add_common_prune_prameters!([
255f378a 2136 ("group", false, &StringSchema::new("Backup group.").schema()),
552c2259 2137 ], [
255f378a 2138 ("repository", true, &REPO_URL_SCHEMA),
552c2259 2139 ])
255f378a
DM
2140 )
2141 );
2142
2143 let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE)
49fddd98 2144 .arg_param(&["group"])
9fdc3ef4 2145 .completion_cb("group", complete_backup_group)
d0a03d40 2146 .completion_cb("repository", complete_repository);
9f912493 2147
552c2259 2148 #[sortable]
255f378a
DM
2149 const API_METHOD_STATUS: ApiMethod = ApiMethod::new(
2150 &ApiHandler::Sync(&status),
2151 &ObjectSchema::new(
2152 "Get repository status.",
552c2259 2153 &sorted!([
255f378a
DM
2154 ("repository", true, &REPO_URL_SCHEMA),
2155 ("output-format", true, &OUTPUT_FORMAT),
552c2259 2156 ]),
255f378a
DM
2157 )
2158 );
2159
2160 let status_cmd_def = CliCommand::new(&API_METHOD_STATUS)
34a816cc
DM
2161 .completion_cb("repository", complete_repository);
2162
552c2259 2163 #[sortable]
255f378a
DM
2164 const API_METHOD_API_LOGIN: ApiMethod = ApiMethod::new(
2165 &ApiHandler::Sync(&api_login),
2166 &ObjectSchema::new(
2167 "Try to login. If successful, store ticket.",
552c2259 2168 &sorted!([ ("repository", true, &REPO_URL_SCHEMA) ]),
255f378a
DM
2169 )
2170 );
2171
2172 let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN)
e240d8be
DM
2173 .completion_cb("repository", complete_repository);
2174
552c2259 2175 #[sortable]
255f378a
DM
2176 const API_METHOD_API_LOGOUT: ApiMethod = ApiMethod::new(
2177 &ApiHandler::Sync(&api_logout),
2178 &ObjectSchema::new(
2179 "Logout (delete stored ticket).",
552c2259 2180 &sorted!([ ("repository", true, &REPO_URL_SCHEMA) ]),
255f378a
DM
2181 )
2182 );
2183
2184 let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT)
e240d8be 2185 .completion_cb("repository", complete_repository);
32efac1c 2186
552c2259 2187 #[sortable]
255f378a
DM
2188 const API_METHOD_MOUNT: ApiMethod = ApiMethod::new(
2189 &ApiHandler::Sync(&mount),
2190 &ObjectSchema::new(
2191 "Mount pxar archive.",
552c2259 2192 &sorted!([
255f378a
DM
2193 ("snapshot", false, &StringSchema::new("Group/Snapshot path.").schema()),
2194 ("archive-name", false, &StringSchema::new("Backup archive name.").schema()),
2195 ("target", false, &StringSchema::new("Target directory path.").schema()),
2196 ("repository", true, &REPO_URL_SCHEMA),
2197 ("keyfile", true, &StringSchema::new("Path to encryption key.").schema()),
2198 ("verbose", true, &BooleanSchema::new("Verbose output.").default(false).schema()),
552c2259 2199 ]),
255f378a
DM
2200 )
2201 );
2202
2203 let mount_cmd_def = CliCommand::new(&API_METHOD_MOUNT)
49fddd98 2204 .arg_param(&["snapshot", "archive-name", "target"])
70235f72
CE
2205 .completion_cb("repository", complete_repository)
2206 .completion_cb("snapshot", complete_group_or_snapshot)
2207 .completion_cb("archive-name", complete_archive_name)
2208 .completion_cb("target", tools::complete_file_name);
e240d8be 2209
3cf73c4e
CE
2210 #[sortable]
2211 const API_METHOD_SHELL: ApiMethod = ApiMethod::new(
2212 &ApiHandler::Sync(&shell),
2213 &ObjectSchema::new(
2214 "Shell to interactively inspect and restore snapshots.",
2215 &sorted!([
2216 ("snapshot", false, &StringSchema::new("Group/Snapshot path.").schema()),
2217 ("archive-name", false, &StringSchema::new("Backup archive name.").schema()),
2218 ("repository", true, &REPO_URL_SCHEMA),
2219 ("keyfile", true, &StringSchema::new("Path to encryption key.").schema()),
2220 ]),
2221 )
2222 );
2223
2224 let shell_cmd_def = CliCommand::new(&API_METHOD_SHELL)
49fddd98 2225 .arg_param(&["snapshot", "archive-name"])
3cf73c4e
CE
2226 .completion_cb("repository", complete_repository)
2227 .completion_cb("archive-name", complete_archive_name)
2228 .completion_cb("snapshot", complete_group_or_snapshot);
2229
41c039e1 2230 let cmd_def = CliCommandMap::new()
597a9203 2231 .insert("backup".to_owned(), backup_cmd_def.into())
ec34f7eb 2232 .insert("upload-log".to_owned(), upload_log_cmd_def.into())
6f62c924 2233 .insert("forget".to_owned(), forget_cmd_def.into())
9049a8cf 2234 .insert("catalog".to_owned(), catalog_cmd_def.into())
8cc0d6af 2235 .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into())
83b7db02 2236 .insert("list".to_owned(), list_cmd_def.into())
e240d8be
DM
2237 .insert("login".to_owned(), login_cmd_def.into())
2238 .insert("logout".to_owned(), logout_cmd_def.into())
184f17af 2239 .insert("prune".to_owned(), prune_cmd_def.into())
9f912493 2240 .insert("restore".to_owned(), restore_cmd_def.into())
f2401311 2241 .insert("snapshots".to_owned(), snapshots_cmd_def.into())
52c171e4 2242 .insert("files".to_owned(), files_cmd_def.into())
34a816cc 2243 .insert("status".to_owned(), status_cmd_def.into())
70235f72 2244 .insert("key".to_owned(), key_mgmt_cli().into())
3cf73c4e
CE
2245 .insert("mount".to_owned(), mount_cmd_def.into())
2246 .insert("shell".to_owned(), shell_cmd_def.into());
a914a774 2247
e9722f8b
WB
2248 run_cli_command(cmd_def.into());
2249}
496a6784 2250
e9722f8b
WB
2251fn async_main<F: Future>(fut: F) -> <F as Future>::Output {
2252 let rt = tokio::runtime::Runtime::new().unwrap();
2253 let ret = rt.block_on(fut);
2254 rt.shutdown_now();
2255 ret
ff5d3707 2256}