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