-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy paths3fs.cpp
More file actions
1587 lines (1375 loc) · 59.3 KB
/
Copy paths3fs.cpp
File metadata and controls
1587 lines (1375 loc) · 59.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "s3fs.hpp"
#include "duckdb/logging/logger.hpp"
#include "hash_functions.hpp"
#include "duckdb.hpp"
#include "duckdb/common/exception/http_exception.hpp"
#include "duckdb/logging/log_type.hpp"
#include "duckdb/logging/file_system_logger.hpp"
#include "duckdb/common/helper.hpp"
#include "duckdb/common/thread.hpp"
#include "duckdb/common/types/timestamp.hpp"
#include "duckdb/function/scalar/strftime_format.hpp"
#include "http_state.hpp"
#include "duckdb/common/string_util.hpp"
#include "duckdb/common/crypto/md5.hpp"
#include "duckdb/common/types/blob.hpp"
#include "duckdb/function/scalar/string_common.hpp"
#include "duckdb/main/secret/secret_manager.hpp"
#include "duckdb/storage/buffer_manager.hpp"
#include "duckdb/common/multi_file/multi_file_list.hpp"
#include "s3_multi_part_upload.hpp"
#include "create_secret_functions.hpp"
#include <iostream>
#include <iostream>
namespace duckdb {
HTTPHeaders CreateS3Header(EncryptionUtil &encryption_util, string url, string query, string host, string service,
string method, const S3AuthParams &auth_params, string date_now, string datetime_now,
string payload_hash, string content_type, string content_md5) {
HTTPHeaders res;
res["Host"] = host;
// If access key is not set, we don't set the headers at all to allow accessing public files through s3 urls
if (auth_params.secret_access_key.empty() && auth_params.access_key_id.empty()) {
return res;
}
if (payload_hash == "") {
payload_hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; // Empty payload hash
}
// we can pass date/time but this is mostly useful in testing. normally we just get the current datetime here.
if (datetime_now.empty()) {
auto timestamp = Timestamp::GetCurrentTimestamp();
date_now = StrfTimeFormat::Format(timestamp, "%Y%m%d");
datetime_now = StrfTimeFormat::Format(timestamp, "%Y%m%dT%H%M%SZ");
}
// Only some S3 operations supports SSE-KMS, which this "heuristic" attempts to detect.
// https://docs.aws.amazon.com/AmazonS3/latest/userguide/specifying-kms-encryption.html#sse-request-headers-kms
bool use_sse_kms = auth_params.kms_key_id.length() > 0 && (method == "POST" || method == "PUT") &&
query.find("uploadId") == std::string::npos;
res["x-amz-date"] = datetime_now;
res["x-amz-content-sha256"] = payload_hash;
if (auth_params.session_token.length() > 0) {
res["x-amz-security-token"] = auth_params.session_token;
}
if (use_sse_kms) {
res["x-amz-server-side-encryption"] = "aws:kms";
res["x-amz-server-side-encryption-aws-kms-key-id"] = auth_params.kms_key_id;
}
bool use_requester_pays = auth_params.requester_pays;
if (use_requester_pays) {
res["x-amz-request-payer"] = "requester";
}
string signed_headers = "";
hash_bytes canonical_request_hash;
hash_str canonical_request_hash_str;
if (content_md5.length() > 0) {
signed_headers += "content-md5;";
res["content-md5"] = content_md5;
}
if (content_type.length() > 0) {
signed_headers += "content-type;";
if (content_type != "application/octet-stream") {
res["content-type"] = content_type;
}
}
signed_headers += "host;x-amz-content-sha256;x-amz-date";
if (use_requester_pays) {
signed_headers += ";x-amz-request-payer";
}
if (auth_params.session_token.length() > 0) {
signed_headers += ";x-amz-security-token";
}
if (use_sse_kms) {
signed_headers += ";x-amz-server-side-encryption;x-amz-server-side-encryption-aws-kms-key-id";
}
auto canonical_request = method + "\n" + S3FileSystem::UrlEncode(url) + "\n" + query;
if (content_md5.length() > 0) {
canonical_request += "\ncontent-md5:" + content_md5;
}
if (content_type.length() > 0) {
canonical_request += "\ncontent-type:" + content_type;
}
canonical_request += "\nhost:" + host + "\nx-amz-content-sha256:" + payload_hash + "\nx-amz-date:" + datetime_now;
if (use_requester_pays) {
canonical_request += "\nx-amz-request-payer:requester";
}
if (auth_params.session_token.length() > 0) {
canonical_request += "\nx-amz-security-token:" + auth_params.session_token;
}
if (use_sse_kms) {
canonical_request += "\nx-amz-server-side-encryption:aws:kms";
canonical_request += "\nx-amz-server-side-encryption-aws-kms-key-id:" + auth_params.kms_key_id;
}
canonical_request += "\n\n" + signed_headers + "\n" + payload_hash;
sha256(encryption_util, canonical_request.c_str(), canonical_request.length(), canonical_request_hash);
hex256(canonical_request_hash, canonical_request_hash_str);
auto string_to_sign = "AWS4-HMAC-SHA256\n" + datetime_now + "\n" + date_now + "/" + auth_params.region + "/" +
service + "/aws4_request\n" + string((char *)canonical_request_hash_str, sizeof(hash_str));
// compute signature
hash_bytes k_date, k_region, k_service, signing_key, signature;
hash_str signature_str;
auto sign_key = "AWS4" + auth_params.secret_access_key;
hmac256(encryption_util, date_now, sign_key.c_str(), sign_key.length(), k_date);
hmac256(encryption_util, auth_params.region, k_date, k_region);
hmac256(encryption_util, service, k_region, k_service);
hmac256(encryption_util, "aws4_request", k_service, signing_key);
hmac256(encryption_util, string_to_sign, signing_key, signature);
hex256(signature, signature_str);
res["Authorization"] = "AWS4-HMAC-SHA256 Credential=" + auth_params.access_key_id + "/" + date_now + "/" +
auth_params.region + "/" + service + "/aws4_request, SignedHeaders=" + signed_headers +
", Signature=" + string((char *)signature_str, sizeof(hash_str));
return res;
}
string S3FileSystem::UrlDecode(string input) {
return StringUtil::URLDecode(input, true);
}
string S3FileSystem::UrlEncode(const string &input, bool encode_slash) {
return StringUtil::URLEncode(input, encode_slash);
}
static bool IsGCSRequest(const string &url) {
return StringUtil::StartsWith(url, "gcs://") || StringUtil::StartsWith(url, "gs://");
}
void AWSEnvironmentCredentialsProvider::SetExtensionOptionValue(string key, const char *env_var_name) {
char *evar;
if ((evar = std::getenv(env_var_name)) != NULL) {
if (StringUtil::Lower(evar) == "false") {
this->config.SetOption(key, Value(false));
} else if (StringUtil::Lower(evar) == "true") {
this->config.SetOption(key, Value(true));
} else {
this->config.SetOption(key, Value(evar));
}
}
}
void AWSEnvironmentCredentialsProvider::SetAll() {
this->SetExtensionOptionValue("s3_region", DEFAULT_REGION_ENV_VAR);
this->SetExtensionOptionValue("s3_region", REGION_ENV_VAR);
this->SetExtensionOptionValue("s3_access_key_id", ACCESS_KEY_ENV_VAR);
this->SetExtensionOptionValue("s3_secret_access_key", SECRET_KEY_ENV_VAR);
this->SetExtensionOptionValue("s3_session_token", SESSION_TOKEN_ENV_VAR);
this->SetExtensionOptionValue("s3_endpoint", DUCKDB_ENDPOINT_ENV_VAR);
this->SetExtensionOptionValue("s3_use_ssl", DUCKDB_USE_SSL_ENV_VAR);
this->SetExtensionOptionValue("s3_kms_key_id", DUCKDB_KMS_KEY_ID_ENV_VAR);
this->SetExtensionOptionValue("s3_requester_pays", DUCKDB_REQUESTER_PAYS_ENV_VAR);
}
S3AuthParams S3AuthParams::ReadFrom(optional_ptr<FileOpener> opener, FileOpenerInfo &info) {
// Without a FileOpener we can not access settings nor secrets: return empty auth params
if (!opener) {
return {};
}
const char *secret_types[] = {"s3", "r2", "gcs", "aws"};
S3KeyValueReader secret_reader(*opener, info, secret_types, 4);
return ReadFrom(secret_reader, info.file_path);
}
bool EndpointIsAWS(const string &endpoint) {
if (endpoint.empty()) {
// default (empty) endpoint is AWS
return true;
}
if (StringUtil::StartsWith(endpoint, "s3.") && StringUtil::EndsWith(endpoint, ".amazonaws.com")) {
return true;
}
return false;
}
void S3AuthParams::InitializeEndpoint() {
if (!EndpointIsAWS(endpoint)) {
return;
}
if (region.empty()) {
if (access_key_id.empty()) {
// no access key and no region - use legacy global endpoint
endpoint = "s3.amazonaws.com";
return;
}
// access key but no region - default to us-east-1
region = "us-east-1";
}
endpoint = StringUtil::Format("s3.%s.amazonaws.com", region);
}
S3AuthParams S3AuthParams::ReadFrom(S3KeyValueReader &secret_reader, const string &file_path) {
auto result = S3AuthParams();
// These settings we just set or leave to their S3AuthParams default value
secret_reader.TryGetSecretKeyOrSetting("region", "s3_region", result.region);
secret_reader.TryGetSecretKeyOrSetting("key_id", "s3_access_key_id", result.access_key_id);
secret_reader.TryGetSecretKeyOrSetting("secret", "s3_secret_access_key", result.secret_access_key);
secret_reader.TryGetSecretKeyOrSetting("session_token", "s3_session_token", result.session_token);
secret_reader.TryGetSecretKeyOrSetting("region", "s3_region", result.region);
secret_reader.TryGetSecretKeyOrSetting("use_ssl", "s3_use_ssl", result.use_ssl);
secret_reader.TryGetSecretKeyOrSetting("kms_key_id", "s3_kms_key_id", result.kms_key_id);
secret_reader.TryGetSecretKeyOrSetting("s3_url_compatibility_mode", "s3_url_compatibility_mode",
result.s3_url_compatibility_mode);
secret_reader.TryGetSecretKeyOrSetting("requester_pays", "s3_requester_pays", result.requester_pays);
// Endpoint and url style are slightly more complex and require special handling for gcs and r2
auto endpoint_result = secret_reader.TryGetSecretKeyOrSetting("endpoint", "s3_endpoint", result.endpoint);
auto url_style_result = secret_reader.TryGetSecretKeyOrSetting("url_style", "s3_url_style", result.url_style);
if (StringUtil::StartsWith(file_path, "gcs://") || StringUtil::StartsWith(file_path, "gs://")) {
// For GCS urls we force the endpoint and vhost path style, allowing only to be overridden by secrets
if (result.endpoint.empty() || !endpoint_result || endpoint_result.GetScope() != SettingScope::SECRET) {
result.endpoint = "storage.googleapis.com";
}
if (result.url_style.empty() || !url_style_result || url_style_result.GetScope() != SettingScope::SECRET) {
result.url_style = "path";
}
// Read bearer token for GCS
secret_reader.TryGetSecretKey("bearer_token", result.oauth2_bearer_token);
}
result.InitializeEndpoint();
return result;
}
void S3AuthParams::SetRegion(string new_region) {
region = std::move(new_region);
InitializeEndpoint();
}
unique_ptr<KeyValueSecret> CreateSecret(vector<string> &prefix_paths_p, string &type, string &provider, string &name,
S3AuthParams ¶ms) {
auto return_value =
make_uniq<KeyValueSecret>(prefix_paths_p, Identifier(type), Identifier(provider), Identifier(name));
//! Set key value map
return_value->secret_map["region"] = params.region;
return_value->secret_map["key_id"] = params.access_key_id;
return_value->secret_map["secret"] = params.secret_access_key;
return_value->secret_map["session_token"] = params.session_token;
return_value->secret_map["endpoint"] = params.endpoint;
return_value->secret_map["url_style"] = params.url_style;
return_value->secret_map["use_ssl"] = params.use_ssl;
return_value->secret_map["kms_key_id"] = params.kms_key_id;
return_value->secret_map["s3_url_compatibility_mode"] = params.s3_url_compatibility_mode;
return_value->secret_map["requester_pays"] = params.requester_pays;
return_value->secret_map["bearer_token"] = params.oauth2_bearer_token;
//! Set redact keys
return_value->redact_keys = {"secret", "session_token"};
if (!params.oauth2_bearer_token.empty()) {
return_value->redact_keys.insert("bearer_token");
}
return return_value;
}
S3HTTPInput::S3HTTPInput(unique_ptr<HTTPParams> params_p, const S3AuthParams &auth_params_p,
const S3ConfigParams &config_params_p)
: HTTPInput(std::move(params_p)), auth_params(auth_params_p), config_params(config_params_p) {
}
S3HTTPInput::~S3HTTPInput() {
}
S3FileHandle::S3FileHandle(FileSystem &fs, const OpenFileInfo &file, FileOpenFlags flags,
unique_ptr<HTTPParams> http_params_p, const S3AuthParams &auth_params_p,
const S3ConfigParams &config_params_p)
: HTTPFileHandle(fs, file, flags,
make_shared_ptr<S3HTTPInput>(std::move(http_params_p), auth_params_p, config_params_p)),
auth_params(http_input->Cast<S3HTTPInput>().auth_params),
config_params(http_input->Cast<S3HTTPInput>().config_params) {
auto_fallback_to_full_file_download = false;
if (flags.OpenForReading() && flags.OpenForWriting()) {
throw NotImplementedException("Cannot open an HTTP file for both reading and writing");
} else if (flags.OpenForAppending()) {
throw NotImplementedException("Cannot open an HTTP file for appending");
}
if (file.extended_info) {
auto entry = file.extended_info->options.find("s3_region");
if (entry != file.extended_info->options.end()) {
SetRegion(entry->second.ToString());
}
}
if (flags.OpenForWriting()) {
multi_part_upload = make_shared_ptr<S3MultiPartUpload>(*this);
}
}
S3FileHandle::~S3FileHandle() {
if (Exception::UncaughtException()) {
// We are in an exception, don't do anything
return;
}
try {
Close();
} catch (...) { // NOLINT
}
}
void S3FileHandle::SetRegion(string region_p) {
auth_params.SetRegion(std::move(region_p));
client_cache.Clear();
}
S3ConfigParams S3ConfigParams::ReadFrom(optional_ptr<FileOpener> opener) {
uint64_t uploader_max_filesize;
uint64_t max_parts_per_file;
uint64_t max_upload_threads;
Value value;
if (FileOpener::TryGetCurrentSetting(opener, "s3_uploader_max_filesize", value)) {
uploader_max_filesize = DBConfig::ParseMemoryLimit(value.GetValue<string>());
} else {
uploader_max_filesize = S3ConfigParams::DEFAULT_MAX_FILESIZE;
}
if (FileOpener::TryGetCurrentSetting(opener, "s3_uploader_max_parts_per_file", value)) {
max_parts_per_file = value.GetValue<uint64_t>();
} else {
max_parts_per_file = S3ConfigParams::DEFAULT_MAX_PARTS_PER_FILE; // AWS Default
}
if (FileOpener::TryGetCurrentSetting(opener, "s3_uploader_thread_limit", value)) {
max_upload_threads = value.GetValue<uint64_t>();
} else {
max_upload_threads = S3ConfigParams::DEFAULT_MAX_UPLOAD_THREADS;
}
return {uploader_max_filesize, max_parts_per_file, max_upload_threads};
}
void S3FileHandle::Close() {
FinalizeUpload();
}
void S3FileHandle::FinalizeUpload() {
if (flags.OpenForWriting() && multi_part_upload) {
multi_part_upload->Finalize();
}
}
unique_ptr<HTTPClient> S3FileHandle::CreateClient() {
auto parsed_url = S3FileSystem::S3UrlParse(path, this->auth_params);
string proto_host_port = parsed_url.http_proto + parsed_url.host;
return http_params.http_util.InitializeClient(http_params, proto_host_port);
}
// Wrapper around the BufferManager::Allocate to that allows limiting the number of buffers that will be handed out
BufferHandle S3FileSystem::Allocate(idx_t part_size, uint16_t max_threads) {
return buffer_manager.Allocate(MemoryTag::EXTENSION, part_size);
}
void GetQueryParam(const string &key, string ¶m, unordered_map<string, string> &query_params) {
auto found_param = query_params.find(key);
if (found_param != query_params.end()) {
param = found_param->second;
query_params.erase(found_param);
}
}
void S3FileSystem::ReadQueryParams(const string &url_query_param, S3AuthParams ¶ms) {
if (url_query_param.empty()) {
return;
}
auto query_params = HTTPFSUtil::ParseGetParameters(url_query_param);
GetQueryParam("s3_region", params.region, query_params);
GetQueryParam("s3_access_key_id", params.access_key_id, query_params);
GetQueryParam("s3_secret_access_key", params.secret_access_key, query_params);
GetQueryParam("s3_session_token", params.session_token, query_params);
GetQueryParam("s3_endpoint", params.endpoint, query_params);
GetQueryParam("s3_url_style", params.url_style, query_params);
auto found_param = query_params.find("s3_use_ssl");
if (found_param != query_params.end()) {
if (found_param->second == "true") {
params.use_ssl = true;
} else if (found_param->second == "false") {
params.use_ssl = false;
} else {
throw IOException("Incorrect setting found for s3_use_ssl, allowed values are: 'true' or 'false'");
}
query_params.erase(found_param);
}
auto found_requester_pays_param = query_params.find("s3_requester_pays");
if (found_requester_pays_param != query_params.end()) {
if (found_requester_pays_param->second == "true") {
params.requester_pays = true;
} else if (found_requester_pays_param->second == "false") {
params.requester_pays = false;
} else {
throw IOException("Incorrect setting found for s3_requester_pays, allowed values are: 'true' or 'false'");
}
query_params.erase(found_requester_pays_param);
}
if (!query_params.empty()) {
throw IOException("Invalid query parameters found. Supported parameters are:\n's3_region', 's3_access_key_id', "
"'s3_secret_access_key', 's3_session_token',\n's3_endpoint', 's3_url_style', 's3_use_ssl', "
"'s3_requester_pays'");
}
}
string S3FileSystem::TryGetPrefix(const string &url) {
const string prefixes[] = {"s3://", "s3a://", "s3n://", "gcs://", "gs://", "r2://"};
for (auto &prefix : prefixes) {
if (StringUtil::StartsWith(StringUtil::Lower(url), prefix)) {
return prefix;
}
}
return {};
}
string S3FileSystem::GetPrefix(const string &url) {
auto prefix = TryGetPrefix(url);
if (prefix.empty()) {
throw IOException("URL needs to start with s3://, gcs:// or r2://");
}
return prefix;
}
ParsedS3Url S3FileSystem::S3UrlParse(string url, const S3AuthParams ¶ms) {
string http_proto, prefix, host, bucket, key, path, query_param, trimmed_s3_url;
prefix = GetPrefix(url);
auto prefix_end_pos = url.find("//") + 2;
auto slash_pos = url.find('/', prefix_end_pos);
if (slash_pos == string::npos) {
throw IOException("URL needs to contain a '/' after the host");
}
bucket = url.substr(prefix_end_pos, slash_pos - prefix_end_pos);
if (bucket.empty()) {
throw IOException("URL needs to contain a bucket name");
}
if (params.s3_url_compatibility_mode) {
// In url compatibility mode, we will ignore any special chars, so query param strings are disabled
trimmed_s3_url = url;
key += url.substr(slash_pos);
} else {
// Parse query parameters
auto question_pos = url.find_first_of('?');
if (question_pos != string::npos) {
query_param = url.substr(question_pos + 1);
trimmed_s3_url = url.substr(0, question_pos);
} else {
trimmed_s3_url = url;
}
if (!query_param.empty()) {
key += url.substr(slash_pos, question_pos - slash_pos);
} else {
key += url.substr(slash_pos);
}
}
if (key.empty()) {
throw IOException("URL needs to contain key");
}
// Derived host and path based on the endpoint
auto sub_path_pos = params.endpoint.find_first_of('/');
if (sub_path_pos != string::npos) {
// Host header should conform to <host>:<port> so not include the path
host = params.endpoint.substr(0, sub_path_pos);
path = params.endpoint.substr(sub_path_pos);
} else {
host = params.endpoint;
path = "";
}
// Update host and path according to the url style
// See https://docs.aws.amazon.com/AmazonS3/latest/userguide/VirtualHosting.html
if (params.url_style == "vhost" || params.url_style == "virtual" || params.url_style == "") {
host = bucket + "." + host;
} else if (params.url_style == "path") {
path += "/" + bucket;
}
// Append key (including leading slash) to the path
path += key;
// Remove leading slash from key
key = key.substr(1);
http_proto = params.use_ssl ? "https://" : "http://";
return {http_proto, prefix, host, bucket, key, path, query_param, trimmed_s3_url};
}
EncryptionUtil &S3FileSystem::GetEncryptionUtil() {
auto &config = DBConfig::GetConfig(buffer_manager.GetDatabase());
if (!config.encryption_util) {
throw InternalException("HTTPFS encryption util has not been initialized");
}
return *config.encryption_util;
}
string S3FileSystem::GetPayloadHash(char *buffer, idx_t buffer_len) {
if (buffer_len > 0) {
hash_bytes payload_hash_bytes;
hash_str payload_hash_str;
sha256(GetEncryptionUtil(), buffer, buffer_len, payload_hash_bytes);
hex256(payload_hash_bytes, payload_hash_str);
return string((char *)payload_hash_str, sizeof(payload_hash_str));
} else {
return "";
}
}
string ParsedS3Url::GetHTTPUrl(S3AuthParams &auth_params, const string &http_query_string) {
string full_url = http_proto + host + S3FileSystem::UrlEncode(path);
if (!http_query_string.empty()) {
full_url += "?" + http_query_string;
}
return full_url;
}
unique_ptr<HTTPResponse> S3FileSystem::PostRequest(HTTPInput &input, string url, HTTPHeaders header_map, string &result,
char *buffer_in, idx_t buffer_in_len, string http_params) {
auto &s3_input = input.Cast<S3HTTPInput>();
auto auth_params = s3_input.auth_params;
auto parsed_s3_url = S3UrlParse(url, auth_params);
string http_url = parsed_s3_url.GetHTTPUrl(auth_params, http_params);
HTTPHeaders headers;
if (IsGCSRequest(url) && !auth_params.oauth2_bearer_token.empty()) {
// Use bearer token for GCS
headers["Authorization"] = "Bearer " + auth_params.oauth2_bearer_token;
headers["Host"] = parsed_s3_url.host;
headers["Content-Type"] = "application/octet-stream";
} else {
// Use existing S3 authentication
auto payload_hash = GetPayloadHash(buffer_in, buffer_in_len);
headers = CreateS3Header(GetEncryptionUtil(), parsed_s3_url.path, http_params, parsed_s3_url.host, "s3", "POST",
auth_params, "", "", payload_hash, "application/octet-stream");
}
return HTTPFileSystem::PostRequest(input, http_url, headers, result, buffer_in, buffer_in_len);
}
unique_ptr<HTTPResponse> S3FileSystem::PutRequest(HTTPInput &input, string url, HTTPHeaders header_map, char *buffer_in,
idx_t buffer_in_len, string http_params) {
auto &s3_input = input.Cast<S3HTTPInput>();
auto auth_params = s3_input.auth_params;
auto parsed_s3_url = S3UrlParse(url, auth_params);
string http_url = parsed_s3_url.GetHTTPUrl(auth_params, http_params);
auto content_type = "application/octet-stream";
HTTPHeaders headers;
if (IsGCSRequest(url) && !auth_params.oauth2_bearer_token.empty()) {
// Use bearer token for GCS
headers["Authorization"] = "Bearer " + auth_params.oauth2_bearer_token;
headers["Host"] = parsed_s3_url.host;
headers["Content-Type"] = content_type;
} else {
// Use existing S3 authentication
auto payload_hash = GetPayloadHash(buffer_in, buffer_in_len);
headers = CreateS3Header(GetEncryptionUtil(), parsed_s3_url.path, http_params, parsed_s3_url.host, "s3", "PUT",
auth_params, "", "", payload_hash, content_type);
}
return HTTPFileSystem::PutRequest(input, http_url, headers, buffer_in, buffer_in_len);
}
unique_ptr<HTTPResponse> S3FileSystem::HeadRequest(FileHandle &handle, string s3_url, HTTPHeaders header_map) {
auto auth_params = handle.Cast<S3FileHandle>().auth_params;
auto parsed_s3_url = S3UrlParse(s3_url, auth_params);
string http_url = parsed_s3_url.GetHTTPUrl(auth_params);
HTTPHeaders headers;
if (IsGCSRequest(s3_url) && !auth_params.oauth2_bearer_token.empty()) {
// Use bearer token for GCS
headers["Authorization"] = "Bearer " + auth_params.oauth2_bearer_token;
headers["Host"] = parsed_s3_url.host;
} else {
// Use existing S3 authentication
headers = CreateS3Header(GetEncryptionUtil(), parsed_s3_url.path, "", parsed_s3_url.host, "s3", "HEAD",
auth_params, "", "", "", "");
}
return HTTPFileSystem::HeadRequest(handle, http_url, headers);
}
unique_ptr<HTTPResponse> S3FileSystem::GetRequest(FileHandle &handle, string s3_url, HTTPHeaders header_map) {
auto &s3_handle = handle.Cast<S3FileHandle>();
auto auth_params = s3_handle.auth_params;
auto parsed_s3_url = S3UrlParse(s3_url, auth_params);
string query_string;
if (!s3_handle.version_id.empty()) {
query_string = "versionId=" + UrlEncode(s3_handle.version_id, true);
}
string http_url = parsed_s3_url.GetHTTPUrl(auth_params, query_string);
HTTPHeaders headers;
if (IsGCSRequest(s3_url) && !auth_params.oauth2_bearer_token.empty()) {
// Use bearer token for GCS
headers["Authorization"] = "Bearer " + auth_params.oauth2_bearer_token;
headers["Host"] = parsed_s3_url.host;
} else {
// Use existing S3 authentication
headers = CreateS3Header(GetEncryptionUtil(), parsed_s3_url.path, query_string, parsed_s3_url.host, "s3", "GET",
auth_params, "", "", "", "");
}
return HTTPFileSystem::GetRequest(handle, http_url, headers);
}
unique_ptr<HTTPResponse> S3FileSystem::GetRangeRequest(FileHandle &handle, string s3_url, HTTPHeaders header_map,
idx_t file_offset, char *buffer_out, idx_t buffer_out_len) {
auto &s3_handle = handle.Cast<S3FileHandle>();
auto auth_params = s3_handle.auth_params;
auto parsed_s3_url = S3UrlParse(s3_url, auth_params);
string query_string;
if (!s3_handle.version_id.empty()) {
query_string = "versionId=" + UrlEncode(s3_handle.version_id, true);
}
string http_url = parsed_s3_url.GetHTTPUrl(auth_params, query_string);
HTTPHeaders headers;
if (IsGCSRequest(s3_url) && !auth_params.oauth2_bearer_token.empty()) {
// Use bearer token for GCS
headers["Authorization"] = "Bearer " + auth_params.oauth2_bearer_token;
headers["Host"] = parsed_s3_url.host;
} else {
// Use existing S3 authentication
headers = CreateS3Header(GetEncryptionUtil(), parsed_s3_url.path, query_string, parsed_s3_url.host, "s3", "GET",
auth_params, "", "", "", "");
}
return HTTPFileSystem::GetRangeRequest(handle, http_url, headers, file_offset, buffer_out, buffer_out_len);
}
unique_ptr<HTTPResponse> S3FileSystem::DeleteRequest(FileHandle &handle, string s3_url, HTTPHeaders header_map) {
auto auth_params = handle.Cast<S3FileHandle>().auth_params;
auto parsed_s3_url = S3UrlParse(s3_url, auth_params);
string http_url = parsed_s3_url.GetHTTPUrl(auth_params);
HTTPHeaders headers;
if (IsGCSRequest(s3_url) && !auth_params.oauth2_bearer_token.empty()) {
// Use bearer token for GCS
headers["Authorization"] = "Bearer " + auth_params.oauth2_bearer_token;
headers["Host"] = parsed_s3_url.host;
} else {
// Use existing S3 authentication
headers = CreateS3Header(GetEncryptionUtil(), parsed_s3_url.path, "", parsed_s3_url.host, "s3", "DELETE",
auth_params, "", "", "", "");
}
return HTTPFileSystem::DeleteRequest(handle, http_url, headers);
}
unique_ptr<HTTPFileHandle> S3FileSystem::CreateHandle(const OpenFileInfo &file, FileOpenFlags flags,
optional_ptr<FileOpener> opener) {
FileOpenerInfo info = {file.path};
S3AuthParams auth_params = S3AuthParams::ReadFrom(opener, info);
// Scan the query string for any s3 authentication parameters
auto parsed_s3_url = S3UrlParse(file.path, auth_params);
ReadQueryParams(parsed_s3_url.query_param, auth_params);
auto &http_util = HTTPFSUtil::GetHTTPUtil(opener);
auto params = http_util.InitializeParameters(opener, info);
return duckdb::make_uniq<S3FileHandle>(*this, file, flags, std::move(params), auth_params,
S3ConfigParams::ReadFrom(opener));
}
void S3FileHandle::InitializeFromCacheEntry(const HTTPMetadataCacheEntry &cache_entry) {
HTTPFileHandle::InitializeFromCacheEntry(cache_entry);
auto entry = cache_entry.properties.find("s3_region");
if (entry != cache_entry.properties.end()) {
SetRegion(entry->second);
}
}
HTTPMetadataCacheEntry S3FileHandle::GetCacheEntry() const {
auto result = HTTPFileHandle::GetCacheEntry();
if (!auth_params.region.empty()) {
result.properties["s3_region"] = auth_params.region;
}
return result;
}
void S3FileHandle::Initialize(optional_ptr<FileOpener> opener) {
try {
HTTPFileHandle::Initialize(opener);
} catch (std::exception &ex) {
ErrorData error(ex);
bool refreshed_secret = false;
if (error.Type() == ExceptionType::IO || error.Type() == ExceptionType::HTTP) {
// legacy endpoint (no region) returns 400
auto context = opener->TryGetClientContext();
if (context) {
auto transaction = CatalogTransaction::GetSystemCatalogTransaction(*context);
for (const string type : {"s3", "r2", "gcs", "aws"}) {
auto res = context->db->GetSecretManager().LookupSecret(transaction, path, type);
if (res.HasMatch()) {
refreshed_secret |= CreateS3SecretFunctions::TryRefreshS3Secret(*context, *res.secret_entry);
}
}
}
}
string correct_region;
if (!refreshed_secret) {
auto &extra_info = error.ExtraInfo();
auto entry = extra_info.find("status_code");
if (entry != extra_info.end()) {
if (entry->second == "301" || entry->second == "400") {
auto new_region = extra_info.find("header_x-amz-bucket-region");
if (new_region != extra_info.end()) {
correct_region = new_region->second;
}
}
if (entry->second == "403") {
// 403: FORBIDDEN
string extra_text;
if (IsGCSRequest(path)) {
extra_text = S3FileSystem::GetGCSAuthError(auth_params);
} else {
extra_text = S3FileSystem::GetS3AuthError(auth_params);
}
throw Exception(extra_info, error.Type(), error.RawMessage() + extra_text);
}
}
if (correct_region.empty()) {
throw;
}
}
// We have succesfully refreshed a secret: retry initializing with new credentials
FileOpenerInfo info = {path};
auth_params = S3AuthParams::ReadFrom(opener, info);
if (!correct_region.empty()) {
DUCKDB_LOG_WARNING(
logger,
"Read S3 file \"%s\" from incorrect region \"%s\" - retrying with updated region \"%s\".\n"
"Consider setting the S3 region to this explicitly to avoid extra round-trips.",
path, auth_params.region, correct_region);
SetRegion(std::move(correct_region));
}
ResetDownloadState();
HTTPFileHandle::Initialize(opener);
}
if (flags.OpenForWriting()) {
auto aws_minimum_part_size = 5242880; // 5 MiB https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html
auto max_part_count = config_params.max_parts_per_file;
auto required_part_size = config_params.max_file_size / max_part_count;
auto minimum_part_size = MaxValue<idx_t>(aws_minimum_part_size, required_part_size);
// Round part size up to multiple of Storage::DEFAULT_BLOCK_SIZE
multi_part_upload->part_size =
((minimum_part_size + Storage::DEFAULT_BLOCK_SIZE - 1) / Storage::DEFAULT_BLOCK_SIZE) *
Storage::DEFAULT_BLOCK_SIZE;
D_ASSERT(multi_part_upload->part_size * max_part_count >= config_params.max_file_size);
}
}
bool S3FileSystem::CanHandleFile(const string &fpath) {
return fpath.rfind("s3://", 0) * fpath.rfind("s3a://", 0) * fpath.rfind("s3n://", 0) * fpath.rfind("gcs://", 0) *
fpath.rfind("gs://", 0) * fpath.rfind("r2://", 0) ==
0;
}
void S3FileSystem::RemoveFile(const string &path, optional_ptr<FileOpener> opener) {
auto handle = OpenFile(path, FileFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS, opener);
if (!handle) {
throw IOException({{"errno", "404"}}, "Could not remove file \"%s\": %s", path,
string("No such file or directory"));
}
auto &s3fh = handle->Cast<S3FileHandle>();
auto res = DeleteRequest(*handle, s3fh.path, {});
if (res->status != HTTPStatusCode::OK_200 && res->status != HTTPStatusCode::NoContent_204) {
throw IOException({{"errno", to_string(static_cast<int>(res->status))}}, "Could not remove file \"%s\": %s",
path, res->GetError());
}
}
// Forward declaration for FindTagContents (defined later in file)
optional_idx FindTagContents(const string &response, const string &tag, idx_t cur_pos, string &result);
void S3FileSystem::RemoveFiles(const vector<string> &paths, optional_ptr<FileOpener> opener) {
if (paths.empty()) {
return;
}
struct BucketUrlInfo {
string prefix;
string http_proto;
string host;
string path;
S3AuthParams auth_params;
};
unordered_map<string, vector<string>> keys_by_bucket;
unordered_map<string, BucketUrlInfo> url_info_by_bucket;
for (auto &path : paths) {
FileOpenerInfo info = {path};
S3AuthParams auth_params = S3AuthParams::ReadFrom(opener, info);
auto parsed_url = S3UrlParse(path, auth_params);
ReadQueryParams(parsed_url.query_param, auth_params);
const string &bucket = parsed_url.bucket;
if (keys_by_bucket.find(bucket) == keys_by_bucket.end()) {
string bucket_path = parsed_url.path.substr(0, parsed_url.path.length() - parsed_url.key.length());
if (bucket_path.empty()) {
bucket_path = "/";
}
url_info_by_bucket[bucket] = {parsed_url.prefix, parsed_url.http_proto, parsed_url.host, bucket_path,
auth_params};
}
keys_by_bucket[bucket].push_back(parsed_url.key);
}
constexpr idx_t MAX_KEYS_PER_REQUEST = 1000;
for (auto &bucket_entry : keys_by_bucket) {
const string &bucket = bucket_entry.first;
const vector<string> &keys = bucket_entry.second;
const auto &url_info = url_info_by_bucket[bucket];
for (idx_t batch_start = 0; batch_start < keys.size(); batch_start += MAX_KEYS_PER_REQUEST) {
idx_t batch_end = MinValue<idx_t>(batch_start + MAX_KEYS_PER_REQUEST, keys.size());
std::stringstream xml_body;
xml_body << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
xml_body << "<Delete xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">";
for (idx_t i = batch_start; i < batch_end; i++) {
xml_body << "<Object><Key>" << keys[i] << "</Key></Object>";
}
xml_body << "<Quiet>true</Quiet>";
xml_body << "</Delete>";
string body = xml_body.str();
MD5Context md5_context;
md5_context.Add(body);
data_t md5_hash[MD5Context::MD5_HASH_LENGTH_BINARY];
md5_context.Finish(md5_hash);
string_t md5_blob(const_char_ptr_cast(md5_hash), MD5Context::MD5_HASH_LENGTH_BINARY);
string content_md5 = Blob::ToBase64(md5_blob);
const string http_query_param_for_sig = "delete=";
const string http_query_param_for_url = "delete";
auto payload_hash = GetPayloadHash(const_cast<char *>(body.data()), body.length());
auto headers =
CreateS3Header(GetEncryptionUtil(), url_info.path, http_query_param_for_sig, url_info.host, "s3",
"POST", url_info.auth_params, "", "", payload_hash, "application/xml", content_md5);
string http_url = url_info.http_proto + url_info.host + S3FileSystem::UrlEncode(url_info.path) + "?" +
http_query_param_for_url;
string bucket_url = url_info.prefix + bucket + "/";
FileOpenerInfo info = {bucket_url};
auto &http_util = HTTPFSUtil::GetHTTPUtil(opener);
auto http_params = http_util.InitializeParameters(opener, info);
S3HTTPInput http_input(std::move(http_params), url_info.auth_params, S3ConfigParams::ReadFrom(opener));
string result;
auto res = HTTPFileSystem::PostRequest(http_input, http_url, headers, result,
const_cast<char *>(body.data()), body.length());
if (res->status != HTTPStatusCode::OK_200) {
throw IOException("Failed to remove files: HTTP %d (%s)\n%s", static_cast<int>(res->status),
res->GetError(), result);
}
idx_t cur_pos = 0;
string error_content;
auto error_pos = FindTagContents(result, "Error", cur_pos, error_content);
if (error_pos.IsValid()) {
throw IOException("Failed to remove files: %s", error_content);
}
}
}
}
void S3FileSystem::RemoveDirectory(const string &path, optional_ptr<FileOpener> opener) {
vector<string> files_to_remove;
ListFiles(
path, [&](const string &file, bool is_dir) { files_to_remove.push_back(file); }, opener.get());
RemoveFiles(files_to_remove, opener);
}
void S3FileSystem::FileSync(FileHandle &handle) {
auto &s3fh = handle.Cast<S3FileHandle>();
s3fh.FinalizeUpload();
}
void S3FileSystem::Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) {
auto &s3fh = handle.Cast<S3FileHandle>();
if (!s3fh.flags.OpenForWriting()) {
throw InternalException("Write called on file not opened in write mode");
}
int64_t bytes_written = 0;
while (bytes_written < nr_bytes) {
auto curr_location = location + bytes_written;
if (curr_location != s3fh.file_offset) {
throw InternalException("Non-sequential write not supported!");
}
// Find buffer for writing
auto part_size = s3fh.multi_part_upload->part_size;
auto write_buffer_idx = curr_location / part_size;
// Get write buffer, may block until buffer is available
auto write_buffer = s3fh.multi_part_upload->GetBuffer(write_buffer_idx);
// Writing to buffer
auto idx_to_write = curr_location - write_buffer->buffer_start;
auto bytes_to_write = MinValue<idx_t>(nr_bytes - bytes_written, part_size - idx_to_write);
memcpy((char *)write_buffer->Ptr() + idx_to_write, (char *)buffer + bytes_written, bytes_to_write);
write_buffer->idx += bytes_to_write;
// Flush to HTTP if full
if (write_buffer->idx >= part_size) {
s3fh.multi_part_upload->FlushBuffer(write_buffer);
}
s3fh.file_offset += bytes_to_write;
s3fh.length += bytes_to_write;
bytes_written += bytes_to_write;
}
DUCKDB_LOG_FILE_SYSTEM_WRITE(handle, bytes_written, s3fh.file_offset - bytes_written);
}
static bool Match(vector<string>::const_iterator key, vector<string>::const_iterator key_end,
vector<string>::const_iterator pattern, vector<string>::const_iterator pattern_end, bool completed) {
if (key == key_end && !completed) {
return true;
}
while (key != key_end && pattern != pattern_end) {
if (*pattern == "**") {
if (std::next(pattern) == pattern_end) {
return true;
}
pattern++;
while (key != key_end) {
if (Match(key, key_end, pattern, pattern_end, completed)) {
return true;
}
key++;
}
if (!completed)
return true;
return false;
}
if (!Glob(key->data(), key->length(), pattern->data(), pattern->length())) {
return false;
}
key++;
pattern++;
}
if (pattern != pattern_end && !completed) {
return true;
}
return key == key_end && pattern == pattern_end;