1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2,
6 * as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package com
.owncloud
.android
.network
;
20 import java
.io
.FileInputStream
;
21 import java
.io
.FileOutputStream
;
22 import java
.io
.IOException
;
23 import java
.io
.InputStream
;
24 import java
.security
.GeneralSecurityException
;
25 import java
.security
.KeyStore
;
26 import java
.security
.KeyStoreException
;
27 import java
.security
.NoSuchAlgorithmException
;
28 import java
.security
.cert
.Certificate
;
29 import java
.security
.cert
.CertificateException
;
31 import javax
.net
.ssl
.SSLContext
;
32 import javax
.net
.ssl
.TrustManager
;
34 import org
.apache
.commons
.httpclient
.MultiThreadedHttpConnectionManager
;
35 import org
.apache
.commons
.httpclient
.protocol
.Protocol
;
36 import org
.apache
.http
.conn
.ssl
.BrowserCompatHostnameVerifier
;
37 import org
.apache
.http
.conn
.ssl
.X509HostnameVerifier
;
39 import com
.owncloud
.android
.AccountUtils
;
40 import com
.owncloud
.android
.authentication
.AccountAuthenticator
;
41 import com
.owncloud
.android
.Log_OC
;
43 import eu
.alefzero
.webdav
.WebdavClient
;
45 import android
.accounts
.Account
;
46 import android
.accounts
.AccountManager
;
47 import android
.accounts
.AccountManagerFuture
;
48 import android
.accounts
.AuthenticatorException
;
49 import android
.accounts
.OperationCanceledException
;
50 import android
.app
.Activity
;
51 import android
.content
.Context
;
52 import android
.net
.Uri
;
53 import android
.os
.Bundle
;
55 public class OwnCloudClientUtils
{
57 final private static String TAG
= OwnCloudClientUtils
.class.getSimpleName();
59 /** Default timeout for waiting data from the server */
60 public static final int DEFAULT_DATA_TIMEOUT
= 60000;
62 /** Default timeout for establishing a connection */
63 public static final int DEFAULT_CONNECTION_TIMEOUT
= 60000;
65 /** Connection manager for all the WebdavClients */
66 private static MultiThreadedHttpConnectionManager mConnManager
= null
;
68 private static Protocol mDefaultHttpsProtocol
= null
;
70 private static AdvancedSslSocketFactory mAdvancedSslSocketFactory
= null
;
72 private static X509HostnameVerifier mHostnameVerifier
= null
;
76 * Creates a WebdavClient setup for an ownCloud account
78 * Do not call this method from the main thread.
80 * @param account The ownCloud account
81 * @param appContext Android application context
82 * @return A WebdavClient object ready to be used
83 * @throws AuthenticatorException If the authenticator failed to get the authorization token for the account.
84 * @throws OperationCanceledException If the authenticator operation was cancelled while getting the authorization token for the account.
85 * @throws IOException If there was some I/O error while getting the authorization token for the account.
87 public static WebdavClient
createOwnCloudClient (Account account
, Context appContext
) throws OperationCanceledException
, AuthenticatorException
, IOException
{
88 //Log_OC.d(TAG, "Creating WebdavClient associated to " + account.name);
90 Uri uri
= Uri
.parse(AccountUtils
.constructFullURLForAccount(appContext
, account
));
91 WebdavClient client
= createOwnCloudClient(uri
, appContext
);
92 AccountManager am
= AccountManager
.get(appContext
);
93 if (am
.getUserData(account
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
) != null
) { // TODO avoid a call to getUserData here
94 String accessToken
= am
.blockingGetAuthToken(account
, AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
, false
);
95 client
.setBearerCredentials(accessToken
); // TODO not assume that the access token is a bearer token
98 String username
= account
.name
.substring(0, account
.name
.lastIndexOf('@'));
99 //String password = am.getPassword(account);
100 String password
= am
.blockingGetAuthToken(account
, AccountAuthenticator
.AUTH_TOKEN_TYPE_PASSWORD
, false
);
101 client
.setBasicCredentials(username
, password
);
108 public static WebdavClient
createOwnCloudClient (Account account
, Context appContext
, Activity currentActivity
) throws OperationCanceledException
, AuthenticatorException
, IOException
{
109 Uri uri
= Uri
.parse(AccountUtils
.constructFullURLForAccount(appContext
, account
));
110 WebdavClient client
= createOwnCloudClient(uri
, appContext
);
111 AccountManager am
= AccountManager
.get(appContext
);
112 if (am
.getUserData(account
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
) != null
) { // TODO avoid a call to getUserData here
113 AccountManagerFuture
<Bundle
> future
= am
.getAuthToken(account
, AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
, null
, currentActivity
, null
, null
);
114 Bundle result
= future
.getResult();
115 String accessToken
= result
.getString(AccountManager
.KEY_AUTHTOKEN
);
116 //String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, false);
117 if (accessToken
== null
) throw new AuthenticatorException("WTF!");
118 client
.setBearerCredentials(accessToken
); // TODO not assume that the access token is a bearer token
121 String username
= account
.name
.substring(0, account
.name
.lastIndexOf('@'));
122 //String password = am.getPassword(account);
123 //String password = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, false);
124 AccountManagerFuture
<Bundle
> future
= am
.getAuthToken(account
, AccountAuthenticator
.AUTH_TOKEN_TYPE_PASSWORD
, null
, currentActivity
, null
, null
);
125 Bundle result
= future
.getResult();
126 String password
= result
.getString(AccountManager
.KEY_AUTHTOKEN
);
127 client
.setBasicCredentials(username
, password
);
134 * Creates a WebdavClient to access a URL and sets the desired parameters for ownCloud client connections.
136 * @param uri URL to the ownCloud server
137 * @param context Android context where the WebdavClient is being created.
138 * @return A WebdavClient object ready to be used
140 public static WebdavClient
createOwnCloudClient(Uri uri
, Context context
) {
141 //Log_OC.d(TAG, "Creating WebdavClient for " + uri);
143 //allowSelfsignedCertificates(true);
145 registerAdvancedSslContext(true
, context
);
146 } catch (GeneralSecurityException e
) {
147 Log_OC
.e(TAG
, "Advanced SSL Context could not be loaded. Default SSL management in the system will be used for HTTPS connections", e
);
149 } catch (IOException e
) {
150 Log_OC
.e(TAG
, "The local server truststore could not be read. Default SSL management in the system will be used for HTTPS connections", e
);
153 WebdavClient client
= new WebdavClient(getMultiThreadedConnManager());
155 client
.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT
, DEFAULT_CONNECTION_TIMEOUT
);
156 client
.setBaseUri(uri
);
163 * Registers or unregisters the proper components for advanced SSL handling.
164 * @throws IOException
166 private static void registerAdvancedSslContext(boolean register
, Context context
) throws GeneralSecurityException
, IOException
{
169 pr
= Protocol
.getProtocol("https");
170 if (pr
!= null
&& mDefaultHttpsProtocol
== null
) {
171 mDefaultHttpsProtocol
= pr
;
173 } catch (IllegalStateException e
) {
174 // nothing to do here; really
176 boolean isRegistered
= (pr
!= null
&& pr
.getSocketFactory() instanceof AdvancedSslSocketFactory
);
177 if (register
&& !isRegistered
) {
178 Protocol
.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context
), 443));
180 } else if (!register
&& isRegistered
) {
181 if (mDefaultHttpsProtocol
!= null
) {
182 Protocol
.registerProtocol("https", mDefaultHttpsProtocol
);
187 public static AdvancedSslSocketFactory
getAdvancedSslSocketFactory(Context context
) throws GeneralSecurityException
, IOException
{
188 if (mAdvancedSslSocketFactory
== null
) {
189 KeyStore trustStore
= getKnownServersStore(context
);
190 AdvancedX509TrustManager trustMgr
= new AdvancedX509TrustManager(trustStore
);
191 TrustManager
[] tms
= new TrustManager
[] { trustMgr
};
193 SSLContext sslContext
= SSLContext
.getInstance("TLS");
194 sslContext
.init(null
, tms
, null
);
196 mHostnameVerifier
= new BrowserCompatHostnameVerifier();
197 mAdvancedSslSocketFactory
= new AdvancedSslSocketFactory(sslContext
, trustMgr
, mHostnameVerifier
);
199 return mAdvancedSslSocketFactory
;
203 private static String LOCAL_TRUSTSTORE_FILENAME
= "knownServers.bks";
205 private static String LOCAL_TRUSTSTORE_PASSWORD
= "password";
207 private static KeyStore mKnownServersStore
= null
;
210 * Returns the local store of reliable server certificates, explicitly accepted by the user.
212 * Returns a KeyStore instance with empty content if the local store was never created.
214 * Loads the store from the storage environment if needed.
216 * @param context Android context where the operation is being performed.
217 * @return KeyStore instance with explicitly-accepted server certificates.
218 * @throws KeyStoreException When the KeyStore instance could not be created.
219 * @throws IOException When an existing local trust store could not be loaded.
220 * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm.
221 * @throws CertificateException When an exception occurred while loading the certificates from the local trust store.
223 private static KeyStore
getKnownServersStore(Context context
) throws KeyStoreException
, IOException
, NoSuchAlgorithmException
, CertificateException
{
224 if (mKnownServersStore
== null
) {
225 //mKnownServersStore = KeyStore.getInstance("BKS");
226 mKnownServersStore
= KeyStore
.getInstance(KeyStore
.getDefaultType());
227 File localTrustStoreFile
= new File(context
.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME
);
228 Log_OC
.d(TAG
, "Searching known-servers store at " + localTrustStoreFile
.getAbsolutePath());
229 if (localTrustStoreFile
.exists()) {
230 InputStream
in = new FileInputStream(localTrustStoreFile
);
232 mKnownServersStore
.load(in, LOCAL_TRUSTSTORE_PASSWORD
.toCharArray());
237 mKnownServersStore
.load(null
, LOCAL_TRUSTSTORE_PASSWORD
.toCharArray()); // necessary to initialize an empty KeyStore instance
240 return mKnownServersStore
;
244 public static void addCertToKnownServersStore(Certificate cert
, Context context
) throws KeyStoreException
, NoSuchAlgorithmException
,
245 CertificateException
, IOException
{
246 KeyStore knownServers
= getKnownServersStore(context
);
247 knownServers
.setCertificateEntry(Integer
.toString(cert
.hashCode()), cert
);
248 FileOutputStream fos
= null
;
250 fos
= context
.openFileOutput(LOCAL_TRUSTSTORE_FILENAME
, Context
.MODE_PRIVATE
);
251 knownServers
.store(fos
, LOCAL_TRUSTSTORE_PASSWORD
.toCharArray());
258 static private MultiThreadedHttpConnectionManager
getMultiThreadedConnManager() {
259 if (mConnManager
== null
) {
260 mConnManager
= new MultiThreadedHttpConnectionManager();
261 mConnManager
.getParams().setDefaultMaxConnectionsPerHost(5);
262 mConnManager
.getParams().setMaxTotalConnections(5);