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
27 changes: 26 additions & 1 deletion src/entry/filetype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,11 @@ impl Filetype {
} else if native.is_dir() {
Self::Directory
} else if native.is_symlink() {
Self::Symlink
// A link to a file acts as that file
match fs::metadata(path) {
Ok(target) if target.is_file() => Self::from_file(path),
_ => Self::Symlink,
}
} else {
Self::Unknown
}
Expand Down Expand Up @@ -254,6 +258,27 @@ mod tests {
assert!(file("firmware.bin") == Filetype::Text);
}

#[test]
fn treats_a_link_to_a_file_as_that_file() {
let folder = std::env::temp_dir().join(format!("lsi-symlink-{}", std::process::id()));
fs::create_dir_all(&folder).unwrap();
let target = folder.join("notes.md");
fs::write(&target, "").unwrap();
let link = folder.join("link.md");

#[cfg(unix)]
let created = std::os::unix::fs::symlink(&target, &link);
#[cfg(windows)]
let created = std::os::windows::fs::symlink_file(&target, &link);

// Windows refuses symlinks without admin rights or developer mode
if created.is_ok() {
let native = fs::symlink_metadata(&link).unwrap().file_type();
assert!(Filetype::from_native(native, &link) == Filetype::Markdown);
}
fs::remove_dir_all(&folder).unwrap();
}

#[test]
fn groups_every_shell_script_together() {
for name in [
Expand Down
119 changes: 104 additions & 15 deletions src/entry/shortcut.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
//! Windows shortcuts (`.lnk` files).

use std::{fs, panic};
use std::{
fs, panic,
path::{Path, PathBuf},
};

use lnk::ShellLink;

/// Where the shortcut at `path` points. Gives `path` back when the target is missing, and
/// `None` when the shortcut cannot be read.
pub fn resolve(path: &str) -> Option<String> {
/// The folder the shortcut at `path` points to. `None` when the shortcut points to anything
/// else, or cannot be read.
pub fn folder(path: &str) -> Option<String> {
// Silence the expected panic, then put back the previous hook
let previous_hook = panic::take_hook();
panic::set_hook(Box::new(|_info| {}));
Expand All @@ -15,17 +18,38 @@ pub fn resolve(path: &str) -> Option<String> {

panic::set_hook(previous_hook);

let target = link
.ok()?
.string_data()
.relative_path()
.as_ref()
.and_then(|target| fs::canonicalize(target).ok());

Some(target.map_or_else(
|| path.to_owned(),
|target| target.to_string_lossy().to_string(),
))
let folder = Path::new(path).parent().unwrap_or_else(|| Path::new(""));
targets(&link.ok()?, folder)
.into_iter()
.find_map(|target| fs::canonicalize(target).ok())
.filter(|target| target.is_dir())
.map(|target| target.to_string_lossy().to_string())
}

/// The paths a shortcut in `folder` may point to, most reliable first.
fn targets(link: &ShellLink, folder: &Path) -> Vec<PathBuf> {
let mut targets = Vec::new();

if let Some(info) = link.link_info() {
let base = info
.local_base_path_unicode()
.as_deref()
.or_else(|| info.local_base_path());
let suffix = info
.common_path_suffix_unicode()
.as_deref()
.unwrap_or_else(|| info.common_path_suffix());
if let Some(base) = base {
targets.push(PathBuf::from(format!("{base}{suffix}")));
}
}

// The relative path starts at the shortcut's own folder
if let Some(relative) = link.string_data().relative_path() {
targets.push(folder.join(relative));
}

targets
}

// Encoding for non-Unicode .lnk strings: the system's active ANSI code page
Expand All @@ -49,3 +73,68 @@ fn ansi_encoding() -> lnk::Encoding {
encoding_rs::WINDOWS_1252
}
}

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

/// A minimal Unicode shortcut that stores only a relative path.
fn relative_shortcut(relative: &str) -> Vec<u8> {
const HAS_RELATIVE_PATH: u32 = 0x08;
const IS_UNICODE: u32 = 0x80;
const SHOW_NORMAL: u8 = 1;
const LINK_CLSID: [u8; 16] = [
0x01, 0x14, 0x02, 0, 0, 0, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46,
];

let mut bytes = vec![0; 76];
bytes[0..4].copy_from_slice(&76u32.to_le_bytes());
bytes[4..20].copy_from_slice(&LINK_CLSID);
bytes[20..24].copy_from_slice(&(HAS_RELATIVE_PATH | IS_UNICODE).to_le_bytes());
bytes[60] = SHOW_NORMAL;

let chars: Vec<u16> = relative.encode_utf16().collect();
bytes.extend(u16::try_from(chars.len()).unwrap().to_le_bytes());
bytes.extend(chars.iter().flat_map(|c| c.to_le_bytes()));
bytes.extend(0u32.to_le_bytes());
bytes
}

/// Makes a fresh folder holding a folder `inner`, a file `file.txt` and the given
/// shortcuts, then runs `check` on that folder and removes it.
fn with_shortcuts(test: &str, shortcuts: &[(&str, &str)], check: impl FnOnce(&Path)) {
let folder = std::env::temp_dir().join(format!("lsi-{test}-{}", std::process::id()));
fs::create_dir_all(folder.join("inner")).unwrap();
fs::write(folder.join("file.txt"), "").unwrap();
for (name, relative) in shortcuts {
fs::write(folder.join(name), relative_shortcut(relative)).unwrap();
}

check(&folder);
fs::remove_dir_all(&folder).unwrap();
}

fn folder_of(link: &Path) -> Option<String> {
self::folder(link.to_str().unwrap())
}

#[test]
fn finds_a_relative_folder_from_the_shortcut_folder() {
with_shortcuts("relative", &[("inner.lnk", ".\\inner")], |folder| {
let expected = fs::canonicalize(folder.join("inner")).unwrap();
assert_eq!(
folder_of(&folder.join("inner.lnk")),
Some(expected.to_string_lossy().to_string())
);
});
}

#[test]
fn finds_no_folder_behind_a_shortcut_to_a_file_or_nothing() {
let shortcuts = [("file.lnk", ".\\file.txt"), ("gone.lnk", ".\\gone")];
with_shortcuts("not-folders", &shortcuts, |folder| {
assert_eq!(folder_of(&folder.join("file.lnk")), None);
assert_eq!(folder_of(&folder.join("gone.lnk")), None);
});
}
}
54 changes: 38 additions & 16 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,15 @@ fn main_loop(initial_path: String, no_exec: bool) {
break;
}

// A shortcut to a folder browses it. Any other shortcut opens like a file.
let shortcut_folder = (entry.filetype == Filetype::Lnk)
.then(|| shortcut::folder(&entry.path))
.flatten();
let opens = entry.filetype.should_exec()
|| (entry.filetype == Filetype::Lnk && shortcut_folder.is_none());

// exec file
if entry.filetype.should_exec() || modifier == KeyModifiers::CONTROL {
if opens || modifier == KeyModifiers::CONTROL {
if no_exec {
finish(&mut ui);
print!("{}", pretty_path(target));
Expand All @@ -111,17 +118,8 @@ fn main_loop(initial_path: String, no_exec: bool) {

// browse directory by continuing loop with new path
selected_entry = entry;

if selected_entry.filetype == Filetype::Lnk {
// An error must not land inside the prompt
finish(&mut ui);
match shortcut::resolve(&selected_entry.path) {
Some(target) => selected_entry.path = target,
None => err(format!(
"Failed to read shortcut \"{}\"",
pretty_path(&selected_entry.path)
)),
}
if let Some(folder) = shortcut_folder {
selected_entry.path = folder;
}
}
}
Expand Down Expand Up @@ -203,10 +201,18 @@ fn get_choices(entry: &Entry) -> Vec<Entry> {
});
}

// Get files in directory
if let Ok(entries) = fs::read_dir(&entry.path) {
for entry in entries.flatten() {
result_vector.push(Entry::from_dir_entry(&entry));
// Get files in directory. A link that denies listing, like `C:\Documents and Settings`,
// lists its target, and its entries keep paths under the link.
let folder = Path::new(&entry.path);
let listing = fs::read_dir(folder).or_else(|_| fs::read_dir(fs::canonicalize(folder)?));
if let Ok(entries) = listing {
for dir_entry in entries.flatten() {
let mut item = Entry::from_dir_entry(&dir_entry);
item.path = folder
.join(dir_entry.file_name())
.to_string_lossy()
.to_string();
result_vector.push(item);
}
}

Expand Down Expand Up @@ -252,6 +258,22 @@ mod tests {
assert_eq!(modified_target(&current, &choices[0]), "/lsi/missing");
}

#[cfg(windows)]
#[test]
fn lists_a_junction_that_denies_listing_through_its_target() {
let junction = r"C:\Documents and Settings";
let choices = get_choices(&folder("Documents and Settings", junction));

let listed: Vec<_> = choices
.iter()
.filter(|choice| choice.name != "..")
.collect();
assert!(listed.iter().all(|choice| choice.name != "<Open>"));
assert!(listed
.iter()
.all(|choice| choice.path.starts_with(&format!(r"{junction}\"))));
}

#[test]
fn a_modified_enter_on_any_other_entry_targets_that_entry() {
// The first entry is not `..` in the root folder and in the drive view
Expand Down