-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
HttpClientConfigurer.java
291 lines (257 loc) · 14.4 KB
/
HttpClientConfigurer.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
/*
* Copyright 2011 the original author or authors.
*
* 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 org.gradle.internal.resource.transport.http;
import com.google.common.collect.Lists;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.NTCredentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.auth.BasicSchemeFactory;
import org.apache.http.impl.auth.DigestSchemeFactory;
import org.apache.http.impl.auth.KerberosSchemeFactory;
import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.SystemDefaultCredentialsProvider;
import org.apache.http.impl.conn.SystemDefaultRoutePlanner;
import org.apache.http.impl.cookie.DefaultCookieSpecProvider;
import org.apache.http.impl.cookie.IgnoreSpecProvider;
import org.apache.http.impl.cookie.NetscapeDraftSpecProvider;
import org.apache.http.impl.cookie.RFC6265CookieSpecProvider;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.gradle.api.JavaVersion;
import org.gradle.api.credentials.PasswordCredentials;
import org.gradle.api.specs.Spec;
import org.gradle.authentication.Authentication;
import org.gradle.authentication.http.BasicAuthentication;
import org.gradle.authentication.http.DigestAuthentication;
import org.gradle.internal.Cast;
import org.gradle.internal.authentication.AllSchemesAuthentication;
import org.gradle.internal.authentication.AuthenticationInternal;
import org.gradle.internal.resource.UriTextResource;
import org.gradle.internal.resource.transport.http.ntlm.NTLMCredentials;
import org.gradle.internal.resource.transport.http.ntlm.NTLMSchemeFactory;
import org.gradle.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import java.io.IOException;
import java.net.ProxySelector;
import java.util.Collection;
import java.util.Collections;
public class HttpClientConfigurer {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientConfigurer.class);
private static final int MAX_HTTP_CONNECTIONS = 20;
private static final String[] SSL_PROTOCOLS;
private static final String HTTPS_PROTOCOLS = "https.protocols";
static {
String httpsProtocols = System.getProperty(HTTPS_PROTOCOLS);
if (httpsProtocols != null) {
SSL_PROTOCOLS = httpsProtocols.split(",");
} else if (JavaVersion.current().isJava7()) {
SSL_PROTOCOLS = new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"};
} else {
SSL_PROTOCOLS = null;
}
}
private final HttpSettings httpSettings;
public HttpClientConfigurer(HttpSettings httpSettings) {
this.httpSettings = httpSettings;
}
public void configure(HttpClientBuilder builder) {
SystemDefaultCredentialsProvider credentialsProvider = new SystemDefaultCredentialsProvider();
configureSslSocketConnectionFactory(builder, httpSettings.getSslContextFactory(), httpSettings.getHostnameVerifier());
configureAuthSchemeRegistry(builder);
configureCredentials(builder, credentialsProvider, httpSettings.getAuthenticationSettings());
configureProxy(builder, credentialsProvider, httpSettings);
configureUserAgent(builder);
configureCookieSpecRegistry(builder);
configureRequestConfig(builder);
configureSocketConfig(builder);
configureRedirectStrategy(builder);
builder.setDefaultCredentialsProvider(credentialsProvider);
builder.setMaxConnTotal(MAX_HTTP_CONNECTIONS);
builder.setMaxConnPerRoute(MAX_HTTP_CONNECTIONS);
}
private void configureSslSocketConnectionFactory(HttpClientBuilder builder, SslContextFactory sslContextFactory, HostnameVerifier hostnameVerifier) {
builder.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContextFactory.createSslContext(), SSL_PROTOCOLS, null, hostnameVerifier));
}
private void configureAuthSchemeRegistry(HttpClientBuilder builder) {
builder.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.BASIC, new BasicSchemeFactory())
.register(AuthSchemes.DIGEST, new DigestSchemeFactory())
.register(AuthSchemes.NTLM, new NTLMSchemeFactory())
.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory())
.build()
);
}
private void configureCredentials(HttpClientBuilder builder, CredentialsProvider credentialsProvider, Collection<Authentication> authentications) {
if(authentications.size() > 0) {
useCredentials(credentialsProvider, AuthScope.ANY_HOST, AuthScope.ANY_PORT, authentications);
// Use preemptive authorisation if no other authorisation has been established
builder.addInterceptorFirst(new PreemptiveAuth(new BasicScheme(), isPreemptiveEnabled(authentications)));
}
}
private void configureProxy(HttpClientBuilder builder, CredentialsProvider credentialsProvider, HttpSettings httpSettings) {
HttpProxySettings.HttpProxy httpProxy = httpSettings.getProxySettings().getProxy();
HttpProxySettings.HttpProxy httpsProxy = httpSettings.getSecureProxySettings().getProxy();
for (HttpProxySettings.HttpProxy proxy : Lists.newArrayList(httpProxy, httpsProxy)) {
if (proxy != null) {
if (proxy.credentials != null) {
useCredentials(credentialsProvider, proxy.host, proxy.port, Collections.singleton(new AllSchemesAuthentication(proxy.credentials)));
}
}
}
builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
}
private void useCredentials(CredentialsProvider credentialsProvider, String host, int port, Collection<? extends Authentication> authentications) {
Credentials httpCredentials;
for (Authentication authentication : authentications) {
String scheme = getAuthScheme(authentication);
PasswordCredentials credentials = getPasswordCredentials(authentication);
if (authentication instanceof AllSchemesAuthentication) {
NTLMCredentials ntlmCredentials = new NTLMCredentials(credentials);
httpCredentials = new NTCredentials(ntlmCredentials.getUsername(), ntlmCredentials.getPassword(), ntlmCredentials.getWorkstation(), ntlmCredentials.getDomain());
credentialsProvider.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, AuthSchemes.NTLM), httpCredentials);
LOGGER.debug("Using {} and {} for authenticating against '{}:{}' using {}", credentials, ntlmCredentials, host, port, AuthSchemes.NTLM);
}
httpCredentials = new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword());
credentialsProvider.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, scheme), httpCredentials);
LOGGER.debug("Using {} for authenticating against '{}:{}' using {}", credentials, host, port, scheme);
}
}
private boolean isPreemptiveEnabled(Collection<Authentication> authentications) {
return CollectionUtils.any(authentications, new Spec<Authentication>() {
@Override
public boolean isSatisfiedBy(Authentication element) {
return element instanceof BasicAuthentication;
}
});
}
public void configureUserAgent(HttpClientBuilder builder) {
builder.setUserAgent(UriTextResource.getUserAgentString());
}
private void configureCookieSpecRegistry(HttpClientBuilder builder) {
PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.getDefault();
builder.setPublicSuffixMatcher(publicSuffixMatcher);
// Add more data patterns to the default configuration to work around https://github.com/gradle/gradle/issues/1596
final CookieSpecProvider defaultProvider = new DefaultCookieSpecProvider(DefaultCookieSpecProvider.CompatibilityLevel.DEFAULT, publicSuffixMatcher, new String[]{
"EEE, dd-MMM-yy HH:mm:ss z", // Netscape expires pattern
DateUtils.PATTERN_RFC1036,
DateUtils.PATTERN_ASCTIME,
DateUtils.PATTERN_RFC1123
}, false);
final CookieSpecProvider laxStandardProvider = new RFC6265CookieSpecProvider(
RFC6265CookieSpecProvider.CompatibilityLevel.RELAXED, publicSuffixMatcher);
final CookieSpecProvider strictStandardProvider = new RFC6265CookieSpecProvider(
RFC6265CookieSpecProvider.CompatibilityLevel.STRICT, publicSuffixMatcher);
builder.setDefaultCookieSpecRegistry(RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.DEFAULT, defaultProvider)
.register("best-match", defaultProvider)
.register("compatibility", defaultProvider)
.register(CookieSpecs.STANDARD, laxStandardProvider)
.register(CookieSpecs.STANDARD_STRICT, strictStandardProvider)
.register(CookieSpecs.NETSCAPE, new NetscapeDraftSpecProvider())
.register(CookieSpecs.IGNORE_COOKIES, new IgnoreSpecProvider())
.build()
);
}
private void configureRequestConfig(HttpClientBuilder builder) {
HttpTimeoutSettings timeoutSettings = httpSettings.getTimeoutSettings();
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeoutSettings.getConnectionTimeoutMs())
.setSocketTimeout(timeoutSettings.getSocketTimeoutMs())
.build();
builder.setDefaultRequestConfig(config);
}
private void configureSocketConfig(HttpClientBuilder builder) {
HttpTimeoutSettings timeoutSettings = httpSettings.getTimeoutSettings();
builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeoutSettings.getSocketTimeoutMs()).build());
}
private PasswordCredentials getPasswordCredentials(Authentication authentication) {
org.gradle.api.credentials.Credentials credentials = ((AuthenticationInternal) authentication).getCredentials();
if (!(credentials instanceof PasswordCredentials)) {
throw new IllegalArgumentException(String.format("Credentials must be an instance of: %s", PasswordCredentials.class.getCanonicalName()));
}
return Cast.uncheckedCast(credentials);
}
private void configureRedirectStrategy(HttpClientBuilder builder) {
if (httpSettings.isFollowRedirects()) {
builder.setRedirectStrategy(new AlwaysRedirectRedirectStrategy());
} else {
builder.disableRedirectHandling();
}
}
private String getAuthScheme(Authentication authentication) {
if (authentication instanceof BasicAuthentication) {
return AuthSchemes.BASIC;
} else if (authentication instanceof DigestAuthentication) {
return AuthSchemes.DIGEST;
} else if (authentication instanceof AllSchemesAuthentication) {
return AuthScope.ANY_SCHEME;
} else {
throw new IllegalArgumentException(String.format("Authentication scheme of '%s' is not supported.", authentication.getClass().getSimpleName()));
}
}
static class PreemptiveAuth implements HttpRequestInterceptor {
private final AuthScheme authScheme;
private final boolean alwaysSendAuth;
PreemptiveAuth(AuthScheme authScheme, boolean alwaysSendAuth) {
this.authScheme = authScheme;
this.alwaysSendAuth = alwaysSendAuth;
}
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
if (authState.getAuthScheme() != null || authState.hasAuthOptions()) {
return;
}
// If no authState has been established and this is a PUT or POST request, add preemptive authorisation
String requestMethod = request.getRequestLine().getMethod();
if (alwaysSendAuth || requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
if (credentials == null) {
throw new HttpException("No credentials for preemptive authentication");
}
authState.update(authScheme, credentials);
}
}
}
}