This wraps the android.util.logging into Log_OC which , if its enabled
[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 as published by
6 * the Free Software Foundation, either version 2 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.Log_OC;
42
43 import eu.alefzero.webdav.WebdavClient;
44
45 import android.accounts.Account;
46 import android.accounts.AccountManager;
47 import android.content.Context;
48 import android.net.Uri;
49 import android.util.Log;
50
51 public class OwnCloudClientUtils {
52
53 final private static String TAG = "OwnCloudClientFactory";
54
55 /** Default timeout for waiting data from the server */
56 public static final int DEFAULT_DATA_TIMEOUT = 60000;
57
58 /** Default timeout for establishing a connection */
59 public static final int DEFAULT_CONNECTION_TIMEOUT = 60000;
60
61 /** Connection manager for all the WebdavClients */
62 private static MultiThreadedHttpConnectionManager mConnManager = null;
63
64 private static Protocol mDefaultHttpsProtocol = null;
65
66 private static AdvancedSslSocketFactory mAdvancedSslSocketFactory = null;
67
68 private static X509HostnameVerifier mHostnameVerifier = null;
69
70
71 /**
72 * Creates a WebdavClient setup for an ownCloud account
73 *
74 * @param account The ownCloud account
75 * @param context The application context
76 * @return A WebdavClient object ready to be used
77 */
78 public static WebdavClient createOwnCloudClient (Account account, Context context) {
79 Log_OC.d(TAG, "Creating WebdavClient associated to " + account.name);
80
81 Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(context, account));
82 WebdavClient client = createOwnCloudClient(uri, 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_OC.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_OC.d(TAG, "Creating WebdavClient for " + uri);
123
124 //allowSelfsignedCertificates(true);
125 try {
126 registerAdvancedSslContext(true, context);
127 } catch (GeneralSecurityException e) {
128 Log_OC.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_OC.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 * Registers or unregisters the proper components for advanced SSL handling.
145 * @throws IOException
146 */
147 private static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException {
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 isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory);
158 if (register && !isRegistered) {
159 Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443));
160
161 } else if (!register && isRegistered) {
162 if (mDefaultHttpsProtocol != null) {
163 Protocol.registerProtocol("https", mDefaultHttpsProtocol);
164 }
165 }
166 }
167
168 public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException {
169 if (mAdvancedSslSocketFactory == null) {
170 KeyStore trustStore = getKnownServersStore(context);
171 AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore);
172 TrustManager[] tms = new TrustManager[] { trustMgr };
173
174 SSLContext sslContext = SSLContext.getInstance("TLS");
175 sslContext.init(null, tms, null);
176
177 mHostnameVerifier = new BrowserCompatHostnameVerifier();
178 mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier);
179 }
180 return mAdvancedSslSocketFactory;
181 }
182
183
184 private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks";
185
186 private static String LOCAL_TRUSTSTORE_PASSWORD = "password";
187
188 private static KeyStore mKnownServersStore = null;
189
190 /**
191 * Returns the local store of reliable server certificates, explicitly accepted by the user.
192 *
193 * Returns a KeyStore instance with empty content if the local store was never created.
194 *
195 * Loads the store from the storage environment if needed.
196 *
197 * @param context Android context where the operation is being performed.
198 * @return KeyStore instance with explicitly-accepted server certificates.
199 * @throws KeyStoreException When the KeyStore instance could not be created.
200 * @throws IOException When an existing local trust store could not be loaded.
201 * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm.
202 * @throws CertificateException When an exception occurred while loading the certificates from the local trust store.
203 */
204 private static KeyStore getKnownServersStore(Context context) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
205 if (mKnownServersStore == null) {
206 //mKnownServersStore = KeyStore.getInstance("BKS");
207 mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
208 File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
209 Log_OC.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath());
210 if (localTrustStoreFile.exists()) {
211 InputStream in = new FileInputStream(localTrustStoreFile);
212 try {
213 mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
214 } finally {
215 in.close();
216 }
217 } else {
218 mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance
219 }
220 }
221 return mKnownServersStore;
222 }
223
224
225 public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException,
226 CertificateException, IOException {
227 KeyStore knownServers = getKnownServersStore(context);
228 knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert);
229 FileOutputStream fos = null;
230 try {
231 fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE);
232 knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
233 } finally {
234 fos.close();
235 }
236 }
237
238
239 static private MultiThreadedHttpConnectionManager getMultiThreadedConnManager() {
240 if (mConnManager == null) {
241 mConnManager = new MultiThreadedHttpConnectionManager();
242 mConnManager.getParams().setDefaultMaxConnectionsPerHost(5);
243 mConnManager.getParams().setMaxTotalConnections(5);
244 }
245 return mConnManager;
246 }
247
248 }