-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.cpp
More file actions
182 lines (151 loc) · 7.38 KB
/
Copy pathplugin.cpp
File metadata and controls
182 lines (151 loc) · 7.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#include "logger.h"
#include "src/game/EventBus.h"
#include "src/server/WsServer.h"
#include <DbgHelp.h>
#include <boost/asio.hpp>
#include <memory>
#include <thread>
#include <vector>
static constexpr std::uint16_t DEFAULT_PORT = 8765;
static constexpr const char* DEFAULT_ADDRESS = "127.0.0.1";
namespace asio = boost::asio;
using tcp = asio::ip::tcp;
static asio::io_context g_ioc;
static std::unique_ptr<WsServer> g_server;
static std::thread g_ioThread;
// Keeps g_ioc.run() alive even when there are no async operations scheduled.
static std::unique_ptr<asio::executor_work_guard<
asio::io_context::executor_type>> g_workGuard;
// Address marker used to locate this DLL's HMODULE at runtime.
static const char kModuleLocator = 0;
// Path for the minidump written by the crash handler (set at plugin load).
static std::wstring g_dumpPath;
// Previous unhandled-exception filter, chained from our handler.
static LPTOP_LEVEL_EXCEPTION_FILTER g_prevCrashFilter = nullptr;
// Parse the LogLevel string read from the [Debug] INI section.
// Accepted values (case-insensitive): "trace", "debug", "info".
// Anything else (including the default empty/"off") returns level::off.
static spdlog::level::level_enum ParseLogLevel(const char* str)
{
if (_stricmp(str, "trace") == 0) return spdlog::level::trace;
if (_stricmp(str, "debug") == 0) return spdlog::level::debug;
if (_stricmp(str, "info") == 0) return spdlog::level::info;
return spdlog::level::off;
}
// Unhandled-exception filter: flushes the log and writes a minidump next to
// the log file, then chains to any previously registered filter.
static LONG WINAPI SkyrimWebSocketCrashHandler(EXCEPTION_POINTERS* ep)
{
if (auto* log = spdlog::default_logger_raw()) {
log->critical("=== CRASH DETECTED ===");
log->critical("Exception code: 0x{:08X}", ep->ExceptionRecord->ExceptionCode);
log->critical("Exception address: 0x{:016X}",
reinterpret_cast<std::uintptr_t>(ep->ExceptionRecord->ExceptionAddress));
log->flush();
}
if (!g_dumpPath.empty()) {
HANDLE hFile = ::CreateFileW(g_dumpPath.c_str(), GENERIC_WRITE, 0, nullptr,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile != INVALID_HANDLE_VALUE) {
MINIDUMP_EXCEPTION_INFORMATION info{};
info.ThreadId = ::GetCurrentThreadId();
info.ExceptionPointers = ep;
info.ClientPointers = FALSE;
::MiniDumpWriteDump(::GetCurrentProcess(), ::GetCurrentProcessId(),
hFile, MiniDumpNormal, &info, nullptr, nullptr);
::CloseHandle(hFile);
}
}
if (g_prevCrashFilter)
return g_prevCrashFilter(ep);
return EXCEPTION_CONTINUE_SEARCH;
}
static std::string GetIniPath()
{
HMODULE hModule = nullptr;
if (!::GetModuleHandleExA(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
&kModuleLocator,
&hModule)) {
return {};
}
// Use a growing buffer to handle paths longer than MAX_PATH.
std::vector<char> buf(MAX_PATH);
for (;;) {
const DWORD len = ::GetModuleFileNameA(hModule, buf.data(),
static_cast<DWORD>(buf.size()));
if (len == 0)
return {};
if (len < buf.size() - 1)
break;
// Buffer was too small; double it and try again.
if (buf.size() >= 32 * 1024)
return {}; // sanity guard
buf.resize(buf.size() * 2);
}
std::string path(buf.data());
auto lastSlash = path.find_last_of("\\/");
if (lastSlash != std::string::npos)
path = path.substr(0, lastSlash);
return path + "\\SkyrimWebSocket.ini";
}
SKSEPluginLoad(const SKSE::LoadInterface* skse)
{
SKSE::Init(skse);
// ── Logging setup ────────────────────────────────────────────────────
// Read LogLevel from [Debug] before anything else so every subsequent
// log call is already routed to the right sink.
std::string iniPath = GetIniPath();
char levelBuf[32] = {};
::GetPrivateProfileStringA("Debug", "LogLevel", "off",
levelBuf, sizeof(levelBuf), iniPath.c_str());
const auto logLevel = ParseLogLevel(levelBuf);
SetupLog(logLevel);
if (logLevel != spdlog::level::off) {
logger::info("SkyrimWebSocket starting (LogLevel={})", levelBuf);
logger::info("INI path: {}", iniPath.empty() ? "(not found)" : iniPath);
// Pre-compute the minidump path (same folder as the .log file).
auto logsFolder = SKSE::log::log_directory();
if (logsFolder) {
auto pluginName = SKSE::PluginDeclaration::GetSingleton()->GetName();
g_dumpPath = (*logsFolder / std::format("{}.dmp", pluginName)).wstring();
logger::debug("Minidump path: {}", (*logsFolder / std::format("{}.dmp", pluginName)).string());
}
g_prevCrashFilter = ::SetUnhandledExceptionFilter(SkyrimWebSocketCrashHandler);
}
// ── Server startup ───────────────────────────────────────────────────
// Start the WS server once, as soon as data files are loaded (i.e. main
// menu is visible). This lets clients connect before any save is loaded.
// Field resolvers are responsible for returning null for fields that
// require an actual in-game session (see FieldRegistry::IsInGame).
SKSE::GetMessagingInterface()->RegisterListener([](SKSE::MessagingInterface::Message* msg) {
if (msg->type == SKSE::MessagingInterface::kDataLoaded && !g_server) {
// Wire up SKSE event sinks for the event-driven optimisation
// layer. Must run on the game thread — kDataLoaded is delivered
// there.
EventBus::Install();
std::string iniPath = GetIniPath();
char addressBuf[64];
::GetPrivateProfileStringA(
"Server", "ListenAddress", DEFAULT_ADDRESS,
addressBuf, sizeof(addressBuf), iniPath.c_str());
UINT port = ::GetPrivateProfileIntA("Server", "Port", DEFAULT_PORT, iniPath.c_str());
if (port == 0 || port > 65535)
port = DEFAULT_PORT;
boost::system::error_code ec;
auto addr = asio::ip::make_address(addressBuf, ec);
if (ec)
addr = asio::ip::make_address(DEFAULT_ADDRESS);
logger::debug("WS server starting on {}:{}", addressBuf, port);
tcp::endpoint endpoint(addr, static_cast<std::uint16_t>(port));
g_server = std::make_unique<WsServer>(g_ioc, endpoint);
// Keep the io_context alive even if there are momentarily no
// pending operations — avoids the run() thread exiting early.
g_workGuard = std::make_unique<asio::executor_work_guard<
asio::io_context::executor_type>>(g_ioc.get_executor());
g_ioThread = std::thread([] { g_ioc.run(); });
g_ioThread.detach();
}
});
return true;
}