1#![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
82pub const CONFIGURATION_PATH: &str = "/configuration/system/time_zone.json";
84
85const TEMPORARY_PATH: &str = "/configuration/system/.time_zone.json-new";
87
88pub const ENVIRONMENT_VARIABLE: &str = "TZ";
91
92pub const DEFAULT_TIME_ZONE: &str = "UTC0";
94
95pub const MAXIMUM_TIME_ZONE_LENGTH: usize = 64;
98
99pub const MAXIMUM_NAME_LENGTH: usize = 64;
102
103pub const MAXIMUM_CONFIGURATION_SIZE: usize = 256;
105
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub enum SettingError {
109 InvalidName,
112 TimeZoneTooLong,
114 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#[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 pub fn utc() -> Self {
146 Self {
147 name: None,
148 time_zone: DEFAULT_TIME_ZONE.to_string(),
149 }
150 }
151
152 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 pub fn name(&self) -> Option<&str> {
170 self.name.as_deref()
171 }
172
173 pub fn time_zone_string(&self) -> &str {
175 &self.time_zone
176 }
177
178 pub fn time_zone(&self) -> TimeZone {
180 TimeZone::parse(&self.time_zone).unwrap_or_else(|_| utc())
182 }
183
184 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 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#[derive(miniserde::Serialize, miniserde::Deserialize)]
205struct ConfigurationFile {
206 name: Option<String>,
207 time_zone: String,
208}
209
210pub 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
226pub const fn utc() -> TimeZone {
228 TimeZone::utc()
229}
230
231fn 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
246pub 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 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
294pub 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
302pub 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
328static 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
338pub fn stored() -> Setting {
341 IN_USE.lock(|in_use| in_use.borrow().clone().unwrap_or_else(Setting::utc))
342}
343
344static SET_LOCK: Mutex<CriticalSectionRawMutex, ()> = Mutex::new(());
348
349pub 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
385pub 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
400async 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 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 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
448pub 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
464pub 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
477pub 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}