]> git.proxmox.com Git - proxmox-backup.git/blob - src/bin/proxmox-backup-manager.rs
start ACL api
[proxmox-backup.git] / src / bin / proxmox-backup-manager.rs
1 use std::path::PathBuf;
2 use std::collections::HashMap;
3
4 use failure::*;
5 use serde_json::{json, Value};
6
7 use proxmox::api::{api, cli::*, RpcEnvironment, ApiHandler};
8
9 use proxmox_backup::configdir;
10 use proxmox_backup::tools;
11 use proxmox_backup::config::{self, remote::{self, Remote}};
12 use proxmox_backup::api2::{self, types::* };
13 use proxmox_backup::client::*;
14 use proxmox_backup::tools::ticket::*;
15 use proxmox_backup::auth_helpers::*;
16
17 async fn view_task_result(
18 client: HttpClient,
19 result: Value,
20 output_format: &str,
21 ) -> Result<(), Error> {
22 let data = &result["data"];
23 if output_format == "text" {
24 if let Some(upid) = data.as_str() {
25 display_task_log(client, upid, true).await?;
26 }
27 } else {
28 format_and_print_result(&data, &output_format);
29 }
30
31 Ok(())
32 }
33
34 fn connect() -> Result<HttpClient, Error> {
35
36 let uid = nix::unistd::Uid::current();
37
38 let mut options = HttpClientOptions::new()
39 .prefix(Some("proxmox-backup".to_string()))
40 .verify_cert(false); // not required for connection to localhost
41
42 let client = if uid.is_root() {
43 let ticket = assemble_rsa_ticket(private_auth_key(), "PBS", Some("root@pam"), None)?;
44 options = options.password(Some(ticket));
45 HttpClient::new("localhost", "root@pam", options)?
46 } else {
47 options = options.ticket_cache(true).interactive(true);
48 HttpClient::new("localhost", "root@pam", options)?
49 };
50
51 Ok(client)
52 }
53
54 #[api(
55 input: {
56 properties: {
57 "output-format": {
58 schema: OUTPUT_FORMAT,
59 optional: true,
60 },
61 }
62 }
63 )]
64 /// List configured remotes.
65 fn list_remotes(param: Value, rpcenv: &mut dyn RpcEnvironment) -> Result<Value, Error> {
66
67 let output_format = get_output_format(&param);
68
69 let info = &api2::config::remote::API_METHOD_LIST_REMOTES;
70 let mut data = match info.handler {
71 ApiHandler::Sync(handler) => (handler)(param, info, rpcenv)?,
72 _ => unreachable!(),
73 };
74
75 let options = default_table_format_options()
76 .column(ColumnConfig::new("name"))
77 .column(ColumnConfig::new("host"))
78 .column(ColumnConfig::new("userid"))
79 .column(ColumnConfig::new("fingerprint"))
80 .column(ColumnConfig::new("comment"));
81
82 format_and_print_result_full(&mut data, info.returns, &output_format, &options);
83
84 Ok(Value::Null)
85 }
86
87 fn remote_commands() -> CommandLineInterface {
88
89 let cmd_def = CliCommandMap::new()
90 .insert("list", CliCommand::new(&&API_METHOD_LIST_REMOTES))
91 .insert(
92 "create",
93 // fixme: howto handle password parameter?
94 CliCommand::new(&api2::config::remote::API_METHOD_CREATE_REMOTE)
95 .arg_param(&["name"])
96 )
97 .insert(
98 "update",
99 CliCommand::new(&api2::config::remote::API_METHOD_UPDATE_REMOTE)
100 .arg_param(&["name"])
101 .completion_cb("name", config::remote::complete_remote_name)
102 )
103 .insert(
104 "remove",
105 CliCommand::new(&api2::config::remote::API_METHOD_DELETE_REMOTE)
106 .arg_param(&["name"])
107 .completion_cb("name", config::remote::complete_remote_name)
108 );
109
110 cmd_def.into()
111 }
112
113 #[api(
114 input: {
115 properties: {
116 "output-format": {
117 schema: OUTPUT_FORMAT,
118 optional: true,
119 },
120 }
121 }
122 )]
123 /// List configured users.
124 fn list_users(param: Value, rpcenv: &mut dyn RpcEnvironment) -> Result<Value, Error> {
125
126 let output_format = get_output_format(&param);
127
128 let info = &api2::access::user::API_METHOD_LIST_USERS;
129 let mut data = match info.handler {
130 ApiHandler::Sync(handler) => (handler)(param, info, rpcenv)?,
131 _ => unreachable!(),
132 };
133
134 let options = default_table_format_options()
135 .column(ColumnConfig::new("userid"))
136 .column(ColumnConfig::new("enable"))
137 .column(ColumnConfig::new("expire"))
138 .column(ColumnConfig::new("firstname"))
139 .column(ColumnConfig::new("lastname"))
140 .column(ColumnConfig::new("email"))
141 .column(ColumnConfig::new("comment"));
142
143 format_and_print_result_full(&mut data, info.returns, &output_format, &options);
144
145 Ok(Value::Null)
146 }
147
148 fn user_commands() -> CommandLineInterface {
149
150 let cmd_def = CliCommandMap::new()
151 .insert("list", CliCommand::new(&&API_METHOD_LIST_USERS))
152 .insert(
153 "create",
154 // fixme: howto handle password parameter?
155 CliCommand::new(&api2::access::user::API_METHOD_CREATE_USER)
156 .arg_param(&["userid"])
157 )
158 .insert(
159 "update",
160 CliCommand::new(&api2::access::user::API_METHOD_UPDATE_USER)
161 .arg_param(&["userid"])
162 .completion_cb("userid", config::user::complete_user_name)
163 )
164 .insert(
165 "remove",
166 CliCommand::new(&api2::access::user::API_METHOD_DELETE_USER)
167 .arg_param(&["userid"])
168 .completion_cb("userid", config::user::complete_user_name)
169 );
170
171 cmd_def.into()
172 }
173
174 #[api(
175 input: {
176 properties: {
177 "output-format": {
178 schema: OUTPUT_FORMAT,
179 optional: true,
180 },
181 }
182 }
183 )]
184 /// Access Control list.
185 fn list_acls(param: Value, rpcenv: &mut dyn RpcEnvironment) -> Result<Value, Error> {
186
187 let output_format = get_output_format(&param);
188
189 let info = &api2::access::acl::API_METHOD_READ_ACL;
190 let mut data = match info.handler {
191 ApiHandler::Sync(handler) => (handler)(param, info, rpcenv)?,
192 _ => unreachable!(),
193 };
194
195 fn render_ugid(value: &Value, record: &Value) -> Result<String, Error> {
196 if value.is_null() { return Ok(String::new()); }
197 let ugid = value.as_str().unwrap();
198 let ugid_type = record["ugid_type"].as_str().unwrap();
199
200 if ugid_type == "user" {
201 Ok(ugid.to_string())
202 } else if ugid_type == "group" {
203 Ok(format!("@{}", ugid))
204 } else {
205 bail!("render_ugid: got unknown ugid_type");
206 }
207 }
208
209 let options = default_table_format_options()
210 .column(ColumnConfig::new("ugid").renderer(render_ugid))
211 .column(ColumnConfig::new("path"))
212 .column(ColumnConfig::new("propagate"))
213 .column(ColumnConfig::new("roleid"));
214
215 format_and_print_result_full(&mut data, info.returns, &output_format, &options);
216
217 Ok(Value::Null)
218 }
219
220 fn acl_commands() -> CommandLineInterface {
221
222 let cmd_def = CliCommandMap::new()
223 .insert("list", CliCommand::new(&&API_METHOD_LIST_ACLS));
224
225 cmd_def.into()
226 }
227
228 fn datastore_commands() -> CommandLineInterface {
229
230 let cmd_def = CliCommandMap::new()
231 .insert("list", CliCommand::new(&api2::config::datastore::API_METHOD_LIST_DATASTORES))
232 .insert("create",
233 CliCommand::new(&api2::config::datastore::API_METHOD_CREATE_DATASTORE)
234 .arg_param(&["name", "path"])
235 )
236 .insert("update",
237 CliCommand::new(&api2::config::datastore::API_METHOD_UPDATE_DATASTORE)
238 .arg_param(&["name"])
239 .completion_cb("name", config::datastore::complete_datastore_name)
240 )
241 .insert("remove",
242 CliCommand::new(&api2::config::datastore::API_METHOD_DELETE_DATASTORE)
243 .arg_param(&["name"])
244 .completion_cb("name", config::datastore::complete_datastore_name)
245 );
246
247 cmd_def.into()
248 }
249
250
251 #[api(
252 input: {
253 properties: {
254 store: {
255 schema: DATASTORE_SCHEMA,
256 },
257 "output-format": {
258 schema: OUTPUT_FORMAT,
259 optional: true,
260 },
261 }
262 }
263 )]
264 /// Start garbage collection for a specific datastore.
265 async fn start_garbage_collection(param: Value) -> Result<Value, Error> {
266
267 let output_format = get_output_format(&param);
268
269 let store = tools::required_string_param(&param, "store")?;
270
271 let mut client = connect()?;
272
273 let path = format!("api2/json/admin/datastore/{}/gc", store);
274
275 let result = client.post(&path, None).await?;
276
277 view_task_result(client, result, &output_format).await?;
278
279 Ok(Value::Null)
280 }
281
282 #[api(
283 input: {
284 properties: {
285 store: {
286 schema: DATASTORE_SCHEMA,
287 },
288 "output-format": {
289 schema: OUTPUT_FORMAT,
290 optional: true,
291 },
292 }
293 }
294 )]
295 /// Show garbage collection status for a specific datastore.
296 async fn garbage_collection_status(param: Value) -> Result<Value, Error> {
297
298 let output_format = get_output_format(&param);
299
300 let store = tools::required_string_param(&param, "store")?;
301
302 let client = connect()?;
303
304 let path = format!("api2/json/admin/datastore/{}/gc", store);
305
306 let mut result = client.get(&path, None).await?;
307 let mut data = result["data"].take();
308 let schema = api2::admin::datastore::API_RETURN_SCHEMA_GARBAGE_COLLECTION_STATUS;
309
310 let options = default_table_format_options();
311
312 format_and_print_result_full(&mut data, schema, &output_format, &options);
313
314 Ok(Value::Null)
315 }
316
317 fn garbage_collection_commands() -> CommandLineInterface {
318
319 let cmd_def = CliCommandMap::new()
320 .insert("status",
321 CliCommand::new(&API_METHOD_GARBAGE_COLLECTION_STATUS)
322 .arg_param(&["store"])
323 .completion_cb("store", config::datastore::complete_datastore_name)
324 )
325 .insert("start",
326 CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
327 .arg_param(&["store"])
328 .completion_cb("store", config::datastore::complete_datastore_name)
329 );
330
331 cmd_def.into()
332 }
333
334 #[api(
335 input: {
336 properties: {
337 limit: {
338 description: "The maximal number of tasks to list.",
339 type: Integer,
340 optional: true,
341 minimum: 1,
342 maximum: 1000,
343 default: 50,
344 },
345 "output-format": {
346 schema: OUTPUT_FORMAT,
347 optional: true,
348 },
349 all: {
350 type: Boolean,
351 description: "Also list stopped tasks.",
352 optional: true,
353 }
354 }
355 }
356 )]
357 /// List running server tasks.
358 async fn task_list(param: Value) -> Result<Value, Error> {
359
360 let output_format = get_output_format(&param);
361
362 let client = connect()?;
363
364 let limit = param["limit"].as_u64().unwrap_or(50) as usize;
365 let running = !param["all"].as_bool().unwrap_or(false);
366 let args = json!({
367 "running": running,
368 "start": 0,
369 "limit": limit,
370 });
371 let mut result = client.get("api2/json/nodes/localhost/tasks", Some(args)).await?;
372
373 let mut data = result["data"].take();
374 let schema = api2::node::tasks::API_RETURN_SCHEMA_LIST_TASKS;
375
376 let options = default_table_format_options()
377 .column(ColumnConfig::new("starttime").right_align(false).renderer(tools::format::render_epoch))
378 .column(ColumnConfig::new("endtime").right_align(false).renderer(tools::format::render_epoch))
379 .column(ColumnConfig::new("upid"))
380 .column(ColumnConfig::new("status").renderer(tools::format::render_task_status));
381
382 format_and_print_result_full(&mut data, schema, &output_format, &options);
383
384 Ok(Value::Null)
385 }
386
387 #[api(
388 input: {
389 properties: {
390 upid: {
391 schema: UPID_SCHEMA,
392 },
393 }
394 }
395 )]
396 /// Display the task log.
397 async fn task_log(param: Value) -> Result<Value, Error> {
398
399 let upid = tools::required_string_param(&param, "upid")?;
400
401 let client = connect()?;
402
403 display_task_log(client, upid, true).await?;
404
405 Ok(Value::Null)
406 }
407
408 #[api(
409 input: {
410 properties: {
411 upid: {
412 schema: UPID_SCHEMA,
413 },
414 }
415 }
416 )]
417 /// Try to stop a specific task.
418 async fn task_stop(param: Value) -> Result<Value, Error> {
419
420 let upid_str = tools::required_string_param(&param, "upid")?;
421
422 let mut client = connect()?;
423
424 let path = format!("api2/json/nodes/localhost/tasks/{}", upid_str);
425 let _ = client.delete(&path, None).await?;
426
427 Ok(Value::Null)
428 }
429
430 fn task_mgmt_cli() -> CommandLineInterface {
431
432 let task_log_cmd_def = CliCommand::new(&API_METHOD_TASK_LOG)
433 .arg_param(&["upid"]);
434
435 let task_stop_cmd_def = CliCommand::new(&API_METHOD_TASK_STOP)
436 .arg_param(&["upid"]);
437
438 let cmd_def = CliCommandMap::new()
439 .insert("list", CliCommand::new(&API_METHOD_TASK_LIST))
440 .insert("log", task_log_cmd_def)
441 .insert("stop", task_stop_cmd_def);
442
443 cmd_def.into()
444 }
445
446 fn x509name_to_string(name: &openssl::x509::X509NameRef) -> Result<String, Error> {
447 let mut parts = Vec::new();
448 for entry in name.entries() {
449 parts.push(format!("{} = {}", entry.object().nid().short_name()?, entry.data().as_utf8()?));
450 }
451 Ok(parts.join(", "))
452 }
453
454 #[api]
455 /// Diplay node certificate information.
456 fn cert_info() -> Result<(), Error> {
457
458 let cert_path = PathBuf::from(configdir!("/proxy.pem"));
459
460 let cert_pem = proxmox::tools::fs::file_get_contents(&cert_path)?;
461
462 let cert = openssl::x509::X509::from_pem(&cert_pem)?;
463
464 println!("Subject: {}", x509name_to_string(cert.subject_name())?);
465
466 if let Some(san) = cert.subject_alt_names() {
467 for name in san.iter() {
468 if let Some(v) = name.dnsname() {
469 println!(" DNS:{}", v);
470 } else if let Some(v) = name.ipaddress() {
471 println!(" IP:{:?}", v);
472 } else if let Some(v) = name.email() {
473 println!(" EMAIL:{}", v);
474 } else if let Some(v) = name.uri() {
475 println!(" URI:{}", v);
476 }
477 }
478 }
479
480 println!("Issuer: {}", x509name_to_string(cert.issuer_name())?);
481 println!("Validity:");
482 println!(" Not Before: {}", cert.not_before());
483 println!(" Not After : {}", cert.not_after());
484
485 let fp = cert.digest(openssl::hash::MessageDigest::sha256())?;
486 let fp_string = proxmox::tools::digest_to_hex(&fp);
487 let fp_string = fp_string.as_bytes().chunks(2).map(|v| std::str::from_utf8(v).unwrap())
488 .collect::<Vec<&str>>().join(":");
489
490 println!("Fingerprint (sha256): {}", fp_string);
491
492 let pubkey = cert.public_key()?;
493 println!("Public key type: {}", openssl::nid::Nid::from_raw(pubkey.id().as_raw()).long_name()?);
494 println!("Public key bits: {}", pubkey.bits());
495
496 Ok(())
497 }
498
499 #[api(
500 input: {
501 properties: {
502 force: {
503 description: "Force generation of new SSL certifate.",
504 type: Boolean,
505 optional:true,
506 },
507 }
508 },
509 )]
510 /// Update node certificates and generate all needed files/directories.
511 fn update_certs(force: Option<bool>) -> Result<(), Error> {
512
513 config::create_configdir()?;
514
515 if let Err(err) = generate_auth_key() {
516 bail!("unable to generate auth key - {}", err);
517 }
518
519 if let Err(err) = generate_csrf_key() {
520 bail!("unable to generate csrf key - {}", err);
521 }
522
523 config::update_self_signed_cert(force.unwrap_or(false))?;
524
525 Ok(())
526 }
527
528 fn cert_mgmt_cli() -> CommandLineInterface {
529
530 let cmd_def = CliCommandMap::new()
531 .insert("info", CliCommand::new(&API_METHOD_CERT_INFO))
532 .insert("update", CliCommand::new(&API_METHOD_UPDATE_CERTS));
533
534 cmd_def.into()
535 }
536
537 // fixme: avoid API redefinition
538 #[api(
539 input: {
540 properties: {
541 "local-store": {
542 schema: DATASTORE_SCHEMA,
543 },
544 remote: {
545 schema: REMOTE_ID_SCHEMA,
546 },
547 "remote-store": {
548 schema: DATASTORE_SCHEMA,
549 },
550 delete: {
551 description: "Delete vanished backups. This remove the local copy if the remote backup was deleted.",
552 type: Boolean,
553 optional: true,
554 default: true,
555 },
556 "output-format": {
557 schema: OUTPUT_FORMAT,
558 optional: true,
559 },
560 }
561 }
562 )]
563 /// Sync datastore from another repository
564 async fn pull_datastore(
565 remote: String,
566 remote_store: String,
567 local_store: String,
568 delete: Option<bool>,
569 param: Value,
570 ) -> Result<Value, Error> {
571
572 let output_format = get_output_format(&param);
573
574 let mut client = connect()?;
575
576 let mut args = json!({
577 "store": local_store,
578 "remote": remote,
579 "remote-store": remote_store,
580 });
581
582 if let Some(delete) = delete {
583 args["delete"] = delete.into();
584 }
585
586 let result = client.post("api2/json/pull", Some(args)).await?;
587
588 view_task_result(client, result, &output_format).await?;
589
590 Ok(Value::Null)
591 }
592
593 fn main() {
594
595 let cmd_def = CliCommandMap::new()
596 .insert("acl", acl_commands())
597 .insert("datastore", datastore_commands())
598 .insert("user", user_commands())
599 .insert("remote", remote_commands())
600 .insert("garbage-collection", garbage_collection_commands())
601 .insert("cert", cert_mgmt_cli())
602 .insert("task", task_mgmt_cli())
603 .insert(
604 "pull",
605 CliCommand::new(&API_METHOD_PULL_DATASTORE)
606 .arg_param(&["remote", "remote-store", "local-store"])
607 .completion_cb("local-store", config::datastore::complete_datastore_name)
608 .completion_cb("remote", config::remote::complete_remote_name)
609 .completion_cb("remote-store", complete_remote_datastore_name)
610 );
611
612 proxmox_backup::tools::runtime::main(run_async_cli_command(cmd_def));
613 }
614
615 // shell completion helper
616 pub fn complete_remote_datastore_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
617
618 let mut list = Vec::new();
619
620 let _ = proxmox::try_block!({
621 let remote = param.get("remote").ok_or_else(|| format_err!("no remote"))?;
622 let (remote_config, _digest) = remote::config()?;
623
624 let remote: Remote = remote_config.lookup("remote", &remote)?;
625
626 let options = HttpClientOptions::new()
627 .password(Some(remote.password.clone()))
628 .fingerprint(remote.fingerprint.clone());
629
630 let client = HttpClient::new(
631 &remote.host,
632 &remote.userid,
633 options,
634 )?;
635
636 let result = crate::tools::runtime::block_on(client.get("api2/json/admin/datastore", None))?;
637
638 if let Some(data) = result["data"].as_array() {
639 for item in data {
640 if let Some(store) = item["store"].as_str() {
641 list.push(store.to_owned());
642 }
643 }
644 }
645
646 Ok(())
647 }).map_err(|_err: Error| { /* ignore */ });
648
649 list
650 }