lbug 0.18.1

An in-process property graph database management system built for query speed and scalability
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
#include "extension/extension.h"

#include <array>
#include <cstdlib>
#include <filesystem>

#include "common/exception/io.h"
#include "common/string_utils.h"
#include "common/system_message.h"
#include "main/client_context.h"
#include "main/database.h"
#include "storage/storage_manager.h"
#ifdef _WIN32

#include "windows.h"
#define RTLD_NOW 0
#define RTLD_LOCAL 0

#else
#include <dlfcn.h>

#include <format>
#endif

namespace lbug {
namespace extension {

namespace {

struct ParsedURL {
    std::string scheme;
    std::string host;
    int port = -1;
};

std::string getEnv(const char* name) {
    const auto value = std::getenv(name); // NOLINT(*-mt-unsafe)
    return value == nullptr ? "" : value;
}

std::string getProxyEnv(std::initializer_list<const char*> names) {
    for (auto name : names) {
        auto value = getEnv(name);
        if (!value.empty()) {
            return value;
        }
    }
    return "";
}

int parsePort(const std::string& port) {
    try {
        auto parsedPort = std::stoi(port);
        return parsedPort > 0 && parsedPort <= 65535 ? parsedPort : -1;
    } catch (...) {
        return -1;
    }
}

ParsedURL parseURL(std::string url) {
    ParsedURL result;
    auto schemeEnd = url.find("://");
    if (schemeEnd != std::string::npos) {
        result.scheme = common::StringUtils::getLower(url.substr(0, schemeEnd));
        url = url.substr(schemeEnd + 3);
    }
    auto pathStart = url.find_first_of("/?#");
    if (pathStart != std::string::npos) {
        url = url.substr(0, pathStart);
    }
    auto atPos = url.rfind('@');
    if (atPos != std::string::npos) {
        url = url.substr(atPos + 1);
    }
    if (url.starts_with('[')) {
        auto bracketEnd = url.find(']');
        if (bracketEnd != std::string::npos) {
            result.host = url.substr(1, bracketEnd - 1);
            if (bracketEnd + 1 < url.size() && url[bracketEnd + 1] == ':') {
                result.port = parsePort(url.substr(bracketEnd + 2));
            }
        }
        return result;
    }
    auto portPos = url.rfind(':');
    if (portPos != std::string::npos && url.find(':') == portPos) {
        result.host = url.substr(0, portPos);
        result.port = parsePort(url.substr(portPos + 1));
    } else {
        result.host = url;
    }
    return result;
}

bool noProxyMatches(std::string noProxy, const ParsedURL& target) {
    auto targetHost = common::StringUtils::getLower(target.host);
    while (!noProxy.empty()) {
        auto commaPos = noProxy.find(',');
        auto entry = commaPos == std::string::npos ? noProxy : noProxy.substr(0, commaPos);
        entry = common::StringUtils::ltrim(common::StringUtils::rtrim(entry));
        entry = common::StringUtils::getLower(entry);
        if (entry == "*") {
            return true;
        }
        if (entry.starts_with('.')) {
            if (targetHost.ends_with(entry)) {
                return true;
            }
        } else {
            auto entryHost = parseURL(entry).host;
            entryHost = common::StringUtils::getLower(entryHost);
            if (targetHost == entryHost || targetHost.ends_with("." + entryHost)) {
                return true;
            }
        }
        if (commaPos == std::string::npos) {
            break;
        }
        noProxy = noProxy.substr(commaPos + 1);
    }
    return false;
}

} // namespace

std::string getOS() {
    std::string os = "linux";
#if !defined(_GLIBCXX_USE_CXX11_ABI) || _GLIBCXX_USE_CXX11_ABI == 0
    if (os == "linux") {
        os = "linux_old";
    }
#endif
#ifdef _WIN32
    os = "win";
#elif defined(__APPLE__)
    os = "osx";
#endif
    return os;
}

std::string getArch() {
    std::string arch = "amd64";
#if defined(__i386__) || defined(_M_IX86)
    arch = "x86";
#elif defined(__aarch64__) || defined(__ARM_ARCH_ISA_A64)
    arch = "arm64";
#endif
    return arch;
}

std::string getPlatform() {
    return getOS() + "_" + getArch();
}

static ExtensionRepoInfo getExtensionRepoInfo(const std::string& extensionURL) {
    auto parsedURL = parseURL(extensionURL);
    auto scheme = parsedURL.scheme.empty() ? "http" : parsedURL.scheme;
    auto hostStart = extensionURL.find("://");
    hostStart = hostStart == std::string::npos ? 0 : hostStart + 3;
    auto hostPathStart = extensionURL.find('/', hostStart);
    auto hostName = hostPathStart == std::string::npos ?
                        extensionURL.substr(hostStart) :
                        extensionURL.substr(hostStart, hostPathStart - hostStart);
    auto hostURL = std::format("{}://{}", scheme, hostName);
    auto hostPath = hostPathStart == std::string::npos ? "/" : extensionURL.substr(hostPathStart);
    return {hostPath, hostURL, extensionURL};
}

std::string ExtensionSourceUtils::toString(ExtensionSource source) {
    switch (source) {
    case ExtensionSource::OFFICIAL:
        return "OFFICIAL";
    case ExtensionSource::USER:
        return "USER";
    case ExtensionSource::STATIC_LINKED:
        return "STATIC LINK";
    default:
        UNREACHABLE_CODE;
    }
}

static ExtensionRepoInfo getExtensionFilePath(const std::string& extensionName,
    const std::string& extensionRepo, const std::string& fileName) {
    auto extensionURL = std::format(ExtensionUtils::EXTENSION_FILE_REPO_PATH, extensionRepo,
        LBUG_EXTENSION_VERSION, getPlatform(), extensionName, fileName);
    return getExtensionRepoInfo(extensionURL);
}

ExtensionRepoInfo ExtensionUtils::getExtensionLibRepoInfo(const std::string& extensionName,
    const std::string& extensionRepo) {
    return getExtensionFilePath(extensionName, extensionRepo, getExtensionFileName(extensionName));
}

ExtensionRepoInfo ExtensionUtils::getExtensionLoaderRepoInfo(const std::string& extensionName,
    const std::string& extensionRepo) {
    return getExtensionFilePath(extensionName, extensionRepo,
        getExtensionFileName(extensionName + EXTENSION_LOADER_SUFFIX));
}

ExtensionRepoInfo ExtensionUtils::getExtensionInstallerRepoInfo(const std::string& extensionName,
    const std::string& extensionRepo) {
    return getExtensionFilePath(extensionName, extensionRepo,
        getExtensionFileName(extensionName + EXTENSION_INSTALLER_SUFFIX));
}

ExtensionRepoInfo ExtensionUtils::getSharedLibRepoInfo(const std::string& fileName,
    const std::string& extensionRepo) {
    auto extensionURL = std::format(SHARED_LIB_REPO, extensionRepo, LBUG_EXTENSION_VERSION,
        getPlatform(), fileName);
    return getExtensionRepoInfo(extensionURL);
}

std::optional<ExtensionProxyConfig> ExtensionUtils::parseProxyConfig(const std::string& proxyURL) {
    auto parsedURL = parseURL(proxyURL);
    if (parsedURL.host.empty()) {
        return std::nullopt;
    }
    ExtensionProxyConfig config{parsedURL.host, parsedURL.port == -1 ? 80 : parsedURL.port, "", ""};
    auto authority = proxyURL;
    auto schemeEnd = authority.find("://");
    if (schemeEnd != std::string::npos) {
        authority = authority.substr(schemeEnd + 3);
    }
    auto pathStart = authority.find_first_of("/?#");
    if (pathStart != std::string::npos) {
        authority = authority.substr(0, pathStart);
    }
    auto atPos = authority.rfind('@');
    if (atPos != std::string::npos) {
        auto userInfo = authority.substr(0, atPos);
        auto passwordPos = userInfo.find(':');
        if (passwordPos == std::string::npos) {
            config.username = userInfo;
        } else {
            config.username = userInfo.substr(0, passwordPos);
            config.password = userInfo.substr(passwordPos + 1);
        }
    }
    return config;
}

std::optional<ExtensionProxyConfig> ExtensionUtils::getProxyConfigForURL(const std::string& url) {
    auto targetURL = parseURL(url);
    if (targetURL.host.empty()) {
        return std::nullopt;
    }
    auto noProxy = getProxyEnv({"LADYBUG_NO_PROXY", "no_proxy", "NO_PROXY"});
    if (!noProxy.empty() && noProxyMatches(noProxy, targetURL)) {
        return std::nullopt;
    }
    std::string proxyURL;
    if (targetURL.scheme == "https") {
        proxyURL = getProxyEnv({"LADYBUG_HTTPS_PROXY", "https_proxy", "HTTPS_PROXY"});
    } else {
        proxyURL = getProxyEnv({"LADYBUG_HTTP_PROXY", "http_proxy", "HTTP_PROXY"});
    }
    if (proxyURL.empty()) {
        proxyURL = getProxyEnv({"LADYBUG_ALL_PROXY", "all_proxy", "ALL_PROXY"});
    }
    return proxyURL.empty() ? std::nullopt : parseProxyConfig(proxyURL);
}

std::optional<ExtensionCaCertPath> ExtensionUtils::getCaCertPath() {
    namespace fs = std::filesystem;
    std::error_code ec;

    // 1. Respect SSL_CERT_FILE environment variable (OpenSSL standard).
    if (const char* env = std::getenv("SSL_CERT_FILE")) { // NOLINT(*-mt-unsafe)
        if (fs::exists(env, ec) && !fs::is_empty(env, ec)) {
            return ExtensionCaCertPath{env, ""};
        }
    }
    // 2. Respect SSL_CERT_DIR environment variable (OpenSSL standard).
    if (const char* env = std::getenv("SSL_CERT_DIR")) { // NOLINT(*-mt-unsafe)
        if (fs::is_directory(env, ec)) {
            return ExtensionCaCertPath{"", env};
        }
    }
    // 3. Probe well-known CA bundle file locations by distro.
    constexpr std::array<const char*, 6> wellKnownFiles = {
        "/etc/ssl/certs/ca-certificates.crt", // Debian / Ubuntu
        "/etc/pki/tls/certs/ca-bundle.crt",   // RHEL / Fedora / CentOS
        "/etc/ssl/ca-bundle.pem",             // openSUSE
        "/etc/ssl/certs/ca-bundle.crt",       // Alpine / Arch (alt)
        "/etc/pki/tls/cert.pem",              // RHEL / Fedora (alternate)
        "/etc/ssl/cert.pem",                  // macOS (Homebrew openssl), some BSDs
    };
    for (const auto* path : wellKnownFiles) {
        if (fs::exists(path, ec) && !fs::is_empty(path, ec)) {
            return ExtensionCaCertPath{path, ""};
        }
    }
    // 4. Probe well-known CApath directories (Debian hashed-symlink layout).
    constexpr std::array<const char*, 2> wellKnownDirs = {
        "/etc/ssl/certs",     // Debian / Ubuntu (hashed symlinks)
        "/etc/pki/tls/certs", // RHEL (fallback, mixed)
    };
    for (const auto* path : wellKnownDirs) {
        if (fs::is_directory(path, ec)) {
            return ExtensionCaCertPath{"", path};
        }
    }
    // No CA bundle found - let OpenSSL fall back to its compile-time defaults
    // (SSL_CTX_set_default_verify_paths on Linux; Windows cert store on Windows).
    return std::nullopt;
}

std::string ExtensionUtils::getExtensionFileName(const std::string& name) {
    return std::format(EXTENSION_FILE_NAME, common::StringUtils::getLower(name),
        EXTENSION_FILE_SUFFIX);
}

std::string ExtensionUtils::getLocalPathForExtensionLib(main::ClientContext* context,
    const std::string& extensionName) {
    return std::format("{}/{}", getLocalDirForExtension(context, extensionName),
        getExtensionFileName(extensionName));
}

std::string ExtensionUtils::getLocalPathForExtensionLoader(main::ClientContext* context,
    const std::string& extensionName) {
    return std::format("{}/{}", getLocalDirForExtension(context, extensionName),
        getExtensionFileName(extensionName + EXTENSION_LOADER_SUFFIX));
}

std::string ExtensionUtils::getLocalPathForExtensionInstaller(main::ClientContext* context,
    const std::string& extensionName) {
    return std::format("{}/{}", getLocalDirForExtension(context, extensionName),
        getExtensionFileName(extensionName + EXTENSION_INSTALLER_SUFFIX));
}

std::string ExtensionUtils::getLocalDirForExtension(main::ClientContext* context,
    const std::string& extensionName) {
    return std::format("{}{}", context->getExtensionDir(), extensionName);
}

std::string ExtensionUtils::appendLibSuffix(const std::string& libName) {
    auto os = getOS();
    std::string suffix;
    if (os == "linux" || os == "linux_old") {
        suffix = "so";
    } else if (os == "osx") {
        suffix = "dylib";
    } else {
        UNREACHABLE_CODE;
    }
    return std::format("{}.{}", libName, suffix);
}

std::string ExtensionUtils::getLocalPathForSharedLib(main::ClientContext* context,
    const std::string& libName) {
    return std::format("{}common/{}", context->getExtensionDir(), libName);
}

std::string ExtensionUtils::getLocalPathForSharedLib(main::ClientContext* context) {
    return std::format("{}common/", context->getExtensionDir());
}

bool ExtensionUtils::isOfficialExtension(const std::string& extension) {
    auto extensionUpperCase = common::StringUtils::getUpper(extension);
    for (auto& officialExtension : OFFICIAL_EXTENSION) {
        if (officialExtension == extensionUpperCase) {
            return true;
        }
    }
    return false;
}

void ExtensionUtils::registerIndexType(main::Database& database, storage::IndexType type) {
    database.getStorageManager()->registerIndexType(std::move(type));
}

ExtensionLibLoader::ExtensionLibLoader(const std::string& extensionName, const std::string& path)
    : extensionName{extensionName} {
    libHdl = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
    if (libHdl == nullptr) {
        throw common::IOException(
            std::format("Failed to load library: {} which is needed by extension: {}.\nError: {}.",
                path, extensionName, common::dlErrMessage()));
    }
}

ext_load_func_t ExtensionLibLoader::getLoadFunc() {
    return (ext_load_func_t)getDynamicLibFunc(EXTENSION_LOAD_FUNC_NAME);
}

ext_init_func_t ExtensionLibLoader::getInitFunc() {
    return (ext_init_func_t)getDynamicLibFunc(EXTENSION_INIT_FUNC_NAME);
}

ext_name_func_t ExtensionLibLoader::getNameFunc() {
    return (ext_name_func_t)getDynamicLibFunc(EXTENSION_NAME_FUNC_NAME);
}

ext_install_func_t ExtensionLibLoader::getInstallFunc() {
    return (ext_install_func_t)getDynamicLibFunc(EXTENSION_INSTALL_FUNC_NAME);
}

void ExtensionLibLoader::unload() {
    DASSERT(libHdl != nullptr);
    dlclose(libHdl);
    libHdl = nullptr;
}

void* ExtensionLibLoader::getDynamicLibFunc(const std::string& funcName) {
    DASSERT(libHdl != nullptr);
    auto sym = dlsym(libHdl, funcName.c_str());
    if (sym == nullptr) {
        throw common::IOException(
            std::format("Failed to load {} function in extension {}.\nError: {}", funcName,
                extensionName, common::dlErrMessage()));
    }
    return sym;
}

#ifdef _WIN32
std::wstring utf8ToUnicode(const char* input) {
    uint32_t result;

    result = MultiByteToWideChar(CP_UTF8, 0, input, -1, nullptr, 0);
    if (result == 0) {
        throw common::IOException("Failure in MultiByteToWideChar");
    }
    auto buffer = std::make_unique<wchar_t[]>(result);
    result = MultiByteToWideChar(CP_UTF8, 0, input, -1, buffer.get(), result);
    if (result == 0) {
        throw common::IOException("Failure in MultiByteToWideChar");
    }
    return std::wstring(buffer.get(), result);
}

void* dlopen(const char* file, int /*mode*/) {
    DASSERT(file);
    auto fpath = utf8ToUnicode(file);
    return (void*)LoadLibraryW(fpath.c_str());
}

void* dlsym(void* handle, const char* name) {
    DASSERT(handle);
    return (void*)GetProcAddress((HINSTANCE)handle, name);
}

void dlclose(void* handle) {
    DASSERT(handle);
    FreeLibrary((HINSTANCE)handle);
}
#endif

} // namespace extension
} // namespace lbug