1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package com
.owncloud
.android
.network
;
21 import java
.io
.FileInputStream
;
22 import java
.io
.FileOutputStream
;
23 import java
.io
.IOException
;
24 import java
.io
.InputStream
;
26 import java
.security
.GeneralSecurityException
;
27 import java
.security
.KeyStore
;
28 import java
.security
.KeyStoreException
;
29 import java
.security
.NoSuchAlgorithmException
;
30 import java
.security
.cert
.Certificate
;
31 import java
.security
.cert
.CertificateException
;
33 import javax
.net
.ssl
.SSLContext
;
34 import javax
.net
.ssl
.TrustManager
;
36 import org
.apache
.commons
.httpclient
.MultiThreadedHttpConnectionManager
;
37 import org
.apache
.commons
.httpclient
.protocol
.Protocol
;
38 import org
.apache
.http
.conn
.ssl
.BrowserCompatHostnameVerifier
;
39 import org
.apache
.http
.conn
.ssl
.X509HostnameVerifier
;
41 import com
.owncloud
.android
.AccountUtils
;
42 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
44 import eu
.alefzero
.webdav
.WebdavClient
;
46 import android
.accounts
.Account
;
47 import android
.accounts
.AccountManager
;
48 import android
.content
.Context
;
49 import android
.net
.Uri
;
50 import android
.util
.Log
;
52 public class OwnCloudClientUtils
{
54 final private static String TAG
= "OwnCloudClientFactory";
56 /** Default timeout for waiting data from the server */
57 public static final int DEFAULT_DATA_TIMEOUT
= 60000;
59 /** Default timeout for establishing a connection */
60 public static final int DEFAULT_CONNECTION_TIMEOUT
= 60000;
62 /** Connection manager for all the WebdavClients */
63 private static MultiThreadedHttpConnectionManager mConnManager
= null
;
65 private static Protocol mDefaultHttpsProtocol
= null
;
67 private static AdvancedSslSocketFactory mAdvancedSslSocketFactory
= null
;
69 private static X509HostnameVerifier mHostnameVerifier
= null
;
73 * Creates a WebdavClient setup for an ownCloud account
75 * @param account The ownCloud account
76 * @param context The application context
77 * @return A WebdavClient object ready to be used
79 public static WebdavClient
createOwnCloudClient (Account account
, Context context
) {
80 //Log.d(TAG, "Creating WebdavClient associated to " + account.name);
82 Uri uri
= Uri
.parse(AccountUtils
.constructFullURLForAccount(context
, account
));
83 WebdavClient client
= createOwnCloudClient(uri
, context
);
85 String username
= account
.name
.substring(0, account
.name
.lastIndexOf('@'));
86 /*if (ama.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2)) {
87 // TODO - this is a trap; the OAuth access token shouldn't be saved as the account password
88 String accessToken = AccountManager.get(context).getPassword(account);
89 client.setCredentials("bearer", accessToken);
92 String password
= AccountManager
.get(context
).getPassword(account
);
93 //String password = am.blockingGetAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE, true);
94 client
.setCredentials(username
, password
);
102 * Creates a WebdavClient to try a new account before saving it
104 * @param uri URL to the ownCloud server
105 * @param username User name
106 * @param password User password
107 * @param context Android context where the WebdavClient is being created.
108 * @return A WebdavClient object ready to be used
110 public static WebdavClient
createOwnCloudClient(Uri uri
, String username
, String password
, Context context
) {
111 //Log.d(TAG, "Creating WebdavClient for " + username + "@" + uri);
113 WebdavClient client
= createOwnCloudClient(uri
, context
);
115 client
.setCredentials(username
, password
);
122 * Creates a WebdavClient to access a URL and sets the desired parameters for ownCloud client connections.
124 * @param uri URL to the ownCloud server
125 * @param context Android context where the WebdavClient is being created.
126 * @return A WebdavClient object ready to be used
128 public static WebdavClient
createOwnCloudClient(Uri uri
, Context context
) {
129 //Log.d(TAG, "Creating WebdavClient for " + uri);
131 //allowSelfsignedCertificates(true);
133 registerAdvancedSslContext(true
, context
);
134 } catch (GeneralSecurityException e
) {
135 Log
.e(TAG
, "Advanced SSL Context could not be loaded. Default SSL management in the system will be used for HTTPS connections", e
);
137 } catch (IOException e
) {
138 Log
.e(TAG
, "The local server truststore could not be read. Default SSL management in the system will be used for HTTPS connections", e
);
141 WebdavClient client
= new WebdavClient(getMultiThreadedConnManager());
143 client
.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT
, DEFAULT_CONNECTION_TIMEOUT
);
144 client
.setBaseUri(uri
);
151 * Allows or disallows self-signed certificates in ownCloud servers to reach
153 * @param allow 'True' to allow, 'false' to disallow
155 public static void allowSelfsignedCertificates(boolean allow
) {
158 pr
= Protocol
.getProtocol("https");
159 if (pr
!= null
&& mDefaultHttpsProtocol
== null
) {
160 mDefaultHttpsProtocol
= pr
;
162 } catch (IllegalStateException e
) {
163 // nothing to do here; really
165 boolean isAllowed
= (pr
!= null
&& pr
.getSocketFactory() instanceof EasySSLSocketFactory
);
166 if (allow
&& !isAllowed
) {
167 Protocol
.registerProtocol("https", new Protocol("https", new EasySSLSocketFactory(), 443));
168 } else if (!allow
&& isAllowed
) {
169 if (mDefaultHttpsProtocol
!= null
) {
170 Protocol
.registerProtocol("https", mDefaultHttpsProtocol
);
177 * Registers or unregisters the proper components for advanced SSL handling.
178 * @throws IOException
180 private static void registerAdvancedSslContext(boolean register
, Context context
) throws GeneralSecurityException
, IOException
{
183 pr
= Protocol
.getProtocol("https");
184 if (pr
!= null
&& mDefaultHttpsProtocol
== null
) {
185 mDefaultHttpsProtocol
= pr
;
187 } catch (IllegalStateException e
) {
188 // nothing to do here; really
190 boolean isRegistered
= (pr
!= null
&& pr
.getSocketFactory() instanceof AdvancedSslSocketFactory
);
191 if (register
&& !isRegistered
) {
192 Protocol
.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context
), 443));
194 } else if (!register
&& isRegistered
) {
195 if (mDefaultHttpsProtocol
!= null
) {
196 Protocol
.registerProtocol("https", mDefaultHttpsProtocol
);
201 public static AdvancedSslSocketFactory
getAdvancedSslSocketFactory(Context context
) throws GeneralSecurityException
, IOException
{
202 if (mAdvancedSslSocketFactory
== null
) {
203 KeyStore trustStore
= getKnownServersStore(context
);
204 AdvancedX509TrustManager trustMgr
= new AdvancedX509TrustManager(trustStore
);
205 TrustManager
[] tms
= new TrustManager
[] { trustMgr
};
207 SSLContext sslContext
= SSLContext
.getInstance("TLS");
208 sslContext
.init(null
, tms
, null
);
210 mHostnameVerifier
= new BrowserCompatHostnameVerifier();
211 mAdvancedSslSocketFactory
= new AdvancedSslSocketFactory(sslContext
, trustMgr
, mHostnameVerifier
);
213 return mAdvancedSslSocketFactory
;
217 private static String LOCAL_TRUSTSTORE_FILENAME
= "knownServers.bks";
219 private static String LOCAL_TRUSTSTORE_PASSWORD
= "password";
221 private static KeyStore mKnownServersStore
= null
;
224 * Returns the local store of reliable server certificates, explicitly accepted by the user.
226 * Returns a KeyStore instance with empty content if the local store was never created.
228 * Loads the store from the storage environment if needed.
230 * @param context Android context where the operation is being performed.
231 * @return KeyStore instance with explicitly-accepted server certificates.
232 * @throws KeyStoreException When the KeyStore instance could not be created.
233 * @throws IOException When an existing local trust store could not be loaded.
234 * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm.
235 * @throws CertificateException When an exception occurred while loading the certificates from the local trust store.
237 private static KeyStore
getKnownServersStore(Context context
) throws KeyStoreException
, IOException
, NoSuchAlgorithmException
, CertificateException
{
238 if (mKnownServersStore
== null
) {
239 //mKnownServersStore = KeyStore.getInstance("BKS");
240 mKnownServersStore
= KeyStore
.getInstance(KeyStore
.getDefaultType());
241 File localTrustStoreFile
= new File(context
.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME
);
242 Log
.d(TAG
, "Searching known-servers store at " + localTrustStoreFile
.getAbsolutePath());
243 if (localTrustStoreFile
.exists()) {
244 InputStream
in = new FileInputStream(localTrustStoreFile
);
246 mKnownServersStore
.load(in, LOCAL_TRUSTSTORE_PASSWORD
.toCharArray());
251 mKnownServersStore
.load(null
, LOCAL_TRUSTSTORE_PASSWORD
.toCharArray()); // necessary to initialize an empty KeyStore instance
254 return mKnownServersStore
;
258 public static void addCertToKnownServersStore(Certificate cert
, Context context
) throws KeyStoreException
, NoSuchAlgorithmException
,
259 CertificateException
, IOException
{
260 KeyStore knownServers
= getKnownServersStore(context
);
261 knownServers
.setCertificateEntry(Integer
.toString(cert
.hashCode()), cert
);
262 FileOutputStream fos
= null
;
264 fos
= context
.openFileOutput(LOCAL_TRUSTSTORE_FILENAME
, Context
.MODE_PRIVATE
);
265 knownServers
.store(fos
, LOCAL_TRUSTSTORE_PASSWORD
.toCharArray());
272 static private MultiThreadedHttpConnectionManager
getMultiThreadedConnManager() {
273 if (mConnManager
== null
) {
274 mConnManager
= new MultiThreadedHttpConnectionManager();
275 mConnManager
.getParams().setDefaultMaxConnectionsPerHost(5);
276 mConnManager
.getParams().setMaxTotalConnections(5);