Rise
The Vieneo Province
Loading...
Searching...
No Matches
CrashUpload.cpp
Go to the documentation of this file.
1#include "CrashUpload.h"
2#include "CrashShared.h"
3#include <winhttp.h>
4#include <bcrypt.h>
5#include <filesystem>
6#include <fstream>
7#include <vector>
8#include <array>
9#include <algorithm>
10#pragma comment(lib, "winhttp.lib")
11#pragma comment(lib, "bcrypt.lib")
12
13namespace fs = std::filesystem;
14namespace CrashReporting
15{
16 namespace
17 {
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)
21 {
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;
26 }
27 return true;
28 }
29 void Status(const fs::path& path, const std::string& message)
30 {
31 // Last attempt only; no credentials, response bodies, or growing log.
32 std::ofstream out(path, std::ios::trunc); out << message << '\n';
33 }
34 std::wstring Hash(HANDLE file)
35 {
36 BCRYPT_ALG_HANDLE algorithm = nullptr;
37 BCRYPT_HASH_HANDLE hash = nullptr;
38 if (BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0) return {};
39 std::wstring result;
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;
43 for (;;) {
44 if (!ReadFile(file, buffer.data(), static_cast<DWORD>(buffer.size()), &bytes, nullptr)) { success = false; break; }
45 if (!bytes) break;
46 if (BCryptHashData(hash, buffer.data(), bytes, 0) < 0) { success = false; break; }
47 }
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]; }
52 }
53 BCryptDestroyHash(hash);
54 }
55 BCryptCloseAlgorithmProvider(algorithm, 0);
56 SetFilePointer(file, 0, nullptr, FILE_BEGIN);
57 return result;
58 }
59 bool Receipt(HINTERNET request, const wchar_t* header, const std::wstring& expected)
60 {
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;
64 }
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)
67 {
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)));
78 }
79 bool Upload(const fs::path& path, const std::wstring& endpoint, const std::wstring& trace, std::string& status, unsigned& retryAfter)
80 {
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);
85 // HTTP exists only for an isolated local test server. Never bypass TLS validation.
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;
90 }
91 File input { CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) };
92 LARGE_INTEGER size;
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;
95 }
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;
116 DWORD bytes = 0;
117 ULONGLONG deadline = GetTickCount64() + 60000;
118 for (;;) {
119 if (!ReadFile(input.h, buffer.data(), static_cast<DWORD>(buffer.size()), &bytes, nullptr)) return false;
120 if (!bytes) break;
121 DWORD written = 0;
122 if (GetTickCount64() > deadline || !WinHttpWriteData(request.h, buffer.data(), bytes, &written) || written != bytes) return false;
123 }
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))
130 return false;
131 status = "Delivered: "; for (wchar_t c : hash) status += static_cast<char>(c); // ASCII hex only.
132 return true;
133 }
134 }
135
136 std::wstring UploadEndpoint()
137 {
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());
144 return endpoint; // Blank value disables upload while retaining local capture.
145 }
146
147 void UploadPending(const std::wstring& directory, const std::wstring& endpoint, bool forceRetry)
148 {
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;
172 }
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);
176 // Persist before the request, so interrupted uploads cannot spin on restart.
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);
181 Status(attempt, status);
182 if (delivered) Status(base.wstring() + L".uploaded", status);
183 else if (retryAfter > backoff) std::ofstream(base.wstring() + L".retry") << NowSeconds() + retryAfter << ' ' << failures + 1;
184 }
185 }
186
187 void MaintainQueue(const std::wstring& directory)
188 {
189 for (const auto& entry : fs::directory_iterator(directory)) {
190 // An interrupted helper may leave an unpublished dump. Do not let
191 // old partial files consume the queue forever.
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;
195 }
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);
206 }
207 }
208 }
209
210 bool HasCaptureSpace(const std::wstring& directory)
211 {
212 ULARGE_INTEGER free;
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)) {
216 // The retry worker can remove expired reports concurrently.
217 std::error_code error;
218 if (entry.is_regular_file(error)) { auto size = entry.file_size(error); if (!error) bytes += size; }
219 }
220 return bytes < 512ull * 1024 * 1024;
221 }
222}
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
@ Status
Definition Message.h:10
uint32_t Hash(int x, int y, int z, uint32_t salt)
std::wstring UploadEndpoint()
constexpr unsigned long long MaxDumpBytes
Definition CrashShared.h:8
void UploadPending(const std::wstring &directory, const std::wstring &endpoint, bool forceRetry)
void MaintainQueue(const std::wstring &directory)
bool HasCaptureSpace(const std::wstring &directory)
path
Definition erin.py:153