OwnCloudClientUtils.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /* ownCloud Android client application
  2. * Copyright (C) 2011 Bartek Przybylski
  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 as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  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.
  13. *
  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/>.
  16. *
  17. */
  18. package com.owncloud.android.network;
  19. import java.io.File;
  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;
  30. import javax.net.ssl.SSLContext;
  31. import javax.net.ssl.TrustManager;
  32. import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
  33. import org.apache.commons.httpclient.protocol.Protocol;
  34. import com.owncloud.android.AccountUtils;
  35. import com.owncloud.android.authenticator.AccountAuthenticator;
  36. import com.owncloud.android.utils.OwnCloudVersion;
  37. import eu.alefzero.webdav.WebdavClient;
  38. import android.accounts.Account;
  39. import android.accounts.AccountManager;
  40. import android.content.Context;
  41. import android.net.Uri;
  42. import android.util.Log;
  43. public class OwnCloudClientUtils {
  44. final private static String TAG = "OwnCloudClientFactory";
  45. /** Default timeout for waiting data from the server */
  46. public static final int DEFAULT_DATA_TIMEOUT = 60000;
  47. /** Default timeout for establishing a connection */
  48. public static final int DEFAULT_CONNECTION_TIMEOUT = 60000;
  49. /** Connection manager for all the WebdavClients */
  50. private static MultiThreadedHttpConnectionManager mConnManager = null;
  51. private static Protocol mDefaultHttpsProtocol = null;
  52. private static AdvancedSslSocketFactory mAdvancedSslSocketFactory = null;
  53. /**
  54. * Creates a WebdavClient setup for an ownCloud account
  55. *
  56. * @param account The ownCloud account
  57. * @param context The application context
  58. * @return A WebdavClient object ready to be used
  59. */
  60. public static WebdavClient createOwnCloudClient (Account account, Context context) {
  61. Log.d(TAG, "Creating WebdavClient associated to " + account.name);
  62. String baseUrl = AccountManager.get(context).getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL);
  63. OwnCloudVersion ownCloudVersion = new OwnCloudVersion(AccountManager.get(context).getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
  64. String webDavPath = AccountUtils.getWebdavPath(ownCloudVersion);
  65. WebdavClient client = createOwnCloudClient(Uri.parse(baseUrl + webDavPath), context);
  66. String username = account.name.substring(0, account.name.lastIndexOf('@'));
  67. String password = AccountManager.get(context).getPassword(account);
  68. //String password = am.blockingGetAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE, true);
  69. client.setCredentials(username, password);
  70. return client;
  71. }
  72. /**
  73. * Creates a WebdavClient to try a new account before saving it
  74. *
  75. * @param uri URL to the ownCloud server
  76. * @param username User name
  77. * @param password User password
  78. * @param context Android context where the WebdavClient is being created.
  79. * @return A WebdavClient object ready to be used
  80. */
  81. public static WebdavClient createOwnCloudClient(Uri uri, String username, String password, Context context) {
  82. Log.d(TAG, "Creating WebdavClient for " + username + "@" + uri);
  83. WebdavClient client = createOwnCloudClient(uri, context);
  84. client.setCredentials(username, password);
  85. return client;
  86. }
  87. /**
  88. * Creates a WebdavClient to access a URL and sets the desired parameters for ownCloud client connections.
  89. *
  90. * @param uri URL to the ownCloud server
  91. * @param context Android context where the WebdavClient is being created.
  92. * @return A WebdavClient object ready to be used
  93. */
  94. public static WebdavClient createOwnCloudClient(Uri uri, Context context) {
  95. Log.d(TAG, "Creating WebdavClient for " + uri);
  96. //allowSelfsignedCertificates(true);
  97. try {
  98. registerAdvancedSslContext(true, context);
  99. } catch (GeneralSecurityException e) {
  100. Log.e(TAG, "Advanced SSL Context could not be loaded. Default SSL management in the system will be used for HTTPS connections", e);
  101. } catch (IOException e) {
  102. Log.e(TAG, "The local server truststore could not be read. Default SSL management in the system will be used for HTTPS connections", e);
  103. }
  104. WebdavClient client = new WebdavClient(getMultiThreadedConnManager());
  105. client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
  106. client.setBaseUri(uri);
  107. return client;
  108. }
  109. /**
  110. * Allows or disallows self-signed certificates in ownCloud servers to reach
  111. *
  112. * @param allow 'True' to allow, 'false' to disallow
  113. */
  114. public static void allowSelfsignedCertificates(boolean allow) {
  115. Protocol pr = null;
  116. try {
  117. pr = Protocol.getProtocol("https");
  118. if (pr != null && mDefaultHttpsProtocol == null) {
  119. mDefaultHttpsProtocol = pr;
  120. }
  121. } catch (IllegalStateException e) {
  122. // nothing to do here; really
  123. }
  124. boolean isAllowed = (pr != null && pr.getSocketFactory() instanceof EasySSLSocketFactory);
  125. if (allow && !isAllowed) {
  126. Protocol.registerProtocol("https", new Protocol("https", new EasySSLSocketFactory(), 443));
  127. } else if (!allow && isAllowed) {
  128. if (mDefaultHttpsProtocol != null) {
  129. Protocol.registerProtocol("https", mDefaultHttpsProtocol);
  130. }
  131. }
  132. }
  133. /**
  134. * Registers or unregisters the proper components for advanced SSL handling.
  135. * @throws IOException
  136. */
  137. private static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException {
  138. Protocol pr = null;
  139. try {
  140. pr = Protocol.getProtocol("https");
  141. if (pr != null && mDefaultHttpsProtocol == null) {
  142. mDefaultHttpsProtocol = pr;
  143. }
  144. } catch (IllegalStateException e) {
  145. // nothing to do here; really
  146. }
  147. boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory);
  148. if (register && !isRegistered) {
  149. Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443));
  150. } else if (!register && isRegistered) {
  151. if (mDefaultHttpsProtocol != null) {
  152. Protocol.registerProtocol("https", mDefaultHttpsProtocol);
  153. }
  154. }
  155. }
  156. private static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException {
  157. if (mAdvancedSslSocketFactory == null) {
  158. KeyStore trustStore = getKnownServersStore(context);
  159. AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore);
  160. TrustManager[] tms = new TrustManager[] { trustMgr };
  161. SSLContext sslContext = SSLContext.getInstance("TLS");
  162. sslContext.init(null, tms, null);
  163. /*} catch (KeyStoreException e) {
  164. e.printStackTrace();
  165. } catch (NoSuchAlgorithmException e) {
  166. e.printStackTrace();
  167. } catch (KeyManagementException e) {
  168. e.printStackTrace();
  169. }*/
  170. mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, null); // TODO HOST NAME VERIFIER
  171. }
  172. return mAdvancedSslSocketFactory;
  173. }
  174. private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks";
  175. private static String LOCAL_TRUSTSTORE_PASSWORD = "password";
  176. private static KeyStore mKnownServersStore = null;
  177. /**
  178. * Returns the local store of reliable server certificates, explicitly accepted by the user.
  179. *
  180. * Returns a KeyStore instance with empty content if the local store was never created.
  181. *
  182. * Loads the store from the storage environment if needed.
  183. *
  184. * @param context Android context where the operation is being performed.
  185. * @return KeyStore instance with explicitly-accepted server certificates.
  186. * @throws KeyStoreException When the KeyStore instance could not be created.
  187. * @throws IOException When an existing local trust store could not be loaded.
  188. * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm.
  189. * @throws CertificateException When an exception occurred while loading the certificates from the local trust store.
  190. */
  191. private static KeyStore getKnownServersStore(Context context) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
  192. if (mKnownServersStore == null) {
  193. //mKnownServersStore = KeyStore.getInstance("BKS");
  194. mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
  195. File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
  196. Log.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath());
  197. if (localTrustStoreFile.exists()) {
  198. InputStream in = new FileInputStream(localTrustStoreFile);
  199. try {
  200. mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
  201. } finally {
  202. in.close();
  203. }
  204. } else {
  205. mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance
  206. }
  207. }
  208. return mKnownServersStore;
  209. }
  210. public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException,
  211. CertificateException, IOException {
  212. KeyStore knownServers = getKnownServersStore(context);
  213. knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert);
  214. FileOutputStream fos = null;
  215. try {
  216. fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE);
  217. knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
  218. } finally {
  219. fos.close();
  220. }
  221. }
  222. static private MultiThreadedHttpConnectionManager getMultiThreadedConnManager() {
  223. if (mConnManager == null) {
  224. mConnManager = new MultiThreadedHttpConnectionManager();
  225. mConnManager.getParams().setDefaultMaxConnectionsPerHost(5);
  226. mConnManager.getParams().setMaxTotalConnections(5);
  227. }
  228. return mConnManager;
  229. }
  230. }