Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace which with a manual implementation using SearchPathW #96

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
11 changes: 8 additions & 3 deletions Building.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,18 @@ Note, if you run that on the public toolchain, you'll most definitely run into `

### Notes on updating the cargo feed

For internal reasons, we need to maintain a separate Azure Artifacts cargo feed. Largely we just pull dependencies through from crates.io into that feed. Hence the config to replace the default cargo feed with our own.
For internal reasons, we need to maintain a separate Azure Artifacts cargo feed.
Largely we just pull dependencies through from crates.io into that feed. Hence
the config to replace the default cargo feed with our own.

As a maintainer, if you need to update that feed, then you'll need to do the following:
As a maintainer, if you need to update that feed, You should check out the steps
under ["Cargo" on this
page](https://dev.azure.com/shine-oss/sudo/_artifacts/feed/Sudo_PublicPackages).
TL;DR, do the following:

```cmd
az login
az account get-access-token --query "join(' ', ['Bearer', accessToken])" --output tsv | cargo login --registry Sudo_PublicPackages
```

That'll log you in via the Azure CLI and then log you into the cargo feed. That'll let you pull down the packages but oh yikes everything is awful.
That'll log you in via the Azure CLI and then log you into the cargo feed. I believe that should allow you to pull packages through to the Azure feed, from the public feed. If it doesn't, maintainers should have the necessary permissions to add packages to the feed.
75 changes: 64 additions & 11 deletions sudo/src/run_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,19 +191,58 @@ pub fn run_target(
do_request(req, copy_env, manually_requested_dir)
}

fn search_path(filename: &str) -> Result<String> {
let filename = &HSTRING::from(filename);
let len = unsafe { SearchPathW(None, filename, None, None, None) };
/// Returns all the extensions from PATHEXT that are used for "executables"
fn get_path_extensions() -> Vec<String> {
env::var("PATHEXT")
.unwrap_or_else(|_| {
// If PATHEXT isn't set, use the default
".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC".to_string()
})
.split(';')
.map(|ext| ext.to_string())
.collect()
}
Comment on lines +195 to +204
Copy link
Member

@lhecker lhecker Aug 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this was inside search_path_with_extensions it wouldn't need to collect into a vector first, nor allocate each string chunk.

Like this:

let pathext = env::var("PATHEXT");
let extensions = pathext
    .as_deref()
    // If PATHEXT isn't set, use the default
    .unwrap_or(".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC")
    .split(';');

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking about it some more, I think it'd be preferable if we still did this, but it's not something I would block over.


if len == 0 {
return Err(Error::from_win32());
}
/// Searches the PATH for the given filename, with the extensions from PATHEXT.
/// Returns the full path to the file if it's found, or an error if it's not.
fn search_path_with_extensions(filename: &str) -> Result<String> {
let filename = HSTRING::from(filename);
let mut buffer = vec![0; 260];
let extensions = get_path_extensions();
for extension in extensions {
let extension_hstring = HSTRING::from(extension);
// SearchPathW will ignore the extension if the filename already has one.
let len: u32 = unsafe {
SearchPathW(
None,
&filename,
&extension_hstring,
Some(&mut buffer),
None,
)
};

// If the function fails, the return value is zero.
if len == 0 {
continue;
}

let mut buffer = vec![0; len as usize];
let len = unsafe { SearchPathW(None, filename, None, Some(&mut buffer), None) };
buffer.truncate(len as usize);
// If the function succeeds, the value returned is the
// length of the string that is copied to the buffer,
// not including the terminating null character.
if len < buffer.len() as u32 {
buffer.truncate(len as usize);
return Ok(String::from_utf16(&buffer)?);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW you could also consider returning an OsString or even better Path here, as that would be consistent with other parts of Rust and this app. It would also allow you to revert the change to absolute_path below.

}

Ok(String::from_utf16(&buffer)?)
// If the return value is greater than nBufferLength, the value
// returned is the size of the buffer that is required to hold
// the path, including the terminating null character.
//
// Includes some padding just in case and because it's cheap.
buffer.resize((len + 64) as usize, 0);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wait, doesn't this mean that if it fails to fit in the buffer we will move on to the next extension after growing the buffer? That doesn't seem correct.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hah. I didn't even catch this! My initial suggestion had a loop, so this looked quite similar. 😅 But it needs a loop in a loop.

}
Err(Error::from_win32())
}

/// Constructs an ElevateRequest from the given arguments. We'll package up
Expand Down Expand Up @@ -277,7 +316,7 @@ fn prepare_request(
event_log_request(true, &req);

// Does the application exist somewhere on the path?
let where_result = search_path(&req.application);
let where_result = search_path_with_extensions(&req.application);

if let Ok(path) = where_result {
// It's a real file that exists on the PATH.
Expand Down Expand Up @@ -538,6 +577,20 @@ fn runas_admin_impl(exe: &OsStr, args: &OsStr, show: SHOW_WINDOW_CMD) -> Result<
mod tests {
use super::*;

#[test]
fn test_search_path_cmd() {
let path = search_path_with_extensions("cmd").unwrap();
assert!(path.eq_ignore_ascii_case("C:\\Windows\\System32\\cmd.exe"));
let path = search_path_with_extensions("cmd.exe").unwrap();
assert!(path.eq_ignore_ascii_case("C:\\Windows\\System32\\cmd.exe"));
}
#[test]
fn test_search_path_bad() {
// There's no way this file exists
let path = search_path_with_extensions("acaeb0cf7e91430eb8958a64bee752a7").unwrap_err();
assert_eq!(path.code().0, E_FILENOTFOUND.0);
}

#[test]
fn test_cmd_is_cui() {
let app_name = "cmd".to_string();
Expand Down