WSL: bundle zoneinfo and self-repair empty /etc/localtime directories (#938) (#942)

This commit is contained in:
Precious Okwu authored and GitHub committed 2026-11-25 11:13:49 +01:00
1 parent 7e437bae77
commit c5459e6bc1
12 files changed
+1119 -8

No files matched your search

+4
View File
@@ -34,6 +34,10 @@ if [ -n "$ro_state" ]; then
exit 2
fi
mkdir -p "$HOME" /var/log
# Clear an empty /etc/localtime or /etc/timezone directory left by pre-fix
# `-v` bind mounts before the daemon starts and restores valid files (#938).
[ -d /etc/localtime ] && [ ! -L /etc/localtime ] && rmdir /etc/localtime 2>/dev/null || true
[ -d /etc/timezone ] && [ ! -L /etc/timezone ] && rmdir /etc/timezone 2>/dev/null || true
# One at a time: the boot command, the bridge, kiri-win and `kiri`
# (crates/kiri/src/wsl.rs) can each start it at once, and two would each
# remove the socket and start a daemon. busybox flock has no time limit of
+5
View File
@@ -105,6 +105,11 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap<libc::pid_t, Pr
let mut host_dns = HostDns::default();
if host_process {
host_dns.get();
if super::sys::is_wsl()
&& let Err(e) = super::localtime::ensure_localtime()
{
eprintln!("kiri-init: localtime: {e}");
}
}
let mut dhcp: Option<Dhcp> = if host_process {
if let Err(e) = net::host_uplink() {
+15 -1
View File
@@ -1754,7 +1754,21 @@ pub(super) fn parse_mounts(list: StrList<'_>) -> io::Result<Vec<Mount>> {
}
// A missing source becomes a directory, as Docker does; one that is
// there already (a file such as /etc/hostname, too) is used as it is.
if flags.contains(&"create") && fs::symlink_metadata(src).is_err() {
// Never create a directory at /etc/localtime or /etc/timezone (#938).
let norm = lexical_normalize(Path::new(src));
if norm == Path::new("/etc/localtime") {
if fs::symlink_metadata(src).is_ok_and(|m| m.file_type().is_dir())
|| (flags.contains(&"create") && fs::metadata(src).is_err())
{
super::localtime::ensure_localtime()?;
}
} else if norm == Path::new("/etc/timezone") {
if fs::symlink_metadata(src).is_ok_and(|m| m.file_type().is_dir())
|| (flags.contains(&"create") && fs::metadata(src).is_err())
{
super::localtime::ensure_timezone()?;
}
} else if flags.contains(&"create") && fs::symlink_metadata(src).is_err() {
fs::create_dir_all(src)?;
}
let mut loop_mount = None;
+363
View File
@@ -0,0 +1,363 @@
//! Ensures `/etc/localtime` (and `/etc/timezone`) is a valid timezone file or
//! symlink rather than missing or an empty directory (#938).
//!
//! Runs in `kiri-init` on WSL startup (self-healing upgraded pre-0.2.3 Kiri WSL
//! distros where Alpine minirootfs lacked `tzdata`) and guards `parse_mounts`
//! so bind-mount source creation never turns `/etc/localtime` or `/etc/timezone`
//! into a directory.
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt, symlink};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
/// Canonical RFC 8536 `TZif2` binary for UTC (`UTC0`), 114 bytes:
/// v1 header (44 B) + v1 data (10 B) + v2 header (44 B) + v2 data (10 B) +
/// POSIX TZ footer (`\nUTC0\n`, 6 B).
pub const UTC_TZIF2: [u8; 114] = [
// V1 header (44 bytes): magic "TZif", version '2', 15 reserved zero bytes,
// isutcnt=0, isstdcnt=0, leapcnt=0, timecnt=0, typecnt=1, charcnt=4.
b'T', b'Z', b'i', b'f', b'2',
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, // isutcnt = 0
0, 0, 0, 0, // isstdcnt = 0
0, 0, 0, 0, // leapcnt = 0
0, 0, 0, 0, // timecnt = 0
0, 0, 0, 1, // typecnt = 1
0, 0, 0, 4, // charcnt = 4
// V1 data (10 bytes): ttinfo(utoff=0, isdst=0, idx=0) + "UTC\0"
0, 0, 0, 0, 0, 0,
b'U', b'T', b'C', 0,
// V2 header (44 bytes): identical counts
b'T', b'Z', b'i', b'f', b'2',
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, // isutcnt = 0
0, 0, 0, 0, // isstdcnt = 0
0, 0, 0, 0, // leapcnt = 0
0, 0, 0, 0, // timecnt = 0
0, 0, 0, 1, // typecnt = 1
0, 0, 0, 4, // charcnt = 4
// V2 data (10 bytes): ttinfo(utoff=0, isdst=0, idx=0) + "UTC\0"
0, 0, 0, 0, 0, 0,
b'U', b'T', b'C', 0,
// POSIX TZ footer (6 bytes): "\nUTC0\n"
b'\n', b'U', b'T', b'C', b'0', b'\n',
];
static TMP_SEQ: AtomicU64 = AtomicU64::new(0);
/// Strict validation for relative IANA zone names from `TZ`: non-empty, no
/// leading or trailing `/`, no `.` or `..` components, no `\` or `\0`, and
/// only ASCII `[A-Za-z0-9_+.-/]`.
pub fn valid_tz_name(tz: &str) -> bool {
if tz.is_empty() || tz.len() > 255 || tz.starts_with('/') || tz.ends_with('/') {
return false;
}
if !tz.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'+' | b'-' | b'.' | b'/')) {
return false;
}
tz.split('/').all(|c| !c.is_empty() && c != "." && c != "..")
}
fn join_confined(root: &Path, rel: &Path) -> Option<PathBuf> {
use std::path::Component;
let mut stack: Vec<std::ffi::OsString> = Vec::new();
for c in rel.components() {
match c {
Component::Normal(p) => stack.push(p.to_owned()),
Component::CurDir | Component::RootDir | Component::Prefix(_) => {}
Component::ParentDir => {
stack.pop()?;
}
}
}
let mut out = root.to_path_buf();
for s in stack {
out.push(s);
}
Some(out)
}
fn resolve_confined_file(root: &Path, allowed_bases: &[&Path], path: &Path) -> bool {
let Ok(canon_root) = fs::canonicalize(root) else {
return false;
};
let mut cur = path.to_path_buf();
for _ in 0..16 {
let Ok(meta) = fs::symlink_metadata(&cur) else {
return false;
};
let ft = meta.file_type();
if !ft.is_symlink() {
if !ft.is_file() || meta.len() == 0 {
return false;
}
let Ok(canon_target) = fs::canonicalize(&cur) else {
return false;
};
if !canon_target.starts_with(&canon_root) {
return false;
}
return allowed_bases.iter().any(|base| {
fs::canonicalize(base).is_ok_and(|cb| canon_target.starts_with(&cb))
});
}
let Ok(target) = fs::read_link(&cur) else {
return false;
};
let next = if target.is_absolute() {
if root != Path::new("/") && target.starts_with(root) {
let rel = target.strip_prefix(root).unwrap_or(&target);
join_confined(root, rel)
} else {
let rel = target.strip_prefix("/").unwrap_or(&target);
join_confined(root, rel)
}
} else {
let Some(parent_rel) = cur.parent().and_then(|p| p.strip_prefix(root).ok()) else {
return false;
};
let combined = parent_rel.join(target);
join_confined(root, &combined)
};
let Some(n) = next else {
return false;
};
cur = n;
}
false
}
fn resolve_symlink_is_file(root: &Path, path: &Path) -> bool {
let zinfo = root.join("usr/share/zoneinfo");
let etc = root.join("etc");
resolve_confined_file(root, &[zinfo.as_path(), etc.as_path()], path)
}
fn zoneinfo_file_exists(root: &Path, tz: &str) -> bool {
let zinfo = root.join("usr/share/zoneinfo");
let Some(candidate) = join_confined(&zinfo, Path::new(tz)) else {
return false;
};
resolve_confined_file(root, &[zinfo.as_path()], &candidate)
}
fn temp_path_in(dir: &Path, prefix: &str) -> PathBuf {
let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed);
dir.join(format!(".{prefix}.kiri.{}.{seq}.tmp", std::process::id()))
}
fn atomic_write_file(dest: &Path, bytes: &[u8]) -> io::Result<()> {
let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?;
fs::create_dir_all(dir)?;
let tmp = temp_path_in(dir, dest.file_name().and_then(|n| n.to_str()).unwrap_or("tz"));
let write_res = (|| -> io::Result<()> {
let mut f = OpenOptions::new().write(true).create_new(true).mode(0o644).open(&tmp)?;
f.write_all(bytes)?;
f.set_permissions(fs::Permissions::from_mode(0o644))?;
f.sync_all()?;
Ok(())
})();
if let Err(e) = write_res {
let _ = fs::remove_file(&tmp);
return Err(e);
}
if let Err(e) = fs::rename(&tmp, dest) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
Ok(())
}
fn atomic_symlink(target: &str, dest: &Path) -> io::Result<()> {
let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?;
fs::create_dir_all(dir)?;
let tmp = temp_path_in(dir, dest.file_name().and_then(|n| n.to_str()).unwrap_or("tz"));
symlink(target, &tmp)?;
if let Err(e) = fs::rename(&tmp, dest) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
Ok(())
}
fn write_timezone_if_missing(root: &Path, zone: &str) {
let tz_path = root.join("etc/timezone");
match fs::symlink_metadata(&tz_path) {
Ok(meta) if meta.file_type().is_dir() => {
if fs::remove_dir(&tz_path).is_err() {
return;
}
}
Ok(meta) if meta.file_type().is_file() && meta.len() > 0 => return,
Ok(meta) if meta.file_type().is_symlink() && resolve_symlink_is_file(root, &tz_path) => return,
Ok(meta) if !meta.file_type().is_file() && !meta.file_type().is_symlink() => return,
Ok(_) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(_) => return,
}
let _ = atomic_write_file(&tz_path, format!("{zone}\n").as_bytes());
}
/// Ensures `/etc/localtime` on `/` is a valid timezone file or symlink.
pub fn ensure_localtime() -> io::Result<()> {
let tz = std::env::var("TZ").ok();
ensure_localtime_at(Path::new("/"), tz.as_deref())
}
/// Ensures `<root>/etc/localtime` is a valid timezone file or symlink.
pub fn ensure_localtime_at(root: &Path, tz_env: Option<&str>) -> io::Result<()> {
let localtime = root.join("etc/localtime");
match fs::symlink_metadata(&localtime) {
Ok(meta) => {
let ft = meta.file_type();
if ft.is_dir() {
match fs::remove_dir(&localtime) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
} else if ft.is_file() {
if meta.len() > 0 {
return Ok(());
}
} else if ft.is_symlink() {
if resolve_symlink_is_file(root, &localtime) {
return Ok(());
}
} else {
return Err(io::Error::other(format!(
"{} is not a regular file, symlink, or empty directory",
localtime.display()
)));
}
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
if let Some(tz) = tz_env.filter(|tz| valid_tz_name(tz))
&& zoneinfo_file_exists(root, tz)
{
atomic_symlink(&format!("/usr/share/zoneinfo/{tz}"), &localtime)?;
write_timezone_if_missing(root, tz);
return Ok(());
}
if zoneinfo_file_exists(root, "Etc/UTC") {
atomic_symlink("/usr/share/zoneinfo/Etc/UTC", &localtime)?;
write_timezone_if_missing(root, "Etc/UTC");
return Ok(());
}
atomic_write_file(&localtime, &UTC_TZIF2)?;
write_timezone_if_missing(root, "UTC");
Ok(())
}
/// Ensures `/etc/timezone` on `/` is a valid timezone name file.
pub fn ensure_timezone() -> io::Result<()> {
let tz = std::env::var("TZ").ok();
ensure_timezone_at(Path::new("/"), tz.as_deref())
}
/// Ensures `<root>/etc/timezone` is a valid timezone name file (never a
/// directory), refusing to delete a non-empty directory.
pub fn ensure_timezone_at(root: &Path, tz_env: Option<&str>) -> io::Result<()> {
let tz_path = root.join("etc/timezone");
match fs::symlink_metadata(&tz_path) {
Ok(meta) => {
let ft = meta.file_type();
if ft.is_dir() {
match fs::remove_dir(&tz_path) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
} else if ft.is_file() {
if meta.len() > 0 {
return Ok(());
}
} else if ft.is_symlink() {
if resolve_symlink_is_file(root, &tz_path) {
return Ok(());
}
} else {
return Err(io::Error::other(format!(
"{} is not a regular file, symlink, or empty directory",
tz_path.display()
)));
}
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
let inferred = fs::read_link(root.join("etc/localtime"))
.ok()
.and_then(|p| p.to_str().map(str::to_owned))
.and_then(|s| s.split_once("zoneinfo/").map(|(_, z)| z.to_owned()))
.filter(|z| valid_tz_name(z));
let zone = inferred
.as_deref()
.or_else(|| tz_env.filter(|tz| valid_tz_name(tz)))
.unwrap_or("UTC");
atomic_write_file(&tz_path, format!("{zone}\n").as_bytes())
}
#[cfg(test)]
mod tests {
use super::*;
fn test_root(name: &str) -> PathBuf {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("kiri-init-localtime-{name}-{}-{n}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("etc")).unwrap();
dir
}
#[test]
fn repairs_empty_dir_and_refuses_non_empty_dir() {
let root = test_root("dir");
let lt = root.join("etc/localtime");
fs::create_dir(&lt).unwrap();
ensure_localtime_at(&root, None).unwrap();
let bytes = fs::read(&lt).unwrap();
assert!(bytes.starts_with(b"TZif2"));
assert!(bytes.ends_with(b"\nUTC0\n"));
assert_eq!(bytes.len(), 114);
assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "UTC\n");
fs::remove_file(&lt).unwrap();
fs::create_dir(&lt).unwrap();
fs::write(lt.join("keep"), b"x").unwrap();
assert!(ensure_localtime_at(&root, None).is_err());
assert_eq!(fs::read(lt.join("keep")).unwrap(), b"x");
let _ = fs::remove_dir_all(&root);
}
#[test]
fn preserves_valid_and_validates_tz() {
let root = test_root("tz");
let shanghai = root.join("usr/share/zoneinfo/Asia/Shanghai");
fs::create_dir_all(shanghai.parent().unwrap()).unwrap();
fs::write(&shanghai, &UTC_TZIF2).unwrap();
ensure_localtime_at(&root, Some("../etc/shadow")).unwrap();
assert!(fs::symlink_metadata(root.join("etc/localtime")).unwrap().file_type().is_file());
fs::remove_file(root.join("etc/localtime")).unwrap();
fs::remove_file(root.join("etc/timezone")).unwrap();
ensure_localtime_at(&root, Some("Asia/Shanghai")).unwrap();
assert_eq!(fs::read_link(root.join("etc/localtime")).unwrap(), Path::new("/usr/share/zoneinfo/Asia/Shanghai"));
assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Asia/Shanghai\n");
// Second call leaves valid symlink untouched.
ensure_localtime_at(&root, None).unwrap();
assert_eq!(fs::read_link(root.join("etc/localtime")).unwrap(), Path::new("/usr/share/zoneinfo/Asia/Shanghai"));
let _ = fs::remove_dir_all(&root);
}
}
+1
View File
@@ -11,6 +11,7 @@ mod fsview;
mod hostopts;
mod inroot;
mod layers;
mod localtime;
mod net;
mod netlink;
mod pid1;
+98 -7
View File
@@ -2022,6 +2022,57 @@ fn volumes_from_mounts(guest: &[String], info: &[Value], ro: bool) -> Vec<(Strin
.collect()
}
/// Prepares a host bind-mount source path before adding it to a container spec.
/// On Linux/WSL, `/etc/localtime` and `/etc/timezone` are never created as
/// directories: if missing (for `-v`) or an empty directory (left by an earlier
/// version before #938), they are created/repaired as valid timezone files.
fn prepare_bind_source(src: &str, here: &str, create_missing: bool) -> Result<(), Error> {
let tz = std::env::var("TZ").ok();
prepare_bind_source_at(std::path::Path::new("/"), src, here, create_missing, !cfg!(target_os = "macos"), tz.as_deref())
}
fn prepare_bind_source_at(
root: &std::path::Path,
src: &str,
here: &str,
create_missing: bool,
linux_tz_guard: bool,
tz_env: Option<&str>,
) -> Result<(), Error> {
let norm = lexical_path(here);
let p = if root == std::path::Path::new("/") {
std::path::PathBuf::from(here)
} else {
root.join(norm.trim_start_matches('/'))
};
if linux_tz_guard && matches!(norm.as_str(), "/etc/localtime" | "/etc/timezone") {
let heal = || match norm.as_str() {
"/etc/localtime" => super::localtime::ensure_localtime_at(root, tz_env).map_err(Error::Io),
_ => super::localtime::ensure_timezone_at(root, tz_env).map_err(Error::Io),
};
let is_dir = std::fs::symlink_metadata(&p).is_ok_and(|m| m.file_type().is_dir());
if is_dir {
return heal();
}
if !super::localtime::is_valid_timezone_file_at(root, &p) {
if !create_missing && !std::fs::symlink_metadata(&p).is_ok_and(|m| m.file_type().is_file()) {
return Err(Error::BadRequest(format!(
"invalid mount config for type \"bind\": bind source path does not exist: {src}"
)));
}
return heal();
}
return Ok(());
}
if !p.exists() {
if !create_missing {
return Err(Error::BadRequest(format!("invalid mount config for type \"bind\": bind source path does not exist: {src}")));
}
super::binds::make_source(&p).map_err(Error::Io)?;
}
Ok(())
}
/// `-v`, `--mount`, `--tmpfs`, `--volumes-from`, `-v /path` and the image's
/// VOLUME lines.
#[cfg(test)]
@@ -2097,13 +2148,7 @@ fn mounts_for(body: &Value, engine: &Engine, image: &kiri_image::Image, caller:
out.info.push(json!({"Type": "bind", "Source": src, "Destination": dst, "Mode": "", "RW": !ro, "Propagation": "rprivate"}));
return Ok(());
};
let p = std::path::Path::new(&here);
if !p.exists() {
if !create_missing {
return Err(Error::BadRequest(format!("invalid mount config for type \"bind\": bind source path does not exist: {src}")));
}
super::binds::make_source(p).map_err(Error::Io)?;
}
prepare_bind_source(src, &here, create_missing)?;
// After a missing source was made, so its links are followed too.
out.guest.push(format!("{}\t{dst}\t{}", guest_bind_source(src), flag("")));
out.info.push(json!({"Type": "bind", "Source": src, "Destination": dst, "Mode": "", "RW": !ro, "Propagation": "rprivate"}));
@@ -8061,4 +8106,50 @@ mod resources_disk_tests {
bad_guest.join().unwrap();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
#[test]
fn bind_mount_preparation_never_creates_localtime_or_timezone_directory() {
let root = std::env::temp_dir().join(format!("kiri-api-localtime-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("etc")).unwrap();
// `--mount type=bind` (`create_missing = false`) refuses missing /etc/localtime without creating a directory.
let err = super::prepare_bind_source_at(&root, "/etc/localtime", "/etc/localtime", false, true, None).unwrap_err();
assert!(matches!(err, super::Error::BadRequest(ref m) if m.contains("bind source path does not exist")), "{err:?}");
assert!(std::fs::symlink_metadata(root.join("etc/localtime")).is_err());
// `-v /etc/localtime:/etc/localtime:ro` (`create_missing = true`) creates a valid TZif2 file, never a directory.
super::prepare_bind_source_at(&root, "/etc/localtime", "/etc//localtime", true, true, None).unwrap();
let lt = root.join("etc/localtime");
assert!(std::fs::symlink_metadata(&lt).unwrap().file_type().is_file());
let bytes = std::fs::read(&lt).unwrap();
assert!(bytes.starts_with(b"TZif2") && bytes.ends_with(b"\nUTC0\n"));
// Existing empty directory at /etc/localtime is repaired into a file for both `-v` and `--mount`.
std::fs::remove_file(&lt).unwrap();
std::fs::create_dir(&lt).unwrap();
super::prepare_bind_source_at(&root, "/etc/localtime", "/etc/./localtime", false, true, None).unwrap();
assert!(std::fs::symlink_metadata(&lt).unwrap().file_type().is_file());
// Non-empty directory at /etc/localtime is refused without deleting its contents.
std::fs::remove_file(&lt).unwrap();
std::fs::create_dir(&lt).unwrap();
std::fs::write(lt.join("keep"), b"keep").unwrap();
assert!(super::prepare_bind_source_at(&root, "/etc/localtime", "/etc/localtime", true, true, None).is_err());
assert_eq!(std::fs::read(lt.join("keep")).unwrap(), b"keep");
std::fs::remove_dir_all(&lt).unwrap();
// `-v /etc/timezone:/etc/timezone:ro` creates/repairs a regular file, never a directory.
let tz = root.join("etc/timezone");
let _ = std::fs::remove_file(&tz);
super::prepare_bind_source_at(&root, "/etc/timezone", "/etc/timezone", true, true, Some("Asia/Shanghai")).unwrap();
assert!(std::fs::symlink_metadata(&tz).unwrap().file_type().is_file());
assert_eq!(std::fs::read_to_string(&tz).unwrap(), "Asia/Shanghai\n");
// Regular missing bind paths still become directories under `-v`.
super::prepare_bind_source_at(&root, "/srv/app", "/srv/app", true, true, None).unwrap();
assert!(root.join("srv/app").is_dir());
let _ = std::fs::remove_dir_all(&root);
}
}
+10
View File
@@ -535,6 +535,16 @@ fn engine_socket_with_alias(src: &str, own: &str, alias: Option<&str>, resolve:
/// folders 0750 and shut out the user whose mount it is. Folders already
/// there are left as they are.
pub fn make_source(path: &Path) -> std::io::Result<()> {
#[cfg(target_os = "linux")]
if path.is_absolute() {
let norm = lexical_clean(&path.to_string_lossy());
if norm == "/etc/localtime" {
return super::localtime::ensure_localtime();
}
if norm == "/etc/timezone" {
return super::localtime::ensure_timezone();
}
}
use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
let missing: Vec<&Path> = path.ancestors().take_while(|a| std::fs::symlink_metadata(a).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)).collect();
if missing.is_empty() {
+574
View File
@@ -0,0 +1,574 @@
//! Ensures `/etc/localtime` (and `/etc/timezone`) is a valid timezone file or
//! symlink rather than missing or an empty directory (#938).
//!
//! Pre-0.2.3 Kiri WSL distros were built from Alpine minirootfs without
//! `tzdata`, so `/etc/localtime` did not exist and `-v /etc/localtime:...`
//! created an empty directory there. On WSL startup and before host bind mounts
//! of `/etc/localtime` or `/etc/timezone`, this module heals empty directories
//! (never non-empty directories) and creates either a symlink into
//! `/usr/share/zoneinfo` or a canonical RFC 8536 `TZif2` UTC binary.
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt, symlink};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
/// Canonical RFC 8536 `TZif2` binary for UTC (`UTC0`), 114 bytes:
/// v1 header (44 B) + v1 data (10 B) + v2 header (44 B) + v2 data (10 B) +
/// POSIX TZ footer (`\nUTC0\n`, 6 B).
pub const UTC_TZIF2: [u8; 114] = [
// V1 header (44 bytes): magic "TZif", version '2', 15 reserved zero bytes,
// isutcnt=0, isstdcnt=0, leapcnt=0, timecnt=0, typecnt=1, charcnt=4.
b'T', b'Z', b'i', b'f', b'2',
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, // isutcnt = 0
0, 0, 0, 0, // isstdcnt = 0
0, 0, 0, 0, // leapcnt = 0
0, 0, 0, 0, // timecnt = 0
0, 0, 0, 1, // typecnt = 1
0, 0, 0, 4, // charcnt = 4
// V1 data (10 bytes): ttinfo(utoff=0, isdst=0, idx=0) + "UTC\0"
0, 0, 0, 0, 0, 0,
b'U', b'T', b'C', 0,
// V2 header (44 bytes): identical counts
b'T', b'Z', b'i', b'f', b'2',
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, // isutcnt = 0
0, 0, 0, 0, // isstdcnt = 0
0, 0, 0, 0, // leapcnt = 0
0, 0, 0, 0, // timecnt = 0
0, 0, 0, 1, // typecnt = 1
0, 0, 0, 4, // charcnt = 4
// V2 data (10 bytes): ttinfo(utoff=0, isdst=0, idx=0) + "UTC\0"
0, 0, 0, 0, 0, 0,
b'U', b'T', b'C', 0,
// POSIX TZ footer (6 bytes): "\nUTC0\n"
b'\n', b'U', b'T', b'C', b'0', b'\n',
];
static TMP_SEQ: AtomicU64 = AtomicU64::new(0);
/// Strict validation for relative IANA zone names from `TZ` (e.g.
/// `"Asia/Shanghai"`, `"America/New_York"`, `"Etc/GMT+5"`): non-empty, no
/// leading or trailing `/`, no `.` or `..` components, no `\` or `\0`, and
/// only ASCII `[A-Za-z0-9_+.-/]`.
pub fn valid_tz_name(tz: &str) -> bool {
if tz.is_empty() || tz.len() > 255 || tz.starts_with('/') || tz.ends_with('/') {
return false;
}
if !tz.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'+' | b'-' | b'.' | b'/')) {
return false;
}
tz.split('/').all(|c| !c.is_empty() && c != "." && c != "..")
}
/// Checks whether `path` (interpreted within `root`) is a non-empty regular
/// file or a symlink whose target stays confined to `<root>/usr/share/zoneinfo`
/// (or `<root>/etc`) and resolves to a non-empty regular file.
pub fn is_valid_timezone_file_at(root: &Path, path: &Path) -> bool {
let Ok(meta) = fs::symlink_metadata(path) else {
return false;
};
let ft = meta.file_type();
if ft.is_file() {
return meta.len() > 0;
}
if ft.is_symlink() {
let zinfo = root.join("usr/share/zoneinfo");
let etc = root.join("etc");
return resolve_confined_file(root, &[zinfo.as_path(), etc.as_path()], path);
}
false
}
/// Lexically normalizes `rel` beneath `root`, returning `None` if `..` would
/// escape above `root`.
fn join_confined(root: &Path, rel: &Path) -> Option<PathBuf> {
use std::path::Component;
let mut stack: Vec<std::ffi::OsString> = Vec::new();
for c in rel.components() {
match c {
Component::Normal(p) => stack.push(p.to_owned()),
Component::CurDir | Component::RootDir | Component::Prefix(_) => {}
Component::ParentDir => {
stack.pop()?;
}
}
}
let mut out = root.to_path_buf();
for s in stack {
out.push(s);
}
Some(out)
}
/// Resolves symlinks starting at `path` within `root` and returns true iff the
/// final target is a non-empty regular file whose canonical path sits inside
/// one of `allowed_bases`.
fn resolve_confined_file(root: &Path, allowed_bases: &[&Path], path: &Path) -> bool {
let canon_root = fs::canonicalize(root).ok();
let Some(canon_root_ref) = canon_root.as_deref() else {
return false;
};
let mut cur = path.to_path_buf();
for _ in 0..16 {
let Ok(meta) = fs::symlink_metadata(&cur) else {
return false;
};
let ft = meta.file_type();
if !ft.is_symlink() {
if !ft.is_file() || meta.len() == 0 {
return false;
}
let Ok(canon_target) = fs::canonicalize(&cur) else {
return false;
};
if !canon_target.starts_with(canon_root_ref) {
return false;
}
return allowed_bases.iter().any(|base| {
fs::canonicalize(base).is_ok_and(|cb| canon_target.starts_with(&cb))
});
}
let Ok(target) = fs::read_link(&cur) else {
return false;
};
let next = if target.is_absolute() {
if root != Path::new("/") && target.starts_with(root) {
let rel = target.strip_prefix(root).unwrap_or(&target);
join_confined(root, rel)
} else {
let rel = target.strip_prefix("/").unwrap_or(&target);
join_confined(root, rel)
}
} else {
let Some(parent_rel) = cur.parent().and_then(|p| p.strip_prefix(root).ok()) else {
return false;
};
let combined = parent_rel.join(target);
join_confined(root, &combined)
};
let Some(n) = next else {
return false;
};
cur = n;
}
false
}
fn resolve_symlink_is_file(root: &Path, path: &Path) -> bool {
let zinfo = root.join("usr/share/zoneinfo");
let etc = root.join("etc");
resolve_confined_file(root, &[zinfo.as_path(), etc.as_path()], path)
}
fn zoneinfo_file_exists(root: &Path, tz: &str) -> bool {
let zinfo = root.join("usr/share/zoneinfo");
let Some(candidate) = join_confined(&zinfo, Path::new(tz)) else {
return false;
};
resolve_confined_file(root, &[zinfo.as_path()], &candidate)
}
fn temp_path_in(dir: &Path, prefix: &str) -> PathBuf {
let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed);
dir.join(format!(".{prefix}.kiri.{}.{seq}.tmp", std::process::id()))
}
fn atomic_write_file(dest: &Path, bytes: &[u8]) -> io::Result<()> {
let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?;
fs::create_dir_all(dir)?;
let tmp = temp_path_in(dir, dest.file_name().and_then(|n| n.to_str()).unwrap_or("tz"));
let write_res = (|| -> io::Result<()> {
let mut f = OpenOptions::new().write(true).create_new(true).mode(0o644).open(&tmp)?;
f.write_all(bytes)?;
f.set_permissions(fs::Permissions::from_mode(0o644))?;
f.sync_all()?;
Ok(())
})();
if let Err(e) = write_res {
let _ = fs::remove_file(&tmp);
return Err(e);
}
if let Err(e) = fs::rename(&tmp, dest) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
Ok(())
}
fn atomic_symlink(target: &str, dest: &Path) -> io::Result<()> {
let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?;
fs::create_dir_all(dir)?;
let tmp = temp_path_in(dir, dest.file_name().and_then(|n| n.to_str()).unwrap_or("tz"));
symlink(target, &tmp)?;
if let Err(e) = fs::rename(&tmp, dest) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
Ok(())
}
/// Writes `<zone>\n` to `<root>/etc/timezone` if it is missing (or an empty
/// directory). Never overwrites an existing valid file or non-empty directory.
fn write_timezone_if_missing(root: &Path, zone: &str) {
let tz_path = root.join("etc/timezone");
match fs::symlink_metadata(&tz_path) {
Ok(meta) if meta.file_type().is_dir() => {
// Only remove an empty directory; never remove_dir_all.
if fs::remove_dir(&tz_path).is_err() {
return;
}
}
Ok(meta) if meta.file_type().is_file() && meta.len() > 0 => return,
Ok(meta) if meta.file_type().is_symlink() && resolve_symlink_is_file(root, &tz_path) => return,
Ok(meta) if !meta.file_type().is_file() && !meta.file_type().is_symlink() => return,
Ok(_) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(_) => return,
}
let _ = atomic_write_file(&tz_path, format!("{zone}\n").as_bytes());
}
/// Ensures `/etc/localtime` on the live root (`/`) is a valid file or symlink.
pub fn ensure_localtime() -> io::Result<()> {
let tz = std::env::var("TZ").ok();
ensure_localtime_at(Path::new("/"), tz.as_deref())
}
/// Ensures `<root>/etc/localtime` is a valid timezone file or symlink:
/// 1. If `<root>/etc/localtime` is a directory, removes it ONLY if empty
/// (`remove_dir`, never `remove_dir_all`).
/// 2. If it is already a non-empty regular file or a symlink resolving to a
/// regular file, leaves it untouched.
/// 3. If missing, empty file, or broken symlink:
/// - If `tz_env` is a valid relative zone name and
/// `<root>/usr/share/zoneinfo/<tz>` is a regular file, symlinks
/// `/etc/localtime` -> `/usr/share/zoneinfo/<tz>` and writes `<tz>\n` to
/// `<root>/etc/timezone` if missing.
/// - Else if `<root>/usr/share/zoneinfo/Etc/UTC` is a regular file, symlinks
/// `/etc/localtime` -> `/usr/share/zoneinfo/Etc/UTC` and writes `Etc/UTC\n`
/// to `<root>/etc/timezone` if missing.
/// - Else atomically writes canonical RFC 8536 `UTC_TZIF2` (`0644`) to
/// `<root>/etc/localtime` and writes `UTC\n` to `<root>/etc/timezone` if
/// missing.
pub fn ensure_localtime_at(root: &Path, tz_env: Option<&str>) -> io::Result<()> {
let localtime = root.join("etc/localtime");
match fs::symlink_metadata(&localtime) {
Ok(meta) => {
let ft = meta.file_type();
if ft.is_dir() {
// ONLY removes an empty directory; non-empty directories return an error.
match fs::remove_dir(&localtime) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
} else if ft.is_file() {
if meta.len() > 0 {
return Ok(());
}
} else if ft.is_symlink() {
if resolve_symlink_is_file(root, &localtime) {
return Ok(());
}
} else {
return Err(io::Error::other(format!(
"{} is not a regular file, symlink, or empty directory",
localtime.display()
)));
}
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
if let Some(tz) = tz_env.filter(|tz| valid_tz_name(tz))
&& zoneinfo_file_exists(root, tz)
{
atomic_symlink(&format!("/usr/share/zoneinfo/{tz}"), &localtime)?;
write_timezone_if_missing(root, tz);
return Ok(());
}
if zoneinfo_file_exists(root, "Etc/UTC") {
atomic_symlink("/usr/share/zoneinfo/Etc/UTC", &localtime)?;
write_timezone_if_missing(root, "Etc/UTC");
return Ok(());
}
atomic_write_file(&localtime, &UTC_TZIF2)?;
write_timezone_if_missing(root, "UTC");
Ok(())
}
/// Ensures `/etc/timezone` on the live root (`/`) is a valid file or symlink.
pub fn ensure_timezone() -> io::Result<()> {
let tz = std::env::var("TZ").ok();
ensure_timezone_at(Path::new("/"), tz.as_deref())
}
/// Ensures `<root>/etc/timezone` is a valid timezone name file (never a
/// directory), refusing to delete a non-empty directory.
pub fn ensure_timezone_at(root: &Path, tz_env: Option<&str>) -> io::Result<()> {
let tz_path = root.join("etc/timezone");
match fs::symlink_metadata(&tz_path) {
Ok(meta) => {
let ft = meta.file_type();
if ft.is_dir() {
match fs::remove_dir(&tz_path) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
} else if ft.is_file() {
if meta.len() > 0 {
return Ok(());
}
} else if ft.is_symlink() {
if resolve_symlink_is_file(root, &tz_path) {
return Ok(());
}
} else {
return Err(io::Error::other(format!(
"{} is not a regular file, symlink, or empty directory",
tz_path.display()
)));
}
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
let inferred = fs::read_link(root.join("etc/localtime"))
.ok()
.and_then(|p| p.to_str().map(str::to_owned))
.and_then(|s| s.split_once("zoneinfo/").map(|(_, z)| z.to_owned()))
.filter(|z| valid_tz_name(z));
let zone = inferred
.as_deref()
.or_else(|| tz_env.filter(|tz| valid_tz_name(tz)))
.unwrap_or("UTC");
atomic_write_file(&tz_path, format!("{zone}\n").as_bytes())
}
#[cfg(test)]
mod tests {
use super::*;
fn test_root(name: &str) -> PathBuf {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("kiri-localtime-{name}-{}-{n}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("etc")).unwrap();
dir
}
/// Minimal RFC 8536 TZif2 parser check verifying header counts, v1/v2 data
/// block framing, UTC designation, and POSIX TZ footer.
fn assert_valid_utc_tzif2(bytes: &[u8]) {
assert_eq!(bytes.len(), 114, "canonical UTC TZif2 is 114 bytes");
assert!(bytes.starts_with(b"TZif2"), "must start with TZif2 magic");
assert!(bytes.ends_with(b"\nUTC0\n"), "must end with POSIX UTC0 footer");
let be_u32 = |off: usize| u32::from_be_bytes(bytes[off..off + 4].try_into().unwrap());
// Verify both v1 (offset 0) and v2 (offset 54) sections.
for base in [0usize, 54usize] {
assert_eq!(&bytes[base..base + 5], b"TZif2");
assert_eq!(&bytes[base + 5..base + 20], &[0u8; 15]);
assert_eq!(be_u32(base + 20), 0, "isutcnt");
assert_eq!(be_u32(base + 24), 0, "isstdcnt");
assert_eq!(be_u32(base + 28), 0, "leapcnt");
assert_eq!(be_u32(base + 32), 0, "timecnt");
assert_eq!(be_u32(base + 36), 1, "typecnt");
assert_eq!(be_u32(base + 40), 4, "charcnt");
// Local time type record: utoff=0, isdst=0, desigidx=0
assert_eq!(&bytes[base + 44..base + 50], &[0u8; 6]);
// Abbreviation string table: "UTC\0"
assert_eq!(&bytes[base + 50..base + 54], b"UTC\0");
}
assert_eq!(&bytes[108..114], b"\nUTC0\n");
}
#[test]
fn repairs_empty_localtime_directory_into_valid_tzif2_file() {
let root = test_root("empty-dir");
let lt = root.join("etc/localtime");
fs::create_dir(&lt).unwrap();
assert!(fs::symlink_metadata(&lt).unwrap().file_type().is_dir());
ensure_localtime_at(&root, None).unwrap();
let meta = fs::symlink_metadata(&lt).unwrap();
assert!(meta.file_type().is_file(), "repaired /etc/localtime must be a regular file");
assert_eq!(meta.permissions().mode() & 0o777, 0o644);
let bytes = fs::read(&lt).unwrap();
assert_valid_utc_tzif2(&bytes);
assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "UTC\n");
let _ = fs::remove_dir_all(&root);
}
#[test]
fn refuses_to_delete_non_empty_localtime_directory() {
let root = test_root("non-empty-dir");
let lt = root.join("etc/localtime");
fs::create_dir(&lt).unwrap();
let keep = lt.join("sentinel.txt");
fs::write(&keep, b"do-not-delete").unwrap();
let err = ensure_localtime_at(&root, None).expect_err("non-empty directory must not be removed");
assert!(lt.is_dir(), "directory must remain intact after error ({err})");
assert_eq!(fs::read(&keep).unwrap(), b"do-not-delete");
// Same safety invariant for /etc/timezone.
let tz = root.join("etc/timezone");
fs::create_dir(&tz).unwrap();
let keep_tz = tz.join("keep");
fs::write(&keep_tz, b"safe").unwrap();
assert!(ensure_timezone_at(&root, None).is_err());
assert_eq!(fs::read(&keep_tz).unwrap(), b"safe");
let _ = fs::remove_dir_all(&root);
}
#[test]
fn preserves_existing_valid_localtime_file_and_symlink() {
let root = test_root("preserve");
let lt = root.join("etc/localtime");
let custom = b"TZif2-custom-existing-file";
fs::write(&lt, custom).unwrap();
// Even with TZ pointing to a valid zoneinfo file, existing valid file is untouched.
let shanghai = root.join("usr/share/zoneinfo/Asia/Shanghai");
fs::create_dir_all(shanghai.parent().unwrap()).unwrap();
fs::write(&shanghai, &UTC_TZIF2).unwrap();
ensure_localtime_at(&root, Some("Asia/Shanghai")).unwrap();
assert!(fs::symlink_metadata(&lt).unwrap().file_type().is_file());
assert_eq!(fs::read(&lt).unwrap(), custom);
assert!(!root.join("etc/timezone").exists(), "should not touch /etc/timezone when /etc/localtime is already valid");
// Valid symlink resolving inside root is also preserved untouched.
fs::remove_file(&lt).unwrap();
let ny = root.join("usr/share/zoneinfo/America/New_York");
fs::create_dir_all(ny.parent().unwrap()).unwrap();
fs::write(&ny, &UTC_TZIF2).unwrap();
symlink("/usr/share/zoneinfo/America/New_York", &lt).unwrap();
ensure_localtime_at(&root, Some("Asia/Shanghai")).unwrap();
assert_eq!(fs::read_link(&lt).unwrap(), Path::new("/usr/share/zoneinfo/America/New_York"));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn links_valid_tz_env_and_rejects_path_traversal() {
let root = test_root("tz-env");
let shanghai = root.join("usr/share/zoneinfo/Asia/Shanghai");
fs::create_dir_all(shanghai.parent().unwrap()).unwrap();
fs::write(&shanghai, &UTC_TZIF2).unwrap();
let utc = root.join("usr/share/zoneinfo/Etc/UTC");
fs::create_dir_all(utc.parent().unwrap()).unwrap();
fs::write(&utc, &UTC_TZIF2).unwrap();
// Valid TZ links to /usr/share/zoneinfo/<TZ> and populates /etc/timezone.
ensure_localtime_at(&root, Some("Asia/Shanghai")).unwrap();
assert_eq!(fs::read_link(root.join("etc/localtime")).unwrap(), Path::new("/usr/share/zoneinfo/Asia/Shanghai"));
assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Asia/Shanghai\n");
// Reject path-traversal and invalid TZ strings; fall back to Etc/UTC.
for bad in [
"../etc/shadow",
"/etc/passwd",
"Asia/../../etc/passwd",
"",
".",
"..",
"Asia/",
"Asia//Shanghai",
"Asia\\Shanghai",
"Asia/Shanghai\0",
"Asia/Shanghai\n",
":Asia/Shanghai",
] {
assert!(!valid_tz_name(bad), "{bad:?} must be rejected");
let _ = fs::remove_file(root.join("etc/localtime"));
let _ = fs::remove_file(root.join("etc/timezone"));
ensure_localtime_at(&root, Some(bad)).unwrap();
assert_eq!(
fs::read_link(root.join("etc/localtime")).unwrap(),
Path::new("/usr/share/zoneinfo/Etc/UTC"),
"bad TZ {bad:?} must fall back to Etc/UTC"
);
assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Etc/UTC\n");
}
let _ = fs::remove_dir_all(&root);
}
#[test]
fn replaces_broken_symlink_and_empty_file() {
let root = test_root("broken-link");
let lt = root.join("etc/localtime");
// Dangling symlink pointing to /usr/share/zoneinfo/Etc/UTC when root has no zoneinfo.
symlink("/usr/share/zoneinfo/Etc/UTC", &lt).unwrap();
ensure_localtime_at(&root, None).unwrap();
assert!(fs::symlink_metadata(&lt).unwrap().file_type().is_file());
assert_valid_utc_tzif2(&fs::read(&lt).unwrap());
// Symlink pointing to a directory is treated as broken.
fs::remove_file(&lt).unwrap();
fs::create_dir_all(root.join("usr/share/zoneinfo")).unwrap();
symlink("/usr/share/zoneinfo", &lt).unwrap();
ensure_localtime_at(&root, None).unwrap();
assert!(fs::symlink_metadata(&lt).unwrap().file_type().is_file());
assert_valid_utc_tzif2(&fs::read(&lt).unwrap());
// 0-byte regular file is repaired into a valid TZif2 file.
fs::write(&lt, b"").unwrap();
ensure_localtime_at(&root, None).unwrap();
assert_valid_utc_tzif2(&fs::read(&lt).unwrap());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn ensures_timezone_file_and_infers_from_localtime_link() {
let root = test_root("timezone");
let berlin = root.join("usr/share/zoneinfo/Europe/Berlin");
fs::create_dir_all(berlin.parent().unwrap()).unwrap();
fs::write(&berlin, &UTC_TZIF2).unwrap();
symlink("/usr/share/zoneinfo/Europe/Berlin", root.join("etc/localtime")).unwrap();
fs::create_dir(root.join("etc/timezone")).unwrap();
ensure_timezone_at(&root, None).unwrap();
assert!(fs::symlink_metadata(root.join("etc/timezone")).unwrap().file_type().is_file());
assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Europe/Berlin\n");
let _ = fs::remove_dir_all(&root);
}
#[test]
fn rejects_symlinks_escaping_zoneinfo_or_root() {
let root = test_root("confined");
let zinfo = root.join("usr/share/zoneinfo");
fs::create_dir_all(&zinfo).unwrap();
fs::create_dir_all(root.join("var/secret")).unwrap();
fs::write(root.join("var/secret/token"), b"secret").unwrap();
// A symlink inside zoneinfo escaping to /var/secret/token is rejected for TZ
// and falls back to writing UTC_TZIF2 instead of linking to the secret file.
symlink("../../../var/secret/token", zinfo.join("EvilZone")).unwrap();
assert!(!super::zoneinfo_file_exists(&root, "EvilZone"));
ensure_localtime_at(&root, Some("EvilZone")).unwrap();
let lt = root.join("etc/localtime");
assert!(fs::symlink_metadata(&lt).unwrap().file_type().is_file());
assert_valid_utc_tzif2(&fs::read(&lt).unwrap());
// An /etc/localtime symlink pointing outside /usr/share/zoneinfo and /etc is
// rejected by is_valid_timezone_file_at and replaced on ensure_localtime_at.
fs::remove_file(&lt).unwrap();
symlink("/var/secret/token", &lt).unwrap();
assert!(!is_valid_timezone_file_at(&root, &lt));
ensure_localtime_at(&root, None).unwrap();
assert!(fs::symlink_metadata(&lt).unwrap().file_type().is_file());
assert_valid_utc_tzif2(&fs::read(&lt).unwrap());
let _ = fs::remove_dir_all(&root);
}
}
+8
View File
@@ -23,6 +23,8 @@ mod hostetc;
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
mod hostroots;
mod hostopts;
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) mod localtime;
mod mirror;
mod http;
mod logfile;
@@ -217,6 +219,12 @@ pub fn run(_args: &[String]) -> io::Result<()> {
}
}
let _ = BOUND_SOCKET.set(socket.clone());
#[cfg(target_os = "linux")]
if rofs::is_wsl()
&& let Err(e) = localtime::ensure_localtime()
{
diag::warn!("could not repair /etc/localtime", error = e);
}
if let Some(ref msg) = rofs::check_daemon_storage(None) {
diag::error!("storage filesystem is read-only", detail = msg);
}
+6
View File
@@ -13,6 +13,12 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug
## Fixes
### #938 Windows (WSL 2): bundle `zoneinfo`, self-heal `/etc/localtime`, and prevent bind mounts from creating timezone directories (unreleased)
- Fixes: #938 Windows: `/etc/localtime` is a directory in Kiri WSL, breaking common bind mounts
- Caused: none known
- Caused by: -
- Check: `crates/kiri/src/daemon/localtime.rs`, `crates/kiri-init/src/linux/localtime.rs`, `scripts/kiri-linux.sh`
### #935 Machines: use local images before pulling and mount `--systemd` `/tmp` and `/run` with `exec` (unreleased)
- Fixes: #935 `kiri machine create`: `--systemd` machines get a `noexec` `/tmp`, and `--image` always pulls instead of using a local image
- Caused: none known
+32
View File
@@ -19,9 +19,41 @@ mkdir -p "$cache"
# The .part is this process's own: CI jobs on one machine share the cache.
[ -f "$cache/$ALPINE" ] || { curl -fsSL --retry 3 -o "$cache/$ALPINE.$$.part" "$ALPINE_URL" && mv -f "$cache/$ALPINE.$$.part" "$cache/$ALPINE"; } || rm -f "$cache/$ALPINE.$$.part"
echo "$ALPINE_SHA256 $cache/$ALPINE" | sha256sum -c - >/dev/null || { rm -f "$cache/$ALPINE"; echo "$ALPINE: SHA-256 mismatch" >&2; exit 1; }
write_utc_tzif() {
# Canonical RFC 8536 TZif2 binary for UTC (UTC0): v1 header+data (54 B),
# v2 header+data (54 B), POSIX TZ footer ("\nUTC0\n", 6 B).
for _ in 1 2; do
printf 'TZif2'
printf '\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000'
printf '\001\000\000\000\004\000\000\000\000\000\000UTC\000'
done
printf '\nUTC0\n'
}
root=$(mktemp -d)
trap 'rm -rf "$root"' EXIT
tar --no-same-owner -xzf "$cache/$ALPINE" -C "$root"
install -m 755 "$bin/kiri" "$bin/kiri-init" "$repo/contrib/wsl/kiri-linux/kiri-start" "$root/usr/local/bin/"
install -m 644 "$repo/contrib/wsl/kiri-linux/wsl.conf" "$root/etc/wsl.conf"
# Bundle zoneinfo and /etc/localtime so WSL 2's Windows-to-Linux timezone sync
# finds /usr/share/zoneinfo and common `-v /etc/localtime:...` bind mounts
# never turn /etc/localtime into a directory (#938).
if [ -d /usr/share/zoneinfo ]; then
mkdir -p "$root/usr/share/zoneinfo"
cp -a /usr/share/zoneinfo/. "$root/usr/share/zoneinfo"
fi
if [ -L "$root/usr/share/zoneinfo/Etc/UTC" ] || [ ! -f "$root/usr/share/zoneinfo/Etc/UTC" ]; then
mkdir -p "$root/usr/share/zoneinfo/Etc"
rm -f "$root/usr/share/zoneinfo/Etc/UTC"
write_utc_tzif > "$root/usr/share/zoneinfo/Etc/UTC"
chmod 644 "$root/usr/share/zoneinfo/Etc/UTC"
fi
if [ -L "$root/usr/share/zoneinfo/UTC" ] || [ ! -f "$root/usr/share/zoneinfo/UTC" ]; then
rm -f "$root/usr/share/zoneinfo/UTC"
write_utc_tzif > "$root/usr/share/zoneinfo/UTC"
chmod 644 "$root/usr/share/zoneinfo/UTC"
fi
ln -snf /usr/share/zoneinfo/Etc/UTC "$root/etc/localtime"
rm -f "$root/etc/timezone"
printf 'Etc/UTC\n' > "$root/etc/timezone"
chmod 644 "$root/etc/timezone"
tar -C "$root" --numeric-owner --owner=0 --group=0 -czf "$out" .
+3
View File
@@ -353,3 +353,6 @@ crates/kiri/src/vm_cli.rs #473 macOS low ports (<1024) on 127.0.0.1/::1 failed w
finder-mount-nobrowse #929 Finder showed an automatic < sidebar entry for the local NFS socket mount
guest-kernel-ext2-vfat #934 guest kernel lacked CONFIG_EXT4_USE_FOR_EXT2 and CONFIG_VFAT_FS so loop-mounted ext2 and FAT/EFI disk images failed to mount
crates/kiri/src/machine.rs #935 kiri machine create always pulled --image instead of probing local images first, and --systemd machines mounted /tmp and /run with noexec
crates/kiri/src/daemon/localtime.rs #938 Kiri WSL lacked /etc/localtime so `-v /etc/localtime:/etc/localtime:ro` created an empty directory there, breaking timezone bind mounts until self-healed and guarded against directory creation
crates/kiri-init/src/linux/localtime.rs #938 kiri-init on WSL did not self-heal a missing or empty-directory /etc/localtime on startup and parse_mounts could create a directory at /etc/localtime or /etc/timezone
scripts/kiri-linux.sh #938 Kiri Linux WSL rootfs omitted /usr/share/zoneinfo, /etc/localtime and /etc/timezone, preventing WSL 2 Windows-to-Linux timezone sync and leaving /etc/localtime missing on fresh installs
Can't render this file because it contains an unexpected character in line 2 and column 52.