5d852d870227dced735604bfba679ec22eaf8bc2
[pub/Android/ownCloud.git] / src / com / owncloud / android / network / OwnCloudClientUtils.java
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
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
31 import javax.net.ssl.SSLContext;
32 import javax.net.ssl.TrustManager;
33
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;
38
39 import com.owncloud.android.AccountUtils;
40 import com.owncloud.android.authentication.AccountAuthenticator;
41 import com.owncloud.android.Log_OC;
42
43 import eu.alefzero.webdav.WebdavClient;
44
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;
54
55 public class OwnCloudClientUtils {
56
57 final private static String TAG = OwnCloudClientUtils.class.getSimpleName();
58
59 /** Default timeout for waiting data from the server */
60 public static final int DEFAULT_DATA_TIMEOUT = 60000;
61
62 /** Default timeout for establishing a connection */
63 public static final int DEFAULT_CONNECTION_TIMEOUT = 60000;
64
65 /** Connection manager for all the WebdavClients */
66 private static MultiThreadedHttpConnectionManager mConnManager = null;
67
68 private static Protocol mDefaultHttpsProtocol = null;
69
70 private static AdvancedSslSocketFactory mAdvancedSslSocketFactory = null;
71
72 private static X509HostnameVerifier mHostnameVerifier = null;
73
74
75 /**
76 * Creates a WebdavClient setup for an ownCloud account
77 *
78 * Do not call this method from the main thread.
79 *
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.
86 */
87 public static WebdavClient createOwnCloudClient (Account account, Context appContext) throws OperationCanceledException, AuthenticatorException, IOException {
88 //Log_OC.d(TAG, "Creating WebdavClient associated to " + account.name);
89
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
96
97 } else {
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);
102 }
103
104 return client;
105 }
106
107
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
119
120 } else {
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);
128 }
129
130 return client;
131 }
132
133 /**
134 * Creates a WebdavClient to access a URL and sets the desired parameters for ownCloud client connections.
135 *
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
139 */
140 public static WebdavClient createOwnCloudClient(Uri uri, Context context) {
141 //Log_OC.d(TAG, "Creating WebdavClient for " + uri);
142
143 //allowSelfsignedCertificates(true);
144 try {
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);
148
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);
151 }
152
153 WebdavClient client = new WebdavClient(getMultiThreadedConnManager());
154
155 client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
156 client.setBaseUri(uri);
157
158 return client;
159 }
160
161
162 /**
163 * Registers or unregisters the proper components for advanced SSL handling.
164 * @throws IOException
165 */
166 private static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException {
167 Protocol pr = null;
168 try {
169 pr = Protocol.getProtocol("https");
170 if (pr != null && mDefaultHttpsProtocol == null) {
171 mDefaultHttpsProtocol = pr;
172 }
173 } catch (IllegalStateException e) {
174 // nothing to do here; really
175 }
176 boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory);
177 if (register && !isRegistered) {
178 Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443));
179
180 } else if (!register && isRegistered) {
181 if (mDefaultHttpsProtocol != null) {
182 Protocol.registerProtocol("https", mDefaultHttpsProtocol);
183 }
184 }
185 }
186
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 };
192
193 SSLContext sslContext = SSLContext.getInstance("TLS");
194 sslContext.init(null, tms, null);
195
196 mHostnameVerifier = new BrowserCompatHostnameVerifier();
197 mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier);
198 }
199 return mAdvancedSslSocketFactory;
200 }
201
202
203 private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks";
204
205 private static String LOCAL_TRUSTSTORE_PASSWORD = "password";
206
207 private static KeyStore mKnownServersStore = null;
208
209 /**
210 * Returns the local store of reliable server certificates, explicitly accepted by the user.
211 *
212 * Returns a KeyStore instance with empty content if the local store was never created.
213 *
214 * Loads the store from the storage environment if needed.
215 *
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.
222 */
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);
231 try {
232 mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
233 } finally {
234 in.close();
235 }
236 } else {
237 mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance
238 }
239 }
240 return mKnownServersStore;
241 }
242
243
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;
249 try {
250 fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE);
251 knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
252 } finally {
253 fos.close();
254 }
255 }
256
257
258 static private MultiThreadedHttpConnectionManager getMultiThreadedConnManager() {
259 if (mConnManager == null) {
260 mConnManager = new MultiThreadedHttpConnectionManager();
261 mConnManager.getParams().setDefaultMaxConnectionsPerHost(5);
262 mConnManager.getParams().setMaxTotalConnections(5);
263 }
264 return mConnManager;
265 }
266
267
268 }