Merge branch 'develop' into check_server_certificates_in_SSO_webview
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / SsoWebViewClient.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
18 package com.owncloud.android.authentication;
19
20 import java.io.ByteArrayInputStream;
21 import java.lang.ref.WeakReference;
22 import java.security.cert.Certificate;
23 import java.security.cert.CertificateException;
24 import java.security.cert.CertificateFactory;
25 import java.security.cert.X509Certificate;
26
27 import com.owncloud.android.lib.common.network.NetworkUtils;
28 import com.actionbarsherlock.app.SherlockFragmentActivity;
29 import com.owncloud.android.ui.dialog.SslUntrustedCertDialogABSTRACT;
30 import com.owncloud.android.utils.Log_OC;
31
32 import android.content.Context;
33 import android.graphics.Bitmap;
34 import android.net.http.SslCertificate;
35 import android.net.http.SslError;
36 import android.os.Bundle;
37 import android.os.Handler;
38 import android.os.Message;
39 import android.support.v4.app.FragmentManager;
40 import android.support.v4.app.FragmentTransaction;
41 import android.view.KeyEvent;
42 import android.view.View;
43 import android.webkit.CookieManager;
44 import android.webkit.HttpAuthHandler;
45 import android.webkit.SslErrorHandler;
46 import android.webkit.WebResourceResponse;
47 import android.webkit.WebView;
48 import android.webkit.WebViewClient;
49
50
51 /**
52 * Custom {@link WebViewClient} client aimed to catch the end of a single-sign-on process
53 * running in the {@link WebView} that is attached to.
54 *
55 * Assumes that the single-sign-on is kept thanks to a cookie set at the end of the
56 * authentication process.
57 *
58 * @author David A. Velasco
59 */
60 public class SsoWebViewClient extends WebViewClient {
61
62 private static final String TAG = SsoWebViewClient.class.getSimpleName();
63
64 public interface SsoWebViewClientListener {
65 public void onSsoFinished(String sessionCookie);
66 }
67
68 private Context mContext;
69 private Handler mListenerHandler;
70 private WeakReference<SsoWebViewClientListener> mListenerRef;
71 private String mTargetUrl;
72 private String mLastReloadedUrlAtError;
73
74 public SsoWebViewClient (Context context, Handler listenerHandler, SsoWebViewClientListener listener) {
75 mContext = context;
76 mListenerHandler = listenerHandler;
77 mListenerRef = new WeakReference<SsoWebViewClient.SsoWebViewClientListener>(listener);
78 mTargetUrl = "fake://url.to.be.set";
79 mLastReloadedUrlAtError = null;
80 }
81
82 public String getTargetUrl() {
83 return mTargetUrl;
84 }
85
86 public void setTargetUrl(String targetUrl) {
87 mTargetUrl = targetUrl;
88 }
89
90 @Override
91 public void onPageStarted (WebView view, String url, Bitmap favicon) {
92 Log_OC.d(TAG, "onPageStarted : " + url);
93 super.onPageStarted(view, url, favicon);
94 }
95
96 @Override
97 public void onFormResubmission (WebView view, Message dontResend, Message resend) {
98 Log_OC.d(TAG, "onFormResubMission ");
99
100 // necessary to grant reload of last page when device orientation is changed after sending a form
101 resend.sendToTarget();
102 }
103
104 @Override
105 public boolean shouldOverrideUrlLoading(WebView view, String url) {
106 return false;
107 }
108
109 @Override
110 public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) {
111 Log_OC.e(TAG, "onReceivedError : " + failingUrl + ", code " + errorCode + ", description: " + description);
112 if (!failingUrl.equals(mLastReloadedUrlAtError)) {
113 view.reload();
114 mLastReloadedUrlAtError = failingUrl;
115 } else {
116 mLastReloadedUrlAtError = null;
117 super.onReceivedError(view, errorCode, description, failingUrl);
118 }
119 }
120
121 @Override
122 public void onPageFinished (WebView view, String url) {
123 Log_OC.d(TAG, "onPageFinished : " + url);
124 mLastReloadedUrlAtError = null;
125 if (url.startsWith(mTargetUrl)) {
126 view.setVisibility(View.GONE);
127 CookieManager cookieManager = CookieManager.getInstance();
128 final String cookies = cookieManager.getCookie(url);
129 Log_OC.d(TAG, "Cookies: " + cookies);
130 if (mListenerHandler != null && mListenerRef != null) {
131 // this is good idea because onPageFinished is not running in the UI thread
132 mListenerHandler.post(new Runnable() {
133 @Override
134 public void run() {
135 SsoWebViewClientListener listener = mListenerRef.get();
136 if (listener != null) {
137 // Send Cookies to the listener
138 listener.onSsoFinished(cookies);
139 }
140 }
141 });
142 }
143 }
144 }
145
146
147 @Override
148 public void doUpdateVisitedHistory (WebView view, String url, boolean isReload) {
149 Log_OC.d(TAG, "doUpdateVisitedHistory : " + url);
150 }
151
152 @Override
153 public void onReceivedSslError (final WebView view, final SslErrorHandler handler, SslError error) {
154 Log_OC.d(TAG, "onReceivedSslError : " + error);
155 // Test 1
156 X509Certificate x509Certificate = getX509CertificateFromError(error);
157 boolean isKnownServer = false;
158
159 if (x509Certificate != null) {
160 Log_OC.d(TAG, "------>>>>> x509Certificate " + x509Certificate.toString());
161
162 try {
163 isKnownServer = NetworkUtils.isCertInKnownServersStore((Certificate) x509Certificate, mContext);
164 } catch (Exception e) {
165 Log_OC.e(TAG, "Exception: " + e.getMessage());
166 }
167 }
168
169 if (isKnownServer) {
170 handler.proceed();
171 } else if (x509Certificate != null) {
172 // Show a dialog with the certificate info
173 ((AuthenticatorActivity)mContext).showUntrustedCertDialog(x509Certificate, error);
174 handler.cancel();
175 } else {
176 // Show a dialog with the certificate information available in SslError (not full)
177 SslUntrustedCertDialogABSTRACT dialog = SslUntrustedCertDialogABSTRACT.newInstanceForEmptySslError(error, handler);
178 FragmentManager fm = ((SherlockFragmentActivity)mContext).getSupportFragmentManager();
179 FragmentTransaction ft = fm.beginTransaction();
180 dialog.show(ft, AuthenticatorActivity.DIALOG_UNTRUSTED_CERT);
181 // let's forward the handler, and see what happens...
182 }
183 }
184
185 /**
186 * Obtain the X509Certificate from SslError
187 * @param error SslError
188 * @return X509Certificate from error
189 */
190 public X509Certificate getX509CertificateFromError (SslError error) {
191 Bundle bundle = SslCertificate.saveState(error.getCertificate());
192 X509Certificate x509Certificate;
193 byte[] bytes = bundle.getByteArray("x509-certificate");
194 if (bytes == null) {
195 x509Certificate = null;
196 } else {
197 try {
198 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
199 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
200 x509Certificate = (X509Certificate) cert;
201 } catch (CertificateException e) {
202 x509Certificate = null;
203 }
204 }
205 return x509Certificate;
206 }
207
208 @Override
209 public void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm) {
210 Log_OC.d(TAG, "onReceivedHttpAuthRequest : " + host);
211 }
212
213 @Override
214 public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
215 Log_OC.d(TAG, "shouldInterceptRequest : " + url);
216 return null;
217 }
218
219 @Override
220 public void onLoadResource (WebView view, String url) {
221 Log_OC.d(TAG, "onLoadResource : " + url);
222 }
223
224 @Override
225 public void onReceivedLoginRequest (WebView view, String realm, String account, String args) {
226 Log_OC.d(TAG, "onReceivedLoginRequest : " + realm + ", " + account + ", " + args);
227 }
228
229 @Override
230 public void onScaleChanged (WebView view, float oldScale, float newScale) {
231 Log_OC.d(TAG, "onScaleChanged : " + oldScale + " -> " + newScale);
232 super.onScaleChanged(view, oldScale, newScale);
233 }
234
235 @Override
236 public void onUnhandledKeyEvent (WebView view, KeyEvent event) {
237 Log_OC.d(TAG, "onUnhandledKeyEvent : " + event);
238 }
239
240 @Override
241 public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
242 Log_OC.d(TAG, "shouldOverrideKeyEvent : " + event);
243 return false;
244 }
245
246 }