forked from duckdb/duckdb-wasm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
duckdb.patch
477 lines (454 loc) · 19.1 KB
/
duckdb.patch
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
diff --git a/extension/json/CMakeLists.txt b/extension/json/CMakeLists.txt
index 4101111df8..3e035e80d3 100644
--- a/extension/json/CMakeLists.txt
+++ b/extension/json/CMakeLists.txt
@@ -34,6 +34,7 @@ set(JSON_EXTENSION_FILES
build_static_extension(json ${JSON_EXTENSION_FILES})
set(PARAMETERS "-warnings")
build_loadable_extension(json ${PARAMETERS} ${JSON_EXTENSION_FILES})
+target_link_libraries(json_loadable_extension duckdb_yyjson)
install(
TARGETS json_extension
diff --git a/src/common/file_system.cpp b/src/common/file_system.cpp
index 27160adc3f..f3dfc7441b 100644
--- a/src/common/file_system.cpp
+++ b/src/common/file_system.cpp
@@ -623,9 +623,14 @@ FileType FileHandle::GetType() {
}
bool FileSystem::IsRemoteFile(const string &path) {
- const string prefixes[] = {"http://", "https://", "s3://", "s3a://", "s3n://", "gcs://", "gs://", "r2://", "hf://"};
- for (auto &prefix : prefixes) {
- if (StringUtil::StartsWith(path, prefix)) {
+ string extension = "";
+ return IsRemoteFile(path, extension);
+}
+
+bool FileSystem::IsRemoteFile(const string &path, string &extension) {
+ for (const auto &entry : EXTENSION_FILE_PREFIXES) {
+ if (StringUtil::StartsWith(path, entry.name)) {
+ extension = entry.extension;
return true;
}
}
diff --git a/src/execution/operator/schema/physical_attach.cpp b/src/execution/operator/schema/physical_attach.cpp
index 2c2b76a0fc..2d835441c2 100644
--- a/src/execution/operator/schema/physical_attach.cpp
+++ b/src/execution/operator/schema/physical_attach.cpp
@@ -96,6 +96,25 @@ SourceResultType PhysicalAttach::GetData(ExecutionContext &context, DataChunk &c
}
}
+ string extension = "";
+ if (FileSystem::IsRemoteFile(path, extension)) {
+ if (!ExtensionHelper::TryAutoLoadExtension(context.client, extension)) {
+ throw MissingExtensionException("Attaching path '%s' requires extension '%s' to be loaded", path,
+ extension);
+ }
+ if (access_mode == AccessMode::AUTOMATIC) {
+ // Attaching of remote files gets bumped to READ_ONLY
+ // This is due to the fact that on most (all?) remote files writes to DB are not available
+ // and having this raised later is not super helpful
+ access_mode = AccessMode::READ_ONLY;
+ }
+ if (access_mode == AccessMode::READ_WRITE) {
+ auto attached_mode = EnumUtil::ToString(access_mode);
+ throw BinderException("Remote database \"%s\" can't be attached in %s mode",
+ name, attached_mode);
+ }
+ }
+
// get the database type and attach the database
db_manager.GetDatabaseType(context.client, db_type, *info, config, unrecognized_option);
auto attached_db = db_manager.AttachDatabase(context.client, *info, db_type, access_mode);
diff --git a/src/include/duckdb/common/file_open_flags.hpp b/src/include/duckdb/common/file_open_flags.hpp
index d0509a214b..1b5107e849 100644
--- a/src/include/duckdb/common/file_open_flags.hpp
+++ b/src/include/duckdb/common/file_open_flags.hpp
@@ -100,8 +100,9 @@ public:
return flags & FILE_FLAGS_PARALLEL_ACCESS;
}
-private:
idx_t flags = 0;
+
+private:
FileLockType lock = FileLockType::NO_LOCK;
FileCompressionType compression = FileCompressionType::UNCOMPRESSED;
};
diff --git a/src/include/duckdb/common/file_system.hpp b/src/include/duckdb/common/file_system.hpp
index e0df2f70c2..fa2b938199 100644
--- a/src/include/duckdb/common/file_system.hpp
+++ b/src/include/duckdb/common/file_system.hpp
@@ -238,6 +238,7 @@ public:
//! Whether or not a file is remote or local, based only on file path
DUCKDB_API static bool IsRemoteFile(const string &path);
+ DUCKDB_API static bool IsRemoteFile(const string &path, string &extension);
DUCKDB_API virtual void SetDisabledFileSystems(const vector<string> &names);
diff --git a/src/include/duckdb/main/extension_install_info.hpp b/src/include/duckdb/main/extension_install_info.hpp
index 64b7b520a7..b03f64b3aa 100644
--- a/src/include/duckdb/main/extension_install_info.hpp
+++ b/src/include/duckdb/main/extension_install_info.hpp
@@ -49,9 +49,9 @@ public:
struct ExtensionRepository {
//! All currently available repositories
- static constexpr const char *CORE_REPOSITORY_URL = "http://extensions.duckdb.org";
- static constexpr const char *CORE_NIGHTLY_REPOSITORY_URL = "http://nightly-extensions.duckdb.org";
- static constexpr const char *COMMUNITY_REPOSITORY_URL = "http://community-extensions.duckdb.org";
+ static constexpr const char *CORE_REPOSITORY_URL = "https://extensions.duckdb.org";
+ static constexpr const char *CORE_NIGHTLY_REPOSITORY_URL = "https://nightly-extensions.duckdb.org";
+ static constexpr const char *COMMUNITY_REPOSITORY_URL = "https://community-extensions.duckdb.org";
//! Debugging repositories (target local, relative paths that are produced by DuckDB's build system)
static constexpr const char *BUILD_DEBUG_REPOSITORY_PATH = "./build/debug/repository";
diff --git a/src/main/extension/extension_helper.cpp b/src/main/extension/extension_helper.cpp
index 37b3cd1aa0..b91f0059b4 100644
--- a/src/main/extension/extension_helper.cpp
+++ b/src/main/extension/extension_helper.cpp
@@ -302,7 +302,6 @@ vector<ExtensionUpdateResult> ExtensionHelper::UpdateExtensions(DatabaseInstance
auto &config = DBConfig::GetConfig(db);
-#ifndef WASM_LOADABLE_EXTENSIONS
case_insensitive_set_t seen_extensions;
// scan the install directory for installed extensions
@@ -319,7 +318,6 @@ vector<ExtensionUpdateResult> ExtensionHelper::UpdateExtensions(DatabaseInstance
result.push_back(UpdateExtensionInternal(db, fs, fs.JoinPath(ext_directory, path), extension_name));
});
-#endif
return result;
}
diff --git a/src/main/extension/extension_install.cpp b/src/main/extension/extension_install.cpp
index 8a278832b1..b9447440de 100644
--- a/src/main/extension/extension_install.cpp
+++ b/src/main/extension/extension_install.cpp
@@ -197,7 +197,7 @@ string ExtensionHelper::ExtensionUrlTemplate(optional_ptr<const DBConfig> db_con
versioned_path = "/${REVISION}/${PLATFORM}/${NAME}.duckdb_extension";
}
#ifdef WASM_LOADABLE_EXTENSIONS
- string default_endpoint = DEFAULT_REPOSITORY;
+ string default_endpoint = ExtensionRepository::DEFAULT_REPOSITORY_URL;
versioned_path = versioned_path + ".wasm";
#else
string default_endpoint = ExtensionRepository::DEFAULT_REPOSITORY_URL;
diff --git a/src/main/extension/extension_load.cpp b/src/main/extension/extension_load.cpp
index 65438aa8ec..591c759a7f 100644
--- a/src/main/extension/extension_load.cpp
+++ b/src/main/extension/extension_load.cpp
@@ -175,7 +175,13 @@ bool ExtensionHelper::TryInitialLoad(DBConfig &config, FileSystem &fs, const str
direct_load = false;
string extension_name = ApplyExtensionAlias(extension);
#ifdef WASM_LOADABLE_EXTENSIONS
- string url_template = ExtensionUrlTemplate(&config, "");
+ ExtensionRepository repository;
+
+ string custom_endpoint = config.options.custom_extension_repo;
+ if (!custom_endpoint.empty()) {
+ repository = ExtensionRepository("custom", custom_endpoint);
+ }
+ string url_template = ExtensionUrlTemplate(&config, repository, "");
string url = ExtensionFinalizeUrlTemplate(url_template, extension_name);
char *str = (char *)EM_ASM_PTR(
@@ -215,68 +221,223 @@ bool ExtensionHelper::TryInitialLoad(DBConfig &config, FileSystem &fs, const str
direct_load = true;
filename = fs.ExpandPath(filename);
}
- if (!fs.FileExists(filename)) {
- string message;
- bool exact_match = ExtensionHelper::CreateSuggestions(extension, message);
- if (exact_match) {
- message += "\nInstall it first using \"INSTALL " + extension + "\".";
- }
- error = StringUtil::Format("Extension \"%s\" not found.\n%s", filename, message);
- return false;
- }
-
- auto handle = fs.OpenFile(filename, FileFlags::FILE_FLAGS_READ);
+ /* if (!fs.FileExists(filename)) {
+ string message;
+ bool exact_match = ExtensionHelper::CreateSuggestions(extension, message);
+ if (exact_match) {
+ message += "\nInstall it first using \"INSTALL " + extension + "\".";
+ }
+ error = StringUtil::Format("Extension \"%s\" not found.\n%s", filename, message);
+ return false;
+ }
+ */
+
+ /* auto handle = fs.OpenFile(filename, FileFlags::FILE_FLAGS_READ);
+
+ // Parse the extension metadata from the extension binary
+ auto parsed_metadata = ParseExtensionMetaData(*handle);
+
+ auto metadata_mismatch_error = parsed_metadata.GetInvalidMetadataError();
+
+ if (!metadata_mismatch_error.empty()) {
+ metadata_mismatch_error = StringUtil::Format("Failed to load '%s', %s", extension, metadata_mismatch_error);
+ }
+
+ if (!config.options.allow_unsigned_extensions) {
+ bool signature_valid =
+ CheckExtensionSignature(*handle, parsed_metadata, config.options.allow_community_extensions);
+
+ if (!signature_valid) {
+ throw IOException(config.error_manager->FormatException(ErrorType::UNSIGNED_EXTENSION, filename) +
+ metadata_mismatch_error);
+ }
+
+ if (!metadata_mismatch_error.empty()) {
+ // Signed extensions perform the full check
+ throw InvalidInputException(metadata_mismatch_error);
+ }
+ } else if (!config.options.allow_extensions_metadata_mismatch) {
+ if (!metadata_mismatch_error.empty()) {
+ // Unsigned extensions AND configuration allowing n, loading allowed, mainly for
+ // debugging purposes
+ throw InvalidInputException(metadata_mismatch_error);
+ }
+ }
+ */
+ auto filebase = fs.ExtractBaseName(filename);
- // Parse the extension metadata from the extension binary
- auto parsed_metadata = ParseExtensionMetaData(*handle);
+#ifdef WASM_LOADABLE_EXTENSIONS
+ auto basename = fs.ExtractBaseName(filename);
+ char *exe = NULL;
+ exe = (char *)EM_ASM_PTR(
+ {
+ // Next few lines should argubly in separate JavaScript-land function call
+ // TODO: move them out / have them configurable
- auto metadata_mismatch_error = parsed_metadata.GetInvalidMetadataError();
+ var url = (UTF8ToString($0));
+
+ if (typeof XMLHttpRequest === "undefined") {
+ const os = require('os');
+ const path = require('path');
+ const fs = require('fs');
+
+ var array = url.split("/");
+ var l = array.length;
+
+ var folder = path.join(os.homedir(), ".duckdb/extensions/" + array[l - 4] + "/" + array[l - 3] + "/" +
+ array[l - 2] + "/");
+ var filePath = path.join(folder, array[l - 1]);
+
+ try {
+ if (!fs.existsSync(folder)) {
+ fs.mkdirSync(folder, {recursive : true});
+ }
+
+ if (!fs.existsSync(filePath)) {
+ const int32 = new Int32Array(new SharedArrayBuffer(8));
+ var Worker = require('node:worker_threads').Worker;
+ var worker = new Worker("const {Worker,isMainThread,parentPort,workerData,} = require('node:worker_threads');var times = 0;var SAB = 23;var Z = 0; async function ZZZ(e) {var x = await fetch(e);var res = await x.arrayBuffer();Atomics.store(SAB, 1, res.byteLength);Atomics.store(SAB, 0, 1);Atomics.notify(SAB, 1);Atomics.notify(SAB, 0);Z = res;};parentPort.on('message', function(event) {if (times == 0) {times++;SAB = event;} else if (times == 1) {times++; ZZZ(event);} else {const a = new Uint8Array(Z);const b = new Uint8Array(event.buffer);var K = Z.byteLength;for (var i = 0; i < K; i++) {b[i] = a[i];}Atomics.notify(event, 0);Atomics.store(SAB, 0, 2);Atomics.notify(SAB, 0);}});", {
+ eval: true
+ });
+ var uInt8Array;
+
+ int32[0] = 0;
+ int32[2] = 4;
+ worker.postMessage(int32);
+
+ worker.postMessage(url);
+ Atomics.wait(int32, 0, 0);
+
+ const int32_2 = new Int32Array(new SharedArrayBuffer(int32[1] + 3 - ((int32[1] + 3) % 4)));
+ worker.postMessage(int32_2);
+
+ Atomics.wait(int32, 0, 1);
+
+ var x = new Uint8Array(int32_2.buffer, 0, int32[1]);
+ uInt8Array = x;
+ worker.terminate();
+ fs.writeFileSync(filePath, uInt8Array);
+
+ } else {
+ uInt8Array = fs.readFileSync(filePath);
+ }
+ } catch (e) {
+ console.log("Error fetching module", e);
+ return 0;
+ }
+ } else {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", url, false);
+ xhr.responseType = "arraybuffer";
+ xhr.send(null);
+ if (xhr.status != 200)
+ return 0;
+ uInt8Array = xhr.response;
+ }
+
+ var valid = WebAssembly.validate(uInt8Array);
+ var len = uInt8Array.byteLength;
+ var fileOnWasmHeap = _malloc(len + 4);
+
+ var properArray = new Uint8Array(uInt8Array);
+
+ for (var iii = 0; iii < len; iii++) {
+ Module.HEAPU8[iii + fileOnWasmHeap + 4] = properArray[iii];
+ }
+ var LEN123 = new Uint8Array(4);
+ LEN123[0] = len % 256;
+ len -= LEN123[0];
+ len /= 256;
+ LEN123[1] = len % 256;
+ len -= LEN123[1];
+ len /= 256;
+ LEN123[2] = len % 256;
+ len -= LEN123[2];
+ len /= 256;
+ LEN123[3] = len % 256;
+ len -= LEN123[3];
+ len /= 256;
+ Module.HEAPU8.set(LEN123, fileOnWasmHeap);
+ // FIXME: found how to expose those to the logger interface
+ // console.log(LEN123);
+ // console.log(properArray);
+ // console.log(new Uint8Array(Module.HEAPU8, fileOnWasmHeap, len+4));
+ // console.log('Loading extension ', UTF8ToString($1));
- if (!metadata_mismatch_error.empty()) {
- metadata_mismatch_error = StringUtil::Format("Failed to load '%s', %s", extension, metadata_mismatch_error);
+ // Here we add the uInt8Array to Emscripten's filesystem, for it to be found by dlopen
+ FS.writeFile(UTF8ToString($1), new Uint8Array(uInt8Array));
+ return fileOnWasmHeap;
+ },
+ filename.c_str(), basename.c_str());
+ if (!exe) {
+ throw IOException("Extension %s is not available", filename);
}
+ auto dopen_from = basename;
if (!config.options.allow_unsigned_extensions) {
- bool signature_valid =
- CheckExtensionSignature(*handle, parsed_metadata, config.options.allow_community_extensions);
+ // signature is the last 256 bytes of the file
+
+ string signature;
+ signature.resize(256);
+
+ D_ASSERT(exe);
+ uint64_t LEN = 0;
+ LEN *= 256;
+ LEN += ((uint8_t *)exe)[3];
+ LEN *= 256;
+ LEN += ((uint8_t *)exe)[2];
+ LEN *= 256;
+ LEN += ((uint8_t *)exe)[1];
+ LEN *= 256;
+ LEN += ((uint8_t *)exe)[0];
+ auto signature_offset = LEN - signature.size();
+
+ const idx_t maxLenChunks = 1024ULL * 1024ULL;
+ const idx_t numChunks = (signature_offset + maxLenChunks - 1) / maxLenChunks;
+ std::vector<std::string> hash_chunks(numChunks);
+ std::vector<idx_t> splits(numChunks + 1);
+
+ for (idx_t i = 0; i < numChunks; i++) {
+ splits[i] = maxLenChunks * i;
+ }
+ splits.back() = signature_offset;
+
+ for (idx_t i = 0; i < numChunks; i++) {
+ string x;
+ x.resize(splits[i + 1] - splits[i]);
+ for (idx_t j = 0; j < x.size(); j++) {
+ x[j] = ((uint8_t *)exe)[j + 4 + splits[i]];
+ }
+ ComputeSHA256String(x, &hash_chunks[i]);
+ }
+
+ string hash_concatenation;
+ hash_concatenation.reserve(32 * numChunks); // 256 bits -> 32 bytes per chunk
- if (!signature_valid) {
- throw IOException(config.error_manager->FormatException(ErrorType::UNSIGNED_EXTENSION, filename) +
- metadata_mismatch_error);
+ for (auto &hash_chunk : hash_chunks) {
+ hash_concatenation += hash_chunk;
}
- if (!metadata_mismatch_error.empty()) {
- // Signed extensions perform the full check
- throw InvalidInputException(metadata_mismatch_error);
+ string two_level_hash;
+ ComputeSHA256String(hash_concatenation, &two_level_hash);
+
+ for (idx_t j = 0; j < signature.size(); j++) {
+ signature[j] = ((uint8_t *)exe)[4 + signature_offset + j];
+ }
+ bool any_valid = false;
+ for (auto &key : ExtensionHelper::GetPublicKeys(config.options.allow_community_extensions)) {
+ if (duckdb_mbedtls::MbedTlsWrapper::IsValidSha256Signature(key, signature, two_level_hash)) {
+ any_valid = true;
+ break;
+ }
}
- } else if (!config.options.allow_extensions_metadata_mismatch) {
- if (!metadata_mismatch_error.empty()) {
- // Unsigned extensions AND configuration allowing n, loading allowed, mainly for
- // debugging purposes
- throw InvalidInputException(metadata_mismatch_error);
+ if (!any_valid) {
+ throw IOException(config.error_manager->FormatException(ErrorType::UNSIGNED_EXTENSION, filename));
}
}
-
- auto filebase = fs.ExtractBaseName(filename);
-
-#ifdef WASM_LOADABLE_EXTENSIONS
- EM_ASM(
- {
- // Next few lines should argubly in separate JavaScript-land function call
- // TODO: move them out / have them configurable
- const xhr = new XMLHttpRequest();
- xhr.open("GET", UTF8ToString($0), false);
- xhr.responseType = "arraybuffer";
- xhr.send(null);
- var uInt8Array = xhr.response;
- WebAssembly.validate(uInt8Array);
- console.log('Loading extension ', UTF8ToString($1));
-
- // Here we add the uInt8Array to Emscripten's filesystem, for it to be found by dlopen
- FS.writeFile(UTF8ToString($1), new Uint8Array(uInt8Array));
- },
- filename.c_str(), filebase.c_str());
- auto dopen_from = filebase;
+ if (exe) {
+ free(exe);
+ }
#else
auto dopen_from = filename;
#endif
@@ -294,25 +455,27 @@ bool ExtensionHelper::TryInitialLoad(DBConfig &config, FileSystem &fs, const str
result.lib_hdl = lib_hdl;
if (!direct_load) {
- auto info_file_name = filename + ".info";
-
- result.install_info = ExtensionInstallInfo::TryReadInfoFile(fs, info_file_name, lowercase_extension_name);
-
- if (result.install_info->mode == ExtensionInstallMode::UNKNOWN) {
- // The info file was missing, we just set the version, since we have it from the parsed footer
- result.install_info->version = parsed_metadata.extension_version;
- }
-
- if (result.install_info->version != parsed_metadata.extension_version) {
- throw IOException("Metadata mismatch detected when loading extension '%s'\nPlease try reinstalling the "
- "extension using `FORCE INSTALL '%s'`",
- filename, extension);
- }
+ /*
+ auto info_file_name = filename + ".info";
+
+ result.install_info = ExtensionInstallInfo::TryReadInfoFile(fs, info_file_name,
+ lowercase_extension_name);
+
+ if (result.install_info->mode == ExtensionInstallMode::UNKNOWN) {
+ // The info file was missing, we just set the version, since we have it from the parsed footer
+ result.install_info->version = parsed_metadata.extension_version;
+ }
+
+ if (result.install_info->version != parsed_metadata.extension_version) {
+ throw IOException("Metadata mismatch detected when loading extension '%s'\nPlease try reinstalling
+ the " "extension using `FORCE INSTALL '%s'`", filename, extension);
+ }
+ */
} else {
result.install_info = make_uniq<ExtensionInstallInfo>();
result.install_info->mode = ExtensionInstallMode::NOT_INSTALLED;
result.install_info->full_path = filename;
- result.install_info->version = parsed_metadata.extension_version;
+ result.install_info->version = ""; // parsed_metadata.extension_version;
}
return true;