whiteoutlib 0.1.2

Read and write Blizzard game assets from Rust: models (MDX, M2, M3), textures (BLP, DDS, PNG, JPEG, BMP, TGA, TIFF, GIF) and archives (CASC, MPQ).
Documentation
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Fernando Sahmkow

#include <whiteout/utils/simple_http_handler.h>

#ifdef _WIN32

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN

#endif
#include <windows.h>
#include <winhttp.h>
#ifdef _MSC_VER
#pragma comment(lib, "winhttp.lib")
#endif
// MinGW/clang-mingw resolve winhttp via CMake target_link_libraries instead.

// WINHTTP_PROTOCOL_FLAG_HTTP2 requires Windows 10 1607 SDK or later.
#ifndef WINHTTP_PROTOCOL_FLAG_HTTP2
#define WINHTTP_PROTOCOL_FLAG_HTTP2 0x1

#endif
#ifndef WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL
#define WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL 133

#endif

#include <atomic>
#include <condition_variable>
#include <deque>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

namespace whiteout::utils {

// ============================================================================
// Helpers
// ============================================================================

/// Parse a URL string into WinHTTP components.
struct ParsedUrl {
    std::wstring host;
    std::wstring path; // includes query string
    INTERNET_PORT port = INTERNET_DEFAULT_HTTPS_PORT;
    bool https = true;
    bool valid = false;
};

static std::wstring toWide(const std::string& s) {
    if (s.empty())
        return {};
    int const len = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0);
    std::wstring w(len, L'\0');
    MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), w.data(), len);
    return w;
}

static ParsedUrl parseUrl(const std::string& url) {
    ParsedUrl out;
    auto wurl = toWide(url);

    URL_COMPONENTS uc{};
    uc.dwStructSize = sizeof(uc);

    wchar_t hostBuf[256]{};
    wchar_t pathBuf[2048]{};
    uc.lpszHostName = hostBuf;
    uc.dwHostNameLength = (DWORD)std::size(hostBuf);
    uc.lpszUrlPath = pathBuf;
    uc.dwUrlPathLength = (DWORD)std::size(pathBuf);

    if (!WinHttpCrackUrl(wurl.c_str(), (DWORD)wurl.size(), 0, &uc))
        return out;

    out.host = hostBuf;
    out.path = pathBuf;
    out.port = uc.nPort;
    out.https = (uc.nScheme == INTERNET_SCHEME_HTTPS);
    out.valid = true;
    return out;
}

// ============================================================================
// Request job
// ============================================================================

struct HttpJob {
    std::string url;
    interfaces::HttpCallback callback;
    bool rangeRequest = false;
    u64 rangeStart = 0;
    u64 rangeEnd = 0;
};

// ============================================================================
// Impl
// ============================================================================

struct SimpleHttpHandler::Impl {
    HINTERNET hSession = nullptr;
    std::vector<std::thread> workers;
    std::deque<HttpJob> queue;
    std::mutex mutex;
    std::condition_variable cv;
    std::atomic<bool> shutdown{false};

    Impl(size_t nThreads) {
        hSession = WinHttpOpen(L"WhiteoutLib/1.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
                               WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
        if (hSession) {
            // Enable HTTP/2 if available (Windows 10 1607+).
            DWORD option = WINHTTP_PROTOCOL_FLAG_HTTP2;
            WinHttpSetOption(hSession, WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL, &option,
                             sizeof(option));

            // Set reasonable timeouts (connect=15s, send=30s, receive=60s).
            WinHttpSetTimeouts(hSession, 0, 15000, 30000, 60000);
        }

        workers.reserve(nThreads);
        for (size_t i = 0; i < nThreads; ++i) {
            workers.emplace_back([this] { workerLoop(); });
        }
    }

    ~Impl() {
        {
            std::lock_guard<std::mutex> const lk(mutex);
            shutdown.store(true, std::memory_order_relaxed);
        }
        cv.notify_all();
        for (auto& t : workers) {
            if (t.joinable())
                t.join();
        }
        if (hSession)
            WinHttpCloseHandle(hSession);
    }

    void enqueue(HttpJob job) {
        {
            std::lock_guard<std::mutex> const lk(mutex);
            queue.push_back(std::move(job));
        }
        cv.notify_one();
    }

    void workerLoop() {
        while (true) {
            HttpJob job;
            {
                std::unique_lock<std::mutex> lk(mutex);
                cv.wait(lk,
                        [&] { return shutdown.load(std::memory_order_relaxed) || !queue.empty(); });
                if (shutdown.load(std::memory_order_relaxed) && queue.empty())
                    return;
                job = std::move(queue.front());
                queue.pop_front();
            }
            executeJob(std::move(job));
        }
    }

    void executeJob(HttpJob job) const {
        interfaces::HttpResponse resp;

        auto parsed = parseUrl(job.url);
        if (!parsed.valid || !hSession) {
            resp.error = "invalid URL or WinHTTP not initialized";
            job.callback(std::move(resp));
            return;
        }

        HINTERNET hConnect = WinHttpConnect(hSession, parsed.host.c_str(), parsed.port, 0);
        if (!hConnect) {
            resp.error = "WinHttpConnect failed (error " + std::to_string(GetLastError()) + ")";
            job.callback(std::move(resp));
            return;
        }

        DWORD const flags = parsed.https ? WINHTTP_FLAG_SECURE : 0;
        HINTERNET hRequest =
            WinHttpOpenRequest(hConnect, L"GET", parsed.path.c_str(), nullptr, WINHTTP_NO_REFERER,
                               WINHTTP_DEFAULT_ACCEPT_TYPES, flags);
        if (!hRequest) {
            resp.error = "WinHttpOpenRequest failed (error " + std::to_string(GetLastError()) + ")";
            WinHttpCloseHandle(hConnect);
            job.callback(std::move(resp));
            return;
        }

        // Enable HTTP/2 on this request.
        DWORD http2 = WINHTTP_PROTOCOL_FLAG_HTTP2;
        WinHttpSetOption(hRequest, WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL, &http2, sizeof(http2));

        // Add Range header if needed.
        if (job.rangeRequest) {
            auto rangeHeader = L"Range: bytes=" + std::to_wstring(job.rangeStart) + L"-" +
                               std::to_wstring(job.rangeEnd);
            WinHttpAddRequestHeaders(hRequest, rangeHeader.c_str(), (DWORD)rangeHeader.size(),
                                     WINHTTP_ADDREQ_FLAG_ADD);
        }

        // Send request.
        if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA,
                                0, 0, 0)) {
            resp.error = "WinHttpSendRequest failed (error " + std::to_string(GetLastError()) + ")";
            WinHttpCloseHandle(hRequest);
            WinHttpCloseHandle(hConnect);
            job.callback(std::move(resp));
            return;
        }

        // Receive response.
        if (!WinHttpReceiveResponse(hRequest, nullptr)) {
            resp.error =
                "WinHttpReceiveResponse failed (error " + std::to_string(GetLastError()) + ")";
            WinHttpCloseHandle(hRequest);
            WinHttpCloseHandle(hConnect);
            job.callback(std::move(resp));
            return;
        }

        // Read status code.
        DWORD statusCode = 0;
        DWORD statusSize = sizeof(statusCode);
        WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
                            WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusSize,
                            WINHTTP_NO_HEADER_INDEX);
        resp.statusCode = static_cast<i32>(statusCode);

        // Read body.
        std::vector<u8> body;
        DWORD bytesAvailable = 0;
        while (WinHttpQueryDataAvailable(hRequest, &bytesAvailable) && bytesAvailable > 0) {
            size_t const prevSize = body.size();
            body.resize(prevSize + bytesAvailable);
            DWORD bytesRead = 0;
            if (!WinHttpReadData(hRequest, body.data() + prevSize, bytesAvailable, &bytesRead)) {
                body.resize(prevSize);
                break;
            }
            body.resize(prevSize + bytesRead);
            if (bytesRead == 0)
                break;
            bytesAvailable = 0;
        }
        resp.body = std::move(body);

        WinHttpCloseHandle(hRequest);
        WinHttpCloseHandle(hConnect);

        job.callback(std::move(resp));
    }
};

// ============================================================================
// Public API
// ============================================================================

SimpleHttpHandler::SimpleHttpHandler(size_t nThreads) : m_impl(std::make_unique<Impl>(nThreads)) {}

SimpleHttpHandler::~SimpleHttpHandler() = default;

u32 SimpleHttpHandler::capabilities() const noexcept {
    return interfaces::HttpCapability::Http2Multiplexing;
}

void SimpleHttpHandler::getAsync(const std::string& url, interfaces::HttpCallback callback) {
    HttpJob job;
    job.url = url;
    job.callback = std::move(callback);
    m_impl->enqueue(std::move(job));
}

void SimpleHttpHandler::getRangeAsync(const std::string& url, u64 start, u64 end,
                                      interfaces::HttpCallback callback) {
    HttpJob job;
    job.url = url;
    job.callback = std::move(callback);
    job.rangeRequest = true;
    job.rangeStart = start;
    job.rangeEnd = end;
    m_impl->enqueue(std::move(job));
}

} // namespace whiteout::utils

#elif defined(WHITEOUT_HAVE_CURL)

// ── libcurl backend (Linux, macOS, BSD, …) ───────────────────────────

#include <curl/curl.h>

#include <atomic>
#include <condition_variable>
#include <cstdlib>
#include <deque>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

namespace whiteout::utils {

namespace {

// Lazily one-shot-init libcurl.  curl_global_init touches process-wide state
// (TLS engine, signal handlers, etc.) and is not safe to call concurrently;
// std::call_once gives us the right barrier.
std::once_flag g_curl_init_flag;
void ensureCurlInit() {
    std::call_once(g_curl_init_flag, [] {
        curl_global_init(CURL_GLOBAL_DEFAULT);
        std::atexit([] { curl_global_cleanup(); });
    });
}

size_t writeCb(char* ptr, size_t size, size_t nmemb, void* userdata) noexcept {
    auto* body = static_cast<std::vector<u8>*>(userdata);
    const size_t total = size * nmemb;
    body->insert(body->end(), reinterpret_cast<u8*>(ptr), reinterpret_cast<u8*>(ptr) + total);
    return total;
}

} // namespace

struct HttpJob {
    std::string url;
    interfaces::HttpCallback callback;
    bool rangeRequest = false;
    u64 rangeStart = 0;
    u64 rangeEnd = 0;
};

struct SimpleHttpHandler::Impl {
    std::vector<std::thread> workers;
    std::deque<HttpJob> queue;
    std::mutex mutex;
    std::condition_variable cv;
    std::atomic<bool> shutdown{false};

    explicit Impl(size_t nThreads) {
        ensureCurlInit();
        workers.reserve(nThreads);
        for (size_t i = 0; i < nThreads; ++i) {
            workers.emplace_back([this] { workerLoop(); });
        }
    }

    ~Impl() {
        {
            std::lock_guard<std::mutex> lk(mutex);
            shutdown.store(true, std::memory_order_relaxed);
        }
        cv.notify_all();
        for (auto& t : workers) {
            if (t.joinable())
                t.join();
        }
    }

    void enqueue(HttpJob job) {
        {
            std::lock_guard<std::mutex> lk(mutex);
            queue.push_back(std::move(job));
        }
        cv.notify_one();
    }

    void workerLoop() {
        // One CURL easy handle per worker — libcurl reuses the connection
        // cache across curl_easy_perform calls on the same handle, so we
        // get keep-alive for free without sharing handles across threads
        // (which is not safe).
        CURL* curl = curl_easy_init();
        if (!curl) {
            // Drain pending jobs with a clear error so callers don't hang.
            while (true) {
                HttpJob job;
                {
                    std::unique_lock<std::mutex> lk(mutex);
                    cv.wait(lk, [&] {
                        return shutdown.load(std::memory_order_relaxed) || !queue.empty();
                    });
                    if (shutdown.load(std::memory_order_relaxed) && queue.empty())
                        return;
                    job = std::move(queue.front());
                    queue.pop_front();
                }
                interfaces::HttpResponse resp;
                resp.error = "libcurl: curl_easy_init failed";
                job.callback(std::move(resp));
            }
        }

        while (true) {
            HttpJob job;
            {
                std::unique_lock<std::mutex> lk(mutex);
                cv.wait(lk,
                        [&] { return shutdown.load(std::memory_order_relaxed) || !queue.empty(); });
                if (shutdown.load(std::memory_order_relaxed) && queue.empty()) {
                    curl_easy_cleanup(curl);
                    return;
                }
                job = std::move(queue.front());
                queue.pop_front();
            }
            executeJob(curl, std::move(job));
        }
    }

    void executeJob(CURL* curl, HttpJob job) {
        interfaces::HttpResponse resp;

        // Wipe per-request options but keep the connection cache.
        curl_easy_reset(curl);

        curl_easy_setopt(curl, CURLOPT_URL, job.url.c_str());
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_USERAGENT, "WhiteoutLib/1.0");
        // NOSIGNAL: libcurl's default DNS resolver uses SIGALRM for timeouts
        // and is not thread-safe under that mode.  Disabling signals forces
        // the threaded resolver path (built in by default on modern libcurl).
        curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, 15000L);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, 60000L);
        curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, static_cast<long>(CURL_HTTP_VERSION_2TLS));
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &writeCb);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resp.body);

        std::string rangeStr;
        if (job.rangeRequest) {
            rangeStr = std::to_string(job.rangeStart) + "-" + std::to_string(job.rangeEnd);
            curl_easy_setopt(curl, CURLOPT_RANGE, rangeStr.c_str());
        }

        const CURLcode rc = curl_easy_perform(curl);
        if (rc != CURLE_OK) {
            resp.body.clear();
            resp.error = std::string("libcurl: ") + curl_easy_strerror(rc);
            job.callback(std::move(resp));
            return;
        }

        long code = 0;
        curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
        resp.statusCode = static_cast<i32>(code);

        job.callback(std::move(resp));
    }
};

SimpleHttpHandler::SimpleHttpHandler(size_t nThreads) : m_impl(std::make_unique<Impl>(nThreads)) {}

SimpleHttpHandler::~SimpleHttpHandler() = default;

u32 SimpleHttpHandler::capabilities() const noexcept {
    // libcurl negotiates HTTP/2 per-connection via CURL_HTTP_VERSION_2TLS;
    // it does not multiplex requests across our worker handles, but the
    // wire-level capability is present.
    return interfaces::HttpCapability::Http2Multiplexing;
}

void SimpleHttpHandler::getAsync(const std::string& url, interfaces::HttpCallback callback) {
    HttpJob job;
    job.url = url;
    job.callback = std::move(callback);
    m_impl->enqueue(std::move(job));
}

void SimpleHttpHandler::getRangeAsync(const std::string& url, u64 start, u64 end,
                                      interfaces::HttpCallback callback) {
    HttpJob job;
    job.url = url;
    job.callback = std::move(callback);
    job.rangeRequest = true;
    job.rangeStart = start;
    job.rangeEnd = end;
    m_impl->enqueue(std::move(job));
}

} // namespace whiteout::utils

#else // !_WIN32 && !WHITEOUT_HAVE_CURL


// ── Stub when no backend is available ────────────────────────────────

namespace whiteout::utils {

struct SimpleHttpHandler::Impl {};

SimpleHttpHandler::SimpleHttpHandler(size_t /*nThreads*/) : m_impl(std::make_unique<Impl>()) {}

SimpleHttpHandler::~SimpleHttpHandler() = default;

u32 SimpleHttpHandler::capabilities() const noexcept {
    return interfaces::HttpCapability::None;
}

void SimpleHttpHandler::getAsync(const std::string& /*url*/, interfaces::HttpCallback callback) {
    interfaces::HttpResponse resp;
    resp.error = "SimpleHttpHandler: no HTTP backend compiled in "
                 "(build with libcurl or provide your own HttpHandler)";
    callback(std::move(resp));
}

void SimpleHttpHandler::getRangeAsync(const std::string& /*url*/, u64 /*start*/, u64 /*end*/,
                                      interfaces::HttpCallback callback) {
    interfaces::HttpResponse resp;
    resp.error = "SimpleHttpHandler: no HTTP backend compiled in "
                 "(build with libcurl or provide your own HttpHandler)";
    callback(std::move(resp));
}

} // namespace whiteout::utils

#endif // backend selection