Debian Codegraph @

debian/rust-vendor/jiff/src/tz/system/mod.rs

raw
1 use std::{sync::RwLock, time::Duration};
2
3 use alloc::string::ToString;
4
5 use jcore::tz::posix;
6
7 use crate::{
8 error::{tz::system::Error as E, Error, ErrorContext},
9 tz::{TimeZone, TimeZoneDatabase},
10 util::cache::Expiration,
11 };
12
13 #[cfg(all(unix, not(any(target_os = "android", target_os = "emscripten"))))]
14 #[path = "unix.rs"]
15 mod sys;
16
17 #[cfg(all(unix, target_os = "android"))]
18 #[path = "android.rs"]
19 mod sys;
20
21 #[cfg(windows)]
22 #[path = "windows/mod.rs"]
23 mod sys;
24
25 #[cfg(all(
26 feature = "js",
27 any(target_arch = "wasm32", target_arch = "wasm64"),
28 target_os = "unknown"
29 ))]
30 #[path = "wasm_js.rs"]
31 mod sys;
32
33 #[cfg(all(target_family = "wasm", target_os = "emscripten"))]
34 #[path = "wasm_emscripten.rs"]
35 mod sys;
36
37 #[cfg(not(any(
38 unix,
39 windows,
40 all(
41 feature = "js",
42 any(target_arch = "wasm32", target_arch = "wasm64"),
43 target_os = "unknown"
44 )
45 )))]
46 mod sys {
47 use crate::tz::{TimeZone, TimeZoneDatabase};
48
49 pub(super) fn get(_db: &TimeZoneDatabase) -> Option<TimeZone> {
50 warn!("getting system time zone on this platform is unsupported");
51 None
52 }
53
54 pub(super) fn read(
55 _db: &TimeZoneDatabase,
56 path: &str,
57 ) -> Option<TimeZone> {
58 match super::read_unnamed_tzif_file(path) {
59 Ok(tz) => Some(tz),
60 Err(_err) => {
61 debug!("failed to read {path} as unnamed time zone: {_err}");
62 None
63 }
64 }
65 }
66 }
67
68 /// The duration of time that a cached time zone should be considered valid.
69 static TTL: Duration = Duration::new(5 * 60, 0);
70
71 /// A cached time zone.
72 ///
73 /// When there's a cached time zone that hasn't expired, then we return what's
74 /// in the cache. This is because determining the time zone can be mildly
75 /// expensive. For example, doing syscalls and potentially parsing TZif data.
76 ///
77 /// We could use a `thread_local!` for this instead which may perhaps be
78 /// faster.
79 ///
80 /// Note that our cache here is somewhat simplistic because we lean on the
81 /// fact that: 1) in the vast majority of cases, our platform specific code is
82 /// limited to finding a time zone name, and 2) looking up a time zone name in
83 /// `TimeZoneDatabase` has its own cache. The main cases this doesn't really
84 /// cover are when we can't find a time zone name. In which case, we might be
85 /// re-parsing POSIX TZ strings or TZif data unnecessarily. But it's not clear
86 /// this matters much. It might matter more if we shrink our TTL though.
87 static CACHE: RwLock<Cache> = RwLock::new(Cache::empty());
88
89 /// A simple global mutable cache of the most recently created system
90 /// `TimeZone`.
91 ///
92 /// This gets clearer periodically where subsequent calls to `get` must
93 /// re-create the time zone. This is likely wasted work in the vast majority
94 /// of cases, but the TTL should ensure it doesn't happen too often.
95 ///
96 /// Of course, in those cases where you want it to happen faster, we provide
97 /// a way to reset this cache and force a re-creation of the time zone.
98 struct Cache {
99 tz: Option<TimeZone>,
100 expiration: Expiration,
101 }
102
103 impl Cache {
104 /// Create an empty cache. The default state.
105 const fn empty() -> Cache {
106 Cache { tz: None, expiration: Expiration::expired() }
107 }
108 }
109
110 /// Retrieve the "system" time zone.
111 ///
112 /// If there is a cached time zone that isn't stale, then that is returned
113 /// instead.
114 ///
115 /// If there is no cached time zone, then this tries to determine the system
116 /// time zone in a platform specific manner. This may involve reading files
117 /// or making system calls. If that fails then an error is returned.
118 ///
119 /// Note that the `TimeZone` returned may not have an IANA name! In some cases,
120 /// it is just impractical to determine the time zone name. For example, when
121 /// `/etc/localtime` is a hard link to a TZif file instead of a symlink and
122 /// when the time zone name isn't recorded in any of the other obvious places.
123 pub(crate) fn get(db: &TimeZoneDatabase) -> Result<TimeZone, Error> {
124 {
125 let cache = CACHE.read().unwrap();
126 if let Some(ref tz) = cache.tz {
127 if !cache.expiration.is_expired() {
128 return Ok(tz.clone());
129 }
130 }
131 }
132 let tz = get_force(db)?;
133 {
134 // It's okay that we race here. We basically assume that any
135 // sufficiently close but approximately simultaneous detection of
136 // "system" time will lead to the same result. Of course, this is not
137 // strictly true, but since we invalidate the cache after a TTL, it
138 // will eventually be true in any sane environment.
139 let mut cache = CACHE.write().unwrap();
140 cache.tz = Some(tz.clone());
141 cache.expiration = Expiration::after(TTL);
142 }
143 Ok(tz)
144 }
145
146 /// Always attempt retrieve the system time zone. This never uses a cache.
147 pub(crate) fn get_force(db: &TimeZoneDatabase) -> Result<TimeZone, Error> {
148 match get_env_tz(db) {
149 Ok(Some(tz)) => {
150 debug!("checked `TZ` environment variable and found {tz:?}");
151 return Ok(tz);
152 }
153 Ok(None) => {
154 debug!("`TZ` environment variable is not set");
155 }
156 Err(err) => {
157 return Err(err.context(E::FailedEnvTz));
158 }
159 }
160 if let Some(tz) = sys::get(db) {
161 return Ok(tz);
162 }
163 Err(Error::from(E::FailedSystemTimeZone))
164 }
165
166 /// Materializes a `TimeZone` from a `TZ` environment variable.
167 ///
168 /// Basically, `TZ` is usually just an IANA Time Zone Database name like
169 /// `TZ=America/New_York` or `TZ=UTC`. But it can also be a POSIX time zone
170 /// transition string like `TZ=EST5EDTM3.2.0,M11.1.0` or it can be a file path
171 /// (absolute or relative) to a TZif file.
172 ///
173 /// We try very hard to extract a time zone name from `TZ` and use that to look
174 /// it up via `TimeZoneDatabase`. But we will fall back to unnamed TZif
175 /// `TimeZone` if necessary.
176 ///
177 /// This routine only returns `Ok(None)` when `TZ` is not set. If it is set
178 /// but a `TimeZone` could not be extracted, then an error is returned.
179 fn get_env_tz(db: &TimeZoneDatabase) -> Result<Option<TimeZone>, Error> {
180 // This routine is pretty Unix-y, but there's no reason it can't
181 // partially work on Windows. For example, setting TZ=America/New_York
182 // should work totally fine on Windows. I don't see a good reason not to
183 // support it anyway.
184
185 let Some(tzenv) = std::env::var_os("TZ") else { return Ok(None) };
186 // It is commonly agreed (across GNU and BSD tooling at least), but
187 // not standard, that setting an empty `TZ=` is indistinguishable from
188 // `TZ=UTC`.
189 if tzenv.is_empty() {
190 debug!(
191 "`TZ` environment variable set to empty value, \
192 assuming `TZ=UTC` in order to conform to \
193 widespread convention among Unix tooling",
194 );
195 return Ok(Some(TimeZone::UTC));
196 }
197 let tz_name_or_path = match posix::TzEnv::parse_os_str(&tzenv) {
198 Err(_err) => {
199 debug!(
200 "failed to parse {tzenv:?} as POSIX TZ rule \
201 (attempting to treat it as an IANA time zone): {_err}",
202 );
203 tzenv.to_str().ok_or(E::FailedPosixTzAndUtf8)?.to_string()
204 }
205 Ok(posix::TzEnv::Implementation(string)) => string.to_string(),
206 Ok(posix::TzEnv::Rule(tz)) => {
207 return Ok(Some(TimeZone::from_posix_tz(tz)))
208 }
209 };
210 // At this point, TZ is set to something that is definitively not a
211 // POSIX TZ transition string. Some possible values at this point are:
212 //
213 // TZ=America/New_York
214 // TZ=:America/New_York
215 // TZ=EST5EDT
216 // TZ=:EST5EDT
217 // TZ=/usr/share/zoneinfo/America/New_York
218 // TZ=:/usr/share/zoneinfo/America/New_York
219 // TZ=../zoneinfo/America/New_York
220 // TZ=:../zoneinfo/America/New_York
221 //
222 // `zoneinfo` is the common thread here. So we look for that first. If we
223 // can't find it, then we assume the entire string is a time zone name
224 // that we can look up in the system zoneinfo database.
225 let needle = "zoneinfo/";
226 let Some(rpos) = tz_name_or_path.rfind(needle) else {
227 // No zoneinfo means this is probably a IANA Time Zone name. But...
228 // it could just be a file path.
229 debug!(
230 "could not find {needle:?} in `TZ={tz_name_or_path:?}`, \
231 therefore attempting lookup in `{db:?}`",
232 );
233 return match db.get(&tz_name_or_path) {
234 Ok(tz) => Ok(Some(tz)),
235 Err(_err) => {
236 debug!(
237 "using `TZ={tz_name_or_path:?}` as time zone name failed, \
238 could not find time zone in zoneinfo database `{db:?}` \
239 (continuing to try and read `{tz_name_or_path}` as \
240 a TZif file)",
241 );
242 sys::read(db, &tz_name_or_path)
243 .ok_or_else(|| Error::from(E::FailedEnvTzAsTzif))
244 .map(Some)
245 }
246 };
247 };
248 // We now try to be a little cute here and extract the IANA time zone name
249 // from what we now believe is a file path by taking everything after
250 // `zoneinfo/`. Once we have that, we try to look it up in our tzdb.
251 let name = &tz_name_or_path[rpos + needle.len()..];
252 debug!(
253 "extracted `{name}` from `TZ={tz_name_or_path}` \
254 and assuming it is an IANA time zone name",
255 );
256 match db.get(&name) {
257 Ok(tz) => return Ok(Some(tz)),
258 Err(_err) => {
259 debug!(
260 "using `{name}` from `TZ={tz_name_or_path}`, \
261 could not find time zone in zoneinfo database `{db:?}` \
262 (continuing to try and use `{tz_name_or_path}`)",
263 );
264 }
265 }
266 // At this point, we have tried our hardest but we just cannot seem to
267 // extract an IANA time zone name out of the `TZ` environment variable.
268 // The only thing left for us to do is treat the value as a file path
269 // and read the data as TZif. This will give us time zone data if it works,
270 // but without a name.
271 sys::read(db, &tz_name_or_path)
272 .ok_or_else(|| Error::from(E::FailedEnvTzAsTzif))
273 .map(Some)
274 }
275
276 /// Returns the given file path as TZif data without a time zone name.
277 ///
278 /// Normally we require TZif time zones to have a name associated with it.
279 /// But because there are likely platforms that hardlink /etc/localtime and
280 /// perhaps have no other way to get a time zone name, we choose to support
281 /// that use case. Although I cannot actually name such a platform...
282 fn read_unnamed_tzif_file(path: &str) -> Result<TimeZone, Error> {
283 let data = std::fs::read(path)
284 .map_err(Error::io)
285 .context(E::FailedUnnamedTzifRead)?;
286 let tz =
287 TimeZone::tzif_system(&data).context(E::FailedUnnamedTzifInvalid)?;
288 Ok(tz)
289 }