Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions openvmm/openvmm_entry/src/microvm/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,14 @@ impl MicrovmReportPlan {
&& teardown.auxiliary_workers_stopped,
},
};
let parent = self.path.parent().unwrap_or(Path::new("."));
// `tempfile` publishes the report with Win32 functions that take a path
// beyond the legacy MAX_PATH limits only in its extended-length form.
#[cfg(windows)]
let path = pal::windows::fs::extended_length_path(&self.path)
.context("failed to resolve the microVM report path")?;
#[cfg(not(windows))]
let path = self.path;
let parent = path.parent().unwrap_or(Path::new("."));
let mut temporary = tempfile::NamedTempFile::new_in(parent)
.context("failed to create the microVM report staging file")?;
serde_json::to_writer_pretty(temporary.as_file_mut(), &report)
Expand All @@ -231,7 +238,7 @@ impl MicrovmReportPlan {
.sync_all()
.context("failed to flush the microVM report")?;
temporary
.persist_noclobber(&self.path)
.persist_noclobber(&path)
.map_err(|error| error.error)
.context("failed to publish the microVM report")?;
Ok(())
Expand Down Expand Up @@ -426,4 +433,27 @@ mod tests {
let error = validate_destination(&path).unwrap_err();
assert!(error.to_string().contains("destination already exists"));
}

#[cfg(windows)]
#[test]
fn reports_are_published_below_long_paths() {
use std::os::windows::ffi::OsStrExt;

// The report's path exceeds the legacy MAX_PATH limits of the Win32
// functions with which `tempfile` publishes it.
let directory = tempfile::tempdir().unwrap();
let mut parent = directory.path().to_path_buf();
while parent.as_os_str().encode_wide().count() < 300 {
parent.push("long-report-parent-component");
}
fs_err::create_dir_all(&parent).unwrap();
let path = parent.join("outcome.json");
test_plan(path.clone()).write(&Ok(0)).unwrap();
assert_eq!(read_report(&path)["outcome"]["category"], "success");

// A second report replaces nothing, and neither leaves a staging file.
test_plan(path.clone()).write(&Ok(1)).unwrap_err();
assert_eq!(read_report(&path)["outcome"]["category"], "success");
assert_eq!(fs_err::read_dir(&parent).unwrap().count(), 1);
}
}
75 changes: 75 additions & 0 deletions support/pal/src/windows/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,18 @@ pub mod sparse;

use super::chk_status;
use super::dos_to_nt_path;
use std::ffi::OsString;
use std::ffi::c_void;
use std::fs;
use std::io;
use std::mem::zeroed;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::ffi::OsStringExt;
use std::os::windows::io::AsRawHandle;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use std::path::Prefix;
use std::ptr::null_mut;
use widestring::U16CString;
use windows_sys::Wdk::Foundation::OBJECT_ATTRIBUTES;
Expand Down Expand Up @@ -96,13 +102,82 @@ pub fn is_unix_socket(path: &Path) -> io::Result<bool> {
&& data.dwReserved0 == IO_REPARSE_TAG_AF_UNIX)
}

/// Returns `path` in a form that the Win32 file functions take whatever its
/// length. Without the extended-length `\\?\` prefix, `CreateDirectoryW`
/// refuses a path of 248 or more UTF-16 code units, and the other functions,
/// such as `CreateFileW` and `MoveFileExW`, one of 260 or more.
///
/// The path is resolved, as Win32 resolves it, before the prefix is added,
/// since the file system takes an extended-length path as given, and a path
/// shorter than 248 code units keeps its resolved form. Win32 also takes an NT
/// path, `\??\...`, as given, and refuses an empty path itself, so both keep
/// their form, as do verbatim and device paths.
pub fn extended_length_path(path: &Path) -> io::Result<PathBuf> {
let raw = path.as_os_str();
if raw.is_empty() || raw.encode_wide().take(4).eq(r"\??\".encode_utf16()) {
return Ok(path.to_path_buf());
}
let path = std::path::absolute(path)?;
if path.as_os_str().encode_wide().count() < 248 {
return Ok(path);
}
let (prefix, skip) = match path.components().next() {
Some(Component::Prefix(prefix)) => match prefix.kind() {
Prefix::Disk(_) => (r"\\?\", 0),
Prefix::UNC(..) => (r"\\?\UNC\", 2),
_ => ("", 0),
},
_ => ("", 0),
};
let extended = prefix
.encode_utf16()
.chain(path.as_os_str().encode_wide().skip(skip))
.collect::<Vec<_>>();
Ok(OsString::from_wide(&extended).into())
}

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

#[test]
fn test_query_stat_lx() {
let result = query_stat_lx_by_name(r"C:\\".as_ref()).unwrap();
assert_ne!(0, result.FileId);
}

#[test]
fn extended_length_paths_prefix_resolved_long_paths() {
let extended = |path: &str| extended_length_path(Path::new(path)).unwrap();
let name = |length| "a".repeat(length);

// Disk and UNC paths take the prefix from 248 UTF-16 code units, once
// resolved.
let short = format!(r"C:\{}", name(244));
let long = format!(r"C:\{}", name(245));
assert_eq!(extended(&short), Path::new(&short));
assert_eq!(extended(&long), Path::new(&format!(r"\\?\{long}")));
let long = format!(r"\\server\share\{}", name(233));
assert_eq!(
extended(&long),
Path::new(&format!(r"\\?\UNC\{}", &long[2..]))
);
assert_eq!(
extended(&format!("C:/{}/./child/../leaf", name(300))),
Path::new(&format!(r"\\?\C:\{}\leaf", name(300)))
);
let relative = std::env::current_dir().unwrap().join(name(300));
assert_eq!(extended(&name(300)), extended(relative.to_str().unwrap()));

// Verbatim, NT, device, and empty paths keep their form.
for path in [
format!(r"\\?\C:\{}", name(300)),
format!(r"\??\C:\{}", name(300)),
format!(r"\\.\C:\{}", name(300)),
String::new(),
] {
assert_eq!(extended(&path), Path::new(&path));
}
}
}
47 changes: 8 additions & 39 deletions support/pal/src/windows/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ use std::io::ErrorKind;
use std::marker::PhantomData;
use std::ops::Deref;
use std::os::windows::prelude::*;
use std::path::Component;
use std::path::Path;
use std::path::Prefix;
use std::ptr::NonNull;
use std::ptr::null_mut;
use std::str::FromStr;
Expand Down Expand Up @@ -391,44 +389,13 @@ where
}
}

/// Encodes `path` for the Win32 creation functions. Without the extended-length
/// `\\?\` prefix, `CreateDirectoryW` refuses a path of 248 or more UTF-16 code
/// units and `CreateFileW` one of 260 or more.
///
/// The path is resolved, as Win32 resolves it, before the prefix is added,
/// since the file system takes an extended-length path as given. Win32 also
/// takes an NT path, `\??\...`, as given, and refuses an empty path itself, so
/// both keep their form.
/// Encodes `path` for the Win32 creation functions, in the form that
/// [`extended_length_path`](super::fs::extended_length_path) returns, which
/// they take whatever its length.
fn secure_create_path(path: &Path) -> std::io::Result<U16CString> {
fn encode(path: &Path) -> std::io::Result<U16CString> {
U16CString::from_os_str(path.as_os_str())
.map_err(|error| std::io::Error::new(ErrorKind::InvalidInput, error))
}

let raw = path.as_os_str();
if raw.is_empty() || raw.encode_wide().take(4).eq(r"\??\".encode_utf16()) {
return encode(path);
}
let path = std::path::absolute(path)?;
let name = encode(&path)?;
if name.len() < 248 {
return Ok(name);
}
let (prefix, skip) = match path.components().next() {
Some(Component::Prefix(prefix)) => match prefix.kind() {
Prefix::Disk(_) => (r"\\?\", 0),
Prefix::UNC(..) => (r"\\?\UNC\", 2),
_ => ("", 0),
},
_ => ("", 0),
};
U16CString::from_vec(
prefix
.encode_utf16()
.chain(name.as_slice().iter().copied().skip(skip))
.collect::<Vec<_>>(),
)
.map_err(|error| std::io::Error::new(ErrorKind::InvalidInput, error))
let path = super::fs::extended_length_path(path)?;
U16CString::from_os_str(path.as_os_str())
.map_err(|error| std::io::Error::new(ErrorKind::InvalidInput, error))
}

/// Creates a directory with `security_descriptor` applied atomically.
Expand Down Expand Up @@ -497,7 +464,9 @@ mod tests {
use std::io::Write;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::ffi::OsStringExt;
use std::path::Component;
use std::path::PathBuf;
use std::path::Prefix;
use test_with_tracing::test;
use widestring::U16CStr;
use windows_sys::Win32::Foundation::LocalFree;
Expand Down
Loading