Skip to main content

local_time/
lib.rs

1//! The system time zone setting of Xila.
2//!
3//! Civil time stays outside the kernel clock: the `time` subsystem keeps UTC
4//! and monotonic time only (xila-project/core#463). This crate stores the time
5//! zone that the user chose, loads it at start-up and publishes it to every
6//! task as the POSIX `TZ` environment variable. Programs convert UTC to local
7//! time with the `xila-time-zone` crate.
8//!
9//! # Stored setting
10//!
11//! [`CONFIGURATION_PATH`] (`/configuration/system/time_zone.json`) holds one
12//! JSON object:
13//!
14//! ```json
15//! { "name": "Europe/Paris", "time_zone": "CET-1CEST,M3.5.0,M10.5.0/3" }
16//! ```
17//!
18//! - `time_zone` (required) is the POSIX TZ string, the `TZ` format of POSIX
19//!   `tzset`. It is the only value that Core reads and publishes, so Core needs
20//!   no IANA zone table.
21//! - `name` (optional) is the IANA zone name that the user chose, for display
22//!   only. It is absent when the user entered a custom TZ string. A program
23//!   with a newer zone table can resolve the name again. An invalid name is
24//!   dropped and the TZ string still applies.
25//!
26//! Only root may have written the file: it belongs to root, others cannot
27//! write it, and its group can only if it is root's group, as for the other
28//! files of `/configuration/system`. Everyone can read it. [`set`] replaces it
29//! atomically (a temporary file created with mode 0644, then a rename; a
30//! temporary file left by a failed write is truncated by the next one). A
31//! missing, unreadable or invalid file gives UTC (`UTC0`) and one warning at
32//! start-up, from [`initialize`]; [`load`] logs nothing. It never blocks the
33//! start-up.
34//!
35//! # Publication
36//!
37//! [`initialize`] runs once at start-up, before the shell, and publishes the
38//! stored TZ string via [`task::Manager::set_system_environment_variable`]: in
39//! the root task and in every task whose current `TZ` matches the root task's
40//! previous value (every task without `TZ` when called once at start-up).
41//! Every task inherits the environment of its parent, so native executables
42//! and WebAssembly guests (through WASI `environ_get`) see `TZ` from their
43//! start.
44//!
45//! [`set`] writes the file and then gives `TZ` the new value in the root task
46//! and in every task whose `TZ` is still the previous system value
47//! ([`task::Manager::set_system_environment_variable`]); a task that set a `TZ`
48//! of its own keeps it, unless it set the system value itself: such a task
49//! cannot be told apart from one that inherited the value, so it follows the
50//! change. Calls of [`set`] are serialised, so the file and `TZ` always hold
51//! the same setting. Tasks started after the change get the new value at
52//! once. A native program that reads `TZ` again, for example through
53//! [`current`] on each display update, follows the change. A WebAssembly guest
54//! copies its environment when it starts, so a running guest keeps the old
55//! value until it is restarted.
56//!
57//! # Sizes
58//!
59//! On 32-bit targets, [`Setting`] is 24 bytes (two heap strings, the name with
60//! the niche of `Option`) and [`SettingError`] is 1 byte.
61
62#![no_std]
63
64extern crate alloc;
65
66use alloc::string::{String, ToString};
67use core::cell::RefCell;
68use file_system::{
69    AccessFlags, CreateFlags, Flags, IntoIoErrorKind, IoErrorKind, Kind, Path, Permission,
70    Permissions, Special, Statistics,
71};
72use synchronization::{
73    blocking_mutex::{Mutex as BlockingMutex, raw::CriticalSectionRawMutex},
74    mutex::Mutex,
75};
76use task::TaskIdentifier;
77use users::{ADMINISTRATOR_GROUP_NAME, GroupIdentifier, UserIdentifier};
78use virtual_file_system::{File, VirtualFileSystem};
79
80pub use time_zone::{self, ParseError, TimeZone};
81
82/// The file that holds the setting.
83pub const CONFIGURATION_PATH: &str = "/configuration/system/time_zone.json";
84
85/// The temporary file that [`set`] writes before it renames it.
86const TEMPORARY_PATH: &str = "/configuration/system/.time_zone.json-new";
87
88/// The environment variable that holds the POSIX TZ string of the system
89/// time zone.
90pub const ENVIRONMENT_VARIABLE: &str = "TZ";
91
92/// The TZ string used when no valid setting is stored: UTC.
93pub const DEFAULT_TIME_ZONE: &str = "UTC0";
94
95/// The longest TZ string accepted, in bytes. The longest TZ string of tzdata
96/// 2026f has 50 bytes (`Pacific/Chatham`).
97pub const MAXIMUM_TIME_ZONE_LENGTH: usize = 64;
98
99/// The longest zone name accepted, in bytes. The longest IANA name of tzdata
100/// 2026f has 32 bytes (`America/Argentina/ComodRivadavia`).
101pub const MAXIMUM_NAME_LENGTH: usize = 64;
102
103/// The largest configuration file read, in bytes.
104pub const MAXIMUM_CONFIGURATION_SIZE: usize = 256;
105
106/// Why a setting is rejected.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub enum SettingError {
109    /// The name is empty, too long, or has a character that IANA names do not
110    /// use (only ASCII letters, digits, `/`, `_`, `-` and `+` are accepted).
111    InvalidName,
112    /// The TZ string is longer than [`MAXIMUM_TIME_ZONE_LENGTH`].
113    TimeZoneTooLong,
114    /// The TZ string does not parse.
115    InvalidTimeZone(ParseError),
116}
117
118impl core::fmt::Display for SettingError {
119    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
120        match self {
121            SettingError::InvalidName => write!(formatter, "invalid time zone name"),
122            SettingError::TimeZoneTooLong => write!(formatter, "TZ string too long"),
123            SettingError::InvalidTimeZone(error) => {
124                write!(formatter, "invalid TZ string: {error:?}")
125            }
126        }
127    }
128}
129
130/// A valid time zone setting: an optional zone name and a POSIX TZ string.
131#[derive(Clone, Debug, PartialEq, Eq)]
132pub struct Setting {
133    name: Option<String>,
134    time_zone: String,
135}
136
137impl Default for Setting {
138    fn default() -> Self {
139        Self::utc()
140    }
141}
142
143impl Setting {
144    /// UTC, with no name.
145    pub fn utc() -> Self {
146        Self {
147            name: None,
148            time_zone: DEFAULT_TIME_ZONE.to_string(),
149        }
150    }
151
152    /// Check and build a setting. `name` is the IANA zone name that
153    /// `time_zone` was resolved from, or None for a custom TZ string. The name
154    /// is not looked up: Core has no zone table.
155    pub fn new(name: Option<&str>, time_zone: &str) -> Result<Self, SettingError> {
156        if let Some(name) = name
157            && !is_valid_name(name)
158        {
159            return Err(SettingError::InvalidName);
160        }
161        validate_time_zone(time_zone)?;
162        Ok(Self {
163            name: name.map(ToString::to_string),
164            time_zone: time_zone.to_string(),
165        })
166    }
167
168    /// The IANA zone name, or None for a custom TZ string.
169    pub fn name(&self) -> Option<&str> {
170        self.name.as_deref()
171    }
172
173    /// The POSIX TZ string.
174    pub fn time_zone_string(&self) -> &str {
175        &self.time_zone
176    }
177
178    /// The parsed time zone.
179    pub fn time_zone(&self) -> TimeZone {
180        // The string was checked when the setting was built.
181        TimeZone::parse(&self.time_zone).unwrap_or_else(|_| utc())
182    }
183
184    /// Parse the JSON body of a configuration file. An invalid `name` is
185    /// dropped: it is for display only, and the TZ string still applies.
186    pub fn from_json(text: &str) -> Option<Self> {
187        let file: ConfigurationFile = miniserde::json::from_str(text).ok()?;
188        let name = file.name.as_deref().filter(|name| is_valid_name(name));
189        Self::new(name, &file.time_zone).ok()
190    }
191
192    /// The JSON body of a configuration file.
193    pub fn to_json(&self) -> String {
194        let mut text = miniserde::json::to_string(&ConfigurationFile {
195            name: self.name.clone(),
196            time_zone: self.time_zone.clone(),
197        });
198        text.push('\n');
199        text
200    }
201}
202
203/// The file as written. Unknown keys are ignored.
204#[derive(miniserde::Serialize, miniserde::Deserialize)]
205struct ConfigurationFile {
206    name: Option<String>,
207    time_zone: String,
208}
209
210/// Check a POSIX TZ string as a setting: its length and its syntax.
211pub fn validate_time_zone(time_zone: &str) -> Result<TimeZone, SettingError> {
212    if time_zone.len() > MAXIMUM_TIME_ZONE_LENGTH {
213        return Err(SettingError::TimeZoneTooLong);
214    }
215    TimeZone::parse(time_zone).map_err(SettingError::InvalidTimeZone)
216}
217
218fn is_valid_name(name: &str) -> bool {
219    !name.is_empty()
220        && name.len() <= MAXIMUM_NAME_LENGTH
221        && name
222            .bytes()
223            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'_' | b'-' | b'+'))
224}
225
226/// UTC as a parsed time zone.
227pub const fn utc() -> TimeZone {
228    TimeZone::utc()
229}
230
231/// Whether only root can have written a file: it belongs to root, others may
232/// not write it, and its group may only if it is root's group.
233fn is_written_by_root_only(statistics: &Statistics) -> bool {
234    statistics.user == UserIdentifier::ROOT
235        && !statistics
236            .permissions
237            .get_others()
238            .contains(Permission::Write)
239        && (statistics.group == GroupIdentifier::ROOT
240            || !statistics
241                .permissions
242                .get_group()
243                .contains(Permission::Write))
244}
245
246/// Read the stored setting, without a fallback.
247///
248/// Fails with `NotFound` when there is no file, `PermissionDenied` when the
249/// file is not a regular file written by root only, `FileTooLarge` when it is
250/// larger than [`MAXIMUM_CONFIGURATION_SIZE`], and `InvalidData` when its
251/// contents are not a valid setting.
252pub async fn read(
253    virtual_file_system: &VirtualFileSystem,
254    task: TaskIdentifier,
255) -> Result<Setting, IoErrorKind> {
256    let mut file = File::open(
257        virtual_file_system,
258        task,
259        CONFIGURATION_PATH,
260        AccessFlags::Read.into(),
261    )
262    .await?;
263
264    let result = async {
265        let statistics = file.get_statistics().await?;
266        if statistics.kind != Kind::File || !is_written_by_root_only(&statistics) {
267            return Err(IoErrorKind::PermissionDenied);
268        }
269        // One byte more than the limit tells a full file from a larger one.
270        // The buffer is on the heap for the duration of the read, so it does
271        // not stay in the state of the caller's future.
272        let mut contents = alloc::vec![0u8; MAXIMUM_CONFIGURATION_SIZE + 1];
273        let mut length = 0;
274        while length < contents.len() {
275            let received = file.read(&mut contents[length..]).await?;
276            if received == 0 {
277                break;
278            }
279            length += received;
280        }
281        if length > MAXIMUM_CONFIGURATION_SIZE {
282            return Err(IoErrorKind::FileTooLarge);
283        }
284        let text =
285            core::str::from_utf8(&contents[..length]).map_err(|_| IoErrorKind::InvalidData)?;
286        Setting::from_json(text).ok_or(IoErrorKind::InvalidData)
287    }
288    .await;
289
290    let closed = file.close(virtual_file_system).await;
291    result.and_then(|setting| closed.map(|()| setting))
292}
293
294/// Read the stored setting, or UTC when it is missing or invalid. It logs
295/// nothing; [`initialize`] reports at start-up why UTC is used.
296pub async fn load(virtual_file_system: &VirtualFileSystem, task: TaskIdentifier) -> Setting {
297    read(virtual_file_system, task)
298        .await
299        .unwrap_or_else(|_| Setting::utc())
300}
301
302/// Load the stored setting and publish its TZ string as `TZ` via
303/// [`task::Manager::set_system_environment_variable`] (in the root task and in
304/// every task whose `TZ` matches the root task's previous value, which is every
305/// task without `TZ` when called once at start-up). Call it once at start-up,
306/// after the file systems are mounted and before the shell or the startup
307/// application starts. It returns the setting in use, UTC when the stored one
308/// is missing or invalid.
309pub async fn initialize(
310    task_manager: &task::Manager,
311    virtual_file_system: &VirtualFileSystem,
312    task: TaskIdentifier,
313) -> Setting {
314    let setting = match read(virtual_file_system, task).await {
315        Ok(setting) => setting,
316        Err(error) => {
317            log::warning!("Time zone: {CONFIGURATION_PATH} not used ({error}); using UTC");
318            Setting::utc()
319        }
320    };
321    task_manager
322        .set_system_environment_variable(ENVIRONMENT_VARIABLE, &setting.time_zone)
323        .await;
324    store(&setting);
325    setting
326}
327
328/// The setting in use, as [`initialize`] loaded it or [`set`] stored it. It is
329/// kept in RAM (24 bytes and two short heap strings), so that programs that
330/// show the setting, such as Settings, do not read the file again.
331static IN_USE: BlockingMutex<CriticalSectionRawMutex, RefCell<Option<Setting>>> =
332    BlockingMutex::new(RefCell::new(None));
333
334fn store(setting: &Setting) {
335    IN_USE.lock(|in_use| *in_use.borrow_mut() = Some(setting.clone()));
336}
337
338/// The setting in use: the one that [`initialize`] loaded or that [`set`]
339/// stored last, or UTC before [`initialize`]. It does not read the file.
340pub fn stored() -> Setting {
341    IN_USE.lock(|in_use| in_use.borrow().clone().unwrap_or_else(Setting::utc))
342}
343
344/// Serialises [`set`]: the file write and the publication of `TZ` of one call
345/// finish before the next call starts, so the file and `TZ` always hold the
346/// same setting. A blocking mutex is not usable here: the write awaits.
347static SET_LOCK: Mutex<CriticalSectionRawMutex, ()> = Mutex::new(());
348
349/// Store a new setting and publish it.
350///
351/// The user of `task` must be root or a member of the administrator group;
352/// otherwise the call fails with `PermissionDenied`. The file is written with
353/// the identity of the root task, so it stays owned by root. The new TZ string
354/// is published only once the file is in place. See the crate documentation
355/// for which tasks see the change.
356pub async fn set(
357    task_manager: &task::Manager,
358    users_manager: &users::Manager,
359    virtual_file_system: &VirtualFileSystem,
360    task: TaskIdentifier,
361    setting: &Setting,
362) -> Result<(), IoErrorKind> {
363    let user = task_manager
364        .get_user(task)
365        .await
366        .map_err(IntoIoErrorKind::into_io_error_kind)?;
367    if !is_administrator(users_manager, user).await {
368        return Err(IoErrorKind::PermissionDenied);
369    }
370
371    let _guard = SET_LOCK.lock().await;
372    write(
373        virtual_file_system,
374        task::Manager::ROOT_TASK_IDENTIFIER,
375        setting.to_json().as_bytes(),
376    )
377    .await?;
378    task_manager
379        .set_system_environment_variable(ENVIRONMENT_VARIABLE, &setting.time_zone)
380        .await;
381    store(setting);
382    Ok(())
383}
384
385/// Whether a user may change the system time zone: root, or a member of the
386/// administrator group.
387pub async fn is_administrator(users_manager: &users::Manager, user: UserIdentifier) -> bool {
388    if user == UserIdentifier::ROOT {
389        return true;
390    }
391    match users_manager
392        .get_group_identifier(ADMINISTRATOR_GROUP_NAME)
393        .await
394    {
395        Ok(group) => users_manager.is_in_group(user, group).await,
396        Err(_) => false,
397    }
398}
399
400/// Replace the configuration file atomically: write a temporary file, then
401/// rename it over the old one. On failure the old file is unchanged.
402async fn write(
403    virtual_file_system: &VirtualFileSystem,
404    task: TaskIdentifier,
405    contents: &[u8],
406) -> Result<(), IoErrorKind> {
407    let temporary = Path::from_str(TEMPORARY_PATH);
408    // Root can write; everyone can read, from the creation of the file on. A
409    // temporary file left by an interrupted write is truncated and reused:
410    // only root can create it, so its permissions are already these.
411    let mut file = File::open_with_permissions(
412        virtual_file_system,
413        task,
414        temporary,
415        Flags::new(AccessFlags::Write, Some(CreateFlags::CREATE_TRUNCATE), None),
416        Permissions::new(
417            Permission::READ_WRITE,
418            Permission::Read,
419            Permission::Read,
420            Special::NONE,
421        ),
422    )
423    .await?;
424    let result = async {
425        let mut written = 0;
426        while written < contents.len() {
427            let count = file.write(&contents[written..]).await?;
428            if count == 0 {
429                return Err(IoErrorKind::WriteZero);
430            }
431            written += count;
432        }
433        file.flush().await
434    }
435    .await;
436    let closed = file.close(virtual_file_system).await;
437    // A failed write leaves the temporary file; the next write truncates it.
438    match result.and(closed) {
439        Ok(()) => {
440            virtual_file_system
441                .rename(task, &temporary, &Path::from_str(CONFIGURATION_PATH))
442                .await
443        }
444        Err(error) => Err(error),
445    }
446}
447
448/// The time zone of a task: its `TZ` variable, parsed. UTC when the task has
449/// no `TZ` or when it does not parse.
450///
451/// Native programs call it again when they update a display, so that they
452/// follow a change made through [`set`]. It reads one variable and parses one
453/// short string; it does not touch the file system.
454pub async fn current(task_manager: &task::Manager, task: TaskIdentifier) -> TimeZone {
455    match task_manager
456        .get_environment_variable(task, ENVIRONMENT_VARIABLE)
457        .await
458    {
459        Ok(variable) => TimeZone::parse(variable.get_value()).unwrap_or_else(|_| utc()),
460        Err(_) => utc(),
461    }
462}
463
464/// Write a UTC offset in seconds as `+HH:MM`, or `+HH:MM:SS` when the seconds
465/// are not zero. For example, `3600` is `+01:00` and `-12600` is `-03:30`.
466pub fn write_offset(output: &mut dyn core::fmt::Write, offset_seconds: i32) -> core::fmt::Result {
467    let sign = if offset_seconds < 0 { '-' } else { '+' };
468    let magnitude = offset_seconds.unsigned_abs();
469    let (hours, minutes, seconds) = (magnitude / 3600, magnitude / 60 % 60, magnitude % 60);
470    if seconds == 0 {
471        write!(output, "{sign}{hours:02}:{minutes:02}")
472    } else {
473        write!(output, "{sign}{hours:02}:{minutes:02}:{seconds:02}")
474    }
475}
476
477/// Write the local time of `utc` (seconds since the Unix epoch) in `zone`,
478/// for example `2026-03-29 03:00:00 CEST (UTC+02:00)`. Settings and the shell
479/// share it, so it takes a `dyn` writer and is linked once.
480pub fn write_local_time(
481    output: &mut dyn core::fmt::Write,
482    zone: &TimeZone,
483    utc: i64,
484) -> core::fmt::Result {
485    let local = zone.from_utc(utc);
486    let date_time = local.date_time;
487    write!(
488        output,
489        "{:04}-{:02}-{:02} {:02}:{:02}:{:02} {} (UTC",
490        date_time.year,
491        date_time.month,
492        date_time.day,
493        date_time.hour,
494        date_time.minute,
495        date_time.second,
496        local.abbreviation,
497    )?;
498    write_offset(output, local.offset_seconds)?;
499    output.write_char(')')
500}
501
502#[cfg(test)]
503mod tests {
504    extern crate std;
505
506    use super::*;
507    use std::string::String;
508
509    #[test]
510    fn sizes_on_32_bit_targets() {
511        if cfg!(target_pointer_width = "32") {
512            assert_eq!(core::mem::size_of::<Setting>(), 24);
513        }
514        assert_eq!(core::mem::size_of::<SettingError>(), 1);
515    }
516
517    #[test]
518    fn setting_validation() {
519        let paris = Setting::new(Some("Europe/Paris"), "CET-1CEST,M3.5.0,M10.5.0/3").unwrap();
520        assert_eq!(paris.name(), Some("Europe/Paris"));
521        assert_eq!(paris.time_zone().standard_abbreviation(), "CET");
522        assert!(Setting::new(None, "<+0530>-5:30").is_ok());
523        assert!(Setting::new(Some("Etc/GMT+5"), "<-05>5").is_ok());
524        assert_eq!(
525            Setting::new(Some(""), "UTC0"),
526            Err(SettingError::InvalidName)
527        );
528        assert_eq!(
529            Setting::new(Some("Europe/Paris\n"), "UTC0"),
530            Err(SettingError::InvalidName)
531        );
532        assert_eq!(
533            Setting::new(Some("Europe Paris"), "UTC0"),
534            Err(SettingError::InvalidName)
535        );
536        assert!(matches!(
537            Setting::new(None, "UTC"),
538            Err(SettingError::InvalidTimeZone(_))
539        ));
540        assert!(matches!(
541            Setting::new(None, "Europe/Paris"),
542            Err(SettingError::InvalidTimeZone(_))
543        ));
544        let long = "A".repeat(MAXIMUM_TIME_ZONE_LENGTH + 1);
545        assert_eq!(
546            Setting::new(None, &long),
547            Err(SettingError::TimeZoneTooLong)
548        );
549    }
550
551    #[test]
552    fn json_round_trip() {
553        for setting in [
554            Setting::new(Some("Europe/Paris"), "CET-1CEST,M3.5.0,M10.5.0/3").unwrap(),
555            Setting::new(None, "<+0545>-5:45").unwrap(),
556        ] {
557            assert_eq!(Setting::from_json(&setting.to_json()), Some(setting));
558        }
559        assert_eq!(
560            Setting::from_json(r#"{"time_zone":"UTC0","$schema":"x"}"#),
561            Some(Setting::utc())
562        );
563        assert_eq!(Setting::from_json(r#"{"name":"Europe/Paris"}"#), None);
564        assert_eq!(Setting::from_json(r#"{"time_zone":"bad"}"#), None);
565        assert_eq!(Setting::from_json("UTC0"), None);
566    }
567
568    #[test]
569    fn local_time_at_a_daylight_saving_change() {
570        let paris = TimeZone::parse("CET-1CEST,M3.5.0,M10.5.0/3").unwrap();
571        let mut output = String::new();
572        write_local_time(&mut output, &paris, 1_774_745_999).unwrap();
573        assert_eq!(output, "2026-03-29 01:59:59 CET (UTC+01:00)");
574        output.clear();
575        write_local_time(&mut output, &paris, 1_774_746_000).unwrap();
576        assert_eq!(output, "2026-03-29 03:00:00 CEST (UTC+02:00)");
577    }
578
579    #[test]
580    fn an_invalid_name_keeps_the_time_zone() {
581        let setting = Setting::from_json(r#"{"name":"Not a name!","time_zone":"JST-9"}"#).unwrap();
582        assert_eq!(setting.name(), None);
583        assert_eq!(setting.time_zone_string(), "JST-9");
584    }
585
586    #[test]
587    fn offsets() {
588        let format = |offset| {
589            let mut output = String::new();
590            write_offset(&mut output, offset).unwrap();
591            output
592        };
593        assert_eq!(format(0), "+00:00");
594        assert_eq!(format(3600), "+01:00");
595        assert_eq!(format(-12600), "-03:30");
596        assert_eq!(format(20700), "+05:45");
597        assert_eq!(format(-5), "-00:00:05");
598    }
599}