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