Files
PowerToys/src/modules/Hosts/HostsModuleInterface/dllmain.cpp

278 lines
7.1 KiB
C++
Raw Normal View History

2022-10-13 13:05:43 +02:00
#include "pch.h"
#include "trace.h"
#include <common/logger/logger.h>
#include <common/utils/logger_helper.h>
#include <interface/powertoy_module_interface.h>
#include "Generated Files/resource.h"
#include <shellapi.h>
#include <common/interop/shared_constants.h>
#include <common/utils/EventWaiter.h>
2022-10-13 13:05:43 +02:00
#include <common/utils/resources.h>
#include <common/utils/winapi_error.h>
#include <common/SettingsAPI/settings_objects.h>
#include <string>
extern "C" IMAGE_DOS_HEADER __ImageBase;
BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD ul_reason_for_call, LPVOID /*lpReserved*/)
2022-10-13 13:05:43 +02:00
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
Trace::RegisterProvider();
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
Trace::UnregisterProvider();
break;
}
return TRUE;
}
namespace
{
// Name of the powertoy module.
inline const std::wstring ModuleKey = L"Hosts";
}
class HostsModuleInterface : public PowertoyModuleIface
{
private:
bool m_enabled = false;
std::wstring app_name;
//contains the non localized key of the powertoy
std::wstring app_key;
HANDLE m_hProcess;
HANDLE m_hShowEvent;
HANDLE m_hShowAdminEvent;
2022-10-13 13:05:43 +02:00
bool is_process_running()
{
return WaitForSingleObject(m_hProcess, 0) == WAIT_TIMEOUT;
}
void bring_process_to_front()
{
auto enum_windows = [](HWND hwnd, LPARAM param) -> BOOL {
HANDLE process_handle = reinterpret_cast<HANDLE>(param);
2022-10-13 13:05:43 +02:00
DWORD window_process_id = 0;
GetWindowThreadProcessId(hwnd, &window_process_id);
if (GetProcessId(process_handle) == window_process_id)
{
SetForegroundWindow(hwnd);
return FALSE;
}
return TRUE;
};
EnumWindows(enum_windows, (LPARAM)m_hProcess);
}
void launch_process(bool runas)
{
Logger::trace(L"Starting Hosts process");
unsigned long powertoys_pid = GetCurrentProcessId();
std::wstring executable_args = L"";
executable_args.append(std::to_wstring(powertoys_pid));
SHELLEXECUTEINFOW sei{ sizeof(sei) };
sei.fMask = { SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI };
[General]Reduce installer size by flattening application paths (#27451) * Flatten everything and succeed build * Figure out Settings assets * Remove UseCommonOutputDirectory tag * Proper settings app path * [VCM] Fix assets location * Fix some runtime paths * [RegistryPreview]Use MRTCore specific pri file * [Hosts]Use MRTCore specific pri file * [Settings]Use MRTCore specific pri file * [Peek]Use MRTCore specific pri file * [FileLocksmith]Use MRTCore specific pri file * [ScreenRuler]Use MRTCore specific pri file * [PowerRename]Use MRTCore specific pri file * [Peek]Move assets to own folder * [FileLocksmith] Use own Assets path * [Hosts]Use own assets folder * [PowerRename]Use own assets dir * [MeasureTool] Use its own assets folder * [ImageResizer]Use its own assets path * Fix spellcheck * Fix tab instead of space in project files * Normalize target frameworks and platforms * Remove WINRT_NO_MAKE_DETECTION flag. No longer needed? * Fix AOT and Hosts locations * Fix Dll version differences on dependency * Add Common.UI.csproj as refernce to fix dll versions * Update ControlzEx to normalize dll versions * Update System.Management version to 7.0.2 * Add GPOWrapper to Registry Preview to fix dll versions * [PTRun]Reference Microsoft.Extensions.Hosting to fix dll versions * Fix remaining output paths / dll version conflicts * [KeyboardManager]Executables still on their own directories * Fix Monaco paths * WinAppSDK apps get to play outside again * Enable VCM settings again * Fix KBM Editor path again * [Monaco]Set to own Assets dir * Fix installer preamble; Fix publish. remove unneeded publishes * Remove Hardlink functions * Installer builds again (still needs work to work) * Readd Monaco to spellcheck excludes * Fix spellcheck and call publish.cmd again * [Installer] Remove components that don't need own dirs * [Installer] Refactor Power Launcher * [Installer] Refactor Color Picker * [Installer] Refactor Monaco assets * [Installer]Generate File script no longer needs to remove files * [Installer]Refactor FileLocksmith * [Installer] Refactor Hosts * [Installer]Refactor Image Resizer * [Installer]Refactor MouseUtils * [Installer]Refactor MWB * [Installer]Refactor MeasureTool * [Installer]Refactor Peek * [Installer]Refactor PowerRename and registry fixes * [Installer]Refactor RegistryPreview * [Installer]Refactor ShortcutGuide * [Installer]Refactor Settings * [Installer]Clean up some unused stuff * [Installer]Clean up stuff for user install * [Installer]Fix WinUi3Apps wxs * [Installer]Fix misplaced folders * [Installer]Move x86 VCM dll to right path * Fix monaco language list location * [Installer]Fix VCM directory reference * [CI]Fix signing * [Installer] Fix resources folder for release CI * [ci]Looks like we still ship NLog on PowerToys Run * [Settings]Add dependency to avoid dll collision with Experimentation * [RegistryPreview]Move XAML files to own path * [RegistryPreview]Fix app icon * [Hosts]Move XAML files to their own path * [FileLocksmith]Move XAML files to their own path * [Peek]Move XAML files to own path * [ScreenRuler]Move XAML files to its own path * [Settings]Move XAML to its own path * [ColorPicker]Move Resources to Assets * [ShortcutGuide]Move svgs to own Assets path * [Awake]Move images to assets path * [Runner]Remove debug checks for PowerToys Run assets * [PTRun]Move images to its own assets path * [ImageResizer]Icon for context menu on own assets path * [PowerRename]Move ico to its own path * Remove unneeded intermediary directories * Remove further int dirs * Move tests to its own output path * Fix spellcheck * spellcheck: remove warnings * [CppAnalyzers]Ignore rule in a tool * [CI]Check if all deps.json files reference same versions * fix spellcheck * [ci]Fix task identation * [ci]Add script to guard against asset conflicts * [ci]Add more deps.json audit steps in the release build * Add xbf to spellcheck expects * Fix typo in asset conflict check scripts * Fix some more dependency conflicts * Downgrade CsWinRT to have the same dll version as sdk * [ci]Do a recursive check for every deps.json * Fix spellcheck error inside comment * [ci]Fix asset script error * [ci]Name deps.json verify tasks a bit better * [ci]Improve deps json verify script output * [ci]Update WinRT version to the same running in CI * Also upgrade CsWinRT in NOTICE.MD * [PowerRename]Move XAML files to own path * [Common]Fix Settings executable path * [ci]Verify there's no xbf files in app directories * [installer]Fix firewall path * [Monaco]Move new files to their proper assets path * [Monaco]Fix paths for new files after merge * [Feedback]Removed unneeded build conditions * [Feedback]Clear vcxproj direct reference to frameworks * [Feedback]RunPlugins name to hold PTRun plugins * [Feedback]Remove unneeded foreach * [Feedback]Shortcut Guide svgs with ** in project file * [Feedback]Fix spellcheck
2023-07-20 00:12:46 +01:00
sei.lpFile = L"WinUI3Apps\\PowerToys.Hosts.exe";
2022-10-13 13:05:43 +02:00
sei.nShow = SW_SHOWNORMAL;
sei.lpParameters = executable_args.data();
if (runas)
{
sei.lpVerb = L"runas";
}
if (ShellExecuteExW(&sei))
{
Logger::trace("Successfully started the Hosts process");
}
else
{
Logger::error(L"Hosts failed to start. {}", get_last_error_or_default(GetLastError()));
}
m_hProcess = sei.hProcess;
}
public:
EventWaiter m_showEventWaiter;
EventWaiter m_showAdminEventWaiter;
2022-10-13 13:05:43 +02:00
HostsModuleInterface()
{
app_name = GET_RESOURCE_STRING(IDS_HOSTS_NAME);
app_key = ModuleKey;
LoggerHelpers::init_logger(app_key, L"ModuleInterface", LogSettings::hostsLoggerName);
m_hShowEvent = CreateDefaultEvent(CommonSharedConstants::SHOW_HOSTS_EVENT);
if (!m_hShowEvent)
{
Logger::error(L"Failed to create show hosts event");
auto message = get_last_error_message(GetLastError());
if (message.has_value())
{
Logger::error(message.value());
}
}
m_hShowAdminEvent = CreateDefaultEvent(CommonSharedConstants::SHOW_HOSTS_ADMIN_EVENT);
if (!m_hShowAdminEvent)
{
Logger::error(L"Failed to create show hosts admin event");
auto message = get_last_error_message(GetLastError());
if (message.has_value())
{
Logger::error(message.value());
}
}
m_showEventWaiter = EventWaiter(CommonSharedConstants::SHOW_HOSTS_EVENT, [&](int err)
{
if (m_enabled && err == ERROR_SUCCESS)
{
Logger::trace(L"{} event was signaled", CommonSharedConstants::SHOW_HOSTS_EVENT);
if (is_process_running())
{
bring_process_to_front();
}
else
{
launch_process(false);
}
Trace::ActivateEditor();
}
});
m_showAdminEventWaiter = EventWaiter(CommonSharedConstants::SHOW_HOSTS_ADMIN_EVENT, [&](int err)
{
if (m_enabled && err == ERROR_SUCCESS)
{
Logger::trace(L"{} event was signaled", CommonSharedConstants::SHOW_HOSTS_ADMIN_EVENT);
if (is_process_running())
{
bring_process_to_front();
}
else
{
launch_process(true);
}
Trace::ActivateEditor();
}
});
2022-10-13 13:05:43 +02:00
}
~HostsModuleInterface()
{
m_enabled = false;
}
// Destroy the powertoy and free memory
virtual void destroy() override
{
Logger::trace("HostsModuleInterface::destroy()");
if (m_hShowEvent)
{
CloseHandle(m_hShowEvent);
m_hShowEvent = nullptr;
}
if (m_hShowAdminEvent)
{
CloseHandle(m_hShowAdminEvent);
m_hShowAdminEvent = nullptr;
}
2022-10-13 13:05:43 +02:00
delete this;
}
// Return the localized display name of the powertoy
virtual const wchar_t* get_name() override
{
return app_name.c_str();
}
// Return the non localized key of the powertoy, this will be cached by the runner
virtual const wchar_t* get_key() override
{
return app_key.c_str();
}
2022-10-26 14:02:31 +01:00
// Return the configured status for the gpo policy for the module
virtual powertoys_gpo::gpo_rule_configured_t gpo_policy_enabled_configuration() override
{
return powertoys_gpo::getConfiguredHostsFileEditorEnabledValue();
}
virtual bool get_config(wchar_t* /*buffer*/, int* /*buffer_size*/) override
2022-10-13 13:05:43 +02:00
{
return false;
}
virtual void call_custom_action(const wchar_t* /*action*/) override
2022-10-13 13:05:43 +02:00
{
}
virtual void set_config(const wchar_t* /*config*/) override
2022-10-13 13:05:43 +02:00
{
}
virtual bool is_enabled() override
{
return m_enabled;
}
virtual void enable()
{
Logger::trace("HostsModuleInterface::enable()");
m_enabled = true;
Trace::EnableHostsFileEditor(true);
2022-10-13 13:05:43 +02:00
};
virtual void disable()
{
Logger::trace("HostsModuleInterface::disable()");
if (m_enabled)
{
if (m_hShowEvent)
{
ResetEvent(m_hShowEvent);
}
if (m_hShowAdminEvent)
{
ResetEvent(m_hShowAdminEvent);
}
2022-10-13 13:05:43 +02:00
TerminateProcess(m_hProcess, 1);
}
m_enabled = false;
Trace::EnableHostsFileEditor(false);
2022-10-13 13:05:43 +02:00
}
};
extern "C" __declspec(dllexport) PowertoyModuleIface* __cdecl powertoy_create()
{
return new HostsModuleInterface();
}