Debian Codegraph @

debian/missing-sources/jiff/src/tz/system/windows/mod.rs

raw
1 use core::mem::MaybeUninit;
2
3 use alloc::string::String;
4
5 use windows_sys::Win32::System::Time::{
6 GetDynamicTimeZoneInformation, DYNAMIC_TIME_ZONE_INFORMATION,
7 TIME_ZONE_ID_INVALID,
8 };
9
10 use crate::{
11 error::{tz::system::Error as E, Error, ErrorContext},
12 tz::{TimeZone, TimeZoneDatabase},
13 util::utf8,
14 };
15
16 use self::windows_zones::WINDOWS_TO_IANA;
17
18 #[allow(dead_code)] // we don't currently read the version
19 mod windows_zones;
20
21 /// Attempts to find the default "system" time zone.
22 ///
23 /// This works by querying `GetDynamicTimeZoneInformation` via the Windows
24 /// API, and mapping the time zone key name returned to an IANA time zone
25 /// name via the [CLDR XML data].
26 ///
27 /// If the API call fails or a valid mapping could not be found, then `None`
28 /// is returned and some log messages are emitted.
29 ///
30 /// Windows does provide a [WinRT GetTimeZone] call that will return the IANA
31 /// time zone name directly, but it looks like a mess to use WinRT from Rust
32 /// currently. And this approach enjoys wider platform support.
33 ///
34 /// [CLDR XML data]: https://github.com/unicode-org/cldr/raw/main/common/supplemental/windowsZones.xml
35 /// [WinRT GetTimeZone]: https://learn.microsoft.com/en-us/uwp/api/windows.globalization.calendar.gettimezone?view=winrt-22621
36 pub(super) fn get(db: &TimeZoneDatabase) -> Option<TimeZone> {
37 let tz_key_name = match get_tz_key_name() {
38 Ok(tz_key_name) => tz_key_name,
39 Err(_err) => {
40 warn!(
41 "failed to discover current time zone via \
42 winapi GetDynamicTimeZoneInformation: {_err}",
43 );
44 return None;
45 }
46 };
47 let iana_name = match windows_to_iana(&tz_key_name) {
48 Ok(iana_name) => iana_name,
49 Err(_err) => {
50 warn!("could not find IANA time zone name: {_err}");
51 return None;
52 }
53 };
54 let tz = match db.get(iana_name) {
55 Ok(tz) => tz,
56 Err(_err) => {
57 warn!(
58 "could not find mapped IANA time zone {iana_name} \
59 in zoneinfo database {db:?}: {_err}",
60 );
61 return None;
62 }
63 };
64 Some(tz)
65 }
66
67 pub(super) fn read(_db: &TimeZoneDatabase, path: &str) -> Option<TimeZone> {
68 match super::read_unnamed_tzif_file(path) {
69 Ok(tz) => Some(tz),
70 Err(_err) => {
71 trace!("failed to read {path} as unnamed time zone: {_err}");
72 None
73 }
74 }
75 }
76
77 fn windows_to_iana(tz_key_name: &str) -> Result<&'static str, Error> {
78 let result = WINDOWS_TO_IANA.binary_search_by(|(win_name, _)| {
79 utf8::cmp_ignore_ascii_case(win_name, &tz_key_name)
80 });
81 let Ok(index) = result else {
82 return Err(Error::from(E::WindowsMissingIanaMapping));
83 };
84 let iana_name = WINDOWS_TO_IANA[index].1;
85 trace!(
86 "found Windows time zone name `{tz_key_name}`, and \
87 successfully mapped it to IANA time zone `{iana_name}`",
88 );
89 Ok(iana_name)
90 }
91
92 fn get_tz_key_name() -> Result<String, Error> {
93 let mut info: MaybeUninit<DYNAMIC_TIME_ZONE_INFORMATION> =
94 MaybeUninit::uninit();
95 // SAFETY: We pass a pointer to the expected input and signal it as
96 // unitializaed to rustc via MaybeUninit.
97 let rc = unsafe { GetDynamicTimeZoneInformation(info.as_mut_ptr()) };
98 if rc == TIME_ZONE_ID_INVALID {
99 return Err(Error::io(std::io::Error::last_os_error()));
100 }
101 // SAFETY: Windows API docs indicate that the pointer is correctly written
102 // to unless it fails, and we check for failure above. So we're only here
103 // when `info` is properly initialized.
104 let info = unsafe { info.assume_init() };
105 let tz_key_name = nul_terminated_utf16_to_string(&info.TimeZoneKeyName)
106 .context(E::WindowsTimeZoneKeyName)?;
107 Ok(tz_key_name)
108 }
109
110 fn nul_terminated_utf16_to_string(
111 code_units: &[u16],
112 ) -> Result<String, Error> {
113 let nul = code_units
114 .iter()
115 .position(|&cu| cu == 0)
116 .ok_or(E::WindowsUtf16DecodeNul)?;
117 let string = String::from_utf16(&code_units[..nul])
118 .map_err(|_| E::WindowsUtf16DecodeInvalid)?;
119 Ok(string)
120 }
121
122 #[cfg(test)]
123 mod tests {
124 use super::*;
125
126 #[test]
127 fn get_time_zone_name_windows_dynamic_time_zone() {
128 let _ = crate::logging::Logger::init();
129
130 let db = crate::tz::db();
131 if crate::tz::db().is_definitively_empty() {
132 return;
133 }
134 let path = std::path::Path::new("/etc/localtime");
135 if !path.exists() {
136 return;
137 }
138 // It's hard to assert much other than that a time zone could be
139 // successfully constructed. Presumably this may fail in certain
140 // environments, but hopefully the `is_definitively_empty` check above
141 // will filter most out.
142 assert!(get(db).is_some());
143 }
144 }