]>
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; |
1c0472e8 | 6 | use chrono::{Local, TimeZone}; |
e9c9409a | 7 | use std::path::{Path, PathBuf}; |
496a6784 | 8 | use std::collections::HashMap; |
ff5d3707 | 9 | |
fe0e04c6 | 10 | use proxmox_backup::tools; |
4de0e142 | 11 | use proxmox_backup::cli::*; |
ef2f2efb | 12 | use proxmox_backup::api_schema::*; |
dc9a007b | 13 | use proxmox_backup::api_schema::router::*; |
151c6ce2 | 14 | use proxmox_backup::client::*; |
247cdbce | 15 | use proxmox_backup::backup::*; |
86eda3eb DM |
16 | use proxmox_backup::pxar; |
17 | ||
fe0e04c6 DM |
18 | //use proxmox_backup::backup::image_index::*; |
19 | //use proxmox_backup::config::datastore; | |
8968258b | 20 | //use proxmox_backup::pxar::encoder::*; |
728797d0 | 21 | //use proxmox_backup::backup::datastore::*; |
23bb8780 | 22 | |
f5f13ebc | 23 | use serde_json::{json, Value}; |
1c0472e8 | 24 | //use hyper::Body; |
33d64b81 | 25 | use std::sync::Arc; |
ae0be2dd | 26 | use regex::Regex; |
d0a03d40 | 27 | use xdg::BaseDirectories; |
ae0be2dd DM |
28 | |
29 | use lazy_static::lazy_static; | |
5a2df000 | 30 | use futures::*; |
c4ff3dce | 31 | use tokio::sync::mpsc; |
ae0be2dd DM |
32 | |
33 | lazy_static! { | |
ec8a9bb9 | 34 | static ref BACKUPSPEC_REGEX: Regex = Regex::new(r"^([a-zA-Z0-9_-]+\.(?:pxar|img|conf)):(.+)$").unwrap(); |
f2401311 DM |
35 | |
36 | static ref REPO_URL_SCHEMA: Arc<Schema> = Arc::new( | |
37 | StringSchema::new("Repository URL.") | |
38 | .format(BACKUP_REPO_URL.clone()) | |
39 | .max_length(256) | |
40 | .into() | |
41 | ); | |
ae0be2dd | 42 | } |
33d64b81 | 43 | |
d0a03d40 DM |
44 | |
45 | fn record_repository(repo: &BackupRepository) { | |
46 | ||
47 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
48 | Ok(v) => v, | |
49 | _ => return, | |
50 | }; | |
51 | ||
52 | // usually $HOME/.cache/proxmox-backup/repo-list | |
53 | let path = match base.place_cache_file("repo-list") { | |
54 | Ok(v) => v, | |
55 | _ => return, | |
56 | }; | |
57 | ||
49cf9f3d | 58 | let mut data = tools::file_get_json(&path, None).unwrap_or(json!({})); |
d0a03d40 DM |
59 | |
60 | let repo = repo.to_string(); | |
61 | ||
62 | data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 }; | |
63 | ||
64 | let mut map = serde_json::map::Map::new(); | |
65 | ||
66 | loop { | |
67 | let mut max_used = 0; | |
68 | let mut max_repo = None; | |
69 | for (repo, count) in data.as_object().unwrap() { | |
70 | if map.contains_key(repo) { continue; } | |
71 | if let Some(count) = count.as_i64() { | |
72 | if count > max_used { | |
73 | max_used = count; | |
74 | max_repo = Some(repo); | |
75 | } | |
76 | } | |
77 | } | |
78 | if let Some(repo) = max_repo { | |
79 | map.insert(repo.to_owned(), json!(max_used)); | |
80 | } else { | |
81 | break; | |
82 | } | |
83 | if map.len() > 10 { // store max. 10 repos | |
84 | break; | |
85 | } | |
86 | } | |
87 | ||
88 | let new_data = json!(map); | |
89 | ||
90 | let _ = tools::file_set_contents(path, new_data.to_string().as_bytes(), None); | |
91 | } | |
92 | ||
49811347 | 93 | fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
d0a03d40 DM |
94 | |
95 | let mut result = vec![]; | |
96 | ||
97 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
98 | Ok(v) => v, | |
99 | _ => return result, | |
100 | }; | |
101 | ||
102 | // usually $HOME/.cache/proxmox-backup/repo-list | |
103 | let path = match base.place_cache_file("repo-list") { | |
104 | Ok(v) => v, | |
105 | _ => return result, | |
106 | }; | |
107 | ||
49cf9f3d | 108 | let data = tools::file_get_json(&path, None).unwrap_or(json!({})); |
d0a03d40 DM |
109 | |
110 | if let Some(map) = data.as_object() { | |
49811347 | 111 | for (repo, _count) in map { |
d0a03d40 DM |
112 | result.push(repo.to_owned()); |
113 | } | |
114 | } | |
115 | ||
116 | result | |
117 | } | |
118 | ||
17d6979a | 119 | fn backup_directory<P: AsRef<Path>>( |
c4ff3dce | 120 | client: &BackupClient, |
17d6979a | 121 | dir_path: P, |
247cdbce | 122 | archive_name: &str, |
36898ffc | 123 | chunk_size: Option<usize>, |
eed6db39 | 124 | all_file_systems: bool, |
219ef0e6 | 125 | verbose: bool, |
f98ac774 | 126 | crypt_config: Option<Arc<CryptConfig>>, |
247cdbce | 127 | ) -> Result<(), Error> { |
33d64b81 | 128 | |
c4ff3dce | 129 | let pxar_stream = PxarBackupStream::open(dir_path.as_ref(), all_file_systems, verbose)?; |
36898ffc | 130 | let chunk_stream = ChunkStream::new(pxar_stream, chunk_size); |
ff3d3100 | 131 | |
c4ff3dce | 132 | let (tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks |
5e7a09be | 133 | |
c4ff3dce DM |
134 | let stream = rx |
135 | .map_err(Error::from) | |
136 | .and_then(|x| x); // flatten | |
17d6979a | 137 | |
c4ff3dce DM |
138 | // spawn chunker inside a separate task so that it can run parallel |
139 | tokio::spawn( | |
140 | tx.send_all(chunk_stream.then(|r| Ok(r))) | |
1c0472e8 | 141 | .map_err(|_| {}).map(|_| ()) |
c4ff3dce | 142 | ); |
17d6979a | 143 | |
f98ac774 | 144 | client.upload_stream(archive_name, stream, "dynamic", None, crypt_config).wait()?; |
bcd879cf DM |
145 | |
146 | Ok(()) | |
147 | } | |
148 | ||
6af905c1 DM |
149 | fn backup_image<P: AsRef<Path>>( |
150 | client: &BackupClient, | |
151 | image_path: P, | |
152 | archive_name: &str, | |
153 | image_size: u64, | |
36898ffc | 154 | chunk_size: Option<usize>, |
1c0472e8 | 155 | _verbose: bool, |
f98ac774 | 156 | crypt_config: Option<Arc<CryptConfig>>, |
6af905c1 DM |
157 | ) -> Result<(), Error> { |
158 | ||
6af905c1 DM |
159 | let path = image_path.as_ref().to_owned(); |
160 | ||
161 | let file = tokio::fs::File::open(path).wait()?; | |
162 | ||
163 | let stream = tokio::codec::FramedRead::new(file, tokio::codec::BytesCodec::new()) | |
164 | .map_err(Error::from); | |
165 | ||
36898ffc | 166 | let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024)); |
6af905c1 | 167 | |
f98ac774 | 168 | client.upload_stream(archive_name, stream, "fixed", Some(image_size), crypt_config).wait()?; |
6af905c1 DM |
169 | |
170 | Ok(()) | |
171 | } | |
172 | ||
6899dbfb | 173 | fn strip_server_file_expenstions(list: Vec<String>) -> Vec<String> { |
8e39232a DM |
174 | |
175 | let mut result = vec![]; | |
176 | ||
177 | for file in list.into_iter() { | |
178 | if file.ends_with(".didx") { | |
179 | result.push(file[..file.len()-5].to_owned()); | |
180 | } else if file.ends_with(".fidx") { | |
181 | result.push(file[..file.len()-5].to_owned()); | |
6899dbfb DM |
182 | } else if file.ends_with(".blob") { |
183 | result.push(file[..file.len()-5].to_owned()); | |
8e39232a DM |
184 | } else { |
185 | result.push(file); // should not happen | |
186 | } | |
187 | } | |
188 | ||
189 | result | |
190 | } | |
191 | ||
8968258b | 192 | /* not used: |
6049b71f DM |
193 | fn list_backups( |
194 | param: Value, | |
195 | _info: &ApiMethod, | |
dd5495d6 | 196 | _rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 197 | ) -> Result<Value, Error> { |
41c039e1 | 198 | |
33d64b81 | 199 | let repo_url = tools::required_string_param(¶m, "repository")?; |
edd3c8c6 | 200 | let repo: BackupRepository = repo_url.parse()?; |
41c039e1 | 201 | |
45cdce06 | 202 | let mut client = HttpClient::new(repo.host(), repo.user())?; |
41c039e1 | 203 | |
d0a03d40 | 204 | let path = format!("api2/json/admin/datastore/{}/backups", repo.store()); |
41c039e1 | 205 | |
9e391bb7 | 206 | let result = client.get(&path, None)?; |
41c039e1 | 207 | |
d0a03d40 DM |
208 | record_repository(&repo); |
209 | ||
8c75372b DM |
210 | // fixme: implement and use output formatter instead .. |
211 | let list = result["data"].as_array().unwrap(); | |
212 | ||
213 | for item in list { | |
214 | ||
49dc0740 DM |
215 | let id = item["backup-id"].as_str().unwrap(); |
216 | let btype = item["backup-type"].as_str().unwrap(); | |
217 | let epoch = item["backup-time"].as_i64().unwrap(); | |
e909522f | 218 | |
391d3107 | 219 | let backup_dir = BackupDir::new(btype, id, epoch); |
e909522f DM |
220 | |
221 | let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect(); | |
6899dbfb | 222 | let files = strip_server_file_expenstions(files); |
e909522f | 223 | |
8e39232a DM |
224 | for filename in files { |
225 | let path = backup_dir.relative_path().to_str().unwrap().to_owned(); | |
226 | println!("{} | {}/{}", backup_dir.backup_time().format("%c"), path, filename); | |
8c75372b DM |
227 | } |
228 | } | |
229 | ||
230 | //Ok(result) | |
231 | Ok(Value::Null) | |
41c039e1 | 232 | } |
8968258b | 233 | */ |
41c039e1 | 234 | |
812c6f87 DM |
235 | fn list_backup_groups( |
236 | param: Value, | |
237 | _info: &ApiMethod, | |
dd5495d6 | 238 | _rpcenv: &mut dyn RpcEnvironment, |
812c6f87 DM |
239 | ) -> Result<Value, Error> { |
240 | ||
241 | let repo_url = tools::required_string_param(¶m, "repository")?; | |
edd3c8c6 | 242 | let repo: BackupRepository = repo_url.parse()?; |
812c6f87 | 243 | |
45cdce06 | 244 | let client = HttpClient::new(repo.host(), repo.user())?; |
812c6f87 | 245 | |
d0a03d40 | 246 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
812c6f87 | 247 | |
9e391bb7 | 248 | let mut result = client.get(&path, None).wait()?; |
812c6f87 | 249 | |
d0a03d40 DM |
250 | record_repository(&repo); |
251 | ||
812c6f87 | 252 | // fixme: implement and use output formatter instead .. |
80822b95 DM |
253 | let list = result["data"].as_array_mut().unwrap(); |
254 | ||
255 | list.sort_unstable_by(|a, b| { | |
256 | let a_id = a["backup-id"].as_str().unwrap(); | |
257 | let a_backup_type = a["backup-type"].as_str().unwrap(); | |
258 | let b_id = b["backup-id"].as_str().unwrap(); | |
259 | let b_backup_type = b["backup-type"].as_str().unwrap(); | |
260 | ||
261 | let type_order = a_backup_type.cmp(b_backup_type); | |
262 | if type_order == std::cmp::Ordering::Equal { | |
263 | a_id.cmp(b_id) | |
264 | } else { | |
265 | type_order | |
266 | } | |
267 | }); | |
812c6f87 DM |
268 | |
269 | for item in list { | |
270 | ||
ad20d198 DM |
271 | let id = item["backup-id"].as_str().unwrap(); |
272 | let btype = item["backup-type"].as_str().unwrap(); | |
273 | let epoch = item["last-backup"].as_i64().unwrap(); | |
812c6f87 | 274 | let last_backup = Local.timestamp(epoch, 0); |
ad20d198 | 275 | let backup_count = item["backup-count"].as_u64().unwrap(); |
812c6f87 | 276 | |
1e9a94e5 | 277 | let group = BackupGroup::new(btype, id); |
812c6f87 DM |
278 | |
279 | let path = group.group_path().to_str().unwrap().to_owned(); | |
ad20d198 | 280 | |
8e39232a | 281 | let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect(); |
6899dbfb | 282 | let files = strip_server_file_expenstions(files); |
ad20d198 | 283 | |
80822b95 | 284 | println!("{:20} | {} | {:5} | {}", path, last_backup.format("%c"), |
ad20d198 | 285 | backup_count, tools::join(&files, ' ')); |
812c6f87 DM |
286 | } |
287 | ||
288 | //Ok(result) | |
289 | Ok(Value::Null) | |
290 | } | |
291 | ||
184f17af DM |
292 | fn list_snapshots( |
293 | param: Value, | |
294 | _info: &ApiMethod, | |
dd5495d6 | 295 | _rpcenv: &mut dyn RpcEnvironment, |
184f17af DM |
296 | ) -> Result<Value, Error> { |
297 | ||
298 | let repo_url = tools::required_string_param(¶m, "repository")?; | |
edd3c8c6 | 299 | let repo: BackupRepository = repo_url.parse()?; |
184f17af DM |
300 | |
301 | let path = tools::required_string_param(¶m, "group")?; | |
302 | let group = BackupGroup::parse(path)?; | |
303 | ||
45cdce06 | 304 | let client = HttpClient::new(repo.host(), repo.user())?; |
184f17af | 305 | |
9e391bb7 | 306 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
184f17af | 307 | |
9e391bb7 DM |
308 | let result = client.get(&path, Some(json!({ |
309 | "backup-type": group.backup_type(), | |
310 | "backup-id": group.backup_id(), | |
311 | }))).wait()?; | |
184f17af | 312 | |
d0a03d40 DM |
313 | record_repository(&repo); |
314 | ||
184f17af DM |
315 | // fixme: implement and use output formatter instead .. |
316 | let list = result["data"].as_array().unwrap(); | |
317 | ||
318 | for item in list { | |
319 | ||
320 | let id = item["backup-id"].as_str().unwrap(); | |
321 | let btype = item["backup-type"].as_str().unwrap(); | |
322 | let epoch = item["backup-time"].as_i64().unwrap(); | |
184f17af | 323 | |
391d3107 | 324 | let snapshot = BackupDir::new(btype, id, epoch); |
184f17af DM |
325 | |
326 | let path = snapshot.relative_path().to_str().unwrap().to_owned(); | |
327 | ||
8e39232a | 328 | let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect(); |
6899dbfb | 329 | let files = strip_server_file_expenstions(files); |
184f17af | 330 | |
875fb1c0 | 331 | println!("{} | {} | {}", path, snapshot.backup_time().format("%c"), tools::join(&files, ' ')); |
184f17af DM |
332 | } |
333 | ||
334 | Ok(Value::Null) | |
335 | } | |
336 | ||
6f62c924 DM |
337 | fn forget_snapshots( |
338 | param: Value, | |
339 | _info: &ApiMethod, | |
dd5495d6 | 340 | _rpcenv: &mut dyn RpcEnvironment, |
6f62c924 DM |
341 | ) -> Result<Value, Error> { |
342 | ||
343 | let repo_url = tools::required_string_param(¶m, "repository")?; | |
edd3c8c6 | 344 | let repo: BackupRepository = repo_url.parse()?; |
6f62c924 DM |
345 | |
346 | let path = tools::required_string_param(¶m, "snapshot")?; | |
347 | let snapshot = BackupDir::parse(path)?; | |
348 | ||
45cdce06 | 349 | let mut client = HttpClient::new(repo.host(), repo.user())?; |
6f62c924 | 350 | |
9e391bb7 | 351 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
6f62c924 | 352 | |
9e391bb7 DM |
353 | let result = client.delete(&path, Some(json!({ |
354 | "backup-type": snapshot.group().backup_type(), | |
355 | "backup-id": snapshot.group().backup_id(), | |
356 | "backup-time": snapshot.backup_time().timestamp(), | |
357 | }))).wait()?; | |
6f62c924 | 358 | |
d0a03d40 DM |
359 | record_repository(&repo); |
360 | ||
6f62c924 DM |
361 | Ok(result) |
362 | } | |
363 | ||
8cc0d6af DM |
364 | fn start_garbage_collection( |
365 | param: Value, | |
366 | _info: &ApiMethod, | |
dd5495d6 | 367 | _rpcenv: &mut dyn RpcEnvironment, |
8cc0d6af DM |
368 | ) -> Result<Value, Error> { |
369 | ||
370 | let repo_url = tools::required_string_param(¶m, "repository")?; | |
edd3c8c6 | 371 | let repo: BackupRepository = repo_url.parse()?; |
8cc0d6af | 372 | |
45cdce06 | 373 | let mut client = HttpClient::new(repo.host(), repo.user())?; |
8cc0d6af | 374 | |
d0a03d40 | 375 | let path = format!("api2/json/admin/datastore/{}/gc", repo.store()); |
8cc0d6af | 376 | |
5a2df000 | 377 | let result = client.post(&path, None).wait()?; |
8cc0d6af | 378 | |
d0a03d40 DM |
379 | record_repository(&repo); |
380 | ||
8cc0d6af DM |
381 | Ok(result) |
382 | } | |
33d64b81 | 383 | |
ae0be2dd DM |
384 | fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> { |
385 | ||
386 | if let Some(caps) = BACKUPSPEC_REGEX.captures(value) { | |
387 | return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str())); | |
388 | } | |
389 | bail!("unable to parse directory specification '{}'", value); | |
390 | } | |
391 | ||
6049b71f DM |
392 | fn create_backup( |
393 | param: Value, | |
394 | _info: &ApiMethod, | |
dd5495d6 | 395 | _rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 396 | ) -> Result<Value, Error> { |
ff5d3707 | 397 | |
33d64b81 | 398 | let repo_url = tools::required_string_param(¶m, "repository")?; |
ae0be2dd DM |
399 | |
400 | let backupspec_list = tools::required_array_param(¶m, "backupspec")?; | |
a914a774 | 401 | |
edd3c8c6 | 402 | let repo: BackupRepository = repo_url.parse()?; |
33d64b81 | 403 | |
eed6db39 DM |
404 | let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false); |
405 | ||
219ef0e6 DM |
406 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
407 | ||
36898ffc | 408 | let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize); |
2d9d143a | 409 | |
247cdbce DM |
410 | if let Some(size) = chunk_size_opt { |
411 | verify_chunk_size(size)?; | |
2d9d143a DM |
412 | } |
413 | ||
6d0983db DM |
414 | let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p)); |
415 | ||
fba30411 DM |
416 | let backup_id = param["host-id"].as_str().unwrap_or(&tools::nodename()); |
417 | ||
ae0be2dd | 418 | let mut upload_list = vec![]; |
a914a774 | 419 | |
ec8a9bb9 | 420 | enum BackupType { PXAR, IMAGE, CONFIG }; |
6af905c1 | 421 | |
ae0be2dd DM |
422 | for backupspec in backupspec_list { |
423 | let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?; | |
bcd879cf | 424 | |
eb1804c5 DM |
425 | use std::os::unix::fs::FileTypeExt; |
426 | ||
427 | let metadata = match std::fs::metadata(filename) { | |
428 | Ok(m) => m, | |
ae0be2dd DM |
429 | Err(err) => bail!("unable to access '{}' - {}", filename, err), |
430 | }; | |
eb1804c5 | 431 | let file_type = metadata.file_type(); |
23bb8780 | 432 | |
ec8a9bb9 | 433 | let extension = Path::new(target).extension().map(|s| s.to_str().unwrap()).unwrap(); |
bcd879cf | 434 | |
ec8a9bb9 DM |
435 | match extension { |
436 | "pxar" => { | |
437 | if !file_type.is_dir() { | |
438 | bail!("got unexpected file type (expected directory)"); | |
439 | } | |
440 | upload_list.push((BackupType::PXAR, filename.to_owned(), target.to_owned(), 0)); | |
441 | } | |
442 | "img" => { | |
eb1804c5 | 443 | |
ec8a9bb9 DM |
444 | if !(file_type.is_file() || file_type.is_block_device()) { |
445 | bail!("got unexpected file type (expected file or block device)"); | |
446 | } | |
eb1804c5 | 447 | |
ec8a9bb9 | 448 | let size = tools::image_size(&PathBuf::from(filename))?; |
23bb8780 | 449 | |
ec8a9bb9 | 450 | if size == 0 { bail!("got zero-sized file '{}'", filename); } |
ae0be2dd | 451 | |
ec8a9bb9 DM |
452 | upload_list.push((BackupType::IMAGE, filename.to_owned(), target.to_owned(), size)); |
453 | } | |
454 | "conf" => { | |
455 | if !file_type.is_file() { | |
456 | bail!("got unexpected file type (expected regular file)"); | |
457 | } | |
458 | upload_list.push((BackupType::CONFIG, filename.to_owned(), target.to_owned(), metadata.len())); | |
459 | } | |
460 | _ => { | |
461 | bail!("got unknown archive extension '{}'", extension); | |
462 | } | |
ae0be2dd DM |
463 | } |
464 | } | |
465 | ||
cdebd467 | 466 | let backup_time = Local.timestamp(Local::now().timestamp(), 0); |
ae0be2dd | 467 | |
c4ff3dce | 468 | let client = HttpClient::new(repo.host(), repo.user())?; |
d0a03d40 DM |
469 | record_repository(&repo); |
470 | ||
cdebd467 DM |
471 | println!("Starting backup"); |
472 | println!("Client name: {}", tools::nodename()); | |
473 | println!("Start Time: {}", backup_time.to_rfc3339()); | |
51144821 | 474 | |
bb823140 DM |
475 | let (crypt_config, rsa_encrypted_key) = match keyfile { |
476 | None => (None, None), | |
6d0983db | 477 | Some(path) => { |
bb823140 DM |
478 | let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?; |
479 | ||
480 | let crypt_config = CryptConfig::new(key)?; | |
481 | ||
482 | let path = master_pubkey_path()?; | |
483 | if path.exists() { | |
484 | let pem_data = proxmox_backup::tools::file_get_contents(&path)?; | |
485 | let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?; | |
486 | let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?; | |
487 | (Some(Arc::new(crypt_config)), Some(enc_key)) | |
488 | } else { | |
489 | (Some(Arc::new(crypt_config)), None) | |
490 | } | |
6d0983db DM |
491 | } |
492 | }; | |
f98ac774 | 493 | |
39e60bd6 | 494 | let client = client.start_backup(repo.store(), "host", &backup_id, verbose).wait()?; |
c4ff3dce | 495 | |
6af905c1 DM |
496 | for (backup_type, filename, target, size) in upload_list { |
497 | match backup_type { | |
ec8a9bb9 DM |
498 | BackupType::CONFIG => { |
499 | println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target); | |
9f46c7de | 500 | client.upload_blob_from_file(&filename, &target, crypt_config.clone(), true).wait()?; |
ec8a9bb9 | 501 | } |
6af905c1 DM |
502 | BackupType::PXAR => { |
503 | println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target); | |
f98ac774 DM |
504 | backup_directory( |
505 | &client, | |
506 | &filename, | |
507 | &target, | |
508 | chunk_size_opt, | |
509 | all_file_systems, | |
510 | verbose, | |
511 | crypt_config.clone(), | |
512 | )?; | |
6af905c1 DM |
513 | } |
514 | BackupType::IMAGE => { | |
515 | println!("Upload image '{}' to '{:?}' as {}", filename, repo, target); | |
f98ac774 DM |
516 | backup_image( |
517 | &client, | |
518 | &filename, | |
519 | &target, | |
520 | size, | |
521 | chunk_size_opt, | |
522 | verbose, | |
523 | crypt_config.clone(), | |
524 | )?; | |
6af905c1 DM |
525 | } |
526 | } | |
4818c8b6 DM |
527 | } |
528 | ||
bb823140 DM |
529 | if let Some(rsa_encrypted_key) = rsa_encrypted_key { |
530 | let target = "rsa-encrypted.key"; | |
531 | println!("Upload RSA encoded key to '{:?}' as {}", repo, target); | |
532 | client.upload_blob_from_data(rsa_encrypted_key, target, None, false).wait()?; | |
533 | ||
534 | // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t | |
535 | /* | |
536 | let mut buffer2 = vec![0u8; rsa.size() as usize]; | |
537 | let pem_data = proxmox_backup::tools::file_get_contents("master-private.pem")?; | |
538 | let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?; | |
539 | let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?; | |
540 | println!("TEST {} {:?}", len, buffer2); | |
541 | */ | |
9f46c7de DM |
542 | } |
543 | ||
c4ff3dce DM |
544 | client.finish().wait()?; |
545 | ||
cdebd467 | 546 | let end_time = Local.timestamp(Local::now().timestamp(), 0); |
3ec3ec3f DM |
547 | let elapsed = end_time.signed_duration_since(backup_time); |
548 | println!("Duration: {}", elapsed); | |
549 | ||
cdebd467 | 550 | println!("End Time: {}", end_time.to_rfc3339()); |
3d5c11e5 | 551 | |
ff5d3707 | 552 | Ok(Value::Null) |
f98ea63d DM |
553 | } |
554 | ||
d0a03d40 | 555 | fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
f98ea63d DM |
556 | |
557 | let mut result = vec![]; | |
558 | ||
559 | let data: Vec<&str> = arg.splitn(2, ':').collect(); | |
560 | ||
bff11030 | 561 | if data.len() != 2 { |
8968258b DM |
562 | result.push(String::from("root.pxar:/")); |
563 | result.push(String::from("etc.pxar:/etc")); | |
bff11030 DM |
564 | return result; |
565 | } | |
f98ea63d | 566 | |
496a6784 | 567 | let files = tools::complete_file_name(data[1], param); |
f98ea63d DM |
568 | |
569 | for file in files { | |
570 | result.push(format!("{}:{}", data[0], file)); | |
571 | } | |
572 | ||
573 | result | |
ff5d3707 | 574 | } |
575 | ||
9f912493 DM |
576 | fn restore( |
577 | param: Value, | |
578 | _info: &ApiMethod, | |
dd5495d6 | 579 | _rpcenv: &mut dyn RpcEnvironment, |
9f912493 DM |
580 | ) -> Result<Value, Error> { |
581 | ||
582 | let repo_url = tools::required_string_param(¶m, "repository")?; | |
edd3c8c6 | 583 | let repo: BackupRepository = repo_url.parse()?; |
9f912493 | 584 | |
86eda3eb DM |
585 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
586 | ||
d5c34d98 DM |
587 | let archive_name = tools::required_string_param(¶m, "archive-name")?; |
588 | ||
86eda3eb | 589 | let client = HttpClient::new(repo.host(), repo.user())?; |
d0a03d40 | 590 | |
d0a03d40 | 591 | record_repository(&repo); |
d5c34d98 | 592 | |
9f912493 | 593 | let path = tools::required_string_param(¶m, "snapshot")?; |
9f912493 | 594 | |
86eda3eb | 595 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { |
d5c34d98 | 596 | let group = BackupGroup::parse(path)?; |
9f912493 | 597 | |
9e391bb7 DM |
598 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
599 | let result = client.get(&path, Some(json!({ | |
d5c34d98 DM |
600 | "backup-type": group.backup_type(), |
601 | "backup-id": group.backup_id(), | |
9e391bb7 | 602 | }))).wait()?; |
9f912493 | 603 | |
d5c34d98 DM |
604 | let list = result["data"].as_array().unwrap(); |
605 | if list.len() == 0 { | |
606 | bail!("backup group '{}' does not contain any snapshots:", path); | |
607 | } | |
9f912493 | 608 | |
86eda3eb DM |
609 | let epoch = list[0]["backup-time"].as_i64().unwrap(); |
610 | let backup_time = Local.timestamp(epoch, 0); | |
611 | (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time) | |
d5c34d98 DM |
612 | } else { |
613 | let snapshot = BackupDir::parse(path)?; | |
86eda3eb DM |
614 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) |
615 | }; | |
9f912493 | 616 | |
d5c34d98 | 617 | let target = tools::required_string_param(¶m, "target")?; |
2ae7d196 | 618 | |
86eda3eb | 619 | let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p)); |
2ae7d196 | 620 | |
86eda3eb DM |
621 | let crypt_config = match keyfile { |
622 | None => None, | |
623 | Some(path) => { | |
624 | let (key, _) = load_and_decrtypt_key(&path, get_encryption_key_password)?; | |
625 | Some(Arc::new(CryptConfig::new(key)?)) | |
626 | } | |
627 | }; | |
d5c34d98 | 628 | |
afb4cd28 DM |
629 | let server_archive_name = if archive_name.ends_with(".pxar") { |
630 | format!("{}.didx", archive_name) | |
631 | } else if archive_name.ends_with(".img") { | |
632 | format!("{}.fidx", archive_name) | |
633 | } else { | |
f8100e96 | 634 | format!("{}.blob", archive_name) |
afb4cd28 | 635 | }; |
9f912493 | 636 | |
86eda3eb DM |
637 | let client = client.start_backup_reader(repo.store(), &backup_type, &backup_id, backup_time, true).wait()?; |
638 | ||
639 | use std::os::unix::fs::OpenOptionsExt; | |
640 | ||
641 | let tmpfile = std::fs::OpenOptions::new() | |
642 | .write(true) | |
643 | .read(true) | |
644 | .custom_flags(libc::O_TMPFILE) | |
645 | .open("/tmp")?; | |
646 | ||
f8100e96 DM |
647 | if server_archive_name.ends_with(".blob") { |
648 | ||
649 | let writer = Vec::with_capacity(1024*1024); | |
650 | let blob_data = client.download(&server_archive_name, writer).wait()?; | |
651 | let blob = DataBlob::from_raw(blob_data)?; | |
652 | blob.verify_crc()?; | |
653 | ||
654 | let raw_data = match crypt_config { | |
655 | Some(ref crypt_config) => blob.decode(Some(crypt_config))?, | |
656 | None => blob.decode(None)?, | |
657 | }; | |
658 | ||
659 | crate::tools::file_set_contents(target, &raw_data, None)?; | |
660 | ||
661 | } else if server_archive_name.ends_with(".didx") { | |
afb4cd28 | 662 | let tmpfile = client.download(&server_archive_name, tmpfile).wait()?; |
86eda3eb | 663 | |
afb4cd28 DM |
664 | let index = DynamicIndexReader::new(tmpfile) |
665 | .map_err(|err| format_err!("unable to read dynamic index '{}' - {}", archive_name, err))?; | |
86eda3eb | 666 | |
f4bf7dfc DM |
667 | let most_used = index.find_most_used_chunks(8); |
668 | ||
669 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
670 | ||
afb4cd28 | 671 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
86eda3eb | 672 | |
afb4cd28 DM |
673 | let feature_flags = pxar::CA_FORMAT_DEFAULT; |
674 | let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags, |path| { | |
675 | if verbose { | |
676 | println!("{:?}", path); | |
677 | } | |
678 | Ok(()) | |
679 | }); | |
86eda3eb | 680 | |
afb4cd28 DM |
681 | decoder.restore(Path::new(target))?; |
682 | ||
683 | } else if server_archive_name.ends_with(".fidx") { | |
684 | let tmpfile = client.download(&server_archive_name, tmpfile).wait()?; | |
685 | ||
686 | let index = FixedIndexReader::new(tmpfile) | |
687 | .map_err(|err| format_err!("unable to read fixed index '{}' - {}", archive_name, err))?; | |
7dcbe051 | 688 | |
f4bf7dfc DM |
689 | let most_used = index.find_most_used_chunks(8); |
690 | ||
691 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
692 | ||
afb4cd28 DM |
693 | let mut reader = BufferedFixedReader::new(index, chunk_reader); |
694 | ||
695 | let mut writer = std::fs::OpenOptions::new() | |
696 | .write(true) | |
697 | .create(true) | |
698 | .create_new(true) | |
699 | .open(target) | |
700 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?; | |
701 | ||
702 | std::io::copy(&mut reader, &mut writer) | |
703 | .map_err(|err| format_err!("unable to store data - {}", err))?; | |
45db6f89 | 704 | } else { |
f8100e96 | 705 | bail!("unknown archive file extension (expected .pxar of .img)"); |
3031e44c | 706 | } |
fef44d4f DM |
707 | |
708 | Ok(Value::Null) | |
45db6f89 DM |
709 | } |
710 | ||
83b7db02 DM |
711 | fn prune( |
712 | mut param: Value, | |
713 | _info: &ApiMethod, | |
dd5495d6 | 714 | _rpcenv: &mut dyn RpcEnvironment, |
83b7db02 DM |
715 | ) -> Result<Value, Error> { |
716 | ||
717 | let repo_url = tools::required_string_param(¶m, "repository")?; | |
edd3c8c6 | 718 | let repo: BackupRepository = repo_url.parse()?; |
83b7db02 | 719 | |
45cdce06 | 720 | let mut client = HttpClient::new(repo.host(), repo.user())?; |
83b7db02 | 721 | |
d0a03d40 | 722 | let path = format!("api2/json/admin/datastore/{}/prune", repo.store()); |
83b7db02 DM |
723 | |
724 | param.as_object_mut().unwrap().remove("repository"); | |
725 | ||
5a2df000 | 726 | let result = client.post(&path, Some(param)).wait()?; |
83b7db02 | 727 | |
d0a03d40 DM |
728 | record_repository(&repo); |
729 | ||
83b7db02 DM |
730 | Ok(result) |
731 | } | |
732 | ||
5a2df000 | 733 | // like get, but simply ignore errors and return Null instead |
b2388518 | 734 | fn try_get(repo: &BackupRepository, url: &str) -> Value { |
024f11bb | 735 | |
45cdce06 DM |
736 | let client = match HttpClient::new(repo.host(), repo.user()) { |
737 | Ok(v) => v, | |
738 | _ => return Value::Null, | |
739 | }; | |
b2388518 | 740 | |
9e391bb7 | 741 | let mut resp = match client.get(url, None).wait() { |
b2388518 DM |
742 | Ok(v) => v, |
743 | _ => return Value::Null, | |
744 | }; | |
745 | ||
746 | if let Some(map) = resp.as_object_mut() { | |
747 | if let Some(data) = map.remove("data") { | |
748 | return data; | |
749 | } | |
750 | } | |
751 | Value::Null | |
752 | } | |
753 | ||
754 | fn extract_repo(param: &HashMap<String, String>) -> Option<BackupRepository> { | |
024f11bb DM |
755 | |
756 | let repo_url = match param.get("repository") { | |
757 | Some(v) => v, | |
b2388518 | 758 | _ => return None, |
024f11bb DM |
759 | }; |
760 | ||
761 | let repo: BackupRepository = match repo_url.parse() { | |
762 | Ok(v) => v, | |
b2388518 | 763 | _ => return None, |
024f11bb DM |
764 | }; |
765 | ||
b2388518 DM |
766 | Some(repo) |
767 | } | |
024f11bb | 768 | |
b2388518 | 769 | fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
024f11bb | 770 | |
b2388518 DM |
771 | let mut result = vec![]; |
772 | ||
773 | let repo = match extract_repo(param) { | |
774 | Some(v) => v, | |
024f11bb DM |
775 | _ => return result, |
776 | }; | |
777 | ||
b2388518 DM |
778 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
779 | ||
780 | let data = try_get(&repo, &path); | |
781 | ||
782 | if let Some(list) = data.as_array() { | |
024f11bb | 783 | for item in list { |
98f0b972 DM |
784 | if let (Some(backup_id), Some(backup_type)) = |
785 | (item["backup-id"].as_str(), item["backup-type"].as_str()) | |
786 | { | |
787 | result.push(format!("{}/{}", backup_type, backup_id)); | |
024f11bb DM |
788 | } |
789 | } | |
790 | } | |
791 | ||
792 | result | |
793 | } | |
794 | ||
b2388518 DM |
795 | fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
796 | ||
797 | let mut result = vec![]; | |
798 | ||
799 | let repo = match extract_repo(param) { | |
800 | Some(v) => v, | |
801 | _ => return result, | |
802 | }; | |
803 | ||
804 | if arg.matches('/').count() < 2 { | |
805 | let groups = complete_backup_group(arg, param); | |
806 | for group in groups { | |
807 | result.push(group.to_string()); | |
808 | result.push(format!("{}/", group)); | |
809 | } | |
810 | return result; | |
811 | } | |
812 | ||
813 | let mut parts = arg.split('/'); | |
814 | let query = tools::json_object_to_query(json!({ | |
815 | "backup-type": parts.next().unwrap(), | |
816 | "backup-id": parts.next().unwrap(), | |
817 | })).unwrap(); | |
818 | ||
819 | let path = format!("api2/json/admin/datastore/{}/snapshots?{}", repo.store(), query); | |
820 | ||
821 | let data = try_get(&repo, &path); | |
822 | ||
823 | if let Some(list) = data.as_array() { | |
824 | for item in list { | |
825 | if let (Some(backup_id), Some(backup_type), Some(backup_time)) = | |
826 | (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64()) | |
827 | { | |
828 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time); | |
829 | result.push(snapshot.relative_path().to_str().unwrap().to_owned()); | |
830 | } | |
831 | } | |
832 | } | |
833 | ||
834 | result | |
835 | } | |
836 | ||
45db6f89 | 837 | fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
08dc340a DM |
838 | |
839 | let mut result = vec![]; | |
840 | ||
841 | let repo = match extract_repo(param) { | |
842 | Some(v) => v, | |
843 | _ => return result, | |
844 | }; | |
845 | ||
846 | let snapshot = match param.get("snapshot") { | |
847 | Some(path) => { | |
848 | match BackupDir::parse(path) { | |
849 | Ok(v) => v, | |
850 | _ => return result, | |
851 | } | |
852 | } | |
853 | _ => return result, | |
854 | }; | |
855 | ||
856 | let query = tools::json_object_to_query(json!({ | |
857 | "backup-type": snapshot.group().backup_type(), | |
858 | "backup-id": snapshot.group().backup_id(), | |
859 | "backup-time": snapshot.backup_time().timestamp(), | |
860 | })).unwrap(); | |
861 | ||
862 | let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query); | |
863 | ||
864 | let data = try_get(&repo, &path); | |
865 | ||
866 | if let Some(list) = data.as_array() { | |
867 | for item in list { | |
868 | if let Some(filename) = item.as_str() { | |
869 | result.push(filename.to_owned()); | |
870 | } | |
871 | } | |
872 | } | |
873 | ||
45db6f89 DM |
874 | result |
875 | } | |
876 | ||
877 | fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
878 | ||
879 | let result = complete_server_file_name(arg, param); | |
880 | ||
6899dbfb | 881 | strip_server_file_expenstions(result) |
08dc340a DM |
882 | } |
883 | ||
49811347 DM |
884 | fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
885 | ||
886 | let mut result = vec![]; | |
887 | ||
888 | let mut size = 64; | |
889 | loop { | |
890 | result.push(size.to_string()); | |
891 | size = size * 2; | |
892 | if size > 4096 { break; } | |
893 | } | |
894 | ||
895 | result | |
896 | } | |
897 | ||
826f309b | 898 | fn get_encryption_key_password() -> Result<Vec<u8>, Error> { |
ff5d3707 | 899 | |
f2401311 DM |
900 | // fixme: implement other input methods |
901 | ||
902 | use std::env::VarError::*; | |
903 | match std::env::var("PBS_ENCRYPTION_PASSWORD") { | |
826f309b | 904 | Ok(p) => return Ok(p.as_bytes().to_vec()), |
f2401311 DM |
905 | Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"), |
906 | Err(NotPresent) => { | |
907 | // Try another method | |
908 | } | |
909 | } | |
910 | ||
911 | // If we're on a TTY, query the user for a password | |
912 | if crate::tools::tty::stdin_isatty() { | |
826f309b | 913 | return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?); |
f2401311 DM |
914 | } |
915 | ||
916 | bail!("no password input mechanism available"); | |
917 | } | |
918 | ||
ac716234 DM |
919 | fn key_create( |
920 | param: Value, | |
921 | _info: &ApiMethod, | |
922 | _rpcenv: &mut dyn RpcEnvironment, | |
923 | ) -> Result<Value, Error> { | |
924 | ||
9b06db45 DM |
925 | let path = tools::required_string_param(¶m, "path")?; |
926 | let path = PathBuf::from(path); | |
ac716234 | 927 | |
181f097a | 928 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
ac716234 DM |
929 | |
930 | let key = proxmox::sys::linux::random_data(32)?; | |
931 | ||
181f097a DM |
932 | if kdf == "scrypt" { |
933 | // always read passphrase from tty | |
934 | if !crate::tools::tty::stdin_isatty() { | |
935 | bail!("unable to read passphrase - no tty"); | |
936 | } | |
ac716234 | 937 | |
181f097a DM |
938 | let password = crate::tools::tty::read_password("Encryption Key Password: ")?; |
939 | ||
ab44acff | 940 | let key_config = encrypt_key_with_passphrase(&key, &password)?; |
37c5a175 | 941 | |
ab44acff | 942 | store_key_config(&path, false, key_config)?; |
181f097a DM |
943 | |
944 | Ok(Value::Null) | |
945 | } else if kdf == "none" { | |
946 | let created = Local.timestamp(Local::now().timestamp(), 0); | |
947 | ||
948 | store_key_config(&path, false, KeyConfig { | |
949 | kdf: None, | |
950 | created, | |
ab44acff | 951 | modified: created, |
181f097a DM |
952 | data: key, |
953 | })?; | |
954 | ||
955 | Ok(Value::Null) | |
956 | } else { | |
957 | unreachable!(); | |
958 | } | |
ac716234 DM |
959 | } |
960 | ||
9f46c7de DM |
961 | fn master_pubkey_path() -> Result<PathBuf, Error> { |
962 | let base = BaseDirectories::with_prefix("proxmox-backup")?; | |
963 | ||
964 | // usually $HOME/.config/proxmox-backup/master-public.pem | |
965 | let path = base.place_config_file("master-public.pem")?; | |
966 | ||
967 | Ok(path) | |
968 | } | |
969 | ||
3ea8bfc9 DM |
970 | fn key_import_master_pubkey( |
971 | param: Value, | |
972 | _info: &ApiMethod, | |
973 | _rpcenv: &mut dyn RpcEnvironment, | |
974 | ) -> Result<Value, Error> { | |
975 | ||
976 | let path = tools::required_string_param(¶m, "path")?; | |
977 | let path = PathBuf::from(path); | |
978 | ||
979 | let pem_data = proxmox_backup::tools::file_get_contents(&path)?; | |
980 | ||
981 | if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) { | |
982 | bail!("Unable to decode PEM data - {}", err); | |
983 | } | |
984 | ||
9f46c7de | 985 | let target_path = master_pubkey_path()?; |
3ea8bfc9 DM |
986 | |
987 | proxmox_backup::tools::file_set_contents(&target_path, &pem_data, None)?; | |
988 | ||
989 | println!("Imported public master key to {:?}", target_path); | |
990 | ||
991 | Ok(Value::Null) | |
992 | } | |
993 | ||
37c5a175 DM |
994 | fn key_create_master_key( |
995 | _param: Value, | |
996 | _info: &ApiMethod, | |
997 | _rpcenv: &mut dyn RpcEnvironment, | |
998 | ) -> Result<Value, Error> { | |
999 | ||
1000 | // we need a TTY to query the new password | |
1001 | if !crate::tools::tty::stdin_isatty() { | |
1002 | bail!("unable to create master key - no tty"); | |
1003 | } | |
1004 | ||
1005 | let rsa = openssl::rsa::Rsa::generate(4096)?; | |
1006 | let pkey = openssl::pkey::PKey::from_rsa(rsa)?; | |
1007 | ||
1008 | let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?; | |
1009 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
1010 | ||
1011 | if new_pw != verify_pw { | |
1012 | bail!("Password verification fail!"); | |
1013 | } | |
1014 | ||
1015 | if new_pw.len() < 5 { | |
1016 | bail!("Password is too short!"); | |
1017 | } | |
1018 | ||
1019 | let pub_key: Vec<u8> = pkey.public_key_to_pem()?; | |
1020 | let filename_pub = "master-public.pem"; | |
1021 | println!("Writing public master key to {}", filename_pub); | |
1022 | proxmox_backup::tools::file_set_contents(filename_pub, pub_key.as_slice(), None)?; | |
1023 | ||
1024 | let cipher = openssl::symm::Cipher::aes_256_cbc(); | |
1025 | let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?; | |
1026 | ||
1027 | let filename_priv = "master-private.pem"; | |
1028 | println!("Writing private master key to {}", filename_priv); | |
1029 | proxmox_backup::tools::file_set_contents(filename_priv, priv_key.as_slice(), None)?; | |
1030 | ||
1031 | Ok(Value::Null) | |
1032 | } | |
ac716234 DM |
1033 | |
1034 | fn key_change_passphrase( | |
1035 | param: Value, | |
1036 | _info: &ApiMethod, | |
1037 | _rpcenv: &mut dyn RpcEnvironment, | |
1038 | ) -> Result<Value, Error> { | |
1039 | ||
9b06db45 DM |
1040 | let path = tools::required_string_param(¶m, "path")?; |
1041 | let path = PathBuf::from(path); | |
ac716234 | 1042 | |
181f097a DM |
1043 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
1044 | ||
ac716234 DM |
1045 | // we need a TTY to query the new password |
1046 | if !crate::tools::tty::stdin_isatty() { | |
1047 | bail!("unable to change passphrase - no tty"); | |
1048 | } | |
1049 | ||
ab44acff | 1050 | let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?; |
ac716234 | 1051 | |
181f097a | 1052 | if kdf == "scrypt" { |
ac716234 | 1053 | |
181f097a DM |
1054 | let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?; |
1055 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
ac716234 | 1056 | |
181f097a DM |
1057 | if new_pw != verify_pw { |
1058 | bail!("Password verification fail!"); | |
1059 | } | |
1060 | ||
1061 | if new_pw.len() < 5 { | |
1062 | bail!("Password is too short!"); | |
1063 | } | |
ac716234 | 1064 | |
ab44acff DM |
1065 | let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?; |
1066 | new_key_config.created = created; // keep original value | |
1067 | ||
1068 | store_key_config(&path, true, new_key_config)?; | |
ac716234 | 1069 | |
181f097a DM |
1070 | Ok(Value::Null) |
1071 | } else if kdf == "none" { | |
ab44acff | 1072 | let modified = Local.timestamp(Local::now().timestamp(), 0); |
181f097a DM |
1073 | |
1074 | store_key_config(&path, true, KeyConfig { | |
1075 | kdf: None, | |
ab44acff DM |
1076 | created, // keep original value |
1077 | modified, | |
6d0983db | 1078 | data: key.to_vec(), |
181f097a DM |
1079 | })?; |
1080 | ||
1081 | Ok(Value::Null) | |
1082 | } else { | |
1083 | unreachable!(); | |
1084 | } | |
f2401311 DM |
1085 | } |
1086 | ||
1087 | fn key_mgmt_cli() -> CliCommandMap { | |
1088 | ||
181f097a DM |
1089 | let kdf_schema: Arc<Schema> = Arc::new( |
1090 | StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.") | |
1091 | .format(Arc::new(ApiStringFormat::Enum(&["scrypt", "none"]))) | |
1092 | .default("scrypt") | |
1093 | .into() | |
1094 | ); | |
1095 | ||
f2401311 DM |
1096 | let key_create_cmd_def = CliCommand::new( |
1097 | ApiMethod::new( | |
1098 | key_create, | |
1099 | ObjectSchema::new("Create a new encryption key.") | |
9b06db45 | 1100 | .required("path", StringSchema::new("File system path.")) |
181f097a | 1101 | .optional("kdf", kdf_schema.clone()) |
f2401311 | 1102 | )) |
9b06db45 DM |
1103 | .arg_param(vec!["path"]) |
1104 | .completion_cb("path", tools::complete_file_name); | |
f2401311 | 1105 | |
ac716234 DM |
1106 | let key_change_passphrase_cmd_def = CliCommand::new( |
1107 | ApiMethod::new( | |
1108 | key_change_passphrase, | |
1109 | ObjectSchema::new("Change the passphrase required to decrypt the key.") | |
9b06db45 | 1110 | .required("path", StringSchema::new("File system path.")) |
181f097a | 1111 | .optional("kdf", kdf_schema.clone()) |
9b06db45 DM |
1112 | )) |
1113 | .arg_param(vec!["path"]) | |
1114 | .completion_cb("path", tools::complete_file_name); | |
ac716234 | 1115 | |
37c5a175 DM |
1116 | let key_create_master_key_cmd_def = CliCommand::new( |
1117 | ApiMethod::new( | |
1118 | key_create_master_key, | |
1119 | ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.") | |
1120 | )); | |
1121 | ||
3ea8bfc9 DM |
1122 | let key_import_master_pubkey_cmd_def = CliCommand::new( |
1123 | ApiMethod::new( | |
1124 | key_import_master_pubkey, | |
1125 | ObjectSchema::new("Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.") | |
1126 | .required("path", StringSchema::new("File system path.")) | |
1127 | )) | |
1128 | .arg_param(vec!["path"]) | |
1129 | .completion_cb("path", tools::complete_file_name); | |
1130 | ||
f2401311 | 1131 | let cmd_def = CliCommandMap::new() |
ac716234 | 1132 | .insert("create".to_owned(), key_create_cmd_def.into()) |
37c5a175 | 1133 | .insert("create-master-key".to_owned(), key_create_master_key_cmd_def.into()) |
3ea8bfc9 | 1134 | .insert("import-master-pubkey".to_owned(), key_import_master_pubkey_cmd_def.into()) |
ac716234 | 1135 | .insert("change-passphrase".to_owned(), key_change_passphrase_cmd_def.into()); |
f2401311 DM |
1136 | |
1137 | cmd_def | |
1138 | } | |
1139 | ||
f2401311 | 1140 | fn main() { |
33d64b81 | 1141 | |
25f1650b DM |
1142 | let backup_source_schema: Arc<Schema> = Arc::new( |
1143 | StringSchema::new("Backup source specification ([<label>:<path>]).") | |
1144 | .format(Arc::new(ApiStringFormat::Pattern(&BACKUPSPEC_REGEX))) | |
1145 | .into() | |
1146 | ); | |
1147 | ||
597a9203 | 1148 | let backup_cmd_def = CliCommand::new( |
ff5d3707 | 1149 | ApiMethod::new( |
bcd879cf | 1150 | create_backup, |
597a9203 | 1151 | ObjectSchema::new("Create (host) backup.") |
f2401311 | 1152 | .required("repository", REPO_URL_SCHEMA.clone()) |
ae0be2dd DM |
1153 | .required( |
1154 | "backupspec", | |
1155 | ArraySchema::new( | |
74cdb521 | 1156 | "List of backup source specifications ([<label.ext>:<path>] ...)", |
25f1650b | 1157 | backup_source_schema, |
ae0be2dd DM |
1158 | ).min_length(1) |
1159 | ) | |
6d0983db DM |
1160 | .optional( |
1161 | "keyfile", | |
1162 | StringSchema::new("Path to encryption key. All data will be encrypted using this key.")) | |
219ef0e6 DM |
1163 | .optional( |
1164 | "verbose", | |
1165 | BooleanSchema::new("Verbose output.").default(false)) | |
fba30411 DM |
1166 | .optional( |
1167 | "host-id", | |
1168 | StringSchema::new("Use specified ID for the backup group name ('host/<id>'). The default is the system hostname.")) | |
2d9d143a DM |
1169 | .optional( |
1170 | "chunk-size", | |
1171 | IntegerSchema::new("Chunk size in KB. Must be a power of 2.") | |
1172 | .minimum(64) | |
1173 | .maximum(4096) | |
1174 | .default(4096) | |
1175 | ) | |
ff5d3707 | 1176 | )) |
ae0be2dd | 1177 | .arg_param(vec!["repository", "backupspec"]) |
d0a03d40 | 1178 | .completion_cb("repository", complete_repository) |
49811347 | 1179 | .completion_cb("backupspec", complete_backup_source) |
6d0983db | 1180 | .completion_cb("keyfile", tools::complete_file_name) |
49811347 | 1181 | .completion_cb("chunk-size", complete_chunk_size); |
f8838fe9 | 1182 | |
41c039e1 DM |
1183 | let list_cmd_def = CliCommand::new( |
1184 | ApiMethod::new( | |
812c6f87 DM |
1185 | list_backup_groups, |
1186 | ObjectSchema::new("List backup groups.") | |
f2401311 | 1187 | .required("repository", REPO_URL_SCHEMA.clone()) |
41c039e1 | 1188 | )) |
d0a03d40 DM |
1189 | .arg_param(vec!["repository"]) |
1190 | .completion_cb("repository", complete_repository); | |
41c039e1 | 1191 | |
184f17af DM |
1192 | let snapshots_cmd_def = CliCommand::new( |
1193 | ApiMethod::new( | |
1194 | list_snapshots, | |
1195 | ObjectSchema::new("List backup snapshots.") | |
f2401311 | 1196 | .required("repository", REPO_URL_SCHEMA.clone()) |
184f17af DM |
1197 | .required("group", StringSchema::new("Backup group.")) |
1198 | )) | |
d0a03d40 | 1199 | .arg_param(vec!["repository", "group"]) |
024f11bb | 1200 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 1201 | .completion_cb("repository", complete_repository); |
184f17af | 1202 | |
6f62c924 DM |
1203 | let forget_cmd_def = CliCommand::new( |
1204 | ApiMethod::new( | |
1205 | forget_snapshots, | |
1206 | ObjectSchema::new("Forget (remove) backup snapshots.") | |
f2401311 | 1207 | .required("repository", REPO_URL_SCHEMA.clone()) |
6f62c924 DM |
1208 | .required("snapshot", StringSchema::new("Snapshot path.")) |
1209 | )) | |
d0a03d40 | 1210 | .arg_param(vec!["repository", "snapshot"]) |
b2388518 DM |
1211 | .completion_cb("repository", complete_repository) |
1212 | .completion_cb("snapshot", complete_group_or_snapshot); | |
6f62c924 | 1213 | |
8cc0d6af DM |
1214 | let garbage_collect_cmd_def = CliCommand::new( |
1215 | ApiMethod::new( | |
1216 | start_garbage_collection, | |
1217 | ObjectSchema::new("Start garbage collection for a specific repository.") | |
f2401311 | 1218 | .required("repository", REPO_URL_SCHEMA.clone()) |
8cc0d6af | 1219 | )) |
d0a03d40 DM |
1220 | .arg_param(vec!["repository"]) |
1221 | .completion_cb("repository", complete_repository); | |
8cc0d6af | 1222 | |
9f912493 DM |
1223 | let restore_cmd_def = CliCommand::new( |
1224 | ApiMethod::new( | |
1225 | restore, | |
1226 | ObjectSchema::new("Restore backup repository.") | |
f2401311 | 1227 | .required("repository", REPO_URL_SCHEMA.clone()) |
d5c34d98 DM |
1228 | .required("snapshot", StringSchema::new("Group/Snapshot path.")) |
1229 | .required("archive-name", StringSchema::new("Backup archive name.")) | |
9f912493 | 1230 | .required("target", StringSchema::new("Target directory path.")) |
86eda3eb DM |
1231 | .optional("keyfile", StringSchema::new("Path to encryption key.")) |
1232 | .optional( | |
1233 | "verbose", | |
1234 | BooleanSchema::new("Verbose output.").default(false) | |
1235 | ) | |
9f912493 | 1236 | )) |
d0a03d40 | 1237 | .arg_param(vec!["repository", "snapshot", "archive-name", "target"]) |
b2388518 | 1238 | .completion_cb("repository", complete_repository) |
08dc340a DM |
1239 | .completion_cb("snapshot", complete_group_or_snapshot) |
1240 | .completion_cb("archive-name", complete_archive_name) | |
1241 | .completion_cb("target", tools::complete_file_name); | |
9f912493 | 1242 | |
83b7db02 DM |
1243 | let prune_cmd_def = CliCommand::new( |
1244 | ApiMethod::new( | |
1245 | prune, | |
1246 | proxmox_backup::api2::admin::datastore::add_common_prune_prameters( | |
1247 | ObjectSchema::new("Prune backup repository.") | |
f2401311 | 1248 | .required("repository", REPO_URL_SCHEMA.clone()) |
83b7db02 DM |
1249 | ) |
1250 | )) | |
d0a03d40 DM |
1251 | .arg_param(vec!["repository"]) |
1252 | .completion_cb("repository", complete_repository); | |
9f912493 | 1253 | |
41c039e1 | 1254 | let cmd_def = CliCommandMap::new() |
597a9203 | 1255 | .insert("backup".to_owned(), backup_cmd_def.into()) |
6f62c924 | 1256 | .insert("forget".to_owned(), forget_cmd_def.into()) |
8cc0d6af | 1257 | .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into()) |
83b7db02 | 1258 | .insert("list".to_owned(), list_cmd_def.into()) |
184f17af | 1259 | .insert("prune".to_owned(), prune_cmd_def.into()) |
9f912493 | 1260 | .insert("restore".to_owned(), restore_cmd_def.into()) |
f2401311 DM |
1261 | .insert("snapshots".to_owned(), snapshots_cmd_def.into()) |
1262 | .insert("key".to_owned(), key_mgmt_cli().into()); | |
a914a774 | 1263 | |
5a2df000 DM |
1264 | hyper::rt::run(futures::future::lazy(move || { |
1265 | run_cli_command(cmd_def.into()); | |
1266 | Ok(()) | |
1267 | })); | |
496a6784 | 1268 | |
ff5d3707 | 1269 | } |