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