jiff 1.1.0

A date-time library that encourages you to jump into the pit of success. This library is heavily inspired by the Temporal project.
Documentation
use std::path::{Path, PathBuf};

use crate::tz::{TimeZone, TimeZoneDatabase};

static UNIX_LOCALTIME_PATH: &str = "/etc/localtime";

/// Attempts to find the default "system" time zone.
///
/// In the happy path, this looks at `/etc/localtime`, assumes it is a
/// symlink to something in `/usr/share/zoneinfo` and extracts out the IANA
/// time zone name. From there, it looks up that time zone name in the given
/// time zone database.
///
/// When `/etc/localtime` isn't a symlink, or if the time zone couldn't be
/// found in the given time zone database, then `/etc/localtime` is read
/// directly as a TZif data file describing a time zone. The reason why we
/// try to avoid this is because a TZif data file does not contain the time
/// zone name. And we *really* want the time zone name as it is the only
/// standardized way to roundtrip a datetime in a particular time zone.
pub(super) fn get(db: &TimeZoneDatabase) -> Option<TimeZone> {
    read(db, UNIX_LOCALTIME_PATH)
}

/// Given a path to a system default TZif file, return its corresponding
/// time zone.
///
/// In Unix, we attempt to read it as a symlink and extract an IANA time zone
/// identifier. If that ID exists in the tzdb, we return that. Otherwise, we
/// read the TZif file as an unnamed time zone.
pub(super) fn read(db: &TimeZoneDatabase, path: &str) -> Option<TimeZone> {
    if let Some(tz) = read_link_to_zoneinfo(db, path) {
        return Some(tz);
    }
    trace!(
        "failed to find time zone name using Unix-specific heuristics, \
         attempting to read {UNIX_LOCALTIME_PATH} as unnamed time zone",
    );
    match super::read_unnamed_tzif_file(path) {
        Ok(tz) => Some(tz),
        Err(_err) => {
            trace!("failed to read {path} as unnamed time zone: {_err}");
            None
        }
    }
}

/// Attempt to determine the time zone name from the symlink path given.
///
/// This follows up to 10 symlinks in a chain, checking each link target for a
/// known zoneinfo path before following it further.
///
/// If the path isn't a symlink or if none of the followed targets were
/// recognized as pointing into a known zoneinfo database, then this returns
/// `None` (and emits some log messages).
fn read_link_to_zoneinfo(
    db: &TimeZoneDatabase,
    path: &str,
) -> Option<TimeZone> {
    const MAX_HOPS: usize = 10;

    let mut current = PathBuf::from(path);
    for _ in 0..MAX_HOPS {
        let target = match std::fs::read_link(&current) {
            Ok(target) => target,
            Err(_err) => {
                trace!(
                    "failed to read {} as symbolic link: {_err}",
                    current.display(),
                );
                return None;
            }
        };
        if let Some(tz) = lookup_zoneinfo_target(db, &current, &target) {
            return Some(tz);
        }
        current = if target.is_absolute() {
            target
        } else if let Some(parent) = current.parent() {
            parent.join(target)
        } else {
            target
        };
    }
    trace!(
        "exceeded maximum symlink depth ({MAX_HOPS}) while resolving \
         {path:?}, so could not determine time zone name from symlink",
    );
    None
}

/// Attempt to extract an IANA time zone name from a single symlink target and
/// look it up in the given database.
fn lookup_zoneinfo_target(
    db: &TimeZoneDatabase,
    _path: &Path,
    target: &Path,
) -> Option<TimeZone> {
    let Some(target) = target.to_str() else {
        trace!("symlink target {target:?} for {_path:?} is not valid UTF-8");
        return None;
    };
    let needle = "zoneinfo/";
    let Some(rpos) = target.rfind(needle) else {
        trace!(
            "could not find {needle:?} in symlink target {target:?} \
             for path {_path:?}, so could not determine time zone name \
             from symlink",
        );
        return None;
    };
    let name = &target[rpos + needle.len()..];
    trace!(
        "extracted {name:?} from symlink target {target:?} \
         for path {_path:?} and assuming it is an IANA time zone name",
    );
    let tz = match db.get(name) {
        Ok(tz) => tz,
        Err(_err) => {
            trace!(
                "using {name:?} symlink target {target:?} \
                 for path {_path:?} as time zone name, \
                 but failed to find time zone with that name in \
                 zoneinfo database {db:?}",
            );
            return None;
        }
    };
    Some(tz)
}

#[cfg(not(miri))]
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn get_time_zone_name_etc_localtime() {
        let _ = crate::logging::Logger::init();

        let db = crate::tz::db();
        if crate::tz::db().is_definitively_empty() {
            return;
        }
        let path = std::path::Path::new("/etc/localtime");
        if !path.exists() {
            return;
        }
        // It's hard to assert much other than that a time zone could be
        // successfully constructed. Presumably this may fail in certain
        // environments, but hopefully the `is_definitively_empty` check above
        // will filter most out.
        assert!(get(db).is_some());
    }

    #[test]
    fn read_chained_localtime_symlink() {
        let _ = crate::logging::Logger::init();

        let db = crate::tz::db();
        if db.is_definitively_empty() {
            return;
        }

        let tmpdir =
            tempfile::TempDir::with_prefix("jiff-unix-localtime-").unwrap();
        let etc = tmpdir.path().join("etc");
        let host_etc = tmpdir.path().join("run/host/etc");
        std::fs::create_dir_all(&etc).unwrap();
        std::fs::create_dir_all(&host_etc).unwrap();

        let host_localtime = host_etc.join("localtime");
        std::os::unix::fs::symlink(
            "../usr/share/zoneinfo/America/New_York",
            &host_localtime,
        )
        .unwrap();

        let localtime = etc.join("localtime");
        std::os::unix::fs::symlink(&host_localtime, &localtime).unwrap();

        let tz = read(db, localtime.to_str().unwrap()).unwrap();
        assert_eq!(tz.iana_name(), Some("America/New_York"));
    }

    #[test]
    fn read_chained_localtime_relative_intermediate() {
        let _ = crate::logging::Logger::init();

        let db = crate::tz::db();
        if db.is_definitively_empty() {
            return;
        }

        let tmpdir =
            tempfile::TempDir::with_prefix("jiff-unix-localtime-").unwrap();
        let etc = tmpdir.path().join("etc");
        let host_etc = tmpdir.path().join("run/host/etc");
        let host_share = tmpdir.path().join("run/share");
        std::fs::create_dir_all(&etc).unwrap();
        std::fs::create_dir_all(&host_etc).unwrap();
        std::fs::create_dir_all(&host_share).unwrap();

        let third = host_share.join("localtime");
        std::os::unix::fs::symlink("../zoneinfo/America/New_York", &third)
            .unwrap();

        let second = host_etc.join("localtime");
        std::os::unix::fs::symlink("../../share/localtime", &second).unwrap();

        let first = etc.join("localtime");
        std::os::unix::fs::symlink("../run/host/etc/localtime", &first)
            .unwrap();

        let tz = read(db, first.to_str().unwrap()).unwrap();
        assert_eq!(tz.iana_name(), Some("America/New_York"));
    }

    #[test]
    fn read_link_to_zoneinfo_hop_limit_and_cycle() {
        let _ = crate::logging::Logger::init();

        let db = crate::tz::db();
        if db.is_definitively_empty() {
            return;
        }

        let tmpdir =
            tempfile::TempDir::with_prefix("jiff-unix-localtime-").unwrap();

        // Build a chain of 11 symlinks: link0 -> link1 -> ... -> link10 ->
        // ../usr/share/zoneinfo/America/New_York.
        let link10 = tmpdir.path().join("link10");
        std::os::unix::fs::symlink(
            "../usr/share/zoneinfo/America/New_York",
            &link10,
        )
        .unwrap();
        for i in (0..10).rev() {
            let from = tmpdir.path().join(std::format!("link{i}"));
            let to = std::format!("link{}", i + 1);
            std::os::unix::fs::symlink(&to, &from).unwrap();
        }

        // Direct link (hop 1).
        let tz = read_link_to_zoneinfo(db, link10.to_str().unwrap()).unwrap();
        assert_eq!(tz.iana_name(), Some("America/New_York"));

        // Name found on hop 10.
        let link1 = tmpdir.path().join("link1");
        let tz = read_link_to_zoneinfo(db, link1.to_str().unwrap()).unwrap();
        assert_eq!(tz.iana_name(), Some("America/New_York"));

        // Name first exposed on hop 11 exceeds the limit.
        let link0 = tmpdir.path().join("link0");
        assert!(read_link_to_zoneinfo(db, link0.to_str().unwrap()).is_none());

        // Symlink cycle yields None.
        let cycle_a = tmpdir.path().join("cycle_a");
        let cycle_b = tmpdir.path().join("cycle_b");
        std::os::unix::fs::symlink("cycle_b", &cycle_a).unwrap();
        std::os::unix::fs::symlink("cycle_a", &cycle_b).unwrap();
        assert!(
            read_link_to_zoneinfo(db, cycle_a.to_str().unwrap()).is_none()
        );
    }
}