a76cd4a2007d8e32d41606840dbb1529a243666f
[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
38 import com.owncloud.android.AccountUtils;
39 import com.owncloud.android.authenticator.AccountAuthenticator;
40 import com.owncloud.android.utils.OwnCloudVersion;
41
42 import eu.alefzero.webdav.WebdavClient;
43
44 import android.accounts.Account;
45 import android.accounts.AccountManager;
46 import android.content.Context;
47 import android.net.Uri;
48 import android.util.Log;
49
50 public class OwnCloudClientUtils {
51
52 final private static String TAG = "OwnCloudClientFactory";
53
54 /** Default timeout for waiting data from the server */
55 public static final int DEFAULT_DATA_TIMEOUT = 60000;
56
57 /** Default timeout for establishing a connection */
58 public static final int DEFAULT_CONNECTION_TIMEOUT = 60000;
59
60 /** Connection manager for all the WebdavClients */
61 private static MultiThreadedHttpConnectionManager mConnManager = null;
62
63 private static Protocol mDefaultHttpsProtocol = null;
64
65 private static AdvancedSslSocketFactory mAdvancedSslSocketFactory = null;
66
67
68 /**
69 * Creates a WebdavClient setup for an ownCloud account
70 *
71 * @param account The ownCloud account
72 * @param context The application context
73 * @return A WebdavClient object ready to be used
74 */
75 public static WebdavClient createOwnCloudClient (Account account, Context context) {
76 Log.d(TAG, "Creating WebdavClient associated to " + account.name);
77
78 String baseUrl = AccountManager.get(context).getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL);
79 OwnCloudVersion ownCloudVersion = new OwnCloudVersion(AccountManager.get(context).getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
80 String webDavPath = AccountUtils.getWebdavPath(ownCloudVersion);
81
82 WebdavClient client = createOwnCloudClient(Uri.parse(baseUrl + webDavPath), context);
83
84 String username = account.name.substring(0, account.name.lastIndexOf('@'));
85 String password = AccountManager.get(context).getPassword(account);
86 //String password = am.blockingGetAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE, true);
87
88 client.setCredentials(username, password);
89
90 return client;
91 }
92
93
94 /**
95 * Creates a WebdavClient to try a new account before saving it
96 *
97 * @param uri URL to the ownCloud server
98 * @param username User name
99 * @param password User password
100 * @param context Android context where the WebdavClient is being created.
101 * @return A WebdavClient object ready to be used
102 */
103 public static WebdavClient createOwnCloudClient(Uri uri, String username, String password, Context context) {
104 Log.d(TAG, "Creating WebdavClient for " + username + "@" + uri);
105
106 WebdavClient client = createOwnCloudClient(uri, context);
107
108 client.setCredentials(username, password);
109
110 return client;
111 }
112
113
114 /**
115 * Creates a WebdavClient to access a URL and sets the desired parameters for ownCloud client connections.
116 *
117 * @param uri URL to the ownCloud server
118 * @param context Android context where the WebdavClient is being created.
119 * @return A WebdavClient object ready to be used
120 */
121 public static WebdavClient createOwnCloudClient(Uri uri, Context context) {
122 Log.d(TAG, "Creating WebdavClient for " + uri);
123
124 //allowSelfsignedCertificates(true);
125 try {
126 registerAdvancedSslContext(true, context);
127 } catch (GeneralSecurityException e) {
128 Log.e(TAG, "Advanced SSL Context could not be loaded. Default SSL management in the system will be used for HTTPS connections", e);
129
130 } catch (IOException e) {
131 Log.e(TAG, "The local server truststore could not be read. Default SSL management in the system will be used for HTTPS connections", e);
132 }
133
134 WebdavClient client = new WebdavClient(getMultiThreadedConnManager());
135
136 client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
137 client.setBaseUri(uri);
138
139 return client;
140 }
141
142
143 /**
144 * Allows or disallows self-signed certificates in ownCloud servers to reach
145 *
146 * @param allow 'True' to allow, 'false' to disallow
147 */
148 public static void allowSelfsignedCertificates(boolean allow) {
149 Protocol pr = null;
150 try {
151 pr = Protocol.getProtocol("https");
152 if (pr != null && mDefaultHttpsProtocol == null) {
153 mDefaultHttpsProtocol = pr;
154 }
155 } catch (IllegalStateException e) {
156 // nothing to do here; really
157 }
158 boolean isAllowed = (pr != null && pr.getSocketFactory() instanceof EasySSLSocketFactory);
159 if (allow && !isAllowed) {
160 Protocol.registerProtocol("https", new Protocol("https", new EasySSLSocketFactory(), 443));
161 } else if (!allow && isAllowed) {
162 if (mDefaultHttpsProtocol != null) {
163 Protocol.registerProtocol("https", mDefaultHttpsProtocol);
164 }
165 }
166 }
167
168
169 /**
170 * Registers or unregisters the proper components for advanced SSL handling.
171 * @throws IOException
172 */
173 private static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException {
174 Protocol pr = null;
175 try {
176 pr = Protocol.getProtocol("https");
177 if (pr != null && mDefaultHttpsProtocol == null) {
178 mDefaultHttpsProtocol = pr;
179 }
180 } catch (IllegalStateException e) {
181 // nothing to do here; really
182 }
183 boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory);
184 if (register && !isRegistered) {
185 Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443));
186
187 } else if (!register && isRegistered) {
188 if (mDefaultHttpsProtocol != null) {
189 Protocol.registerProtocol("https", mDefaultHttpsProtocol);
190 }
191 }
192 }
193
194 private static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException {
195 if (mAdvancedSslSocketFactory == null) {
196 KeyStore trustStore = getKnownServersStore(context);
197 AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore);
198 TrustManager[] tms = new TrustManager[] { trustMgr };
199
200 SSLContext sslContext = SSLContext.getInstance("TLS");
201 sslContext.init(null, tms, null);
202
203 /*} catch (KeyStoreException e) {
204 e.printStackTrace();
205
206 } catch (NoSuchAlgorithmException e) {
207 e.printStackTrace();
208
209 } catch (KeyManagementException e) {
210 e.printStackTrace();
211
212 }*/
213 mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, null); // TODO HOST NAME VERIFIER
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.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 }