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