Merge branch 'master' into oauth_login
[pub/Android/ownCloud.git] / src / com / owncloud / android / network / OwnCloudClientUtils.java
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
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.security.GeneralSecurityException;
26 import java.security.KeyStore;
27 import java.security.KeyStoreException;
28 import java.security.NoSuchAlgorithmException;
29 import java.security.cert.Certificate;
30 import java.security.cert.CertificateException;
31
32 import javax.net.ssl.SSLContext;
33 import javax.net.ssl.TrustManager;
34
35 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
36 import org.apache.commons.httpclient.protocol.Protocol;
37 import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
38 import org.apache.http.conn.ssl.X509HostnameVerifier;
39
40 import com.owncloud.android.AccountUtils;
41 import com.owncloud.android.authenticator.AccountAuthenticator;
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 import android.util.Log;
55
56 public class OwnCloudClientUtils {
57
58 final private static String TAG = OwnCloudClientUtils.class.getSimpleName();
59
60 /** Default timeout for waiting data from the server */
61 public static final int DEFAULT_DATA_TIMEOUT = 60000;
62
63 /** Default timeout for establishing a connection */
64 public static final int DEFAULT_CONNECTION_TIMEOUT = 60000;
65
66 /** Connection manager for all the WebdavClients */
67 private static MultiThreadedHttpConnectionManager mConnManager = null;
68
69 private static Protocol mDefaultHttpsProtocol = null;
70
71 private static AdvancedSslSocketFactory mAdvancedSslSocketFactory = null;
72
73 private static X509HostnameVerifier mHostnameVerifier = null;
74
75
76 /**
77 * Creates a WebdavClient setup for an ownCloud account
78 *
79 * Do not call this method from the main thread.
80 *
81 * @param account The ownCloud account
82 * @param appContext Android application context
83 * @return A WebdavClient object ready to be used
84 * @throws AuthenticatorException If the authenticator failed to get the authorization token for the account.
85 * @throws OperationCanceledException If the authenticator operation was cancelled while getting the authorization token for the account.
86 * @throws IOException If there was some I/O error while getting the authorization token for the account.
87 */
88 public static WebdavClient createOwnCloudClient (Account account, Context appContext) throws OperationCanceledException, AuthenticatorException, IOException {
89 //Log.d(TAG, "Creating WebdavClient associated to " + account.name);
90
91 Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
92 WebdavClient client = createOwnCloudClient(uri, appContext);
93 AccountManager am = AccountManager.get(appContext);
94 if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null) { // TODO avoid a call to getUserData here
95 String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, false);
96 client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token
97
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 client.setBasicCredentials(username, password);
103 }
104
105 return client;
106 }
107
108
109 public static WebdavClient createOwnCloudClient (Account account, Context appContext, Activity currentActivity) throws OperationCanceledException, AuthenticatorException, IOException {
110 Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
111 WebdavClient client = createOwnCloudClient(uri, appContext);
112 AccountManager am = AccountManager.get(appContext);
113 if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null) { // TODO avoid a call to getUserData here
114 AccountManagerFuture<Bundle> future = am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, null, currentActivity, null, null);
115 Bundle result = future.getResult();
116 String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
117 //String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, false);
118 if (accessToken == null) throw new AuthenticatorException("WTF!");
119 client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token
120
121 } else {
122 String username = account.name.substring(0, account.name.lastIndexOf('@'));
123 //String password = am.getPassword(account);
124 //String password = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, false);
125 AccountManagerFuture<Bundle> future = am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, null, currentActivity, null, null);
126 Bundle result = future.getResult();
127 String password = result.getString(AccountManager.KEY_AUTHTOKEN);
128 client.setBasicCredentials(username, password);
129 }
130
131 return client;
132 }
133
134 /**
135 * Creates a WebdavClient to try a new account before saving it
136 *
137 * @param uri URL to the ownCloud server
138 * @param username User name
139 * @param password User password
140 * @param context Android context where the WebdavClient is being created.
141 * @return A WebdavClient object ready to be used
142 */
143 public static WebdavClient createOwnCloudClient(Uri uri, String username, String password, Context context) {
144 //Log.d(TAG, "Creating WebdavClient for " + username + "@" + uri);
145
146 WebdavClient client = createOwnCloudClient(uri, context);
147
148 client.setBasicCredentials(username, password);
149
150 return client;
151 }
152
153
154 /**
155 * Creates a WebdavClient to access a URL and sets the desired parameters for ownCloud client connections.
156 *
157 * @param uri URL to the ownCloud server
158 * @param context Android context where the WebdavClient is being created.
159 * @return A WebdavClient object ready to be used
160 */
161 public static WebdavClient createOwnCloudClient(Uri uri, Context context) {
162 //Log.d(TAG, "Creating WebdavClient for " + uri);
163
164 //allowSelfsignedCertificates(true);
165 try {
166 registerAdvancedSslContext(true, context);
167 } catch (GeneralSecurityException e) {
168 Log.e(TAG, "Advanced SSL Context could not be loaded. Default SSL management in the system will be used for HTTPS connections", e);
169
170 } catch (IOException e) {
171 Log.e(TAG, "The local server truststore could not be read. Default SSL management in the system will be used for HTTPS connections", e);
172 }
173
174 WebdavClient client = new WebdavClient(getMultiThreadedConnManager());
175
176 client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
177 client.setBaseUri(uri);
178
179 return client;
180 }
181
182
183 /**
184 * Allows or disallows self-signed certificates in ownCloud servers to reach
185 *
186 * @param allow 'True' to allow, 'false' to disallow
187 */
188 public static void allowSelfsignedCertificates(boolean allow) {
189 Protocol pr = null;
190 try {
191 pr = Protocol.getProtocol("https");
192 if (pr != null && mDefaultHttpsProtocol == null) {
193 mDefaultHttpsProtocol = pr;
194 }
195 } catch (IllegalStateException e) {
196 // nothing to do here; really
197 }
198 boolean isAllowed = (pr != null && pr.getSocketFactory() instanceof EasySSLSocketFactory);
199 if (allow && !isAllowed) {
200 Protocol.registerProtocol("https", new Protocol("https", new EasySSLSocketFactory(), 443));
201 } else if (!allow && isAllowed) {
202 if (mDefaultHttpsProtocol != null) {
203 Protocol.registerProtocol("https", mDefaultHttpsProtocol);
204 }
205 }
206 }
207
208
209 /**
210 * Registers or unregisters the proper components for advanced SSL handling.
211 * @throws IOException
212 */
213 private static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException {
214 Protocol pr = null;
215 try {
216 pr = Protocol.getProtocol("https");
217 if (pr != null && mDefaultHttpsProtocol == null) {
218 mDefaultHttpsProtocol = pr;
219 }
220 } catch (IllegalStateException e) {
221 // nothing to do here; really
222 }
223 boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory);
224 if (register && !isRegistered) {
225 Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443));
226
227 } else if (!register && isRegistered) {
228 if (mDefaultHttpsProtocol != null) {
229 Protocol.registerProtocol("https", mDefaultHttpsProtocol);
230 }
231 }
232 }
233
234 public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException {
235 if (mAdvancedSslSocketFactory == null) {
236 KeyStore trustStore = getKnownServersStore(context);
237 AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore);
238 TrustManager[] tms = new TrustManager[] { trustMgr };
239
240 SSLContext sslContext = SSLContext.getInstance("TLS");
241 sslContext.init(null, tms, null);
242
243 mHostnameVerifier = new BrowserCompatHostnameVerifier();
244 mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier);
245 }
246 return mAdvancedSslSocketFactory;
247 }
248
249
250 private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks";
251
252 private static String LOCAL_TRUSTSTORE_PASSWORD = "password";
253
254 private static KeyStore mKnownServersStore = null;
255
256 /**
257 * Returns the local store of reliable server certificates, explicitly accepted by the user.
258 *
259 * Returns a KeyStore instance with empty content if the local store was never created.
260 *
261 * Loads the store from the storage environment if needed.
262 *
263 * @param context Android context where the operation is being performed.
264 * @return KeyStore instance with explicitly-accepted server certificates.
265 * @throws KeyStoreException When the KeyStore instance could not be created.
266 * @throws IOException When an existing local trust store could not be loaded.
267 * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm.
268 * @throws CertificateException When an exception occurred while loading the certificates from the local trust store.
269 */
270 private static KeyStore getKnownServersStore(Context context) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
271 if (mKnownServersStore == null) {
272 //mKnownServersStore = KeyStore.getInstance("BKS");
273 mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
274 File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
275 Log.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath());
276 if (localTrustStoreFile.exists()) {
277 InputStream in = new FileInputStream(localTrustStoreFile);
278 try {
279 mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
280 } finally {
281 in.close();
282 }
283 } else {
284 mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance
285 }
286 }
287 return mKnownServersStore;
288 }
289
290
291 public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException,
292 CertificateException, IOException {
293 KeyStore knownServers = getKnownServersStore(context);
294 knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert);
295 FileOutputStream fos = null;
296 try {
297 fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE);
298 knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
299 } finally {
300 fos.close();
301 }
302 }
303
304
305 static private MultiThreadedHttpConnectionManager getMultiThreadedConnManager() {
306 if (mConnManager == null) {
307 mConnManager = new MultiThreadedHttpConnectionManager();
308 mConnManager.getParams().setDefaultMaxConnectionsPerHost(5);
309 mConnManager.getParams().setMaxTotalConnections(5);
310 }
311 return mConnManager;
312 }
313
314
315 }