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