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