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