c94516ae2ac75a5fb8850b1e076f6dbe31f7e72e
[pub/Android/ownCloud.git] / oc_framework / src / com / owncloud / android / oc_framework / network / NetworkUtils.java
1 /* ownCloud Android Library is available under MIT license
2 * Copyright (C) 2014 ownCloud (http://www.owncloud.org/)
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
18 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
19 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 * THE SOFTWARE.
22 *
23 */
24
25 package com.owncloud.android.oc_framework.network;
26
27 import java.io.File;
28 import java.io.FileInputStream;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.security.GeneralSecurityException;
33 import java.security.KeyStore;
34 import java.security.KeyStoreException;
35 import java.security.NoSuchAlgorithmException;
36 import java.security.cert.Certificate;
37 import java.security.cert.CertificateException;
38
39 import javax.net.ssl.SSLContext;
40 import javax.net.ssl.TrustManager;
41
42 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
43 import org.apache.commons.httpclient.protocol.Protocol;
44 import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
45 import org.apache.http.conn.ssl.X509HostnameVerifier;
46
47 import android.content.Context;
48 import android.util.Log;
49
50 public class NetworkUtils {
51
52 final private static String TAG = NetworkUtils.class.getSimpleName();
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 * Registers or unregisters the proper components for advanced SSL handling.
72 * @throws IOException
73 */
74 public static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException {
75 Protocol pr = null;
76 try {
77 pr = Protocol.getProtocol("https");
78 if (pr != null && mDefaultHttpsProtocol == null) {
79 mDefaultHttpsProtocol = pr;
80 }
81 } catch (IllegalStateException e) {
82 // nothing to do here; really
83 }
84 boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory);
85 if (register && !isRegistered) {
86 Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443));
87
88 } else if (!register && isRegistered) {
89 if (mDefaultHttpsProtocol != null) {
90 Protocol.registerProtocol("https", mDefaultHttpsProtocol);
91 }
92 }
93 }
94
95 public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException {
96 if (mAdvancedSslSocketFactory == null) {
97 KeyStore trustStore = getKnownServersStore(context);
98 AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore);
99 TrustManager[] tms = new TrustManager[] { trustMgr };
100
101 SSLContext sslContext = SSLContext.getInstance("TLS");
102 sslContext.init(null, tms, null);
103
104 mHostnameVerifier = new BrowserCompatHostnameVerifier();
105 mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier);
106 }
107 return mAdvancedSslSocketFactory;
108 }
109
110
111 private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks";
112
113 private static String LOCAL_TRUSTSTORE_PASSWORD = "password";
114
115 private static KeyStore mKnownServersStore = null;
116
117 /**
118 * Returns the local store of reliable server certificates, explicitly accepted by the user.
119 *
120 * Returns a KeyStore instance with empty content if the local store was never created.
121 *
122 * Loads the store from the storage environment if needed.
123 *
124 * @param context Android context where the operation is being performed.
125 * @return KeyStore instance with explicitly-accepted server certificates.
126 * @throws KeyStoreException When the KeyStore instance could not be created.
127 * @throws IOException When an existing local trust store could not be loaded.
128 * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm.
129 * @throws CertificateException When an exception occurred while loading the certificates from the local trust store.
130 */
131 private static KeyStore getKnownServersStore(Context context) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
132 if (mKnownServersStore == null) {
133 //mKnownServersStore = KeyStore.getInstance("BKS");
134 mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
135 File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
136 Log.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath());
137 if (localTrustStoreFile.exists()) {
138 InputStream in = new FileInputStream(localTrustStoreFile);
139 try {
140 mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
141 } finally {
142 in.close();
143 }
144 } else {
145 mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance
146 }
147 }
148 return mKnownServersStore;
149 }
150
151
152 public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException,
153 CertificateException, IOException {
154 KeyStore knownServers = getKnownServersStore(context);
155 knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert);
156 FileOutputStream fos = null;
157 try {
158 fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE);
159 knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
160 } finally {
161 fos.close();
162 }
163 }
164
165
166 static public MultiThreadedHttpConnectionManager getMultiThreadedConnManager() {
167 if (mConnManager == null) {
168 mConnManager = new MultiThreadedHttpConnectionManager();
169 mConnManager.getParams().setDefaultMaxConnectionsPerHost(5);
170 mConnManager.getParams().setMaxTotalConnections(5);
171 }
172 return mConnManager;
173 }
174
175
176 }