]> git.proxmox.com Git - proxmox-backup.git/blob - src/api2/node/time.rs
add protected flag for some api methods
[proxmox-backup.git] / src / api2 / node / time.rs
1 use failure::*;
2
3 use crate::tools;
4 use crate::api::schema::*;
5 use crate::api::router::*;
6 use serde_json::{json, Value};
7
8 use chrono::prelude::*;
9
10 fn read_etc_localtime() -> Result<String, Error> {
11
12 let line = tools::file_read_firstline("/etc/timezone")?;
13
14 Ok(line.trim().to_owned())
15 }
16
17 fn get_time(
18 _param: Value,
19 _info: &ApiMethod,
20 _rpcenv: &mut RpcEnvironment,
21 ) -> Result<Value, Error> {
22
23 let datetime = Local::now();
24 let offset = datetime.offset();
25 let time = datetime.timestamp();
26 let localtime = time + (offset.fix().local_minus_utc() as i64);
27
28 Ok(json!({
29 "timezone": read_etc_localtime()?,
30 "time": time,
31 "localtime": localtime,
32 }))
33 }
34
35 extern "C" { fn tzset(); }
36
37 // Note:: this needs root rights ??
38
39 fn set_timezone(
40 param: Value,
41 _info: &ApiMethod,
42 _rpcenv: &mut RpcEnvironment,
43 ) -> Result<Value, Error> {
44
45 let timezone = tools::required_string_param(&param, "timezone")?;
46
47 let path = std::path::PathBuf::from(format!("/usr/share/zoneinfo/{}", timezone));
48
49 if !path.exists() {
50 bail!("No such timezone.");
51 }
52
53 tools::file_set_contents("/etc/timezone", timezone.as_bytes(), None)?;
54
55 let _ = std::fs::remove_file("/etc/localtime");
56
57 use std::os::unix::fs::symlink;
58 symlink(path, "/etc/localtime")?;
59
60 unsafe { tzset() };
61
62 Ok(Value::Null)
63 }
64
65 pub fn router() -> Router {
66
67 let route = Router::new()
68 .get(
69 ApiMethod::new(
70 get_time,
71 ObjectSchema::new("Read server time and time zone settings.")
72 ).returns(
73 ObjectSchema::new("Returns server time and timezone.")
74 .required("timezone", StringSchema::new("Time zone"))
75 .required("time", IntegerSchema::new("Seconds since 1970-01-01 00:00:00 UTC.")
76 .minimum(1297163644))
77 .required("localtime", IntegerSchema::new("Seconds since 1970-01-01 00:00:00 UTC. (local time)")
78 .minimum(1297163644))
79 )
80 )
81 .put(
82 ApiMethod::new(
83 set_timezone,
84 ObjectSchema::new("Set time zone.")
85 .required("timezone", StringSchema::new("Time zone. The file '/usr/share/zoneinfo/zone.tab' contains the list of valid names."))
86 ).protected(true)
87 );
88
89
90 route
91 }