lu_http source code

The complete source code of the lu_http module (web requests). It is free to read, change and rebuild; a changed copy can be shipped with your own server in Modules/.

Download all files (lu_http-source.zip)

Building

build_linux.sh

13 lines

#!/bin/bash
# Builds lu_http.so (32 bit ELF, libgcc / libstdc++ / OpenSSL linked in statically) inside an Ubuntu 18.04 container, like the server.
# Usage: ./build_linux.sh   (folder holds lu_http.cpp, sqapi.h and squirrel_include/)      Output: ./lu_http.so
set -e
cd "$(dirname "$0")"
docker run --rm -v "$PWD":/src -w /src ubuntu:18.04 bash -ec '
    dpkg --add-architecture i386
    apt-get update -qq
    apt-get install -y -qq --no-install-recommends g++-multilib libssl-dev:i386 >/dev/null
    g++ -m32 -DSQUSEDOUBLE -shared -fPIC -O2 -Wall -fvisibility=hidden -static-libgcc -static-libstdc++ -I squirrel_include lu_http.cpp -o lu_http.so -Wl,--exclude-libs,ALL -Wl,-Bstatic -lssl -lcrypto -Wl,-Bdynamic -ldl -lpthread
'
echo "Done: lu_http.so"

build_win.cmd

9 lines

@echo off
rem Builds lu_http.dll (32 bit, static CRT, WinHTTP) with Visual Studio 2012. Output: ..\..\lu_http.dll
call "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\vcvarsall.bat" x86 >nul
cd /d "%~dp0"
cl /nologo /DSQUSEDOUBLE /O2 /MT /LD /EHsc /W3 /D_CRT_SECURE_NO_WARNINGS /I..\..\..\lu-server\squirrel\include lu_http.cpp /Fe..\..\lu_http.dll /Fo%TEMP%\lu_http.obj /link /SUBSYSTEM:WINDOWS,5.01 winhttp.lib
if exist ..\..\lu_http.exp del ..\..\lu_http.exp
if exist ..\..\lu_http.lib del ..\..\lu_http.lib
echo done %errorlevel%

lu_http.cpp

1333 lines

// lu_http - web requests for LU server scripts (Windows + Linux). LoadModule("lu_http");
//
// Every request runs on a worker thread, the script callback runs on the server's main thread (SQPulse) when the answer is in, so a
// slow web server can never freeze the game server. Windows: WinHTTP (system certificates, proxy settings). Linux: a small HTTP/1.1
// client, HTTPS through a statically linked OpenSSL (system CA bundle; nothing to install on the host).
//
//   fetch(url, callback)
//   fetch(url, method, body, callback)
//   fetch(url, method, body, headers, callback)
//   fetch(url, options, callback)                   options: a table with method / body / headers / timeout / insecure / follow
//   http_get(url, callback)   http_get(url, query, callback)       query: "a=1&b=2" or a table
//   http_post(url, body, callback)                                 body: a string, or a table / array (sent as JSON)
//   GetJson(url, callback)    GetJson(url, query, callback)        callback(data, response): the parsed JSON (null if it failed)
//   PostJson(url, value, callback)
//   ParseJson(text) -> value (throws on invalid JSON)   ToJson(value) -> string
//   UrlEncode(s) UrlDecode(s)  SetHttpTimeout(ms)  SetHttpInsecure(bool)  SetHttpUserAgent(s)  HttpPending()
//
// The callback gets one table: response.ok (2xx), response.status (0 = no answer), response.body, response.error, response.url
// (after redirects), response.time (ms), response.headers (a table, lower case names).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <string>
#include <vector>
#include <deque>

#include "sqapi.h"

#ifdef _WIN32
    #define WIN32_LEAN_AND_MEAN
    #include <windows.h>
    #include <winhttp.h>
    #include <process.h>
    #pragma comment(lib, "winhttp.lib")
    #define LU_EXPORT extern "C" __declspec(dllexport)
    #define LU_SNPRINTF _snprintf
    static unsigned int NowMs() { return (unsigned int)GetTickCount(); }
    struct Mutex { CRITICAL_SECTION cs; Mutex() { InitializeCriticalSection(&cs); } void Lock() { EnterCriticalSection(&cs); } void Unlock() { LeaveCriticalSection(&cs); } };
    struct Sem { HANDLE h; Sem() { h = CreateSemaphoreA(NULL, 0, 0x7fffffff, NULL); } void Post() { ReleaseSemaphore(h, 1, NULL); } void Wait() { WaitForSingleObject(h, INFINITE); } };
    struct ThreadArg { void (*fn)(void*); void* arg; };
    static unsigned __stdcall ThreadMain(void* p) { ThreadArg a = *(ThreadArg*)p; delete (ThreadArg*)p; a.fn(a.arg); return 0; }
    static bool StartThread(void (*fn)(void*), void* arg)
    {
        ThreadArg* a = new ThreadArg; a->fn = fn; a->arg = arg;
        uintptr_t h = _beginthreadex(NULL, 0, ThreadMain, a, 0, NULL);
        if (!h) { delete a; return false; }
        CloseHandle((HANDLE)h);
        return true;
    }
    // the module stays mapped while worker threads can still be inside it (a request that is waiting on the network cannot be cancelled)
    static void PinModule()
    {
        HMODULE h = NULL;
        GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, (LPCSTR)&PinModule, &h);
    }
    #define LU_STRICMP _stricmp
#else
    #include <time.h>
    #include <unistd.h>
    #include <pthread.h>
    #include <semaphore.h>
    #include <signal.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <poll.h>
    #include <netdb.h>
    #include <dlfcn.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netinet/tcp.h>
    #include <arpa/inet.h>
    #include <openssl/ssl.h>
    #include <openssl/err.h>
    #include <openssl/x509v3.h>
    #define LU_EXPORT extern "C" __attribute__((visibility("default")))
    #define LU_SNPRINTF snprintf
    #define LU_STRICMP strcasecmp
    static unsigned int NowMs()
    {
        struct timespec ts;
        clock_gettime(CLOCK_MONOTONIC, &ts);
        return (unsigned int)(ts.tv_sec * 1000u + ts.tv_nsec / 1000000u);
    }
    struct Mutex { pthread_mutex_t m; Mutex() { pthread_mutex_init(&m, NULL); } void Lock() { pthread_mutex_lock(&m); } void Unlock() { pthread_mutex_unlock(&m); } };
    struct Sem { sem_t s; Sem() { sem_init(&s, 0, 0); } void Post() { sem_post(&s); } void Wait() { while (sem_wait(&s) != 0 && errno == EINTR) {} } };
    struct ThreadArg { void (*fn)(void*); void* arg; };
    static void* ThreadMain(void* p) { ThreadArg a = *(ThreadArg*)p; delete (ThreadArg*)p; a.fn(a.arg); return NULL; }
    static bool StartThread(void (*fn)(void*), void* arg)
    {
        ThreadArg* a = new ThreadArg; a->fn = fn; a->arg = arg;
        pthread_t t; pthread_attr_t at;
        pthread_attr_init(&at);
        pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
        int r = pthread_create(&t, &at, ThreadMain, a);
        pthread_attr_destroy(&at);
        if (r != 0) { delete a; return false; }
        return true;
    }
    static void PinModule()
    {
        Dl_info di;
        if (dladdr((void*)&PinModule, &di) && di.dli_fname) dlopen(di.dli_fname, RTLD_NOW | RTLD_NODELETE);
    }
#endif

static SQAPI g_api = NULL;
static HSQUIRRELVM g_vm = NULL;

static int  g_timeoutMs = 15000;
static bool g_insecure = false;
static std::string g_userAgent = "LU-Server-http/1.0";

static const size_t MAX_BODY = 16u * 1024u * 1024u;   // largest answer kept
static const int MAX_QUEUE = 256;
static const int MAX_WORKERS = 4;
static const int MAX_REDIRECTS = 5;

// ------------------------------------------------------------------------------------------------------------------------------
// helpers
// ------------------------------------------------------------------------------------------------------------------------------
static std::string Lower(const std::string& s) { std::string r = s; for (size_t i = 0; i < r.size(); i++) r[i] = (char)tolower((unsigned char)r[i]); return r; }
static std::string Trim(const std::string& s)
{
    size_t a = 0, b = s.size();
    while (a < b && (s[a] == ' ' || s[a] == '\t' || s[a] == '\r' || s[a] == '\n')) a++;
    while (b > a && (s[b - 1] == ' ' || s[b - 1] == '\t' || s[b - 1] == '\r' || s[b - 1] == '\n')) b--;
    return s.substr(a, b - a);
}
static bool StartsWithI(const std::string& s, const char* p) { size_t n = strlen(p); return s.size() >= n && LU_STRICMP(s.substr(0, n).c_str(), p) == 0; }

static std::string UrlEnc(const std::string& s)
{
    static const char* hex = "0123456789ABCDEF";
    std::string o;
    for (size_t i = 0; i < s.size(); i++)
    {
        unsigned char c = (unsigned char)s[i];
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') o += (char)c;
        else { o += '%'; o += hex[c >> 4]; o += hex[c & 15]; }
    }
    return o;
}
static int HexVal(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; }
static std::string UrlDec(const std::string& s)
{
    std::string o;
    for (size_t i = 0; i < s.size(); i++)
    {
        if (s[i] == '%' && i + 2 < s.size() + 0 && HexVal(s[i + 1]) >= 0 && HexVal(s[i + 2]) >= 0) { o += (char)(HexVal(s[i + 1]) * 16 + HexVal(s[i + 2])); i += 2; }
        else if (s[i] == '+') o += ' ';
        else o += s[i];
    }
    return o;
}

// a header value or name must not carry a line break (header injection)
static bool CleanHeader(const std::string& h) { return h.find('\r') == std::string::npos && h.find('\n') == std::string::npos && h.find(':') != std::string::npos && h.find(':') > 0; }

// ------------------------------------------------------------------------------------------------------------------------------
// squirrel argument helpers
// ------------------------------------------------------------------------------------------------------------------------------
static int AbsIdx(HSQUIRRELVM v, int idx) { return idx < 0 ? (int)g_api->gettop(v) + idx + 1 : idx; }
static bool IsFn(HSQUIRRELVM v, int idx) { SQObjectType t = g_api->gettype(v, idx); return t == OT_CLOSURE || t == OT_NATIVECLOSURE; }
static bool GetStr(HSQUIRRELVM v, int idx, std::string& out)
{
    if (g_api->gettype(v, idx) != OT_STRING) return false;
    const SQChar* s = NULL;
    if (SQ_FAILED(g_api->getstring(v, idx, &s)) || !s) return false;
    out.assign(s, (size_t)g_api->getsize(v, idx));
    return true;
}
static void PushStr(HSQUIRRELVM v, const std::string& s) { g_api->pushstring(v, s.c_str(), (SQInteger)s.size()); }
static void SetSlotStr(HSQUIRRELVM v, const char* name, const std::string& val) { g_api->pushstring(v, name, -1); PushStr(v, val); g_api->rawset(v, -3); }
static void SetSlotInt(HSQUIRRELVM v, const char* name, int val) { g_api->pushstring(v, name, -1); g_api->pushinteger(v, val); g_api->rawset(v, -3); }
static void SetSlotBool(HSQUIRRELVM v, const char* name, bool val) { g_api->pushstring(v, name, -1); g_api->pushbool(v, val ? SQTrue : SQFalse); g_api->rawset(v, -3); }

// ------------------------------------------------------------------------------------------------------------------------------
// JSON <-> squirrel values
// ------------------------------------------------------------------------------------------------------------------------------
static void AppendUtf8(std::string& o, unsigned cp)
{
    if (cp < 0x80) o += (char)cp;
    else if (cp < 0x800) { o += (char)(0xC0 | (cp >> 6)); o += (char)(0x80 | (cp & 0x3F)); }
    else if (cp < 0x10000) { o += (char)(0xE0 | (cp >> 12)); o += (char)(0x80 | ((cp >> 6) & 0x3F)); o += (char)(0x80 | (cp & 0x3F)); }
    else { o += (char)(0xF0 | (cp >> 18)); o += (char)(0x80 | ((cp >> 12) & 0x3F)); o += (char)(0x80 | ((cp >> 6) & 0x3F)); o += (char)(0x80 | (cp & 0x3F)); }
}

struct JsonParser
{
    const char* p; const char* end; HSQUIRRELVM v; std::string err;
    void Ws() { while (p < end && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')) p++; }
    bool Fail(const char* m) { if (err.empty()) { char b[128]; LU_SNPRINTF(b, sizeof(b), "%s", m); err = b; } return false; }
    bool Hex4(unsigned& o)
    {
        if (end - p < 4) return false;
        o = 0;
        for (int i = 0; i < 4; i++) { int h = HexVal(p[i]); if (h < 0) return false; o = o * 16 + (unsigned)h; }
        p += 4;
        return true;
    }
    bool Str(std::string& o)
    {
        // p is just behind the opening quote
        for (;;)
        {
            if (p >= end) return Fail("unterminated string");
            unsigned char c = (unsigned char)*p++;
            if (c == '"') return true;
            if (c == '\\')
            {
                if (p >= end) return Fail("bad escape");
                char e = *p++;
                switch (e)
                {
                case '"': o += '"'; break; case '\\': o += '\\'; break; case '/': o += '/'; break;
                case 'b': o += '\b'; break; case 'f': o += '\f'; break; case 'n': o += '\n'; break; case 'r': o += '\r'; break; case 't': o += '\t'; break;
                case 'u':
                {
                    unsigned cp;
                    if (!Hex4(cp)) return Fail("bad \\u escape");
                    if (cp >= 0xD800 && cp < 0xDC00 && end - p >= 6 && p[0] == '\\' && p[1] == 'u')
                    {
                        const char* save = p; p += 2;
                        unsigned lo;
                        if (Hex4(lo) && lo >= 0xDC00 && lo < 0xE000) cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
                        else p = save;
                    }
                    AppendUtf8(o, cp);
                    break;
                }
                default: return Fail("bad escape");
                }
            }
            else o += (char)c;
        }
    }
    bool Value(int depth)
    {
        if (depth > 64) return Fail("nested too deep");
        Ws();
        if (p >= end) return Fail("unexpected end");
        char c = *p;
        if (c == '{')
        {
            p++;
            g_api->newtable(v);
            Ws();
            if (p < end && *p == '}') { p++; return true; }
            for (;;)
            {
                Ws();
                if (p >= end || *p != '"') return Fail("object key expected");
                p++;
                std::string k;
                if (!Str(k)) return false;
                Ws();
                if (p >= end || *p != ':') return Fail("':' expected");
                p++;
                PushStr(v, k);
                if (!Value(depth + 1)) return false;
                g_api->rawset(v, -3);
                Ws();
                if (p < end && *p == ',') { p++; continue; }
                if (p < end && *p == '}') { p++; return true; }
                return Fail("',' or '}' expected");
            }
        }
        if (c == '[')
        {
            p++;
            g_api->newarray(v, 0);
            Ws();
            if (p < end && *p == ']') { p++; return true; }
            for (;;)
            {
                if (!Value(depth + 1)) return false;
                g_api->arrayappend(v, -2);
                Ws();
                if (p < end && *p == ',') { p++; continue; }
                if (p < end && *p == ']') { p++; return true; }
                return Fail("',' or ']' expected");
            }
        }
        if (c == '"') { p++; std::string s; if (!Str(s)) return false; PushStr(v, s); return true; }
        if (end - p >= 4 && strncmp(p, "true", 4) == 0) { p += 4; g_api->pushbool(v, SQTrue); return true; }
        if (end - p >= 5 && strncmp(p, "false", 5) == 0) { p += 5; g_api->pushbool(v, SQFalse); return true; }
        if (end - p >= 4 && strncmp(p, "null", 4) == 0) { p += 4; g_api->pushnull(v); return true; }
        if (c == '-' || (c >= '0' && c <= '9'))
        {
            const char* b = p;
            bool isFloat = false;
            if (*p == '-') p++;
            while (p < end && ((*p >= '0' && *p <= '9') || *p == '.' || *p == 'e' || *p == 'E' || *p == '+' || *p == '-')) { if (*p == '.' || *p == 'e' || *p == 'E') isFloat = true; p++; }
            std::string num(b, (size_t)(p - b));
            if (!isFloat && num.size() < 11)
            {
                long long n = _strtoi64_compat(num.c_str());
                if (n >= -2147483647LL && n <= 2147483647LL) { g_api->pushinteger(v, (SQInteger)n); return true; }
            }
            g_api->pushdouble(v, strtod(num.c_str(), NULL));
            return true;
        }
        return Fail("unexpected character");
    }
    static long long _strtoi64_compat(const char* s)
    {
        bool neg = false; long long n = 0;
        if (*s == '-') { neg = true; s++; }
        while (*s >= '0' && *s <= '9') { n = n * 10 + (*s - '0'); s++; }
        return neg ? -n : n;
    }
};

// parses text and leaves the value on the stack; false (nothing left on the stack) with err set on failure
static bool JsonParse(HSQUIRRELVM v, const std::string& text, std::string& err)
{
    SQInteger top = g_api->gettop(v);
    g_api->reservestack(v, 400);
    JsonParser jp; jp.p = text.c_str(); jp.end = text.c_str() + text.size(); jp.v = v;
    bool ok = jp.Value(0);
    if (ok) { jp.Ws(); if (jp.p != jp.end) { jp.Fail("trailing characters"); ok = false; } }
    if (!ok)
    {
        g_api->settop(v, top);
        char b[200]; LU_SNPRINTF(b, sizeof(b), "invalid JSON at offset %d: %s", (int)(jp.p - text.c_str()), jp.err.c_str());
        err = b;
        return false;
    }
    return true;
}

static void JsonStr(std::string& o, const std::string& s)
{
    o += '"';
    for (size_t i = 0; i < s.size(); i++)
    {
        unsigned char c = (unsigned char)s[i];
        switch (c)
        {
        case '"': o += "\\\""; break; case '\\': o += "\\\\"; break;
        case '\n': o += "\\n"; break; case '\r': o += "\\r"; break; case '\t': o += "\\t"; break; case '\b': o += "\\b"; break; case '\f': o += "\\f"; break;
        default:
            if (c < 0x20) { char b[8]; LU_SNPRINTF(b, sizeof(b), "\\u%04x", c); o += b; }
            else o += (char)c;
        }
    }
    o += '"';
}

static void JsonOut(HSQUIRRELVM v, int idx, std::string& o, int depth)
{
    idx = AbsIdx(v, idx);
    SQObjectType t = g_api->gettype(v, idx);
    if (depth > 64) { o += "null"; return; }
    switch (t)
    {
    case OT_NULL: o += "null"; return;
    case OT_BOOL: { SQBool b = SQFalse; g_api->getbool(v, idx, &b); o += b ? "true" : "false"; return; }
    case OT_INTEGER: { SQInteger n = 0; g_api->getinteger(v, idx, &n); char b[24]; LU_SNPRINTF(b, sizeof(b), "%d", (int)n); o += b; return; }
    case OT_FLOAT:
    {
        double f = 0; g_api->getdouble(v, idx, &f);
        if (f != f || f > 1e300 || f < -1e300) { o += "null"; return; }
        char b[40]; LU_SNPRINTF(b, sizeof(b), "%.9g", (double)f); o += b; return;
    }
    case OT_STRING: { std::string s; GetStr(v, idx, s); JsonStr(o, s); return; }
    case OT_ARRAY:
    {
        o += '[';
        g_api->pushnull(v);
        bool first = true;
        while (SQ_SUCCEEDED(g_api->next(v, idx)))
        {
            if (!first) o += ',';
            first = false;
            JsonOut(v, -1, o, depth + 1);
            g_api->pop(v, 2);
        }
        g_api->pop(v, 1);
        o += ']';
        return;
    }
    case OT_TABLE:
    {
        o += '{';
        g_api->pushnull(v);
        bool first = true;
        while (SQ_SUCCEEDED(g_api->next(v, idx)))
        {
            if (!first) o += ',';
            first = false;
            std::string k;
            if (!GetStr(v, -2, k)) { g_api->tostring(v, -2); GetStr(v, -1, k); g_api->pop(v, 1); }
            JsonStr(o, k);
            o += ':';
            JsonOut(v, -1, o, depth + 1);
            g_api->pop(v, 2);
        }
        g_api->pop(v, 1);
        o += '}';
        return;
    }
    default:
    {
        // anything else (instances, closures...): its string form
        g_api->tostring(v, idx);
        std::string s; GetStr(v, -1, s); g_api->pop(v, 1);
        JsonStr(o, s);
        return;
    }
    }
}

// ------------------------------------------------------------------------------------------------------------------------------
// the request / answer
// ------------------------------------------------------------------------------------------------------------------------------
struct Job
{
    std::string method, url, body;
    std::vector<std::string> hdrs;       // "Name: value"
    int timeoutMs; bool insecure; bool follow; int kind;   // kind 0 = plain callback(response), 1 = callback(data, response)
    HSQOBJECT cb;
    // answer
    bool ok; int status; std::string rbody, rheaders, error, finalUrl; unsigned elapsed;
    Job() : timeoutMs(15000), insecure(false), follow(true), kind(0), ok(false), status(0), elapsed(0) { memset(&cb, 0, sizeof(cb)); }
};

static bool HasHeader(const std::vector<std::string>& h, const char* name)
{
    size_t n = strlen(name);
    for (size_t i = 0; i < h.size(); i++)
        if (h[i].size() > n && h[i][n] == ':' && LU_STRICMP(h[i].substr(0, n).c_str(), name) == 0) return true;
    return false;
}

struct Url { bool tls; std::string host, path; int port; };
static bool ParseUrl(const std::string& u0, Url& o)
{
    std::string u = u0;
    size_t sp;
    while ((sp = u.find(' ')) != std::string::npos) u.replace(sp, 1, "%20");
    size_t h = u.find('#'); if (h != std::string::npos) u.erase(h);
    size_t pos;
    if (StartsWithI(u, "https://")) { o.tls = true; pos = 8; o.port = 443; }
    else if (StartsWithI(u, "http://")) { o.tls = false; pos = 7; o.port = 80; }
    else return false;
    size_t e = u.find_first_of("/?", pos);
    std::string auth = u.substr(pos, e == std::string::npos ? std::string::npos : e - pos);
    o.path = e == std::string::npos ? "/" : u.substr(e);
    if (o.path[0] == '?') o.path = "/" + o.path;
    size_t at = auth.rfind('@'); if (at != std::string::npos) auth.erase(0, at + 1);
    if (!auth.empty() && auth[0] == '[')
    {
        size_t rb = auth.find(']');
        if (rb == std::string::npos) return false;
        o.host = auth.substr(1, rb - 1);
        if (rb + 1 < auth.size() && auth[rb + 1] == ':') o.port = atoi(auth.c_str() + rb + 2);
    }
    else
    {
        size_t c = auth.rfind(':');
        if (c != std::string::npos) { o.host = auth.substr(0, c); o.port = atoi(auth.c_str() + c + 1); }
        else o.host = auth;
    }
    return !o.host.empty() && o.port > 0 && o.port < 65536;
}

// "Name: value" lines -> value of one header (empty if missing)
static std::string HeaderValue(const std::string& raw, const char* name)
{
    std::string want = Lower(name);
    size_t i = 0;
    while (i < raw.size())
    {
        size_t e = raw.find('\n', i);
        std::string line = raw.substr(i, e == std::string::npos ? std::string::npos : e - i);
        i = e == std::string::npos ? raw.size() : e + 1;
        size_t c = line.find(':');
        if (c == std::string::npos) continue;
        if (Lower(Trim(line.substr(0, c))) == want) return Trim(line.substr(c + 1));
    }
    return "";
}

#ifdef _WIN32
// ------------------------------------------------------------------------------------------------------------------------------
// Windows: WinHTTP
// ------------------------------------------------------------------------------------------------------------------------------
#ifndef WINHTTP_OPTION_SECURE_PROTOCOLS
#define WINHTTP_OPTION_SECURE_PROTOCOLS 84
#endif
static std::wstring W(const std::string& s)
{
    if (s.empty()) return std::wstring();
    int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), NULL, 0);
    std::wstring w((size_t)n, L'\0');
    MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), &w[0], n);
    return w;
}
static std::string FromW(const wchar_t* w, int len)
{
    if (len <= 0) return std::string();
    int n = WideCharToMultiByte(CP_UTF8, 0, w, len, NULL, 0, NULL, NULL);
    std::string s((size_t)n, '\0');
    WideCharToMultiByte(CP_UTF8, 0, w, len, &s[0], n, NULL, NULL);
    return s;
}
static std::string WinErr(DWORD e)
{
    switch (e)
    {
    case ERROR_WINHTTP_TIMEOUT: return "timeout";
    case ERROR_WINHTTP_NAME_NOT_RESOLVED: return "could not resolve the host name";
    case ERROR_WINHTTP_CANNOT_CONNECT: return "could not connect";
    case ERROR_WINHTTP_CONNECTION_ERROR: return "connection error";
    case ERROR_WINHTTP_SECURE_FAILURE: return "TLS / certificate error (SetHttpInsecure(true) skips certificate checks)";
    case ERROR_WINHTTP_INVALID_URL: return "invalid url";
    case ERROR_WINHTTP_UNRECOGNIZED_SCHEME: return "unsupported url scheme";
    case ERROR_WINHTTP_REDIRECT_FAILED: return "redirect failed";
    }
    char b[64]; LU_SNPRINTF(b, sizeof(b), "network error %lu", (unsigned long)e);
    return b;
}

static void Perform(Job* j)
{
    unsigned t0 = NowMs();
    HINTERNET ses = NULL, con = NULL, req = NULL;
    j->finalUrl = j->url;
    do
    {
        Url u;
        if (!ParseUrl(j->url, u)) { j->error = "invalid url (only http:// and https:// are supported)"; break; }
        ses = WinHttpOpen(W(g_userAgent).c_str(), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
        if (!ses) { j->error = WinErr(GetLastError()); break; }
        DWORD sp = 0x2A80;      // TLS 1.0 | 1.1 | 1.2 | 1.3 (older systems refuse the unknown bit: then without it)
        if (!WinHttpSetOption(ses, WINHTTP_OPTION_SECURE_PROTOCOLS, &sp, sizeof(sp))) { sp = 0x0A80; WinHttpSetOption(ses, WINHTTP_OPTION_SECURE_PROTOCOLS, &sp, sizeof(sp)); }
        int to = j->timeoutMs;
        WinHttpSetTimeouts(ses, to, to, to, to);
        std::wstring whost = W(u.host);
        con = WinHttpConnect(ses, whost.c_str(), (INTERNET_PORT)u.port, 0);
        if (!con) { j->error = WinErr(GetLastError()); break; }
        req = WinHttpOpenRequest(con, W(j->method).c_str(), W(u.path).c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, u.tls ? WINHTTP_FLAG_SECURE : 0);
        if (!req) { j->error = WinErr(GetLastError()); break; }
        if (j->insecure)
        {
            DWORD f = SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE;
            WinHttpSetOption(req, WINHTTP_OPTION_SECURITY_FLAGS, &f, sizeof(f));
        }
        if (!j->follow) { DWORD d = WINHTTP_DISABLE_REDIRECTS; WinHttpSetOption(req, WINHTTP_OPTION_DISABLE_FEATURE, &d, sizeof(d)); }
        std::string hs;
        for (size_t i = 0; i < j->hdrs.size(); i++) hs += j->hdrs[i] + "\r\n";
        if (!HasHeader(j->hdrs, "Accept")) hs += "Accept: */*\r\n";
        std::wstring wh = W(hs);
        if (!wh.empty()) WinHttpAddRequestHeaders(req, wh.c_str(), (DWORD)-1, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE);
        DWORD blen = (DWORD)j->body.size();
        if (!WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, blen ? (LPVOID)j->body.data() : WINHTTP_NO_REQUEST_DATA, blen, blen, 0)) { j->error = WinErr(GetLastError()); break; }
        if (!WinHttpReceiveResponse(req, NULL)) { j->error = WinErr(GetLastError()); break; }
        DWORD st = 0, sz = sizeof(st);
        WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &st, &sz, WINHTTP_NO_HEADER_INDEX);
        j->status = (int)st;
        DWORD hl = 0;
        WinHttpQueryHeaders(req, WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, WINHTTP_NO_OUTPUT_BUFFER, &hl, WINHTTP_NO_HEADER_INDEX);
        if (hl > 0)
        {
            std::vector<wchar_t> hb(hl / sizeof(wchar_t) + 2);
            if (WinHttpQueryHeaders(req, WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, &hb[0], &hl, WINHTTP_NO_HEADER_INDEX))
                j->rheaders = FromW(&hb[0], (int)(hl / sizeof(wchar_t)));
        }
        DWORD ul = 0;
        WinHttpQueryOption(req, WINHTTP_OPTION_URL, NULL, &ul);
        if (ul > 0) { std::vector<wchar_t> ub(ul / sizeof(wchar_t) + 2); if (WinHttpQueryOption(req, WINHTTP_OPTION_URL, &ub[0], &ul)) j->finalUrl = FromW(&ub[0], (int)(ul / sizeof(wchar_t))); }
        bool bad = false;
        for (;;)
        {
            DWORD avail = 0;
            if (!WinHttpQueryDataAvailable(req, &avail)) { j->error = WinErr(GetLastError()); bad = true; break; }
            if (avail == 0) break;
            if (j->rbody.size() + avail > MAX_BODY) { j->error = "the answer is larger than 16 MB"; bad = true; break; }
            size_t at = j->rbody.size();
            j->rbody.resize(at + avail);
            DWORD got = 0;
            if (!WinHttpReadData(req, &j->rbody[at], avail, &got)) { j->error = WinErr(GetLastError()); bad = true; break; }
            j->rbody.resize(at + got);
            if (got == 0) break;
        }
        if (bad) { j->status = j->status; break; }
        j->ok = (j->status >= 200 && j->status < 300);
    } while (0);
    if (req) WinHttpCloseHandle(req);
    if (con) WinHttpCloseHandle(con);
    if (ses) WinHttpCloseHandle(ses);
    j->elapsed = NowMs() - t0;
}

#else
// ------------------------------------------------------------------------------------------------------------------------------
// Linux: sockets + OpenSSL
// ------------------------------------------------------------------------------------------------------------------------------
static Mutex g_tlsLock;
static SSL_CTX* g_sslCtx = NULL;
static bool g_sslFailed = false;
static std::string g_sslErr;

static SSL_CTX* GetSslCtx(std::string& err)
{
    g_tlsLock.Lock();
    if (!g_sslCtx && !g_sslFailed)
    {
        OPENSSL_init_ssl(0, NULL);
        SSL_CTX* c = SSL_CTX_new(TLS_client_method());
        if (!c) { g_sslFailed = true; g_sslErr = "TLS init failed"; }
        else
        {
            SSL_CTX_set_min_proto_version(c, TLS1_VERSION);
            SSL_CTX_set_mode(c, SSL_MODE_AUTO_RETRY);
            static const char* bundles[] = { "/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", "/etc/ssl/ca-bundle.pem", "/etc/ssl/cert.pem", "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", NULL };
            bool loaded = false;
            for (int i = 0; bundles[i] && !loaded; i++) if (SSL_CTX_load_verify_locations(c, bundles[i], NULL) == 1) loaded = true;
            if (!loaded) loaded = SSL_CTX_set_default_verify_paths(c) == 1;
            g_sslCtx = c;
            if (!loaded) g_sslErr = "no CA certificate bundle found on this host (install ca-certificates, or SetHttpInsecure(true))";
        }
    }
    SSL_CTX* r = g_sslCtx;
    if (!r) err = g_sslErr;
    g_tlsLock.Unlock();
    return r;
}

struct Conn
{
    int fd; SSL* ssl;
    Conn() : fd(-1), ssl(NULL) {}
    void Close() { if (ssl) { SSL_shutdown(ssl); SSL_free(ssl); ssl = NULL; } if (fd >= 0) { close(fd); fd = -1; } }
};

static int Remaining(unsigned deadline) { int r = (int)(deadline - NowMs()); return r; }

static bool Connect(const Url& u, unsigned deadline, Conn& c, std::string& err)
{
    char port[16]; LU_SNPRINTF(port, sizeof(port), "%d", u.port);
    struct addrinfo hints, *res = NULL;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM;
    int gr = getaddrinfo(u.host.c_str(), port, &hints, &res);
    if (gr != 0 || !res) { err = "could not resolve the host name"; return false; }
    bool timedOut = false;
    for (struct addrinfo* ai = res; ai; ai = ai->ai_next)
    {
        int fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
        if (fd < 0) continue;
        int fl = fcntl(fd, F_GETFL, 0);
        fcntl(fd, F_SETFL, fl | O_NONBLOCK);
        int r = connect(fd, ai->ai_addr, ai->ai_addrlen);
        bool ok = (r == 0);
        if (r < 0 && errno == EINPROGRESS)
        {
            int left = Remaining(deadline);
            struct pollfd pf; pf.fd = fd; pf.events = POLLOUT; pf.revents = 0;
            int pr = left > 0 ? poll(&pf, 1, left) : 0;
            if (pr > 0) { int se = 0; socklen_t sl = sizeof(se); getsockopt(fd, SOL_SOCKET, SO_ERROR, &se, &sl); ok = (se == 0); }
            else if (pr == 0) timedOut = true;
        }
        if (!ok) { close(fd); continue; }
        fcntl(fd, F_SETFL, fl);
        int one = 1; setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
        c.fd = fd;
        freeaddrinfo(res);
        return true;
    }
    freeaddrinfo(res);
    err = timedOut ? "connect timeout" : "could not connect";
    return false;
}

static void SetIoTimeout(Conn& c, unsigned deadline)
{
    int left = Remaining(deadline);
    if (left < 1) left = 1;
    struct timeval tv; tv.tv_sec = left / 1000; tv.tv_usec = (left % 1000) * 1000;
    setsockopt(c.fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
    setsockopt(c.fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
}

static bool TlsStart(const Url& u, bool insecure, Conn& c, std::string& err)
{
    SSL_CTX* ctx = GetSslCtx(err);
    if (!ctx) return false;
    c.ssl = SSL_new(ctx);
    if (!c.ssl) { err = "TLS init failed"; return false; }
    SSL_set_fd(c.ssl, c.fd);
    struct in_addr a4; struct in6_addr a6;
    bool isIp = inet_pton(AF_INET, u.host.c_str(), &a4) == 1 || inet_pton(AF_INET6, u.host.c_str(), &a6) == 1;
    if (!isIp) { SSL_set_tlsext_host_name(c.ssl, u.host.c_str()); }
    if (insecure) SSL_set_verify(c.ssl, SSL_VERIFY_NONE, NULL);
    else
    {
        SSL_set_verify(c.ssl, SSL_VERIFY_PEER, NULL);
        if (isIp) X509_VERIFY_PARAM_set1_ip_asc(SSL_get0_param(c.ssl), u.host.c_str());
        else SSL_set1_host(c.ssl, u.host.c_str());
    }
    int r = SSL_connect(c.ssl);
    if (r != 1)
    {
        long vr = SSL_get_verify_result(c.ssl);
        if (!insecure && vr != X509_V_OK) { err = std::string("TLS certificate error: ") + X509_verify_cert_error_string(vr) + " (SetHttpInsecure(true) skips certificate checks)"; }
        else
        {
            int se = SSL_get_error(c.ssl, r);
            err = (se == SSL_ERROR_SYSCALL && (errno == EAGAIN || errno == EWOULDBLOCK)) ? "timeout" : "TLS handshake failed";
        }
        ERR_clear_error();
        return false;
    }
    return true;
}

static int ConnWrite(Conn& c, const char* d, int n)
{
    if (c.ssl) return SSL_write(c.ssl, d, n);
    return (int)send(c.fd, d, n, MSG_NOSIGNAL);
}
static int ConnRead(Conn& c, char* d, int n, bool* timedOut)
{
    int r;
    if (c.ssl)
    {
        r = SSL_read(c.ssl, d, n);
        if (r <= 0)
        {
            int se = SSL_get_error(c.ssl, r);
            if (se == SSL_ERROR_SYSCALL && r < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) *timedOut = true;
            ERR_clear_error();
            return r <= 0 ? -1 : r;
        }
        return r;
    }
    r = (int)recv(c.fd, d, n, 0);
    if (r < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) *timedOut = true;
    return r;
}

static bool SendAll(Conn& c, const std::string& s)
{
    size_t off = 0;
    while (off < s.size())
    {
        int r = ConnWrite(c, s.data() + off, (int)(s.size() - off));
        if (r <= 0) return false;
        off += (size_t)r;
    }
    return true;
}

// reads more into buf; false at the end of the stream / on error (timedOut set when it was the timeout)
static bool More(Conn& c, std::string& buf, unsigned deadline, bool* timedOut)
{
    if (Remaining(deadline) <= 0) { *timedOut = true; return false; }
    SetIoTimeout(c, deadline);
    char tmp[16384];
    int r = ConnRead(c, tmp, sizeof(tmp), timedOut);
    if (r <= 0) return false;
    buf.append(tmp, (size_t)r);
    return true;
}

// one request / answer on a fresh connection (Connection: close). Returns false with err set when there is no usable answer.
static bool Exchange(Job* j, const std::string& method, const Url& u, const std::string& body, const std::vector<std::string>& hdrs, unsigned deadline, int& status, std::string& rheaders, std::string& rbody, std::string& err)
{
    Conn c;
    if (!Connect(u, deadline, c, err)) return false;
    SetIoTimeout(c, deadline);
    if (u.tls && !TlsStart(u, j->insecure, c, err)) { c.Close(); return false; }
    std::string hostHdr = u.host.find(':') != std::string::npos ? "[" + u.host + "]" : u.host;
    if ((u.tls && u.port != 443) || (!u.tls && u.port != 80)) { char pb[16]; LU_SNPRINTF(pb, sizeof(pb), ":%d", u.port); hostHdr += pb; }
    std::string rq = method + " " + u.path + " HTTP/1.1\r\nHost: " + hostHdr + "\r\nConnection: close\r\n";
    if (!HasHeader(hdrs, "User-Agent")) rq += "User-Agent: " + g_userAgent + "\r\n";
    if (!HasHeader(hdrs, "Accept")) rq += "Accept: */*\r\n";
    if (!HasHeader(hdrs, "Accept-Encoding")) rq += "Accept-Encoding: identity\r\n";
    for (size_t i = 0; i < hdrs.size(); i++) { std::string l = Lower(hdrs[i]); if (l.compare(0, 5, "host:") == 0 || l.compare(0, 11, "connection:") == 0 || l.compare(0, 15, "content-length:") == 0) continue; rq += hdrs[i] + "\r\n"; }
    if (!body.empty() || method == "POST" || method == "PUT" || method == "PATCH") { char b[48]; LU_SNPRINTF(b, sizeof(b), "Content-Length: %u\r\n", (unsigned)body.size()); rq += b; }
    rq += "\r\n";
    rq += body;
    if (!SendAll(c, rq)) { err = "could not send the request"; c.Close(); return false; }

    std::string buf;
    bool timedOut = false;
    size_t he;
    while ((he = buf.find("\r\n\r\n")) == std::string::npos)
    {
        if (buf.size() > 262144) { err = "bad answer (headers too large)"; c.Close(); return false; }
        if (!More(c, buf, deadline, &timedOut)) { err = timedOut ? "timeout" : "the server closed the connection without an answer"; c.Close(); return false; }
    }
    std::string head = buf.substr(0, he);
    std::string rest = buf.substr(he + 4);
    size_t le = head.find("\r\n");
    std::string statusLine = head.substr(0, le);
    rheaders = le == std::string::npos ? "" : head.substr(le + 2);
    int major = 0, minor = 0, code = 0;
    if (sscanf(statusLine.c_str(), "HTTP/%d.%d %d", &major, &minor, &code) != 3) { err = "bad answer (no HTTP status line)"; c.Close(); return false; }
    status = code;
    bool noBody = (method == "HEAD") || code == 204 || code == 304 || (code >= 100 && code < 200);
    rbody.clear();
    if (!noBody)
    {
        std::string te = Lower(HeaderValue(rheaders, "transfer-encoding"));
        std::string cl = HeaderValue(rheaders, "content-length");
        if (te.find("chunked") != std::string::npos)
        {
            std::string in = rest; size_t pos = 0;
            for (;;)
            {
                size_t e;
                while ((e = in.find("\r\n", pos)) == std::string::npos) { if (!More(c, in, deadline, &timedOut)) { err = timedOut ? "timeout" : "truncated answer"; c.Close(); return false; } }
                unsigned long sz = strtoul(in.c_str() + pos, NULL, 16);
                pos = e + 2;
                if (sz == 0) break;
                if (rbody.size() + sz > MAX_BODY) { err = "the answer is larger than 16 MB"; c.Close(); return false; }
                while (in.size() - pos < sz + 2) { if (!More(c, in, deadline, &timedOut)) { err = timedOut ? "timeout" : "truncated answer"; c.Close(); return false; } }
                rbody.append(in, pos, sz);
                pos += sz + 2;
                if (pos > 65536) { in.erase(0, pos); pos = 0; }
            }
        }
        else if (!cl.empty())
        {
            unsigned long n = strtoul(cl.c_str(), NULL, 10);
            if (n > MAX_BODY) { err = "the answer is larger than 16 MB"; c.Close(); return false; }
            rbody = rest;
            while (rbody.size() < n) { if (!More(c, rbody, deadline, &timedOut)) { err = timedOut ? "timeout" : "truncated answer"; c.Close(); return false; } }
            if (rbody.size() > n) rbody.resize(n);
        }
        else
        {
            rbody = rest;
            while (More(c, rbody, deadline, &timedOut))
                if (rbody.size() > MAX_BODY) { err = "the answer is larger than 16 MB"; c.Close(); return false; }
            if (timedOut) { err = "timeout"; c.Close(); return false; }
        }
    }
    c.Close();
    return true;
}

static std::string ResolveLocation(const Url& cur, const std::string& loc)
{
    std::string scheme = cur.tls ? "https" : "http";
    std::string hostPort = cur.host.find(':') != std::string::npos ? "[" + cur.host + "]" : cur.host;
    if ((cur.tls && cur.port != 443) || (!cur.tls && cur.port != 80)) { char pb[16]; LU_SNPRINTF(pb, sizeof(pb), ":%d", cur.port); hostPort += pb; }
    if (StartsWithI(loc, "http://") || StartsWithI(loc, "https://")) return loc;
    if (loc.compare(0, 2, "//") == 0) return scheme + ":" + loc;
    if (!loc.empty() && loc[0] == '/') return scheme + "://" + hostPort + loc;
    std::string dir = cur.path;
    size_t q = dir.find('?'); if (q != std::string::npos) dir.erase(q);
    size_t sl = dir.rfind('/'); dir = sl == std::string::npos ? "/" : dir.substr(0, sl + 1);
    return scheme + "://" + hostPort + dir + loc;
}

static void Perform(Job* j)
{
    unsigned t0 = NowMs();
    unsigned deadline = t0 + (unsigned)j->timeoutMs;
    std::string url = j->url, method = j->method, body = j->body;
    std::vector<std::string> hdrs = j->hdrs;
    j->finalUrl = url;
    for (int redirects = 0;; redirects++)
    {
        Url u;
        if (!ParseUrl(url, u)) { j->error = "invalid url (only http:// and https:// are supported)"; break; }
        int status = 0; std::string rh, rb, err;
        if (!Exchange(j, method, u, body, hdrs, deadline, status, rh, rb, err)) { j->error = err; break; }
        j->status = status; j->rheaders = rh; j->rbody = rb; j->finalUrl = url;
        std::string loc = HeaderValue(rh, "location");
        if (j->follow && !loc.empty() && (status == 301 || status == 302 || status == 303 || status == 307 || status == 308))
        {
            if (redirects >= MAX_REDIRECTS) { j->error = "too many redirects"; break; }
            std::string next = ResolveLocation(u, loc);
            Url nu;
            if (!ParseUrl(next, nu)) { j->error = "bad redirect target"; break; }
            if (nu.host != u.host)       // credentials never follow a redirect to another host
            {
                std::vector<std::string> keep;
                for (size_t i = 0; i < hdrs.size(); i++) { std::string l = Lower(hdrs[i]); if (l.compare(0, 14, "authorization:") != 0 && l.compare(0, 7, "cookie:") != 0) keep.push_back(hdrs[i]); }
                hdrs.swap(keep);
            }
            if (status == 303 || ((status == 301 || status == 302) && method == "POST")) { if (method != "HEAD") method = "GET"; body.clear(); std::vector<std::string> keep; for (size_t i = 0; i < hdrs.size(); i++) { std::string l = Lower(hdrs[i]); if (l.compare(0, 13, "content-type:") != 0) keep.push_back(hdrs[i]); } hdrs.swap(keep); }
            url = next;
            continue;
        }
        j->ok = (status >= 200 && status < 300);
        break;
    }
    j->elapsed = NowMs() - t0;
}
#endif

// ------------------------------------------------------------------------------------------------------------------------------
// the queue
// ------------------------------------------------------------------------------------------------------------------------------
struct Ctx
{
    Mutex m; Sem sem;
    std::deque<Job*> q, done;
    bool alive; int workers; int inflight;
    Ctx() : alive(true), workers(0), inflight(0) {}
};
static Ctx* g_ctx = NULL;
static bool g_pinned = false;

static void WorkerMain(void* arg)
{
    Ctx* c = (Ctx*)arg;
    for (;;)
    {
        c->sem.Wait();
        c->m.Lock();
        if (!c->alive) { c->m.Unlock(); break; }
        if (c->q.empty()) { c->m.Unlock(); continue; }
        Job* j = c->q.front(); c->q.pop_front();
        c->m.Unlock();
        Perform(j);
        c->m.Lock();
        if (c->alive) c->done.push_back(j); else delete j;
        c->m.Unlock();
    }
}

static void FailJob(Job* j, const char* msg) { j->ok = false; j->status = 0; j->error = msg; }

// takes over j (and its callback reference)
static void Enqueue(Job* j)
{
    Ctx* c = g_ctx;
    if (!c) { delete j; return; }
    c->m.Lock();
    if ((int)c->q.size() >= MAX_QUEUE) { FailJob(j, "too many pending requests"); c->done.push_back(j); c->m.Unlock(); return; }
    c->q.push_back(j);
    bool spawn = c->workers < MAX_WORKERS;
    if (spawn) c->workers++;
    c->m.Unlock();
    if (spawn)
    {
        if (!g_pinned) { PinModule(); g_pinned = true; }
        if (!StartThread(WorkerMain, c)) { c->m.Lock(); c->workers--; if (c->workers == 0) { c->q.pop_back(); FailJob(j, "could not start a worker thread"); c->done.push_back(j); c->m.Unlock(); return; } c->m.Unlock(); }
    }
    c->sem.Post();
}

// ------------------------------------------------------------------------------------------------------------------------------
// delivering an answer to the script (main thread)
// ------------------------------------------------------------------------------------------------------------------------------
static void BuildResponse(HSQUIRRELVM v, Job* j)
{
    g_api->newtable(v);
    SetSlotBool(v, "ok", j->ok);
    SetSlotInt(v, "status", j->status);
    SetSlotStr(v, "body", j->rbody);
    SetSlotStr(v, "error", j->error);
    SetSlotStr(v, "url", j->finalUrl);
    SetSlotInt(v, "time", (int)j->elapsed);
    g_api->pushstring(v, "headers", -1);
    g_api->newtable(v);
    {
        // lower case names, repeated headers joined with ", "
        std::vector<std::pair<std::string, std::string> > hv;
        size_t i = 0; const std::string& raw = j->rheaders;
        while (i < raw.size())
        {
            size_t e = raw.find('\n', i);
            std::string line = raw.substr(i, e == std::string::npos ? std::string::npos : e - i);
            i = e == std::string::npos ? raw.size() : e + 1;
            size_t cpos = line.find(':');
            if (cpos == std::string::npos || cpos == 0) continue;
            std::string name = Lower(Trim(line.substr(0, cpos))), val = Trim(line.substr(cpos + 1));
            bool found = false;
            for (size_t k = 0; k < hv.size(); k++) if (hv[k].first == name) { hv[k].second += ", " + val; found = true; break; }
            if (!found) hv.push_back(std::make_pair(name, val));
        }
        for (size_t k = 0; k < hv.size(); k++) SetSlotStr(v, hv[k].first.c_str(), hv[k].second);
    }
    g_api->rawset(v, -3);
}

static void Deliver(Job* j)
{
    HSQUIRRELVM v = g_vm;
    if (!v) { delete j; return; }
    SQInteger top = g_api->gettop(v);
    g_api->reservestack(v, 400);
    g_api->pushobject(v, j->cb);
    g_api->pushroottable(v);
    int nargs = 1;
    if (j->kind == 1)
    {
        std::string err;
        bool parsed = false;
        if (j->ok || !j->rbody.empty()) parsed = JsonParse(v, j->rbody, err);
        if (!parsed)
        {
            g_api->pushnull(v);
            if (j->ok && !err.empty()) { j->ok = false; if (j->error.empty()) j->error = err; }
        }
        nargs = 2;
    }
    BuildResponse(v, j);
    g_api->call(v, nargs + 1, SQFalse, SQTrue);
    g_api->settop(v, top);
    g_api->release(v, &j->cb);
    delete j;
}

// ------------------------------------------------------------------------------------------------------------------------------
// natives
// ------------------------------------------------------------------------------------------------------------------------------
static SQInteger Throw(HSQUIRRELVM v, const char* m) { return g_api->throwerror(v, m); }

// appends a query to a url: a string "a=1&b=2" or a table
static bool AppendQuery(HSQUIRRELVM v, int idx, std::string& url)
{
    std::string q;
    SQObjectType t = g_api->gettype(v, idx);
    idx = AbsIdx(v, idx);
    if (t == OT_STRING) { GetStr(v, idx, q); }
    else if (t == OT_TABLE)
    {
        g_api->pushnull(v);
        while (SQ_SUCCEEDED(g_api->next(v, idx)))
        {
            std::string k, val;
            if (!GetStr(v, -2, k)) { g_api->tostring(v, -2); GetStr(v, -1, k); g_api->pop(v, 1); }
            g_api->tostring(v, -1); GetStr(v, -1, val); g_api->pop(v, 1);
            if (!q.empty()) q += '&';
            q += UrlEnc(k) + "=" + UrlEnc(val);
            g_api->pop(v, 2);
        }
        g_api->pop(v, 1);
    }
    else if (t != OT_NULL) return false;
    if (!q.empty()) { url += (url.find('?') == std::string::npos ? "?" : "&"); url += q; }
    return true;
}

static void AddHeader(Job* j, const std::string& line) { if (CleanHeader(line)) j->hdrs.push_back(Trim(line.substr(0, line.find(':'))) + ": " + Trim(line.substr(line.find(':') + 1))); }

// headers: a string ("A: b\nC: d"), an array of such lines, or a table {name = value}
static bool ReadHeaders(HSQUIRRELVM v, int idx, Job* j)
{
    idx = AbsIdx(v, idx);
    SQObjectType t = g_api->gettype(v, idx);
    if (t == OT_NULL) return true;
    if (t == OT_STRING)
    {
        std::string s; GetStr(v, idx, s);
        size_t i = 0;
        while (i < s.size()) { size_t e = s.find('\n', i); AddHeader(j, s.substr(i, e == std::string::npos ? std::string::npos : e - i)); i = e == std::string::npos ? s.size() : e + 1; }
        return true;
    }
    if (t == OT_ARRAY)
    {
        g_api->pushnull(v);
        while (SQ_SUCCEEDED(g_api->next(v, idx))) { std::string s; if (GetStr(v, -1, s)) AddHeader(j, s); g_api->pop(v, 2); }
        g_api->pop(v, 1);
        return true;
    }
    if (t == OT_TABLE)
    {
        g_api->pushnull(v);
        while (SQ_SUCCEEDED(g_api->next(v, idx)))
        {
            std::string k, val;
            if (!GetStr(v, -2, k)) { g_api->tostring(v, -2); GetStr(v, -1, k); g_api->pop(v, 1); }
            g_api->tostring(v, -1); GetStr(v, -1, val); g_api->pop(v, 1);
            AddHeader(j, k + ": " + val);
            g_api->pop(v, 2);
        }
        g_api->pop(v, 1);
        return true;
    }
    return false;
}

// a request body: string, null, number/bool (their text), table / array (JSON)
static bool ReadBody(HSQUIRRELVM v, int idx, Job* j)
{
    idx = AbsIdx(v, idx);
    SQObjectType t = g_api->gettype(v, idx);
    if (t == OT_NULL) return true;
    if (t == OT_STRING) { GetStr(v, idx, j->body); return true; }
    if (t == OT_TABLE || t == OT_ARRAY)
    {
        g_api->reservestack(v, 400);
        JsonOut(v, idx, j->body, 0);
        if (!HasHeader(j->hdrs, "Content-Type")) j->hdrs.push_back("Content-Type: application/json");
        return true;
    }
    if (t == OT_INTEGER || t == OT_FLOAT || t == OT_BOOL) { g_api->tostring(v, idx); GetStr(v, -1, j->body); g_api->pop(v, 1); return true; }
    return false;
}

static void ReadOptions(HSQUIRRELVM v, int idx, Job* j, bool& bad)
{
    idx = AbsIdx(v, idx);
    g_api->pushnull(v);
    while (SQ_SUCCEEDED(g_api->next(v, idx)))
    {
        std::string k;
        if (GetStr(v, -2, k))
        {
            k = Lower(k);
            SQObjectType t = g_api->gettype(v, -1);
            if (k == "method") { std::string m; if (GetStr(v, -1, m)) { for (size_t i = 0; i < m.size(); i++) m[i] = (char)toupper((unsigned char)m[i]); j->method = m; } else bad = true; }
            else if (k == "body" || k == "json") { if (!ReadBody(v, -1, j)) bad = true; }
            else if (k == "headers") { if (!ReadHeaders(v, -1, j)) bad = true; }
            else if (k == "timeout") { SQInteger n = 0; if (SQ_SUCCEEDED(g_api->getinteger(v, -1, &n)) && n > 0) j->timeoutMs = (int)n; else if (t == OT_FLOAT) { double f = 0; g_api->getdouble(v, -1, &f); if (f > 0) j->timeoutMs = (int)f; } }
            else if (k == "insecure") { SQBool b = SQFalse; if (SQ_SUCCEEDED(g_api->getbool(v, -1, &b))) j->insecure = b != SQFalse; }
            else if (k == "follow" || k == "redirect") { SQBool b = SQTrue; if (SQ_SUCCEEDED(g_api->getbool(v, -1, &b))) j->follow = b != SQFalse; }
        }
        g_api->pop(v, 2);
    }
    g_api->pop(v, 1);
}

static Job* NewJob(const std::string& method, const std::string& url)
{
    Job* j = new Job;
    j->method = method; j->url = url;
    j->timeoutMs = g_timeoutMs; j->insecure = g_insecure;
    return j;
}

// the last argument must be a function: keeps it and starts the job
static SQInteger Launch(HSQUIRRELVM v, Job* j, int cbIdx)
{
    if (!g_ctx) { delete j; return Throw(v, "lu_http is not loaded"); }
    if (j->method.empty()) j->method = "GET";
    cbIdx = AbsIdx(v, cbIdx);
    g_api->getstackobj(v, cbIdx, &j->cb);
    g_api->addref(v, &j->cb);
    Enqueue(j);
    g_api->pushinteger(v, 1);
    return 1;
}

// fetch(url, callback) | fetch(url, options, callback) | fetch(url, method, [body, [headers,]] callback)
static SQInteger fnFetch(HSQUIRRELVM v)
{
    int top = (int)g_api->gettop(v);
    std::string url;
    if (top < 3) return Throw(v, "fetch(url [, method, body, headers], callback)");
    if (!GetStr(v, 2, url)) return Throw(v, "fetch: the url must be a string");
    if (!IsFn(v, top)) return Throw(v, "fetch: the last argument must be a callback function");
    Job* j = NewJob("GET", url);
    bool bad = false;
    int idx = 3;
    if (idx < top)
    {
        SQObjectType t = g_api->gettype(v, idx);
        if (t == OT_TABLE) { ReadOptions(v, idx, j, bad); idx++; }
        else if (t == OT_STRING)
        {
            std::string m; GetStr(v, idx, m);
            for (size_t i = 0; i < m.size(); i++) m[i] = (char)toupper((unsigned char)m[i]);
            j->method = m; idx++;
            if (idx < top) { if (!ReadBody(v, idx, j)) bad = true; idx++; }
            if (idx < top) { if (!ReadHeaders(v, idx, j)) bad = true; idx++; }
        }
        else bad = true;
        if (idx < top) bad = true;
    }
    if (bad) { delete j; return Throw(v, "fetch: bad arguments (method / body / headers / options)"); }
    return Launch(v, j, top);
}

// http_get(url, [query,] callback)  /  GetJson(url, [query,] callback)
static SQInteger GetCommon(HSQUIRRELVM v, int kind, const char* who)
{
    int top = (int)g_api->gettop(v);
    std::string url;
    if (top < 3 || top > 4 || !GetStr(v, 2, url)) { char b[96]; LU_SNPRINTF(b, sizeof(b), "%s(url [, query], callback)", who); return Throw(v, b); }
    if (!IsFn(v, top)) { char b[96]; LU_SNPRINTF(b, sizeof(b), "%s: the last argument must be a callback function", who); return Throw(v, b); }
    if (top == 4 && !AppendQuery(v, 3, url)) { char b[96]; LU_SNPRINTF(b, sizeof(b), "%s: the query must be a string or a table", who); return Throw(v, b); }
    Job* j = NewJob("GET", url);
    j->kind = kind;
    if (kind == 1) j->hdrs.push_back("Accept: application/json");
    return Launch(v, j, top);
}
static SQInteger fnHttpGet(HSQUIRRELVM v) { return GetCommon(v, 0, "http_get"); }
static SQInteger fnGetJson(HSQUIRRELVM v) { return GetCommon(v, 1, "GetJson"); }

static SQInteger PostCommon(HSQUIRRELVM v, int kind, const char* who)
{
    int top = (int)g_api->gettop(v);
    std::string url;
    if (top != 4 || !GetStr(v, 2, url)) { char b[96]; LU_SNPRINTF(b, sizeof(b), "%s(url, body, callback)", who); return Throw(v, b); }
    if (!IsFn(v, 4)) { char b[96]; LU_SNPRINTF(b, sizeof(b), "%s: the last argument must be a callback function", who); return Throw(v, b); }
    Job* j = NewJob("POST", url);
    j->kind = kind;
    if (kind == 1) j->hdrs.push_back("Accept: application/json");
    if (!ReadBody(v, 3, j)) { delete j; char b[96]; LU_SNPRINTF(b, sizeof(b), "%s: the body must be a string, table or array", who); return Throw(v, b); }
    if (!HasHeader(j->hdrs, "Content-Type")) j->hdrs.push_back("Content-Type: application/x-www-form-urlencoded");
    return Launch(v, j, 4);
}
static SQInteger fnHttpPost(HSQUIRRELVM v) { return PostCommon(v, 0, "http_post"); }
static SQInteger fnPostJson(HSQUIRRELVM v)
{
    // PostJson(url, value, callback): value is always sent as JSON (a string is sent as it is)
    return PostCommon(v, 1, "PostJson");
}

static SQInteger fnParseJson(HSQUIRRELVM v)
{
    std::string s, err;
    if (!GetStr(v, 2, s)) return Throw(v, "ParseJson(text): text must be a string");
    if (!JsonParse(v, s, err)) return Throw(v, err.c_str());
    return 1;
}
static SQInteger fnToJson(HSQUIRRELVM v)
{
    std::string o;
    g_api->reservestack(v, 400);
    JsonOut(v, 2, o, 0);
    PushStr(v, o);
    return 1;
}
static SQInteger fnUrlEncode(HSQUIRRELVM v) { std::string s; if (!GetStr(v, 2, s)) return Throw(v, "UrlEncode(string)"); PushStr(v, UrlEnc(s)); return 1; }
static SQInteger fnUrlDecode(HSQUIRRELVM v) { std::string s; if (!GetStr(v, 2, s)) return Throw(v, "UrlDecode(string)"); PushStr(v, UrlDec(s)); return 1; }
static SQInteger fnSetTimeout(HSQUIRRELVM v)
{
    SQInteger n = 0;
    if (SQ_FAILED(g_api->getinteger(v, 2, &n)) || n < 100 || n > 600000) return Throw(v, "SetHttpTimeout(ms): 100 .. 600000");
    g_timeoutMs = (int)n;
    return 0;
}
static SQInteger fnSetInsecure(HSQUIRRELVM v) { SQBool b = SQFalse; g_api->getbool(v, 2, &b); g_insecure = b != SQFalse; return 0; }
static SQInteger fnSetUserAgent(HSQUIRRELVM v) { std::string s; if (!GetStr(v, 2, s) || s.empty() || s.find_first_of("\r\n") != std::string::npos) return Throw(v, "SetHttpUserAgent(string)"); g_userAgent = s; return 0; }
static SQInteger fnPending(HSQUIRRELVM v)
{
    int n = 0;
    Ctx* c = g_ctx;
    if (c) { c->m.Lock(); n = (int)c->q.size() + (int)c->done.size(); c->m.Unlock(); }
    g_api->pushinteger(v, n);
    return 1;
}

static void Register(HSQUIRRELVM v, const char* name, SQFUNCTION fn, int nargs)
{
    g_api->pushroottable(v);
    g_api->pushstring(v, name, -1);
    g_api->newclosure(v, fn, 0);
    g_api->setparamscheck(v, nargs, NULL);          // nargs counts the environment: n + 1; negative = at least
    g_api->setnativeclosurename(v, -1, name);
    g_api->newslot(v, -3, SQFalse);
    g_api->pop(v, 1);
}

// ------------------------------------------------------------------------------------------------------------------------------
// module entry points
// ------------------------------------------------------------------------------------------------------------------------------
LU_EXPORT SQRESULT SQLoad(HSQUIRRELVM v, SQAPI api)
{
    g_api = api;
    g_vm = v;
#ifndef _WIN32
    {   // a server that closes a connection must not kill the process
        struct sigaction sa;
        if (sigaction(SIGPIPE, NULL, &sa) == 0 && sa.sa_handler == SIG_DFL) signal(SIGPIPE, SIG_IGN);
    }
#endif
    g_ctx = new Ctx;
    Register(v, "fetch", fnFetch, -3);
    Register(v, "http_get", fnHttpGet, -3);
    Register(v, "http_post", fnHttpPost, 4);
    Register(v, "GetJson", fnGetJson, -3);
    Register(v, "PostJson", fnPostJson, 4);
    Register(v, "ParseJson", fnParseJson, 2);
    Register(v, "ToJson", fnToJson, 2);
    Register(v, "UrlEncode", fnUrlEncode, 2);
    Register(v, "UrlDecode", fnUrlDecode, 2);
    Register(v, "SetHttpTimeout", fnSetTimeout, 2);
    Register(v, "SetHttpInsecure", fnSetInsecure, 2);
    Register(v, "SetHttpUserAgent", fnSetUserAgent, 2);
    Register(v, "HttpPending", fnPending, 1);
    return 0;
}

// the script VM is about to close (ReloadScripts / shutdown): requests still running are abandoned, their callbacks never run
LU_EXPORT SQRESULT SQUnload(void)
{
    Ctx* c = g_ctx;
    g_ctx = NULL;
    if (c)
    {
        c->m.Lock();
        c->alive = false;
        for (size_t i = 0; i < c->q.size(); i++) { if (g_vm) g_api->release(g_vm, &c->q[i]->cb); delete c->q[i]; }
        for (size_t i = 0; i < c->done.size(); i++) { if (g_vm) g_api->release(g_vm, &c->done[i]->cb); delete c->done[i]; }
        c->q.clear(); c->done.clear();
        int w = c->workers;
        c->m.Unlock();
        for (int i = 0; i < w; i++) c->sem.Post();      // the workers leave; the Ctx stays allocated for them
    }
    g_vm = NULL;
    return 0;
}

LU_EXPORT SQRESULT SQCallback(unsigned int callback, void* data)
{
    (void)callback; (void)data;
    return 0;
}

// every server tick: hand finished answers to their script callbacks
LU_EXPORT SQRESULT SQPulse(void)
{
    Ctx* c = g_ctx;
    if (!c || !g_vm) return 0;
    for (int n = 0; n < 16; n++)
    {
        Job* j = NULL;
        c->m.Lock();
        if (!c->done.empty()) { j = c->done.front(); c->done.pop_front(); }
        c->m.Unlock();
        if (!j) break;
        Deliver(j);
        if (g_ctx != c) break;      // a callback reloaded the scripts
    }
    return 0;
}

sqapi.h

156 lines

// The SQAPI function table a native module receives in SQLoad() - identical to the one in lu-server/scripting.cpp (the original LU
// SquirrelModule SDK layout: the ORDER of the members is the ABI). Only the Squirrel types come from the server's headers.
#ifndef LU_SQAPI_H
#define LU_SQAPI_H

#include "squirrel.h"

typedef struct
{
    /* VM */
    HSQUIRRELVM        (*open)(SQInteger initialstacksize);
    HSQUIRRELVM        (*newthread)(HSQUIRRELVM friendvm, SQInteger initialstacksize);
    void               (*seterrorhandler)(HSQUIRRELVM v);
    void               (*close)(HSQUIRRELVM v);
    void               (*setforeignptr)(HSQUIRRELVM v, SQUserPointer p);
    SQUserPointer      (*getforeignptr)(HSQUIRRELVM v);
    void               (*setprintfunc)(HSQUIRRELVM v, SQPRINTFUNCTION printfunc, SQPRINTFUNCTION errfunc);
    SQPRINTFUNCTION    (*getprintfunc)(HSQUIRRELVM v);
    SQRESULT           (*suspendvm)(HSQUIRRELVM v);
    SQRESULT           (*wakeupvm)(HSQUIRRELVM v, SQBool resumedret, SQBool retval, SQBool raiseerror, SQBool throwerror);
    SQInteger          (*getvmstate)(HSQUIRRELVM v);

    /* Compiler */
    SQRESULT           (*compile)(HSQUIRRELVM v, SQLEXREADFUNC read, SQUserPointer p, const SQChar* sourcename, SQBool raiseerror);
    SQRESULT           (*compilebuffer)(HSQUIRRELVM v, const SQChar* s, SQInteger size, const SQChar* sourcename, SQBool raiseerror);
    void               (*enabledebuginfo)(HSQUIRRELVM v, SQBool enable);
    void               (*notifyallexceptions)(HSQUIRRELVM v, SQBool enable);
    void               (*setcompilererrorhandler)(HSQUIRRELVM v, SQCOMPILERERROR f);

    /* Stack */
    void               (*push)(HSQUIRRELVM v, SQInteger idx);
    void               (*pop)(HSQUIRRELVM v, SQInteger nelemstopop);
    void               (*poptop)(HSQUIRRELVM v);
    void               (*remove)(HSQUIRRELVM v, SQInteger idx);
    SQInteger          (*gettop)(HSQUIRRELVM v);
    void               (*settop)(HSQUIRRELVM v, SQInteger newtop);
    void               (*reservestack)(HSQUIRRELVM v, SQInteger nsize);
    SQInteger          (*cmp)(HSQUIRRELVM v);
    void               (*move)(HSQUIRRELVM dest, HSQUIRRELVM src, SQInteger idx);

    /* Object creation */
    SQUserPointer      (*newuserdata)(HSQUIRRELVM v, SQUnsignedInteger size);
    void               (*newtable)(HSQUIRRELVM v);
    void               (*newarray)(HSQUIRRELVM v, SQInteger size);
    void               (*newclosure)(HSQUIRRELVM v, SQFUNCTION func, SQUnsignedInteger nfreevars);
    SQRESULT           (*setparamscheck)(HSQUIRRELVM v, SQInteger nparamscheck, const SQChar* typemask);
    SQRESULT           (*bindenv)(HSQUIRRELVM v, SQInteger idx);
    void               (*pushstring)(HSQUIRRELVM v, const SQChar* s, SQInteger len);
    void               (*pushfloat)(HSQUIRRELVM v, float f);              /* 32-bit float (old ABI): use pushdouble below */
    void               (*pushinteger)(HSQUIRRELVM v, SQInteger n);
    void               (*pushbool)(HSQUIRRELVM v, SQBool b);
    void               (*pushuserpointer)(HSQUIRRELVM v, SQUserPointer p);
    void               (*pushnull)(HSQUIRRELVM v);
    SQObjectType       (*gettype)(HSQUIRRELVM v, SQInteger idx);
    SQInteger          (*getsize)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*getbase)(HSQUIRRELVM v, SQInteger idx);
    SQBool             (*instanceof)(HSQUIRRELVM v);
    void               (*tostring)(HSQUIRRELVM v, SQInteger idx);
    void               (*tobool)(HSQUIRRELVM v, SQInteger idx, SQBool* b);
    SQRESULT           (*getstring)(HSQUIRRELVM v, SQInteger idx, const SQChar** c);
    SQRESULT           (*getinteger)(HSQUIRRELVM v, SQInteger idx, SQInteger* i);
    SQRESULT           (*getfloat)(HSQUIRRELVM v, SQInteger idx, float* f);   /* 32-bit float (old ABI): use getdouble below */
    SQRESULT           (*getbool)(HSQUIRRELVM v, SQInteger idx, SQBool* b);
    SQRESULT           (*getthread)(HSQUIRRELVM v, SQInteger idx, HSQUIRRELVM* thread);
    SQRESULT           (*getuserpointer)(HSQUIRRELVM v, SQInteger idx, SQUserPointer* p);
    SQRESULT           (*getuserdata)(HSQUIRRELVM v, SQInteger idx, SQUserPointer* p, SQUserPointer* typetag);
    SQRESULT           (*settypetag)(HSQUIRRELVM v, SQInteger idx, SQUserPointer typetag);
    SQRESULT           (*gettypetag)(HSQUIRRELVM v, SQInteger idx, SQUserPointer* typetag);
    void               (*setreleasehook)(HSQUIRRELVM v, SQInteger idx, SQRELEASEHOOK hook);
    SQChar*            (*getscratchpad)(HSQUIRRELVM v, SQInteger minsize);
    SQRESULT           (*getclosureinfo)(HSQUIRRELVM v, SQInteger idx, SQUnsignedInteger* nparams, SQUnsignedInteger* nfreevars);
    SQRESULT           (*setnativeclosurename)(HSQUIRRELVM v, SQInteger idx, const SQChar* name);
    SQRESULT           (*setinstanceup)(HSQUIRRELVM v, SQInteger idx, SQUserPointer p);
    SQRESULT           (*getinstanceup)(HSQUIRRELVM v, SQInteger idx, SQUserPointer* p, SQUserPointer typetag);
    SQRESULT           (*setclassudsize)(HSQUIRRELVM v, SQInteger idx, SQInteger udsize);
    SQRESULT           (*newclass)(HSQUIRRELVM v, SQBool hasbase);
    SQRESULT           (*createinstance)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*setattributes)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*getattributes)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*getclass)(HSQUIRRELVM v, SQInteger idx);
    void               (*weakref)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*getdefaultdelegate)(HSQUIRRELVM v, SQObjectType t);

    /* Object manipulation */
    void               (*pushroottable)(HSQUIRRELVM v);
    void               (*pushregistrytable)(HSQUIRRELVM v);
    void               (*pushconsttable)(HSQUIRRELVM v);
    SQRESULT           (*setroottable)(HSQUIRRELVM v);
    SQRESULT           (*setconsttable)(HSQUIRRELVM v);
    SQRESULT           (*newslot)(HSQUIRRELVM v, SQInteger idx, SQBool bstatic);
    SQRESULT           (*deleteslot)(HSQUIRRELVM v, SQInteger idx, SQBool pushval);
    SQRESULT           (*set)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*get)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*rawget)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*rawset)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*rawdeleteslot)(HSQUIRRELVM v, SQInteger idx, SQBool pushval);
    SQRESULT           (*arrayappend)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*arraypop)(HSQUIRRELVM v, SQInteger idx, SQBool pushval);
    SQRESULT           (*arrayresize)(HSQUIRRELVM v, SQInteger idx, SQInteger newsize);
    SQRESULT           (*arrayreverse)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*arrayremove)(HSQUIRRELVM v, SQInteger idx, SQInteger itemidx);
    SQRESULT           (*arrayinsert)(HSQUIRRELVM v, SQInteger idx, SQInteger destpos);
    SQRESULT           (*setdelegate)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*getdelegate)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*clone)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*setfreevariable)(HSQUIRRELVM v, SQInteger idx, SQUnsignedInteger nval);
    SQRESULT           (*next)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*getweakrefval)(HSQUIRRELVM v, SQInteger idx);
    SQRESULT           (*clear)(HSQUIRRELVM v, SQInteger idx);

    /* Calls */
    SQRESULT           (*call)(HSQUIRRELVM v, SQInteger params, SQBool retval, SQBool raiseerror);
    SQRESULT           (*resume)(HSQUIRRELVM v, SQBool retval, SQBool raiseerror);
    const SQChar*      (*getlocal)(HSQUIRRELVM v, SQUnsignedInteger level, SQUnsignedInteger idx);
    const SQChar*      (*getfreevariable)(HSQUIRRELVM v, SQInteger idx, SQUnsignedInteger nval);
    SQRESULT           (*throwerror)(HSQUIRRELVM v, const SQChar* err);
    void               (*reseterror)(HSQUIRRELVM v);
    void               (*getlasterror)(HSQUIRRELVM v);

    /* Raw object handling */
    SQRESULT           (*getstackobj)(HSQUIRRELVM v, SQInteger idx, HSQOBJECT* po);
    void               (*pushobject)(HSQUIRRELVM v, HSQOBJECT obj);
    void               (*addref)(HSQUIRRELVM v, HSQOBJECT* po);
    SQBool             (*release)(HSQUIRRELVM v, HSQOBJECT* po);
    void               (*resetobject)(HSQOBJECT* po);
    const SQChar*      (*objtostring)(HSQOBJECT* o);
    SQBool             (*objtobool)(HSQOBJECT* o);
    SQInteger          (*objtointeger)(HSQOBJECT* o);
    float              (*objtofloat)(HSQOBJECT* o);
    SQRESULT           (*getobjtypetag)(HSQOBJECT* o, SQUserPointer* typetag);

    /* GC */
    SQInteger          (*collectgarbage)(HSQUIRRELVM v);

    /* Serialization */
    SQRESULT           (*writeclosure)(HSQUIRRELVM vm, SQWRITEFUNC writef, SQUserPointer up);
    SQRESULT           (*readclosure)(HSQUIRRELVM vm, SQREADFUNC readf, SQUserPointer up);

    /* Memory */
    void*              (*malloc)(SQUnsignedInteger size);
    void*              (*realloc)(void* p, SQUnsignedInteger oldsize, SQUnsignedInteger newsize);
    void               (*free)(void* p, SQUnsignedInteger size);

    /* Debug */
    SQRESULT           (*stackinfos)(HSQUIRRELVM v, SQInteger level, SQStackInfos* si);
    void               (*setdebughook)(HSQUIRRELVM v);

    /* 0.5.1: 64-bit floats (the server's scripts use doubles; modules are built with SQUSEDOUBLE) */
    void               (*pushdouble)(HSQUIRRELVM v, double f);
    SQRESULT           (*getdouble)(HSQUIRRELVM v, SQInteger idx, double* f);
} SquirrelAPI;

typedef SquirrelAPI* SQAPI;

#endif
Categories: Native modules