10#pragma comment(lib, "winhttp.lib")
11#pragma comment(lib, "bcrypt.lib")
13namespace fs = std::filesystem;
18 struct File { HANDLE h; ~File() {
if (h != INVALID_HANDLE_VALUE) CloseHandle(h); } };
19 struct Http { HINTERNET h; ~Http() {
if (h) WinHttpCloseHandle(h); } };
20 bool IsId(
const std::wstring&
id)
22 if (
id.size() != 36)
return false;
23 for (
size_t i = 0; i <
id.size(); ++i) {
24 if (i == 8 || i == 13 || i == 18 || i == 23) {
if (
id[i] != L
'-')
return false; }
25 else if (!((
id[i] >= L
'0' &&
id[i] <= L
'9') || (
id[i] >= L
'a' &&
id[i] <= L
'f')))
return false;
29 void Status(
const fs::path& path,
const std::string& message)
32 std::ofstream out(path, std::ios::trunc); out << message <<
'\n';
34 std::wstring
Hash(HANDLE file)
36 BCRYPT_ALG_HANDLE algorithm =
nullptr;
37 BCRYPT_HASH_HANDLE hash =
nullptr;
38 if (BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM,
nullptr, 0) < 0)
return {};
40 if (BCryptCreateHash(algorithm, &hash,
nullptr, 0,
nullptr, 0, 0) >= 0) {
41 std::array<unsigned char, 64 * 1024> buffer;
42 DWORD bytes = 0;
bool success =
true;
44 if (!ReadFile(file, buffer.data(),
static_cast<DWORD>(buffer.size()), &bytes,
nullptr)) { success =
false;
break; }
46 if (BCryptHashData(hash, buffer.data(), bytes, 0) < 0) { success =
false;
break; }
48 unsigned char digest[32];
49 if (success && BCryptFinishHash(hash, digest,
sizeof digest, 0) >= 0) {
50 const wchar_t hex[] = L
"0123456789abcdef";
51 for (
auto c : digest) { result += hex[c >> 4]; result += hex[c & 15]; }
53 BCryptDestroyHash(hash);
55 BCryptCloseAlgorithmProvider(algorithm, 0);
56 SetFilePointer(file, 0,
nullptr, FILE_BEGIN);
59 bool Receipt(HINTERNET request,
const wchar_t* header,
const std::wstring& expected)
61 wchar_t actual[128] = {};
DWORD bytes =
sizeof actual;
62 return WinHttpQueryHeaders(request, WINHTTP_QUERY_CUSTOM, header, actual, &bytes, WINHTTP_NO_HEADER_INDEX)
63 && actual == expected;
65 long long NowSeconds() {
return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count(); }
66 unsigned RetryAfter(HINTERNET request)
68 wchar_t value[128] = {};
DWORD bytes =
sizeof value;
69 if (!WinHttpQueryHeaders(request, WINHTTP_QUERY_CUSTOM, L
"Retry-After", value, &bytes, WINHTTP_NO_HEADER_INDEX))
return 0;
70 wchar_t* end =
nullptr;
71 unsigned long seconds = wcstoul(value, &end, 10);
72 if (*value && !*end && *value != L
'-')
return (std::min)(seconds, 30ul * 24 * 3600);
73 SYSTEMTIME date = {}; FILETIME file = {};
74 if (!WinHttpTimeToSystemTime(value, &date) || !SystemTimeToFileTime(&date, &file))
return 0;
75 ULARGE_INTEGER ticks; ticks.LowPart = file.dwLowDateTime; ticks.HighPart = file.dwHighDateTime;
76 long long delay =
static_cast<long long>(ticks.QuadPart / 10000000) - 11644473600ll - NowSeconds();
77 return static_cast<unsigned>((std::max)(0ll, (std::min)(delay, 30ll * 24 * 3600)));
79 bool Upload(
const fs::path& path,
const std::wstring& endpoint,
const std::wstring& trace, std::string& status,
unsigned& retryAfter)
81 URL_COMPONENTS
url = {};
url.dwStructSize =
sizeof url;
82 url.dwHostNameLength =
url.dwUrlPathLength =
url.dwExtraInfoLength =
url.dwUserNameLength =
url.dwPasswordLength =
DWORD(-1);
83 if (!WinHttpCrackUrl(endpoint.c_str(), 0, 0, &url)) { status =
"Invalid endpoint";
return false; }
84 std::wstring host(
url.lpszHostName,
url.dwHostNameLength);
86 bool loopback = host == L
"127.0.0.1" || host == L
"localhost" || host == L
"[::1]";
87 if ((
url.nScheme != INTERNET_SCHEME_HTTPS && !(loopback &&
url.nScheme == INTERNET_SCHEME_HTTP))
88 ||
url.dwUserNameLength ||
url.dwPasswordLength ||
url.dwExtraInfoLength) {
89 status =
"Endpoint must be HTTPS without credentials, query or fragment";
return false;
91 File input { CreateFileW(
path.c_str(), GENERIC_READ, FILE_SHARE_READ,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
nullptr) };
93 if (input.h == INVALID_HANDLE_VALUE || !GetFileSizeEx(input.h, &size) || size.QuadPart < 32 || size.QuadPart >
MaxDumpBytes) {
94 status =
"Dump unavailable or exceeds 64 MiB";
return false;
96 std::wstring hash =
Hash(input.h);
97 if (hash.empty()) { status =
"Could not hash dump";
return false; }
98 Http session { WinHttpOpen(L
"RiseCrashHandler/1", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
nullptr,
nullptr, 0) };
99 if (!session.h)
return false;
100 WinHttpSetTimeouts(session.h, 5000, 5000, 15000, 15000);
101 Http connection { WinHttpConnect(session.h, host.c_str(),
url.nPort, 0) };
102 if (!connection.h)
return false;
103 std::wstring
target(
url.lpszUrlPath,
url.dwUrlPathLength);
104 Http request { WinHttpOpenRequest(connection.h, L
"POST",
target.c_str(),
nullptr, WINHTTP_NO_REFERER,
105 WINHTTP_DEFAULT_ACCEPT_TYPES,
url.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0) };
106 if (!request.h)
return false;
107 DWORD redirects = WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
108 WinHttpSetOption(request.h, WINHTTP_OPTION_REDIRECT_POLICY, &redirects,
sizeof redirects);
109 DWORD autologon = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
110 WinHttpSetOption(request.h, WINHTTP_OPTION_AUTOLOGON_POLICY, &autologon,
sizeof autologon);
111 auto id =
path.stem().wstring();
112 std::wstring headers = L
"Content-Type: application/octet-stream\r\nX-Rise-Crash-Id: " +
id
113 + L
"\r\nX-Rise-Dump-SHA256: " + hash + L
"\r\nX-Rise-Trace: " + trace + L
"\r\n";
114 if (!WinHttpSendRequest(request.h, headers.c_str(),
DWORD(-1),
nullptr, 0,
static_cast<DWORD>(size.QuadPart), 0))
return false;
115 std::array<char, 64 * 1024> buffer;
117 ULONGLONG deadline = GetTickCount64() + 60000;
119 if (!ReadFile(input.h, buffer.data(),
static_cast<DWORD>(buffer.size()), &bytes,
nullptr))
return false;
122 if (GetTickCount64() > deadline || !WinHttpWriteData(request.h, buffer.data(), bytes, &written) || written != bytes)
return false;
124 if (!WinHttpReceiveResponse(request.h,
nullptr))
return false;
125 DWORD code = 0, length =
sizeof code;
126 if (!WinHttpQueryHeaders(request.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
nullptr, &code, &length,
nullptr))
return false;
127 status =
"HTTP " + std::to_string(code);
128 retryAfter = RetryAfter(request.h);
129 if ((code != 200 && code != 201) || !Receipt(request.h, L
"X-Rise-Crash-Id",
id) || !Receipt(request.h, L
"X-Rise-Dump-SHA256", hash))
131 status =
"Delivered: ";
for (
wchar_t c : hash) status +=
static_cast<char>(c);
138 wchar_t executable[1024];
139 DWORD count = GetModuleFileNameW(
nullptr, executable, 1024);
140 if (!count || count >= 1024)
return {};
141 auto config = fs::path(executable).parent_path() / L
"CrashHandler.ini";
142 wchar_t endpoint[2048];
143 GetPrivateProfileStringW(L
"CrashReporting", L
"UploadUrl", L
"https://api.risetvp.com/v1/client-crashes", endpoint, 2048, config.c_str());
147 void UploadPending(
const std::wstring& directory,
const std::wstring& endpoint,
bool forceRetry)
149 if (endpoint.empty())
return;
150 unsigned attempted = 0;
151 std::vector<fs::path> pending;
152 for (
const auto& entry : fs::directory_iterator(directory))
153 if (entry.is_regular_file() && entry.path().extension() == L
".dmp" && IsId(entry.path().stem().wstring())) pending.push_back(entry.path());
154 std::sort(pending.begin(), pending.end(), [](
const fs::path& a,
const fs::path& b) { return fs::last_write_time(a) > fs::last_write_time(b); });
155 for (
const auto& path : pending) {
156 auto base = path.parent_path() / path.stem();
157 if (fs::exists(base.wstring() + L
".uploaded"))
continue;
158 File lock { CreateFileW((base.wstring() + L
".lock").c_str(), GENERIC_WRITE, 0,
nullptr, OPEN_ALWAYS,
159 FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
nullptr) };
160 if (lock.h == INVALID_HANDLE_VALUE)
continue;
161 auto attempt = base.wstring() + L
".attempt";
162 long long next = 0;
unsigned failures = 0;
163 std::ifstream(base.wstring() + L
".retry") >> next >> failures;
164 if (!forceRetry && next > NowSeconds())
continue;
165 if (++attempted > 3)
break;
166 std::ifstream metadata(base.wstring() + L
".meta");
167 std::string trace; std::getline(metadata, trace);
168 if (trace.empty() || trace.size() > 128 || trace.find(
"..") != std::string::npos
169 || !isalnum(
static_cast<unsigned char>(trace[0]))
170 || trace.find_first_not_of(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-") != std::string::npos) {
171 Status(attempt,
"Invalid trace metadata; retained locally");
continue;
173 Status(attempt,
"Upload started");
174 failures = (std::min)(failures, 5u);
175 unsigned backoff = (std::min)(1800u << failures, 12u * 3600) +
static_cast<unsigned>(GetTickCount64() % 600);
177 std::ofstream(base.wstring() + L
".retry") << NowSeconds() + backoff <<
' ' << failures + 1;
178 std::string status =
"Transport failure; retained for retry";
179 unsigned retryAfter = 0;
180 bool delivered = Upload(path, endpoint, std::wstring(trace.begin(), trace.end()), status, retryAfter);
182 if (delivered)
Status(base.wstring() + L
".uploaded", status);
183 else if (retryAfter > backoff) std::ofstream(base.wstring() + L
".retry") << NowSeconds() + retryAfter <<
' ' << failures + 1;
189 for (
const auto& entry : fs::directory_iterator(directory)) {
192 if (entry.path().extension() == L
".part" && IsId(entry.path().stem().wstring())
193 && fs::file_time_type::clock::now() - entry.last_write_time() > std::chrono::hours(24 * 30)) {
194 std::error_code ignored; fs::remove(entry.path(), ignored);
continue;
196 if (entry.path().extension() != L
".dmp" || !IsId(entry.path().stem().wstring()))
continue;
197 auto base = entry.path().parent_path() / entry.path().stem();
198 bool uploaded = fs::exists(base.wstring() + L
".uploaded");
199 auto age = fs::file_time_type::clock::now() - entry.last_write_time();
200 if (age < std::chrono::hours(24 * (uploaded ? 7 : 30)))
continue;
201 File lock { CreateFileW((base.wstring() + L
".lock").c_str(), GENERIC_WRITE, 0,
nullptr, OPEN_ALWAYS,
202 FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
nullptr) };
203 if (lock.h == INVALID_HANDLE_VALUE)
continue;
204 for (
auto extension : { L
".dmp", L
".meta", L
".trace.txt", L
".attempt", L
".uploaded", L
".retry" }) {
205 std::error_code ignored; fs::remove(base.wstring() + extension, ignored);
213 if (!GetDiskFreeSpaceExW(directory.c_str(), &free,
nullptr,
nullptr) || free.QuadPart < 128ull * 1024 * 1024)
return false;
214 unsigned long long bytes = 0;
215 for (
const auto& entry : fs::directory_iterator(directory)) {
217 std::error_code error;
218 if (entry.is_regular_file(error)) {
auto size = entry.file_size(error);
if (!error) bytes += size; }
220 return bytes < 512ull * 1024 * 1024;
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
uint32_t Hash(int x, int y, int z, uint32_t salt)
std::wstring UploadEndpoint()
constexpr unsigned long long MaxDumpBytes
void UploadPending(const std::wstring &directory, const std::wstring &endpoint, bool forceRetry)
void MaintainQueue(const std::wstring &directory)
bool HasCaptureSpace(const std::wstring &directory)