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