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