Stream media with OkHttp
This commit is contained in:
parent
b42143ed10
commit
0f974c59d5
|
@ -27,7 +27,7 @@ import java.util.List;
|
|||
import java.util.ListIterator;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import okhttp3.Response;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
|
@ -607,7 +607,7 @@ public class CachedMusicService implements MusicService {
|
|||
}
|
||||
|
||||
@Override
|
||||
public HttpResponse getDownloadInputStream(Context context, Entry song, long offset, int maxBitrate, SilentBackgroundTask task) throws Exception {
|
||||
public Response getDownloadInputStream(Context context, Entry song, long offset, int maxBitrate, SilentBackgroundTask task) throws Exception {
|
||||
return musicService.getDownloadInputStream(context, song, offset, maxBitrate, task);
|
||||
}
|
||||
|
||||
|
|
|
@ -38,10 +38,7 @@ import net.nullsum.audinaut.util.FileUtil;
|
|||
import net.nullsum.audinaut.util.SilentBackgroundTask;
|
||||
import net.nullsum.audinaut.util.Util;
|
||||
|
||||
import org.apache.http.Header;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpStatus;
|
||||
import okhttp3.Response;
|
||||
|
||||
/**
|
||||
* @author Sindre Mehus
|
||||
|
@ -454,21 +451,19 @@ public class DownloadFile implements BufferFile {
|
|||
}
|
||||
if(compare) {
|
||||
// Attempt partial HTTP GET, appending to the file if it exists.
|
||||
HttpResponse response = musicService.getDownloadInputStream(context, song, partialFile.length(), bitRate, DownloadTask.this);
|
||||
Header contentLengthHeader = response.getFirstHeader("Content-Length");
|
||||
if(contentLengthHeader != null) {
|
||||
String contentLengthString = contentLengthHeader.getValue();
|
||||
if(contentLengthString != null) {
|
||||
Log.i(TAG, "Content Length: " + contentLengthString);
|
||||
contentLength = Long.parseLong(contentLengthString);
|
||||
Response response = musicService.getDownloadInputStream(context, song, partialFile.length(), bitRate, DownloadTask.this);
|
||||
if(response.header("Content-Length") != null) {
|
||||
Log.i(TAG, "Content Length: " + contentLength);
|
||||
contentLength = contentLength;
|
||||
}
|
||||
}
|
||||
in = response.getEntity().getContent();
|
||||
boolean partial = response.getStatusLine().getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT;
|
||||
|
||||
boolean partial = response.code() == 206;
|
||||
if (partial) {
|
||||
Log.i(TAG, "Executed partial HTTP GET, skipping " + partialFile.length() + " bytes");
|
||||
}
|
||||
|
||||
in = response.body().byteStream();
|
||||
|
||||
out = new FileOutputStream(partialFile, partial);
|
||||
long n = copy(in, out);
|
||||
Log.i(TAG, "Downloaded " + n + " bytes to " + partialFile);
|
||||
|
|
|
@ -20,7 +20,7 @@ package net.nullsum.audinaut.service;
|
|||
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import okhttp3.Response;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
|
@ -87,7 +87,7 @@ public interface MusicService {
|
|||
|
||||
Bitmap getCoverArt(Context context, MusicDirectory.Entry entry, int size, ProgressListener progressListener, SilentBackgroundTask task) throws Exception;
|
||||
|
||||
HttpResponse getDownloadInputStream(Context context, MusicDirectory.Entry song, long offset, int maxBitrate, SilentBackgroundTask task) throws Exception;
|
||||
Response getDownloadInputStream(Context context, MusicDirectory.Entry song, long offset, int maxBitrate, SilentBackgroundTask task) throws Exception;
|
||||
|
||||
String getMusicUrl(Context context, MusicDirectory.Entry song, int maxBitrate) throws Exception;
|
||||
|
||||
|
|
|
@ -34,7 +34,7 @@ import android.content.SharedPreferences;
|
|||
import android.graphics.Bitmap;
|
||||
import android.util.Log;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import okhttp3.Response;
|
||||
|
||||
import net.nullsum.audinaut.domain.Artist;
|
||||
import net.nullsum.audinaut.domain.Genre;
|
||||
|
@ -206,7 +206,7 @@ public class OfflineMusicService implements MusicService {
|
|||
}
|
||||
|
||||
@Override
|
||||
public HttpResponse getDownloadInputStream(Context context, Entry song, long offset, int maxBitrate, SilentBackgroundTask task) throws Exception {
|
||||
public Response getDownloadInputStream(Context context, Entry song, long offset, int maxBitrate, SilentBackgroundTask task) throws Exception {
|
||||
throw new OfflineException(ERRORMSG);
|
||||
}
|
||||
|
||||
|
|
|
@ -34,37 +34,6 @@ import java.util.concurrent.atomic.AtomicReference;
|
|||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.methods.HttpRequestBase;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.apache.http.conn.params.ConnManagerParams;
|
||||
import org.apache.http.conn.params.ConnPerRouteBean;
|
||||
import org.apache.http.conn.scheme.PlainSocketFactory;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.conn.scheme.SocketFactory;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
|
||||
import org.apache.http.message.BasicHeader;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.params.BasicHttpParams;
|
||||
import org.apache.http.params.HttpConnectionParams;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.protocol.BasicHttpContext;
|
||||
import org.apache.http.protocol.ExecutionContext;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
@ -97,8 +66,6 @@ import net.nullsum.audinaut.service.parser.PlaylistsParser;
|
|||
import net.nullsum.audinaut.service.parser.RandomSongsParser;
|
||||
import net.nullsum.audinaut.service.parser.SearchResult2Parser;
|
||||
import net.nullsum.audinaut.service.parser.UserParser;
|
||||
import net.nullsum.audinaut.service.ssl.SSLSocketFactory;
|
||||
import net.nullsum.audinaut.service.ssl.TrustSelfSignedStrategy;
|
||||
import net.nullsum.audinaut.util.BackgroundTask;
|
||||
import net.nullsum.audinaut.util.Pair;
|
||||
import net.nullsum.audinaut.util.SilentBackgroundTask;
|
||||
|
@ -130,46 +97,13 @@ public class RESTMusicService implements MusicService {
|
|||
private static final int HTTP_REQUEST_MAX_ATTEMPTS = 5;
|
||||
private static final long REDIRECTION_CHECK_INTERVAL_MILLIS = 60L * 60L * 1000L;
|
||||
|
||||
private final DefaultHttpClient httpClient;
|
||||
private long redirectionLastChecked;
|
||||
private int redirectionNetworkType = -1;
|
||||
private String redirectFrom;
|
||||
private String redirectTo;
|
||||
private final ThreadSafeClientConnManager connManager;
|
||||
private Integer instance;
|
||||
|
||||
public RESTMusicService() {
|
||||
|
||||
// Create and initialize default HTTP parameters
|
||||
HttpParams params = new BasicHttpParams();
|
||||
ConnManagerParams.setMaxTotalConnections(params, 20);
|
||||
ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(20));
|
||||
HttpConnectionParams.setConnectionTimeout(params, SOCKET_CONNECT_TIMEOUT);
|
||||
HttpConnectionParams.setSoTimeout(params, SOCKET_READ_TIMEOUT_DEFAULT);
|
||||
|
||||
// Turn off stale checking. Our connections break all the time anyway,
|
||||
// and it's not worth it to pay the penalty of checking every time.
|
||||
HttpConnectionParams.setStaleCheckingEnabled(params, false);
|
||||
|
||||
// Create and initialize scheme registry
|
||||
SchemeRegistry schemeRegistry = new SchemeRegistry();
|
||||
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
|
||||
schemeRegistry.register(new Scheme("https", createSSLSocketFactory(), 443));
|
||||
|
||||
// Create an HttpClient with the ThreadSafeClientConnManager.
|
||||
// This connection manager must be used if more than one thread will
|
||||
// be using the HttpClient.
|
||||
connManager = new ThreadSafeClientConnManager(params, schemeRegistry);
|
||||
httpClient = new DefaultHttpClient(connManager, params);
|
||||
}
|
||||
|
||||
private SocketFactory createSSLSocketFactory() {
|
||||
try {
|
||||
return new SSLSocketFactory(new TrustSelfSignedStrategy(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
|
||||
} catch (Throwable x) {
|
||||
Log.e(TAG, "Failed to create custom SSL socket factory, using default.", x);
|
||||
return org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -744,48 +678,35 @@ public class RESTMusicService implements MusicService {
|
|||
}
|
||||
|
||||
@Override
|
||||
public HttpResponse getDownloadInputStream(Context context, MusicDirectory.Entry song, long offset, int maxBitrate, SilentBackgroundTask task) throws Exception {
|
||||
public Response getDownloadInputStream(Context context, MusicDirectory.Entry song, long offset, int maxBitrate, SilentBackgroundTask task) throws Exception {
|
||||
|
||||
OkHttpClient eagerClient = client.newBuilder()
|
||||
.readTimeout(30, TimeUnit.SECONDS)
|
||||
.build();
|
||||
|
||||
String url = getRestUrl(context, "stream");
|
||||
|
||||
// Set socket read timeout. Note: The timeout increases as the offset gets larger. This is
|
||||
// to avoid the thrashing effect seen when offset is combined with transcoding/downsampling on the server.
|
||||
// In that case, the server uses a long time before sending any data, causing the client to time out.
|
||||
HttpParams params = new BasicHttpParams();
|
||||
int timeout = (int) (SOCKET_READ_TIMEOUT_DOWNLOAD + offset * TIMEOUT_MILLIS_PER_OFFSET_BYTE);
|
||||
HttpConnectionParams.setSoTimeout(params, timeout);
|
||||
url += "&id=" + song.getId();
|
||||
|
||||
// Add "Range" header if offset is given.
|
||||
List<Header> headers = new ArrayList<Header>();
|
||||
Log.i(TAG, "Using music URL: " + url);
|
||||
|
||||
Builder builder = new FormBody.Builder();
|
||||
builder.add("id", song.getId());
|
||||
builder.add("maxBitRate", Integer.toString(maxBitrate));
|
||||
|
||||
RequestBody formBody = builder.build();
|
||||
|
||||
Request.Builder requestBuilder= new Request.Builder();
|
||||
if (offset > 0) {
|
||||
headers.add(new BasicHeader("Range", "bytes=" + offset + "-"));
|
||||
requestBuilder.header("Range", "bytes=" + offset + "-");
|
||||
}
|
||||
|
||||
List<String> parameterNames = new ArrayList<String>();
|
||||
parameterNames.add("id");
|
||||
parameterNames.add("maxBitRate");
|
||||
requestBuilder.url(url);
|
||||
// requestBuilder.post(formBody);
|
||||
|
||||
List<Object> parameterValues = new ArrayList<Object>();
|
||||
parameterValues.add(song.getId());
|
||||
parameterValues.add(maxBitrate);
|
||||
|
||||
HttpResponse response = getResponseForURL(context, url, params, parameterNames, parameterValues, headers, null, task, false);
|
||||
|
||||
// If content type is XML, an error occurred. Get it.
|
||||
String contentType = response.getEntity().getContentType().getValue();
|
||||
if (contentType != null && (contentType.startsWith("text/xml") || contentType.startsWith("text/html"))) {
|
||||
InputStream in = response.getEntity().getContent();
|
||||
Header contentEncoding = response.getEntity().getContentEncoding();
|
||||
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
|
||||
in = new GZIPInputStream(in);
|
||||
}
|
||||
try {
|
||||
new ErrorParser(context, getInstance(context)).parse(in);
|
||||
} finally {
|
||||
Util.close(in);
|
||||
}
|
||||
}
|
||||
Request request = requestBuilder.build();
|
||||
|
||||
Response response = eagerClient.newCall(request).execute();
|
||||
return response;
|
||||
}
|
||||
|
||||
|
@ -972,163 +893,6 @@ public class RESTMusicService implements MusicService {
|
|||
this.instance = instance;
|
||||
}
|
||||
|
||||
private HttpResponse getResponseForURL(Context context, String url, HttpParams requestParams,
|
||||
List<String> parameterNames, List<Object> parameterValues,
|
||||
List<Header> headers, ProgressListener progressListener, SilentBackgroundTask task, boolean throwsErrors) throws Exception {
|
||||
// If not too many parameters, extract them to the URL rather than relying on the HTTP POST request being
|
||||
// received intact. Remember, HTTP POST requests are converted to GET requests during HTTP redirects, thus
|
||||
// loosing its entity.
|
||||
if (parameterNames != null && parameterNames.size() < 10) {
|
||||
StringBuilder builder = new StringBuilder(url);
|
||||
for (int i = 0; i < parameterNames.size(); i++) {
|
||||
builder.append("&").append(parameterNames.get(i)).append("=");
|
||||
String part = URLEncoder.encode(String.valueOf(parameterValues.get(i)), "UTF-8");
|
||||
part = part.replaceAll("\\%27", "'");
|
||||
builder.append(part);
|
||||
}
|
||||
url = builder.toString();
|
||||
parameterNames = null;
|
||||
parameterValues = null;
|
||||
}
|
||||
|
||||
String rewrittenUrl = rewriteUrlWithRedirect(context, url);
|
||||
return executeWithRetry(context, rewrittenUrl, url, requestParams, parameterNames, parameterValues, headers, progressListener, task, throwsErrors);
|
||||
}
|
||||
|
||||
private HttpResponse executeWithRetry(final Context context, String url, String originalUrl, HttpParams requestParams,
|
||||
List<String> parameterNames, List<Object> parameterValues,
|
||||
List<Header> headers, ProgressListener progressListener, SilentBackgroundTask task, boolean throwErrors) throws Exception {
|
||||
// Strip out sensitive information from log
|
||||
if(url.indexOf("scanstatus") == -1) {
|
||||
Log.i(TAG, stripUrlInfo(url));
|
||||
}
|
||||
|
||||
SharedPreferences prefs = Util.getPreferences(context);
|
||||
int networkTimeout = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_NETWORK_TIMEOUT, "15000"));
|
||||
HttpParams newParams = httpClient.getParams();
|
||||
HttpConnectionParams.setSoTimeout(newParams, networkTimeout);
|
||||
httpClient.setParams(newParams);
|
||||
|
||||
final AtomicReference<Boolean> isCancelled = new AtomicReference<Boolean>(false);
|
||||
int attempts = 0;
|
||||
while (true) {
|
||||
attempts++;
|
||||
HttpContext httpContext = new BasicHttpContext();
|
||||
final HttpRequestBase request = (url.indexOf("rest") == -1) ? new HttpGet(url) : new HttpPost(url);
|
||||
|
||||
if (task != null) {
|
||||
// Attempt to abort the HTTP request if the task is cancelled.
|
||||
task.setOnCancelListener(new BackgroundTask.OnCancelListener() {
|
||||
@Override
|
||||
public void onCancel() {
|
||||
try {
|
||||
isCancelled.set(true);
|
||||
if(Thread.currentThread() == Looper.getMainLooper().getThread()) {
|
||||
new SilentBackgroundTask<Void>(context) {
|
||||
@Override
|
||||
protected Void doInBackground() throws Throwable {
|
||||
request.abort();
|
||||
return null;
|
||||
}
|
||||
}.execute();
|
||||
} else {
|
||||
request.abort();
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Log.e(TAG, "Failed to stop http task", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (parameterNames != null && request instanceof HttpPost) {
|
||||
List<NameValuePair> params = new ArrayList<NameValuePair>();
|
||||
for (int i = 0; i < parameterNames.size(); i++) {
|
||||
params.add(new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
|
||||
}
|
||||
((HttpPost) request).setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
|
||||
}
|
||||
|
||||
if (requestParams != null) {
|
||||
request.setParams(requestParams);
|
||||
}
|
||||
|
||||
if (headers != null) {
|
||||
for (Header header : headers) {
|
||||
request.addHeader(header);
|
||||
}
|
||||
}
|
||||
if(url.indexOf("getCoverArt") == -1 && url.indexOf("stream") == -1) {
|
||||
request.addHeader("Accept-Encoding", "gzip");
|
||||
}
|
||||
request.addHeader("User-Agent", Constants.REST_CLIENT_ID);
|
||||
|
||||
// Set credentials to get through apache proxies that require authentication.
|
||||
int instance = getInstance(context);
|
||||
String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
|
||||
String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);
|
||||
httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
|
||||
new UsernamePasswordCredentials(username, password));
|
||||
|
||||
try {
|
||||
HttpResponse response = httpClient.execute(request, httpContext);
|
||||
detectRedirect(originalUrl, context, httpContext);
|
||||
return response;
|
||||
} catch (IOException x) {
|
||||
request.abort();
|
||||
if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || isCancelled.get() || throwErrors) {
|
||||
throw x;
|
||||
}
|
||||
if (progressListener != null) {
|
||||
String msg = context.getResources().getString(R.string.music_service_retry, attempts, HTTP_REQUEST_MAX_ATTEMPTS - 1);
|
||||
progressListener.updateProgress(msg);
|
||||
}
|
||||
Log.w(TAG, "Got IOException " + x + " (" + attempts + "), will retry");
|
||||
increaseTimeouts(requestParams);
|
||||
Thread.sleep(2000L);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void increaseTimeouts(HttpParams requestParams) {
|
||||
if (requestParams != null) {
|
||||
int connectTimeout = HttpConnectionParams.getConnectionTimeout(requestParams);
|
||||
if (connectTimeout != 0) {
|
||||
HttpConnectionParams.setConnectionTimeout(requestParams, (int) (connectTimeout * 1.3F));
|
||||
}
|
||||
int readTimeout = HttpConnectionParams.getSoTimeout(requestParams);
|
||||
if (readTimeout != 0) {
|
||||
HttpConnectionParams.setSoTimeout(requestParams, (int) (readTimeout * 1.5F));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void detectRedirect(String originalUrl, Context context, HttpContext httpContext) throws Exception {
|
||||
HttpUriRequest request = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
|
||||
HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
|
||||
|
||||
// Sometimes the request doesn't contain the "http://host" part
|
||||
String redirectedUrl;
|
||||
if (request.getURI().getScheme() == null) {
|
||||
redirectedUrl = host.toURI() + request.getURI();
|
||||
} else {
|
||||
redirectedUrl = request.getURI().toString();
|
||||
}
|
||||
|
||||
int fromIndex = originalUrl.indexOf("/rest/");
|
||||
int toIndex = redirectedUrl.indexOf("/rest/");
|
||||
if(fromIndex != -1 && toIndex != -1 && !Util.equals(originalUrl, redirectedUrl)) {
|
||||
redirectFrom = originalUrl.substring(0, fromIndex);
|
||||
redirectTo = redirectedUrl.substring(0, toIndex);
|
||||
|
||||
if (redirectFrom.compareTo(redirectTo) != 0) {
|
||||
Log.i(TAG, redirectFrom + " redirects to " + redirectTo);
|
||||
}
|
||||
redirectionLastChecked = System.currentTimeMillis();
|
||||
redirectionNetworkType = getCurrentNetworkType(context);
|
||||
}
|
||||
}
|
||||
|
||||
private String rewriteUrlWithRedirect(Context context, String url) {
|
||||
|
||||
// Only cache for a certain time.
|
||||
|
@ -1177,8 +941,4 @@ public class RESTMusicService implements MusicService {
|
|||
return Util.getRestUrl(context, method, instance, allowAltAddress);
|
||||
}
|
||||
}
|
||||
|
||||
public HttpClient getHttpClient() {
|
||||
return httpClient;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,553 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists of voluntary contributions made by many
|
||||
* individuals on behalf of the Apache Software Foundation. For more
|
||||
* information on the Apache Software Foundation, please see
|
||||
* <http://www.apache.org/>.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.nullsum.audinaut.service.ssl;
|
||||
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
import org.apache.http.conn.ConnectTimeoutException;
|
||||
import org.apache.http.conn.scheme.HostNameResolver;
|
||||
import org.apache.http.conn.scheme.LayeredSocketFactory;
|
||||
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.StrictHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.X509HostnameVerifier;
|
||||
import org.apache.http.params.HttpConnectionParams;
|
||||
import org.apache.http.params.HttpParams;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import javax.net.ssl.KeyManager;
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Array;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.Provider;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.Security;
|
||||
import java.security.UnrecoverableKeyException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Layered socket factory for TLS/SSL connections.
|
||||
* <p>
|
||||
* SSLSocketFactory can be used to validate the identity of the HTTPS server against a list of
|
||||
* trusted certificates and to authenticate to the HTTPS server using a private key.
|
||||
* <p>
|
||||
* SSLSocketFactory will enable server authentication when supplied with
|
||||
* a {@link KeyStore trust-store} file containing one or several trusted certificates. The client
|
||||
* secure socket will reject the connection during the SSL session handshake if the target HTTPS
|
||||
* server attempts to authenticate itself with a non-trusted certificate.
|
||||
* <p>
|
||||
* Use JDK keytool utility to import a trusted certificate and generate a trust-store file:
|
||||
* <pre>
|
||||
* keytool -import -alias "my server cert" -file server.crt -keystore my.truststore
|
||||
* </pre>
|
||||
* <p>
|
||||
* In special cases the standard trust verification process can be bypassed by using a custom
|
||||
* {@link TrustStrategy}. This interface is primarily intended for allowing self-signed
|
||||
* certificates to be accepted as trusted without having to add them to the trust-store file.
|
||||
* <p>
|
||||
* The following parameters can be used to customize the behavior of this
|
||||
* class:
|
||||
* <ul>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
* SSLSocketFactory will enable client authentication when supplied with
|
||||
* a {@link KeyStore key-store} file containing a private key/public certificate
|
||||
* pair. The client secure socket will use the private key to authenticate
|
||||
* itself to the target HTTPS server during the SSL session handshake if
|
||||
* requested to do so by the server.
|
||||
* The target HTTPS server will in its turn verify the certificate presented
|
||||
* by the client in order to establish client's authenticity
|
||||
* <p>
|
||||
* Use the following sequence of actions to generate a key-store file
|
||||
* </p>
|
||||
* <ul>
|
||||
* <li>
|
||||
* <p>
|
||||
* Use JDK keytool utility to generate a new key
|
||||
* <pre>keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore</pre>
|
||||
* For simplicity use the same password for the key as that of the key-store
|
||||
* </p>
|
||||
* </li>
|
||||
* <li>
|
||||
* <p>
|
||||
* Issue a certificate signing request (CSR)
|
||||
* <pre>keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore</pre>
|
||||
* </p>
|
||||
* </li>
|
||||
* <li>
|
||||
* <p>
|
||||
* Send the certificate request to the trusted Certificate Authority for signature.
|
||||
* One may choose to act as her own CA and sign the certificate request using a PKI
|
||||
* tool, such as OpenSSL.
|
||||
* </p>
|
||||
* </li>
|
||||
* <li>
|
||||
* <p>
|
||||
* Import the trusted CA root certificate
|
||||
* <pre>keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore</pre>
|
||||
* </p>
|
||||
* </li>
|
||||
* <li>
|
||||
* <p>
|
||||
* Import the PKCS#7 file containg the complete certificate chain
|
||||
* <pre>keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore</pre>
|
||||
* </p>
|
||||
* </li>
|
||||
* <li>
|
||||
* <p>
|
||||
* Verify the content the resultant keystore file
|
||||
* <pre>keytool -list -v -keystore my.keystore</pre>
|
||||
* </p>
|
||||
* </li>
|
||||
* </ul>
|
||||
*
|
||||
* @since 4.0
|
||||
*/
|
||||
public class SSLSocketFactory implements LayeredSocketFactory {
|
||||
private static final String TAG = SSLSocketFactory.class.getSimpleName();
|
||||
public static final String TLS = "TLS";
|
||||
|
||||
public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER
|
||||
= new AllowAllHostnameVerifier();
|
||||
|
||||
public static final X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
|
||||
= new BrowserCompatHostnameVerifier();
|
||||
|
||||
public static final X509HostnameVerifier STRICT_HOSTNAME_VERIFIER
|
||||
= new StrictHostnameVerifier();
|
||||
|
||||
/**
|
||||
* The default factory using the default JVM settings for secure connections.
|
||||
*/
|
||||
private static final SSLSocketFactory DEFAULT_FACTORY = new SSLSocketFactory();
|
||||
|
||||
/**
|
||||
* Gets the default factory, which uses the default JVM settings for secure
|
||||
* connections.
|
||||
*
|
||||
* @return the default factory
|
||||
*/
|
||||
public static SSLSocketFactory getSocketFactory() {
|
||||
return DEFAULT_FACTORY;
|
||||
}
|
||||
|
||||
private final javax.net.ssl.SSLSocketFactory socketfactory;
|
||||
private final HostNameResolver nameResolver;
|
||||
// TODO: make final
|
||||
private volatile X509HostnameVerifier hostnameVerifier;
|
||||
|
||||
private static SSLContext createSSLContext(
|
||||
String algorithm,
|
||||
final KeyStore keystore,
|
||||
final String keystorePassword,
|
||||
final KeyStore truststore,
|
||||
final SecureRandom random,
|
||||
final TrustStrategy trustStrategy)
|
||||
throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
|
||||
if (algorithm == null) {
|
||||
algorithm = TLS;
|
||||
}
|
||||
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
|
||||
KeyManagerFactory.getDefaultAlgorithm());
|
||||
kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray(): null);
|
||||
KeyManager[] keymanagers = kmfactory.getKeyManagers();
|
||||
TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
|
||||
TrustManagerFactory.getDefaultAlgorithm());
|
||||
tmfactory.init(keystore);
|
||||
TrustManager[] trustmanagers = tmfactory.getTrustManagers();
|
||||
if (trustmanagers != null && trustStrategy != null) {
|
||||
for (int i = 0; i < trustmanagers.length; i++) {
|
||||
TrustManager tm = trustmanagers[i];
|
||||
if (tm instanceof X509TrustManager) {
|
||||
trustmanagers[i] = new TrustManagerDecorator(
|
||||
(X509TrustManager) tm, trustStrategy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SSLContext sslcontext = SSLContext.getInstance(algorithm);
|
||||
sslcontext.init(keymanagers, trustmanagers, random);
|
||||
return sslcontext;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link #SSLSocketFactory(String, KeyStore, String, KeyStore, SecureRandom, X509HostnameVerifier)}
|
||||
*/
|
||||
@Deprecated
|
||||
public SSLSocketFactory(
|
||||
final String algorithm,
|
||||
final KeyStore keystore,
|
||||
final String keystorePassword,
|
||||
final KeyStore truststore,
|
||||
final SecureRandom random,
|
||||
final HostNameResolver nameResolver)
|
||||
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
|
||||
this(createSSLContext(
|
||||
algorithm, keystore, keystorePassword, truststore, random, null),
|
||||
nameResolver);
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public SSLSocketFactory(
|
||||
String algorithm,
|
||||
final KeyStore keystore,
|
||||
final String keystorePassword,
|
||||
final KeyStore truststore,
|
||||
final SecureRandom random,
|
||||
final X509HostnameVerifier hostnameVerifier)
|
||||
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
|
||||
this(createSSLContext(
|
||||
algorithm, keystore, keystorePassword, truststore, random, null),
|
||||
hostnameVerifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public SSLSocketFactory(
|
||||
String algorithm,
|
||||
final KeyStore keystore,
|
||||
final String keystorePassword,
|
||||
final KeyStore truststore,
|
||||
final SecureRandom random,
|
||||
final TrustStrategy trustStrategy,
|
||||
final X509HostnameVerifier hostnameVerifier)
|
||||
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
|
||||
this(createSSLContext(
|
||||
algorithm, keystore, keystorePassword, truststore, random, trustStrategy),
|
||||
hostnameVerifier);
|
||||
}
|
||||
|
||||
public SSLSocketFactory(
|
||||
final KeyStore keystore,
|
||||
final String keystorePassword,
|
||||
final KeyStore truststore)
|
||||
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
|
||||
this(TLS, keystore, keystorePassword, truststore, null, null, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
|
||||
}
|
||||
|
||||
public SSLSocketFactory(
|
||||
final KeyStore keystore,
|
||||
final String keystorePassword)
|
||||
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException{
|
||||
this(TLS, keystore, keystorePassword, null, null, null, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
|
||||
}
|
||||
|
||||
public SSLSocketFactory(
|
||||
final KeyStore truststore)
|
||||
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
|
||||
this(TLS, null, null, truststore, null, null, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public SSLSocketFactory(
|
||||
final TrustStrategy trustStrategy,
|
||||
final X509HostnameVerifier hostnameVerifier)
|
||||
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
|
||||
this(TLS, null, null, null, null, trustStrategy, hostnameVerifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public SSLSocketFactory(
|
||||
final TrustStrategy trustStrategy)
|
||||
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
|
||||
this(TLS, null, null, null, null, trustStrategy, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
|
||||
}
|
||||
|
||||
public SSLSocketFactory(final SSLContext sslContext) {
|
||||
this(sslContext, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link #SSLSocketFactory(SSLContext)}
|
||||
*/
|
||||
@Deprecated
|
||||
public SSLSocketFactory(
|
||||
final SSLContext sslContext, final HostNameResolver nameResolver) {
|
||||
super();
|
||||
this.socketfactory = sslContext.getSocketFactory();
|
||||
this.hostnameVerifier = BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
|
||||
this.nameResolver = nameResolver;
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public SSLSocketFactory(
|
||||
final SSLContext sslContext, final X509HostnameVerifier hostnameVerifier) {
|
||||
super();
|
||||
this.socketfactory = sslContext.getSocketFactory();
|
||||
this.hostnameVerifier = hostnameVerifier;
|
||||
this.nameResolver = null;
|
||||
}
|
||||
|
||||
private SSLSocketFactory() {
|
||||
super();
|
||||
this.socketfactory = HttpsURLConnection.getDefaultSSLSocketFactory();
|
||||
this.hostnameVerifier = null;
|
||||
this.nameResolver = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param params Optional parameters. Parameters passed to this method will have no effect.
|
||||
* This method will create a unconnected instance of {@link Socket} class
|
||||
* using {@link javax.net.ssl.SSLSocketFactory#createSocket()} method.
|
||||
* @since 4.1
|
||||
*/
|
||||
@SuppressWarnings("cast")
|
||||
public Socket createSocket(final HttpParams params) throws IOException {
|
||||
// the cast makes sure that the factory is working as expected
|
||||
SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket();
|
||||
sslSocket.setEnabledProtocols(getProtocols(sslSocket));
|
||||
sslSocket.setEnabledCipherSuites(getCiphers(sslSocket));
|
||||
return sslSocket;
|
||||
}
|
||||
|
||||
@SuppressWarnings("cast")
|
||||
public Socket createSocket() throws IOException {
|
||||
// the cast makes sure that the factory is working as expected
|
||||
SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket();
|
||||
sslSocket.setEnabledProtocols(getProtocols(sslSocket));
|
||||
sslSocket.setEnabledCipherSuites(getCiphers(sslSocket));
|
||||
return sslSocket;
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public Socket connectSocket(
|
||||
final Socket sock,
|
||||
final InetSocketAddress remoteAddress,
|
||||
final InetSocketAddress localAddress,
|
||||
final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
|
||||
if (remoteAddress == null) {
|
||||
throw new IllegalArgumentException("Remote address may not be null");
|
||||
}
|
||||
if (params == null) {
|
||||
throw new IllegalArgumentException("HTTP parameters may not be null");
|
||||
}
|
||||
SSLSocket sslsock = (SSLSocket) (sock != null ? sock : createSocket());
|
||||
if (localAddress != null) {
|
||||
// sslsock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
|
||||
sslsock.bind(localAddress);
|
||||
}
|
||||
|
||||
setHostName(sslsock, remoteAddress.getHostName());
|
||||
int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
|
||||
int soTimeout = HttpConnectionParams.getSoTimeout(params);
|
||||
|
||||
try {
|
||||
sslsock.connect(remoteAddress, connTimeout);
|
||||
} catch (SocketTimeoutException ex) {
|
||||
throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
|
||||
+ remoteAddress.getAddress() + " timed out");
|
||||
}
|
||||
sslsock.setSoTimeout(soTimeout);
|
||||
if (this.hostnameVerifier != null) {
|
||||
try {
|
||||
this.hostnameVerifier.verify(remoteAddress.getHostName(), sslsock);
|
||||
// verifyHostName() didn't blowup - good!
|
||||
} catch (IOException iox) {
|
||||
// close the socket before re-throwing the exception
|
||||
try { sslsock.close(); } catch (Exception x) { /*ignore*/ }
|
||||
throw iox;
|
||||
}
|
||||
}
|
||||
return sslsock;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Checks whether a socket connection is secure.
|
||||
* This factory creates TLS/SSL socket connections
|
||||
* which, by default, are considered secure.
|
||||
* <br/>
|
||||
* Derived classes may override this method to perform
|
||||
* runtime checks, for example based on the cypher suite.
|
||||
*
|
||||
* @param sock the connected socket
|
||||
*
|
||||
* @return <code>true</code>
|
||||
*
|
||||
* @throws IllegalArgumentException if the argument is invalid
|
||||
*/
|
||||
public boolean isSecure(final Socket sock) throws IllegalArgumentException {
|
||||
if (sock == null) {
|
||||
throw new IllegalArgumentException("Socket may not be null");
|
||||
}
|
||||
// This instanceof check is in line with createSocket() above.
|
||||
if (!(sock instanceof SSLSocket)) {
|
||||
throw new IllegalArgumentException("Socket not created by this factory");
|
||||
}
|
||||
// This check is performed last since it calls the argument object.
|
||||
if (sock.isClosed()) {
|
||||
throw new IllegalArgumentException("Socket is closed");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public Socket createLayeredSocket(
|
||||
final Socket socket,
|
||||
final String host,
|
||||
final int port,
|
||||
final boolean autoClose) throws IOException, UnknownHostException {
|
||||
SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(
|
||||
socket,
|
||||
host,
|
||||
port,
|
||||
autoClose
|
||||
);
|
||||
sslSocket.setEnabledProtocols(getProtocols(sslSocket));
|
||||
sslSocket.setEnabledCipherSuites(getCiphers(sslSocket));
|
||||
if (this.hostnameVerifier != null) {
|
||||
this.hostnameVerifier.verify(host, sslSocket);
|
||||
}
|
||||
// verifyHostName() didn't blowup - good!
|
||||
return sslSocket;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void setHostnameVerifier(X509HostnameVerifier hostnameVerifier) {
|
||||
if ( hostnameVerifier == null ) {
|
||||
throw new IllegalArgumentException("Hostname verifier may not be null");
|
||||
}
|
||||
this.hostnameVerifier = hostnameVerifier;
|
||||
}
|
||||
|
||||
public X509HostnameVerifier getHostnameVerifier() {
|
||||
return this.hostnameVerifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)}
|
||||
*/
|
||||
@Deprecated
|
||||
public Socket connectSocket(
|
||||
final Socket socket,
|
||||
final String host, int port,
|
||||
final InetAddress localAddress, int localPort,
|
||||
final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
|
||||
InetSocketAddress local = null;
|
||||
if (localAddress != null || localPort > 0) {
|
||||
// we need to bind explicitly
|
||||
if (localPort < 0) {
|
||||
localPort = 0; // indicates "any"
|
||||
}
|
||||
local = new InetSocketAddress(localAddress, localPort);
|
||||
}
|
||||
InetAddress remoteAddress;
|
||||
if (this.nameResolver != null) {
|
||||
remoteAddress = this.nameResolver.resolve(host);
|
||||
} else {
|
||||
remoteAddress = InetAddress.getByName(host);
|
||||
}
|
||||
InetSocketAddress remote = new InetSocketAddress(remoteAddress, port);
|
||||
return connectSocket(socket, remote, local, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link #createLayeredSocket(Socket, String, int, boolean)}
|
||||
*/
|
||||
@Deprecated
|
||||
public Socket createSocket(
|
||||
final Socket socket,
|
||||
final String host, int port,
|
||||
boolean autoClose) throws IOException, UnknownHostException {
|
||||
SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(socket, host, port, autoClose);
|
||||
sslSocket.setEnabledProtocols(getProtocols(sslSocket));
|
||||
sslSocket.setEnabledCipherSuites(getCiphers(sslSocket));
|
||||
setHostName(sslSocket, host);
|
||||
return sslSocket;
|
||||
}
|
||||
|
||||
private void setHostName(SSLSocket sslsock, String hostname){
|
||||
try {
|
||||
java.lang.reflect.Method setHostnameMethod = sslsock.getClass().getMethod("setHostname", String.class);
|
||||
setHostnameMethod.invoke(sslsock, hostname);
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "SNI not useable", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String[] getProtocols(SSLSocket sslSocket) {
|
||||
String[] protocols = sslSocket.getEnabledProtocols();
|
||||
|
||||
// Remove SSLv3 if it is not the only option
|
||||
if(protocols.length > 1) {
|
||||
List<String> protocolList = new ArrayList(Arrays.asList(protocols));
|
||||
protocolList.remove("SSLv3");
|
||||
protocols = protocolList.toArray(new String[protocolList.size()]);
|
||||
}
|
||||
|
||||
return protocols;
|
||||
}
|
||||
|
||||
private String[] getCiphers(SSLSocket sslSocket) {
|
||||
String[] ciphers = sslSocket.getEnabledCipherSuites();
|
||||
|
||||
List<String> enabledCiphers = new ArrayList(Arrays.asList(ciphers));
|
||||
// On Android 5.0 release, Jetty doesn't seem to play nice with these ciphers
|
||||
// Issue seems to have been fixed in M, and now won't work without them. Because Google
|
||||
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
|
||||
enabledCiphers.remove("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");
|
||||
enabledCiphers.remove("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA");
|
||||
}
|
||||
|
||||
ciphers = enabledCiphers.toArray(new String[enabledCiphers.size()]);
|
||||
return ciphers;
|
||||
}
|
||||
}
|
|
@ -1,65 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists of voluntary contributions made by many
|
||||
* individuals on behalf of the Apache Software Foundation. For more
|
||||
* information on the Apache Software Foundation, please see
|
||||
* <http://www.apache.org/>.
|
||||
*
|
||||
*/
|
||||
package net.nullsum.audinaut.service.ssl;
|
||||
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
class TrustManagerDecorator implements X509TrustManager {
|
||||
|
||||
private final X509TrustManager trustManager;
|
||||
private final TrustStrategy trustStrategy;
|
||||
|
||||
TrustManagerDecorator(final X509TrustManager trustManager, final TrustStrategy trustStrategy) {
|
||||
super();
|
||||
this.trustManager = trustManager;
|
||||
this.trustStrategy = trustStrategy;
|
||||
}
|
||||
|
||||
public void checkClientTrusted(
|
||||
final X509Certificate[] chain, final String authType) throws CertificateException {
|
||||
this.trustManager.checkClientTrusted(chain, authType);
|
||||
}
|
||||
|
||||
public void checkServerTrusted(
|
||||
final X509Certificate[] chain, final String authType) throws CertificateException {
|
||||
if (!this.trustStrategy.isTrusted(chain, authType)) {
|
||||
this.trustManager.checkServerTrusted(chain, authType);
|
||||
}
|
||||
}
|
||||
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return this.trustManager.getAcceptedIssuers();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,44 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists of voluntary contributions made by many
|
||||
* individuals on behalf of the Apache Software Foundation. For more
|
||||
* information on the Apache Software Foundation, please see
|
||||
* <http://www.apache.org/>.
|
||||
*
|
||||
*/
|
||||
package net.nullsum.audinaut.service.ssl;
|
||||
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
/**
|
||||
* A trust strategy that accepts self-signed certificates as trusted. Verification of all other
|
||||
* certificates is done by the trust manager configured in the SSL context.
|
||||
*
|
||||
* @since 4.1
|
||||
*/
|
||||
public class TrustSelfSignedStrategy implements TrustStrategy {
|
||||
|
||||
public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,57 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists of voluntary contributions made by many
|
||||
* individuals on behalf of the Apache Software Foundation. For more
|
||||
* information on the Apache Software Foundation, please see
|
||||
* <http://www.apache.org/>.
|
||||
*
|
||||
*/
|
||||
package net.nullsum.audinaut.service.ssl;
|
||||
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
/**
|
||||
* A strategy to establish trustworthiness of certificates without consulting the trust manager
|
||||
* configured in the actual SSL context. This interface can be used to override the standard
|
||||
* JSSE certificate verification process.
|
||||
*
|
||||
* @since 4.1
|
||||
*/
|
||||
public interface TrustStrategy {
|
||||
|
||||
/**
|
||||
* Determines whether the certificate chain can be trusted without consulting the trust manager
|
||||
* configured in the actual SSL context. This method can be used to override the standard JSSE
|
||||
* certificate verification process.
|
||||
* <p>
|
||||
* Please note that, if this method returns <code>false</code>, the trust manager configured
|
||||
* in the actual SSL context can still clear the certificate as trusted.
|
||||
*
|
||||
* @param chain the peer certificate chain
|
||||
* @param authType the authentication type based on the client certificate
|
||||
* @return <code>true</code> if the certificate can be trusted without verification by
|
||||
* the trust manager, <code>false</code> otherwise.
|
||||
* @throws CertificateException thrown if the certificate is not trusted or invalid.
|
||||
*/
|
||||
boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException;
|
||||
|
||||
}
|
|
@ -65,8 +65,6 @@ import net.nullsum.audinaut.domain.RepeatMode;
|
|||
import net.nullsum.audinaut.receiver.MediaButtonIntentReceiver;
|
||||
import net.nullsum.audinaut.service.DownloadService;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.File;
|
||||
|
|
Loading…
Reference in New Issue