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