ac2e015efb16b2bf903d50dd71ddbc7ed0bf4225
[pub/Android/ownCloud.git] / oc_framework / src / com / owncloud / android / oc_framework / network / NetworkUtils.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 version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17 package com.owncloud.android.oc_framework.network;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.FileOutputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.security.GeneralSecurityException;
25 import java.security.KeyStore;
26 import java.security.KeyStoreException;
27 import java.security.NoSuchAlgorithmException;
28 import java.security.cert.Certificate;
29 import java.security.cert.CertificateException;
30
31 import javax.net.ssl.SSLContext;
32 import javax.net.ssl.TrustManager;
33
34 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
35 import org.apache.commons.httpclient.protocol.Protocol;
36 import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
37 import org.apache.http.conn.ssl.X509HostnameVerifier;
38
39 import android.content.Context;
40 import android.util.Log;
41
42 public class NetworkUtils {
43
44 final private static String TAG = NetworkUtils.class.getSimpleName();
45
46 /** Default timeout for waiting data from the server */
47 public static final int DEFAULT_DATA_TIMEOUT = 60000;
48
49 /** Default timeout for establishing a connection */
50 public static final int DEFAULT_CONNECTION_TIMEOUT = 60000;
51
52 /** Connection manager for all the WebdavClients */
53 private static MultiThreadedHttpConnectionManager mConnManager = null;
54
55 private static Protocol mDefaultHttpsProtocol = null;
56
57 private static AdvancedSslSocketFactory mAdvancedSslSocketFactory = null;
58
59 private static X509HostnameVerifier mHostnameVerifier = null;
60
61
62 /**
63 * Registers or unregisters the proper components for advanced SSL handling.
64 * @throws IOException
65 */
66 public static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException {
67 Protocol pr = null;
68 try {
69 pr = Protocol.getProtocol("https");
70 if (pr != null && mDefaultHttpsProtocol == null) {
71 mDefaultHttpsProtocol = pr;
72 }
73 } catch (IllegalStateException e) {
74 // nothing to do here; really
75 }
76 boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory);
77 if (register && !isRegistered) {
78 Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443));
79
80 } else if (!register && isRegistered) {
81 if (mDefaultHttpsProtocol != null) {
82 Protocol.registerProtocol("https", mDefaultHttpsProtocol);
83 }
84 }
85 }
86
87 public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException {
88 if (mAdvancedSslSocketFactory == null) {
89 KeyStore trustStore = getKnownServersStore(context);
90 AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore);
91 TrustManager[] tms = new TrustManager[] { trustMgr };
92
93 SSLContext sslContext = SSLContext.getInstance("TLS");
94 sslContext.init(null, tms, null);
95
96 mHostnameVerifier = new BrowserCompatHostnameVerifier();
97 mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier);
98 }
99 return mAdvancedSslSocketFactory;
100 }
101
102
103 private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks";
104
105 private static String LOCAL_TRUSTSTORE_PASSWORD = "password";
106
107 private static KeyStore mKnownServersStore = null;
108
109 /**
110 * Returns the local store of reliable server certificates, explicitly accepted by the user.
111 *
112 * Returns a KeyStore instance with empty content if the local store was never created.
113 *
114 * Loads the store from the storage environment if needed.
115 *
116 * @param context Android context where the operation is being performed.
117 * @return KeyStore instance with explicitly-accepted server certificates.
118 * @throws KeyStoreException When the KeyStore instance could not be created.
119 * @throws IOException When an existing local trust store could not be loaded.
120 * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm.
121 * @throws CertificateException When an exception occurred while loading the certificates from the local trust store.
122 */
123 private static KeyStore getKnownServersStore(Context context) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
124 if (mKnownServersStore == null) {
125 //mKnownServersStore = KeyStore.getInstance("BKS");
126 mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
127 File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
128 Log.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath());
129 if (localTrustStoreFile.exists()) {
130 InputStream in = new FileInputStream(localTrustStoreFile);
131 try {
132 mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
133 } finally {
134 in.close();
135 }
136 } else {
137 mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance
138 }
139 }
140 return mKnownServersStore;
141 }
142
143
144 public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException,
145 CertificateException, IOException {
146 KeyStore knownServers = getKnownServersStore(context);
147 knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert);
148 FileOutputStream fos = null;
149 try {
150 fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE);
151 knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
152 } finally {
153 fos.close();
154 }
155 }
156
157
158 static public MultiThreadedHttpConnectionManager getMultiThreadedConnManager() {
159 if (mConnManager == null) {
160 mConnManager = new MultiThreadedHttpConnectionManager();
161 mConnManager.getParams().setDefaultMaxConnectionsPerHost(5);
162 mConnManager.getParams().setMaxTotalConnections(5);
163 }
164 return mConnManager;
165 }
166
167
168 }