]>
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>>( |
cf9271e2 | 183 | client: &BackupWriter, |
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>>( |
cf9271e2 | 215 | client: &BackupWriter, |
6af905c1 DM |
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) => { | |
a8f10f84 | 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 | 481 | async_main(async move { |
9e490a74 DM |
482 | let client = BackupReader::start( |
483 | client, | |
296c50ba | 484 | crypt_config.clone(), |
e9722f8b WB |
485 | repo.store(), |
486 | &snapshot.group().backup_type(), | |
487 | &snapshot.group().backup_id(), | |
9e490a74 DM |
488 | snapshot.backup_time(), |
489 | true, | |
490 | ).await?; | |
9049a8cf | 491 | |
f06b820a | 492 | let manifest = client.download_manifest().await?; |
d2267b11 | 493 | |
e9722f8b WB |
494 | let blob_file = std::fs::OpenOptions::new() |
495 | .read(true) | |
496 | .write(true) | |
497 | .custom_flags(libc::O_TMPFILE) | |
498 | .open("/tmp")?; | |
9049a8cf | 499 | |
d2267b11 DM |
500 | let mut blob_file = client.download(CATALOG_BLOB_NAME, blob_file).await?; |
501 | ||
502 | let (csum, size) = compute_file_csum(&mut blob_file)?; | |
f06b820a | 503 | manifest.verify_file(CATALOG_BLOB_NAME, &csum, size)?; |
a84ef4c2 | 504 | |
e9722f8b | 505 | blob_file.seek(SeekFrom::Start(0))?; |
a84ef4c2 | 506 | |
e9722f8b WB |
507 | let reader = BufReader::new(blob_file); |
508 | let mut catalog_reader = CatalogBlobReader::new(reader, crypt_config)?; | |
9049a8cf | 509 | |
e9722f8b | 510 | catalog_reader.dump()?; |
9049a8cf | 511 | |
e9722f8b WB |
512 | record_repository(&repo); |
513 | ||
514 | Ok::<(), Error>(()) | |
515 | })?; | |
9049a8cf DM |
516 | |
517 | Ok(Value::Null) | |
518 | } | |
519 | ||
52c171e4 DM |
520 | fn list_snapshot_files( |
521 | param: Value, | |
522 | _info: &ApiMethod, | |
523 | _rpcenv: &mut dyn RpcEnvironment, | |
524 | ) -> Result<Value, Error> { | |
525 | ||
526 | let repo = extract_repository_from_value(¶m)?; | |
527 | ||
528 | let path = tools::required_string_param(¶m, "snapshot")?; | |
529 | let snapshot = BackupDir::parse(path)?; | |
530 | ||
531 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); | |
532 | ||
cc2ce4a9 | 533 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
52c171e4 DM |
534 | |
535 | let path = format!("api2/json/admin/datastore/{}/files", repo.store()); | |
536 | ||
e9722f8b WB |
537 | let mut result = async_main(async move { |
538 | client.get(&path, Some(json!({ | |
539 | "backup-type": snapshot.group().backup_type(), | |
540 | "backup-id": snapshot.group().backup_id(), | |
541 | "backup-time": snapshot.backup_time().timestamp(), | |
542 | }))).await | |
543 | })?; | |
52c171e4 DM |
544 | |
545 | record_repository(&repo); | |
546 | ||
8c70e3eb | 547 | let list: Value = result["data"].take(); |
52c171e4 DM |
548 | |
549 | if output_format == "text" { | |
8c70e3eb DM |
550 | for item in list.as_array().unwrap().iter() { |
551 | println!( | |
552 | "{} {}", | |
553 | strip_server_file_expenstion(item["filename"].as_str().unwrap()), | |
554 | item["size"].as_u64().unwrap_or(0), | |
555 | ); | |
52c171e4 DM |
556 | } |
557 | } else { | |
8c70e3eb | 558 | format_and_print_result(&list, &output_format); |
52c171e4 DM |
559 | } |
560 | ||
561 | Ok(Value::Null) | |
562 | } | |
563 | ||
8cc0d6af DM |
564 | fn start_garbage_collection( |
565 | param: Value, | |
566 | _info: &ApiMethod, | |
dd5495d6 | 567 | _rpcenv: &mut dyn RpcEnvironment, |
8cc0d6af DM |
568 | ) -> Result<Value, Error> { |
569 | ||
2665cef7 | 570 | let repo = extract_repository_from_value(¶m)?; |
8cc0d6af | 571 | |
cc2ce4a9 | 572 | let mut client = HttpClient::new(repo.host(), repo.user(), None)?; |
8cc0d6af | 573 | |
d0a03d40 | 574 | let path = format!("api2/json/admin/datastore/{}/gc", repo.store()); |
8cc0d6af | 575 | |
e9722f8b | 576 | let result = async_main(async move { client.post(&path, None).await })?; |
8cc0d6af | 577 | |
d0a03d40 DM |
578 | record_repository(&repo); |
579 | ||
8cc0d6af DM |
580 | Ok(result) |
581 | } | |
33d64b81 | 582 | |
ae0be2dd DM |
583 | fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> { |
584 | ||
585 | if let Some(caps) = BACKUPSPEC_REGEX.captures(value) { | |
586 | return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str())); | |
587 | } | |
588 | bail!("unable to parse directory specification '{}'", value); | |
589 | } | |
590 | ||
6049b71f DM |
591 | fn create_backup( |
592 | param: Value, | |
593 | _info: &ApiMethod, | |
dd5495d6 | 594 | _rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 595 | ) -> Result<Value, Error> { |
ff5d3707 | 596 | |
2665cef7 | 597 | let repo = extract_repository_from_value(¶m)?; |
ae0be2dd DM |
598 | |
599 | let backupspec_list = tools::required_array_param(¶m, "backupspec")?; | |
a914a774 | 600 | |
eed6db39 DM |
601 | let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false); |
602 | ||
5b72c9b4 DM |
603 | let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false); |
604 | ||
219ef0e6 DM |
605 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
606 | ||
ca5d0b61 DM |
607 | let backup_time_opt = param["backup-time"].as_i64(); |
608 | ||
36898ffc | 609 | let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize); |
2d9d143a | 610 | |
247cdbce DM |
611 | if let Some(size) = chunk_size_opt { |
612 | verify_chunk_size(size)?; | |
2d9d143a DM |
613 | } |
614 | ||
6d0983db DM |
615 | let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p)); |
616 | ||
f69adc81 | 617 | let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename()); |
fba30411 | 618 | |
bbf9e7e9 | 619 | let backup_type = param["backup-type"].as_str().unwrap_or("host"); |
ca5d0b61 | 620 | |
2eeaacb9 DM |
621 | let include_dev = param["include-dev"].as_array(); |
622 | ||
623 | let mut devices = if all_file_systems { None } else { Some(HashSet::new()) }; | |
624 | ||
625 | if let Some(include_dev) = include_dev { | |
626 | if all_file_systems { | |
627 | bail!("option 'all-file-systems' conflicts with option 'include-dev'"); | |
628 | } | |
629 | ||
630 | let mut set = HashSet::new(); | |
631 | for path in include_dev { | |
632 | let path = path.as_str().unwrap(); | |
633 | let stat = nix::sys::stat::stat(path) | |
634 | .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?; | |
635 | set.insert(stat.st_dev); | |
636 | } | |
637 | devices = Some(set); | |
638 | } | |
639 | ||
ae0be2dd | 640 | let mut upload_list = vec![]; |
a914a774 | 641 | |
79679c2d | 642 | enum BackupType { PXAR, IMAGE, CONFIG, LOGFILE }; |
6af905c1 | 643 | |
ae0be2dd DM |
644 | for backupspec in backupspec_list { |
645 | let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?; | |
bcd879cf | 646 | |
eb1804c5 DM |
647 | use std::os::unix::fs::FileTypeExt; |
648 | ||
3fa71727 CE |
649 | let metadata = std::fs::metadata(filename) |
650 | .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?; | |
eb1804c5 | 651 | let file_type = metadata.file_type(); |
23bb8780 | 652 | |
4af0ee05 DM |
653 | let extension = target.rsplit('.').next() |
654 | .ok_or(format_err!("missing target file extenion '{}'", target))?; | |
bcd879cf | 655 | |
ec8a9bb9 DM |
656 | match extension { |
657 | "pxar" => { | |
658 | if !file_type.is_dir() { | |
659 | bail!("got unexpected file type (expected directory)"); | |
660 | } | |
4af0ee05 | 661 | upload_list.push((BackupType::PXAR, filename.to_owned(), format!("{}.didx", target), 0)); |
ec8a9bb9 DM |
662 | } |
663 | "img" => { | |
eb1804c5 | 664 | |
ec8a9bb9 DM |
665 | if !(file_type.is_file() || file_type.is_block_device()) { |
666 | bail!("got unexpected file type (expected file or block device)"); | |
667 | } | |
eb1804c5 | 668 | |
e18a6c9e | 669 | let size = image_size(&PathBuf::from(filename))?; |
23bb8780 | 670 | |
ec8a9bb9 | 671 | if size == 0 { bail!("got zero-sized file '{}'", filename); } |
ae0be2dd | 672 | |
4af0ee05 | 673 | upload_list.push((BackupType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size)); |
ec8a9bb9 DM |
674 | } |
675 | "conf" => { | |
676 | if !file_type.is_file() { | |
677 | bail!("got unexpected file type (expected regular file)"); | |
678 | } | |
4af0ee05 | 679 | upload_list.push((BackupType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
ec8a9bb9 | 680 | } |
79679c2d DM |
681 | "log" => { |
682 | if !file_type.is_file() { | |
683 | bail!("got unexpected file type (expected regular file)"); | |
684 | } | |
4af0ee05 | 685 | upload_list.push((BackupType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
79679c2d | 686 | } |
ec8a9bb9 DM |
687 | _ => { |
688 | bail!("got unknown archive extension '{}'", extension); | |
689 | } | |
ae0be2dd DM |
690 | } |
691 | } | |
692 | ||
ca5d0b61 | 693 | let backup_time = Utc.timestamp(backup_time_opt.unwrap_or(Utc::now().timestamp()), 0); |
ae0be2dd | 694 | |
cc2ce4a9 | 695 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
d0a03d40 DM |
696 | record_repository(&repo); |
697 | ||
ca5d0b61 DM |
698 | println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time)); |
699 | ||
f69adc81 | 700 | println!("Client name: {}", proxmox::tools::nodename()); |
ca5d0b61 DM |
701 | |
702 | let start_time = Local::now(); | |
703 | ||
7a6cfbd9 | 704 | println!("Starting protocol: {}", start_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false)); |
51144821 | 705 | |
bb823140 DM |
706 | let (crypt_config, rsa_encrypted_key) = match keyfile { |
707 | None => (None, None), | |
6d0983db | 708 | Some(path) => { |
a8f10f84 | 709 | let (key, created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
bb823140 DM |
710 | |
711 | let crypt_config = CryptConfig::new(key)?; | |
712 | ||
713 | let path = master_pubkey_path()?; | |
714 | if path.exists() { | |
e18a6c9e | 715 | let pem_data = file_get_contents(&path)?; |
bb823140 DM |
716 | let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?; |
717 | let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?; | |
718 | (Some(Arc::new(crypt_config)), Some(enc_key)) | |
719 | } else { | |
720 | (Some(Arc::new(crypt_config)), None) | |
721 | } | |
6d0983db DM |
722 | } |
723 | }; | |
f98ac774 | 724 | |
e9722f8b | 725 | async_main(async move { |
cf9271e2 DM |
726 | let client = BackupWriter::start( |
727 | client, | |
728 | repo.store(), | |
729 | backup_type, | |
730 | &backup_id, | |
731 | backup_time, | |
732 | verbose, | |
733 | ).await?; | |
e9722f8b | 734 | |
59e9ba01 DM |
735 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time.timestamp()); |
736 | let mut manifest = BackupManifest::new(snapshot); | |
e9722f8b WB |
737 | |
738 | // fixme: encrypt/sign catalog? | |
739 | let catalog_file = std::fs::OpenOptions::new() | |
740 | .write(true) | |
741 | .read(true) | |
742 | .custom_flags(libc::O_TMPFILE) | |
743 | .open("/tmp")?; | |
744 | ||
745 | let catalog = Arc::new(Mutex::new(CatalogBlobWriter::new_compressed(catalog_file)?)); | |
746 | let mut upload_catalog = false; | |
747 | ||
748 | for (backup_type, filename, target, size) in upload_list { | |
749 | match backup_type { | |
750 | BackupType::CONFIG => { | |
751 | println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target); | |
752 | let stats = client | |
753 | .upload_blob_from_file(&filename, &target, crypt_config.clone(), true) | |
754 | .await?; | |
59e9ba01 | 755 | manifest.add_file(target, stats.size, stats.csum); |
e9722f8b WB |
756 | } |
757 | BackupType::LOGFILE => { // fixme: remove - not needed anymore ? | |
758 | println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target); | |
759 | let stats = client | |
760 | .upload_blob_from_file(&filename, &target, crypt_config.clone(), true) | |
761 | .await?; | |
59e9ba01 | 762 | manifest.add_file(target, stats.size, stats.csum); |
e9722f8b WB |
763 | } |
764 | BackupType::PXAR => { | |
765 | upload_catalog = true; | |
766 | println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target); | |
767 | catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?; | |
768 | let stats = backup_directory( | |
769 | &client, | |
770 | &filename, | |
771 | &target, | |
772 | chunk_size_opt, | |
773 | devices.clone(), | |
774 | verbose, | |
775 | skip_lost_and_found, | |
776 | crypt_config.clone(), | |
777 | catalog.clone(), | |
778 | ).await?; | |
59e9ba01 | 779 | manifest.add_file(target, stats.size, stats.csum); |
e9722f8b WB |
780 | catalog.lock().unwrap().end_directory()?; |
781 | } | |
782 | BackupType::IMAGE => { | |
783 | println!("Upload image '{}' to '{:?}' as {}", filename, repo, target); | |
784 | let stats = backup_image( | |
785 | &client, | |
786 | &filename, | |
787 | &target, | |
788 | size, | |
789 | chunk_size_opt, | |
790 | verbose, | |
791 | crypt_config.clone(), | |
792 | ).await?; | |
59e9ba01 | 793 | manifest.add_file(target, stats.size, stats.csum); |
e9722f8b | 794 | } |
6af905c1 DM |
795 | } |
796 | } | |
4818c8b6 | 797 | |
e9722f8b WB |
798 | // finalize and upload catalog |
799 | if upload_catalog { | |
800 | let mutex = Arc::try_unwrap(catalog) | |
801 | .map_err(|_| format_err!("unable to get catalog (still used)"))?; | |
802 | let mut catalog_file = mutex.into_inner().unwrap().finish()?; | |
2761d6a4 | 803 | |
d2267b11 | 804 | let target = CATALOG_BLOB_NAME; |
2761d6a4 | 805 | |
e9722f8b | 806 | catalog_file.seek(SeekFrom::Start(0))?; |
9d135fe6 | 807 | |
e9722f8b | 808 | let stats = client.upload_blob(catalog_file, target).await?; |
59e9ba01 | 809 | manifest.add_file(target.to_owned(), stats.size, stats.csum); |
e9722f8b | 810 | } |
2761d6a4 | 811 | |
e9722f8b WB |
812 | if let Some(rsa_encrypted_key) = rsa_encrypted_key { |
813 | let target = "rsa-encrypted.key"; | |
814 | println!("Upload RSA encoded key to '{:?}' as {}", repo, target); | |
815 | let stats = client | |
816 | .upload_blob_from_data(rsa_encrypted_key, target, None, false, false) | |
817 | .await?; | |
59e9ba01 | 818 | manifest.add_file(format!("{}.blob", target), stats.size, stats.csum); |
e9722f8b WB |
819 | |
820 | // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t | |
821 | /* | |
822 | let mut buffer2 = vec![0u8; rsa.size() as usize]; | |
823 | let pem_data = file_get_contents("master-private.pem")?; | |
824 | let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?; | |
825 | let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?; | |
826 | println!("TEST {} {:?}", len, buffer2); | |
827 | */ | |
828 | } | |
9f46c7de | 829 | |
59e9ba01 DM |
830 | // create manifest (index.json) |
831 | let manifest = manifest.into_json(); | |
2c3891d1 | 832 | |
e9722f8b | 833 | println!("Upload index.json to '{:?}'", repo); |
59e9ba01 | 834 | let manifest = serde_json::to_string_pretty(&manifest)?.into(); |
e9722f8b | 835 | client |
59e9ba01 | 836 | .upload_blob_from_data(manifest, MANIFEST_BLOB_NAME, crypt_config.clone(), true, true) |
e9722f8b | 837 | .await?; |
2c3891d1 | 838 | |
e9722f8b | 839 | client.finish().await?; |
c4ff3dce | 840 | |
e9722f8b WB |
841 | let end_time = Local::now(); |
842 | let elapsed = end_time.signed_duration_since(start_time); | |
843 | println!("Duration: {}", elapsed); | |
3ec3ec3f | 844 | |
e9722f8b | 845 | println!("End Time: {}", end_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false)); |
3d5c11e5 | 846 | |
e9722f8b WB |
847 | Ok(Value::Null) |
848 | }) | |
f98ea63d DM |
849 | } |
850 | ||
d0a03d40 | 851 | fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
f98ea63d DM |
852 | |
853 | let mut result = vec![]; | |
854 | ||
855 | let data: Vec<&str> = arg.splitn(2, ':').collect(); | |
856 | ||
bff11030 | 857 | if data.len() != 2 { |
8968258b DM |
858 | result.push(String::from("root.pxar:/")); |
859 | result.push(String::from("etc.pxar:/etc")); | |
bff11030 DM |
860 | return result; |
861 | } | |
f98ea63d | 862 | |
496a6784 | 863 | let files = tools::complete_file_name(data[1], param); |
f98ea63d DM |
864 | |
865 | for file in files { | |
866 | result.push(format!("{}:{}", data[0], file)); | |
867 | } | |
868 | ||
869 | result | |
ff5d3707 | 870 | } |
871 | ||
9f912493 DM |
872 | fn restore( |
873 | param: Value, | |
874 | _info: &ApiMethod, | |
dd5495d6 | 875 | _rpcenv: &mut dyn RpcEnvironment, |
9f912493 | 876 | ) -> Result<Value, Error> { |
e9722f8b WB |
877 | async_main(restore_do(param)) |
878 | } | |
9f912493 | 879 | |
88892ea8 DM |
880 | fn dump_image<W: Write>( |
881 | client: Arc<BackupReader>, | |
882 | crypt_config: Option<Arc<CryptConfig>>, | |
883 | index: FixedIndexReader, | |
884 | mut writer: W, | |
fd04ca7a | 885 | verbose: bool, |
88892ea8 DM |
886 | ) -> Result<(), Error> { |
887 | ||
888 | let most_used = index.find_most_used_chunks(8); | |
889 | ||
890 | let mut chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
891 | ||
892 | // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy | |
893 | // and thus slows down reading. Instead, directly use RemoteChunkReader | |
fd04ca7a DM |
894 | let mut per = 0; |
895 | let mut bytes = 0; | |
896 | let start_time = std::time::Instant::now(); | |
897 | ||
88892ea8 DM |
898 | for pos in 0..index.index_count() { |
899 | let digest = index.index_digest(pos).unwrap(); | |
900 | let raw_data = chunk_reader.read_chunk(&digest)?; | |
901 | writer.write_all(&raw_data)?; | |
fd04ca7a DM |
902 | bytes += raw_data.len(); |
903 | if verbose { | |
904 | let next_per = ((pos+1)*100)/index.index_count(); | |
905 | if per != next_per { | |
906 | eprintln!("progress {}% (read {} bytes, duration {} sec)", | |
907 | next_per, bytes, start_time.elapsed().as_secs()); | |
908 | per = next_per; | |
909 | } | |
910 | } | |
88892ea8 DM |
911 | } |
912 | ||
fd04ca7a DM |
913 | let end_time = std::time::Instant::now(); |
914 | let elapsed = end_time.duration_since(start_time); | |
915 | eprintln!("restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)", | |
916 | bytes, | |
917 | elapsed.as_secs_f64(), | |
918 | bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64()) | |
919 | ); | |
920 | ||
921 | ||
88892ea8 DM |
922 | Ok(()) |
923 | } | |
924 | ||
e9722f8b | 925 | async fn restore_do(param: Value) -> Result<Value, Error> { |
2665cef7 | 926 | let repo = extract_repository_from_value(¶m)?; |
9f912493 | 927 | |
86eda3eb DM |
928 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
929 | ||
46d5aa0a DM |
930 | let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false); |
931 | ||
d5c34d98 DM |
932 | let archive_name = tools::required_string_param(¶m, "archive-name")?; |
933 | ||
cc2ce4a9 | 934 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
d0a03d40 | 935 | |
d0a03d40 | 936 | record_repository(&repo); |
d5c34d98 | 937 | |
9f912493 | 938 | let path = tools::required_string_param(¶m, "snapshot")?; |
9f912493 | 939 | |
86eda3eb | 940 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { |
d5c34d98 | 941 | let group = BackupGroup::parse(path)?; |
9f912493 | 942 | |
9e391bb7 DM |
943 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
944 | let result = client.get(&path, Some(json!({ | |
d5c34d98 DM |
945 | "backup-type": group.backup_type(), |
946 | "backup-id": group.backup_id(), | |
e9722f8b | 947 | }))).await?; |
9f912493 | 948 | |
d5c34d98 DM |
949 | let list = result["data"].as_array().unwrap(); |
950 | if list.len() == 0 { | |
951 | bail!("backup group '{}' does not contain any snapshots:", path); | |
952 | } | |
9f912493 | 953 | |
86eda3eb | 954 | let epoch = list[0]["backup-time"].as_i64().unwrap(); |
fa5d6977 | 955 | let backup_time = Utc.timestamp(epoch, 0); |
86eda3eb | 956 | (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time) |
d5c34d98 DM |
957 | } else { |
958 | let snapshot = BackupDir::parse(path)?; | |
86eda3eb DM |
959 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) |
960 | }; | |
9f912493 | 961 | |
d5c34d98 | 962 | let target = tools::required_string_param(¶m, "target")?; |
bf125261 | 963 | let target = if target == "-" { None } else { Some(target) }; |
2ae7d196 | 964 | |
86eda3eb | 965 | let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p)); |
2ae7d196 | 966 | |
86eda3eb DM |
967 | let crypt_config = match keyfile { |
968 | None => None, | |
969 | Some(path) => { | |
a8f10f84 | 970 | let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
86eda3eb DM |
971 | Some(Arc::new(CryptConfig::new(key)?)) |
972 | } | |
973 | }; | |
d5c34d98 | 974 | |
afb4cd28 DM |
975 | let server_archive_name = if archive_name.ends_with(".pxar") { |
976 | format!("{}.didx", archive_name) | |
977 | } else if archive_name.ends_with(".img") { | |
978 | format!("{}.fidx", archive_name) | |
979 | } else { | |
f8100e96 | 980 | format!("{}.blob", archive_name) |
afb4cd28 | 981 | }; |
9f912493 | 982 | |
296c50ba DM |
983 | let client = BackupReader::start( |
984 | client, | |
985 | crypt_config.clone(), | |
986 | repo.store(), | |
987 | &backup_type, | |
988 | &backup_id, | |
989 | backup_time, | |
990 | true, | |
991 | ).await?; | |
86eda3eb | 992 | |
86eda3eb DM |
993 | let tmpfile = std::fs::OpenOptions::new() |
994 | .write(true) | |
995 | .read(true) | |
996 | .custom_flags(libc::O_TMPFILE) | |
997 | .open("/tmp")?; | |
998 | ||
f06b820a | 999 | let manifest = client.download_manifest().await?; |
02fcf372 | 1000 | |
ad6e5a6f | 1001 | if server_archive_name == MANIFEST_BLOB_NAME { |
f06b820a | 1002 | let backup_index_data = manifest.into_json().to_string(); |
02fcf372 | 1003 | if let Some(target) = target { |
296c50ba | 1004 | file_set_contents(target, backup_index_data.as_bytes(), None)?; |
02fcf372 DM |
1005 | } else { |
1006 | let stdout = std::io::stdout(); | |
1007 | let mut writer = stdout.lock(); | |
296c50ba | 1008 | writer.write_all(backup_index_data.as_bytes()) |
02fcf372 DM |
1009 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1010 | } | |
1011 | ||
1012 | } else if server_archive_name.ends_with(".blob") { | |
2b92971f | 1013 | let mut tmpfile = client.download(&server_archive_name, tmpfile).await?; |
d2267b11 DM |
1014 | |
1015 | let (csum, size) = compute_file_csum(&mut tmpfile)?; | |
f06b820a | 1016 | manifest.verify_file(&server_archive_name, &csum, size)?; |
d2267b11 | 1017 | |
0d986280 DM |
1018 | tmpfile.seek(SeekFrom::Start(0))?; |
1019 | let mut reader = DataBlobReader::new(tmpfile, crypt_config)?; | |
f8100e96 | 1020 | |
bf125261 | 1021 | if let Some(target) = target { |
0d986280 DM |
1022 | let mut writer = std::fs::OpenOptions::new() |
1023 | .write(true) | |
1024 | .create(true) | |
1025 | .create_new(true) | |
1026 | .open(target) | |
1027 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?; | |
1028 | std::io::copy(&mut reader, &mut writer)?; | |
bf125261 DM |
1029 | } else { |
1030 | let stdout = std::io::stdout(); | |
1031 | let mut writer = stdout.lock(); | |
0d986280 | 1032 | std::io::copy(&mut reader, &mut writer) |
bf125261 DM |
1033 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1034 | } | |
f8100e96 DM |
1035 | |
1036 | } else if server_archive_name.ends_with(".didx") { | |
e9722f8b | 1037 | let tmpfile = client.download(&server_archive_name, tmpfile).await?; |
86eda3eb | 1038 | |
afb4cd28 DM |
1039 | let index = DynamicIndexReader::new(tmpfile) |
1040 | .map_err(|err| format_err!("unable to read dynamic index '{}' - {}", archive_name, err))?; | |
86eda3eb | 1041 | |
df65bd3d DM |
1042 | // Note: do not use values stored in index (not trusted) - instead, computed them again |
1043 | let (csum, size) = index.compute_csum(); | |
f06b820a | 1044 | manifest.verify_file(&server_archive_name, &csum, size)?; |
df65bd3d | 1045 | |
f4bf7dfc DM |
1046 | let most_used = index.find_most_used_chunks(8); |
1047 | ||
1048 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
1049 | ||
afb4cd28 | 1050 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
86eda3eb | 1051 | |
bf125261 | 1052 | if let Some(target) = target { |
86eda3eb | 1053 | |
47651f95 | 1054 | let feature_flags = pxar::flags::DEFAULT; |
bf125261 DM |
1055 | let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags, |path| { |
1056 | if verbose { | |
fd04ca7a | 1057 | eprintln!("{:?}", path); |
bf125261 DM |
1058 | } |
1059 | Ok(()) | |
1060 | }); | |
6a879109 CE |
1061 | decoder.set_allow_existing_dirs(allow_existing_dirs); |
1062 | ||
fa7e957c | 1063 | decoder.restore(Path::new(target), &Vec::new())?; |
bf125261 | 1064 | } else { |
88892ea8 DM |
1065 | let mut writer = std::fs::OpenOptions::new() |
1066 | .write(true) | |
1067 | .open("/dev/stdout") | |
1068 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?; | |
afb4cd28 | 1069 | |
bf125261 DM |
1070 | std::io::copy(&mut reader, &mut writer) |
1071 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
1072 | } | |
afb4cd28 | 1073 | } else if server_archive_name.ends_with(".fidx") { |
e9722f8b | 1074 | let tmpfile = client.download(&server_archive_name, tmpfile).await?; |
afb4cd28 DM |
1075 | |
1076 | let index = FixedIndexReader::new(tmpfile) | |
1077 | .map_err(|err| format_err!("unable to read fixed index '{}' - {}", archive_name, err))?; | |
7dcbe051 | 1078 | |
df65bd3d DM |
1079 | // Note: do not use values stored in index (not trusted) - instead, computed them again |
1080 | let (csum, size) = index.compute_csum(); | |
f06b820a | 1081 | manifest.verify_file(&server_archive_name, &csum, size)?; |
df65bd3d | 1082 | |
88892ea8 DM |
1083 | let mut writer = if let Some(target) = target { |
1084 | std::fs::OpenOptions::new() | |
bf125261 DM |
1085 | .write(true) |
1086 | .create(true) | |
1087 | .create_new(true) | |
1088 | .open(target) | |
88892ea8 | 1089 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))? |
bf125261 | 1090 | } else { |
88892ea8 DM |
1091 | std::fs::OpenOptions::new() |
1092 | .write(true) | |
1093 | .open("/dev/stdout") | |
1094 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))? | |
1095 | }; | |
afb4cd28 | 1096 | |
fd04ca7a | 1097 | dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose)?; |
88892ea8 DM |
1098 | |
1099 | } else { | |
f8100e96 | 1100 | bail!("unknown archive file extension (expected .pxar of .img)"); |
3031e44c | 1101 | } |
fef44d4f DM |
1102 | |
1103 | Ok(Value::Null) | |
45db6f89 DM |
1104 | } |
1105 | ||
ec34f7eb DM |
1106 | fn upload_log( |
1107 | param: Value, | |
1108 | _info: &ApiMethod, | |
1109 | _rpcenv: &mut dyn RpcEnvironment, | |
1110 | ) -> Result<Value, Error> { | |
1111 | ||
1112 | let logfile = tools::required_string_param(¶m, "logfile")?; | |
1113 | let repo = extract_repository_from_value(¶m)?; | |
1114 | ||
1115 | let snapshot = tools::required_string_param(¶m, "snapshot")?; | |
1116 | let snapshot = BackupDir::parse(snapshot)?; | |
1117 | ||
cc2ce4a9 | 1118 | let mut client = HttpClient::new(repo.host(), repo.user(), None)?; |
ec34f7eb DM |
1119 | |
1120 | let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p)); | |
1121 | ||
1122 | let crypt_config = match keyfile { | |
1123 | None => None, | |
1124 | Some(path) => { | |
a8f10f84 | 1125 | let (key, _created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
ec34f7eb | 1126 | let crypt_config = CryptConfig::new(key)?; |
9025312a | 1127 | Some(Arc::new(crypt_config)) |
ec34f7eb DM |
1128 | } |
1129 | }; | |
1130 | ||
e18a6c9e | 1131 | let data = file_get_contents(logfile)?; |
ec34f7eb | 1132 | |
7123ff7d | 1133 | let blob = DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?; |
ec34f7eb DM |
1134 | |
1135 | let raw_data = blob.into_inner(); | |
1136 | ||
1137 | let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store()); | |
1138 | ||
1139 | let args = json!({ | |
1140 | "backup-type": snapshot.group().backup_type(), | |
1141 | "backup-id": snapshot.group().backup_id(), | |
1142 | "backup-time": snapshot.backup_time().timestamp(), | |
1143 | }); | |
1144 | ||
1145 | let body = hyper::Body::from(raw_data); | |
1146 | ||
e9722f8b WB |
1147 | async_main(async move { |
1148 | client.upload("application/octet-stream", body, &path, Some(args)).await | |
1149 | }) | |
ec34f7eb DM |
1150 | } |
1151 | ||
83b7db02 | 1152 | fn prune( |
ea7a7ef2 | 1153 | mut param: Value, |
83b7db02 | 1154 | _info: &ApiMethod, |
dd5495d6 | 1155 | _rpcenv: &mut dyn RpcEnvironment, |
83b7db02 DM |
1156 | ) -> Result<Value, Error> { |
1157 | ||
2665cef7 | 1158 | let repo = extract_repository_from_value(¶m)?; |
83b7db02 | 1159 | |
cc2ce4a9 | 1160 | let mut client = HttpClient::new(repo.host(), repo.user(), None)?; |
83b7db02 | 1161 | |
d0a03d40 | 1162 | let path = format!("api2/json/admin/datastore/{}/prune", repo.store()); |
83b7db02 | 1163 | |
9fdc3ef4 DM |
1164 | let group = tools::required_string_param(¶m, "group")?; |
1165 | let group = BackupGroup::parse(group)?; | |
1166 | ||
ea7a7ef2 DM |
1167 | param.as_object_mut().unwrap().remove("repository"); |
1168 | param.as_object_mut().unwrap().remove("group"); | |
1169 | ||
1170 | param["backup-type"] = group.backup_type().into(); | |
1171 | param["backup-id"] = group.backup_id().into(); | |
83b7db02 | 1172 | |
e9722f8b | 1173 | let _result = async_main(async move { client.post(&path, Some(param)).await })?; |
83b7db02 | 1174 | |
d0a03d40 DM |
1175 | record_repository(&repo); |
1176 | ||
43a406fd | 1177 | Ok(Value::Null) |
83b7db02 DM |
1178 | } |
1179 | ||
34a816cc DM |
1180 | fn status( |
1181 | param: Value, | |
1182 | _info: &ApiMethod, | |
1183 | _rpcenv: &mut dyn RpcEnvironment, | |
1184 | ) -> Result<Value, Error> { | |
1185 | ||
1186 | let repo = extract_repository_from_value(¶m)?; | |
1187 | ||
1188 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); | |
1189 | ||
cc2ce4a9 | 1190 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
34a816cc DM |
1191 | |
1192 | let path = format!("api2/json/admin/datastore/{}/status", repo.store()); | |
1193 | ||
e9722f8b | 1194 | let result = async_main(async move { client.get(&path, None).await })?; |
34a816cc DM |
1195 | let data = &result["data"]; |
1196 | ||
1197 | record_repository(&repo); | |
1198 | ||
1199 | if output_format == "text" { | |
1200 | let total = data["total"].as_u64().unwrap(); | |
1201 | let used = data["used"].as_u64().unwrap(); | |
1202 | let avail = data["avail"].as_u64().unwrap(); | |
1203 | let roundup = total/200; | |
1204 | ||
1205 | println!( | |
1206 | "total: {} used: {} ({} %) available: {}", | |
1207 | total, | |
1208 | used, | |
1209 | ((used+roundup)*100)/total, | |
1210 | avail, | |
1211 | ); | |
1212 | } else { | |
f6ede796 | 1213 | format_and_print_result(data, &output_format); |
34a816cc DM |
1214 | } |
1215 | ||
1216 | Ok(Value::Null) | |
1217 | } | |
1218 | ||
5a2df000 | 1219 | // like get, but simply ignore errors and return Null instead |
e9722f8b | 1220 | async fn try_get(repo: &BackupRepository, url: &str) -> Value { |
024f11bb | 1221 | |
cc2ce4a9 | 1222 | let client = match HttpClient::new(repo.host(), repo.user(), None) { |
45cdce06 DM |
1223 | Ok(v) => v, |
1224 | _ => return Value::Null, | |
1225 | }; | |
b2388518 | 1226 | |
e9722f8b | 1227 | let mut resp = match client.get(url, None).await { |
b2388518 DM |
1228 | Ok(v) => v, |
1229 | _ => return Value::Null, | |
1230 | }; | |
1231 | ||
1232 | if let Some(map) = resp.as_object_mut() { | |
1233 | if let Some(data) = map.remove("data") { | |
1234 | return data; | |
1235 | } | |
1236 | } | |
1237 | Value::Null | |
1238 | } | |
1239 | ||
b2388518 | 1240 | fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
e9722f8b WB |
1241 | async_main(async { complete_backup_group_do(param).await }) |
1242 | } | |
1243 | ||
1244 | async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> { | |
024f11bb | 1245 | |
b2388518 DM |
1246 | let mut result = vec![]; |
1247 | ||
2665cef7 | 1248 | let repo = match extract_repository_from_map(param) { |
b2388518 | 1249 | Some(v) => v, |
024f11bb DM |
1250 | _ => return result, |
1251 | }; | |
1252 | ||
b2388518 DM |
1253 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
1254 | ||
e9722f8b | 1255 | let data = try_get(&repo, &path).await; |
b2388518 DM |
1256 | |
1257 | if let Some(list) = data.as_array() { | |
024f11bb | 1258 | for item in list { |
98f0b972 DM |
1259 | if let (Some(backup_id), Some(backup_type)) = |
1260 | (item["backup-id"].as_str(), item["backup-type"].as_str()) | |
1261 | { | |
1262 | result.push(format!("{}/{}", backup_type, backup_id)); | |
024f11bb DM |
1263 | } |
1264 | } | |
1265 | } | |
1266 | ||
1267 | result | |
1268 | } | |
1269 | ||
b2388518 | 1270 | fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
e9722f8b WB |
1271 | async_main(async { complete_group_or_snapshot_do(arg, param).await }) |
1272 | } | |
1273 | ||
1274 | async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
b2388518 | 1275 | |
b2388518 | 1276 | if arg.matches('/').count() < 2 { |
e9722f8b | 1277 | let groups = complete_backup_group_do(param).await; |
543a260f | 1278 | let mut result = vec![]; |
b2388518 DM |
1279 | for group in groups { |
1280 | result.push(group.to_string()); | |
1281 | result.push(format!("{}/", group)); | |
1282 | } | |
1283 | return result; | |
1284 | } | |
1285 | ||
e9722f8b | 1286 | complete_backup_snapshot_do(param).await |
543a260f | 1287 | } |
b2388518 | 1288 | |
3fb53e07 | 1289 | fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
e9722f8b WB |
1290 | async_main(async { complete_backup_snapshot_do(param).await }) |
1291 | } | |
1292 | ||
1293 | async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> { | |
543a260f DM |
1294 | |
1295 | let mut result = vec![]; | |
1296 | ||
1297 | let repo = match extract_repository_from_map(param) { | |
1298 | Some(v) => v, | |
1299 | _ => return result, | |
1300 | }; | |
1301 | ||
1302 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); | |
b2388518 | 1303 | |
e9722f8b | 1304 | let data = try_get(&repo, &path).await; |
b2388518 DM |
1305 | |
1306 | if let Some(list) = data.as_array() { | |
1307 | for item in list { | |
1308 | if let (Some(backup_id), Some(backup_type), Some(backup_time)) = | |
1309 | (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64()) | |
1310 | { | |
1311 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time); | |
1312 | result.push(snapshot.relative_path().to_str().unwrap().to_owned()); | |
1313 | } | |
1314 | } | |
1315 | } | |
1316 | ||
1317 | result | |
1318 | } | |
1319 | ||
45db6f89 | 1320 | fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
e9722f8b WB |
1321 | async_main(async { complete_server_file_name_do(param).await }) |
1322 | } | |
1323 | ||
1324 | async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> { | |
08dc340a DM |
1325 | |
1326 | let mut result = vec![]; | |
1327 | ||
2665cef7 | 1328 | let repo = match extract_repository_from_map(param) { |
08dc340a DM |
1329 | Some(v) => v, |
1330 | _ => return result, | |
1331 | }; | |
1332 | ||
1333 | let snapshot = match param.get("snapshot") { | |
1334 | Some(path) => { | |
1335 | match BackupDir::parse(path) { | |
1336 | Ok(v) => v, | |
1337 | _ => return result, | |
1338 | } | |
1339 | } | |
1340 | _ => return result, | |
1341 | }; | |
1342 | ||
1343 | let query = tools::json_object_to_query(json!({ | |
1344 | "backup-type": snapshot.group().backup_type(), | |
1345 | "backup-id": snapshot.group().backup_id(), | |
1346 | "backup-time": snapshot.backup_time().timestamp(), | |
1347 | })).unwrap(); | |
1348 | ||
1349 | let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query); | |
1350 | ||
e9722f8b | 1351 | let data = try_get(&repo, &path).await; |
08dc340a DM |
1352 | |
1353 | if let Some(list) = data.as_array() { | |
1354 | for item in list { | |
c4f025eb | 1355 | if let Some(filename) = item["filename"].as_str() { |
08dc340a DM |
1356 | result.push(filename.to_owned()); |
1357 | } | |
1358 | } | |
1359 | } | |
1360 | ||
45db6f89 DM |
1361 | result |
1362 | } | |
1363 | ||
1364 | fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
52c171e4 | 1365 | complete_server_file_name(arg, param) |
e9722f8b WB |
1366 | .iter() |
1367 | .map(|v| strip_server_file_expenstion(&v)) | |
1368 | .collect() | |
08dc340a DM |
1369 | } |
1370 | ||
49811347 DM |
1371 | fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
1372 | ||
1373 | let mut result = vec![]; | |
1374 | ||
1375 | let mut size = 64; | |
1376 | loop { | |
1377 | result.push(size.to_string()); | |
1378 | size = size * 2; | |
1379 | if size > 4096 { break; } | |
1380 | } | |
1381 | ||
1382 | result | |
1383 | } | |
1384 | ||
826f309b | 1385 | fn get_encryption_key_password() -> Result<Vec<u8>, Error> { |
ff5d3707 | 1386 | |
f2401311 DM |
1387 | // fixme: implement other input methods |
1388 | ||
1389 | use std::env::VarError::*; | |
1390 | match std::env::var("PBS_ENCRYPTION_PASSWORD") { | |
826f309b | 1391 | Ok(p) => return Ok(p.as_bytes().to_vec()), |
f2401311 DM |
1392 | Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"), |
1393 | Err(NotPresent) => { | |
1394 | // Try another method | |
1395 | } | |
1396 | } | |
1397 | ||
1398 | // If we're on a TTY, query the user for a password | |
1399 | if crate::tools::tty::stdin_isatty() { | |
826f309b | 1400 | return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?); |
f2401311 DM |
1401 | } |
1402 | ||
1403 | bail!("no password input mechanism available"); | |
1404 | } | |
1405 | ||
ac716234 DM |
1406 | fn key_create( |
1407 | param: Value, | |
1408 | _info: &ApiMethod, | |
1409 | _rpcenv: &mut dyn RpcEnvironment, | |
1410 | ) -> Result<Value, Error> { | |
1411 | ||
9b06db45 DM |
1412 | let path = tools::required_string_param(¶m, "path")?; |
1413 | let path = PathBuf::from(path); | |
ac716234 | 1414 | |
181f097a | 1415 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
ac716234 DM |
1416 | |
1417 | let key = proxmox::sys::linux::random_data(32)?; | |
1418 | ||
181f097a DM |
1419 | if kdf == "scrypt" { |
1420 | // always read passphrase from tty | |
1421 | if !crate::tools::tty::stdin_isatty() { | |
1422 | bail!("unable to read passphrase - no tty"); | |
1423 | } | |
ac716234 | 1424 | |
181f097a DM |
1425 | let password = crate::tools::tty::read_password("Encryption Key Password: ")?; |
1426 | ||
ab44acff | 1427 | let key_config = encrypt_key_with_passphrase(&key, &password)?; |
37c5a175 | 1428 | |
ab44acff | 1429 | store_key_config(&path, false, key_config)?; |
181f097a DM |
1430 | |
1431 | Ok(Value::Null) | |
1432 | } else if kdf == "none" { | |
1433 | let created = Local.timestamp(Local::now().timestamp(), 0); | |
1434 | ||
1435 | store_key_config(&path, false, KeyConfig { | |
1436 | kdf: None, | |
1437 | created, | |
ab44acff | 1438 | modified: created, |
181f097a DM |
1439 | data: key, |
1440 | })?; | |
1441 | ||
1442 | Ok(Value::Null) | |
1443 | } else { | |
1444 | unreachable!(); | |
1445 | } | |
ac716234 DM |
1446 | } |
1447 | ||
9f46c7de DM |
1448 | fn master_pubkey_path() -> Result<PathBuf, Error> { |
1449 | let base = BaseDirectories::with_prefix("proxmox-backup")?; | |
1450 | ||
1451 | // usually $HOME/.config/proxmox-backup/master-public.pem | |
1452 | let path = base.place_config_file("master-public.pem")?; | |
1453 | ||
1454 | Ok(path) | |
1455 | } | |
1456 | ||
3ea8bfc9 DM |
1457 | fn key_import_master_pubkey( |
1458 | param: Value, | |
1459 | _info: &ApiMethod, | |
1460 | _rpcenv: &mut dyn RpcEnvironment, | |
1461 | ) -> Result<Value, Error> { | |
1462 | ||
1463 | let path = tools::required_string_param(¶m, "path")?; | |
1464 | let path = PathBuf::from(path); | |
1465 | ||
e18a6c9e | 1466 | let pem_data = file_get_contents(&path)?; |
3ea8bfc9 DM |
1467 | |
1468 | if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) { | |
1469 | bail!("Unable to decode PEM data - {}", err); | |
1470 | } | |
1471 | ||
9f46c7de | 1472 | let target_path = master_pubkey_path()?; |
3ea8bfc9 | 1473 | |
e18a6c9e | 1474 | file_set_contents(&target_path, &pem_data, None)?; |
3ea8bfc9 DM |
1475 | |
1476 | println!("Imported public master key to {:?}", target_path); | |
1477 | ||
1478 | Ok(Value::Null) | |
1479 | } | |
1480 | ||
37c5a175 DM |
1481 | fn key_create_master_key( |
1482 | _param: Value, | |
1483 | _info: &ApiMethod, | |
1484 | _rpcenv: &mut dyn RpcEnvironment, | |
1485 | ) -> Result<Value, Error> { | |
1486 | ||
1487 | // we need a TTY to query the new password | |
1488 | if !crate::tools::tty::stdin_isatty() { | |
1489 | bail!("unable to create master key - no tty"); | |
1490 | } | |
1491 | ||
1492 | let rsa = openssl::rsa::Rsa::generate(4096)?; | |
1493 | let pkey = openssl::pkey::PKey::from_rsa(rsa)?; | |
1494 | ||
1495 | let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?; | |
1496 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
1497 | ||
1498 | if new_pw != verify_pw { | |
1499 | bail!("Password verification fail!"); | |
1500 | } | |
1501 | ||
1502 | if new_pw.len() < 5 { | |
1503 | bail!("Password is too short!"); | |
1504 | } | |
1505 | ||
1506 | let pub_key: Vec<u8> = pkey.public_key_to_pem()?; | |
1507 | let filename_pub = "master-public.pem"; | |
1508 | println!("Writing public master key to {}", filename_pub); | |
e18a6c9e | 1509 | file_set_contents(filename_pub, pub_key.as_slice(), None)?; |
37c5a175 DM |
1510 | |
1511 | let cipher = openssl::symm::Cipher::aes_256_cbc(); | |
1512 | let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?; | |
1513 | ||
1514 | let filename_priv = "master-private.pem"; | |
1515 | println!("Writing private master key to {}", filename_priv); | |
e18a6c9e | 1516 | file_set_contents(filename_priv, priv_key.as_slice(), None)?; |
37c5a175 DM |
1517 | |
1518 | Ok(Value::Null) | |
1519 | } | |
ac716234 DM |
1520 | |
1521 | fn key_change_passphrase( | |
1522 | param: Value, | |
1523 | _info: &ApiMethod, | |
1524 | _rpcenv: &mut dyn RpcEnvironment, | |
1525 | ) -> Result<Value, Error> { | |
1526 | ||
9b06db45 DM |
1527 | let path = tools::required_string_param(¶m, "path")?; |
1528 | let path = PathBuf::from(path); | |
ac716234 | 1529 | |
181f097a DM |
1530 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
1531 | ||
ac716234 DM |
1532 | // we need a TTY to query the new password |
1533 | if !crate::tools::tty::stdin_isatty() { | |
1534 | bail!("unable to change passphrase - no tty"); | |
1535 | } | |
1536 | ||
a8f10f84 | 1537 | let (key, created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
ac716234 | 1538 | |
181f097a | 1539 | if kdf == "scrypt" { |
ac716234 | 1540 | |
181f097a DM |
1541 | let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?; |
1542 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
ac716234 | 1543 | |
181f097a DM |
1544 | if new_pw != verify_pw { |
1545 | bail!("Password verification fail!"); | |
1546 | } | |
1547 | ||
1548 | if new_pw.len() < 5 { | |
1549 | bail!("Password is too short!"); | |
1550 | } | |
ac716234 | 1551 | |
ab44acff DM |
1552 | let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?; |
1553 | new_key_config.created = created; // keep original value | |
1554 | ||
1555 | store_key_config(&path, true, new_key_config)?; | |
ac716234 | 1556 | |
181f097a DM |
1557 | Ok(Value::Null) |
1558 | } else if kdf == "none" { | |
ab44acff | 1559 | let modified = Local.timestamp(Local::now().timestamp(), 0); |
181f097a DM |
1560 | |
1561 | store_key_config(&path, true, KeyConfig { | |
1562 | kdf: None, | |
ab44acff DM |
1563 | created, // keep original value |
1564 | modified, | |
6d0983db | 1565 | data: key.to_vec(), |
181f097a DM |
1566 | })?; |
1567 | ||
1568 | Ok(Value::Null) | |
1569 | } else { | |
1570 | unreachable!(); | |
1571 | } | |
f2401311 DM |
1572 | } |
1573 | ||
1574 | fn key_mgmt_cli() -> CliCommandMap { | |
1575 | ||
181f097a DM |
1576 | let kdf_schema: Arc<Schema> = Arc::new( |
1577 | StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.") | |
1578 | .format(Arc::new(ApiStringFormat::Enum(&["scrypt", "none"]))) | |
1579 | .default("scrypt") | |
1580 | .into() | |
1581 | ); | |
1582 | ||
f2401311 DM |
1583 | let key_create_cmd_def = CliCommand::new( |
1584 | ApiMethod::new( | |
1585 | key_create, | |
1586 | ObjectSchema::new("Create a new encryption key.") | |
9b06db45 | 1587 | .required("path", StringSchema::new("File system path.")) |
181f097a | 1588 | .optional("kdf", kdf_schema.clone()) |
f2401311 | 1589 | )) |
9b06db45 DM |
1590 | .arg_param(vec!["path"]) |
1591 | .completion_cb("path", tools::complete_file_name); | |
f2401311 | 1592 | |
ac716234 DM |
1593 | let key_change_passphrase_cmd_def = CliCommand::new( |
1594 | ApiMethod::new( | |
1595 | key_change_passphrase, | |
1596 | ObjectSchema::new("Change the passphrase required to decrypt the key.") | |
9b06db45 | 1597 | .required("path", StringSchema::new("File system path.")) |
181f097a | 1598 | .optional("kdf", kdf_schema.clone()) |
9b06db45 DM |
1599 | )) |
1600 | .arg_param(vec!["path"]) | |
1601 | .completion_cb("path", tools::complete_file_name); | |
ac716234 | 1602 | |
37c5a175 DM |
1603 | let key_create_master_key_cmd_def = CliCommand::new( |
1604 | ApiMethod::new( | |
1605 | key_create_master_key, | |
1606 | ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.") | |
1607 | )); | |
1608 | ||
3ea8bfc9 DM |
1609 | let key_import_master_pubkey_cmd_def = CliCommand::new( |
1610 | ApiMethod::new( | |
1611 | key_import_master_pubkey, | |
1612 | ObjectSchema::new("Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.") | |
1613 | .required("path", StringSchema::new("File system path.")) | |
1614 | )) | |
1615 | .arg_param(vec!["path"]) | |
1616 | .completion_cb("path", tools::complete_file_name); | |
1617 | ||
f2401311 | 1618 | let cmd_def = CliCommandMap::new() |
ac716234 | 1619 | .insert("create".to_owned(), key_create_cmd_def.into()) |
37c5a175 | 1620 | .insert("create-master-key".to_owned(), key_create_master_key_cmd_def.into()) |
3ea8bfc9 | 1621 | .insert("import-master-pubkey".to_owned(), key_import_master_pubkey_cmd_def.into()) |
ac716234 | 1622 | .insert("change-passphrase".to_owned(), key_change_passphrase_cmd_def.into()); |
f2401311 DM |
1623 | |
1624 | cmd_def | |
1625 | } | |
1626 | ||
70235f72 CE |
1627 | |
1628 | fn mount( | |
1629 | param: Value, | |
1630 | _info: &ApiMethod, | |
1631 | _rpcenv: &mut dyn RpcEnvironment, | |
1632 | ) -> Result<Value, Error> { | |
1633 | let verbose = param["verbose"].as_bool().unwrap_or(false); | |
1634 | if verbose { | |
1635 | // This will stay in foreground with debug output enabled as None is | |
1636 | // passed for the RawFd. | |
1637 | return async_main(mount_do(param, None)); | |
1638 | } | |
1639 | ||
1640 | // Process should be deamonized. | |
1641 | // Make sure to fork before the async runtime is instantiated to avoid troubles. | |
1642 | let pipe = pipe()?; | |
1643 | match fork() { | |
1644 | Ok(ForkResult::Parent { child: _, .. }) => { | |
1645 | nix::unistd::close(pipe.1).unwrap(); | |
1646 | // Blocks the parent process until we are ready to go in the child | |
1647 | let _res = nix::unistd::read(pipe.0, &mut [0]).unwrap(); | |
1648 | Ok(Value::Null) | |
1649 | } | |
1650 | Ok(ForkResult::Child) => { | |
1651 | nix::unistd::close(pipe.0).unwrap(); | |
1652 | nix::unistd::setsid().unwrap(); | |
1653 | async_main(mount_do(param, Some(pipe.1))) | |
1654 | } | |
1655 | Err(_) => bail!("failed to daemonize process"), | |
1656 | } | |
1657 | } | |
1658 | ||
1659 | async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> { | |
1660 | let repo = extract_repository_from_value(¶m)?; | |
1661 | let archive_name = tools::required_string_param(¶m, "archive-name")?; | |
1662 | let target = tools::required_string_param(¶m, "target")?; | |
1663 | let client = HttpClient::new(repo.host(), repo.user(), None)?; | |
1664 | ||
1665 | record_repository(&repo); | |
1666 | ||
1667 | let path = tools::required_string_param(¶m, "snapshot")?; | |
1668 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { | |
1669 | let group = BackupGroup::parse(path)?; | |
1670 | ||
1671 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); | |
1672 | let result = client.get(&path, Some(json!({ | |
1673 | "backup-type": group.backup_type(), | |
1674 | "backup-id": group.backup_id(), | |
1675 | }))).await?; | |
1676 | ||
1677 | let list = result["data"].as_array().unwrap(); | |
1678 | if list.len() == 0 { | |
1679 | bail!("backup group '{}' does not contain any snapshots:", path); | |
1680 | } | |
1681 | ||
1682 | let epoch = list[0]["backup-time"].as_i64().unwrap(); | |
1683 | let backup_time = Utc.timestamp(epoch, 0); | |
1684 | (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time) | |
1685 | } else { | |
1686 | let snapshot = BackupDir::parse(path)?; | |
1687 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) | |
1688 | }; | |
1689 | ||
1690 | let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p)); | |
1691 | let crypt_config = match keyfile { | |
1692 | None => None, | |
1693 | Some(path) => { | |
a8f10f84 | 1694 | let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
70235f72 CE |
1695 | Some(Arc::new(CryptConfig::new(key)?)) |
1696 | } | |
1697 | }; | |
1698 | ||
1699 | let server_archive_name = if archive_name.ends_with(".pxar") { | |
1700 | format!("{}.didx", archive_name) | |
1701 | } else { | |
1702 | bail!("Can only mount pxar archives."); | |
1703 | }; | |
1704 | ||
296c50ba DM |
1705 | let client = BackupReader::start( |
1706 | client, | |
1707 | crypt_config.clone(), | |
1708 | repo.store(), | |
1709 | &backup_type, | |
1710 | &backup_id, | |
1711 | backup_time, | |
1712 | true, | |
1713 | ).await?; | |
70235f72 CE |
1714 | |
1715 | let tmpfile = std::fs::OpenOptions::new() | |
1716 | .write(true) | |
1717 | .read(true) | |
1718 | .custom_flags(libc::O_TMPFILE) | |
1719 | .open("/tmp")?; | |
1720 | ||
f06b820a | 1721 | let manifest = client.download_manifest().await?; |
296c50ba | 1722 | |
70235f72 CE |
1723 | if server_archive_name.ends_with(".didx") { |
1724 | let tmpfile = client.download(&server_archive_name, tmpfile).await?; | |
1725 | let index = DynamicIndexReader::new(tmpfile) | |
1726 | .map_err(|err| format_err!("unable to read dynamic index '{}' - {}", archive_name, err))?; | |
1727 | ||
1728 | // Note: do not use values stored in index (not trusted) - instead, computed them again | |
1729 | let (csum, size) = index.compute_csum(); | |
f06b820a | 1730 | manifest.verify_file(&server_archive_name, &csum, size)?; |
70235f72 CE |
1731 | |
1732 | let most_used = index.find_most_used_chunks(8); | |
1733 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
1734 | let reader = BufferedDynamicReader::new(index, chunk_reader); | |
1735 | let decoder = | |
1736 | pxar::Decoder::<Box<dyn pxar::fuse::ReadSeek>, fn(&Path) -> Result<(), Error>>::new( | |
1737 | Box::new(reader), | |
1738 | |_| Ok(()), | |
1739 | )?; | |
1740 | let options = OsStr::new("ro,default_permissions"); | |
1741 | let mut session = pxar::fuse::Session::from_decoder(decoder, &options, pipe.is_none()) | |
1742 | .map_err(|err| format_err!("pxar mount failed: {}", err))?; | |
1743 | ||
1744 | // Mount the session but not call fuse deamonize as this will cause | |
1745 | // issues with the runtime after the fork | |
1746 | let deamonize = false; | |
1747 | session.mount(&Path::new(target), deamonize)?; | |
1748 | ||
1749 | if let Some(pipe) = pipe { | |
1750 | nix::unistd::chdir(Path::new("/")).unwrap(); | |
1751 | // Finish creation of deamon by redirecting filedescriptors. | |
1752 | let nullfd = nix::fcntl::open( | |
1753 | "/dev/null", | |
1754 | nix::fcntl::OFlag::O_RDWR, | |
1755 | nix::sys::stat::Mode::empty(), | |
1756 | ).unwrap(); | |
1757 | nix::unistd::dup2(nullfd, 0).unwrap(); | |
1758 | nix::unistd::dup2(nullfd, 1).unwrap(); | |
1759 | nix::unistd::dup2(nullfd, 2).unwrap(); | |
1760 | if nullfd > 2 { | |
1761 | nix::unistd::close(nullfd).unwrap(); | |
1762 | } | |
1763 | // Signal the parent process that we are done with the setup and it can | |
1764 | // terminate. | |
1765 | nix::unistd::write(pipe, &mut [0u8])?; | |
1766 | nix::unistd::close(pipe).unwrap(); | |
1767 | } | |
1768 | ||
1769 | let multithreaded = true; | |
1770 | session.run_loop(multithreaded)?; | |
1771 | } else { | |
1772 | bail!("unknown archive file extension (expected .pxar)"); | |
1773 | } | |
1774 | ||
1775 | Ok(Value::Null) | |
1776 | } | |
1777 | ||
f2401311 | 1778 | fn main() { |
33d64b81 | 1779 | |
25f1650b DM |
1780 | let backup_source_schema: Arc<Schema> = Arc::new( |
1781 | StringSchema::new("Backup source specification ([<label>:<path>]).") | |
1782 | .format(Arc::new(ApiStringFormat::Pattern(&BACKUPSPEC_REGEX))) | |
1783 | .into() | |
1784 | ); | |
1785 | ||
597a9203 | 1786 | let backup_cmd_def = CliCommand::new( |
ff5d3707 | 1787 | ApiMethod::new( |
bcd879cf | 1788 | create_backup, |
597a9203 | 1789 | ObjectSchema::new("Create (host) backup.") |
ae0be2dd DM |
1790 | .required( |
1791 | "backupspec", | |
1792 | ArraySchema::new( | |
74cdb521 | 1793 | "List of backup source specifications ([<label.ext>:<path>] ...)", |
25f1650b | 1794 | backup_source_schema, |
ae0be2dd DM |
1795 | ).min_length(1) |
1796 | ) | |
2665cef7 | 1797 | .optional("repository", REPO_URL_SCHEMA.clone()) |
2eeaacb9 DM |
1798 | .optional( |
1799 | "include-dev", | |
1800 | ArraySchema::new( | |
1801 | "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.", | |
1802 | StringSchema::new("Path to file.").into() | |
1803 | ) | |
1804 | ) | |
6d0983db DM |
1805 | .optional( |
1806 | "keyfile", | |
1807 | StringSchema::new("Path to encryption key. All data will be encrypted using this key.")) | |
219ef0e6 DM |
1808 | .optional( |
1809 | "verbose", | |
1810 | BooleanSchema::new("Verbose output.").default(false)) | |
5b72c9b4 DM |
1811 | .optional( |
1812 | "skip-lost-and-found", | |
1813 | BooleanSchema::new("Skip lost+found directory").default(false)) | |
fba30411 | 1814 | .optional( |
bbf9e7e9 DM |
1815 | "backup-type", |
1816 | BACKUP_TYPE_SCHEMA.clone() | |
1817 | ) | |
1818 | .optional( | |
1819 | "backup-id", | |
1820 | BACKUP_ID_SCHEMA.clone() | |
1821 | ) | |
ca5d0b61 DM |
1822 | .optional( |
1823 | "backup-time", | |
bbf9e7e9 | 1824 | BACKUP_TIME_SCHEMA.clone() |
ca5d0b61 | 1825 | ) |
2d9d143a DM |
1826 | .optional( |
1827 | "chunk-size", | |
1828 | IntegerSchema::new("Chunk size in KB. Must be a power of 2.") | |
1829 | .minimum(64) | |
1830 | .maximum(4096) | |
1831 | .default(4096) | |
1832 | ) | |
ff5d3707 | 1833 | )) |
2665cef7 | 1834 | .arg_param(vec!["backupspec"]) |
d0a03d40 | 1835 | .completion_cb("repository", complete_repository) |
49811347 | 1836 | .completion_cb("backupspec", complete_backup_source) |
6d0983db | 1837 | .completion_cb("keyfile", tools::complete_file_name) |
49811347 | 1838 | .completion_cb("chunk-size", complete_chunk_size); |
f8838fe9 | 1839 | |
ec34f7eb DM |
1840 | let upload_log_cmd_def = CliCommand::new( |
1841 | ApiMethod::new( | |
1842 | upload_log, | |
1843 | ObjectSchema::new("Upload backup log file.") | |
1844 | .required("snapshot", StringSchema::new("Snapshot path.")) | |
1845 | .required("logfile", StringSchema::new("The path to the log file you want to upload.")) | |
1846 | .optional("repository", REPO_URL_SCHEMA.clone()) | |
1847 | .optional( | |
1848 | "keyfile", | |
1849 | StringSchema::new("Path to encryption key. All data will be encrypted using this key.")) | |
1850 | )) | |
1851 | .arg_param(vec!["snapshot", "logfile"]) | |
543a260f | 1852 | .completion_cb("snapshot", complete_backup_snapshot) |
ec34f7eb DM |
1853 | .completion_cb("logfile", tools::complete_file_name) |
1854 | .completion_cb("keyfile", tools::complete_file_name) | |
1855 | .completion_cb("repository", complete_repository); | |
1856 | ||
41c039e1 DM |
1857 | let list_cmd_def = CliCommand::new( |
1858 | ApiMethod::new( | |
812c6f87 DM |
1859 | list_backup_groups, |
1860 | ObjectSchema::new("List backup groups.") | |
2665cef7 | 1861 | .optional("repository", REPO_URL_SCHEMA.clone()) |
34a816cc | 1862 | .optional("output-format", OUTPUT_FORMAT.clone()) |
41c039e1 | 1863 | )) |
d0a03d40 | 1864 | .completion_cb("repository", complete_repository); |
41c039e1 | 1865 | |
184f17af DM |
1866 | let snapshots_cmd_def = CliCommand::new( |
1867 | ApiMethod::new( | |
1868 | list_snapshots, | |
1869 | ObjectSchema::new("List backup snapshots.") | |
15c847f1 | 1870 | .optional("group", StringSchema::new("Backup group.")) |
2665cef7 | 1871 | .optional("repository", REPO_URL_SCHEMA.clone()) |
34a816cc | 1872 | .optional("output-format", OUTPUT_FORMAT.clone()) |
184f17af | 1873 | )) |
2665cef7 | 1874 | .arg_param(vec!["group"]) |
024f11bb | 1875 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 1876 | .completion_cb("repository", complete_repository); |
184f17af | 1877 | |
6f62c924 DM |
1878 | let forget_cmd_def = CliCommand::new( |
1879 | ApiMethod::new( | |
1880 | forget_snapshots, | |
1881 | ObjectSchema::new("Forget (remove) backup snapshots.") | |
6f62c924 | 1882 | .required("snapshot", StringSchema::new("Snapshot path.")) |
2665cef7 | 1883 | .optional("repository", REPO_URL_SCHEMA.clone()) |
6f62c924 | 1884 | )) |
2665cef7 | 1885 | .arg_param(vec!["snapshot"]) |
b2388518 | 1886 | .completion_cb("repository", complete_repository) |
543a260f | 1887 | .completion_cb("snapshot", complete_backup_snapshot); |
6f62c924 | 1888 | |
8cc0d6af DM |
1889 | let garbage_collect_cmd_def = CliCommand::new( |
1890 | ApiMethod::new( | |
1891 | start_garbage_collection, | |
1892 | ObjectSchema::new("Start garbage collection for a specific repository.") | |
2665cef7 | 1893 | .optional("repository", REPO_URL_SCHEMA.clone()) |
8cc0d6af | 1894 | )) |
d0a03d40 | 1895 | .completion_cb("repository", complete_repository); |
8cc0d6af | 1896 | |
9f912493 DM |
1897 | let restore_cmd_def = CliCommand::new( |
1898 | ApiMethod::new( | |
1899 | restore, | |
1900 | ObjectSchema::new("Restore backup repository.") | |
d5c34d98 DM |
1901 | .required("snapshot", StringSchema::new("Group/Snapshot path.")) |
1902 | .required("archive-name", StringSchema::new("Backup archive name.")) | |
bf125261 DM |
1903 | .required("target", StringSchema::new(r###"Target directory path. Use '-' to write to stdandard output. |
1904 | ||
1905 | We do not extraxt '.pxar' archives when writing to stdandard output. | |
1906 | ||
1907 | "### | |
1908 | )) | |
46d5aa0a DM |
1909 | .optional( |
1910 | "allow-existing-dirs", | |
1911 | BooleanSchema::new("Do not fail if directories already exists.").default(false)) | |
2665cef7 | 1912 | .optional("repository", REPO_URL_SCHEMA.clone()) |
86eda3eb DM |
1913 | .optional("keyfile", StringSchema::new("Path to encryption key.")) |
1914 | .optional( | |
1915 | "verbose", | |
1916 | BooleanSchema::new("Verbose output.").default(false) | |
1917 | ) | |
9f912493 | 1918 | )) |
2665cef7 | 1919 | .arg_param(vec!["snapshot", "archive-name", "target"]) |
b2388518 | 1920 | .completion_cb("repository", complete_repository) |
08dc340a DM |
1921 | .completion_cb("snapshot", complete_group_or_snapshot) |
1922 | .completion_cb("archive-name", complete_archive_name) | |
1923 | .completion_cb("target", tools::complete_file_name); | |
9f912493 | 1924 | |
52c171e4 DM |
1925 | let files_cmd_def = CliCommand::new( |
1926 | ApiMethod::new( | |
1927 | list_snapshot_files, | |
1928 | ObjectSchema::new("List snapshot files.") | |
1929 | .required("snapshot", StringSchema::new("Snapshot path.")) | |
cec17a3e | 1930 | .optional("repository", REPO_URL_SCHEMA.clone()) |
52c171e4 DM |
1931 | .optional("output-format", OUTPUT_FORMAT.clone()) |
1932 | )) | |
1933 | .arg_param(vec!["snapshot"]) | |
1934 | .completion_cb("repository", complete_repository) | |
543a260f | 1935 | .completion_cb("snapshot", complete_backup_snapshot); |
52c171e4 | 1936 | |
9049a8cf DM |
1937 | let catalog_cmd_def = CliCommand::new( |
1938 | ApiMethod::new( | |
1939 | dump_catalog, | |
1940 | ObjectSchema::new("Dump catalog.") | |
1941 | .required("snapshot", StringSchema::new("Snapshot path.")) | |
1942 | .optional("repository", REPO_URL_SCHEMA.clone()) | |
1943 | )) | |
1944 | .arg_param(vec!["snapshot"]) | |
1945 | .completion_cb("repository", complete_repository) | |
1946 | .completion_cb("snapshot", complete_backup_snapshot); | |
1947 | ||
83b7db02 DM |
1948 | let prune_cmd_def = CliCommand::new( |
1949 | ApiMethod::new( | |
1950 | prune, | |
1951 | proxmox_backup::api2::admin::datastore::add_common_prune_prameters( | |
1952 | ObjectSchema::new("Prune backup repository.") | |
9fdc3ef4 | 1953 | .required("group", StringSchema::new("Backup group.")) |
2665cef7 | 1954 | .optional("repository", REPO_URL_SCHEMA.clone()) |
83b7db02 DM |
1955 | ) |
1956 | )) | |
9fdc3ef4 DM |
1957 | .arg_param(vec!["group"]) |
1958 | .completion_cb("group", complete_backup_group) | |
d0a03d40 | 1959 | .completion_cb("repository", complete_repository); |
9f912493 | 1960 | |
34a816cc DM |
1961 | let status_cmd_def = CliCommand::new( |
1962 | ApiMethod::new( | |
1963 | status, | |
1964 | ObjectSchema::new("Get repository status.") | |
1965 | .optional("repository", REPO_URL_SCHEMA.clone()) | |
1966 | .optional("output-format", OUTPUT_FORMAT.clone()) | |
1967 | )) | |
1968 | .completion_cb("repository", complete_repository); | |
1969 | ||
e240d8be DM |
1970 | let login_cmd_def = CliCommand::new( |
1971 | ApiMethod::new( | |
1972 | api_login, | |
1973 | ObjectSchema::new("Try to login. If successful, store ticket.") | |
1974 | .optional("repository", REPO_URL_SCHEMA.clone()) | |
1975 | )) | |
1976 | .completion_cb("repository", complete_repository); | |
1977 | ||
1978 | let logout_cmd_def = CliCommand::new( | |
1979 | ApiMethod::new( | |
1980 | api_logout, | |
1981 | ObjectSchema::new("Logout (delete stored ticket).") | |
1982 | .optional("repository", REPO_URL_SCHEMA.clone()) | |
1983 | )) | |
1984 | .completion_cb("repository", complete_repository); | |
32efac1c | 1985 | |
70235f72 CE |
1986 | let mount_cmd_def = CliCommand::new( |
1987 | ApiMethod::new( | |
1988 | mount, | |
1989 | ObjectSchema::new("Mount pxar archive.") | |
1990 | .required("snapshot", StringSchema::new("Group/Snapshot path.")) | |
1991 | .required("archive-name", StringSchema::new("Backup archive name.")) | |
1992 | .required("target", StringSchema::new("Target directory path.")) | |
1993 | .optional("repository", REPO_URL_SCHEMA.clone()) | |
1994 | .optional("keyfile", StringSchema::new("Path to encryption key.")) | |
1995 | .optional("verbose", BooleanSchema::new("Verbose output.").default(false)) | |
1996 | )) | |
1997 | .arg_param(vec!["snapshot", "archive-name", "target"]) | |
1998 | .completion_cb("repository", complete_repository) | |
1999 | .completion_cb("snapshot", complete_group_or_snapshot) | |
2000 | .completion_cb("archive-name", complete_archive_name) | |
2001 | .completion_cb("target", tools::complete_file_name); | |
e240d8be | 2002 | |
41c039e1 | 2003 | let cmd_def = CliCommandMap::new() |
597a9203 | 2004 | .insert("backup".to_owned(), backup_cmd_def.into()) |
ec34f7eb | 2005 | .insert("upload-log".to_owned(), upload_log_cmd_def.into()) |
6f62c924 | 2006 | .insert("forget".to_owned(), forget_cmd_def.into()) |
9049a8cf | 2007 | .insert("catalog".to_owned(), catalog_cmd_def.into()) |
8cc0d6af | 2008 | .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into()) |
83b7db02 | 2009 | .insert("list".to_owned(), list_cmd_def.into()) |
e240d8be DM |
2010 | .insert("login".to_owned(), login_cmd_def.into()) |
2011 | .insert("logout".to_owned(), logout_cmd_def.into()) | |
184f17af | 2012 | .insert("prune".to_owned(), prune_cmd_def.into()) |
9f912493 | 2013 | .insert("restore".to_owned(), restore_cmd_def.into()) |
f2401311 | 2014 | .insert("snapshots".to_owned(), snapshots_cmd_def.into()) |
52c171e4 | 2015 | .insert("files".to_owned(), files_cmd_def.into()) |
34a816cc | 2016 | .insert("status".to_owned(), status_cmd_def.into()) |
70235f72 CE |
2017 | .insert("key".to_owned(), key_mgmt_cli().into()) |
2018 | .insert("mount".to_owned(), mount_cmd_def.into()); | |
a914a774 | 2019 | |
e9722f8b WB |
2020 | run_cli_command(cmd_def.into()); |
2021 | } | |
496a6784 | 2022 | |
e9722f8b WB |
2023 | fn async_main<F: Future>(fut: F) -> <F as Future>::Output { |
2024 | let rt = tokio::runtime::Runtime::new().unwrap(); | |
2025 | let ret = rt.block_on(fut); | |
2026 | rt.shutdown_now(); | |
2027 | ret | |
ff5d3707 | 2028 | } |