| 1 |
use alloc::{string::String, vec, vec::Vec}; |
| 2 |
|
| 3 |
use std::{ |
| 4 |
ffi::OsStr, |
| 5 |
fs::File, |
| 6 |
io::Read, |
| 7 |
path::{Component, Path, PathBuf}, |
| 8 |
sync::{ |
| 9 |
atomic::{AtomicUsize, Ordering}, |
| 10 |
Arc, RwLock, |
| 11 |
}, |
| 12 |
time::Duration, |
| 13 |
}; |
| 14 |
|
| 15 |
use crate::{ |
| 16 |
error::{tz::db::Error as E, Error}, |
| 17 |
timestamp::Timestamp, |
| 18 |
tz::{db::special_time_zone, TimeZone, TimeZoneNameIter}, |
| 19 |
util::{self, cache::Expiration, parse, utf8}, |
| 20 |
}; |
| 21 |
|
| 22 |
const DEFAULT_TTL: Duration = Duration::new(5 * 60, 0); |
| 23 |
|
| 24 |
#[cfg(unix)] |
| 25 |
static ZONEINFO_DIRECTORIES: &[&str] = |
| 26 |
&["/usr/share/zoneinfo", "/usr/share/lib/zoneinfo", "/etc/zoneinfo"]; |
| 27 |
|
| 28 |
// In non-Unix environments, there is (as of 2025-05-17) no standard location |
| 29 |
// for the zoneinfo database. And we specifically do not search the Unix-style |
| 30 |
// directories because this can have weird and undesirable effects on Windows. |
| 31 |
// |
| 32 |
// Ref https://github.com/BurntSushi/jiff/issues/376 |
| 33 |
#[cfg(not(unix))] |
| 34 |
static ZONEINFO_DIRECTORIES: &[&str] = &[]; |
| 35 |
|
| 36 |
pub(crate) struct Database { |
| 37 |
dir: Option<PathBuf>, |
| 38 |
names: Option<ZoneInfoNames>, |
| 39 |
zones: RwLock<CachedZones>, |
| 40 |
} |
| 41 |
|
| 42 |
impl Database { |
| 43 |
pub(crate) fn from_env() -> Database { |
| 44 |
if let Some(tzdir) = std::env::var_os("TZDIR") { |
| 45 |
let tzdir = PathBuf::from(tzdir); |
| 46 |
trace!("opening zoneinfo database at TZDIR={}", tzdir.display()); |
| 47 |
match Database::from_dir(&tzdir) { |
| 48 |
Ok(db) => return db, |
| 49 |
Err(_err) => { |
| 50 |
// This is a WARN because it represents a failure to |
| 51 |
// satisfy a more direct request, which should be louder |
| 52 |
// than failures related to auto-detection. |
| 53 |
warn!("failed opening TZDIR={}: {_err}", tzdir.display()); |
| 54 |
// fall through to attempt default directories |
| 55 |
} |
| 56 |
} |
| 57 |
} |
| 58 |
for dir in ZONEINFO_DIRECTORIES { |
| 59 |
let tzdir = Path::new(dir); |
| 60 |
trace!("opening zoneinfo database at {}", tzdir.display()); |
| 61 |
match Database::from_dir(&tzdir) { |
| 62 |
Ok(db) => return db, |
| 63 |
Err(_err) => { |
| 64 |
trace!("failed opening {}: {_err}", tzdir.display()); |
| 65 |
} |
| 66 |
} |
| 67 |
} |
| 68 |
debug!( |
| 69 |
"could not find zoneinfo database at any of the following \ |
| 70 |
paths: {}", |
| 71 |
ZONEINFO_DIRECTORIES.join(", "), |
| 72 |
); |
| 73 |
Database::none() |
| 74 |
} |
| 75 |
|
| 76 |
pub(crate) fn from_dir(dir: &Path) -> Result<Database, Error> { |
| 77 |
let names = Some(ZoneInfoNames::new(dir)?); |
| 78 |
let zones = RwLock::new(CachedZones::new()); |
| 79 |
Ok(Database { dir: Some(dir.to_path_buf()), names, zones }) |
| 80 |
} |
| 81 |
|
| 82 |
/// Creates a "dummy" zoneinfo database in which all lookups fail. |
| 83 |
pub(crate) fn none() -> Database { |
| 84 |
let dir = None; |
| 85 |
let names = None; |
| 86 |
let zones = RwLock::new(CachedZones::new()); |
| 87 |
Database { dir, names, zones } |
| 88 |
} |
| 89 |
|
| 90 |
pub(crate) fn reset(&self) { |
| 91 |
let mut zones = self.zones.write().unwrap(); |
| 92 |
if let Some(ref names) = self.names { |
| 93 |
names.reset(); |
| 94 |
} |
| 95 |
zones.reset(); |
| 96 |
} |
| 97 |
|
| 98 |
pub(crate) fn get(&self, query: &str) -> Option<TimeZone> { |
| 99 |
if let Some(tz) = special_time_zone(query) { |
| 100 |
return Some(tz); |
| 101 |
} |
| 102 |
// If we couldn't build any time zone names, then every lookup will |
| 103 |
// fail. So just bail now. |
| 104 |
let names = self.names.as_ref()?; |
| 105 |
// The fast path is when the query matches a pre-existing unexpired |
| 106 |
// time zone. |
| 107 |
{ |
| 108 |
let zones = self.zones.read().unwrap(); |
| 109 |
if let Some(czone) = zones.get(query) { |
| 110 |
if !czone.is_expired() { |
| 111 |
trace!( |
| 112 |
"for time zone query `{query}`, \ |
| 113 |
found cached zone `{}` \ |
| 114 |
(expiration={}, last_modified={:?})", |
| 115 |
czone.tz.diagnostic_name(), |
| 116 |
czone.expiration, |
| 117 |
czone.last_modified, |
| 118 |
); |
| 119 |
return Some(czone.tz.clone()); |
| 120 |
} |
| 121 |
} |
| 122 |
} |
| 123 |
// At this point, one of three possible cases is true: |
| 124 |
// |
| 125 |
// 1. The given query does not match any time zone in this database. |
| 126 |
// 2. A time zone exists, but isn't cached. |
| 127 |
// 3. A zime exists and is cached, but needs to be revalidated. |
| 128 |
// |
| 129 |
// While (3) is probably the common case since our TTLs are pretty |
| 130 |
// short, both (2) and (3) require write access. Thus we rule out (1) |
| 131 |
// before acquiring a write lock on the entire database. Plus, we'll |
| 132 |
// need the zone info for case (2) and possibly for (3) if cache |
| 133 |
// revalidation fails. |
| 134 |
// |
| 135 |
// I feel kind of bad about all this because it seems to me like there |
| 136 |
// is too much work being done while holding on to the write lock. |
| 137 |
// In particular, it seems like bad juju to do any I/O of any kind |
| 138 |
// while holding any lock at all. I think I could design something |
| 139 |
// that avoids doing I/O while holding a lock, but it seems a lot more |
| 140 |
// complicated. (And what happens if the I/O becomes outdated by the |
| 141 |
// time you acquire the lock?) |
| 142 |
let info = names.get(query)?; |
| 143 |
let mut zones = self.zones.write().unwrap(); |
| 144 |
let ttl = zones.ttl; |
| 145 |
match zones.get_zone_index(query) { |
| 146 |
Ok(i) => { |
| 147 |
let czone = &mut zones.zones[i]; |
| 148 |
if czone.revalidate(&info, ttl) { |
| 149 |
// Metadata on the file didn't change, so we assume the |
| 150 |
// file hasn't either. |
| 151 |
return Some(czone.tz.clone()); |
| 152 |
} |
| 153 |
// Revalidation failed. Re-read the TZif data. |
| 154 |
let czone = match CachedTimeZone::new(&info, zones.ttl) { |
| 155 |
Ok(czone) => czone, |
| 156 |
Err(_err) => { |
| 157 |
warn!( |
| 158 |
"failed to re-cache time zone from file {}: {_err}", |
| 159 |
info.inner.full.display(), |
| 160 |
); |
| 161 |
return None; |
| 162 |
} |
| 163 |
}; |
| 164 |
let tz = czone.tz.clone(); |
| 165 |
zones.zones[i] = czone; |
| 166 |
Some(tz) |
| 167 |
} |
| 168 |
Err(i) => { |
| 169 |
let czone = match CachedTimeZone::new(&info, ttl) { |
| 170 |
Ok(czone) => czone, |
| 171 |
Err(_err) => { |
| 172 |
warn!( |
| 173 |
"failed to cache time zone from file {}: {_err}", |
| 174 |
info.inner.full.display(), |
| 175 |
); |
| 176 |
return None; |
| 177 |
} |
| 178 |
}; |
| 179 |
let tz = czone.tz.clone(); |
| 180 |
zones.zones.insert(i, czone); |
| 181 |
Some(tz) |
| 182 |
} |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
pub(crate) fn available<'d>(&'d self) -> TimeZoneNameIter<'d> { |
| 187 |
let Some(names) = self.names.as_ref() else { |
| 188 |
return TimeZoneNameIter::empty(); |
| 189 |
}; |
| 190 |
TimeZoneNameIter::from_iter(names.available().into_iter()) |
| 191 |
} |
| 192 |
|
| 193 |
pub(crate) fn is_definitively_empty(&self) -> bool { |
| 194 |
self.names.is_none() |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
impl core::fmt::Debug for Database { |
| 199 |
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { |
| 200 |
f.write_str("ZoneInfo(")?; |
| 201 |
if let Some(ref dir) = self.dir { |
| 202 |
core::fmt::Display::fmt(&dir.display(), f)?; |
| 203 |
} else { |
| 204 |
f.write_str("unavailable")?; |
| 205 |
} |
| 206 |
f.write_str(")") |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
#[derive(Debug)] |
| 211 |
struct CachedZones { |
| 212 |
zones: Vec<CachedTimeZone>, |
| 213 |
ttl: Duration, |
| 214 |
} |
| 215 |
|
| 216 |
impl CachedZones { |
| 217 |
const DEFAULT_TTL: Duration = DEFAULT_TTL; |
| 218 |
|
| 219 |
fn new() -> CachedZones { |
| 220 |
CachedZones { zones: vec![], ttl: CachedZones::DEFAULT_TTL } |
| 221 |
} |
| 222 |
|
| 223 |
fn get(&self, query: &str) -> Option<&CachedTimeZone> { |
| 224 |
self.get_zone_index(query).ok().map(|i| &self.zones[i]) |
| 225 |
} |
| 226 |
|
| 227 |
fn get_zone_index(&self, query: &str) -> Result<usize, usize> { |
| 228 |
// The common case is that our query matches the time zone name case |
| 229 |
// sensitively, so check for that first. It's a bit cheaper than doing |
| 230 |
// a case insensitive search. |
| 231 |
if let Ok(i) = self |
| 232 |
.zones |
| 233 |
.binary_search_by(|zone| zone.name.original().cmp(&query)) |
| 234 |
{ |
| 235 |
return Ok(i); |
| 236 |
} |
| 237 |
self.zones.binary_search_by(|zone| { |
| 238 |
utf8::cmp_ignore_ascii_case(zone.name.lower(), query) |
| 239 |
}) |
| 240 |
} |
| 241 |
|
| 242 |
fn reset(&mut self) { |
| 243 |
self.zones.clear(); |
| 244 |
} |
| 245 |
} |
| 246 |
|
| 247 |
#[derive(Clone, Debug)] |
| 248 |
struct CachedTimeZone { |
| 249 |
tz: TimeZone, |
| 250 |
name: ZoneInfoName, |
| 251 |
expiration: Expiration, |
| 252 |
last_modified: Option<Timestamp>, |
| 253 |
} |
| 254 |
|
| 255 |
impl CachedTimeZone { |
| 256 |
/// Create a new cached time zone. |
| 257 |
/// |
| 258 |
/// The `info` says which time zone to create and where to find it. The |
| 259 |
/// `ttl` says how long the cached time zone should minimally remain fresh |
| 260 |
/// for. |
| 261 |
fn new( |
| 262 |
info: &ZoneInfoName, |
| 263 |
ttl: Duration, |
| 264 |
) -> Result<CachedTimeZone, Error> { |
| 265 |
fn imp( |
| 266 |
info: &ZoneInfoName, |
| 267 |
ttl: Duration, |
| 268 |
) -> Result<CachedTimeZone, Error> { |
| 269 |
let path = info.path(); |
| 270 |
let mut file = |
| 271 |
File::open(path).map_err(|e| Error::io(e).path(path))?; |
| 272 |
let mut data = vec![]; |
| 273 |
file.read_to_end(&mut data) |
| 274 |
.map_err(|e| Error::io(e).path(path))?; |
| 275 |
let tz = TimeZone::tzif(&info.inner.original, &data) |
| 276 |
.map_err(|e| e.path(path))?; |
| 277 |
let name = info.clone(); |
| 278 |
let last_modified = util::fs::last_modified_from_file(path, &file); |
| 279 |
let expiration = Expiration::after(ttl); |
| 280 |
Ok(CachedTimeZone { tz, name, expiration, last_modified }) |
| 281 |
} |
| 282 |
|
| 283 |
let result = imp(info, ttl); |
| 284 |
info.set_validity(result.is_ok()); |
| 285 |
result |
| 286 |
} |
| 287 |
|
| 288 |
/// Returns true if this time zone has gone stale and should, at minimum, |
| 289 |
/// be revalidated. |
| 290 |
fn is_expired(&self) -> bool { |
| 291 |
self.expiration.is_expired() |
| 292 |
} |
| 293 |
|
| 294 |
/// Attempts to revalidate this cached time zone. |
| 295 |
/// |
| 296 |
/// Upon successful revalidation (that is, the cached time zone is still |
| 297 |
/// fresh and okay to use), this returns true. Otherwise, the cached time |
| 298 |
/// zone should be considered stale and must be re-created. |
| 299 |
/// |
| 300 |
/// Note that technically another layer of revalidation could be done. |
| 301 |
/// For example, we could keep a checksum of the TZif data, and only |
| 302 |
/// consider rebuilding the time zone when the checksum changes. But I |
| 303 |
/// think the last modified metadata will in practice be good enough, and |
| 304 |
/// parsing a TZif file should be quite fast. |
| 305 |
fn revalidate(&mut self, info: &ZoneInfoName, ttl: Duration) -> bool { |
| 306 |
// If we started with no last modified timestamp, then I guess we |
| 307 |
// should always fail revalidation? I suppose a case could be made to |
| 308 |
// do the opposite: always pass revalidation. |
| 309 |
let Some(old_last_modified) = self.last_modified else { |
| 310 |
trace!( |
| 311 |
"revalidation for {} failed because old last modified time \ |
| 312 |
is unavailable", |
| 313 |
info.inner.full.display(), |
| 314 |
); |
| 315 |
return false; |
| 316 |
}; |
| 317 |
let Some(new_last_modified) = |
| 318 |
util::fs::last_modified_from_path(info.path()) |
| 319 |
else { |
| 320 |
trace!( |
| 321 |
"revalidation for {} failed because new last modified time \ |
| 322 |
is unavailable", |
| 323 |
info.inner.full.display(), |
| 324 |
); |
| 325 |
return false; |
| 326 |
}; |
| 327 |
// We consider any change to invalidate cache. |
| 328 |
if old_last_modified != new_last_modified { |
| 329 |
trace!( |
| 330 |
"revalidation for {} failed because last modified times \ |
| 331 |
do not match: old = {} != {} = new", |
| 332 |
info.inner.full.display(), |
| 333 |
old_last_modified, |
| 334 |
new_last_modified, |
| 335 |
); |
| 336 |
return false; |
| 337 |
} |
| 338 |
trace!( |
| 339 |
"revalidation for {} succeeded because last modified times \ |
| 340 |
match: old = {} == {} = new", |
| 341 |
info.inner.full.display(), |
| 342 |
old_last_modified, |
| 343 |
new_last_modified, |
| 344 |
); |
| 345 |
self.expiration = Expiration::after(ttl); |
| 346 |
true |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
/// A collection of time zone names extracted from a zoneinfo directory. |
| 351 |
/// |
| 352 |
/// Each time zone name maps to a full path on the file system corresponding |
| 353 |
/// to the TZif formatted data file for that time zone. |
| 354 |
/// |
| 355 |
/// This type is responsible not just for providing the names, but also for |
| 356 |
/// updating them periodically. |
| 357 |
#[derive(Debug)] |
| 358 |
struct ZoneInfoNames { |
| 359 |
inner: RwLock<ZoneInfoNamesInner>, |
| 360 |
} |
| 361 |
|
| 362 |
#[derive(Debug)] |
| 363 |
struct ZoneInfoNamesInner { |
| 364 |
/// The directory from which we collected time zone names. |
| 365 |
dir: PathBuf, |
| 366 |
/// All available names from the `zoneinfo` directory. |
| 367 |
/// |
| 368 |
/// Each name corresponds to the suffix of a file path |
| 369 |
/// starting with `dir`. For example, `America/New_York` in |
| 370 |
/// `/usr/share/zoneinfo/America/New_York`. Each name also has a normalized |
| 371 |
/// lowercase version of the name for easy case insensitive lookup. |
| 372 |
names: Vec<ZoneInfoName>, |
| 373 |
/// The expiration time of this cached value. |
| 374 |
/// |
| 375 |
/// Note that this is a necessary but not sufficient criterion for |
| 376 |
/// invalidating the cached value. |
| 377 |
ttl: Duration, |
| 378 |
/// The time at which the data in `names` becomes stale. |
| 379 |
expiration: Expiration, |
| 380 |
} |
| 381 |
|
| 382 |
impl ZoneInfoNames { |
| 383 |
/// The default amount of time to wait before checking for added/removed |
| 384 |
/// time zones. |
| 385 |
/// |
| 386 |
/// Note that this TTL is a necessary but not sufficient criterion to |
| 387 |
/// provoke cache invalidation. Namely, since we don't expect the set of |
| 388 |
/// possible time zone names to change often, we only invalidate the cache |
| 389 |
/// under these circumstances: |
| 390 |
/// |
| 391 |
/// 1. The TTL or more has passed since the last time the names were |
| 392 |
/// attempted to be refreshed (even if it wasn't successful). |
| 393 |
/// 2. A name lookup is attempted and it isn't found. This is required |
| 394 |
/// because otherwise there isn't much point in refreshing the names. |
| 395 |
/// |
| 396 |
/// This logic does not deal as well with removals from the underlying time |
| 397 |
/// zone database. That in turn is covered by the TTL on constructing the |
| 398 |
/// `TimeZone` values themselves. |
| 399 |
/// |
| 400 |
/// We could just use the second criterion on its own, but we require the |
| 401 |
/// TTL to expire out of "good sense." Namely, if there is something borked |
| 402 |
/// in the environment, the TTL will prevent doing a full scan of the |
| 403 |
/// zoneinfo directory for every missed time zone lookup. |
| 404 |
const DEFAULT_TTL: Duration = DEFAULT_TTL; |
| 405 |
|
| 406 |
/// Create a new collection of names from the zoneinfo database directory |
| 407 |
/// given. |
| 408 |
/// |
| 409 |
/// If no names of time zones with corresponding TZif data files could be |
| 410 |
/// found in the given directory, then an error is returned. |
| 411 |
fn new(dir: &Path) -> Result<ZoneInfoNames, Error> { |
| 412 |
let names = walk(dir)?; |
| 413 |
let dir = dir.to_path_buf(); |
| 414 |
let ttl = ZoneInfoNames::DEFAULT_TTL; |
| 415 |
let expiration = Expiration::after(ttl); |
| 416 |
let inner = ZoneInfoNamesInner { dir, names, ttl, expiration }; |
| 417 |
Ok(ZoneInfoNames { inner: RwLock::new(inner) }) |
| 418 |
} |
| 419 |
|
| 420 |
/// Attempts to find the name entry for the given query using a case |
| 421 |
/// insensitive search. |
| 422 |
/// |
| 423 |
/// If no match is found and the data is stale, then the time zone names |
| 424 |
/// are refreshed from the file system before doing another check. |
| 425 |
fn get(&self, query: &str) -> Option<ZoneInfoName> { |
| 426 |
{ |
| 427 |
let inner = self.inner.read().unwrap(); |
| 428 |
if let Some(zone_info_name) = inner.get(query) { |
| 429 |
return Some(zone_info_name); |
| 430 |
} |
| 431 |
drop(inner); // unlock |
| 432 |
} |
| 433 |
let mut inner = self.inner.write().unwrap(); |
| 434 |
inner.attempt_refresh(); |
| 435 |
inner.get(query) |
| 436 |
} |
| 437 |
|
| 438 |
/// Returns all available time zone names after attempting a refresh of |
| 439 |
/// the underlying data if it's stale. |
| 440 |
fn available(&self) -> Vec<String> { |
| 441 |
let mut inner = self.inner.write().unwrap(); |
| 442 |
inner.attempt_refresh(); |
| 443 |
inner.available() |
| 444 |
} |
| 445 |
|
| 446 |
fn reset(&self) { |
| 447 |
self.inner.write().unwrap().reset(); |
| 448 |
} |
| 449 |
} |
| 450 |
|
| 451 |
impl ZoneInfoNamesInner { |
| 452 |
/// Attempts to find the name entry for the given query using a case |
| 453 |
/// insensitive search. |
| 454 |
/// |
| 455 |
/// `None` is returned if one isn't found. |
| 456 |
fn get(&self, query: &str) -> Option<ZoneInfoName> { |
| 457 |
self.names |
| 458 |
.binary_search_by(|n| { |
| 459 |
utf8::cmp_ignore_ascii_case(&n.inner.lower, query) |
| 460 |
}) |
| 461 |
.ok() |
| 462 |
.map(|i| self.names[i].clone()) |
| 463 |
} |
| 464 |
|
| 465 |
/// Returns all available time zone names. |
| 466 |
fn available(&self) -> Vec<String> { |
| 467 |
self.names |
| 468 |
.iter() |
| 469 |
.filter(|n| n.is_valid()) |
| 470 |
.map(|n| n.inner.original.clone()) |
| 471 |
.collect() |
| 472 |
} |
| 473 |
|
| 474 |
/// Attempts a refresh, but only follows through if the TTL has been |
| 475 |
/// exceeded. |
| 476 |
/// |
| 477 |
/// The caller must ensure that the other cache invalidation criteria |
| 478 |
/// have been upheld. For example, this should only be called for a missed |
| 479 |
/// zone name lookup. |
| 480 |
fn attempt_refresh(&mut self) { |
| 481 |
if self.expiration.is_expired() { |
| 482 |
self.refresh(); |
| 483 |
} |
| 484 |
} |
| 485 |
|
| 486 |
/// Forcefully refreshes the cached names with possibly new data from disk. |
| 487 |
/// If an error occurs when fetching the names, then no names are updated |
| 488 |
/// (but the `expires_at` is updated). This will also emit a warning log on |
| 489 |
/// failure. |
| 490 |
fn refresh(&mut self) { |
| 491 |
// PERF: Should we try to move this `walk` call to run outside of a |
| 492 |
// lock? It probably happens pretty rarely, so it might not matter. |
| 493 |
let result = walk(&self.dir); |
| 494 |
self.expiration = Expiration::after(self.ttl); |
| 495 |
match result { |
| 496 |
Ok(names) => { |
| 497 |
self.names = names; |
| 498 |
} |
| 499 |
Err(_err) => { |
| 500 |
warn!( |
| 501 |
"failed to refresh zoneinfo time zone name cache \ |
| 502 |
for {}: {_err}", |
| 503 |
self.dir.display(), |
| 504 |
) |
| 505 |
} |
| 506 |
} |
| 507 |
} |
| 508 |
|
| 509 |
/// Resets the state such that the next lookup is guaranteed to force a |
| 510 |
/// cache refresh, and that it is impossible for any data to be stale. |
| 511 |
fn reset(&mut self) { |
| 512 |
// This will force the next lookup to fail. |
| 513 |
self.names.clear(); |
| 514 |
// And this will force the next failed lookup to result in a refresh. |
| 515 |
self.expiration = Expiration::expired(); |
| 516 |
} |
| 517 |
} |
| 518 |
|
| 519 |
/// A single TZif entry in a zoneinfo database directory. |
| 520 |
#[derive(Clone, Debug)] |
| 521 |
struct ZoneInfoName { |
| 522 |
inner: Arc<ZoneInfoNameInner>, |
| 523 |
} |
| 524 |
|
| 525 |
#[derive(Debug)] |
| 526 |
struct ZoneInfoNameInner { |
| 527 |
/// A file path resolvable to the corresponding file relative to the |
| 528 |
/// working directory of this program. |
| 529 |
/// |
| 530 |
/// Should we canonicalize this to a absolute path? I guess in practice it |
| 531 |
/// is an absolute path in most cases. |
| 532 |
full: PathBuf, |
| 533 |
/// The original name of this time zone taken from the file path with |
| 534 |
/// no additional changes. |
| 535 |
original: String, |
| 536 |
/// The lowercase version of `original`. This is how we determine name |
| 537 |
/// equality. |
| 538 |
lower: String, |
| 539 |
/// The known validity state of this time zone name. `0` means unknown (and |
| 540 |
/// thus we need to check), `1` means "presumably valid" and `2` means |
| 541 |
/// "known invalid." The "presumably valid" means that the file has a |
| 542 |
/// 4-byte TZif header and the odds of a false positive a low enough that |
| 543 |
/// we can and should behave as if that file is actually TZif and thus a |
| 544 |
/// valid IANA time zone identifier. |
| 545 |
validity: AtomicUsize, |
| 546 |
} |
| 547 |
|
| 548 |
impl ZoneInfoName { |
| 549 |
/// Create a new time zone info name. |
| 550 |
/// |
| 551 |
/// `base` should corresponding to the zoneinfo directory from which the |
| 552 |
/// suffix `time_zone_name` path was returned. |
| 553 |
fn new(base: &Path, time_zone_name: &Path) -> Result<ZoneInfoName, Error> { |
| 554 |
let full = base.join(time_zone_name); |
| 555 |
let original = iana_name_from_path(time_zone_name) |
| 556 |
.map_err(|err| Error::from(err).path(base))?; |
| 557 |
let lower = original.to_ascii_lowercase(); |
| 558 |
let inner = ZoneInfoNameInner { |
| 559 |
full, |
| 560 |
original, |
| 561 |
lower, |
| 562 |
validity: AtomicUsize::new(ZONE_INFO_NAME_UNKNOWN), |
| 563 |
}; |
| 564 |
Ok(ZoneInfoName { inner: Arc::new(inner) }) |
| 565 |
} |
| 566 |
|
| 567 |
/// Returns the path to the corresponding (presumed) TZif file. |
| 568 |
fn path(&self) -> &Path { |
| 569 |
&self.inner.full |
| 570 |
} |
| 571 |
|
| 572 |
/// Returns the original name of this time zone. |
| 573 |
fn original(&self) -> &str { |
| 574 |
&self.inner.original |
| 575 |
} |
| 576 |
|
| 577 |
/// Returns the lowercase name of this time zone. |
| 578 |
fn lower(&self) -> &str { |
| 579 |
&self.inner.lower |
| 580 |
} |
| 581 |
|
| 582 |
/// Returns true if it is presumed that this points to a valid TZif file. |
| 583 |
/// |
| 584 |
/// The result of this function may use a cached value. |
| 585 |
fn is_valid(&self) -> bool { |
| 586 |
let validity = self.inner.validity.load(Ordering::Relaxed); |
| 587 |
if validity == ZONE_INFO_NAME_VALID { |
| 588 |
return true; |
| 589 |
} else if validity == ZONE_INFO_NAME_INVALID { |
| 590 |
return false; |
| 591 |
} |
| 592 |
if self.is_valid_impl() { |
| 593 |
self.inner.validity.store(ZONE_INFO_NAME_VALID, Ordering::Relaxed); |
| 594 |
true |
| 595 |
} else { |
| 596 |
self.inner |
| 597 |
.validity |
| 598 |
.store(ZONE_INFO_NAME_INVALID, Ordering::Relaxed); |
| 599 |
false |
| 600 |
} |
| 601 |
} |
| 602 |
|
| 603 |
/// Marks this zone info name as known to be valid or invalid. |
| 604 |
/// |
| 605 |
/// e.g., After doing a successful time zone lookup. |
| 606 |
fn set_validity(&self, is_valid: bool) { |
| 607 |
let validity = if is_valid { |
| 608 |
ZONE_INFO_NAME_VALID |
| 609 |
} else { |
| 610 |
ZONE_INFO_NAME_INVALID |
| 611 |
}; |
| 612 |
self.inner.validity.store(validity, Ordering::Relaxed); |
| 613 |
} |
| 614 |
|
| 615 |
/// Performs the actual validity check. |
| 616 |
/// |
| 617 |
/// This is generally only needed for APIs like |
| 618 |
/// `TimeZoneDatabase::available()`, where we don't want to load every time |
| 619 |
/// zone into memory but we also don't want to return IANA time zone ids |
| 620 |
/// like `zone.tab`. (Because a `/usr/share/zoneinfo` directory might have |
| 621 |
/// random junk in it.) |
| 622 |
fn is_valid_impl(&self) -> bool { |
| 623 |
let path = self.path(); |
| 624 |
let mut f = match File::open(path) { |
| 625 |
Ok(f) => f, |
| 626 |
Err(_err) => { |
| 627 |
trace!("failed to open {}: {_err}", path.display()); |
| 628 |
return false; |
| 629 |
} |
| 630 |
}; |
| 631 |
let mut buf = [0; 4]; |
| 632 |
if let Err(_err) = f.read_exact(&mut buf) { |
| 633 |
trace!( |
| 634 |
"failed to read first 4 bytes of {}: {_err}", |
| 635 |
path.display() |
| 636 |
); |
| 637 |
return false; |
| 638 |
} |
| 639 |
if !jcore::tz::tzif::is_possibly_tzif(&buf) { |
| 640 |
// This is a trace because it's perfectly normal for a |
| 641 |
// non-TZif file to be in a zoneinfo directory. But it could |
| 642 |
// still be potentially useful debugging info. |
| 643 |
trace!( |
| 644 |
"found file {} that isn't TZif since its first \ |
| 645 |
four bytes are {:?}", |
| 646 |
path.display(), |
| 647 |
crate::util::escape::Bytes(&buf), |
| 648 |
); |
| 649 |
return false; |
| 650 |
} |
| 651 |
true |
| 652 |
} |
| 653 |
} |
| 654 |
|
| 655 |
fn iana_name_from_path( |
| 656 |
path: &Path, |
| 657 |
) -> Result<String, crate::error::util::OsStrUtf8Error> { |
| 658 |
let mut name = String::new(); |
| 659 |
for component in path.components() { |
| 660 |
let Component::Normal(part) = component else { continue }; |
| 661 |
let part = parse::os_str_utf8(part)?; |
| 662 |
if !name.is_empty() { |
| 663 |
name.push('/'); |
| 664 |
} |
| 665 |
name.push_str(part); |
| 666 |
} |
| 667 |
Ok(name) |
| 668 |
} |
| 669 |
|
| 670 |
impl Eq for ZoneInfoName {} |
| 671 |
|
| 672 |
impl PartialEq for ZoneInfoName { |
| 673 |
fn eq(&self, rhs: &ZoneInfoName) -> bool { |
| 674 |
self.inner.lower == rhs.inner.lower |
| 675 |
} |
| 676 |
} |
| 677 |
|
| 678 |
impl Ord for ZoneInfoName { |
| 679 |
fn cmp(&self, rhs: &ZoneInfoName) -> core::cmp::Ordering { |
| 680 |
self.inner.lower.cmp(&rhs.inner.lower) |
| 681 |
} |
| 682 |
} |
| 683 |
|
| 684 |
impl PartialOrd for ZoneInfoName { |
| 685 |
fn partial_cmp(&self, rhs: &ZoneInfoName) -> Option<core::cmp::Ordering> { |
| 686 |
Some(self.cmp(rhs)) |
| 687 |
} |
| 688 |
} |
| 689 |
|
| 690 |
impl core::hash::Hash for ZoneInfoName { |
| 691 |
fn hash<H: core::hash::Hasher>(&self, state: &mut H) { |
| 692 |
self.inner.lower.hash(state); |
| 693 |
} |
| 694 |
} |
| 695 |
|
| 696 |
static ZONE_INFO_NAME_UNKNOWN: usize = 0; |
| 697 |
static ZONE_INFO_NAME_VALID: usize = 1; |
| 698 |
static ZONE_INFO_NAME_INVALID: usize = 2; |
| 699 |
|
| 700 |
/// Recursively walks the given directory and returns the names of all time |
| 701 |
/// zones found. |
| 702 |
/// |
| 703 |
/// This is guaranteed to return either one or more time zone names OR an |
| 704 |
/// error. That is, `Ok(vec![])` is an impossible result. |
| 705 |
/// |
| 706 |
/// This will attempt to collect as many names as possible, even if some I/O |
| 707 |
/// operations fail. |
| 708 |
/// |
| 709 |
/// The names returned are sorted in lexicographic order according to the |
| 710 |
/// lowercase form of each name. |
| 711 |
/// |
| 712 |
/// # Performance |
| 713 |
/// |
| 714 |
/// Note that this routine is written in a way that, at least on Unix, we |
| 715 |
/// should not be doing a syscall for every file. We need to do one for every |
| 716 |
/// directory, but that should be comparatively rare. It's done this way to |
| 717 |
/// avoid long initialization times when `/usr/share/zoneinfo` is on a slow |
| 718 |
/// file system. |
| 719 |
/// |
| 720 |
/// See: https://github.com/BurntSushi/jiff/issues/366 |
| 721 |
fn walk(start: &Path) -> Result<Vec<ZoneInfoName>, Error> { |
| 722 |
struct StackEntry { |
| 723 |
dir: PathBuf, |
| 724 |
depth: usize, |
| 725 |
} |
| 726 |
|
| 727 |
let mut first_err: Option<Error> = None; |
| 728 |
let mut seterr = |path: &Path, err: Error| { |
| 729 |
if first_err.is_none() { |
| 730 |
first_err = Some(err.path(path)); |
| 731 |
} |
| 732 |
}; |
| 733 |
|
| 734 |
let mut names = vec![]; |
| 735 |
let mut stack = vec![StackEntry { dir: start.to_path_buf(), depth: 0 }]; |
| 736 |
while let Some(StackEntry { dir, depth }) = stack.pop() { |
| 737 |
let readdir = match dir.read_dir() { |
| 738 |
Ok(readdir) => readdir, |
| 739 |
Err(err) => { |
| 740 |
info!( |
| 741 |
"error when reading {} as a directory: {err}", |
| 742 |
dir.display() |
| 743 |
); |
| 744 |
seterr(&dir, Error::io(err)); |
| 745 |
continue; |
| 746 |
} |
| 747 |
}; |
| 748 |
for result in readdir { |
| 749 |
let dent = match result { |
| 750 |
Ok(dent) => dent, |
| 751 |
Err(err) => { |
| 752 |
info!( |
| 753 |
"error when reading directory entry from {}: {err}", |
| 754 |
dir.display() |
| 755 |
); |
| 756 |
seterr(&dir, Error::io(err)); |
| 757 |
continue; |
| 758 |
} |
| 759 |
}; |
| 760 |
let file_type = match dent.file_type() { |
| 761 |
Ok(file_type) => file_type, |
| 762 |
Err(err) => { |
| 763 |
let path = dent.path(); |
| 764 |
info!( |
| 765 |
"error when reading file type from {}: {err}", |
| 766 |
path.display() |
| 767 |
); |
| 768 |
seterr(&path, Error::io(err)); |
| 769 |
continue; |
| 770 |
} |
| 771 |
}; |
| 772 |
let path = dent.path(); |
| 773 |
if file_type.is_dir() { |
| 774 |
// We ignore the `posix` and `right` directories because Jiff |
| 775 |
// doesn't care about them. They tend to bloat the output of |
| 776 |
// `TimeZoneDatabase::available()` for no appreciable reason. |
| 777 |
// If callers want to use them, they can do, e.g., |
| 778 |
// `TZDIR=/usr/share/zoneinfo/posix`. Moreover, they slow down |
| 779 |
// initialization time in environments with very slow file |
| 780 |
// systems. |
| 781 |
if depth == 0 |
| 782 |
&& (dent.file_name() == OsStr::new("posix") |
| 783 |
|| dent.file_name() == OsStr::new("right")) |
| 784 |
{ |
| 785 |
continue; |
| 786 |
} |
| 787 |
stack.push(StackEntry { |
| 788 |
dir: path, |
| 789 |
depth: depth.saturating_add(1), |
| 790 |
}); |
| 791 |
continue; |
| 792 |
} |
| 793 |
trace!( |
| 794 |
"zoneinfo database initialization visiting {path}", |
| 795 |
path = path.display(), |
| 796 |
); |
| 797 |
// We assume symlinks are files, although this may not be |
| 798 |
// appropriate. If we need to also handle the case when they're |
| 799 |
// directories, then we'll need to add symlink loop detection. |
| 800 |
|
| 801 |
let time_zone_name = match path.strip_prefix(start) { |
| 802 |
Ok(time_zone_name) => time_zone_name, |
| 803 |
// I think this error case is actually not possible. |
| 804 |
// Or if it does, is a legitimate bug. Namely, `start` |
| 805 |
// should always be a prefix of `path`, since `path` |
| 806 |
// is itself derived, ultimately, from `start`. |
| 807 |
Err(_err) => { |
| 808 |
trace!( |
| 809 |
"failed to extract time zone name from {} \ |
| 810 |
using {} as a base: {_err}", |
| 811 |
path.display(), |
| 812 |
start.display(), |
| 813 |
); |
| 814 |
seterr(&path, Error::from(E::ZoneInfoStripPrefix)); |
| 815 |
continue; |
| 816 |
} |
| 817 |
}; |
| 818 |
let zone_info_name = |
| 819 |
match ZoneInfoName::new(&start, time_zone_name) { |
| 820 |
Ok(zone_info_name) => zone_info_name, |
| 821 |
Err(err) => { |
| 822 |
seterr(&path, err); |
| 823 |
continue; |
| 824 |
} |
| 825 |
}; |
| 826 |
names.push(zone_info_name); |
| 827 |
} |
| 828 |
} |
| 829 |
if names.is_empty() { |
| 830 |
let err = first_err |
| 831 |
.take() |
| 832 |
.unwrap_or_else(|| Error::from(E::ZoneInfoNoTzifFiles)); |
| 833 |
Err(err) |
| 834 |
} else { |
| 835 |
// If we found at least one valid name, then we declare success and |
| 836 |
// drop any error we might have found. They do all get logged above |
| 837 |
// though. |
| 838 |
names.sort(); |
| 839 |
Ok(names) |
| 840 |
} |
| 841 |
} |
| 842 |
|
| 843 |
#[cfg(all( |
| 844 |
test, |
| 845 |
not(miri), |
| 846 |
not(target_arch = "wasm32"), |
| 847 |
not(target_arch = "wasm64"), |
| 848 |
))] |
| 849 |
mod tests { |
| 850 |
use super::*; |
| 851 |
|
| 852 |
fn mktempdir() -> tempfile::TempDir { |
| 853 |
tempfile::TempDir::with_prefix("jiff-zoneinfo-").unwrap() |
| 854 |
} |
| 855 |
|
| 856 |
#[test] |
| 857 |
fn iana_name_always_uses_slashes() { |
| 858 |
let name = ZoneInfoName::new( |
| 859 |
Path::new("/"), |
| 860 |
&Path::new("Asia").join("Tokyo"), |
| 861 |
) |
| 862 |
.unwrap(); |
| 863 |
assert_eq!("Asia/Tokyo", name.original()); |
| 864 |
} |
| 865 |
|
| 866 |
#[test] |
| 867 |
fn from_dir_uses_iana_name_separators() { |
| 868 |
let tmpdir = mktempdir(); |
| 869 |
let zoneinfo = tmpdir.path().join("zoneinfo"); |
| 870 |
let asia = zoneinfo.join("Asia"); |
| 871 |
std::fs::create_dir_all(&asia).unwrap(); |
| 872 |
std::fs::write( |
| 873 |
asia.join("Tokyo"), |
| 874 |
crate::tz::testdata::TzifTestFile::get("Asia/Tokyo").data, |
| 875 |
) |
| 876 |
.unwrap(); |
| 877 |
|
| 878 |
let db = Database::from_dir(&zoneinfo).unwrap(); |
| 879 |
assert!(db.get("Asia/Tokyo").is_some()); |
| 880 |
assert!(db.get(r"Asia\Tokyo").is_none()); |
| 881 |
} |
| 882 |
|
| 883 |
/// DEBUG COMMAND |
| 884 |
/// |
| 885 |
/// Takes environment variable `JIFF_DEBUG_ZONEINFO_DIR` as input and |
| 886 |
/// prints a list of all time zone names in the directory (one per line). |
| 887 |
/// |
| 888 |
/// Callers may also set `RUST_LOG` to get extra debugging output. |
| 889 |
#[test] |
| 890 |
fn debug_zoneinfo_walk() -> anyhow::Result<()> { |
| 891 |
let _ = crate::logging::Logger::init(); |
| 892 |
|
| 893 |
const ENV: &str = "JIFF_DEBUG_ZONEINFO_DIR"; |
| 894 |
let Some(val) = std::env::var_os(ENV) else { return Ok(()) }; |
| 895 |
let dir = PathBuf::from(val); |
| 896 |
let names = walk(&dir)?; |
| 897 |
for n in names { |
| 898 |
std::eprintln!("{}", n.inner.original); |
| 899 |
} |
| 900 |
Ok(()) |
| 901 |
} |
| 902 |
} |