mireado

starting commit

/* Copyright (C) 2010-2012 kaosu (qiupf2000@gmail.com)
* This file is part of the Interactive Text Hooker.
* Interactive Text Hooker is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
template <class T, unsigned int default_size>
class PointerTable
{
public:
PointerTable()
{
assert((default_size & (default_size - 1)) == 0);
size = default_size;
table = new T*[size];
used = 0;
next = 0;
memset(table, 0, size * sizeof(T*));
}
~PointerTable()
{
delete table;
}
T* Set(unsigned int number, T* ptr)
{
if (number >= size - 2)
{
unsigned int new_size = size;
while (number >= new_size - 2) new_size <<= 1;
Resize(new_size);
}
T* original = table[number + 1];
table[number + 1] = ptr;
if (ptr == 0) //Clear pointer.
{
if (number < next) next = number;
if (number == used - 1) //Last used position is cleared.
{
table[0] = (T*)1;
for (used--; table[used] == 0; used--);
}
}
else //Set pointer.
{
__assume(number < size - 2); //Otherwise a resize operation is invoked.
if (number == next)
{
next++; //Next position is occupied.
for (next++; table[next]; next++); //There is always a zero in the end.
next--; //next is zero based but the table start at one(zero is used as sentry).
}
if (number >= used) used = number + 1;
}
return original;
}
T* Get(unsigned int number)
{
number++;
if (number <= used) return table[number];
else return 0;
}
T* operator [](unsigned int number)
{
number++;
if (number <= used) return table[number];
else return 0;
}
void Append(T* ptr)
{
Set(next,ptr);
}
void Resize(unsigned int new_size)
{
assert(new_size > size);
assert((new_size & (new_size - 1)) == 0);
assert(new_size < 0x10000);
T** temp = new T*[new_size];
memcpy(temp, table, size * sizeof(T*));
memset(temp + size, 0, (new_size - size) * sizeof(T*));
delete table;
size = new_size;
table = temp;
}
void DeleteAll() //Release all pointers on demand.
{
T* p;
next = 0;
while (used)
{
p = table[used];
if (p) delete p;
table[used] = 0;
used--;
}
}
void Reset() //Reset without release pointers.
{
memset(table, 0, sizeof(T*) * (used + 1));
next = 0;
used = 0;
}
unsigned int size,next,used;
T** table;
};
#include "ProcessWindow.h"
#include "resource.h"
#include "ith/host/srv.h"
#include "ith/host/hookman.h"
#include "ProfileManager.h"
#include "Profile.h"
extern HookManager* man; // main.cpp
extern ProfileManager* pfman; // ProfileManager.cpp
ProcessWindow::ProcessWindow(HWND hDialog) : hDlg(hDialog)
{
hbRefresh = GetDlgItem(hDlg, IDC_BUTTON1);
hbAttach = GetDlgItem(hDlg, IDC_BUTTON2);
hbDetach = GetDlgItem(hDlg, IDC_BUTTON3);
hbAddProfile = GetDlgItem(hDlg, IDC_BUTTON5);
hbRemoveProfile = GetDlgItem(hDlg, IDC_BUTTON6);
EnableWindow(hbAddProfile, FALSE);
EnableWindow(hbRemoveProfile, FALSE);
hlProcess = GetDlgItem(hDlg, IDC_LIST1);
heOutput = GetDlgItem(hDlg, IDC_EDIT1);
ListView_SetExtendedListViewStyleEx(hlProcess, LVS_EX_FULLROWSELECT, LVS_EX_FULLROWSELECT);
InitProcessDlg();
RefreshProcess();
}
void ProcessWindow::InitProcessDlg()
{
LVCOLUMN lvc = {};
lvc.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvc.fmt = LVCFMT_RIGHT; // left-aligned column
lvc.cx = 40;
lvc.pszText = L"PID";
ListView_InsertColumn(hlProcess, 0, &lvc);
lvc.cx = 100;
lvc.fmt = LVCFMT_LEFT; // left-aligned column
lvc.pszText = L"Name";
ListView_InsertColumn(hlProcess, 1, &lvc);
}
void ProcessWindow::RefreshProcess()
{
ListView_DeleteAllItems(hlProcess);
LVITEM item = {};
item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_STATE;
DWORD idProcess[1024], cbNeeded;
WCHAR path[MAX_PATH];
if (EnumProcesses(idProcess, sizeof(idProcess), &cbNeeded))
{
DWORD len = cbNeeded / sizeof(DWORD);
for (DWORD i = 0; i < len; ++i)
{
DWORD pid = idProcess[i];
UniqueHandle hProcess(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid));
if (hProcess)
{
if (GetProcessImageFileName(hProcess.get(), path, MAX_PATH))
{
WCHAR buffer[256];
std::swprintf(buffer, L"%d", pid);
PWCHAR name = wcsrchr(path, L'\\') + 1;
item.pszText = buffer;
item.lParam = pid;
ListView_InsertItem(hlProcess, &item);
ListView_SetItemText(hlProcess, item.iItem, 1, name);
}
}
}
}
}
void ProcessWindow::AttachProcess()
{
DWORD pid = GetSelectedPID();
if (IHF_InjectByPID(pid) != -1)
RefreshThreadWithPID(pid, true);
}
void ProcessWindow::DetachProcess()
{
DWORD pid = GetSelectedPID();
if (IHF_ActiveDetachProcess(pid) == 0)
RefreshThreadWithPID(pid, false);
}
void ProcessWindow::AddCurrentToProfile()
{
DWORD pid = GetSelectedPID();
auto path = GetProcessPath(pid);
if (!path.empty())
{
Profile* pf = pfman->AddProfile(path, pid);
pfman->FindProfileAndUpdateHookAddresses(pid, path);
RefreshThread(ListView_GetSelectionMark(hlProcess));
}
}
void ProcessWindow::RemoveCurrentFromProfile()
{
DWORD pid = GetSelectedPID();
auto path = GetProcessPath(pid);
if (!path.empty())
{
pfman->DeleteProfile(path);
RefreshThread(ListView_GetSelectionMark(hlProcess));
}
}
void ProcessWindow::RefreshThread(int index)
{
LVITEM item = {};
item.mask = LVIF_PARAM;
item.iItem = index;
ListView_GetItem(hlProcess, &item);
DWORD pid = item.lParam;
bool isAttached = man->GetProcessRecord(pid) != NULL;
RefreshThreadWithPID(pid, isAttached);
}
void ProcessWindow::RefreshThreadWithPID(DWORD pid, bool isAttached)
{
EnableWindow(hbDetach, isAttached);
EnableWindow(hbAttach, !isAttached);
auto path = GetProcessPath(pid);
bool hasProfile = !path.empty() && pfman->HasProfile(path);
EnableWindow(hbAddProfile, isAttached && !hasProfile);
EnableWindow(hbRemoveProfile, hasProfile);
if (pid == GetCurrentProcessId())
EnableWindow(hbAttach, FALSE);
}
DWORD ProcessWindow::GetSelectedPID()
{
LVITEM item={};
item.mask = LVIF_PARAM;
item.iItem = ListView_GetSelectionMark(hlProcess);
ListView_GetItem(hlProcess, &item);
return item.lParam;
}
#pragma once
#include "ITH.h"
class ProcessWindow
{
public:
ProcessWindow(HWND hDialog);
void InitProcessDlg();
void RefreshProcess();
void AttachProcess();
void DetachProcess();
void AddCurrentToProfile();
void RemoveCurrentFromProfile();
void RefreshThread(int index);
private:
void RefreshThreadWithPID(DWORD pid, bool isAttached);
DWORD GetSelectedPID();
HWND hDlg;
HWND hlProcess;
HWND hbRefresh,hbAttach,hbDetach,hbAddProfile,hbRemoveProfile;
HWND heOutput;
};
/* Copyright (C) 2010-2012 kaosu (qiupf2000@gmail.com)
* This file is part of the Interactive Text Hooker.
* Interactive Text Hooker is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ITH.h"
#include "ith/host/srv.h"
#include "ith/host/hookman.h"
#include "ith/common/types.h"
#include "ith/common/const.h"
#include "Profile.h"
#include "utility.h"
Profile::Profile(const std::wstring& title) :
select_index(-1),
title(title)
{}
std::vector<thread_ptr>::const_iterator Profile::FindThreadProfile(const ThreadParameter& tp) const
{
auto thread_profile = std::find_if(threads.begin(), threads.end(),
[&tp](const thread_ptr& thread_profile) -> bool
{
if (thread_profile->HookAddress() != tp.hook)
return false;
DWORD t1 = thread_profile->Return();
DWORD t2 = tp.retn;
if (thread_profile->Flags() & THREAD_MASK_RETN)
{
t1 &= 0xFFFF;
t2 &= 0xFFFF;
}
if (t1 != t2)
return false;
t1 = thread_profile->Split();
t2 = tp.spl;
if (thread_profile->Flags() & THREAD_MASK_SPLIT)
{
t1 &= 0xFFFF;
t2 &= 0xFFFF;
}
return t1 == t2;
});
return thread_profile;
}
const std::vector<hook_ptr>& Profile::Hooks() const
{
return hooks;
}
const std::vector<thread_ptr>& Profile::Threads() const
{
return threads;
}
const std::vector<link_ptr>& Profile::Links() const
{
return links;
}
bool Profile::XmlReadProfile(pugi::xml_node profile)
{
auto hooks_node = profile.child(L"Hooks");
auto threads_node = profile.child(L"Threads");
auto links_node = profile.child(L"Links");
if (hooks_node && !XmlReadProfileHook(hooks_node))
return false;
if (threads_node && !XmlReadProfileThread(threads_node))
return false;
if (links_node && !XmlReadProfileLink(links_node))
return false;
auto select_node = profile.child(L"Select");
if (select_node)
{
auto thread_index = select_node.attribute(L"ThreadIndex");
if (!thread_index)
return false;
DWORD tmp_select = std::stoul(thread_index.value(), NULL, 16);
select_index = tmp_select & 0xFFFF;
}
return true;
}
bool Profile::XmlReadProfileHook(pugi::xml_node hooks_node)
{
for (auto hook = hooks_node.begin(); hook != hooks_node.end(); ++hook)
{
std::wstring name = hook->name();
if (name.empty() || name.compare(L"Hook") != 0)
return false;
auto type = hook->attribute(L"Type");
if (!type || type.empty())
return false;
auto code = hook->attribute(L"Code");
if (!code)
return false;
std::wstring code_value = code.value();
HookParam hp = {};
switch (type.value()[0])
{
case L'H':
if (code_value[0] != L'/')
return false;
if (code_value[1] != L'H' && code_value[1] != L'h')
return false;
if (Parse(code_value.substr(2), hp))
{
auto name = hook->attribute(L"Name");
if (!name || name.empty())
AddHook(hp, L"");
else
AddHook(hp, name.value());
}
break;
default:
return false;
}
}
return true;
}
bool Profile::XmlReadProfileThread(pugi::xml_node threads_node)
{
std::wstring hook_name_buffer;
for (auto thread = threads_node.begin(); thread != threads_node.end(); ++thread)
{
std::wstring name = thread->name();
if (name.empty() || name.compare(L"Thread") != 0)
return false;
auto hook_name = thread->attribute(L"HookName");
if (!hook_name)
return false;
auto context = thread->attribute(L"Context");
if (!context)
return false;
auto sub_context = thread->attribute(L"SubContext");
if (!sub_context)
return false;
auto mask = thread->attribute(L"Mask");
if (!mask)
return false;
DWORD mask_tmp = std::stoul(mask.value(), NULL, 16);
auto comment = thread->attribute(L"Comment");
auto retn = std::stoul(context.value(), NULL, 16);
WORD hm_index = 0;
auto hook_addr = 0;
auto split = std::stoul(sub_context.value(), NULL, 16);
WORD flags = mask_tmp & 0xFFFF;
auto tp = new ThreadProfile(hook_name.value(), retn, split, hook_addr, hm_index, flags,
comment.value());
AddThread(thread_ptr(tp));
}
return true;
}
bool Profile::XmlReadProfileLink(pugi::xml_node links_node)
{
for (auto link = links_node.begin(); link != links_node.end(); ++link)
{
std::wstring name = link->name();
if (name.empty() || name.compare(L"Link") != 0)
return false;
auto from = link->attribute(L"From");
if (!from)
return false;
DWORD link_from = std::stoul(from.value(), NULL, 16);
auto to = link->attribute(L"To");
if (!to)
return false;
DWORD link_to = std::stoul(to.value(), NULL, 16);
auto lp = new LinkProfile(link_from & 0xFFFF, link_to & 0xFFFF);
AddLink(link_ptr(lp));
}
return true;
}
bool Profile::XmlWriteProfile(pugi::xml_node profile_node)
{
if (!hooks.empty())
{
auto node = profile_node.append_child(L"Hooks");
XmlWriteProfileHook(node);
}
if (!threads.empty())
{
auto node = profile_node.append_child(L"Threads");
XmlWriteProfileThread(node);
}
if (!links.empty())
{
auto node = profile_node.append_child(L"Links");
XmlWriteProfileLink(node);
}
if (select_index != 0xFFFF)
{
auto node = profile_node.append_child(L"Select");
node.append_attribute(L"ThreadIndex") = select_index;
}
return true;
}
bool Profile::XmlWriteProfileHook(pugi::xml_node hooks_node)
{
for (auto hook = hooks.begin(); hook != hooks.end(); ++hook)
{
auto hook_node = hooks_node.append_child(L"Hook");
hook_node.append_attribute(L"Type") = L"H";
hook_node.append_attribute(L"Code") = GetCode((*hook)->HP()).c_str();
if (!(*hook)->Name().empty())
hook_node.append_attribute(L"Name") = (*hook)->Name().c_str();
}
return true;
}
bool Profile::XmlWriteProfileThread(pugi::xml_node threads_node)
{
for (auto thread = threads.begin(); thread != threads.end(); ++thread)
{
const std::wstring& name = (*thread)->HookName();
if (name.empty())
return false;
auto node = threads_node.append_child(L"Thread");
node.append_attribute(L"HookName") = name.c_str();
node.append_attribute(L"Mask") = ToHexString((*thread)->Flags() & 3).c_str();
node.append_attribute(L"SubContext") = ToHexString((*thread)->Split()).c_str();
node.append_attribute(L"Context") = ToHexString((*thread)->Return()).c_str();
if (!(*thread)->Comment().empty())
node.append_attribute(L"Comment") = (*thread)->Comment().c_str();
}
return true;
}
bool Profile::XmlWriteProfileLink(pugi::xml_node links_node)
{
for (auto link = links.begin(); link != links.end(); ++link)
{
auto node = links_node.append_child(L"Link");
node.append_attribute(L"From") = ToHexString((*link)->FromIndex()).c_str();
node.append_attribute(L"To") = ToHexString((*link)->ToIndex()).c_str();
}
return true;
}
void Profile::Clear()
{
title = L"";
select_index = -1;
hooks.clear();
threads.clear();
links.clear();
}
int Profile::AddHook(const HookParam& hp, const std::wstring& name)
{
//if (hook_count == 4) return;
auto it = std::find_if(hooks.begin(), hooks.end(), [&hp](hook_ptr& hook)
{
return hook->HP().addr == hp.addr &&
hook->HP().module == hp.module &&
hook->HP().function == hp.function;
});
if (it != hooks.end())
return it - hooks.begin();
hooks.emplace_back(new HookProfile(hp, name));
return hooks.size() - 1;
}
// add the thread profile and return its index
int Profile::AddThread(thread_ptr tp)
{
auto it = std::find_if(threads.begin(), threads.end(), [&tp](thread_ptr& thread)
{
return thread->HookName().compare(tp->HookName()) == 0 &&
thread->Return() == tp->Return() &&
thread->Split() == tp->Split();
});
if (it != threads.end())
return it - threads.begin();
threads.push_back(std::move(tp));
return threads.size() - 1;
}
int Profile::AddLink(link_ptr lp)
{
auto it = std::find_if(links.begin(), links.end(), [&lp] (link_ptr& link)
{
return link->FromIndex() == lp->FromIndex() &&
link->ToIndex() == lp->ToIndex();
});
if (it != links.end())
return it - links.begin();
links.push_back(std::move(lp));
return links.size() - 1;
}
void Profile::RemoveHook(DWORD index)
{
if (index >= 0 && index < hooks.size())
hooks.erase(hooks.begin() + index);
}
void Profile::RemoveThread(DWORD index)
{
if (index >= 0 && index < threads.size())
{
links.erase(std::remove_if(links.begin(), links.end(), [index](link_ptr& link)
{
return link->FromIndex() == index + 1 || link->ToIndex() == index + 1;
}), links.end());
if (select_index == index)
select_index = -1;
threads.erase(threads.begin() + index);
if (index < select_index)
select_index--;
}
}
void Profile::RemoveLink(DWORD index)
{
if (index >= 0 && index < links.size())
links.erase(links.begin() + index);
}
const std::wstring& Profile::Title() const
{
return title;
}
/* Copyright (C) 2010-2012 kaosu (qiupf2000@gmail.com)
* This file is part of the Interactive Text Hooker.
* Interactive Text Hooker is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "ITH.h"
#include "ith/common/types.h" // HookParam
struct ThreadParameter;
#define THREAD_MASK_RETN 1
#define THREAD_MASK_SPLIT 2
class HookProfile
{
HookParam hp;
std::wstring name;
public:
HookProfile(const HookParam& hp, const std::wstring& name):
hp(hp),
name(name)
{}
const HookParam& HP() const { return hp; };
const std::wstring& Name() const { return name; };
};
class ThreadProfile
{
std::wstring hook_name;
DWORD retn;
DWORD split;
DWORD hook_addr;
WORD hm_index, flags;
std::wstring comment;
public:
ThreadProfile(const std::wstring& hook_name,
DWORD retn,
DWORD split,
DWORD hook_addr,
WORD hm_index,
WORD flags,
const std::wstring& comment) :
hook_name(hook_name),
retn(retn),
split(split),
hook_addr(hook_addr),
hm_index(hm_index),
flags(flags),
comment(comment)
{
}
const std::wstring& HookName() const { return hook_name; }
const std::wstring& Comment() const { return comment; }
DWORD Return() const { return retn; }
DWORD Split() const { return split; }
DWORD& HookAddress() { return hook_addr; }
WORD& HookManagerIndex() { return hm_index; }
WORD Flags() const { return flags; }
};
class LinkProfile
{
WORD from_index, to_index;
public:
LinkProfile(WORD from_index, WORD to_index):
from_index(from_index),
to_index(to_index)
{}
WORD FromIndex() const { return from_index; }
WORD ToIndex() const { return to_index; }
};
typedef std::unique_ptr<HookProfile> hook_ptr;
typedef std::unique_ptr<ThreadProfile> thread_ptr;
typedef std::unique_ptr<LinkProfile> link_ptr;
class Profile
{
public:
Profile(const std::wstring& title);
bool XmlReadProfile(pugi::xml_node profile_node);
bool XmlWriteProfile(pugi::xml_node profile_node);
int AddHook(const HookParam& hp, const std::wstring& name);
int AddThread(thread_ptr tp);
int AddLink(link_ptr lp);
void Clear();
const std::vector<hook_ptr>& Hooks() const;
const std::vector<thread_ptr>& Threads() const;
const std::vector<link_ptr>& Links() const;
const std::wstring& Title() const;
std::vector<thread_ptr>::const_iterator FindThreadProfile(const ThreadParameter& tp) const;
WORD& SelectedIndex() { return select_index; }
private:
void RemoveLink(DWORD index);
void RemoveHook(DWORD index);
void RemoveThread(DWORD index);
bool XmlReadProfileHook(pugi::xml_node hooks_node);
bool XmlReadProfileThread(pugi::xml_node threads_node);
bool XmlReadProfileLink(pugi::xml_node links_node);
bool XmlWriteProfileHook(pugi::xml_node hooks_node);
bool XmlWriteProfileThread(pugi::xml_node threads_node);
bool XmlWriteProfileLink(pugi::xml_node links_node);
std::wstring title;
std::vector<hook_ptr> hooks;
std::vector<thread_ptr> threads;
std::vector<link_ptr> links;
WORD select_index;
};
#include "ProfileManager.h"
#include "Profile.h"
#include "ith/host/srv.h"
#include "ith/host/hookman.h"
#include "ith/common/types.h"
#include "ith/common/const.h"
extern HookManager* man; // main.cpp
extern LONG auto_inject, auto_insert, inject_delay; // main.cpp
extern LONG insert_delay, process_time; // main.cpp
bool MonitorFlag;
ProfileManager* pfman;
DWORD WINAPI MonitorThread(LPVOID lpThreadParameter);
void AddHooksToProfile(Profile& pf, const ProcessRecord& pr);
void AddThreadsToProfile(Profile& pf, const ProcessRecord& pr, DWORD pid);
DWORD AddThreadToProfile(Profile& pf, const ProcessRecord& pr, TextThread& thread);
void MakeHookRelative(const ProcessRecord& pr, HookParam& hp);
std::wstring GetHookNameByAddress(const ProcessRecord& pr, DWORD hook_address);
void GetHookNameToAddressMap(const ProcessRecord& pr, std::map<std::wstring, DWORD>& hookNameToAddress);
ProfileManager::ProfileManager():
hMonitorThread(IthCreateThread(MonitorThread, 0))
{
LoadProfile();
}
ProfileManager::~ProfileManager()
{
SaveProfile();
WaitForSingleObject(hMonitorThread.get(), 0);
}
Profile* ProfileManager::GetProfile(DWORD pid)
{
std::wstring path = GetProcessPath(pid);
if (!path.empty())
{
auto node = profile_tree.find(path);
if (node != profile_tree.end())
return node->second.get();
}
return NULL;
}
bool ProfileManager::AddProfile(pugi::xml_node game)
{
auto file = game.child(L"File");
auto profile = game.child(L"Profile");
if (!file || !profile)
return false;
auto path = file.attribute(L"Path");
if (!path)
return false;
auto profile_title = game.attribute(L"Title");
auto title = profile_title ? profile_title.value() : L"";
auto pf = new Profile(title);
if (!pf->XmlReadProfile(profile))
return false;
AddProfile(path.value(), profile_ptr(pf));
return true;
}
Profile* ProfileManager::AddProfile(const std::wstring& path, DWORD pid)
{
CSLock lock(cs);
auto& pf = profile_tree[path];
if (!pf)
{
std::wstring title = GetProcessTitle(pid);
pf.reset(new Profile(title));
}
return pf.get();
}
Profile* ProfileManager::AddProfile(const std::wstring& path, profile_ptr new_profile)
{
CSLock lock(cs);
auto& pf = profile_tree[path];
if (!pf)
pf.swap(new_profile);
return pf.get();
}
void ProfileManager::WriteProfileXml(const std::wstring& path, Profile& pf, pugi::xml_node root)
{
auto game = root.append_child(L"Game");
auto file_node = game.append_child(L"File");
file_node.append_attribute(L"Path") = path.c_str();
auto profile_node = game.append_child(L"Profile");
pf.XmlWriteProfile(profile_node);
if (!pf.Title().empty())
{
if (!game.attribute(L"Title"))
game.append_attribute(L"Title");
game.attribute(L"Title") = pf.Title().c_str();
}
}
void ProfileManager::LoadProfile()
{
pugi::xml_document doc;
UniqueHandle hFile(IthCreateFile(L"ITH_Profile.xml", GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING));
if (hFile.get() == INVALID_HANDLE_VALUE)
return;
DWORD size = GetFileSize(hFile.get(), NULL);
std::unique_ptr<char[]> buffer(new char[size]);
ReadFile(hFile.get(), buffer.get(), size, &size, NULL);
auto result = doc.load_buffer(buffer.get(), size);
if (!result)
return;
auto root = doc.root().child(L"ITH_Profile");
if (!root)
return;
for (auto game = root.begin(); game != root.end(); ++game)
AddProfile(*game);
}
void ProfileManager::SaveProfile()
{
pugi::xml_document doc;
auto root = doc.append_child(L"ITH_Profile");
for (auto it = profile_tree.begin(); it != profile_tree.end(); ++it) {
auto& path = it->first;
auto& profile = it->second;
WriteProfileXml(path, *profile, root);
}
UniqueHandle hFile(IthCreateFile(L"ITH_Profile.xml", GENERIC_WRITE, 0, CREATE_ALWAYS));
if (hFile.get() != INVALID_HANDLE_VALUE)
{
FileWriter fw(hFile.get());
doc.save(fw);
}
}
void ProfileManager::DeleteProfile(const std::wstring& path)
{
CSLock lock(cs);
profile_tree.erase(profile_tree.find(path));
}
void ProfileManager::FindProfileAndUpdateHookAddresses(DWORD pid, const std::wstring& path)
{
if (path.empty())
return;
auto it = profile_tree.find(path);
if (it == profile_tree.end())
return;
auto& pf = it->second;
const ProcessRecord* pr = man->GetProcessRecord(pid);
if (pr == NULL)
return;
// hook name -> hook address
std::map<std::wstring, DWORD> hookNameToAddress;
GetHookNameToAddressMap(*pr, hookNameToAddress);
for (auto thread_profile = pf->Threads().begin(); thread_profile != pf->Threads().end();
++thread_profile)
{
auto it = hookNameToAddress.find((*thread_profile)->HookName());
if (it != hookNameToAddress.end())
(*thread_profile)->HookAddress() = it->second;
}
}
void GetHookNameToAddressMap(const ProcessRecord& pr,
std::map<std::wstring, DWORD>& hookNameToAddress)
{
WaitForSingleObject(pr.hookman_mutex, 0);
auto hooks = (const Hook*)pr.hookman_map;
for (DWORD i = 0; i < MAX_HOOK; ++i)
{
if (hooks[i].Address() == 0)
continue;
auto& hook = hooks[i];
std::unique_ptr<WCHAR[]> name(new WCHAR[hook.NameLength() * 2]);
if (ReadProcessMemory(pr.process_handle, hook.Name(), name.get(), hook.NameLength() * 2, NULL))
hookNameToAddress[name.get()] = hook.Address();
}
ReleaseMutex(pr.hookman_mutex);
}
bool ProfileManager::HasProfile(const std::wstring& path)
{
return profile_tree.find(path) != profile_tree.end();
}
DWORD ProfileManager::ProfileCount()
{
return profile_tree.size();
}
DWORD WINAPI InjectThread(LPVOID lpThreadParameter)
{
DWORD pid = (DWORD)lpThreadParameter;
Sleep(inject_delay);
if (man == NULL)
return 0;
DWORD status = IHF_InjectByPID(pid);
if (!auto_insert)
return status;
if (status == -1)
return status;
Sleep(insert_delay);
const Profile* pf = pfman->GetProfile(pid);
if (pf)
{
SendParam sp;
sp.type = 0;
for (auto hp = pf->Hooks().begin(); hp != pf->Hooks().end(); ++hp)
IHF_InsertHook(pid, const_cast<HookParam*>(&(*hp)->HP()), (*hp)->Name().c_str());
}
return status;
}
DWORD WINAPI MonitorThread(LPVOID lpThreadParameter)
{
while (MonitorFlag)
{
DWORD aProcesses[1024], cbNeeded, cProcesses;
if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
break;
cProcesses = cbNeeded / sizeof(DWORD);
for (size_t i = 0; i < cProcesses; ++i)
{
Sleep(process_time);
if (!auto_inject || man == NULL || man->GetProcessRecord(aProcesses[i]))
continue;
std::wstring process_path = GetProcessPath(aProcesses[i]);
if (!process_path.empty() && pfman->HasProfile(process_path))
{
UniqueHandle hThread(IthCreateThread(InjectThread, aProcesses[i]));
WaitForSingleObject(hThread.get(), 0);
}
}
}
return 0;
}
DWORD SaveProcessProfile(DWORD pid)
{
const ProcessRecord* pr = man->GetProcessRecord(pid);
if (pr == NULL)
return 0;
std::wstring path = GetProcessPath(pid);
if (path.empty())
return 0;
Profile* pf = pfman->GetProfile(pid);
if (pf != NULL)
pf->Clear();
else
pf = pfman->AddProfile(path, pid);
AddHooksToProfile(*pf, *pr);
AddThreadsToProfile(*pf, *pr, pid);
return 0;
}
void AddHooksToProfile(Profile& pf, const ProcessRecord& pr)
{
WaitForSingleObject(pr.hookman_mutex, 0);
auto hooks = (const Hook*)pr.hookman_map;
for (DWORD i = 0; i < MAX_HOOK; ++i)
{
if (hooks[i].Address() == 0)
continue;
auto& hook = hooks[i];
DWORD type = hook.Type();
if ((type & HOOK_ADDITIONAL) && (type & HOOK_ENGINE) == 0)
{
std::unique_ptr<WCHAR[]> name(new WCHAR[hook.NameLength() * 2]);
if (ReadProcessMemory(pr.process_handle, hook.Name(), name.get(), hook.NameLength() * 2, NULL))
{
if (hook.hp.module)
{
HookParam hp = hook.hp;
MakeHookRelative(pr, hp);
pf.AddHook(hp, name.get());
}
else
pf.AddHook(hook.hp, name.get());
}
}
}
ReleaseMutex(pr.hookman_mutex);
}
void MakeHookRelative(const ProcessRecord& pr, HookParam& hp)
{
MEMORY_BASIC_INFORMATION info;
VirtualQueryEx(pr.process_handle, (LPCVOID)hp.addr, &info, sizeof(info));
hp.addr -= (DWORD)info.AllocationBase;
hp.function = 0;
}
void AddThreadsToProfile(Profile& pf, const ProcessRecord& pr, DWORD pid)
{
man->LockHookman();
ThreadTable* table = man->Table();
for (int i = 0; i < table->Used(); ++i)
{
TextThread* tt = table->FindThread(i);
if (tt == NULL || tt->GetThreadParameter()->pid != pid)
continue;
//if (tt->Status() & CURRENT_SELECT || tt->Link() || tt->GetComment())
if (tt->Status() & CURRENT_SELECT || tt->Link())
AddThreadToProfile(pf, pr, *tt);
}
man->UnlockHookman();
}
DWORD AddThreadToProfile(Profile& pf, const ProcessRecord& pr, TextThread& thread)
{
const ThreadParameter* tp = thread.GetThreadParameter();
std::wstring hook_name = GetHookNameByAddress(pr, tp->hook);
if (hook_name.empty())
return -1;
auto thread_profile = new ThreadProfile(hook_name, tp->retn, tp->spl, 0, 0,
THREAD_MASK_RETN | THREAD_MASK_SPLIT, L"");
DWORD threads_size = pf.Threads().size();
int thread_profile_index = pf.AddThread(thread_ptr(thread_profile));
if (thread_profile_index == threads_size) // new thread
{
WORD iw = thread_profile_index & 0xFFFF;
if (thread.Status() & CURRENT_SELECT)
pf.SelectedIndex() = iw;
if (thread.Link())
{
WORD to_index = AddThreadToProfile(pf, pr, *(thread.Link())) & 0xFFFF;
if (iw >= 0)
pf.AddLink(link_ptr(new LinkProfile(iw, to_index)));
}
}
return thread_profile_index; // in case more than one thread links to the same thread.
}
std::wstring GetHookNameByAddress(const ProcessRecord& pr, DWORD hook_address)
{
std::wstring hook_name;
WaitForSingleObject(pr.hookman_mutex, 0);
auto hooks = (const Hook*)pr.hookman_map;
for (int i = 0; i < MAX_HOOK; ++i)
{
auto& hook = hooks[i];
if (hook.Address() == hook_address)
{
std::unique_ptr<WCHAR[]> name(new WCHAR[hook.NameLength() * 2]);
if (ReadProcessMemory(pr.process_handle, hooks[i].Name(), name.get(), hook.NameLength() * 2, NULL))
hook_name = name.get();
break;
}
}
ReleaseMutex(pr.hookman_mutex);
return hook_name;
}
#pragma once
#include "ITH.h"
#include "utility.h" // UniqueHandle, CriticalSection
class Profile;
class ProfileManager
{
public:
ProfileManager();
~ProfileManager();
Profile* AddProfile(const std::wstring& path, DWORD pid);
void DeleteProfile(const std::wstring& path);
void LoadProfile();
void SaveProfile();
void FindProfileAndUpdateHookAddresses(DWORD pid, const std::wstring& path);
bool HasProfile(const std::wstring& path);
Profile* GetProfile(DWORD pid);
DWORD ProfileCount();
private:
typedef std::unique_ptr<Profile> profile_ptr;
typedef std::map<std::wstring, profile_ptr> profile_map;
ProfileManager(const ProfileManager&);
ProfileManager operator=(const ProfileManager&);
bool AddProfile(pugi::xml_node game);
Profile* AddProfile(const std::wstring& path, profile_ptr new_profile);
void WriteProfileXml(const std::wstring& path, Profile& pf, pugi::xml_node doc);
// locate profile with executable path
profile_map profile_tree;
CriticalSection cs;
UniqueHandle hMonitorThread;
};
#include "TextBuffer.h"
DWORD WINAPI FlushThread(LPVOID lParam); // window.cpp
TextBuffer::TextBuffer(HWND edit) : hThread(IthCreateThread(FlushThread, (DWORD)this)),
hEdit(edit),
running(true)
{
}
TextBuffer::~TextBuffer()
{
running = false;
WaitForSingleObject(hThread.get(), 0);
}
void TextBuffer::AddText(LPCWSTR str, int len, bool line)
{
CSLock lock(cs);
if (len > 0)
this->str.append(str, len);
line_break = line;
}
void TextBuffer::Flush()
{
CSLock lock(cs);
if (line_break || str.empty())
return;
DWORD t = Edit_GetTextLength(hEdit);
Edit_SetSel(hEdit, t, -1);
Edit_ReplaceSel(hEdit, str.c_str());
str.clear();
}
void TextBuffer::ClearBuffer()
{
CSLock lock(cs);
str.clear();
line_break = false;
}
#pragma once
#include "ITH.h"
#include "utility.h" // UniqueHandle, CriticalSection
class TextBuffer
{
public:
TextBuffer(HWND edit);
~TextBuffer();
void Flush();
void AddText(LPCWSTR str, int len, bool line);
void ClearBuffer();
bool Running() { return running; }
private:
CriticalSection cs;
bool line_break, running;
UniqueHandle hThread;
HWND hEdit;
std::wstring str;
};
/* Copyright (C) 2010-2012 kaosu (qiupf2000@gmail.com)
* This file is part of the Interactive Text Hooker.
* Interactive Text Hooker is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
const wchar_t* Warning=L"Warning!";
//command.cpp
const wchar_t* ErrorSyntax=L"Syntax error";
const wchar_t* Usage = L"Syntax:\r\n\
\r\n\
:H[ELP] - print help\r\n\
:Lfrom-to - link from thread 'from' to thread 'to'\r\n\
:Ufrom - unlink link from thread 'from'\r\n\
\r\n\
'from' and 'to' and hexadecimal thread numbers. The thread number is the first number in the combo box.\r\n\
\r\n\
Loader options:\r\n\
/P[{process_id|Nprocess_name}] - attach to process\r\n\
\r\n\
Hook options:\r\n\
/H[X]{A|B|W|S|Q}[N][data_offset[*drdo]][:sub_offset[*drso]]@addr[:module[:{name|#ordinal}]]\r\n\
\r\n\
All numbers in /H (except ordinal) are hexadecimal without any prefixes";
const wchar_t* ExtendedUsage = L"/H[X]{A|B|W|S|Q}[N][data_offset[*drdo]][:sub_offset[*drso]]@addr[:[module[:{name|#ordinal}]]]\r\n\
\r\n\
Set additional custom hook\r\n\
\r\n\
Hook types :\r\n\
A - DBCS char\r\n\
B - DBCS char(big-endian)\r\n\
W - UCS2 char\r\n\
S - MBCS string\r\n\
Q - UTF-16 string\r\n\
\r\n\
Parameters:\r\n\
X - use hardware breakpoints\r\n\
N - don't use contexts\r\n\
data_offset - stack offset to char / string pointer\r\n\
drdo - add a level of indirection to data_offset\r\n\
sub_offset - stack offset to subcontext\r\n\
drso - add a level of indirection to sub_offset\r\n\
addr - address of the hook\r\n\
module - name of the module to use as base for 'addr'\r\n\
name - name of the 'module' export to use as base for 'addr'\r\n\
ordinal - number of the 'module' export ordinal to use as base for 'addr'\r\n\
\r\n\
Negative values of 'data_offset' and 'sub_offset' refer to registers: \r\n\
- 4 for EAX, -8 for ECX, -C for EDX, -10 for EBX, -14 for ESP, -18 for EBP, -1C for ESI, -20 for EDI\r\n\
\r\n\
\"Add a level of indirection\" means in C/C++ style: (*(ESP+data_offset)+drdo) instead of (ESP+data_offset)\r\n\
\r\n\
All numbers except ordinal are hexadecimal without any prefixes";
//inject.cpp
const wchar_t* ErrorRemoteThread=L"Can't create remote thread.";
const wchar_t* ErrorOpenProcess=L"Can't open process.";
const wchar_t* ErrorNoProcess=L"Process not found";
const wchar_t* SelfAttach=L"Please do not attach to ITH.exe";
const wchar_t* AlreadyAttach=L"Process already attached.";
const wchar_t* FormatInject=L"Inject process %d. Module base %.8X";
//main.cpp
const wchar_t* NotAdmin=L"Can't enable SeDebugPrevilege. ITH might malfunction.\r\n\
Please run ITH as administrator or turn off UAC.";
//pipe.cpp
const wchar_t* ErrorCreatePipe=L"Can't create text pipe or too many instance.";
const wchar_t* FormatDetach=L"Process %d detached.";
const wchar_t* ErrorCmdQueueFull=L"Command queue full.";
const wchar_t* ErrorNoAttach=L"No process attached.";
//profile.cpp
const wchar_t* ErrorMonitor=L"Can't monitor process.";
//utility.cpp
const wchar_t* InitMessage=L"Copyright (C) 2010-2012 kaosu <qiupf2000@gmail.com>\r\n\
Copyright (C) 2015 zorkzero <zorkzero@hotmail.com>\r\n\
Source code <https://code.google.com/p/interactive-text-hooker/>\r\n\
General discussion <https://groups.google.com/forum/?fromgroups#!forum/interactive-text-hooker>";
const wchar_t* BackgroundMsg=L"Type \":h\" or \":help\" for help.";
const wchar_t* ErrorLinkExist=L"Link exist.";
const wchar_t* ErrorCylicLink=L"Link failed. No cyclic link allowed.";
const wchar_t* FormatLink=L"Link from thread%.4x to thread%.4x.";
const wchar_t* ErrorLink=L"Link failed. Source or/and destination thread not found.";
const wchar_t* ErrorDeleteCombo=L"Error delete from combo.";
//window.cpp
const wchar_t* ClassName=L"ITH";
const wchar_t* ClassNameAdmin=L"ITH (Administrator)";
const wchar_t* ErrorNotSplit=L"Need to enable split first!";
const wchar_t* ErrorNotModule=L"Need to enable module first!";
//Main window buttons
const wchar_t* ButtonTitleProcess=L"Process";
const wchar_t* ButtonTitleThread=L"Thread";
const wchar_t* ButtonTitleHook=L"Hook";
const wchar_t* ButtonTitleProfile=L"Profile";
const wchar_t* ButtonTitleOption=L"Option";
const wchar_t* ButtonTitleClear=L"Clear";
const wchar_t* ButtonTitleSave=L"Save";
const wchar_t* ButtonTitleTop=L"Top";
//Hook window
const wchar_t* SpecialHook=L"Special hook, no AGTH equivalent.";
//Process window
const wchar_t* TabTitlePID=L"PID";
const wchar_t* TabTitleMemory=L"Memory";
const wchar_t* TabTitleName=L"Name";
const wchar_t* TabTitleTID=L"TID";
const wchar_t* TabTitleStart=L"Start";
const wchar_t* TabTitleModule=L"Module";
const wchar_t* TabTitleState=L"State";
const wchar_t* SuccessAttach=L"Attach ITH to process successfully.";
const wchar_t* FailAttach=L"Failed to attach ITH to process.";
const wchar_t* SuccessDetach=L"ITH detach from process.";
const wchar_t* FailDetach=L"Detach failed.";
//Profile window
const wchar_t* ProfileExist=L"Profile already exists.";
const wchar_t* SuccessAddProfile=L"Profile added.";
const wchar_t* FailAddProfile=L"Fail to add profile";
const wchar_t* TabTitleNumber=L"No.";
const wchar_t* NoFile=L"Can't find file.";
const wchar_t* PathDismatch=L"Process name dismatch, continue?";
const wchar_t* SuccessImportProfile=L"Import profile success";
//const wchar_t* SuccessAddProfile=L"Profile added.";
\ No newline at end of file
/* Copyright (C) 2010-2012 kaosu (qiupf2000@gmail.com)
* This file is part of the Interactive Text Hooker.
* Interactive Text Hooker is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
extern const wchar_t* Warning;
//command.cpp
extern const wchar_t* ErrorSyntax;
extern const wchar_t* Usage;
extern const wchar_t* ExtendedUsage;
//inject.cpp
extern const wchar_t* ErrorRemoteThread;
extern const wchar_t* ErrorOpenProcess;
extern const wchar_t* ErrorNoProcess;
extern const wchar_t* SelfAttach;
extern const wchar_t* AlreadyAttach;
extern const wchar_t* FormatInject;
//main.cpp
extern const wchar_t* NotAdmin;
//pipe.cpp
extern const wchar_t* ErrorCreatePipe;
extern const wchar_t* FormatDetach;
extern const wchar_t* ErrorCmdQueueFull;
extern const wchar_t* ErrorNoAttach;
//profile.cpp
extern const wchar_t* ErrorMonitor;
//utility.cpp
extern const wchar_t* InitMessage;
extern const wchar_t* BackgroundMsg;
extern const wchar_t* ErrorLinkExist;
extern const wchar_t* ErrorCylicLink;
extern const wchar_t* FormatLink;
extern const wchar_t* ErrorLink;
extern const wchar_t* ErrorDeleteCombo;
//window.cpp
extern const wchar_t* ClassName;
extern const wchar_t* ClassNameAdmin;
extern const wchar_t* ErrorNotSplit;
extern const wchar_t* ErrorNotModule;
//Main window buttons
extern const wchar_t* ButtonTitleProcess;
extern const wchar_t* ButtonTitleThread;
extern const wchar_t* ButtonTitleHook;
extern const wchar_t* ButtonTitleProfile;
extern const wchar_t* ButtonTitleOption;
extern const wchar_t* ButtonTitleClear;
extern const wchar_t* ButtonTitleSave;
extern const wchar_t* ButtonTitleTop;
//Hook window
extern const wchar_t* SpecialHook;
//Process window
extern const wchar_t* TabTitlePID;
extern const wchar_t* TabTitleMemory;
extern const wchar_t* TabTitleName;
extern const wchar_t* TabTitleTID;
extern const wchar_t* TabTitleStart;
extern const wchar_t* TabTitleModule;
extern const wchar_t* TabTitleState;
extern const wchar_t* SuccessAttach;
extern const wchar_t* FailAttach;
extern const wchar_t* SuccessDetach;
extern const wchar_t* FailDetach;
//Profile window
extern const wchar_t* ProfileExist;
extern const wchar_t* SuccessAddProfile;
extern const wchar_t* FailAddProfile;
extern const wchar_t* TabTitleNumber;
extern const wchar_t* NoFile;
extern const wchar_t* PathDismatch;
extern const wchar_t* SuccessImportProfile;
\ No newline at end of file
/* Copyright (C) 2010-2012 kaosu (qiupf2000@gmail.com)
* This file is part of the Interactive Text Hooker.
* Interactive Text Hooker is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ITH.h"
#include "ith/host/srv.h"
#include "ith/host/hookman.h"
#include "ith/host/SettingManager.h"
#include "CustomFilter.h"
#include "profile.h"
#include "ProfileManager.h"
HINSTANCE hIns;
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE hInstance, DWORD nCmdShow, RECT *rc);
RECT window;
extern HWND hMainWnd; // windows.cpp
extern bool MonitorFlag; // ProfileManager.cpp
extern ProfileManager* pfman; // ProfileManager.cpp
extern "C" {
BOOL IthInitSystemService();
void IthCloseSystemService();
}
CustomFilter* uni_filter;
CustomFilter* mb_filter;
HookManager* man;
SettingManager* setman;
LONG split_time, cyclic_remove, global_filter;
LONG process_time, inject_delay, insert_delay,
auto_inject, auto_insert, clipboard_flag;
std::map<std::wstring, long> setting;
void RecordMBChar(WORD mb, PVOID f)
{
auto filter = (pugi::xml_node*)f;
DWORD m = mb;
WCHAR buffer[16];
std::swprintf(buffer, L"m%04X", m);
filter->append_attribute(buffer) = L"0";
}
void RecordUniChar(WORD uni, PVOID f)
{
auto filter = (pugi::xml_node*)f;
DWORD m = uni;
WCHAR buffer[16];
std::swprintf(buffer, L"u%04X", m);
filter->append_attribute(buffer) = L"0";
std::wstring text = filter->text().get();
text += (wchar_t)m;
filter->text().set(text.c_str());
}
void SaveSettings()
{
GetWindowRect(hMainWnd, &window);
setting[L"window_left"] = window.left;
setting[L"window_right"] = window.right;
setting[L"window_top"] = window.top;
setting[L"window_bottom"] = window.bottom;
setting[L"split_time"] = split_time;
setting[L"process_time"] = process_time;
setting[L"inject_delay"] = inject_delay;
setting[L"insert_delay"] = insert_delay;
setting[L"auto_inject"] = auto_inject;
setting[L"auto_insert"] = auto_insert;
setting[L"auto_copy"] = clipboard_flag;
setting[L"auto_suppress"] = cyclic_remove;
setting[L"global_filter"] = global_filter;
UniqueHandle hFile(IthCreateFile(L"ITH.xml", GENERIC_WRITE, FILE_SHARE_READ, CREATE_ALWAYS));
if (hFile.get() != INVALID_HANDLE_VALUE)
{
FileWriter fw(hFile.get());
pugi::xml_document doc;
auto root = doc.root().append_child(L"ITH_Setting");
for (auto it = setting.begin(); it != setting.end(); ++it)
root.append_attribute(it->first.c_str()).set_value(it->second);
auto filter = root.append_child(L"SingleCharFilter");
filter.append_child(pugi::xml_node_type::node_pcdata);
mb_filter->Traverse(RecordMBChar, &filter);
uni_filter->Traverse(RecordUniChar, &filter);
doc.save(fw);
}
}
void DefaultSettings()
{
setting[L"split_time"] = 200;
setting[L"process_time"] = 50;
setting[L"inject_delay"] = 3000;
setting[L"insert_delay"] = 500;
setting[L"auto_inject"] = 1;
setting[L"auto_insert"] = 1;
setting[L"auto_copy"] = 0;
setting[L"auto_suppress"] = 0;
setting[L"global_filter"] = 0;
setting[L"window_left"] = 100;
setting[L"window_right"] = 800;
setting[L"window_top"] = 100;
setting[L"window_bottom"] = 600;
}
void InitializeSettings()
{
split_time = setting[L"split_time"];
process_time = setting[L"process_time"];
inject_delay = setting[L"inject_delay"];
insert_delay = setting[L"insert_delay"];
auto_inject = setting[L"auto_inject"];
auto_insert = setting[L"auto_insert"];
clipboard_flag = setting[L"auto_copy"];
cyclic_remove = setting[L"auto_suppress"];
global_filter = setting[L"global_filter"];
window.left = setting[L"window_left"];
window.right = setting[L"window_right"];
window.top = setting[L"window_top"];
window.bottom = setting[L"window_bottom"];
if (auto_inject > 1)
auto_inject = 1;
if (auto_insert > 1)
auto_insert = 1;
if (clipboard_flag > 1)
clipboard_flag = 1;
if (cyclic_remove > 1)
cyclic_remove = 1;
if (window.right < window.left || window.right - window.left < 600)
window.right = window.left + 600;
if (window.bottom < window.top || window.bottom - window.top < 200)
window.bottom = window.top + 200;
}
void LoadSettings()
{
UniqueHandle hFile(IthCreateFile(L"ITH.xml", GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING));
if (hFile.get() != INVALID_HANDLE_VALUE)
{
DWORD size = GetFileSize(hFile.get(), NULL);
std::unique_ptr<char[]> buffer(new char[size]);
ReadFile(hFile.get(), buffer.get(), size, &size, NULL);
pugi::xml_document doc;
auto result = doc.load_buffer_inplace(buffer.get(), size);
if (!result)
return;
auto root = doc.root().child(L"ITH_Setting");
for (auto attr = root.attributes_begin(); attr != root.attributes_end(); ++attr)
{
auto it = setting.find(attr->name());
if (it != setting.end())
it->second = std::stoul(attr->value());
}
auto filter = root.child(L"SingleCharFilter");
if (filter)
{
for (auto attr = filter.attributes_begin(); attr != filter.attributes_end(); ++attr)
{
if (attr->name()[0] == L'm')
{
DWORD c = std::stoul(attr->name() + 1, NULL, 16);
mb_filter->Insert(c & 0xFFFF);
}
else if (attr->name()[0] == L'u')
{
DWORD c = std::stoul(attr->name() + 1, NULL, 16);
uni_filter->Insert(c & 0xFFFF);
}
}
std::wstring filter_value = filter.text().get();
for (auto it = filter_value.begin(); it != filter_value.end(); ++it)
{
WCHAR filter_unichar[2] = { *it, L'\0' };
char filter_mbchar[4];
WC_MB(filter_unichar, filter_mbchar, 4);
mb_filter->Insert(*(WORD*)filter_mbchar);
uni_filter->Insert(*it);
}
}
}
}
extern LPCWSTR ClassName, ClassNameAdmin;
static WCHAR mutex[] = L"ITH_RUNNING";
DWORD FindITH()
{
HWND hwnd = FindWindow(ClassName, ClassName);
if (hwnd == NULL)
hwnd = FindWindow(ClassName, ClassNameAdmin);
if (hwnd)
{
ShowWindow(hwnd, SW_SHOWNORMAL);
SetForegroundWindow(hwnd);
return 0;
}
return 1;
}
LONG WINAPI UnhandledExcept(_EXCEPTION_POINTERS *ExceptionInfo)
{
wchar_t path_name[512]; // fully qualified path name
WCHAR code[16];
EXCEPTION_RECORD* rec = ExceptionInfo->ExceptionRecord;
std::swprintf(code, L"%08X", rec->ExceptionCode);
MEMORY_BASIC_INFORMATION info;
if (VirtualQuery(rec->ExceptionAddress, &info, sizeof(info)))
{
if (GetModuleFileName((HMODULE)info.AllocationBase, path_name, 512))
{
LPWSTR name = wcsrchr(path_name, L'\\');
if (name)
{
DWORD addr = (DWORD)rec->ExceptionAddress;
std::swprintf(name, L"%s:%08X", name + 1, addr - (DWORD)info.AllocationBase);
MessageBox(NULL, name, code, MB_OK);
TerminateProcess(GetCurrentProcess(), 0);
}
}
}
std::swprintf(path_name, L"%08X", rec->ExceptionAddress);
MessageBox(NULL, path_name, code, MB_OK);
TerminateProcess(GetCurrentProcess(), 0);
return 0;
}
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
if (!IthInitSystemService())
TerminateProcess(GetCurrentProcess(), 0);
CreateMutex(NULL, TRUE, L"ITH_MAIN_RUNNING");
if (IHF_Init())
{
SetUnhandledExceptionFilter(UnhandledExcept);
IHF_GetHookManager(&man);
IHF_GetSettingManager(&setman);
setman->SetValue(SETTING_SPLIT_TIME, 200);
MonitorFlag = true;
pfman = new ProfileManager();
mb_filter = new CustomFilter();
uni_filter = new CustomFilter();
DefaultSettings();
LoadSettings();
InitializeSettings();
setman->SetValue(SETTING_SPLIT_TIME, split_time);
setman->SetValue(SETTING_CLIPFLAG, clipboard_flag);
hIns = hInstance;
MyRegisterClass(hIns);
InitInstance(hIns, IHF_IsAdmin(), &window);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
//delete mb_filter;
//delete uni_filter;
delete pfman;
MonitorFlag = false;
man = NULL;
}
else
{
FindITH();
}
IHF_Cleanup();
IthCloseSystemService();
TerminateProcess(GetCurrentProcess(), 0);
}
This diff could not be displayed because it is too large.
/**
* pugixml parser - version 1.5
* --------------------------------------------------------
* Copyright (C) 2006-2014, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
* Report bugs and download new versions at http://pugixml.org/
*
* This library is distributed under the MIT License. See notice at the end
* of this file.
*
* This work is based on the pugxml parser, which is:
* Copyright (C) 2003, by Kristen Wegner (kristen@tima.net)
*/
#ifndef PUGIXML_VERSION
// Define version macro; evaluates to major * 100 + minor so that it's safe to use in less-than comparisons
# define PUGIXML_VERSION 150
#endif
// Include user configuration file (this can define various configuration macros)
#include "pugiconfig.hpp"
#ifndef HEADER_PUGIXML_HPP
#define HEADER_PUGIXML_HPP
// Include stddef.h for size_t and ptrdiff_t
#include <stddef.h>
// Include exception header for XPath
#if !defined(PUGIXML_NO_XPATH) && !defined(PUGIXML_NO_EXCEPTIONS)
# include <exception>
#endif
// Include STL headers
#ifndef PUGIXML_NO_STL
# include <iterator>
# include <iosfwd>
# include <string>
#endif
// Macro for deprecated features
#ifndef PUGIXML_DEPRECATED
# if defined(__GNUC__)
# define PUGIXML_DEPRECATED __attribute__((deprecated))
# elif defined(_MSC_VER) && _MSC_VER >= 1300
# define PUGIXML_DEPRECATED __declspec(deprecated)
# else
# define PUGIXML_DEPRECATED
# endif
#endif
// If no API is defined, assume default
#ifndef PUGIXML_API
# define PUGIXML_API
#endif
// If no API for classes is defined, assume default
#ifndef PUGIXML_CLASS
# define PUGIXML_CLASS PUGIXML_API
#endif
// If no API for functions is defined, assume default
#ifndef PUGIXML_FUNCTION
# define PUGIXML_FUNCTION PUGIXML_API
#endif
// If the platform is known to have long long support, enable long long functions
#ifndef PUGIXML_HAS_LONG_LONG
# if defined(__cplusplus) && __cplusplus >= 201103
# define PUGIXML_HAS_LONG_LONG
# elif defined(_MSC_VER) && _MSC_VER >= 1400
# define PUGIXML_HAS_LONG_LONG
# endif
#endif
// Character interface macros
#ifdef PUGIXML_WCHAR_MODE
# define PUGIXML_TEXT(t) L ## t
# define PUGIXML_CHAR wchar_t
#else
# define PUGIXML_TEXT(t) t
# define PUGIXML_CHAR char
#endif
namespace pugi
{
// Character type used for all internal storage and operations; depends on PUGIXML_WCHAR_MODE
typedef PUGIXML_CHAR char_t;
#ifndef PUGIXML_NO_STL
// String type used for operations that work with STL string; depends on PUGIXML_WCHAR_MODE
typedef std::basic_string<PUGIXML_CHAR, std::char_traits<PUGIXML_CHAR>, std::allocator<PUGIXML_CHAR> > string_t;
#endif
}
// The PugiXML namespace
namespace pugi
{
// Tree node types
enum xml_node_type
{
node_null, // Empty (null) node handle
node_document, // A document tree's absolute root
node_element, // Element tag, i.e. '<node/>'
node_pcdata, // Plain character data, i.e. 'text'
node_cdata, // Character data, i.e. '<![CDATA[text]]>'
node_comment, // Comment tag, i.e. '<!-- text -->'
node_pi, // Processing instruction, i.e. '<?name?>'
node_declaration, // Document declaration, i.e. '<?xml version="1.0"?>'
node_doctype // Document type declaration, i.e. '<!DOCTYPE doc>'
};
// Parsing options
// Minimal parsing mode (equivalent to turning all other flags off).
// Only elements and PCDATA sections are added to the DOM tree, no text conversions are performed.
const unsigned int parse_minimal = 0x0000;
// This flag determines if processing instructions (node_pi) are added to the DOM tree. This flag is off by default.
const unsigned int parse_pi = 0x0001;
// This flag determines if comments (node_comment) are added to the DOM tree. This flag is off by default.
const unsigned int parse_comments = 0x0002;
// This flag determines if CDATA sections (node_cdata) are added to the DOM tree. This flag is on by default.
const unsigned int parse_cdata = 0x0004;
// This flag determines if plain character data (node_pcdata) that consist only of whitespace are added to the DOM tree.
// This flag is off by default; turning it on usually results in slower parsing and more memory consumption.
const unsigned int parse_ws_pcdata = 0x0008;
// This flag determines if character and entity references are expanded during parsing. This flag is on by default.
const unsigned int parse_escapes = 0x0010;
// This flag determines if EOL characters are normalized (converted to #xA) during parsing. This flag is on by default.
const unsigned int parse_eol = 0x0020;
// This flag determines if attribute values are normalized using CDATA normalization rules during parsing. This flag is on by default.
const unsigned int parse_wconv_attribute = 0x0040;
// This flag determines if attribute values are normalized using NMTOKENS normalization rules during parsing. This flag is off by default.
const unsigned int parse_wnorm_attribute = 0x0080;
// This flag determines if document declaration (node_declaration) is added to the DOM tree. This flag is off by default.
const unsigned int parse_declaration = 0x0100;
// This flag determines if document type declaration (node_doctype) is added to the DOM tree. This flag is off by default.
const unsigned int parse_doctype = 0x0200;
// This flag determines if plain character data (node_pcdata) that is the only child of the parent node and that consists only
// of whitespace is added to the DOM tree.
// This flag is off by default; turning it on may result in slower parsing and more memory consumption.
const unsigned int parse_ws_pcdata_single = 0x0400;
// This flag determines if leading and trailing whitespace is to be removed from plain character data. This flag is off by default.
const unsigned int parse_trim_pcdata = 0x0800;
// This flag determines if plain character data that does not have a parent node is added to the DOM tree, and if an empty document
// is a valid document. This flag is off by default.
const unsigned int parse_fragment = 0x1000;
// The default parsing mode.
// Elements, PCDATA and CDATA sections are added to the DOM tree, character/reference entities are expanded,
// End-of-Line characters are normalized, attribute values are normalized using CDATA normalization rules.
const unsigned int parse_default = parse_cdata | parse_escapes | parse_wconv_attribute | parse_eol;
// The full parsing mode.
// Nodes of all types are added to the DOM tree, character/reference entities are expanded,
// End-of-Line characters are normalized, attribute values are normalized using CDATA normalization rules.
const unsigned int parse_full = parse_default | parse_pi | parse_comments | parse_declaration | parse_doctype;
// These flags determine the encoding of input data for XML document
enum xml_encoding
{
encoding_auto, // Auto-detect input encoding using BOM or < / <? detection; use UTF8 if BOM is not found
encoding_utf8, // UTF8 encoding
encoding_utf16_le, // Little-endian UTF16
encoding_utf16_be, // Big-endian UTF16
encoding_utf16, // UTF16 with native endianness
encoding_utf32_le, // Little-endian UTF32
encoding_utf32_be, // Big-endian UTF32
encoding_utf32, // UTF32 with native endianness
encoding_wchar, // The same encoding wchar_t has (either UTF16 or UTF32)
encoding_latin1
};
// Formatting flags
// Indent the nodes that are written to output stream with as many indentation strings as deep the node is in DOM tree. This flag is on by default.
const unsigned int format_indent = 0x01;
// Write encoding-specific BOM to the output stream. This flag is off by default.
const unsigned int format_write_bom = 0x02;
// Use raw output mode (no indentation and no line breaks are written). This flag is off by default.
const unsigned int format_raw = 0x04;
// Omit default XML declaration even if there is no declaration in the document. This flag is off by default.
const unsigned int format_no_declaration = 0x08;
// Don't escape attribute values and PCDATA contents. This flag is off by default.
const unsigned int format_no_escapes = 0x10;
// Open file using text mode in xml_document::save_file. This enables special character (i.e. new-line) conversions on some systems. This flag is off by default.
const unsigned int format_save_file_text = 0x20;
// The default set of formatting flags.
// Nodes are indented depending on their depth in DOM tree, a default declaration is output if document has none.
const unsigned int format_default = format_indent;
// Forward declarations
struct xml_attribute_struct;
struct xml_node_struct;
class xml_node_iterator;
class xml_attribute_iterator;
class xml_named_node_iterator;
class xml_tree_walker;
struct xml_parse_result;
class xml_node;
class xml_text;
#ifndef PUGIXML_NO_XPATH
class xpath_node;
class xpath_node_set;
class xpath_query;
class xpath_variable_set;
#endif
// Range-based for loop support
template <typename It> class xml_object_range
{
public:
typedef It const_iterator;
typedef It iterator;
xml_object_range(It b, It e): _begin(b), _end(e)
{
}
It begin() const { return _begin; }
It end() const { return _end; }
private:
It _begin, _end;
};
// Writer interface for node printing (see xml_node::print)
class PUGIXML_CLASS xml_writer
{
public:
virtual ~xml_writer() {}
// Write memory chunk into stream/file/whatever
virtual void write(const void* data, size_t size) = 0;
};
// xml_writer implementation for FILE*
class PUGIXML_CLASS xml_writer_file: public xml_writer
{
public:
// Construct writer from a FILE* object; void* is used to avoid header dependencies on stdio
xml_writer_file(void* file);
virtual void write(const void* data, size_t size);
private:
void* file;
};
#ifndef PUGIXML_NO_STL
// xml_writer implementation for streams
class PUGIXML_CLASS xml_writer_stream: public xml_writer
{
public:
// Construct writer from an output stream object
xml_writer_stream(std::basic_ostream<char, std::char_traits<char> >& stream);
xml_writer_stream(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream);
virtual void write(const void* data, size_t size);
private:
std::basic_ostream<char, std::char_traits<char> >* narrow_stream;
std::basic_ostream<wchar_t, std::char_traits<wchar_t> >* wide_stream;
};
#endif
// A light-weight handle for manipulating attributes in DOM tree
class PUGIXML_CLASS xml_attribute
{
friend class xml_attribute_iterator;
friend class xml_node;
private:
xml_attribute_struct* _attr;
typedef void (*unspecified_bool_type)(xml_attribute***);
public:
// Default constructor. Constructs an empty attribute.
xml_attribute();
// Constructs attribute from internal pointer
explicit xml_attribute(xml_attribute_struct* attr);
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
// Comparison operators (compares wrapped attribute pointers)
bool operator==(const xml_attribute& r) const;
bool operator!=(const xml_attribute& r) const;
bool operator<(const xml_attribute& r) const;
bool operator>(const xml_attribute& r) const;
bool operator<=(const xml_attribute& r) const;
bool operator>=(const xml_attribute& r) const;
// Check if attribute is empty
bool empty() const;
// Get attribute name/value, or "" if attribute is empty
const char_t* name() const;
const char_t* value() const;
// Get attribute value, or the default value if attribute is empty
const char_t* as_string(const char_t* def = PUGIXML_TEXT("")) const;
// Get attribute value as a number, or the default value if conversion did not succeed or attribute is empty
int as_int(int def = 0) const;
unsigned int as_uint(unsigned int def = 0) const;
double as_double(double def = 0) const;
float as_float(float def = 0) const;
#ifdef PUGIXML_HAS_LONG_LONG
long long as_llong(long long def = 0) const;
unsigned long long as_ullong(unsigned long long def = 0) const;
#endif
// Get attribute value as bool (returns true if first character is in '1tTyY' set), or the default value if attribute is empty
bool as_bool(bool def = false) const;
// Set attribute name/value (returns false if attribute is empty or there is not enough memory)
bool set_name(const char_t* rhs);
bool set_value(const char_t* rhs);
// Set attribute value with type conversion (numbers are converted to strings, boolean is converted to "true"/"false")
bool set_value(int rhs);
bool set_value(unsigned int rhs);
bool set_value(double rhs);
bool set_value(bool rhs);
#ifdef PUGIXML_HAS_LONG_LONG
bool set_value(long long rhs);
bool set_value(unsigned long long rhs);
#endif
// Set attribute value (equivalent to set_value without error checking)
xml_attribute& operator=(const char_t* rhs);
xml_attribute& operator=(int rhs);
xml_attribute& operator=(unsigned int rhs);
xml_attribute& operator=(double rhs);
xml_attribute& operator=(bool rhs);
#ifdef PUGIXML_HAS_LONG_LONG
xml_attribute& operator=(long long rhs);
xml_attribute& operator=(unsigned long long rhs);
#endif
// Get next/previous attribute in the attribute list of the parent node
xml_attribute next_attribute() const;
xml_attribute previous_attribute() const;
// Get hash value (unique for handles to the same object)
size_t hash_value() const;
// Get internal pointer
xml_attribute_struct* internal_object() const;
};
#ifdef __BORLANDC__
// Borland C++ workaround
bool PUGIXML_FUNCTION operator&&(const xml_attribute& lhs, bool rhs);
bool PUGIXML_FUNCTION operator||(const xml_attribute& lhs, bool rhs);
#endif
// A light-weight handle for manipulating nodes in DOM tree
class PUGIXML_CLASS xml_node
{
friend class xml_attribute_iterator;
friend class xml_node_iterator;
friend class xml_named_node_iterator;
protected:
xml_node_struct* _root;
typedef void (*unspecified_bool_type)(xml_node***);
public:
// Default constructor. Constructs an empty node.
xml_node();
// Constructs node from internal pointer
explicit xml_node(xml_node_struct* p);
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
// Comparison operators (compares wrapped node pointers)
bool operator==(const xml_node& r) const;
bool operator!=(const xml_node& r) const;
bool operator<(const xml_node& r) const;
bool operator>(const xml_node& r) const;
bool operator<=(const xml_node& r) const;
bool operator>=(const xml_node& r) const;
// Check if node is empty.
bool empty() const;
// Get node type
xml_node_type type() const;
// Get node name, or "" if node is empty or it has no name
const char_t* name() const;
// Get node value, or "" if node is empty or it has no value
// Note: For <node>text</node> node.value() does not return "text"! Use child_value() or text() methods to access text inside nodes.
const char_t* value() const;
// Get attribute list
xml_attribute first_attribute() const;
xml_attribute last_attribute() const;
// Get children list
xml_node first_child() const;
xml_node last_child() const;
// Get next/previous sibling in the children list of the parent node
xml_node next_sibling() const;
xml_node previous_sibling() const;
// Get parent node
xml_node parent() const;
// Get root of DOM tree this node belongs to
xml_node root() const;
// Get text object for the current node
xml_text text() const;
// Get child, attribute or next/previous sibling with the specified name
xml_node child(const char_t* name) const;
xml_attribute attribute(const char_t* name) const;
xml_node next_sibling(const char_t* name) const;
xml_node previous_sibling(const char_t* name) const;
// Get child value of current node; that is, value of the first child node of type PCDATA/CDATA
const char_t* child_value() const;
// Get child value of child with specified name. Equivalent to child(name).child_value().
const char_t* child_value(const char_t* name) const;
// Set node name/value (returns false if node is empty, there is not enough memory, or node can not have name/value)
bool set_name(const char_t* rhs);
bool set_value(const char_t* rhs);
// Add attribute with specified name. Returns added attribute, or empty attribute on errors.
xml_attribute append_attribute(const char_t* name);
xml_attribute prepend_attribute(const char_t* name);
xml_attribute insert_attribute_after(const char_t* name, const xml_attribute& attr);
xml_attribute insert_attribute_before(const char_t* name, const xml_attribute& attr);
// Add a copy of the specified attribute. Returns added attribute, or empty attribute on errors.
xml_attribute append_copy(const xml_attribute& proto);
xml_attribute prepend_copy(const xml_attribute& proto);
xml_attribute insert_copy_after(const xml_attribute& proto, const xml_attribute& attr);
xml_attribute insert_copy_before(const xml_attribute& proto, const xml_attribute& attr);
// Add child node with specified type. Returns added node, or empty node on errors.
xml_node append_child(xml_node_type type = node_element);
xml_node prepend_child(xml_node_type type = node_element);
xml_node insert_child_after(xml_node_type type, const xml_node& node);
xml_node insert_child_before(xml_node_type type, const xml_node& node);
// Add child element with specified name. Returns added node, or empty node on errors.
xml_node append_child(const char_t* name);
xml_node prepend_child(const char_t* name);
xml_node insert_child_after(const char_t* name, const xml_node& node);
xml_node insert_child_before(const char_t* name, const xml_node& node);
// Add a copy of the specified node as a child. Returns added node, or empty node on errors.
xml_node append_copy(const xml_node& proto);
xml_node prepend_copy(const xml_node& proto);
xml_node insert_copy_after(const xml_node& proto, const xml_node& node);
xml_node insert_copy_before(const xml_node& proto, const xml_node& node);
// Move the specified node to become a child of this node. Returns moved node, or empty node on errors.
xml_node append_move(const xml_node& moved);
xml_node prepend_move(const xml_node& moved);
xml_node insert_move_after(const xml_node& moved, const xml_node& node);
xml_node insert_move_before(const xml_node& moved, const xml_node& node);
// Remove specified attribute
bool remove_attribute(const xml_attribute& a);
bool remove_attribute(const char_t* name);
// Remove specified child
bool remove_child(const xml_node& n);
bool remove_child(const char_t* name);
// Parses buffer as an XML document fragment and appends all nodes as children of the current node.
// Copies/converts the buffer, so it may be deleted or changed after the function returns.
// Note: append_buffer allocates memory that has the lifetime of the owning document; removing the appended nodes does not immediately reclaim that memory.
xml_parse_result append_buffer(const void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Find attribute using predicate. Returns first attribute for which predicate returned true.
template <typename Predicate> xml_attribute find_attribute(Predicate pred) const
{
if (!_root) return xml_attribute();
for (xml_attribute attrib = first_attribute(); attrib; attrib = attrib.next_attribute())
if (pred(attrib))
return attrib;
return xml_attribute();
}
// Find child node using predicate. Returns first child for which predicate returned true.
template <typename Predicate> xml_node find_child(Predicate pred) const
{
if (!_root) return xml_node();
for (xml_node node = first_child(); node; node = node.next_sibling())
if (pred(node))
return node;
return xml_node();
}
// Find node from subtree using predicate. Returns first node from subtree (depth-first), for which predicate returned true.
template <typename Predicate> xml_node find_node(Predicate pred) const
{
if (!_root) return xml_node();
xml_node cur = first_child();
while (cur._root && cur._root != _root)
{
if (pred(cur)) return cur;
if (cur.first_child()) cur = cur.first_child();
else if (cur.next_sibling()) cur = cur.next_sibling();
else
{
while (!cur.next_sibling() && cur._root != _root) cur = cur.parent();
if (cur._root != _root) cur = cur.next_sibling();
}
}
return xml_node();
}
// Find child node by attribute name/value
xml_node find_child_by_attribute(const char_t* name, const char_t* attr_name, const char_t* attr_value) const;
xml_node find_child_by_attribute(const char_t* attr_name, const char_t* attr_value) const;
#ifndef PUGIXML_NO_STL
// Get the absolute node path from root as a text string.
string_t path(char_t delimiter = '/') const;
#endif
// Search for a node by path consisting of node names and . or .. elements.
xml_node first_element_by_path(const char_t* path, char_t delimiter = '/') const;
// Recursively traverse subtree with xml_tree_walker
bool traverse(xml_tree_walker& walker);
#ifndef PUGIXML_NO_XPATH
// Select single node by evaluating XPath query. Returns first node from the resulting node set.
xpath_node select_node(const char_t* query, xpath_variable_set* variables = 0) const;
xpath_node select_node(const xpath_query& query) const;
// Select node set by evaluating XPath query
xpath_node_set select_nodes(const char_t* query, xpath_variable_set* variables = 0) const;
xpath_node_set select_nodes(const xpath_query& query) const;
// (deprecated: use select_node instead) Select single node by evaluating XPath query.
xpath_node select_single_node(const char_t* query, xpath_variable_set* variables = 0) const;
xpath_node select_single_node(const xpath_query& query) const;
#endif
// Print subtree using a writer object
void print(xml_writer& writer, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto, unsigned int depth = 0) const;
#ifndef PUGIXML_NO_STL
// Print subtree to stream
void print(std::basic_ostream<char, std::char_traits<char> >& os, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto, unsigned int depth = 0) const;
void print(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& os, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, unsigned int depth = 0) const;
#endif
// Child nodes iterators
typedef xml_node_iterator iterator;
iterator begin() const;
iterator end() const;
// Attribute iterators
typedef xml_attribute_iterator attribute_iterator;
attribute_iterator attributes_begin() const;
attribute_iterator attributes_end() const;
// Range-based for support
xml_object_range<xml_node_iterator> children() const;
xml_object_range<xml_named_node_iterator> children(const char_t* name) const;
xml_object_range<xml_attribute_iterator> attributes() const;
// Get node offset in parsed file/string (in char_t units) for debugging purposes
ptrdiff_t offset_debug() const;
// Get hash value (unique for handles to the same object)
size_t hash_value() const;
// Get internal pointer
xml_node_struct* internal_object() const;
};
#ifdef __BORLANDC__
// Borland C++ workaround
bool PUGIXML_FUNCTION operator&&(const xml_node& lhs, bool rhs);
bool PUGIXML_FUNCTION operator||(const xml_node& lhs, bool rhs);
#endif
// A helper for working with text inside PCDATA nodes
class PUGIXML_CLASS xml_text
{
friend class xml_node;
xml_node_struct* _root;
typedef void (*unspecified_bool_type)(xml_text***);
explicit xml_text(xml_node_struct* root);
xml_node_struct* _data_new();
xml_node_struct* _data() const;
public:
// Default constructor. Constructs an empty object.
xml_text();
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
// Check if text object is empty
bool empty() const;
// Get text, or "" if object is empty
const char_t* get() const;
// Get text, or the default value if object is empty
const char_t* as_string(const char_t* def = PUGIXML_TEXT("")) const;
// Get text as a number, or the default value if conversion did not succeed or object is empty
int as_int(int def = 0) const;
unsigned int as_uint(unsigned int def = 0) const;
double as_double(double def = 0) const;
float as_float(float def = 0) const;
#ifdef PUGIXML_HAS_LONG_LONG
long long as_llong(long long def = 0) const;
unsigned long long as_ullong(unsigned long long def = 0) const;
#endif
// Get text as bool (returns true if first character is in '1tTyY' set), or the default value if object is empty
bool as_bool(bool def = false) const;
// Set text (returns false if object is empty or there is not enough memory)
bool set(const char_t* rhs);
// Set text with type conversion (numbers are converted to strings, boolean is converted to "true"/"false")
bool set(int rhs);
bool set(unsigned int rhs);
bool set(double rhs);
bool set(bool rhs);
#ifdef PUGIXML_HAS_LONG_LONG
bool set(long long rhs);
bool set(unsigned long long rhs);
#endif
// Set text (equivalent to set without error checking)
xml_text& operator=(const char_t* rhs);
xml_text& operator=(int rhs);
xml_text& operator=(unsigned int rhs);
xml_text& operator=(double rhs);
xml_text& operator=(bool rhs);
#ifdef PUGIXML_HAS_LONG_LONG
xml_text& operator=(long long rhs);
xml_text& operator=(unsigned long long rhs);
#endif
// Get the data node (node_pcdata or node_cdata) for this object
xml_node data() const;
};
#ifdef __BORLANDC__
// Borland C++ workaround
bool PUGIXML_FUNCTION operator&&(const xml_text& lhs, bool rhs);
bool PUGIXML_FUNCTION operator||(const xml_text& lhs, bool rhs);
#endif
// Child node iterator (a bidirectional iterator over a collection of xml_node)
class PUGIXML_CLASS xml_node_iterator
{
friend class xml_node;
private:
mutable xml_node _wrap;
xml_node _parent;
xml_node_iterator(xml_node_struct* ref, xml_node_struct* parent);
public:
// Iterator traits
typedef ptrdiff_t difference_type;
typedef xml_node value_type;
typedef xml_node* pointer;
typedef xml_node& reference;
#ifndef PUGIXML_NO_STL
typedef std::bidirectional_iterator_tag iterator_category;
#endif
// Default constructor
xml_node_iterator();
// Construct an iterator which points to the specified node
xml_node_iterator(const xml_node& node);
// Iterator operators
bool operator==(const xml_node_iterator& rhs) const;
bool operator!=(const xml_node_iterator& rhs) const;
xml_node& operator*() const;
xml_node* operator->() const;
const xml_node_iterator& operator++();
xml_node_iterator operator++(int);
const xml_node_iterator& operator--();
xml_node_iterator operator--(int);
};
// Attribute iterator (a bidirectional iterator over a collection of xml_attribute)
class PUGIXML_CLASS xml_attribute_iterator
{
friend class xml_node;
private:
mutable xml_attribute _wrap;
xml_node _parent;
xml_attribute_iterator(xml_attribute_struct* ref, xml_node_struct* parent);
public:
// Iterator traits
typedef ptrdiff_t difference_type;
typedef xml_attribute value_type;
typedef xml_attribute* pointer;
typedef xml_attribute& reference;
#ifndef PUGIXML_NO_STL
typedef std::bidirectional_iterator_tag iterator_category;
#endif
// Default constructor
xml_attribute_iterator();
// Construct an iterator which points to the specified attribute
xml_attribute_iterator(const xml_attribute& attr, const xml_node& parent);
// Iterator operators
bool operator==(const xml_attribute_iterator& rhs) const;
bool operator!=(const xml_attribute_iterator& rhs) const;
xml_attribute& operator*() const;
xml_attribute* operator->() const;
const xml_attribute_iterator& operator++();
xml_attribute_iterator operator++(int);
const xml_attribute_iterator& operator--();
xml_attribute_iterator operator--(int);
};
// Named node range helper
class PUGIXML_CLASS xml_named_node_iterator
{
friend class xml_node;
public:
// Iterator traits
typedef ptrdiff_t difference_type;
typedef xml_node value_type;
typedef xml_node* pointer;
typedef xml_node& reference;
#ifndef PUGIXML_NO_STL
typedef std::bidirectional_iterator_tag iterator_category;
#endif
// Default constructor
xml_named_node_iterator();
// Construct an iterator which points to the specified node
xml_named_node_iterator(const xml_node& node, const char_t* name);
// Iterator operators
bool operator==(const xml_named_node_iterator& rhs) const;
bool operator!=(const xml_named_node_iterator& rhs) const;
xml_node& operator*() const;
xml_node* operator->() const;
const xml_named_node_iterator& operator++();
xml_named_node_iterator operator++(int);
const xml_named_node_iterator& operator--();
xml_named_node_iterator operator--(int);
private:
mutable xml_node _wrap;
xml_node _parent;
const char_t* _name;
xml_named_node_iterator(xml_node_struct* ref, xml_node_struct* parent, const char_t* name);
};
// Abstract tree walker class (see xml_node::traverse)
class PUGIXML_CLASS xml_tree_walker
{
friend class xml_node;
private:
int _depth;
protected:
// Get current traversal depth
int depth() const;
public:
xml_tree_walker();
virtual ~xml_tree_walker();
// Callback that is called when traversal begins
virtual bool begin(xml_node& node);
// Callback that is called for each node traversed
virtual bool for_each(xml_node& node) = 0;
// Callback that is called when traversal ends
virtual bool end(xml_node& node);
};
// Parsing status, returned as part of xml_parse_result object
enum xml_parse_status
{
status_ok = 0, // No error
status_file_not_found, // File was not found during load_file()
status_io_error, // Error reading from file/stream
status_out_of_memory, // Could not allocate memory
status_internal_error, // Internal error occurred
status_unrecognized_tag, // Parser could not determine tag type
status_bad_pi, // Parsing error occurred while parsing document declaration/processing instruction
status_bad_comment, // Parsing error occurred while parsing comment
status_bad_cdata, // Parsing error occurred while parsing CDATA section
status_bad_doctype, // Parsing error occurred while parsing document type declaration
status_bad_pcdata, // Parsing error occurred while parsing PCDATA section
status_bad_start_element, // Parsing error occurred while parsing start element tag
status_bad_attribute, // Parsing error occurred while parsing element attribute
status_bad_end_element, // Parsing error occurred while parsing end element tag
status_end_element_mismatch,// There was a mismatch of start-end tags (closing tag had incorrect name, some tag was not closed or there was an excessive closing tag)
status_append_invalid_root, // Unable to append nodes since root type is not node_element or node_document (exclusive to xml_node::append_buffer)
status_no_document_element // Parsing resulted in a document without element nodes
};
// Parsing result
struct PUGIXML_CLASS xml_parse_result
{
// Parsing status (see xml_parse_status)
xml_parse_status status;
// Last parsed offset (in char_t units from start of input data)
ptrdiff_t offset;
// Source document encoding
xml_encoding encoding;
// Default constructor, initializes object to failed state
xml_parse_result();
// Cast to bool operator
operator bool() const;
// Get error description
const char* description() const;
};
// Document class (DOM tree root)
class PUGIXML_CLASS xml_document: public xml_node
{
private:
char_t* _buffer;
char _memory[192];
// Non-copyable semantics
xml_document(const xml_document&);
const xml_document& operator=(const xml_document&);
void create();
void destroy();
public:
// Default constructor, makes empty document
xml_document();
// Destructor, invalidates all node/attribute handles to this document
~xml_document();
// Removes all nodes, leaving the empty document
void reset();
// Removes all nodes, then copies the entire contents of the specified document
void reset(const xml_document& proto);
#ifndef PUGIXML_NO_STL
// Load document from stream.
xml_parse_result load(std::basic_istream<char, std::char_traits<char> >& stream, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
xml_parse_result load(std::basic_istream<wchar_t, std::char_traits<wchar_t> >& stream, unsigned int options = parse_default);
#endif
// (deprecated: use load_string instead) Load document from zero-terminated string. No encoding conversions are applied.
xml_parse_result load(const char_t* contents, unsigned int options = parse_default);
// Load document from zero-terminated string. No encoding conversions are applied.
xml_parse_result load_string(const char_t* contents, unsigned int options = parse_default);
// Load document from file
xml_parse_result load_file(const char* path, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
xml_parse_result load_file(const wchar_t* path, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Load document from buffer. Copies/converts the buffer, so it may be deleted or changed after the function returns.
xml_parse_result load_buffer(const void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Load document from buffer, using the buffer for in-place parsing (the buffer is modified and used for storage of document data).
// You should ensure that buffer data will persist throughout the document's lifetime, and free the buffer memory manually once document is destroyed.
xml_parse_result load_buffer_inplace(void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Load document from buffer, using the buffer for in-place parsing (the buffer is modified and used for storage of document data).
// You should allocate the buffer with pugixml allocation function; document will free the buffer when it is no longer needed (you can't use it anymore).
xml_parse_result load_buffer_inplace_own(void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Save XML document to writer (semantics is slightly different from xml_node::print, see documentation for details).
void save(xml_writer& writer, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
#ifndef PUGIXML_NO_STL
// Save XML document to stream (semantics is slightly different from xml_node::print, see documentation for details).
void save(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
void save(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default) const;
#endif
// Save XML to file
bool save_file(const char* path, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
bool save_file(const wchar_t* path, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
// Get document element
xml_node document_element() const;
};
#ifndef PUGIXML_NO_XPATH
// XPath query return type
enum xpath_value_type
{
xpath_type_none, // Unknown type (query failed to compile)
xpath_type_node_set, // Node set (xpath_node_set)
xpath_type_number, // Number
xpath_type_string, // String
xpath_type_boolean // Boolean
};
// XPath parsing result
struct PUGIXML_CLASS xpath_parse_result
{
// Error message (0 if no error)
const char* error;
// Last parsed offset (in char_t units from string start)
ptrdiff_t offset;
// Default constructor, initializes object to failed state
xpath_parse_result();
// Cast to bool operator
operator bool() const;
// Get error description
const char* description() const;
};
// A single XPath variable
class PUGIXML_CLASS xpath_variable
{
friend class xpath_variable_set;
protected:
xpath_value_type _type;
xpath_variable* _next;
xpath_variable();
// Non-copyable semantics
xpath_variable(const xpath_variable&);
xpath_variable& operator=(const xpath_variable&);
public:
// Get variable name
const char_t* name() const;
// Get variable type
xpath_value_type type() const;
// Get variable value; no type conversion is performed, default value (false, NaN, empty string, empty node set) is returned on type mismatch error
bool get_boolean() const;
double get_number() const;
const char_t* get_string() const;
const xpath_node_set& get_node_set() const;
// Set variable value; no type conversion is performed, false is returned on type mismatch error
bool set(bool value);
bool set(double value);
bool set(const char_t* value);
bool set(const xpath_node_set& value);
};
// A set of XPath variables
class PUGIXML_CLASS xpath_variable_set
{
private:
xpath_variable* _data[64];
// Non-copyable semantics
xpath_variable_set(const xpath_variable_set&);
xpath_variable_set& operator=(const xpath_variable_set&);
xpath_variable* find(const char_t* name) const;
public:
// Default constructor/destructor
xpath_variable_set();
~xpath_variable_set();
// Add a new variable or get the existing one, if the types match
xpath_variable* add(const char_t* name, xpath_value_type type);
// Set value of an existing variable; no type conversion is performed, false is returned if there is no such variable or if types mismatch
bool set(const char_t* name, bool value);
bool set(const char_t* name, double value);
bool set(const char_t* name, const char_t* value);
bool set(const char_t* name, const xpath_node_set& value);
// Get existing variable by name
xpath_variable* get(const char_t* name);
const xpath_variable* get(const char_t* name) const;
};
// A compiled XPath query object
class PUGIXML_CLASS xpath_query
{
private:
void* _impl;
xpath_parse_result _result;
typedef void (*unspecified_bool_type)(xpath_query***);
// Non-copyable semantics
xpath_query(const xpath_query&);
xpath_query& operator=(const xpath_query&);
public:
// Construct a compiled object from XPath expression.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws xpath_exception on compilation errors.
explicit xpath_query(const char_t* query, xpath_variable_set* variables = 0);
// Destructor
~xpath_query();
// Get query expression return type
xpath_value_type return_type() const;
// Evaluate expression as boolean value in the specified context; performs type conversion if necessary.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
bool evaluate_boolean(const xpath_node& n) const;
// Evaluate expression as double value in the specified context; performs type conversion if necessary.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
double evaluate_number(const xpath_node& n) const;
#ifndef PUGIXML_NO_STL
// Evaluate expression as string value in the specified context; performs type conversion if necessary.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
string_t evaluate_string(const xpath_node& n) const;
#endif
// Evaluate expression as string value in the specified context; performs type conversion if necessary.
// At most capacity characters are written to the destination buffer, full result size is returned (includes terminating zero).
// If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
// If PUGIXML_NO_EXCEPTIONS is defined, returns empty set instead.
size_t evaluate_string(char_t* buffer, size_t capacity, const xpath_node& n) const;
// Evaluate expression as node set in the specified context.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws xpath_exception on type mismatch and std::bad_alloc on out of memory errors.
// If PUGIXML_NO_EXCEPTIONS is defined, returns empty node set instead.
xpath_node_set evaluate_node_set(const xpath_node& n) const;
// Evaluate expression as node set in the specified context.
// Return first node in document order, or empty node if node set is empty.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws xpath_exception on type mismatch and std::bad_alloc on out of memory errors.
// If PUGIXML_NO_EXCEPTIONS is defined, returns empty node instead.
xpath_node evaluate_node(const xpath_node& n) const;
// Get parsing result (used to get compilation errors in PUGIXML_NO_EXCEPTIONS mode)
const xpath_parse_result& result() const;
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
};
#ifndef PUGIXML_NO_EXCEPTIONS
// XPath exception class
class PUGIXML_CLASS xpath_exception: public std::exception
{
private:
xpath_parse_result _result;
public:
// Construct exception from parse result
explicit xpath_exception(const xpath_parse_result& result);
// Get error message
virtual const char* what() const throw();
// Get parse result
const xpath_parse_result& result() const;
};
#endif
// XPath node class (either xml_node or xml_attribute)
class PUGIXML_CLASS xpath_node
{
private:
xml_node _node;
xml_attribute _attribute;
typedef void (*unspecified_bool_type)(xpath_node***);
public:
// Default constructor; constructs empty XPath node
xpath_node();
// Construct XPath node from XML node/attribute
xpath_node(const xml_node& node);
xpath_node(const xml_attribute& attribute, const xml_node& parent);
// Get node/attribute, if any
xml_node node() const;
xml_attribute attribute() const;
// Get parent of contained node/attribute
xml_node parent() const;
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
// Comparison operators
bool operator==(const xpath_node& n) const;
bool operator!=(const xpath_node& n) const;
};
#ifdef __BORLANDC__
// Borland C++ workaround
bool PUGIXML_FUNCTION operator&&(const xpath_node& lhs, bool rhs);
bool PUGIXML_FUNCTION operator||(const xpath_node& lhs, bool rhs);
#endif
// A fixed-size collection of XPath nodes
class PUGIXML_CLASS xpath_node_set
{
public:
// Collection type
enum type_t
{
type_unsorted, // Not ordered
type_sorted, // Sorted by document order (ascending)
type_sorted_reverse // Sorted by document order (descending)
};
// Constant iterator type
typedef const xpath_node* const_iterator;
// We define non-constant iterator to be the same as constant iterator so that various generic algorithms (i.e. boost foreach) work
typedef const xpath_node* iterator;
// Default constructor. Constructs empty set.
xpath_node_set();
// Constructs a set from iterator range; data is not checked for duplicates and is not sorted according to provided type, so be careful
xpath_node_set(const_iterator begin, const_iterator end, type_t type = type_unsorted);
// Destructor
~xpath_node_set();
// Copy constructor/assignment operator
xpath_node_set(const xpath_node_set& ns);
xpath_node_set& operator=(const xpath_node_set& ns);
// Get collection type
type_t type() const;
// Get collection size
size_t size() const;
// Indexing operator
const xpath_node& operator[](size_t index) const;
// Collection iterators
const_iterator begin() const;
const_iterator end() const;
// Sort the collection in ascending/descending order by document order
void sort(bool reverse = false);
// Get first node in the collection by document order
xpath_node first() const;
// Check if collection is empty
bool empty() const;
private:
type_t _type;
xpath_node _storage;
xpath_node* _begin;
xpath_node* _end;
void _assign(const_iterator begin, const_iterator end);
};
#endif
#ifndef PUGIXML_NO_STL
// Convert wide string to UTF8
std::basic_string<char, std::char_traits<char>, std::allocator<char> > PUGIXML_FUNCTION as_utf8(const wchar_t* str);
std::basic_string<char, std::char_traits<char>, std::allocator<char> > PUGIXML_FUNCTION as_utf8(const std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >& str);
// Convert UTF8 to wide string
std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > PUGIXML_FUNCTION as_wide(const char* str);
std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > PUGIXML_FUNCTION as_wide(const std::basic_string<char, std::char_traits<char>, std::allocator<char> >& str);
#endif
// Memory allocation function interface; returns pointer to allocated memory or NULL on failure
typedef void* (*allocation_function)(size_t size);
// Memory deallocation function interface
typedef void (*deallocation_function)(void* ptr);
// Override default memory management functions. All subsequent allocations/deallocations will be performed via supplied functions.
void PUGIXML_FUNCTION set_memory_management_functions(allocation_function allocate, deallocation_function deallocate);
// Get current memory management functions
allocation_function PUGIXML_FUNCTION get_memory_allocation_function();
deallocation_function PUGIXML_FUNCTION get_memory_deallocation_function();
}
#if !defined(PUGIXML_NO_STL) && (defined(_MSC_VER) || defined(__ICC))
namespace std
{
// Workarounds for (non-standard) iterator category detection for older versions (MSVC7/IC8 and earlier)
std::bidirectional_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_node_iterator&);
std::bidirectional_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_attribute_iterator&);
std::bidirectional_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_named_node_iterator&);
}
#endif
#if !defined(PUGIXML_NO_STL) && defined(__SUNPRO_CC)
namespace std
{
// Workarounds for (non-standard) iterator category detection
std::bidirectional_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_node_iterator&);
std::bidirectional_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_attribute_iterator&);
std::bidirectional_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_named_node_iterator&);
}
#endif
#endif
/**
* Copyright (c) 2006-2014 Arseny Kapoulkine
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef IDC_STATIC
#define IDC_STATIC (-1)
#endif
#define IDD_DIALOG2 102
#define IDD_DIALOG4 104
#define IDI_ICON1 110
#define IDC_CHECK1 1000
#define IDC_CHECK2 1001
#define IDC_CHECK3 1002
#define IDC_CHECK4 1003
#define IDC_CHECK5 1004
#define IDC_EDIT1 1011
#define IDC_EDIT2 1012
#define IDC_EDIT3 1013
#define IDC_EDIT4 1014
#define IDC_BUTTON1 1020
#define IDC_BUTTON2 1021
#define IDC_BUTTON3 1022
#define IDC_BUTTON5 1024
#define IDC_LIST1 1028
#define IDC_BUTTON6 40000
#define IDC_CHECK6 40001
/* Copyright (C) 2010-2012 kaosu (qiupf2000@gmail.com)
* This file is part of the Interactive Text Hooker.
* Interactive Text Hooker is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "utility.h"
#include "ith/host/srv.h"
#include "ith/host/hookman.h"
#include "ith/common/types.h"
#include "ith/common/const.h"
extern HookManager* man; // main.cpp
std::wstring GetDriveLetter(const std::wstring& devicePath);
std::wstring GetWindowsPath(const std::wstring& fileObjectPath);
PVOID GetAllocationBase(DWORD pid, LPCVOID);
std::wstring GetModuleFileNameAsString(DWORD pid, PVOID allocationBase);
std::wstring GetModuleFileNameAsString();
std::wstring GetProcessPath(HANDLE hProc);
void ConsoleOutput(LPCWSTR text)
{
man->AddConsoleOutput(text);
}
void ConsoleOutput(LPCSTR text)
{
int wc_length = MB_WC_count(text, -1);
LPWSTR wc = new WCHAR[wc_length];
MB_WC(text, wc, wc_length);
man->AddConsoleOutput(wc);
delete wc;
}
std::wstring GetProcessPath(DWORD pid)
{
UniqueHandle hProc(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid));
if (hProc)
return GetProcessPath(hProc.get());
else
return L"";
}
std::wstring GetProcessPath(HANDLE hProc)
{
wchar_t path[MAX_PATH];
GetProcessImageFileName(hProc, path, MAX_PATH);
return GetWindowsPath(path);
}
std::wstring GetWindowsPath(const std::wstring& path)
{
// path is in device form
// \Device\HarddiskVolume2\Windows\System32\taskhost.exe
auto pathOffset = path.find(L'\\', 1) + 1;
pathOffset = path.find(L'\\', pathOffset);
std::wstring devicePath = path.substr(0, pathOffset); // \Device\HarddiskVolume2
std::wstring dosDrive = GetDriveLetter(devicePath); // C:
if (dosDrive.empty())
return L"";
std::wstring dosPath = dosDrive; // C:
dosPath += path.substr(pathOffset); // C:\Windows\System32\taskhost.exe
return dosPath;
}
std::wstring GetDriveLetter(const std::wstring& devicePath)
{
for (wchar_t drive = L'A'; drive <= L'Z'; drive++)
{
wchar_t szDriveName[3] = { drive, L':', L'\0' };
wchar_t szTarget[512];
if (QueryDosDevice(szDriveName, szTarget, 512))
if (devicePath.compare(szTarget) == 0)
return szDriveName;
}
return L"";
}
std::wstring GetCode(const HookParam& hp, DWORD pid)
{
std::wstring code(L"/H");
WCHAR c;
if (hp.type & PRINT_DWORD)
c = L'H';
else if (hp.type & USING_UNICODE)
{
if (hp.type & USING_STRING)
c = L'Q';
else if (hp.type & STRING_LAST_CHAR)
c = L'L';
else
c = L'W';
}
else
{
if (hp.type & USING_STRING)
c = L'S';
else if (hp.type & BIG_ENDIAN)
c = L'A';
else if (hp.type & STRING_LAST_CHAR)
c = L'E';
else
c = L'B';
}
code += c;
if (hp.type & NO_CONTEXT)
code += L'N';
if (hp.off >> 31)
code += L"-" + ToHexString(-(hp.off + 4));
else
code += ToHexString(hp.off);
if (hp.type & DATA_INDIRECT)
{
if (hp.ind >> 31)
code += L"*-" + ToHexString(-hp.ind);
else
code += L"*" + ToHexString(hp.ind);
}
if (hp.type & USING_SPLIT)
{
if (hp.split >> 31)
code += L":-" + ToHexString(-(4 + hp.split));
else
code += L":" + ToHexString(hp.split);
}
if (hp.type & SPLIT_INDIRECT)
{
if (hp.split_ind >> 31)
code += L"*-" + ToHexString(-hp.split_ind);
else
code += L"*" + ToHexString(hp.split_ind);
}
if (pid)
{
PVOID allocationBase = GetAllocationBase(pid, (LPCVOID)hp.addr);
if (allocationBase)
{
std::wstring path = GetModuleFileNameAsString(pid, allocationBase);
if (!path.empty())
{
auto fileName = path.substr(path.rfind(L'\\') + 1);
DWORD relativeHookAddress = hp.addr - (DWORD)allocationBase;
code += L"@" + ToHexString(relativeHookAddress) + L":" + fileName;
return code;
}
}
}
if (hp.module)
{
code += L"@" + ToHexString(hp.addr) + L"!" + ToHexString(hp.module);
if (hp.function)
code += L"!" + ToHexString(hp.function);
}
else
{
// hack, the original address is stored in the function field
// if (module == NULL && function != NULL)
// in TextHook::UnsafeInsertHookCode() MODULE_OFFSET and FUNCTION_OFFSET are removed from
// HookParam.type
if (hp.function)
code += L"@" + ToHexString(hp.function);
else
code += L"@" + ToHexString(hp.addr) + L":";
}
return code;
}
std::wstring GetModuleFileNameAsString(DWORD pid, PVOID allocationBase)
{
const ProcessRecord* pr = man->GetProcessRecord(pid);
if (pr)
{
HANDLE hProc = pr->process_handle;
WCHAR path[MAX_PATH];
if (GetModuleFileNameEx(hProc, (HMODULE)allocationBase, path, MAX_PATH))
return path;
}
return L"";
}
PVOID GetAllocationBase(DWORD pid, LPCVOID addr)
{
const ProcessRecord *pr = man->GetProcessRecord(pid);
if (pr)
{
MEMORY_BASIC_INFORMATION info;
HANDLE hProc = pr->process_handle;
if (VirtualQueryEx(hProc, addr, &info, sizeof(info)))
{
if (info.Type & MEM_IMAGE)
return info.AllocationBase;
}
}
return NULL;
}
struct TitleParam
{
DWORD pid, buffer_len, retn_len;
std::wstring buffer;
};
BOOL CALLBACK EnumProc(HWND hwnd, LPARAM lParam)
{
TitleParam* p = (TitleParam*)lParam;
DWORD pid;
GetWindowThreadProcessId(hwnd, &pid);
if (pid == p->pid)
{
if (GetWindowLong(hwnd, GWL_STYLE) & WS_VISIBLE)
{
int len = GetWindowTextLength(hwnd);
std::unique_ptr<wchar_t[]> result(new wchar_t[len + 1]);
GetWindowText(hwnd, result.get(), len + 1);
p->buffer = result.get();
p->retn_len = p->buffer.size();
if (!p->buffer.empty())
return FALSE;
}
}
return TRUE;
}
std::wstring GetProcessTitle(DWORD pid)
{
TitleParam p;
p.pid = pid;
p.buffer_len = 0;
p.retn_len = 0;
EnumWindows(EnumProc, (LPARAM)&p);
return p.buffer;
}
WindowsError::WindowsError(DWORD error_code) : error_code(error_code), msg("")
{
CHAR str[512];
std::sprintf(str, "error code 0x%8x", error_code);
msg = str;
}
const char *WindowsError::what() const
{
return msg.c_str();
}
HANDLE IthCreateThread(LPVOID start_addr, DWORD param)
{
return CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)start_addr, (LPVOID)param, 0, NULL);
}
std::wstring GetModuleFileNameAsString()
{
WCHAR path[MAX_PATH];
GetModuleFileName(NULL, path, MAX_PATH);
return path;
}
bool IthCreateDirectory(LPCWSTR name)
{
std::wstring path = GetModuleFileNameAsString();
path = path.substr(0, path.rfind(L'\\') + 1) + name;
BOOL error_code = CreateDirectory(path.c_str(), NULL);
return error_code != 0 || GetLastError() == ERROR_ALREADY_EXISTS;
}
HANDLE IthCreateFile(LPCWSTR name, DWORD option, DWORD share, DWORD disposition)
{
std::wstring path = GetModuleFileNameAsString();
path = path.substr(0, path.rfind(L'\\') + 1) + name;
return CreateFile(path.c_str(), option, share, NULL, disposition, FILE_ATTRIBUTE_NORMAL, NULL);
}
//SJIS->Unicode. 'mb' must be null-terminated. 'wc_length' is the length of 'wc' in characters.
int MB_WC(const char* mb, wchar_t* wc, int wc_length)
{
return MultiByteToWideChar(932, 0, mb, -1, wc, wc_length);
}
// Count characters in wide string. 'mb_length' is the number of bytes from 'mb' to convert or
// -1 if the string is null terminated.
int MB_WC_count(const char* mb, int mb_length)
{
return MultiByteToWideChar(932, 0, mb, mb_length, NULL, 0);
}
// Unicode->SJIS. Analogous to MB_WC.
int WC_MB(const wchar_t *wc, char* mb, int mb_length)
{
return WideCharToMultiByte(932, 0, wc, -1, mb, mb_length, NULL, NULL);
}
DWORD Hash(const std::wstring& module, int length)
{
DWORD hash = 0;
auto end = length < 0 || static_cast<std::size_t>(length) > module.length() ? module.end() : module.begin() + length;
for (auto it = module.begin(); it != end; ++it)
hash = _rotr(hash, 7) + *it;
return hash;
}
#pragma once
#include "ITH.h"
struct HookParam;
struct ProcessRecord;
DWORD Hash(const std::wstring& module, int length = -1);
DWORD ProcessCommand(const std::wstring& cmd, DWORD pid);
std::wstring GetProcessPath(DWORD pid);
void ConsoleOutput(LPCWSTR);
void ConsoleOutput(LPCSTR text);
std::wstring GetProcessTitle(DWORD pid);
std::wstring GetCode(const HookParam& hp, DWORD pid = 0);
// http://codesequoia.wordpress.com/2012/08/26/stdunique_ptr-for-windows-handles/
struct HandleDeleter
{
typedef HANDLE pointer;
void operator() (HANDLE h)
{
if (h != INVALID_HANDLE_VALUE) {
CloseHandle(h);
}
}
};
typedef std::unique_ptr<HANDLE, HandleDeleter> UniqueHandle;
class FileWriter : public pugi::xml_writer
{
HANDLE hFile;
public:
FileWriter(HANDLE hFile) : hFile(hFile) {};
~FileWriter() {};
virtual void write(const void* data, size_t size)
{
DWORD dwNumberOfBytesWritten;
WriteFile(hFile, data, size, &dwNumberOfBytesWritten, NULL);
}
};
class WindowsError : public std::exception
{
private:
std::string msg;
DWORD error_code;
public:
WindowsError(DWORD error_code);
virtual const char *what() const;
};
HANDLE IthCreateThread(LPVOID start_addr, DWORD param);
bool IthCreateDirectory(LPCWSTR name);
HANDLE IthCreateFile(LPCWSTR name, DWORD option, DWORD share, DWORD disposition);
int MB_WC(const char* mb, wchar_t* wc, int wc_length);
int MB_WC_count(const char* mb, int mb_length);
int WC_MB(const wchar_t *wc, char* mb, int mb_length);
bool Parse(const std::wstring& cmd, HookParam& hp);
template <typename T>
std::wstring ToHexString(T i) {
std::wstringstream ss;
ss << std::uppercase << std::hex << i;
return ss.str();
}
// http://jrdodds.blogs.com/blog/2004/08/raii_in_c.html
class CriticalSection
{
public:
CriticalSection()
{
::InitializeCriticalSection(&m_rep);
}
~CriticalSection()
{
::DeleteCriticalSection(&m_rep);
}
void Enter()
{
::EnterCriticalSection(&m_rep);
}
void Leave()
{
::LeaveCriticalSection(&m_rep);
}
private:
CriticalSection(const CriticalSection&);
CriticalSection& operator=(const CriticalSection&);
CRITICAL_SECTION m_rep;
};
class CSLock
{
public:
CSLock(CriticalSection& a_section)
: m_section(a_section)
{
m_section.Enter();
}
~CSLock()
{
m_section.Leave();
}
private:
CSLock(const CSLock&);
CSLock& operator=(const CSLock&);
CriticalSection& m_section;
};
const wchar_t* build_date=L"27.01.2013";
const WCHAR program_version[] = L"@CPACK_PACKAGE_VERSION_MAJOR@.@CPACK_PACKAGE_VERSION_MINOR@.@CPACK_PACKAGE_VERSION_PATCH@";
/* Copyright (C) 2010-2012 kaosu (qiupf2000@gmail.com)
* This file is part of the Interactive Text Hooker.
* Interactive Text Hooker is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "window.h"
#include "ProcessWindow.h"
#include "resource.h"
#include "language.h"
#include "ith/host/srv.h"
#include "ith/host/hookman.h"
#include "ith/common/const.h"
#include "version.h"
#include "ProfileManager.h"
#include "ith/host/SettingManager.h"
#include "CustomFilter.h"
#include "Profile.h"
#include "TextBuffer.h"
#define CMD_SIZE 512
static WNDPROC proc, proccmd, procChar;
static WCHAR last_cmd[CMD_SIZE];
extern HINSTANCE hIns; // main.cpp
HWND hMainWnd, hwndCombo, hwndProcessComboBox, hwndEdit, hwndCmd;
HWND hwndProcess;
HWND hwndOption, hwndTop, hwndClear, hwndSave, hwndRemoveLink, hwndRemoveHook;
HWND hProcDlg, hOptionDlg;
HBRUSH hWhiteBrush;
DWORD background;
ProcessWindow* pswnd;
TextBuffer* texts;
extern ProfileManager* pfman; // ProfileManager.cpp
extern HookManager* man; // main.cpp
extern CustomFilter* mb_filter; // main.cpp
extern CustomFilter* uni_filter; // main.cpp
extern SettingManager* setman; // main.cpp
#define COMMENT_BUFFER_LENGTH 512
static WCHAR comment_buffer[COMMENT_BUFFER_LENGTH];
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
void SaveSettings(); // main.cpp
extern LONG split_time, process_time, inject_delay, insert_delay,
auto_inject, auto_insert, clipboard_flag, cyclic_remove, global_filter; //main.cpp
static int last_select, last_edit;
void AddLinksToHookManager(const Profile& pf, size_t thread_profile_index, const TextThread& thread);
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = NULL;
wcex.hCursor = NULL;
wcex.hbrBackground = GetStockBrush(WHITE_BRUSH);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = ClassName;
wcex.hIconSm = LoadIcon(hInstance, (LPWSTR)IDI_ICON1);
return RegisterClassEx(&wcex);
}
BOOL InitInstance(HINSTANCE hInstance, DWORD nAdmin, RECT* rc)
{
hIns = hInstance;
LPCWSTR name = (nAdmin) ? ClassNameAdmin : ClassName;
hMainWnd = CreateWindow(ClassName, name, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top, NULL, NULL, hInstance, 0);
if (!hMainWnd)
return FALSE;
ShowWindow(hMainWnd, SW_SHOWNORMAL);
UpdateWindow(hMainWnd);
return TRUE;
}
DWORD SaveProcessProfile(DWORD pid); // ProfileManager.cpp
BOOL CALLBACK OptionDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_INITDIALOG:
{
SetWindowText(GetDlgItem(hDlg, IDC_EDIT1), std::to_wstring((long long)split_time).c_str());
SetWindowText(GetDlgItem(hDlg, IDC_EDIT2), std::to_wstring((long long)process_time).c_str());
SetWindowText(GetDlgItem(hDlg, IDC_EDIT3), std::to_wstring((long long)inject_delay).c_str());
SetWindowText(GetDlgItem(hDlg, IDC_EDIT4), std::to_wstring((long long)insert_delay).c_str());
CheckDlgButton(hDlg, IDC_CHECK1, auto_inject);
CheckDlgButton(hDlg, IDC_CHECK2, auto_insert);
CheckDlgButton(hDlg, IDC_CHECK3, clipboard_flag);
CheckDlgButton(hDlg, IDC_CHECK4, cyclic_remove);
CheckDlgButton(hDlg, IDC_CHECK5, global_filter);
}
return TRUE;
case WM_COMMAND:
{
DWORD wmId = LOWORD(wParam);
DWORD wmEvent = HIWORD(wParam);
switch (wmId)
{
case IDOK:
{
WCHAR str[128];
GetWindowText(GetDlgItem(hDlg, IDC_EDIT1), str, 0x80);
DWORD st = std::stoul(str);
split_time = st > 100 ? st : 100;
GetWindowText(GetDlgItem(hDlg, IDC_EDIT2), str, 0x80);
DWORD pt = std::stoul(str);
process_time = pt > 50 ? pt : 50;
GetWindowText(GetDlgItem(hDlg, IDC_EDIT3), str, 0x80);
DWORD jd = std::stoul(str);
inject_delay = jd > 1000 ? jd : 1000;
GetWindowText(GetDlgItem(hDlg, IDC_EDIT4), str, 0x80);
DWORD sd = std::stoul(str);
insert_delay = sd > 200 ? sd : 200;
if (IsDlgButtonChecked(hDlg, IDC_CHECK6))
{
man->ResetRepeatStatus();
}
auto_inject = IsDlgButtonChecked(hDlg, IDC_CHECK1);
auto_insert = IsDlgButtonChecked(hDlg, IDC_CHECK2);
clipboard_flag = IsDlgButtonChecked(hDlg, IDC_CHECK3);
cyclic_remove = IsDlgButtonChecked(hDlg, IDC_CHECK4);
global_filter = IsDlgButtonChecked(hDlg, IDC_CHECK5);
setman->SetValue(SETTING_CLIPFLAG, clipboard_flag);
setman->SetValue(SETTING_SPLIT_TIME, split_time);
if (auto_inject == 0) auto_insert = 0;
}
case IDCANCEL:
EndDialog(hDlg, 0);
hOptionDlg = NULL;
break;
}
return TRUE;
}
default:
return FALSE;
}
return FALSE;
}
BOOL CALLBACK ProcessDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_INITDIALOG:
{
pswnd = new ProcessWindow(hDlg);
return TRUE;
}
case WM_COMMAND:
{
DWORD wmId, wmEvent;
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
switch (wmId)
{
case WM_DESTROY:
case IDOK:
EndDialog(hDlg, NULL);
hProcDlg = NULL;
delete pswnd;
pswnd = NULL;
break;
case IDC_BUTTON1:
pswnd->RefreshProcess();
break;
case IDC_BUTTON2:
pswnd->AttachProcess();
break;
case IDC_BUTTON3:
pswnd->DetachProcess();
break;
case IDC_BUTTON5:
pswnd->AddCurrentToProfile();
break;
case IDC_BUTTON6:
pswnd->RemoveCurrentFromProfile();
break;
}
}
return TRUE;
case WM_NOTIFY:
{
LPNMHDR dr = (LPNMHDR)lParam;
switch (dr->code)
{
case LVN_ITEMCHANGED:
if (dr->idFrom == IDC_LIST1)
{
NMLISTVIEW *nmlv = (LPNMLISTVIEW)lParam;
if (nmlv->uNewState & LVIS_SELECTED)
pswnd->RefreshThread(nmlv->iItem);
}
break;
}
}
return TRUE;
default:
return FALSE;
}
}
LRESULT CALLBACK EditProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CHAR: //Filter user input.
if (GetKeyState(VK_CONTROL) & 0x8000)
{
if (wParam == 1)
{
Edit_SetSel(hwndEdit, 0, -1);
SendMessage(hwndEdit, WM_COPY, 0, 0);
}
}
return 0;
case WM_LBUTTONUP:
if (hwndEdit)
SendMessage(hwndEdit, WM_COPY, 0, 0);
default:
{
return proc(hWnd, message, wParam, lParam);
}
}
}
LRESULT CALLBACK EditCmdProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_KEYDOWN:
if (wParam == VK_UP)
{
SetWindowText(hWnd, last_cmd);
SetFocus(hWnd);
return 0;
}
break;
case WM_CHAR:
if (wParam == VK_RETURN)
{
DWORD s = 0, pid = 0;
WCHAR str[32];
if (GetWindowTextLength(hWnd) == 0)
break;
GetWindowText(hWnd, last_cmd, CMD_SIZE);
//IthBreak();
if (GetWindowText(hwndProcessComboBox, str, 32))
pid = std::stoul(str);
ProcessCommand(last_cmd, pid);
Edit_SetSel(hWnd, 0, -1);
Edit_ReplaceSel(hWnd, &s);
SetFocus(hWnd);
return 0;
}
default:
break;
}
return CallWindowProc(proccmd, hWnd, message, wParam, lParam);
}
void CreateButtons(HWND hWnd)
{
hwndProcess = CreateWindow(L"Button", L"Process", WS_CHILD | WS_VISIBLE,
0, 0, 0, 0, hWnd, 0, hIns, NULL);
hwndOption = CreateWindow(L"Button", L"Option", WS_CHILD | WS_VISIBLE,
0, 0, 0, 0, hWnd, 0, hIns, NULL);
hwndClear = CreateWindow(L"Button", L"Clear", WS_CHILD | WS_VISIBLE,
0, 0, 0, 0, hWnd, 0, hIns, NULL);
hwndSave = CreateWindow(L"Button", L"Save", WS_CHILD | WS_VISIBLE,
0, 0, 0, 0, hWnd, 0, hIns, NULL);
hwndRemoveLink = CreateWindow(L"Button", L"Unlink", WS_CHILD | WS_VISIBLE,
0, 0, 0, 0, hWnd, 0, hIns, NULL);
hwndRemoveHook = CreateWindow(L"Button", L"Unhook", WS_CHILD | WS_VISIBLE,
0, 0, 0, 0, hWnd, 0, hIns, NULL);
hwndTop = CreateWindow(L"Button", L"Top", WS_CHILD | WS_VISIBLE | BS_PUSHLIKE | BS_CHECKBOX,
0, 0, 0, 0, hWnd, 0, hIns, NULL);
hwndProcessComboBox = CreateWindow(L"ComboBox", NULL,
WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST |
CBS_SORT | WS_VSCROLL | WS_TABSTOP,
0, 0, 0, 0, hWnd, 0, hIns, NULL);
hwndCmd = CreateWindowEx(WS_EX_CLIENTEDGE, L"Edit", NULL,
WS_CHILD | WS_VISIBLE | ES_NOHIDESEL| ES_LEFT | ES_AUTOHSCROLL,
0, 0, 0, 0, hWnd, 0, hIns, NULL);
hwndEdit = CreateWindowEx(WS_EX_CLIENTEDGE, L"Edit", NULL,
WS_CHILD | WS_VISIBLE | ES_NOHIDESEL| WS_VSCROLL |
ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL,
0, 0, 0, 0, hWnd, 0, hIns, NULL);
}
void ClickButton(HWND hWnd, HWND h)
{
if (h == hwndProcess)
{
if (hProcDlg)
SetForegroundWindow(hProcDlg);
else
hProcDlg = CreateDialog(hIns, (LPWSTR)IDD_DIALOG2, 0, ProcessDlgProc);
}
else if (h == hwndOption)
{
if (hOptionDlg)
SetForegroundWindow(hOptionDlg);
else
hOptionDlg = CreateDialog(hIns, (LPWSTR)IDD_DIALOG4, 0, OptionDlgProc);
}
else if (h == hwndClear)
{
WCHAR pwcEntry[128] = {};
DWORD dwId = ComboBox_GetCurSel(hwndCombo);
int len = ComboBox_GetLBText(hwndCombo, dwId, pwcEntry);
dwId = std::stoul(pwcEntry, NULL, 16);
if (dwId == 0)
man->ClearCurrent();
else
man->RemoveSingleThread(dwId);
}
else if (h == hwndTop)
{
if (Button_GetCheck(h)==BST_CHECKED)
{
Button_SetCheck(h, BST_UNCHECKED);
SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
if (hProcDlg)
SetWindowPos(hProcDlg, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
if (hOptionDlg)
SetWindowPos(hOptionDlg, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
}
else
{
Button_SetCheck(h, BST_CHECKED);
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
if (hProcDlg)
SetWindowPos(hProcDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
if (hOptionDlg)
SetWindowPos(hOptionDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
}
}
else if (h == hwndSave)
{
WCHAR str[32];
if (GetWindowText(hwndProcessComboBox, str, 32))
{
DWORD pid = std::stoul(str);
SaveProcessProfile(pid);
}
pfman->SaveProfile();
}
else if (h == hwndRemoveLink)
{
WCHAR str[32];
if (GetWindowText(hwndCombo, str, 32))
{
DWORD from = std::stoul(str, NULL, 16);
if (from != 0)
IHF_UnLink(from);
}
}
else if (h == hwndRemoveHook)
{
WCHAR str[32];
if (GetWindowText(hwndCombo, str, 32))
{
std::wstring entry(str);
std::size_t i;
DWORD threadNumber = std::stoul(entry, &i, 16);
entry = entry.substr(i + 1);
DWORD pid = std::stoul(entry, &i);
entry = entry.substr(i + 1);
DWORD addr = std::stoul(entry, NULL, 16);
if (threadNumber != 0)
IHF_RemoveHook(pid, addr);
}
}
}
DWORD ThreadFilter(TextThread* thread, BYTE* out,DWORD len, DWORD new_line, PVOID data, bool space)
{
DWORD status = thread->Status();
if (global_filter && !new_line && thread->Number() != 0)
{
if (status & USING_UNICODE)
{
DWORD i, j;
len /= 2;
LPWSTR str = (LPWSTR)out;
for (i = 0, j = 0; i < len; i++)
{
WCHAR c = str[i];
if (!uni_filter->Find(c))
str[j++] = c;
}
memset(str + j, 0, (len - j) * 2);
len = j * 2;
}
else
{
DWORD i, j;
for (i = 0, j = 0; i < len; i++)
{
WORD c = out[i];
if (!IsDBCSLeadByte(c & 0xFF))
{
if (!mb_filter->Find(c))
out[j++] = c & 0xFF;
}
else if (i + 1 < len)
{
c = out[i + 1];
c <<= 8;
c |= out[i];
if (!mb_filter->Find(c))
{
out[j++] = c & 0xFF;
out[j++] = c >> 8;
}
i++;
}
}
memset(out + j, 0, len - j);
len = j;
}
}
return len;
}
DWORD ThreadOutput(TextThread* thread, BYTE* out,DWORD len, DWORD new_line, PVOID data, bool space)
{
if (len == 0)
return len;
DWORD status = thread->Status();
if (status & CURRENT_SELECT)
{
if (new_line)
{
if (thread->Number() == 0)
texts->AddText(L"\r\n", 2, true);
else
texts->AddText(L"\r\n\r\n", 4, true);
}
else if (status & USING_UNICODE)
{
texts->AddText((LPWSTR)out, len / 2, false);
}
else
{
int uni_len = MB_WC_count((char*)out, len);
LPWSTR str = new WCHAR[uni_len + 1];
MB_WC((char*)out, str, uni_len + 1);
str[uni_len] = L'\0';
texts->AddText(str, uni_len, false);
delete str;
}
}
return len;
}
bool GetHookParam(DWORD pid, DWORD hook_addr, HookParam& hp)
{
if (!pid)
return false;
ProcessRecord *pr = ::man->GetProcessRecord(pid);
if (!pr)
return false;
bool result = false;
WaitForSingleObject(pr->hookman_mutex, 0);
const Hook *hks = (Hook *)pr->hookman_map;
for (int i = 0; i < MAX_HOOK; i++)
{
if (hks[i].Address() == hook_addr)
{
hp = hks[i].hp;
result = true;
break;
}
}
ReleaseMutex(pr->hookman_mutex);
return result;
}
void AddToCombo(TextThread& thread, bool replace)
{
WCHAR entry[512];
thread.GetEntryString(entry, 512);
std::wstring entryWithLink(entry);
if (thread.Link())
entryWithLink += L"->" + ToHexString(thread.LinkNumber());
if (thread.PID() == 0)
entryWithLink += L"ConsoleOutput";
HookParam hp = {};
if (GetHookParam(thread.PID(), thread.Addr(), hp))
entryWithLink += L" (" + GetCode(hp, thread.PID()) + L")";
int i = ComboBox_FindString(hwndCombo, 0, entry);
if (replace)
{
int sel = ComboBox_GetCurSel(hwndCombo);
if (i != CB_ERR)
ComboBox_DeleteString(hwndCombo, i);
ComboBox_AddString(hwndCombo, entryWithLink.c_str());
ComboBox_SetCurSel(hwndCombo, sel);
}
else
{
if (i == CB_ERR)
ComboBox_AddString(hwndCombo, entryWithLink.c_str());
// Why set current selection to 0 when the new thread is selected?
if (thread.Status() & CURRENT_SELECT)
ComboBox_SetCurSel(hwndCombo, 0);
}
}
void RemoveFromCombo(TextThread* thread)
{
WCHAR entry[512];
thread->GetEntryString(entry, 512);
if (thread->PID() == 0)
std::wcscat(entry, L"ConsoleOutput");
int i = ComboBox_FindString(hwndCombo, 0, entry);
if (i != CB_ERR)
{
if (ComboBox_DeleteString(hwndCombo, i) == CB_ERR)
ConsoleOutput(ErrorDeleteCombo);
}
}
void ComboSelectCurrent(TextThread* thread)
{
ComboBox_SetCurSel(hwndCombo, thread->Number());
}
DWORD SetEditText(LPWSTR wc)
{
DWORD line;
Edit_SetText(hwndEdit, wc);
line = Edit_GetLineCount(hwndEdit);
SendMessage(hwndEdit, EM_LINESCROLL, 0, line);
return 0;
}
DWORD ThreadReset(TextThread* thread)
{
texts->ClearBuffer();
man->SetCurrent(thread);
thread->LockVector();
DWORD uni = thread->Status() & USING_UNICODE;
if (uni)
{
DWORD len = 0;
LPWSTR wc = (LPWSTR)thread->GetStore(&len);
len /= 2;
wc[len] = L'\0';
SetEditText(wc);
}
else
{
DWORD len = MB_WC_count((char*)thread->Storage(), thread->Used());
LPWSTR wc = new WCHAR[len + 1];
MB_WC((char*)thread->Storage(), wc, len + 1);
wc[len] = L'\0';
SetEditText(wc);
delete wc;
}
WCHAR buffer[16];
std::swprintf(buffer, L"%04X", thread->Number());
DWORD tmp = ComboBox_FindString(hwndCombo, 0, buffer);
if (tmp != CB_ERR)
ComboBox_SetCurSel(hwndCombo, tmp);
thread->UnlockVector();
return 0;
}
DWORD AddRemoveLink(TextThread* thread)
{
AddToCombo(*thread, true);
return 0;
}
bool IsUnicodeHook(const ProcessRecord& pr, DWORD hook)
{
bool res = false;
WaitForSingleObject(pr.hookman_mutex, 0);
auto hooks = (const Hook*)pr.hookman_map;
for (DWORD i = 0; i < MAX_HOOK; i++)
{
if (hooks[i].Address() == hook)
{
res = hooks[i].Type() & USING_UNICODE;
break;
}
}
ReleaseMutex(pr.hookman_mutex);
return res;
}
DWORD ThreadCreate(TextThread* thread)
{
thread->RegisterOutputCallBack(ThreadOutput, 0);
thread->RegisterFilterCallBack(ThreadFilter, 0);
AddToCombo(*thread, false);
const auto tp = thread->GetThreadParameter();
auto pr = man->GetProcessRecord(tp->pid);
if (pr != NULL)
{
if (IsUnicodeHook(*pr, tp->hook))
thread->Status() |= USING_UNICODE;
}
auto pf = pfman->GetProfile(tp->pid);
if (pf)
{
auto thread_profile = pf->FindThreadProfile(*tp);
if (thread_profile != pf->Threads().end())
{
(*thread_profile)->HookManagerIndex() = thread->Number();
auto thread_profile_index = thread_profile - pf->Threads().begin();
AddLinksToHookManager(*pf, thread_profile_index, *thread);
if (pf->SelectedIndex() == thread_profile_index)
ThreadReset(thread);
}
}
return 0;
}
void AddLinksToHookManager(const Profile& pf, size_t thread_profile_index, const TextThread& thread)
{
for (auto lp = pf.Links().begin(); lp != pf.Links().end(); ++lp)
{
if ((*lp)->FromIndex() == thread_profile_index)
{
WORD to_index = pf.Threads()[(*lp)->ToIndex()]->HookManagerIndex();
if (to_index != 0)
man->AddLink(thread.Number(), to_index);
}
if ((*lp)->ToIndex() == thread_profile_index)
{
WORD from_index = pf.Threads()[(*lp)->FromIndex()]->HookManagerIndex();
if (from_index != 0)
man->AddLink(from_index, thread.Number());
}
}
}
DWORD ThreadRemove(TextThread* thread)
{
RemoveFromCombo(thread);
const auto tp = thread->GetThreadParameter();
auto pf = pfman->GetProfile(tp->pid);
if (pf)
{
auto thread_profile = pf->FindThreadProfile(*tp);
if (thread_profile != pf->Threads().end())
(*thread_profile)->HookManagerIndex() = 0; // reset hookman index number
}
return 0;
}
DWORD RegisterProcessList(DWORD pid)
{
auto path = GetProcessPath(pid);
if (!path.empty())
{
WCHAR str[MAX_PATH];
std::swprintf(str, L"%04d:%s", pid, path.substr(path.rfind(L'\\') + 1).c_str());
ComboBox_AddString(hwndProcessComboBox, str);
if (ComboBox_GetCount(hwndProcessComboBox) == 1)
ComboBox_SetCurSel(hwndProcessComboBox, 0);
pfman->FindProfileAndUpdateHookAddresses(pid, path);
}
return 0;
}
DWORD RemoveProcessList(DWORD pid)
{
WCHAR str[MAX_PATH];
std::swprintf(str, L"%04d", pid);
DWORD i = ComboBox_FindString(hwndProcessComboBox, 0, str);
DWORD j = ComboBox_GetCurSel(hwndProcessComboBox);
if (i != CB_ERR)
{
DWORD k = ComboBox_DeleteString(hwndProcessComboBox, i);
if (i == j)
ComboBox_SetCurSel(hwndProcessComboBox, 0);
}
return 0;
}
DWORD RefreshProfileOnNewHook(DWORD pid)
{
auto path = GetProcessPath(pid);
if (!path.empty())
pfman->FindProfileAndUpdateHookAddresses(pid, path);
return 0;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
CreateButtons(hWnd);
// Add text to the window.
Edit_LimitText(hwndEdit, -1);
SendMessage(hwndEdit, WM_INPUTLANGCHANGEREQUEST, 0, 0x411);
proc = (WNDPROC)SetWindowLong(hwndEdit, GWL_WNDPROC, (LONG)EditProc);
proccmd = (WNDPROC)SetWindowLong(hwndCmd, GWL_WNDPROC, (LONG)EditCmdProc);
hwndCombo = CreateWindow(L"ComboBox", NULL,
WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST |
CBS_SORT | WS_VSCROLL | WS_TABSTOP,
0, 0, 0, 0, hWnd, 0, hIns, NULL);
{
HFONT hf = CreateFont(18, 0, 0, 0, FW_LIGHT, 0, 0, 0, SHIFTJIS_CHARSET, 0, 0, ANTIALIASED_QUALITY, 0,
L"MS Gothic");
hWhiteBrush = GetStockBrush(WHITE_BRUSH);
SendMessage(hwndCmd, WM_SETFONT, (WPARAM)hf, 0);
SendMessage(hwndEdit, WM_SETFONT, (WPARAM)hf, 0);
SendMessage(hwndCombo, WM_SETFONT, (WPARAM)hf, 0);
SendMessage(hwndProcessComboBox, WM_SETFONT, (WPARAM)hf, 0);
texts = new TextBuffer(hwndEdit);
man->RegisterThreadCreateCallback(ThreadCreate);
man->RegisterThreadRemoveCallback(ThreadRemove);
man->RegisterThreadResetCallback(ThreadReset);
TextThread* console = man->FindSingle(0);
console->RegisterOutputCallBack(ThreadOutput, NULL);
AddToCombo(*console, false);
man->RegisterProcessAttachCallback(RegisterProcessList);
man->RegisterProcessDetachCallback(RemoveProcessList);
man->RegisterProcessNewHookCallback(RefreshProfileOnNewHook);
man->RegisterAddRemoveLinkCallback(AddRemoveLink);
man->RegisterConsoleCallback(ConsoleOutput);
IHF_Start();
{
static const WCHAR program_name[] = L"Interactive Text Hooker";
//static const WCHAR program_version[] = L"3.0";
static WCHAR version_info[256];
std::swprintf(version_info, L"%s %s (%s)", program_name, program_version, build_date);
man->AddConsoleOutput(version_info);
man->AddConsoleOutput(InitMessage);
}
if (background == 0)
man->AddConsoleOutput(BackgroundMsg);
if (!IHF_IsAdmin())
man->AddConsoleOutput(NotAdmin);
}
return 0;
case WM_COMMAND:
{
DWORD wmId, wmEvent, dwId;
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
switch (wmEvent)
{
case EN_VSCROLL:
{
SCROLLBARINFO info={sizeof(info)};
GetScrollBarInfo(hwndEdit, OBJID_VSCROLL, &info);
InvalidateRect(hwndEdit, 0, 1);
ValidateRect(hwndEdit, &info.rcScrollBar);
RedrawWindow(hwndEdit, 0, 0, RDW_ERASE);
}
break;
case CBN_SELENDOK:
{
if ((HWND)lParam == hwndProcessComboBox)
return 0;
dwId = ComboBox_GetCurSel(hwndCombo);
int len = ComboBox_GetLBTextLen(hwndCombo, dwId);
if (len > 0)
{
LPWSTR pwcEntry = new WCHAR[len + 1];
len = ComboBox_GetLBText(hwndCombo, dwId, pwcEntry);
DWORD num = std::stoul(pwcEntry, NULL, 16);
man->SelectCurrent(num);
delete[] pwcEntry;
}
}
return 0;
case BN_CLICKED:
ClickButton(hWnd, (HWND)lParam);
break;
default:
break;
}
}
break;
case WM_SETFOCUS:
SetFocus(hwndEdit);
return 0;
case WM_SIZE:
{
WORD width = LOWORD(lParam);
WORD height = HIWORD(lParam);
DWORD l = width / 7;
WORD h = HIWORD(GetDialogBaseUnits()); // height of the system font
h = h + (h / 2);
HDC hDC = GetDC(hWnd);
RECT rc;
GetClientRect(hWnd, &rc);
FillRect(hDC, &rc, hWhiteBrush);
ReleaseDC(hWnd, hDC);
MoveWindow(hwndProcess, 0, 0, l, h, TRUE);
MoveWindow(hwndOption, l * 1, 0, l, h, TRUE);
MoveWindow(hwndTop, l * 2, 0, l, h, TRUE);
MoveWindow(hwndClear, l * 3, 0, l, h, TRUE);
MoveWindow(hwndRemoveLink, l * 4, 0, l, h, TRUE);
MoveWindow(hwndRemoveHook, l * 5, 0, l, h, TRUE);
MoveWindow(hwndSave, l * 6, 0, width - 6 * l, h, TRUE);
l *= 2;
MoveWindow(hwndProcessComboBox, 0, h, l, 200, TRUE);
MoveWindow(hwndCmd, l, h, width - l, h, TRUE);
MoveWindow(hwndCombo, 0, h * 2, width, 200, TRUE);
h *= 3;
MoveWindow(hwndEdit, 0, h, width, height - h, TRUE);
}
return 0;
case WM_DESTROY:
man->RegisterThreadCreateCallback(0);
man->RegisterThreadRemoveCallback(0);
man->RegisterThreadResetCallback(0);
man->RegisterProcessAttachCallback(0);
man->RegisterProcessDetachCallback(0);
//delete texts;
SaveSettings();
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
DWORD WINAPI FlushThread(LPVOID lParam)
{
TextBuffer* t = (TextBuffer*)lParam;
while (t->Running())
{
t->Flush();
Sleep(10);
}
return 0;
}
/* Copyright (C) 2010-2012 kaosu (qiupf2000@gmail.com)
* This file is part of the Interactive Text Hooker.
* Interactive Text Hooker is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "ITH.h"