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