-
Notifications
You must be signed in to change notification settings - Fork 521
Expand file tree
/
Copy pathHttp.java
More file actions
1917 lines (1668 loc) · 64.8 KB
/
Copy pathHttp.java
File metadata and controls
1917 lines (1668 loc) · 64.8 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
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2025 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.minio;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import io.minio.credentials.Credentials;
import io.minio.errors.MinioException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.ZonedDateTime;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okio.BufferedSink;
import okio.Okio;
/** HTTP utilities. */
public class Http {
public static final MediaType DEFAULT_MEDIA_TYPE = MediaType.parse("application/octet-stream");
public static final MediaType XML_MEDIA_TYPE = MediaType.parse("application/xml");
public static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json");
public static final String US_EAST_1 = "us-east-1";
public static final long DEFAULT_TIMEOUT = TimeUnit.MINUTES.toMillis(5);
public static final Body EMPTY_BODY =
new Body(
Utils.EMPTY_BYTE_ARRAY,
0,
DEFAULT_MEDIA_TYPE,
Checksum.ZERO_SHA256_HASH,
Checksum.ZERO_MD5_HASH);
public static final Set<Integer> RETRIABLE_STATUS_CODES =
ImmutableSet.of(
408, // Request Timeout
429, // Too Many Requests
499, // Client Closed Request (nginx)
500, // Internal Server Error
502, // Bad Gateway
503, // Service Unavailable
504, // Gateway Timeout
520); // Cloudflare unknown error
public static final String END_HTTP = "----------END-HTTP----------";
public static final String UPLOAD_ID = "uploadId";
public static final Set<String> TRACE_QUERY_PARAMS =
ImmutableSet.of("retention", "legal-hold", "tagging", UPLOAD_ID, "acl", "attributes");
private static final Pattern SIGNATURE_PATTERN = Pattern.compile("Signature=([0-9a-f]+)");
private static final Pattern CREDENTIAL_PATTERN = Pattern.compile("Credential=([^/]+)");
/** Base URL of S3 endpoint. */
public static class BaseUrl {
private okhttp3.HttpUrl url;
private String awsS3Prefix;
private String awsDomainSuffix;
private boolean awsDualstack;
private String region;
private boolean useVirtualStyle;
/** Creates BaseUrl to the specified endpoint. */
public BaseUrl(String endpoint) {
setUrl(parse(endpoint));
}
/** Creates BaseUrl to the specified endpoint, port and secure flag. */
public BaseUrl(String endpoint, int port, boolean secure) {
okhttp3.HttpUrl url = parse(endpoint);
if (port < 1 || port > 65535) {
throw new IllegalArgumentException("port must be in range of 1 to 65535");
}
url = url.newBuilder().port(port).scheme(secure ? "https" : "http").build();
setUrl(url);
}
/** Creates BaseUrl to the specified url. */
public BaseUrl(okhttp3.HttpUrl url) {
Utils.validateNotNull(url, "url");
Utils.validateUrl(url);
setUrl(url);
}
/** Creates BaseUrl to the specified url. */
public BaseUrl(URL url) {
Utils.validateNotNull(url, "url");
setUrl(okhttp3.HttpUrl.get(url));
}
private void setAwsInfo(String host, boolean https) {
this.awsS3Prefix = null;
this.awsDomainSuffix = null;
this.awsDualstack = false;
if (!Utils.HOSTNAME_REGEX.matcher(host).find()) return;
if (Utils.AWS_ELB_ENDPOINT_REGEX.matcher(host).find()) {
String[] tokens = host.split("\\.elb\\.amazonaws\\.com", 1)[0].split("\\.");
this.region = tokens[tokens.length - 1];
return;
}
if (!Utils.AWS_ENDPOINT_REGEX.matcher(host).find()) return;
if (!Utils.AWS_S3_ENDPOINT_REGEX.matcher(host).find()) {
throw new IllegalArgumentException("invalid Amazon AWS host " + host);
}
Matcher matcher = Utils.AWS_S3_PREFIX_REGEX.matcher(host);
matcher.lookingAt();
int end = matcher.end();
this.awsS3Prefix = host.substring(0, end);
if (this.awsS3Prefix.contains("s3-accesspoint") && !https) {
throw new IllegalArgumentException("use HTTPS scheme for host " + host);
}
String[] tokens = host.substring(end).split("\\.");
awsDualstack = "dualstack".equals(tokens[0]);
if (awsDualstack) tokens = Arrays.copyOfRange(tokens, 1, tokens.length);
String regionInHost = null;
if (!tokens[0].equals("vpce") && !tokens[0].equals("amazonaws")) {
regionInHost = tokens[0];
tokens = Arrays.copyOfRange(tokens, 1, tokens.length);
}
this.awsDomainSuffix = String.join(".", tokens);
if (host.equals("s3-external-1.amazonaws.com")) regionInHost = "us-east-1";
if (host.equals("s3-us-gov-west-1.amazonaws.com")
|| host.equals("s3-fips-us-gov-west-1.amazonaws.com")) {
regionInHost = "us-gov-west-1";
}
if (regionInHost != null) this.region = regionInHost;
}
private void setUrl(okhttp3.HttpUrl url) {
this.url = url;
this.setAwsInfo(url.host(), url.isHttps());
this.useVirtualStyle = this.awsDomainSuffix != null || url.host().endsWith("aliyuncs.com");
}
private okhttp3.HttpUrl parse(String endpoint) {
Utils.validateNotEmptyString(endpoint, "endpoint");
okhttp3.HttpUrl url = okhttp3.HttpUrl.parse(endpoint);
if (url == null) {
Utils.validateHostnameOrIPAddress(endpoint);
url = new okhttp3.HttpUrl.Builder().scheme("https").host(endpoint).build();
} else {
Utils.validateUrl(url);
}
return url;
}
/** Checks this base url is HTTPS scheme or not. */
public boolean isHttps() {
return url.isHttps();
}
/** Gets AWS S3 prefix. */
public String awsS3Prefix() {
return awsS3Prefix;
}
/** Gets AWS domain suffix. */
public String awsDomainSuffix() {
return awsDomainSuffix;
}
/** Gets region if present in this base url. */
public String region() {
return region;
}
/** Sets region to this base url. */
public void setRegion(String region) {
this.region = region;
}
/** Enables dual-stack endpoint for Amazon S3 endpoint. */
public void enableDualStackEndpoint() {
awsDualstack = true;
}
/** Disables dual-stack endpoint for Amazon S3 endpoint. */
public void disableDualStackEndpoint() {
awsDualstack = false;
}
/** Enables virtual-style endpoint. */
public void enableVirtualStyleEndpoint() {
useVirtualStyle = true;
}
/** Disables virtual-style endpoint. */
public void disableVirtualStyleEndpoint() {
useVirtualStyle = false;
}
/** Sets AWS S3 domain prefix. */
public void setAwsS3Prefix(@Nonnull String awsS3Prefix) {
if (awsS3Prefix == null)
throw new IllegalArgumentException("null Amazon AWS S3 domain prefix");
if (!Utils.AWS_S3_PREFIX_REGEX.matcher(awsS3Prefix).find()) {
throw new IllegalArgumentException("invalid Amazon AWS S3 domain prefix " + awsS3Prefix);
}
this.awsS3Prefix = awsS3Prefix;
}
private String buildAwsUrl(
okhttp3.HttpUrl.Builder builder,
String bucketName,
boolean enforcePathStyle,
String region) {
String host = this.awsS3Prefix + this.awsDomainSuffix;
if (host.equals("s3-external-1.amazonaws.com")
|| host.equals("s3-us-gov-west-1.amazonaws.com")
|| host.equals("s3-fips-us-gov-west-1.amazonaws.com")) {
builder.host(host);
return host;
}
host = this.awsS3Prefix;
if (this.awsS3Prefix.contains("s3-accelerate")) {
if (bucketName.contains(".")) {
throw new IllegalArgumentException(
"bucket name '" + bucketName + "' with '.' is not allowed for accelerate endpoint");
}
if (enforcePathStyle) host = host.replaceFirst("-accelerate", "");
}
if (this.awsDualstack) host += "dualstack.";
if (!this.awsS3Prefix.contains("s3-accelerate")) host += region + ".";
host += this.awsDomainSuffix;
builder.host(host);
return host;
}
private String buildListBucketsUrl(okhttp3.HttpUrl.Builder builder, String region) {
if (this.awsDomainSuffix == null) return null;
String host = this.awsS3Prefix + this.awsDomainSuffix;
if (host.equals("s3-external-1.amazonaws.com")
|| host.equals("s3-us-gov-west-1.amazonaws.com")
|| host.equals("s3-fips-us-gov-west-1.amazonaws.com")) {
builder.host(host);
return host;
}
String s3Prefix = this.awsS3Prefix;
String domainSuffix = this.awsDomainSuffix;
if (this.awsS3Prefix.startsWith("s3.") || this.awsS3Prefix.startsWith("s3-")) {
s3Prefix = "s3.";
domainSuffix = "amazonaws.com" + (domainSuffix.endsWith(".cn") ? ".cn" : "");
}
host = s3Prefix + region + "." + domainSuffix;
builder.host(host);
return host;
}
/** Builds URL for given parameters. */
public okhttp3.HttpUrl buildUrl(
Method method,
String bucketName,
String objectName,
String region,
QueryParameters queryParams)
throws MinioException {
if (bucketName == null && objectName != null) {
throw new IllegalArgumentException("null bucket name for object '" + objectName + "'");
}
okhttp3.HttpUrl.Builder urlBuilder = this.url.newBuilder();
if (queryParams != null) {
for (Map.Entry<String, String> entry : queryParams.entries()) {
urlBuilder.addEncodedQueryParameter(
Utils.encode(entry.getKey()), Utils.encode(entry.getValue()));
}
}
if (bucketName == null) {
this.buildListBucketsUrl(urlBuilder, region);
return urlBuilder.build();
}
boolean enforcePathStyle = (
// use path style for make bucket to workaround "AuthorizationHeaderMalformed" error from
// s3.amazonaws.com
(method == Method.PUT && objectName == null && queryParams == null)
// use path style for location query
|| (queryParams != null && queryParams.containsKey("location"))
// use path style where '.' in bucketName causes SSL certificate validation error
|| (bucketName.contains(".") && this.url.isHttps()));
String host = this.url.host();
if (this.awsDomainSuffix != null) {
host = this.buildAwsUrl(urlBuilder, bucketName, enforcePathStyle, region);
}
if (enforcePathStyle || !this.useVirtualStyle) {
urlBuilder.addEncodedPathSegment(Utils.encode(bucketName));
} else {
urlBuilder.host(bucketName + "." + host);
}
if (objectName != null) {
urlBuilder.addEncodedPathSegments(Utils.encodePath(objectName));
}
return urlBuilder.build();
}
@Override
public String toString() {
return url.toString();
}
}
/** Gets media type of the specified string value. */
public static MediaType mediaType(String value) {
if (value == null) return DEFAULT_MEDIA_TYPE;
MediaType mediaType = MediaType.parse(value);
if (mediaType == null) {
throw new IllegalArgumentException(
"invalid media/content type '" + value + "' as per RFC 2045");
}
return mediaType;
}
private static X509TrustManager createCompositeTrustManager(
List<X509TrustManager> trustManagers) {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
for (X509TrustManager tm : trustManagers) {
try {
tm.checkClientTrusted(chain, authType);
return;
} catch (CertificateException ignored) {
}
}
throw new CertificateException(
"None of the TrustManagers trust this client certificate chain");
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
for (X509TrustManager tm : trustManagers) {
try {
tm.checkServerTrusted(chain, authType);
return;
} catch (CertificateException ignored) {
}
}
throw new CertificateException(
"None of the TrustManagers trust this server certificate chain");
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return trustManagers.stream()
.flatMap(tm -> Arrays.stream(tm.getAcceptedIssuers()))
.toArray(X509Certificate[]::new);
}
};
}
private static X509TrustManager buildTrustManagerFromKeyStore(KeyStore ks)
throws KeyStoreException, NoSuchAlgorithmException {
TrustManagerFactory factory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(ks);
for (TrustManager tm : factory.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
return (X509TrustManager) tm;
}
}
return null;
}
private static int setCertificateEntry(
CertificateFactory cf, KeyStore ks, Path file, String namePrefix)
throws CertificateException, IOException, KeyStoreException {
try (InputStream in = Files.newInputStream(file)) {
int index = 0;
for (Certificate cert : cf.generateCertificates(in)) {
ks.setCertificateEntry(namePrefix + (index++), cert);
}
return index;
}
}
private static X509TrustManager getTrustManagerFromFile(String filePath)
throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null);
if (setCertificateEntry(cf, ks, Paths.get(filePath), "cert-file-") == 0) return null;
return buildTrustManagerFromKeyStore(ks);
}
private static X509TrustManager getTrustManagerFromDir(String dirPath)
throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null);
List<Path> directories =
Stream.of(dirPath.split(File.pathSeparator))
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(Paths::get)
.filter(Files::isDirectory)
.collect(Collectors.toList());
int index = 0;
int number = 1;
for (Path directory : directories) {
try (Stream<Path> paths = Files.walk(directory)) {
for (Path file : (Iterable<Path>) paths.filter(Files::isRegularFile)::iterator) {
try {
index += setCertificateEntry(cf, ks, file, "cert-dir-file-" + number + "-");
number++;
} catch (CertificateException | IOException | KeyStoreException e) {
// Ignore these errors.
}
}
}
}
if (index == 0) return null;
return buildTrustManagerFromKeyStore(ks);
}
private static X509TrustManager getDefaultTrustManager()
throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException {
TrustManagerFactory factory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init((KeyStore) null);
for (TrustManager tm : factory.getTrustManagers()) {
if (tm instanceof X509TrustManager) return (X509TrustManager) tm;
}
return null;
}
private static X509TrustManager getCompositeTrustManager(String filePath, String dirPath)
throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException {
List<X509TrustManager> trustManagers = new ArrayList<>();
X509TrustManager defaultTm = getDefaultTrustManager();
if (defaultTm != null) trustManagers.add(defaultTm);
if (dirPath != null && !dirPath.isEmpty()) {
X509TrustManager dirTm = getTrustManagerFromDir(dirPath);
if (dirTm != null) trustManagers.add(dirTm);
}
if (filePath != null && !filePath.isEmpty()) {
X509TrustManager fileTm = getTrustManagerFromFile(filePath);
if (fileTm != null) trustManagers.add(fileTm);
}
if (trustManagers.isEmpty()) return null;
return createCompositeTrustManager(trustManagers);
}
private static OkHttpClient enableJKSPKCS12Certificates(
OkHttpClient httpClient,
String trustStorePath,
String trustStorePassword,
String keyStorePath,
String keyStorePassword,
String keyStoreType)
throws MinioException {
try {
if (trustStorePath == null || trustStorePath.isEmpty()) {
throw new IllegalArgumentException("trust store path must be provided");
}
if (trustStorePassword == null) {
throw new IllegalArgumentException("trust store password must be provided");
}
if (keyStorePath == null || keyStorePath.isEmpty()) {
throw new IllegalArgumentException("key store path must be provided");
}
if (keyStorePassword == null) {
throw new IllegalArgumentException("key store password must be provided");
}
SSLContext sslContext = SSLContext.getInstance("TLS");
KeyStore trustStore = KeyStore.getInstance("JKS");
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
try (InputStream trustInput = Files.newInputStream(Paths.get(trustStorePath));
InputStream keyInput = Files.newInputStream(Paths.get(keyStorePath)); ) {
trustStore.load(trustInput, trustStorePassword.toCharArray());
keyStore.load(keyInput, keyStorePassword.toCharArray());
}
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
sslContext.init(
keyManagerFactory.getKeyManagers(),
trustManagerFactory.getTrustManagers(),
new java.security.SecureRandom());
return httpClient
.newBuilder()
.sslSocketFactory(
sslContext.getSocketFactory(),
(X509TrustManager) trustManagerFactory.getTrustManagers()[0])
.build();
} catch (GeneralSecurityException | IOException e) {
throw new MinioException(e);
}
}
/** Enables JKS formatted TLS certificates to the specified HTTP client. */
public static OkHttpClient enableJKSCertificates(
OkHttpClient httpClient,
String trustStorePath,
String trustStorePassword,
String keyStorePath,
String keyStorePassword)
throws MinioException {
return enableJKSPKCS12Certificates(
httpClient, trustStorePath, trustStorePassword, keyStorePath, keyStorePassword, "JKS");
}
/** Enables PKCS12 formatted TLS certificates to the specified HTTP client. */
public static OkHttpClient enablePKCS12Certificates(
OkHttpClient httpClient,
String trustStorePath,
String trustStorePassword,
String keyStorePath,
String keyStorePassword)
throws MinioException {
return enableJKSPKCS12Certificates(
httpClient, trustStorePath, trustStorePassword, keyStorePath, keyStorePassword, "PKCS12");
}
/** Enable external TLS certificates from given file path and all valid files from dir path. */
public static OkHttpClient enableExternalCertificates(
OkHttpClient client, String filePath, String dirPath) throws MinioException {
try {
X509TrustManager tm = getCompositeTrustManager(filePath, dirPath);
if (tm == null) return client;
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] {tm}, new SecureRandom());
return client.newBuilder().sslSocketFactory(sslContext.getSocketFactory(), tm).build();
} catch (CertificateException
| IOException
| KeyManagementException
| KeyStoreException
| NoSuchAlgorithmException e) {
throw new MinioException(e);
}
}
/**
* Enables external TLS certificates from SSL_CERT_FILE and SSL_CERT_DIR environment variables if
* present.
*/
public static OkHttpClient enableExternalCertificatesFromEnv(OkHttpClient client)
throws MinioException {
return enableExternalCertificates(
client, System.getenv("SSL_CERT_FILE"), System.getenv("SSL_CERT_DIR"));
}
public static String getRequestTraces(okhttp3.Request request, String bodyString) {
Method method = Method.fromString(request.method());
StringBuilder traceBuilder = new StringBuilder();
traceBuilder.append("---------START-HTTP---------\n");
String encodedPath = request.url().encodedPath();
String encodedQuery = request.url().encodedQuery();
if (encodedQuery != null) encodedPath += "?" + encodedQuery;
traceBuilder.append(method.toString()).append(" ").append(encodedPath).append(" HTTP/1.1\n");
traceBuilder.append(
SIGNATURE_PATTERN
.matcher(
CREDENTIAL_PATTERN
.matcher(request.headers().toString())
.replaceAll("Credential=*REDACTED*"))
.replaceAll("Signature=*REDACTED*"));
String lastTwoChars = traceBuilder.substring(traceBuilder.length() - 2);
if (lastTwoChars.charAt(1) != '\n') {
traceBuilder.append("\n\n");
} else if (lastTwoChars.charAt(0) != '\n') {
traceBuilder.append("\n");
}
if (method == Method.PUT || method == Method.POST) {
if (bodyString != null) {
traceBuilder.append(bodyString);
if (!bodyString.endsWith("\n")) traceBuilder.append("\n");
}
}
return traceBuilder.toString();
}
public static String getResponseTraces(
okhttp3.Response response,
Method method,
QueryParameters queryParams,
boolean isBucketRequest)
throws IOException {
StringBuilder traceBuilder = new StringBuilder();
String trace =
String.format(
"%s %d %s%n%s",
response.protocol().toString().toUpperCase(Locale.US),
response.code(),
response.message(),
response.headers().toString());
if (!trace.endsWith("\n\n")) {
trace += trace.endsWith("\n") ? "\n" : "\n\n";
}
traceBuilder.append(trace);
if (response.isSuccessful()) {
// Trace response body only if the request is not
// GetObject/ListenBucketNotification
// S3 API.
Set<String> keys = queryParams.keySet();
if ((method != Method.GET
|| isBucketRequest
|| !Collections.disjoint(keys, TRACE_QUERY_PARAMS))
&& !(keys.contains("events") && (keys.contains("prefix") || keys.contains("suffix")))) {
String responseBody = response.peekBody(1024 * 1024).string();
traceBuilder.append(responseBody);
if (!responseBody.endsWith("\n")) traceBuilder.append("\n");
} else {
traceBuilder.append("<<<BYTES>>>\n");
}
traceBuilder.append(END_HTTP).append("\n");
} else {
String responseBody = response.peekBody(1024 * 1024).string();
traceBuilder.append(responseBody);
if (!responseBody.endsWith("\n") && !(responseBody.isEmpty() && method == Method.HEAD)) {
traceBuilder.append("\n");
}
traceBuilder.append(END_HTTP).append("\n");
}
return traceBuilder.toString();
}
public static class StatusRetryInterceptor implements Interceptor {
private final Set<Integer> retryStatusCodes;
private final long delayMs;
private final int maxRetries;
private final PrintWriter traceWriter;
private final boolean isBucketRequest;
private StatusRetryInterceptor(
Set<Integer> retryStatusCodes,
long delayMs,
int maxRetries,
PrintWriter traceWriter,
boolean isBucketRequest) {
this.retryStatusCodes = retryStatusCodes;
this.delayMs = delayMs;
this.maxRetries = Math.max(1, maxRetries);
this.traceWriter = traceWriter;
this.isBucketRequest = isBucketRequest;
}
public StatusRetryInterceptor() {
this(RETRIABLE_STATUS_CODES, 100, 5, null, false);
}
public StatusRetryInterceptor(Set<Integer> retryStatusCodes, long delayMs, int maxRetries) {
this(retryStatusCodes, delayMs, maxRetries, null, false);
}
public StatusRetryInterceptor(
StatusRetryInterceptor interceptor, PrintWriter traceWriter, boolean isBucketRequest) {
this(
interceptor != null ? interceptor.retryStatusCodes : RETRIABLE_STATUS_CODES,
interceptor != null ? interceptor.delayMs : 100,
interceptor != null ? interceptor.maxRetries : 5,
traceWriter,
isBucketRequest);
}
@Override
public Response intercept(Chain chain) throws IOException {
okhttp3.Request request = chain.request();
Method method = Method.fromString(request.method());
QueryParameters queryParams = new QueryParameters();
for (String key : request.url().queryParameterNames()) {
for (String value : request.url().queryParameterValues(key)) {
queryParams.add(key, value);
}
}
String bodyString = null;
if (request.body() instanceof RequestBody) {
RequestBody body = (RequestBody) request.body();
bodyString = body.bodyString();
} else if ((method == Method.PUT || method == Method.POST)
&& request.body() != null
&& request.body().contentLength() != 0) {
bodyString = "<<<BYTES>>>";
}
for (int i = 0; i < maxRetries; i++) {
if (traceWriter != null) {
traceWriter.print(getRequestTraces(request, bodyString));
traceWriter.flush();
}
okhttp3.Response response = chain.proceed(request);
if (traceWriter != null) {
traceWriter.print(getResponseTraces(response, method, queryParams, isBucketRequest));
traceWriter.flush();
}
if (response.isSuccessful()
|| i == maxRetries - 1
|| retryStatusCodes == null
|| !retryStatusCodes.contains(response.code())) return response;
response.close();
if (delayMs <= 0) continue;
long maxBackoffLimit = delayMs * (1L << (i + 1));
long jitteredDelay = ThreadLocalRandom.current().nextLong(0, maxBackoffLimit);
try {
Thread.sleep(jitteredDelay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Retry interrupted", e);
}
}
return null; // This never happens.
}
}
/**
* Creates new HTTP client with default timeout with additional TLS certificates from
* SSL_CERT_FILE and SSL_CERT_DIR environment variables if present.
*/
public static OkHttpClient newDefaultClient() {
OkHttpClient client =
new OkHttpClient()
.newBuilder()
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
.protocols(Arrays.asList(Protocol.HTTP_1_1))
.addInterceptor(new StatusRetryInterceptor())
.build();
try {
return enableExternalCertificatesFromEnv(client);
} catch (MinioException e) {
throw new IllegalStateException(e);
}
}
/**
* Disables TLS certificate check as a special case for self-signed certificate and testing to the
* specified HTTP client.
*/
public static OkHttpClient disableCertCheck(OkHttpClient client) throws MinioException {
try {
final TrustManager[] trustAllCerts =
new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
};
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
return client
.newBuilder()
.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0])
.hostnameVerifier(
new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
})
.build();
} catch (KeyManagementException | NoSuchAlgorithmException e) {
throw new MinioException(e);
}
}
/** Sets connect, write and read timeout in milliseconds to the specified HTTP client. */
public static OkHttpClient setTimeout(
OkHttpClient client, long connectTimeout, long writeTimeout, long readTimeout) {
return client
.newBuilder()
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
.readTimeout(readTimeout, TimeUnit.MILLISECONDS)
.build();
}
/** HTTP body of {@link RandomAccessFile}, {@link ByteBuffer} or {@link byte} array. */
public static class Body {
private okhttp3.RequestBody requestBody;
private RandomAccessFile file;
private ByteBuffer buffer;
private byte[] data;
private Long length;
private MediaType contentType;
private String sha256Hash;
private String md5Hash;
private String bodyString = "<<<BYTE>>>";
/** Creates Body for okhttp3 RequestBody. */
public Body(okhttp3.RequestBody requestBody) {
this.requestBody = requestBody;
this.contentType = requestBody.contentType();
}
/** Creates Body for RandomAccessFile. */
public Body(
RandomAccessFile file,
long length,
MediaType contentType,
String sha256Hash,
String md5Hash) {
if (length < 0) throw new IllegalArgumentException("valid length must be provided");
this.file = file;
set(length, contentType, sha256Hash, md5Hash);
}
/** Creates Body for byte array. */
public Body(byte[] data, int length, MediaType contentType, String sha256Hash, String md5Hash) {
if (length < 0) throw new IllegalArgumentException("valid length must be provided");
this.data = data;
set((long) length, contentType, sha256Hash, md5Hash);
}
/** Creates Body for ByteBuffer, string or XML encodable object. */
public Body(Object body, MediaType contentType, String sha256Hash, String md5Hash)
throws MinioException {
if (body instanceof ByteBuffer) {
this.buffer = (ByteBuffer) body;
set(null, contentType, sha256Hash, md5Hash);
return;
}
byte[] data = null;
if (body instanceof CharSequence) {
data = ((CharSequence) body).toString().getBytes(StandardCharsets.UTF_8);
} else {
// For any other object, do XML marshalling.
data = Xml.marshal(body).getBytes(StandardCharsets.UTF_8);
contentType = XML_MEDIA_TYPE;
}
sha256Hash = Checksum.hexString(Checksum.SHA256.sum(data));
md5Hash = Checksum.base64String(Checksum.MD5.sum(data));
this.data = data;
set((long) data.length, contentType, sha256Hash, md5Hash);
this.bodyString = new String(data, StandardCharsets.UTF_8);
}
private void set(Long length, MediaType contentType, String sha256Hash, String md5Hash) {
this.length = length;
this.contentType = contentType == null ? DEFAULT_MEDIA_TYPE : contentType;
this.sha256Hash = sha256Hash;
this.md5Hash = md5Hash;
}
/** Gets content type of this body. */
public MediaType contentType() {
return contentType;
}
/** Gets SHA256 hash of this body. */
public String sha256Hash() {
return sha256Hash;
}
/** Gets SHA256 hash of this body. */
public String md5Hash() {
return md5Hash;
}
/** Checks whether this body is okhttp3 RequestBody. */
public boolean isHttpRequestBody() {
return requestBody != null;
}
/** Creates headers for this body. */
public Headers headers() {
Headers headers = new Headers(Headers.CONTENT_TYPE, contentType.toString());
if (sha256Hash != null) headers.put(Headers.X_AMZ_CONTENT_SHA256, sha256Hash);
if (md5Hash != null) headers.put(Headers.CONTENT_MD5, md5Hash);
return headers;
}
/** Creates HTTP RequestBody for this body. */
public RequestBody toRequestBody() throws MinioException {
if (requestBody != null) return new RequestBody(requestBody);
if (file != null) {
return new RequestBody(file, length, contentType, bodyString);
}
if (buffer != null) {
return new RequestBody(buffer, contentType, bodyString);
}
return new RequestBody(data, length.intValue(), contentType, bodyString);
}