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