package org.glassfish.jersey.client.internal;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.ClientRequest;
import org.glassfish.jersey.client.ClientResponse;
import org.glassfish.jersey.client.HttpUrlConnectorProvider;
import org.glassfish.jersey.client.JerseyClient;
import org.glassfish.jersey.client.RequestEntityProcessing;
import org.glassfish.jersey.client.spi.AsyncConnectorCallback;
import org.glassfish.jersey.client.spi.Connector;
import org.glassfish.jersey.internal.util.PropertiesHelper;
import org.glassfish.jersey.internal.util.collection.LazyValue;
import org.glassfish.jersey.internal.util.collection.UnsafeValue;
import org.glassfish.jersey.internal.util.collection.Value;
import org.glassfish.jersey.internal.util.collection.Values;
import org.glassfish.jersey.message.internal.Statuses;
public class HttpUrlConnector implements Connector {
private static final Logger LOGGER = Logger.getLogger(HttpUrlConnector.class.getName());
private static final String = "sun.net.http.allowRestrictedHeaders";
private static final String[] = {
"Access-Control-Request-Headers",
"Access-Control-Request-Method",
"Connection",
"Content-Length",
"Content-Transfer-Encoding",
"Host",
"Keep-Alive",
"Origin",
"Trailer",
"Transfer-Encoding",
"Upgrade",
"Via"
};
private static final Set<String> = new HashSet<>(restrictedHeaders.length);
static {
for (String headerName : restrictedHeaders) {
restrictedHeaderSet.add(headerName.toLowerCase(Locale.ROOT));
}
}
private final HttpUrlConnectorProvider.ConnectionFactory connectionFactory;
private final int chunkSize;
private final boolean fixLengthStreaming;
private final boolean setMethodWorkaround;
private final boolean ;
private final LazyValue<SSLSocketFactory> sslSocketFactory;
public HttpUrlConnector(
final Client client,
final HttpUrlConnectorProvider.ConnectionFactory connectionFactory,
final int chunkSize,
final boolean fixLengthStreaming,
final boolean setMethodWorkaround) {
sslSocketFactory = Values.lazy(new Value<SSLSocketFactory>() {
@Override
public SSLSocketFactory get() {
return client.getSslContext().getSocketFactory();
}
});
this.connectionFactory = connectionFactory;
this.chunkSize = chunkSize;
this.fixLengthStreaming = fixLengthStreaming;
this.setMethodWorkaround = setMethodWorkaround;
isRestrictedHeaderPropertySet = Boolean.valueOf(AccessController.doPrivileged(
PropertiesHelper.getSystemProperty(ALLOW_RESTRICTED_HEADERS_SYSTEM_PROPERTY, "false")
));
LOGGER.config(isRestrictedHeaderPropertySet
? LocalizationMessages.RESTRICTED_HEADER_PROPERTY_SETTING_TRUE(ALLOW_RESTRICTED_HEADERS_SYSTEM_PROPERTY)
: LocalizationMessages.RESTRICTED_HEADER_PROPERTY_SETTING_FALSE(ALLOW_RESTRICTED_HEADERS_SYSTEM_PROPERTY)
);
}
private static InputStream getInputStream(final HttpURLConnection uc) throws IOException {
return new InputStream() {
private final UnsafeValue<InputStream, IOException> in = Values.lazy(new UnsafeValue<InputStream, IOException>() {
@Override
public InputStream get() throws IOException {
if (uc.getResponseCode() < Response.Status.BAD_REQUEST.getStatusCode()) {
return uc.getInputStream();
} else {
InputStream ein = uc.getErrorStream();
return (ein != null) ? ein : new ByteArrayInputStream(new byte[0]);
}
}
});
private volatile boolean closed = false;
private void throwIOExceptionIfClosed() throws IOException {
if (closed) {
throw new IOException("Stream closed");
}
}
@Override
public int read() throws IOException {
int result = in.get().read();
throwIOExceptionIfClosed();
return result;
}
@Override
public int read(byte[] b) throws IOException {
int result = in.get().read(b);
throwIOExceptionIfClosed();
return result;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int result = in.get().read(b, off, len);
throwIOExceptionIfClosed();
return result;
}
@Override
public long skip(long n) throws IOException {
long result = in.get().skip(n);
throwIOExceptionIfClosed();
return result;
}
@Override
public int available() throws IOException {
int result = in.get().available();
throwIOExceptionIfClosed();
return result;
}
@Override
public void close() throws IOException {
try {
in.get().close();
} finally {
closed = true;
}
}
@Override
public void mark(int readLimit) {
try {
in.get().mark(readLimit);
} catch (IOException e) {
throw new IllegalStateException("Unable to retrieve the underlying input stream.", e);
}
}
@Override
public void reset() throws IOException {
in.get().reset();
throwIOExceptionIfClosed();
}
@Override
public boolean markSupported() {
try {
return in.get().markSupported();
} catch (IOException e) {
throw new IllegalStateException("Unable to retrieve the underlying input stream.", e);
}
}
};
}
@Override
public ClientResponse apply(ClientRequest request) {
try {
return _apply(request);
} catch (IOException ex) {
throw new ProcessingException(ex);
}
}
@Override
public Future<?> apply(final ClientRequest request, final AsyncConnectorCallback callback) {
try {
callback.response(_apply(request));
} catch (IOException ex) {
callback.failure(new ProcessingException(ex));
} catch (Throwable t) {
callback.failure(t);
}
return CompletableFuture.completedFuture(null);
}
@Override
public void close() {
}
protected void secureConnection(final JerseyClient client, final HttpURLConnection uc) {
if (uc instanceof HttpsURLConnection) {
HttpsURLConnection suc = (HttpsURLConnection) uc;
final HostnameVerifier verifier = client.getHostnameVerifier();
if (verifier != null) {
suc.setHostnameVerifier(verifier);
}
if (HttpsURLConnection.getDefaultSSLSocketFactory() == suc.getSSLSocketFactory()) {
suc.setSSLSocketFactory(sslSocketFactory.get());
}
}
}
private ClientResponse _apply(final ClientRequest request) throws IOException {
final HttpURLConnection uc;
uc = this.connectionFactory.getConnection(request.getUri().toURL());
uc.setDoInput(true);
final String httpMethod = request.getMethod();
if (request.resolveProperty(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, setMethodWorkaround)) {
setRequestMethodViaJreBugWorkaround(uc, httpMethod);
} else {
uc.setRequestMethod(httpMethod);
}
uc.setInstanceFollowRedirects(request.resolveProperty(ClientProperties.FOLLOW_REDIRECTS, true));
uc.setConnectTimeout(request.resolveProperty(ClientProperties.CONNECT_TIMEOUT, uc.getConnectTimeout()));
uc.setReadTimeout(request.resolveProperty(ClientProperties.READ_TIMEOUT, uc.getReadTimeout()));
secureConnection(request.getClient(), uc);
final Object entity = request.getEntity();
if (entity != null) {
RequestEntityProcessing entityProcessing = request.resolveProperty(
ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.class);
if (entityProcessing == null || entityProcessing != RequestEntityProcessing.BUFFERED) {
final long length = request.getLengthLong();
if (fixLengthStreaming && length > 0) {
if ("1.6".equals(Runtime.class.getPackage().getSpecificationVersion())) {
uc.setFixedLengthStreamingMode(request.getLength());
} else {
uc.setFixedLengthStreamingMode(length);
}
} else if (entityProcessing == RequestEntityProcessing.CHUNKED) {
uc.setChunkedStreamingMode(chunkSize);
}
}
uc.setDoOutput(true);
if ("GET".equalsIgnoreCase(httpMethod)) {
final Logger logger = Logger.getLogger(HttpUrlConnector.class.getName());
if (logger.isLoggable(Level.INFO)) {
logger.log(Level.INFO, LocalizationMessages.HTTPURLCONNECTION_REPLACES_GET_WITH_ENTITY());
}
}
request.setStreamProvider(contentLength -> {
setOutboundHeaders(request.getStringHeaders(), uc);
return uc.getOutputStream();
});
request.writeEntity();
} else {
setOutboundHeaders(request.getStringHeaders(), uc);
}
final int code = uc.getResponseCode();
final String reasonPhrase = uc.getResponseMessage();
final Response.StatusType status =
reasonPhrase == null ? Statuses.from(code) : Statuses.from(code, reasonPhrase);
final URI resolvedRequestUri;
try {
resolvedRequestUri = uc.getURL().toURI();
} catch (URISyntaxException e) {
throw new ProcessingException(e);
}
ClientResponse responseContext = new ClientResponse(status, request, resolvedRequestUri);
responseContext.headers(
uc.getHeaderFields()
.entrySet()
.stream()
.filter(stringListEntry -> stringListEntry.getKey() != null)
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue))
);
responseContext.setEntityStream(getInputStream(uc));
return responseContext;
}
private void (MultivaluedMap<String, String> headers, HttpURLConnection uc) {
boolean restrictedSent = false;
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
String headerName = header.getKey();
String headerValue;
List<String> headerValues = header.getValue();
if (headerValues.size() == 1) {
headerValue = headerValues.get(0);
uc.setRequestProperty(headerName, headerValue);
} else {
StringBuilder b = new StringBuilder();
boolean add = false;
for (Object value : headerValues) {
if (add) {
b.append(',');
}
add = true;
b.append(value);
}
headerValue = b.toString();
uc.setRequestProperty(headerName, headerValue);
}
if (!isRestrictedHeaderPropertySet && !restrictedSent) {
if (isHeaderRestricted(headerName, headerValue)) {
restrictedSent = true;
}
}
}
if (restrictedSent) {
LOGGER.warning(LocalizationMessages.RESTRICTED_HEADER_POSSIBLY_IGNORED(ALLOW_RESTRICTED_HEADERS_SYSTEM_PROPERTY));
}
}
private boolean (String name, String value) {
name = name.toLowerCase(Locale.ROOT);
return name.startsWith("sec-")
|| restrictedHeaderSet.contains(name)
&& !("connection".equalsIgnoreCase(name) && "close".equalsIgnoreCase(value));
}
private static void setRequestMethodViaJreBugWorkaround(final HttpURLConnection httpURLConnection,
final String method) {
try {
httpURLConnection.setRequestMethod(method);
} catch (final ProtocolException pe) {
try {
AccessController
.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws NoSuchFieldException,
IllegalAccessException {
try {
httpURLConnection.setRequestMethod(method);
} catch (final ProtocolException pe) {
Class<?> connectionClass = httpURLConnection
.getClass();
try {
final Field delegateField = connectionClass.getDeclaredField("delegate");
delegateField.setAccessible(true);
HttpURLConnection delegateConnection =
(HttpURLConnection) delegateField.get(httpURLConnection);
setRequestMethodViaJreBugWorkaround(delegateConnection, method);
} catch (NoSuchFieldException e) {
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
try {
Field methodField;
while (connectionClass != null) {
try {
methodField = connectionClass
.getDeclaredField("method");
} catch (NoSuchFieldException e) {
connectionClass = connectionClass
.getSuperclass();
continue;
}
methodField.setAccessible(true);
methodField.set(httpURLConnection, method);
break;
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
return null;
}
});
} catch (final PrivilegedActionException e) {
final Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else {
throw new RuntimeException(cause);
}
}
}
}
@Override
public String getName() {
return "HttpUrlConnection " + AccessController.doPrivileged(PropertiesHelper.getSystemProperty("java.version"));
}
}