upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/shims/winhttp_offline.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/shims/winhttp_offline.cpp')
-rw-r--r--runtime/shims/winhttp_offline.cpp385
1 files changed, 385 insertions, 0 deletions
diff --git a/runtime/shims/winhttp_offline.cpp b/runtime/shims/winhttp_offline.cpp
new file mode 100644
index 000000000..1cd7d961f
--- /dev/null
+++ b/runtime/shims/winhttp_offline.cpp
@@ -0,0 +1,385 @@
1// winhttp_offline: WinHTTP for a mapped title, with no network.
2//
3// The package's XCurl.dll and libHttpClient.GDK.dll do their HTTP through WinHTTP: between them they import 16
4// functions from winhttp.dll and nothing from Winsock (docs/runtime_imports.md, "WinHTTP offline"). Bound to the host's
5// winhttp.dll a mapped title could reach the network, and nothing here goes online. So winhttp.dll is a module the
6// shims own (a LoadLibrary of it gets a pseudo-handle, library_loader.cpp) and every function a title can reach is
7// answered in-process:
8// - WinHttpOpen, WinHttpConnect and WinHttpOpenRequest return local handles. WinHttpConnect resolves no name and
9// opens no socket.
10// - WinHttpSendRequest fails with ERROR_WINHTTP_CANNOT_CONNECT. On a session opened with WINHTTP_FLAG_ASYNC it
11// returns TRUE and reports the failure the way WinHTTP does, through the status callback:
12// WINHTTP_CALLBACK_STATUS_REQUEST_ERROR with WINHTTP_ASYNC_RESULT { API_SEND_REQUEST, ERROR_WINHTTP_CANNOT_CONNECT },
13// from a thread-pool thread, with the context the request was sent with.
14// - Reading a response (WinHttpReceiveResponse, WinHttpQueryHeaders, WinHttpQueryDataAvailable, WinHttpReadData) and
15// WinHttpWriteData fail with ERROR_WINHTTP_INCORRECT_HANDLE_STATE: no request ever got that far.
16// - Options, timeouts and request headers are accepted. WINHTTP_OPTION_CONTEXT_VALUE is kept per handle and
17// WINHTTP_OPTION_HANDLE_TYPE answered; WinHttpQueryOption reports ERROR_WINHTTP_INVALID_OPTION for the rest.
18// - A status callback set on a handle is inherited by the handles created under it, as in WinHTTP.
19// WINHTTP_CALLBACK_STATUS_HANDLE_CREATED is reported when a child handle is made, and
20// WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING once per handle, last, after WinHttpCloseHandle and any callback still
21// running for it.
22// - WinHttpCrackUrl only parses a string, so it is the host's.
23// Each refused server is logged once ("[rt] winhttp: offline, refused <host>:<port>"), which says what a title tried
24// to reach. Only images mapped by the loader see these: they are bound through the registry, the runtime's own code
25// calls the host directly.
26#include <windows.h>
27#include <winhttp.h>
28
29#include <atomic>
30#include <cstdio>
31#include <cstring>
32#include <mutex>
33#include <set>
34#include <string>
35
36#include "shims.h"
37
38namespace rt::winhttp {
39namespace {
40
41enum class Kind { Session, Connect, Request };
42
43struct Handle {
44 Kind kind = Kind::Session;
45 Handle* parent = nullptr; // holds one reference on the parent
46 bool async = false;
47 std::atomic<long> refs{1}; // the handle's own reference, dropped by WinHttpCloseHandle
48 std::atomic<bool> closed{false};
49
50 std::mutex mutex; // guards the three below
51 WINHTTP_STATUS_CALLBACK callback = nullptr;
52 DWORD notifications = 0;
53 DWORD_PTR context = 0;
54
55 std::wstring server; // Connect: for the log
56 INTERNET_PORT port = 0;
57};
58
59// Intentionally immortal: a mapped DLL can close handles from DLL_PROCESS_DETACH, after normal statics are gone.
60std::mutex& live_mutex() {
61 static auto* m = new std::mutex;
62 return *m;
63}
64std::set<Handle*>& live() {
65 static auto* s = new std::set<Handle*>;
66 return *s;
67}
68
69HINTERNET to_hinternet(Handle* h) { return reinterpret_cast<HINTERNET>(h); }
70
71// Takes a reference on a live handle of an accepted kind. On failure `error` says why: ERROR_INVALID_HANDLE for
72// something that is not an open handle, ERROR_WINHTTP_INCORRECT_HANDLE_TYPE for the wrong kind.
73Handle* acquire(HINTERNET handle, bool session, bool connect, bool request, DWORD& error) {
74 Handle* h = reinterpret_cast<Handle*>(handle);
75 std::lock_guard lock(live_mutex());
76 if (!handle || live().count(h) == 0) {
77 error = ERROR_INVALID_HANDLE;
78 return nullptr;
79 }
80 const bool ok = (h->kind == Kind::Session && session) || (h->kind == Kind::Connect && connect) ||
81 (h->kind == Kind::Request && request);
82 if (!ok) {
83 error = ERROR_WINHTTP_INCORRECT_HANDLE_TYPE;
84 return nullptr;
85 }
86 h->refs.fetch_add(1);
87 return h;
88}
89
90void notify(Handle* h, DWORD status, void* info, DWORD length) {
91 WINHTTP_STATUS_CALLBACK callback;
92 DWORD notifications;
93 DWORD_PTR context;
94 {
95 std::lock_guard lock(h->mutex);
96 callback = h->callback;
97 notifications = h->notifications;
98 context = h->context;
99 }
100 // The WINHTTP_CALLBACK_FLAG_* bits are the status values they select.
101 if (callback && callback != WINHTTP_INVALID_STATUS_CALLBACK && (notifications & status) != 0)
102 callback(to_hinternet(h), context, status, info, length);
103}
104
105void release(Handle* h) {
106 while (h && h->refs.fetch_sub(1) == 1) {
107 HINTERNET self = to_hinternet(h);
108 notify(h, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING, &self, sizeof(self));
109 Handle* parent = h->parent;
110 delete h;
111 h = parent; // the child's reference on its parent
112 }
113}
114
115HINTERNET make_handle(Kind kind, Handle* parent, bool async) {
116 auto* h = new (std::nothrow) Handle;
117 if (!h) {
118 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
119 return nullptr;
120 }
121 h->kind = kind;
122 h->parent = parent;
123 h->async = async;
124 if (parent) {
125 // A callback set on a handle is inherited by the handles created under it.
126 std::lock_guard lock(parent->mutex);
127 h->callback = parent->callback;
128 h->notifications = parent->notifications;
129 }
130 {
131 std::lock_guard lock(live_mutex());
132 live().insert(h);
133 }
134 if (parent) {
135 HINTERNET self = to_hinternet(h);
136 notify(h, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED, &self, sizeof(self));
137 }
138 return to_hinternet(h);
139}
140
141std::wstring server_of(const Handle* request) {
142 const Handle* connect = request ? request->parent : nullptr;
143 if (!connect) return L"?";
144 return connect->server + L":" + std::to_wstring(connect->port);
145}
146
147void log_refused(const Handle* request) {
148 static auto* logged = new std::set<std::wstring>;
149 static auto* mutex = new std::mutex;
150 const std::wstring server = server_of(request);
151 std::lock_guard lock(*mutex);
152 if (logged->insert(server).second) std::fwprintf(stderr, L"[rt] winhttp: offline, refused %ls\n", server.c_str());
153}
154
155void CALLBACK send_failed(PTP_CALLBACK_INSTANCE, void* context) {
156 Handle* h = static_cast<Handle*>(context);
157 if (!h->closed.load()) {
158 WINHTTP_ASYNC_RESULT result{};
159 result.dwResult = API_SEND_REQUEST;
160 result.dwError = ERROR_WINHTTP_CANNOT_CONNECT;
161 notify(h, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result));
162 }
163 release(h); // the reference WinHttpSendRequest took for this callback
164}
165
166BOOL fail(DWORD error) {
167 SetLastError(error);
168 return FALSE;
169}
170
171} // namespace
172
173HINTERNET WINAPI open_session(LPCWSTR, DWORD, LPCWSTR, LPCWSTR, DWORD flags) {
174 static std::once_flag once;
175 std::call_once(once, [] {
176 std::fprintf(stderr, "[rt] winhttp: offline; requests fail with ERROR_WINHTTP_CANNOT_CONNECT\n");
177 });
178 return make_handle(Kind::Session, nullptr, (flags & WINHTTP_FLAG_ASYNC) != 0);
179}
180
181HINTERNET WINAPI open_connection(HINTERNET session, LPCWSTR server, INTERNET_PORT port, DWORD) {
182 DWORD error = 0;
183 Handle* s = acquire(session, true, false, false, error);
184 if (!s) {
185 SetLastError(error);
186 return nullptr;
187 }
188 if (!server || !*server) {
189 release(s);
190 SetLastError(ERROR_INVALID_PARAMETER);
191 return nullptr;
192 }
193 const HINTERNET h = make_handle(Kind::Connect, s, s->async); // keeps the reference on the session
194 if (!h) {
195 release(s);
196 return nullptr;
197 }
198 auto* c = reinterpret_cast<Handle*>(h);
199 c->server = server;
200 c->port = port;
201 return h;
202}
203
204HINTERNET WINAPI open_request(HINTERNET connection, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR*, DWORD) {
205 DWORD error = 0;
206 Handle* c = acquire(connection, false, true, false, error);
207 if (!c) {
208 SetLastError(error);
209 return nullptr;
210 }
211 const HINTERNET h = make_handle(Kind::Request, c, c->async); // keeps the reference on the connection
212 if (!h) release(c);
213 return h;
214}
215
216BOOL WINAPI send_request(HINTERNET request, LPCWSTR, DWORD, LPVOID, DWORD, DWORD, DWORD_PTR context) {
217 DWORD error = 0;
218 Handle* r = acquire(request, false, false, true, error);
219 if (!r) return fail(error);
220 {
221 std::lock_guard lock(r->mutex);
222 r->context = context; // the context this request's callbacks carry
223 }
224 log_refused(r);
225 if (!r->async) {
226 release(r);
227 return fail(ERROR_WINHTTP_CANNOT_CONNECT);
228 }
229 // Asynchronous: the failure arrives through the callback, never on the calling thread, as with WinHTTP. The
230 // reference taken above is the callback's and is dropped there.
231 if (!TrySubmitThreadpoolCallback(&send_failed, r, nullptr)) {
232 const DWORD submit_error = GetLastError();
233 release(r);
234 return fail(submit_error ? submit_error : ERROR_NOT_ENOUGH_MEMORY);
235 }
236 SetLastError(ERROR_SUCCESS);
237 return TRUE;
238}
239
240// No request was ever sent, so there is no response to read and nothing to write to.
241BOOL WINAPI receive_response(HINTERNET request, LPVOID) {
242 DWORD error = 0;
243 Handle* r = acquire(request, false, false, true, error);
244 if (!r) return fail(error);
245 release(r);
246 return fail(ERROR_WINHTTP_INCORRECT_HANDLE_STATE);
247}
248
249BOOL WINAPI query_data_available(HINTERNET request, LPDWORD) { return receive_response(request, nullptr); }
250BOOL WINAPI read_data(HINTERNET request, LPVOID, DWORD, LPDWORD) { return receive_response(request, nullptr); }
251BOOL WINAPI write_data(HINTERNET request, LPCVOID, DWORD, LPDWORD) { return receive_response(request, nullptr); }
252BOOL WINAPI query_headers(HINTERNET request, DWORD, LPCWSTR, LPVOID, LPDWORD, LPDWORD) {
253 return receive_response(request, nullptr);
254}
255
256BOOL WINAPI add_request_headers(HINTERNET request, LPCWSTR, DWORD, DWORD) {
257 DWORD error = 0;
258 Handle* r = acquire(request, false, false, true, error);
259 if (!r) return fail(error);
260 release(r);
261 return TRUE;
262}
263
264BOOL WINAPI set_timeouts(HINTERNET handle, int, int, int, int) {
265 DWORD error = 0;
266 Handle* h = acquire(handle, true, true, true, error);
267 if (!h) return fail(error);
268 release(h);
269 return TRUE;
270}
271
272BOOL WINAPI set_option(HINTERNET handle, DWORD option, LPVOID buffer, DWORD length) {
273 if (!handle) return TRUE; // process-wide options: accepted, nothing to apply
274 DWORD error = 0;
275 Handle* h = acquire(handle, true, true, true, error);
276 if (!h) return fail(error);
277 if (option == WINHTTP_OPTION_CONTEXT_VALUE) {
278 if (!buffer || length < sizeof(DWORD_PTR)) {
279 release(h);
280 return fail(ERROR_INVALID_PARAMETER);
281 }
282 std::lock_guard lock(h->mutex);
283 h->context = *static_cast<const DWORD_PTR*>(buffer);
284 }
285 release(h);
286 return TRUE;
287}
288
289BOOL WINAPI query_option(HINTERNET handle, DWORD option, LPVOID buffer, LPDWORD length) {
290 if (!length) return fail(ERROR_INVALID_PARAMETER);
291 DWORD error = 0;
292 Handle* h = acquire(handle, true, true, true, error);
293 if (!h) return fail(error);
294 DWORD_PTR value_ptr = 0;
295 DWORD value_dword = 0;
296 const void* value = nullptr;
297 DWORD size = 0;
298 if (option == WINHTTP_OPTION_CONTEXT_VALUE) {
299 std::lock_guard lock(h->mutex);
300 value_ptr = h->context;
301 value = &value_ptr;
302 size = sizeof(value_ptr);
303 } else if (option == WINHTTP_OPTION_HANDLE_TYPE) {
304 value_dword = h->kind == Kind::Session ? WINHTTP_HANDLE_TYPE_SESSION
305 : h->kind == Kind::Connect ? WINHTTP_HANDLE_TYPE_CONNECT
306 : WINHTTP_HANDLE_TYPE_REQUEST;
307 value = &value_dword;
308 size = sizeof(value_dword);
309 }
310 release(h);
311 if (!value) return fail(ERROR_WINHTTP_INVALID_OPTION);
312 if (!buffer || *length < size) {
313 *length = size;
314 return fail(ERROR_INSUFFICIENT_BUFFER);
315 }
316 std::memcpy(buffer, value, size);
317 *length = size;
318 return TRUE;
319}
320
321WINHTTP_STATUS_CALLBACK WINAPI set_status_callback(HINTERNET handle, WINHTTP_STATUS_CALLBACK callback,
322 DWORD notifications, DWORD_PTR) {
323 DWORD error = 0;
324 Handle* h = acquire(handle, true, true, true, error);
325 if (!h) {
326 SetLastError(error);
327 return WINHTTP_INVALID_STATUS_CALLBACK;
328 }
329 WINHTTP_STATUS_CALLBACK previous;
330 {
331 std::lock_guard lock(h->mutex);
332 previous = h->callback;
333 h->callback = callback;
334 h->notifications = callback ? notifications : 0;
335 }
336 release(h);
337 return previous;
338}
339
340BOOL WINAPI close_handle(HINTERNET handle) {
341 Handle* h = reinterpret_cast<Handle*>(handle);
342 {
343 std::lock_guard lock(live_mutex());
344 if (!handle || live().erase(h) == 0) return fail(ERROR_INVALID_HANDLE);
345 }
346 h->closed.store(true);
347 release(h); // the handle's own reference; HANDLE_CLOSING follows when nothing else holds it
348 return TRUE;
349}
350
351BOOL WINAPI crack_url(LPCWSTR url, DWORD length, DWORD flags, LPURL_COMPONENTS components) {
352 // Parsing only: the host's, loaded on first use so the runtime does not depend on winhttp.dll otherwise.
353 using CrackUrlFn = BOOL(WINAPI*)(LPCWSTR, DWORD, DWORD, LPURL_COMPONENTS);
354 static CrackUrlFn host = [] {
355 const HMODULE m = LoadLibraryExW(L"winhttp.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
356 return m ? reinterpret_cast<CrackUrlFn>(GetProcAddress(m, "WinHttpCrackUrl")) : nullptr;
357 }();
358 if (!host) return fail(ERROR_PROC_NOT_FOUND);
359 return host(url, length, flags, components);
360}
361
362} // namespace rt::winhttp
363
364namespace {
365using namespace rt::winhttp;
366} // namespace
367
368SHIM_TABLE(winhttp_offline,
369 {"winhttp.dll", "WinHttpOpen", reinterpret_cast<void*>(&open_session)},
370 {"winhttp.dll", "WinHttpConnect", reinterpret_cast<void*>(&open_connection)},
371 {"winhttp.dll", "WinHttpOpenRequest", reinterpret_cast<void*>(&open_request)},
372 {"winhttp.dll", "WinHttpSendRequest", reinterpret_cast<void*>(&send_request)},
373 {"winhttp.dll", "WinHttpReceiveResponse", reinterpret_cast<void*>(&receive_response)},
374 {"winhttp.dll", "WinHttpQueryDataAvailable", reinterpret_cast<void*>(&query_data_available)},
375 {"winhttp.dll", "WinHttpReadData", reinterpret_cast<void*>(&read_data)},
376 {"winhttp.dll", "WinHttpWriteData", reinterpret_cast<void*>(&write_data)},
377 {"winhttp.dll", "WinHttpQueryHeaders", reinterpret_cast<void*>(&query_headers)},
378 {"winhttp.dll", "WinHttpAddRequestHeaders", reinterpret_cast<void*>(&add_request_headers)},
379 {"winhttp.dll", "WinHttpSetTimeouts", reinterpret_cast<void*>(&set_timeouts)},
380 {"winhttp.dll", "WinHttpSetOption", reinterpret_cast<void*>(&set_option)},
381 {"winhttp.dll", "WinHttpQueryOption", reinterpret_cast<void*>(&query_option)},
382 {"winhttp.dll", "WinHttpSetStatusCallback", reinterpret_cast<void*>(&set_status_callback)},
383 {"winhttp.dll", "WinHttpCloseHandle", reinterpret_cast<void*>(&close_handle)},
384 {"winhttp.dll", "WinHttpCrackUrl", reinterpret_cast<void*>(&crack_url)},
385);