Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Windows.h>
- #include <string>
- #include <stdio.h>
- #include <boost/property_tree/ptree.hpp>
- #include <boost/property_tree/json_parser.hpp>
- const LPWSTR kAdblockPipeName = L"\\\\.\\pipe\\adblock";
- const LPWSTR kServerPipeName = kAdblockPipeName;
- const DWORD kPipeTimeout = 5000;
- const DWORD kClientPipeTimeout = 2000;
- #define SAFE_CLOSE_HANDLE(handle) \
- if (handle != NULL && handle != INVALID_HANDLE_VALUE) { \
- CloseHandle(handle); \
- handle = NULL; \
- }
- #define SAFE_SET_EVENT(event) \
- if (event != NULL && event != INVALID_HANDLE_VALUE) { \
- SetEvent(event); \
- }
- typedef enum _IPC_CMD {
- UNKNOWN = 0,
- ENABLE_ADBLOCK,
- DISABLE_ADBLOCK,
- ADD_DOMAIN_TO_EXCEPTION_LIST,
- REMOVE_DOMAIN_FROM_EXCEPTION_LIST
- } IPC_CMD;
- static void PRINT(const WCHAR* fmt, ...) {
- WCHAR buffer[512] = {0};
- va_list args;
- va_start(args, fmt);
- _vsnwprintf(buffer, _countof(buffer), fmt, args);
- va_end(args);
- OutputDebugStringW(buffer);
- }
- static void PRINT(const CHAR* fmt, ...) {
- CHAR buffer[512] = {0};
- va_list args;
- va_start(args, fmt);
- _vsnprintf(buffer, _countof(buffer), fmt, args);
- va_end(args);
- OutputDebugStringA(buffer);
- }
- class IPCClient {
- public:
- IPCClient();
- ~IPCClient();
- bool Init();
- void Send(const std::wstring& msg);
- private:
- HANDLE pipe_;
- };
- IPCClient::IPCClient() : pipe_(NULL) {}
- IPCClient::~IPCClient() { SAFE_CLOSE_HANDLE(pipe_); }
- bool IPCClient::Init() {
- while (true) {
- pipe_ = CreateFileW(kServerPipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL,
- OPEN_EXISTING, 0, NULL);
- if (pipe_ != INVALID_HANDLE_VALUE) {
- break;
- }
- // Exit if an error other than ERROR_PIPE_BUSY occurs.
- if (GetLastError() != ERROR_PIPE_BUSY) {
- PRINT("Could not open pipe: 0x%08x\n", GetLastError());
- return false;
- }
- // All pipe instances are busy, so wait for 2 seconds.
- if (!WaitNamedPipeW(kServerPipeName, kClientPipeTimeout)) {
- PRINT("Could not open pipe: %d seconds wait timed out",
- kClientPipeTimeout);
- return false;
- }
- }
- return true;
- }
- void IPCClient::Send(const std::wstring& msg) {
- DWORD bytes_written = 0;
- if (!WriteFile(pipe_, msg.c_str(), sizeof(WCHAR) * (msg.size() + 1),
- &bytes_written, NULL)) {
- PRINT("Write data to pipe failed: 0x%08x\n", GetLastError());
- }
- }
- int main() {
- IPCClient ipc_client;
- ipc_client.Init();
- {
- boost::property_tree::wptree root;
- std::wstringstream ss;
- root.put<int>(L"cmd", int(DISABLE_ADBLOCK));
- boost::property_tree::write_json(ss, root, false);
- ipc_client.Send(ss.str());
- }
- {
- boost::property_tree::wptree root;
- std::wstringstream ss;
- root.put<int>(L"cmd", int(ENABLE_ADBLOCK));
- boost::property_tree::write_json(ss, root, false);
- ipc_client.Send(ss.str());
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement