From 2b86dc7af679a2e7ac234892e299a1bb73aef625 Mon Sep 17 00:00:00 2001 From: Dan Gohman Date: Tue, 14 Feb 2023 13:27:16 -0800 Subject: [PATCH] Handle `GetFileInformationByHandleEx` returning a long filename. In #18 there is a report that under some situations `GetFileInformationByHandleEx` can produce a file name with a length that extends beyond the end of the buffer. Check for this case and return false if it is. Also, backport the change from std to only search the file name for "msys-" and "cygwin-", rather than the whole path. --- src/lib.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 0994576..9021931 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -165,13 +165,19 @@ unsafe fn msys_tty_on(handle: HANDLE) -> bool { return false; } - let s = &name_info.FileName[..name_info.FileNameLength as usize / 2]; + // Use `get` because `FileNameLength` can be out of range. + let s = match name_info.FileName.get(..name_info.FileNameLength as usize / 2) { + None => return false, + Some(s) => s, + }; let name = String::from_utf16_lossy(s); + // Get the file name only. + let name = name.rsplit('\\').next().unwrap_or(&name); // This checks whether 'pty' exists in the file name, which indicates that // a pseudo-terminal is attached. To mitigate against false positives // (e.g., an actual file name that contains 'pty'), we also require that - // either the strings 'msys-' or 'cygwin-' are in the file name as well.) - let is_msys = name.contains("msys-") || name.contains("cygwin-"); + // the file name begins with either the strings 'msys-' or 'cygwin-'.) + let is_msys = name.starts_with("msys-") || name.starts_with("cygwin-"); let is_pty = name.contains("-pty"); is_msys && is_pty }