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