Files
PowerToys/src/modules/FileLocksmith/FileLocksmithLib/IPC.cpp

68 lines
1.3 KiB
C++
Raw Normal View History

[New PowerToy] File Locksmith (#20930) * Imported offline solution * Make solution compile * Add Windows sample, doesn't work? * Added new project to implement the dll * Remove unneeded header * Implemented IUnknown part of ExplorerCommand * Implemented IExplorerCommand methods * Implemented ClassFactory * Implemented DLL register/unregister * Implemented other DLL exports, not working? * Implemented IShellExtInit inferface * Implemented IContextMenu, it works! * Implement command data fetching * Make sample project compile on VS 2022 * Add plan * Implement Lib as separate project * Implemented IPC, not tested * Console UI project skeleton * Implemented basic console UI * Implemented piping, there are bugs * Prototype works * Remove old project * Added GUI project skeleton * Mitigate issue with WinUI3 * Added a control for displaying results * Add button * Implement core functions in lib project * Call new library function from console main * Implement showing results * Improve UI * Implemented subdirectory search * Remove useless code * Set window size * UI adjustments * Implement killing process * Rename variable * Add lib project to main solution * Add Ext and GUI projects to solution * Tweak packages for GUI project * Add a settings page * Add a few resource strings * Add one more resources string * VS keeps trying to correct this * Add references to File Locksmith in /,github * Implement some parts of FileLocksmithModule * Change output directory * Change target name and add to runner * Add logger * Started implementing settings backend * Fix log folder * Settings work * Add some basic tracing * Attempt at adding resources * Remove junk files * Added missing defines * Replaced some constants with resources Something's not working * Move resources to the Ext project * Remove experiment * Add binaries for signing * Improve tracing * Remove old Settings calls * Show something when there are no results * Change window title * Move computation to another thread, improve UX * Increase font size for default text * Remove entries for killed processes * Show user name * Remove nonrecursive implementation * Implement back end for getting file names * Show list of files, UI tweaks * Remove useless includes * Implement back end for getting full process path * Dark title bar on dark themes * Using Expander, other UI adjustments * Show "No results" after killing all processes * Show progress ring * Update configuration mapping * Revert "Update configuration mapping" This reverts commit d8e13206f3c7de3c6dbf880299bfff3bf9f27a37. * Fixed solution configuration, ARM64 should build * Backend for refreshing * Variable window size * Add refresh button * New WinUI3 C# project for FL * Started porting functionality * Add Interop project * Move IPC to Ext project * Ported native functions to Interop * Ported finding processes * Ported most of Main Window functionality * Display paths of files * Implement killing processes * Use resource string for "End Task" * Remove entries for terminated processes * Show User name * Set default window size * Make the new UI the default * Reading paths from stdin, completed port to C# * Fix small bug * Moving to MVVM * Adding Labs * Merge branch 'ivan/file-locksmith' of https://github.com/microsoft/PowerToys into ivan/file-locksmith Removing one parent commit for cleaner history Co-Authored-By: Niels Laute <niels.laute@live.nl> * Reintroducing features * Moving UI strings to resources file * Restored functionality * Add missing dlls * Add FIle Locksmith to publish.cmd * Rebase fixes * Try updating nuget.config * Fix copy-paste blunder * Add File Locksmith UI for publishing * Add .pubxml file in FileLocksmith * Change build output folder * Fix installer build issues Remove old projects from solution so MSBuild doesn't build them. Downgrade target framework to what most other projects are using. Fix publishing profile and project runtimes. Remove unused CsWinRT references. * [CI] Add clear to nuget packages * Fix module reference counting * Fix nuget for release CI * Fix version and signing * Fix path for resources * Fix incorrect results when running 2 instances * Fix default nuget source * Windows 10 icon and fallback for UI * Code clean-up and spaces instead of tabs * Add gif showcasing FL * Add screenshot of File Locksmith for Settings * Add new files to the installer * Add OOBE page * Showing selected paths in the header * Tweak path list * Added new, wider gif * Add GPO * Add some logs * [CI]Get CommunityToolkit.Labs from BigPark feed * [CI]Use azure package feed for Nuget in release * [CI]Another try for the labs source * Revert changes to feed * Use RestoreAdditionalProjectSources * Add tooltip to file list * Change tooltip to not trim the lines * Add Tips and tricks section mentioning elevated * Add some more logs messages. * Grammar fix * Add to bug report tool * Fix UI virtualization not working * Disable virtualization to avoid crashes * Get better virtualization * Add dialog instead of tooltip to show list of items * No results refresh icon is now a button too * Use managed methods for handling processes * Remove registry code from Ext. * Support drives too Co-authored-by: Niels Laute <niels.laute@live.nl> Co-authored-by: Jaime Bernardo <jaime@janeasystems.com>
2022-10-28 15:51:21 +02:00
#include "pch.h"
#include "IPC.h"
#include "Constants.h"
#include <common/SettingsAPI/settings_helpers.h>
constexpr DWORD DefaultPipeBufferSize = 8192;
constexpr DWORD DefaultPipeTimeoutMillis = 200;
namespace ipc
{
Writer::Writer()
{
start();
}
Writer::~Writer()
{
finish();
}
HRESULT Writer::start()
{
std::wstring path = PTSettingsHelper::get_module_save_folder_location(constants::nonlocalizable::PowerToyName);
path += L"\\";
path += constants::nonlocalizable::LastRunPath;
try
{
[File Locksmith] Fix IPC text-mode file I/O corrupting Unicode paths (#47361) ## Summary of the Pull Request The File Locksmith IPC layer reads and writes raw UTF-16 (WCHAR) bytes to `last-run.log`, but all three stream opens were using the default text mode. On Windows, the CRT translates `0x0A` bytes to `0x0D 0x0A` on write and collapses `0x0D 0x0A` back to `0x0A` on read. Because each WCHAR is 2 bytes, any code unit whose little-endian byte pair contains `0x0A` in the low position (e.g. `U+010A`, `U+0A0D`) is silently corrupted. The fix opens all three streams in binary mode and adds an explicit open-failure guard. ```cpp // IPC.cpp — Writer::start() // Before m_stream = std::ofstream(path); // After m_stream = std::ofstream(path, std::ios::binary); // + is_open() guard returning E_FAIL on failure // NativeMethods.cpp — StartAsElevated() writer // Before std::ofstream stream(paths_file()); // After std::ofstream stream(paths_file(), std::ios::binary); // NativeMethods.cpp — ReadPathsFromFile() reader // Before std::ifstream stream(paths_file()); // After std::ifstream stream(paths_file(), std::ios::binary); ``` ## PR Checklist - [ ] **Communication:** I've discussed this with core contributors already. If the work hasn't been agreed, this work might be rejected - [ ] **Tests:** Added/updated and all pass - [ ] **Localization:** All end-user-facing strings can be localized - [ ] **Dev docs:** Added/updated - [ ] **New binaries:** Added on the required places - [ ] [JSON for signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json) for new binaries - [ ] [WXS for installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs) for new binaries and localization folder - [ ] [YML for CI pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml) for new test projects - [ ] [YML for signed pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml) - [ ] **Documentation updated:** If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys) and link it here: #xxx ## Detailed Description of the Pull Request / Additional comments Three targeted changes across two files: 1. **`FileLocksmithLib/IPC.cpp` — `Writer::start()`**: switched `std::ofstream` from text to binary mode and added an `is_open()` check that returns `E_FAIL` immediately when the file cannot be opened (previously the try/catch did not catch a silent open failure because `std::ofstream` does not throw by default). 2. **`FileLocksmithLibInterop/NativeMethods.cpp` — `StartAsElevated()`**: switched `std::ofstream` from text to binary mode. This is the elevated-restart writer path; without this fix, Unicode corruption persisted when File Locksmith relaunched as administrator. 3. **`FileLocksmithLibInterop/NativeMethods.cpp` — `ReadPathsFromFile()`**: switched `std::ifstream` from text to binary mode. This is the symmetric reader-side bug — even with both writers corrected, the CRT text-mode reader could collapse a `0x0D 0x0A` byte pair (a valid UTF-16 LE code unit, e.g. U+0A0D GURMUKHI EK ONKAR) into a single byte, desynchronising the 2-bytes-at-a-time read loop and corrupting all subsequent path data. No behaviour change for purely ASCII paths. Paths containing Unicode code points whose little-endian UTF-16 byte pair spans `0x0D 0x0A` were silently corrupted in all three code paths before this fix. ## Validation Steps Performed - Code review: no issues flagged. - Full diff reviewed: all three stream opens (`ofstream` writer in `IPC.cpp`, `ofstream` writer in `NativeMethods.cpp`, `ifstream` reader in `NativeMethods.cpp`) now use `std::ios::binary`, making write and read paths byte-exact and symmetric. - Mechanically correct: `std::ios::binary` suppresses Windows CRT `\n`↔`\r\n` translation; the delimiter `L'\n'` (LE bytes `0x0A 0x00`) is unambiguous in binary mode and is handled correctly by the existing read loop. --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: MuyuanMS <116717757+MuyuanMS@users.noreply.github.com> Co-authored-by: Muyuan Li (from Dev Box) <muyuanli@microsoft.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-25 16:30:15 +08:00
m_stream = std::ofstream(path, std::ios::binary);
if (!m_stream.is_open())
{
return E_FAIL;
}
[New PowerToy] File Locksmith (#20930) * Imported offline solution * Make solution compile * Add Windows sample, doesn't work? * Added new project to implement the dll * Remove unneeded header * Implemented IUnknown part of ExplorerCommand * Implemented IExplorerCommand methods * Implemented ClassFactory * Implemented DLL register/unregister * Implemented other DLL exports, not working? * Implemented IShellExtInit inferface * Implemented IContextMenu, it works! * Implement command data fetching * Make sample project compile on VS 2022 * Add plan * Implement Lib as separate project * Implemented IPC, not tested * Console UI project skeleton * Implemented basic console UI * Implemented piping, there are bugs * Prototype works * Remove old project * Added GUI project skeleton * Mitigate issue with WinUI3 * Added a control for displaying results * Add button * Implement core functions in lib project * Call new library function from console main * Implement showing results * Improve UI * Implemented subdirectory search * Remove useless code * Set window size * UI adjustments * Implement killing process * Rename variable * Add lib project to main solution * Add Ext and GUI projects to solution * Tweak packages for GUI project * Add a settings page * Add a few resource strings * Add one more resources string * VS keeps trying to correct this * Add references to File Locksmith in /,github * Implement some parts of FileLocksmithModule * Change output directory * Change target name and add to runner * Add logger * Started implementing settings backend * Fix log folder * Settings work * Add some basic tracing * Attempt at adding resources * Remove junk files * Added missing defines * Replaced some constants with resources Something's not working * Move resources to the Ext project * Remove experiment * Add binaries for signing * Improve tracing * Remove old Settings calls * Show something when there are no results * Change window title * Move computation to another thread, improve UX * Increase font size for default text * Remove entries for killed processes * Show user name * Remove nonrecursive implementation * Implement back end for getting file names * Show list of files, UI tweaks * Remove useless includes * Implement back end for getting full process path * Dark title bar on dark themes * Using Expander, other UI adjustments * Show "No results" after killing all processes * Show progress ring * Update configuration mapping * Revert "Update configuration mapping" This reverts commit d8e13206f3c7de3c6dbf880299bfff3bf9f27a37. * Fixed solution configuration, ARM64 should build * Backend for refreshing * Variable window size * Add refresh button * New WinUI3 C# project for FL * Started porting functionality * Add Interop project * Move IPC to Ext project * Ported native functions to Interop * Ported finding processes * Ported most of Main Window functionality * Display paths of files * Implement killing processes * Use resource string for "End Task" * Remove entries for terminated processes * Show User name * Set default window size * Make the new UI the default * Reading paths from stdin, completed port to C# * Fix small bug * Moving to MVVM * Adding Labs * Merge branch 'ivan/file-locksmith' of https://github.com/microsoft/PowerToys into ivan/file-locksmith Removing one parent commit for cleaner history Co-Authored-By: Niels Laute <niels.laute@live.nl> * Reintroducing features * Moving UI strings to resources file * Restored functionality * Add missing dlls * Add FIle Locksmith to publish.cmd * Rebase fixes * Try updating nuget.config * Fix copy-paste blunder * Add File Locksmith UI for publishing * Add .pubxml file in FileLocksmith * Change build output folder * Fix installer build issues Remove old projects from solution so MSBuild doesn't build them. Downgrade target framework to what most other projects are using. Fix publishing profile and project runtimes. Remove unused CsWinRT references. * [CI] Add clear to nuget packages * Fix module reference counting * Fix nuget for release CI * Fix version and signing * Fix path for resources * Fix incorrect results when running 2 instances * Fix default nuget source * Windows 10 icon and fallback for UI * Code clean-up and spaces instead of tabs * Add gif showcasing FL * Add screenshot of File Locksmith for Settings * Add new files to the installer * Add OOBE page * Showing selected paths in the header * Tweak path list * Added new, wider gif * Add GPO * Add some logs * [CI]Get CommunityToolkit.Labs from BigPark feed * [CI]Use azure package feed for Nuget in release * [CI]Another try for the labs source * Revert changes to feed * Use RestoreAdditionalProjectSources * Add tooltip to file list * Change tooltip to not trim the lines * Add Tips and tricks section mentioning elevated * Add some more logs messages. * Grammar fix * Add to bug report tool * Fix UI virtualization not working * Disable virtualization to avoid crashes * Get better virtualization * Add dialog instead of tooltip to show list of items * No results refresh icon is now a button too * Use managed methods for handling processes * Remove registry code from Ext. * Support drives too Co-authored-by: Niels Laute <niels.laute@live.nl> Co-authored-by: Jaime Bernardo <jaime@janeasystems.com>
2022-10-28 15:51:21 +02:00
return S_OK;
}
catch (...)
{
return E_FAIL;
}
}
HRESULT Writer::add_path(LPCWSTR path)
{
int length = lstrlenW(path);
if (!m_stream.write(reinterpret_cast<const char*>(path), length * sizeof(WCHAR)))
{
return E_FAIL;
}
WCHAR line_break = L'\n';
if (!m_stream.write(reinterpret_cast<const char*>(&line_break), sizeof(WCHAR)))
{
return E_FAIL;
}
return S_OK;
}
void Writer::finish()
{
add_path(L"");
m_stream.close();
}
}