OwnCloudClientUtils.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /* ownCloud Android client application
  2. * Copyright (C) 2012-2013 ownCloud Inc.
  3. *
  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.
  7. *
  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.
  12. *
  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/>.
  15. *
  16. */
  17. package com.owncloud.android.network;
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.FileOutputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.security.GeneralSecurityException;
  24. import java.security.KeyStore;
  25. import java.security.KeyStoreException;
  26. import java.security.NoSuchAlgorithmException;
  27. import java.security.cert.Certificate;
  28. import java.security.cert.CertificateException;
  29. import javax.net.ssl.SSLContext;
  30. import javax.net.ssl.TrustManager;
  31. import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
  32. import org.apache.commons.httpclient.protocol.Protocol;
  33. import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
  34. import org.apache.http.conn.ssl.X509HostnameVerifier;
  35. import com.owncloud.android.AccountUtils;
  36. import com.owncloud.android.authentication.AccountAuthenticator;
  37. import com.owncloud.android.Log_OC;
  38. import eu.alefzero.webdav.WebdavClient;
  39. import android.accounts.Account;
  40. import android.accounts.AccountManager;
  41. import android.accounts.AccountManagerFuture;
  42. import android.accounts.AuthenticatorException;
  43. import android.accounts.OperationCanceledException;
  44. import android.app.Activity;
  45. import android.content.Context;
  46. import android.net.Uri;
  47. import android.os.Bundle;
  48. public class OwnCloudClientUtils {
  49. final private static String TAG = OwnCloudClientUtils.class.getSimpleName();
  50. /** Default timeout for waiting data from the server */
  51. public static final int DEFAULT_DATA_TIMEOUT = 60000;
  52. /** Default timeout for establishing a connection */
  53. public static final int DEFAULT_CONNECTION_TIMEOUT = 60000;
  54. /** Connection manager for all the WebdavClients */
  55. private static MultiThreadedHttpConnectionManager mConnManager = null;
  56. private static Protocol mDefaultHttpsProtocol = null;
  57. private static AdvancedSslSocketFactory mAdvancedSslSocketFactory = null;
  58. private static X509HostnameVerifier mHostnameVerifier = null;
  59. /**
  60. * Creates a WebdavClient setup for an ownCloud account
  61. *
  62. * Do not call this method from the main thread.
  63. *
  64. * @param account The ownCloud account
  65. * @param appContext Android application context
  66. * @return A WebdavClient object ready to be used
  67. * @throws AuthenticatorException If the authenticator failed to get the authorization token for the account.
  68. * @throws OperationCanceledException If the authenticator operation was cancelled while getting the authorization token for the account.
  69. * @throws IOException If there was some I/O error while getting the authorization token for the account.
  70. */
  71. public static WebdavClient createOwnCloudClient (Account account, Context appContext) throws OperationCanceledException, AuthenticatorException, IOException {
  72. //Log_OC.d(TAG, "Creating WebdavClient associated to " + account.name);
  73. Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
  74. WebdavClient client = createOwnCloudClient(uri, appContext);
  75. AccountManager am = AccountManager.get(appContext);
  76. if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null) { // TODO avoid a call to getUserData here
  77. String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, false);
  78. client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token
  79. } else {
  80. String username = account.name.substring(0, account.name.lastIndexOf('@'));
  81. //String password = am.getPassword(account);
  82. String password = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, false);
  83. client.setBasicCredentials(username, password);
  84. }
  85. return client;
  86. }
  87. public static WebdavClient createOwnCloudClient (Account account, Context appContext, Activity currentActivity) throws OperationCanceledException, AuthenticatorException, IOException {
  88. Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
  89. WebdavClient client = createOwnCloudClient(uri, appContext);
  90. AccountManager am = AccountManager.get(appContext);
  91. if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null) { // TODO avoid a call to getUserData here
  92. AccountManagerFuture<Bundle> future = am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, null, currentActivity, null, null);
  93. Bundle result = future.getResult();
  94. String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
  95. //String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, false);
  96. if (accessToken == null) throw new AuthenticatorException("WTF!");
  97. client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token
  98. } else {
  99. String username = account.name.substring(0, account.name.lastIndexOf('@'));
  100. //String password = am.getPassword(account);
  101. //String password = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, false);
  102. AccountManagerFuture<Bundle> future = am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, null, currentActivity, null, null);
  103. Bundle result = future.getResult();
  104. String password = result.getString(AccountManager.KEY_AUTHTOKEN);
  105. client.setBasicCredentials(username, password);
  106. }
  107. return client;
  108. }
  109. /**
  110. * Creates a WebdavClient to access a URL and sets the desired parameters for ownCloud client connections.
  111. *
  112. * @param uri URL to the ownCloud server
  113. * @param context Android context where the WebdavClient is being created.
  114. * @return A WebdavClient object ready to be used
  115. */
  116. public static WebdavClient createOwnCloudClient(Uri uri, Context context) {
  117. //Log_OC.d(TAG, "Creating WebdavClient for " + uri);
  118. //allowSelfsignedCertificates(true);
  119. try {
  120. registerAdvancedSslContext(true, context);
  121. } catch (GeneralSecurityException e) {
  122. Log_OC.e(TAG, "Advanced SSL Context could not be loaded. Default SSL management in the system will be used for HTTPS connections", e);
  123. } catch (IOException e) {
  124. 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);
  125. }
  126. WebdavClient client = new WebdavClient(getMultiThreadedConnManager());
  127. client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
  128. client.setBaseUri(uri);
  129. return client;
  130. }
  131. /**
  132. * Registers or unregisters the proper components for advanced SSL handling.
  133. * @throws IOException
  134. */
  135. private static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException {
  136. Protocol pr = null;
  137. try {
  138. pr = Protocol.getProtocol("https");
  139. if (pr != null && mDefaultHttpsProtocol == null) {
  140. mDefaultHttpsProtocol = pr;
  141. }
  142. } catch (IllegalStateException e) {
  143. // nothing to do here; really
  144. }
  145. boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory);
  146. if (register && !isRegistered) {
  147. Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443));
  148. } else if (!register && isRegistered) {
  149. if (mDefaultHttpsProtocol != null) {
  150. Protocol.registerProtocol("https", mDefaultHttpsProtocol);
  151. }
  152. }
  153. }
  154. public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException {
  155. if (mAdvancedSslSocketFactory == null) {
  156. KeyStore trustStore = getKnownServersStore(context);
  157. AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore);
  158. TrustManager[] tms = new TrustManager[] { trustMgr };
  159. SSLContext sslContext = SSLContext.getInstance("TLS");
  160. sslContext.init(null, tms, null);
  161. mHostnameVerifier = new BrowserCompatHostnameVerifier();
  162. mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier);
  163. }
  164. return mAdvancedSslSocketFactory;
  165. }
  166. private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks";
  167. private static String LOCAL_TRUSTSTORE_PASSWORD = "password";
  168. private static KeyStore mKnownServersStore = null;
  169. /**
  170. * Returns the local store of reliable server certificates, explicitly accepted by the user.
  171. *
  172. * Returns a KeyStore instance with empty content if the local store was never created.
  173. *
  174. * Loads the store from the storage environment if needed.
  175. *
  176. * @param context Android context where the operation is being performed.
  177. * @return KeyStore instance with explicitly-accepted server certificates.
  178. * @throws KeyStoreException When the KeyStore instance could not be created.
  179. * @throws IOException When an existing local trust store could not be loaded.
  180. * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm.
  181. * @throws CertificateException When an exception occurred while loading the certificates from the local trust store.
  182. */
  183. private static KeyStore getKnownServersStore(Context context) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
  184. if (mKnownServersStore == null) {
  185. //mKnownServersStore = KeyStore.getInstance("BKS");
  186. mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
  187. File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
  188. Log_OC.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath());
  189. if (localTrustStoreFile.exists()) {
  190. InputStream in = new FileInputStream(localTrustStoreFile);
  191. try {
  192. mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
  193. } finally {
  194. in.close();
  195. }
  196. } else {
  197. mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance
  198. }
  199. }
  200. return mKnownServersStore;
  201. }
  202. public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException,
  203. CertificateException, IOException {
  204. KeyStore knownServers = getKnownServersStore(context);
  205. knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert);
  206. FileOutputStream fos = null;
  207. try {
  208. fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE);
  209. knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
  210. } finally {
  211. fos.close();
  212. }
  213. }
  214. static private MultiThreadedHttpConnectionManager getMultiThreadedConnManager() {
  215. if (mConnManager == null) {
  216. mConnManager = new MultiThreadedHttpConnectionManager();
  217. mConnManager.getParams().setDefaultMaxConnectionsPerHost(5);
  218. mConnManager.getParams().setMaxTotalConnections(5);
  219. }
  220. return mConnManager;
  221. }
  222. }