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