mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 22:10:44 +00:00
Create guest temporary files on explicit host mounts
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
This commit is contained in:
1 parent
941ac8cf2e
commit
f21d8ea1be
3 files changed
+110
-29
No files matched your search
@@ -10,6 +10,7 @@ use super::{
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs::File;
|
||||
use std::os::unix::fs::FileExt;
|
||||
use std::sync::Arc;
|
||||
@@ -553,6 +554,39 @@ fn temp_file_name(
|
||||
if !prefix.is_ascii() || !valid_component(&format!("{prefix}0000.TMP")) {
|
||||
return state.fail(teb, INVALID_NAME, 0);
|
||||
}
|
||||
if let Some(resolved) = host_files::resolve(&state.mounts, &path, valid_component) {
|
||||
let result = resolved.and_then(|resolved| {
|
||||
if unique == 0 && !resolved.mount.writable() {
|
||||
return Err(ERROR_ACCESS_DENIED);
|
||||
}
|
||||
let directory = resolved.directory()?;
|
||||
let occupied = if unique == 0 {
|
||||
host_files::list(&directory)
|
||||
.map_err(|error| host_files::win32_error(&error))?
|
||||
.into_iter()
|
||||
.map(|entry| entry.name.to_ascii_lowercase())
|
||||
.collect::<BTreeSet<_>>()
|
||||
} else {
|
||||
BTreeSet::new()
|
||||
};
|
||||
write_temp_file_name(memory, output, &path, &prefix, unique, state.clock.now_filetime(), |name| {
|
||||
if occupied.contains(&name.to_ascii_lowercase()) {
|
||||
return Ok(false);
|
||||
}
|
||||
let request = host_files::OpenRequest { read: false, write: true, create: true };
|
||||
match host_files::open_file(&directory, name, &request, None) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(error) if error.raw_os_error() == Some(libc::EEXIST) => Ok(false),
|
||||
Err(error) => Err(host_files::win32_error(&error)),
|
||||
}
|
||||
})
|
||||
});
|
||||
return match result {
|
||||
Ok(number) => Ok(number),
|
||||
Err(error) => state.fail(teb, error, 0),
|
||||
};
|
||||
}
|
||||
|
||||
let mut objects = state.objects.lock().expect("guest object state");
|
||||
let current = &objects.current_directory;
|
||||
let directory = if path == "." {
|
||||
@@ -575,48 +609,63 @@ fn temp_file_name(
|
||||
} else {
|
||||
path
|
||||
};
|
||||
let separator = if path.ends_with('\\') { "" } else { "\\" };
|
||||
let start = match state.clock.now_filetime() as u16 {
|
||||
0 => 1,
|
||||
value => value,
|
||||
};
|
||||
let candidates = (0..u16::MAX).map(|offset| {
|
||||
((u32::from(start) - 1 + u32::from(offset)) % u32::from(u16::MAX) + 1) as u16
|
||||
});
|
||||
let numbers = if unique == 0 {
|
||||
None.into_iter().chain(candidates)
|
||||
} else {
|
||||
Some(unique as u16).into_iter().chain(candidates)
|
||||
};
|
||||
for number in numbers {
|
||||
let name = format!("{prefix}{number:04X}.TMP");
|
||||
let result = write_temp_file_name(memory, output, &path, &prefix, unique, state.clock.now_filetime(), |name| {
|
||||
let name = name.to_ascii_lowercase();
|
||||
let key = if directory.is_empty() {
|
||||
name.to_ascii_lowercase()
|
||||
name
|
||||
} else {
|
||||
format!("{directory}\\{}", name.to_ascii_lowercase())
|
||||
format!("{directory}\\{name}")
|
||||
};
|
||||
if unique == 0 && (objects.files.contains_key(&key) || objects.directories.contains(&key)) {
|
||||
continue;
|
||||
if objects.files.contains_key(&key) || objects.directories.contains(&key) {
|
||||
return Ok(false);
|
||||
}
|
||||
objects.files.insert(key, Vec::new());
|
||||
Ok(true)
|
||||
});
|
||||
match result {
|
||||
Ok(number) => Ok(number),
|
||||
Err(error) => state.fail(teb, error, 0),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_temp_file_name(
|
||||
memory: &mut GuestMemory,
|
||||
output: u64,
|
||||
path: &str,
|
||||
prefix: &str,
|
||||
unique: u32,
|
||||
now: u64,
|
||||
mut create: impl FnMut(&str) -> Result<bool, u32>,
|
||||
) -> Result<u64, u32> {
|
||||
let separator = if path.ends_with('\\') { "" } else { "\\" };
|
||||
let start = (now as u16).max(1);
|
||||
let count = if unique == 0 { u32::from(u16::MAX) } else { 1 };
|
||||
for offset in 0..count {
|
||||
let number = if unique == 0 {
|
||||
((u32::from(start) - 1 + offset) % u32::from(u16::MAX) + 1) as u16
|
||||
} else {
|
||||
unique as u16
|
||||
};
|
||||
let name = format!("{prefix}{number:04X}.TMP");
|
||||
let units = format!("{path}{separator}{name}");
|
||||
if units.encode_utf16().count() >= 260 {
|
||||
return state.fail(teb, 111, 0); // ERROR_BUFFER_OVERFLOW
|
||||
return Err(111); // ERROR_BUFFER_OVERFLOW
|
||||
}
|
||||
let bytes: Vec<_> = units
|
||||
.encode_utf16()
|
||||
.chain([0])
|
||||
.flat_map(u16::to_le_bytes)
|
||||
.collect();
|
||||
if output == 0 || memory.write_bytes(output, &bytes).is_err() {
|
||||
return state.fail(teb, ERROR_NOACCESS, 0);
|
||||
if output == 0 || memory.check_write(output, bytes.len()).is_err() {
|
||||
return Err(ERROR_NOACCESS);
|
||||
}
|
||||
if unique == 0 {
|
||||
objects.files.insert(key, Vec::new());
|
||||
return Ok(u64::from(number));
|
||||
if unique == 0 && !create(&name)? {
|
||||
continue;
|
||||
}
|
||||
return Ok(u64::from(unique));
|
||||
memory.write_bytes(output, &bytes).map_err(|_| ERROR_NOACCESS)?;
|
||||
return Ok(if unique == 0 { u64::from(number) } else { u64::from(unique) });
|
||||
}
|
||||
state.fail(teb, FILE_EXISTS, 0)
|
||||
Err(FILE_EXISTS)
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
|
||||
@@ -23,6 +23,7 @@ const UCRT: &str = "ucrtbase.dll";
|
||||
const IMPORTS: &[(&str, &str)] = &[
|
||||
(KERNEL32, "GetLastError"),
|
||||
(FILE_API, "CreateFileW"),
|
||||
(FILE_API, "GetTempFileNameW"),
|
||||
(KERNEL32, "ReadFile"),
|
||||
(KERNEL32, "WriteFile"),
|
||||
(KERNEL32, "CloseHandle"),
|
||||
@@ -149,6 +150,36 @@ fn symlink(target: &Path, link: &Path) {
|
||||
std::os::unix::fs::symlink(target, link).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temporary_files_use_the_mounted_directory_and_skip_existing_names() {
|
||||
let tree = Tree::new("temp-file");
|
||||
let root = tree.path("root");
|
||||
std::fs::create_dir_all(root.join("Temp")).unwrap();
|
||||
std::fs::write(root.join("Temp/PRE0001.tmp"), b"original").unwrap();
|
||||
let writable = HostMount::new('D', &root, true).unwrap();
|
||||
let readonly = HostMount::new('E', &root, false).unwrap();
|
||||
let mut guest = guest_with(vec![writable, readonly]);
|
||||
let prefix = PATH + 0x200;
|
||||
put_path(&mut guest, prefix, "prefix");
|
||||
put_path(&mut guest, PATH, r"D:\temp");
|
||||
assert_eq!(guest.call("GetTempFileNameW", &[PATH, prefix, 0, 1]), 0);
|
||||
assert_eq!(guest.error(), 998);
|
||||
assert_eq!(guest.call("GetTempFileNameW", &[PATH, prefix, 0, BUFFER]), 2);
|
||||
let name: Vec<_> = (0..32)
|
||||
.map(|i| guest.u16_at(BUFFER + 2 * i))
|
||||
.take_while(|unit| *unit != 0)
|
||||
.collect();
|
||||
assert_eq!(String::from_utf16(&name).unwrap(), r"D:\temp\pre0002.TMP");
|
||||
assert_eq!(std::fs::metadata(root.join("Temp/pre0002.TMP")).unwrap().len(), 0);
|
||||
assert_eq!(std::fs::read(root.join("Temp/PRE0001.tmp")).unwrap(), b"original");
|
||||
|
||||
put_path(&mut guest, PATH, r"E:\Temp");
|
||||
assert_eq!(guest.call("GetTempFileNameW", &[PATH, prefix, 0, BUFFER]), 0);
|
||||
assert_eq!(guest.error(), 5);
|
||||
assert_eq!(guest.call("GetTempFileNameW", &[PATH, prefix, 3, BUFFER]), 3);
|
||||
assert!(!root.join("Temp/pre0003.TMP").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_mount_non_ascii_spelling_and_native_create_collisions() {
|
||||
let tree = Tree::new("non-ascii-case");
|
||||
|
||||
+3
-2
@@ -360,8 +360,9 @@ among `TMP`, `TEMP`, and `USERPROFILE`, falling back to the synthetic
|
||||
directory exists. The narrow entry point accepts ASCII. No host environment
|
||||
is consulted.
|
||||
|
||||
The partial `GetTempFileNameW` service supports the synthetic drive and ASCII
|
||||
prefixes. A nonzero unique value formats a name without creating a file. A zero
|
||||
The partial `GetTempFileNameW` service accepts ASCII prefixes on the synthetic
|
||||
drive and explicitly mounted drives. Automatic creation requires a writable
|
||||
mount and uses exclusive creation inside the resolved directory. A nonzero unique value formats a name without creating a file. A zero
|
||||
value picks an available name using the guest clock and creates an empty file
|
||||
without retaining a handle. Callers can remove it with `DeleteFileW`.
|
||||
|
||||
|
||||
Reference in new issue
Block a user