-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
AwsHostNameUtils.java
294 lines (250 loc) · 10.4 KB
/
AwsHostNameUtils.java
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
/*
* Copyright 2012-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 com.amazonaws.util;
import com.amazonaws.annotation.SdkProtectedApi;
import java.net.InetAddress;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.amazonaws.internal.config.HostRegexToRegionMapping;
import com.amazonaws.internal.config.InternalConfig;
import com.amazonaws.log.InternalLogFactory;
public class AwsHostNameUtils {
private static final Pattern S3_ENDPOINT_PATTERN =
Pattern.compile("^(?:.+\\.)?s3[.-]([a-z0-9-]+)$");
private static final Pattern STANDARD_CLOUDSEARCH_ENDPOINT_PATTERN =
Pattern.compile("^(?:.+\\.)?([a-z0-9-]+)\\.cloudsearch$");
private static final Pattern EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN =
Pattern.compile("^(?:.+\\.)?([a-z0-9-]+)\\.cloudsearch\\..+");
/**
* @deprecated in favor of {@link #parseRegionName(String, String)}.
*/
@Deprecated
public static String parseRegionName(URI endpoint) {
return parseRegionName(endpoint.getHost(), null);
}
/**
* Attempts to parse the region name from an endpoint based on conventions
* about the endpoint format.
*
* @param host the hostname to parse
* @param serviceHint an optional hint about the service for the endpoint
* @return the region parsed from the hostname, or
* "us-east-1" if no region information
* could be found.
* @deprecated in favor of {@link #parseRegion(String, String)}.
*/
@Deprecated
public static String parseRegionName(final String host,
final String serviceHint) {
String region = parseRegion(host, serviceHint);
// If region is null, then endpoint is totally non-standard;
// guess us-east-1 for lack of a better option.
return region == null ? "us-east-1" : region;
}
/**
* Attempts to parse the region name from an endpoint based on conventions
* about the endpoint format. This does not consider any properties in the endpoint
* configuration from the service.
*
* @param host the hostname to parse
* @param serviceHint an optional hint about the service for the endpoint
* @return the region parsed from the hostname, or
* null if no region information could be found.
*/
public static String parseRegion(String host, String serviceHint) {
String result;
result = parseRegionFromInternalConfig(host);
if (result != null) {
return result;
}
result = parseRegionFromAwsPartitionPattern(host);
if (result != null) {
return result;
}
result = parseRegionUsingServiceHint(host, serviceHint);
if (result != null) {
return result;
}
result = parseRegionFromAfterServiceName(host, serviceHint);
return result;
}
/**
* Parse the region from the host name using any internal configuration regex patterns that are available. Returns null if
* it cannot be parsed from the internal configuration.
*/
@SdkProtectedApi
public static String parseRegionFromInternalConfig(String host) {
validateHostname(host);
InternalConfig internConfig = InternalConfig.Factory.getInternalConfig();
for (HostRegexToRegionMapping mapping : internConfig.getHostRegexToRegionMappings()) {
if (mapping.isHostNameMatching(host)) {
return mapping.getRegionName();
}
}
return null;
}
/**
* Parse the region from the host name, if it's in the standard AWS parition (ending in amazonaws.com). Returns null if
* it cannot be parsed from the standard partition pattern.
*/
@SdkProtectedApi
public static String parseRegionFromAwsPartitionPattern(String host) {
validateHostname(host);
if (host.endsWith(".amazonaws.com")) {
int index = host.length() - ".amazonaws.com".length();
return parseStandardRegionName(host.substring(0, index));
}
return null;
}
/**
* Parse the region using service-specific logic from the host name. Returns null if
* it cannot be parsed from the host using service-specific logic.
*/
@SdkProtectedApi
public static String parseRegionUsingServiceHint(String host, String serviceHint) {
validateHostname(host);
if (serviceHint != null) {
if (serviceHint.equals("cloudsearch")
&& !host.startsWith("cloudsearch.")) {
// CloudSearch domains use the nonstandard domain format
// [domain].[region].cloudsearch.[suffix].
Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN
.matcher(host);
if (matcher.matches()) {
return matcher.group(1);
}
}
}
return null;
}
/**
* Parse the region by looking for the service name in the hostname and assuming anything that follows it (separated by
* a . or a -) is the region. Returns null if this process fails.
*/
public static String parseRegionFromAfterServiceName(String host, String serviceHint) {
validateHostname(host);
if (serviceHint != null) {
// If we have a service hint, look for 'service.[region]' or
// 'service-[region]' in the endpoint's hostname.
Pattern pattern = Pattern.compile(
"^(?:.+\\.)?"
+ Pattern.quote(serviceHint)
+ "[.-]([a-z0-9-]+)\\."
);
Matcher matcher = pattern.matcher(host);
if (matcher.find()) {
return matcher.group(1);
}
}
return null;
}
private static void validateHostname(String hostname) {
if (hostname == null) {
throw new IllegalArgumentException("hostname cannot be null");
}
}
/**
* Parses the region name from a standard (*.amazonaws.com) endpoint.
*
* @param fragment the portion of the endpoint excluding
* ".amazonaws.com"
* @return the parsed region name (or "us-east-1" as a
* best guess if we can't tell for sure)
*/
private static String parseStandardRegionName(final String fragment) {
Matcher matcher = S3_ENDPOINT_PATTERN.matcher(fragment);
if (matcher.matches()) {
// host was 'bucket.s3-[region].amazonaws.com'.
return matcher.group(1);
}
matcher = STANDARD_CLOUDSEARCH_ENDPOINT_PATTERN.matcher(fragment);
if (matcher.matches()) {
// host was 'domain.[region].cloudsearch.amazonaws.com'.
return matcher.group(1);
}
int index = fragment.lastIndexOf('.');
if (index == -1) {
// host was 'service.amazonaws.com', guess us-east-1
// for lack of a better option.
return "us-east-1";
}
// host was 'service.[region].amazonaws.com'.
String region = fragment.substring(index + 1);
// Special case for iam.us-gov.amazonaws.com, which is actually
// us-gov-west-1.
if ("us-gov".equals(region)) {
region = "us-gov-west-1";
}
return region;
}
/**
* Parses the service name from an endpoint. Can only handle endpoints of
* the form 'service.[region.]amazonaws.com'.
*
* @Deprecated This method currently doesn't support BJS endpoints. This
* method is used only in AWS4Signer to identify the service name from an
* endpoint. This method is broken as it no longer returns the service
* name to used for signing for all AWS services. This method will be
* removed as part of next major version upgrade.
*/
@Deprecated
public static String parseServiceName(URI endpoint) {
String host = endpoint.getHost();
// If we don't recognize the domain, throw an exception.
if (!host.endsWith(".amazonaws.com")) {
throw new IllegalArgumentException(
"Cannot parse a service name from an unrecognized endpoint ("
+ host
+ ").");
}
String serviceAndRegion =
host.substring(0, host.indexOf(".amazonaws.com"));
// Special cases for S3 endpoints with bucket names embedded.
if (serviceAndRegion.endsWith(".s3")
|| S3_ENDPOINT_PATTERN.matcher(serviceAndRegion).matches()) {
return "s3";
}
char separator = '.';
// If we don't detect a separator between service name and region, then
// assume that the region is not included in the hostname, and it's only
// the service name (ex: "http://iam.amazonaws.com").
if (serviceAndRegion.indexOf(separator) == -1) {
return serviceAndRegion;
}
String service =
serviceAndRegion.substring(0, serviceAndRegion.indexOf(separator));
return service;
}
/**
* Returns the host name for the local host. If the operation is not allowed
* by the security check, the textual representation of the IP address of
* the local host is returned instead. If the ip address of the local host
* cannot be resolved or if there is any other failure, "localhost" is
* returned as a fallback.
*/
public static String localHostName() {
try {
InetAddress localhost = InetAddress.getLocalHost();
return localhost.getHostName();
} catch (Exception e) {
InternalLogFactory.getLog(AwsHostNameUtils.class)
.debug(
"Failed to determine the local hostname; fall back to "
+ "use \"localhost\".", e);
return "localhost";
}
}
}