Repositorio del curso CCOM4030 el semestre B91 del proyecto kilometro0

SystemWebViewClient.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. /*
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. package org.apache.cordova.engine;
  18. import android.annotation.TargetApi;
  19. import android.content.pm.ApplicationInfo;
  20. import android.content.pm.PackageManager;
  21. import android.content.pm.PackageManager.NameNotFoundException;
  22. import android.graphics.Bitmap;
  23. import android.net.Uri;
  24. import android.net.http.SslError;
  25. import android.os.Build;
  26. import android.webkit.ClientCertRequest;
  27. import android.webkit.HttpAuthHandler;
  28. import android.webkit.SslErrorHandler;
  29. import android.webkit.WebResourceResponse;
  30. import android.webkit.WebView;
  31. import android.webkit.WebViewClient;
  32. import org.apache.cordova.AuthenticationToken;
  33. import org.apache.cordova.CordovaClientCertRequest;
  34. import org.apache.cordova.CordovaHttpAuthHandler;
  35. import org.apache.cordova.CordovaResourceApi;
  36. import org.apache.cordova.LOG;
  37. import org.apache.cordova.PluginManager;
  38. import java.io.FileNotFoundException;
  39. import java.io.IOException;
  40. import java.util.Hashtable;
  41. /**
  42. * This class is the WebViewClient that implements callbacks for our web view.
  43. * The kind of callbacks that happen here are regarding the rendering of the
  44. * document instead of the chrome surrounding it, such as onPageStarted(),
  45. * shouldOverrideUrlLoading(), etc. Related to but different than
  46. * CordovaChromeClient.
  47. */
  48. public class SystemWebViewClient extends WebViewClient {
  49. private static final String TAG = "SystemWebViewClient";
  50. protected final SystemWebViewEngine parentEngine;
  51. private boolean doClearHistory = false;
  52. boolean isCurrentlyLoading;
  53. /** The authorization tokens. */
  54. private Hashtable<String, AuthenticationToken> authenticationTokens = new Hashtable<String, AuthenticationToken>();
  55. public SystemWebViewClient(SystemWebViewEngine parentEngine) {
  56. this.parentEngine = parentEngine;
  57. }
  58. /**
  59. * Give the host application a chance to take over the control when a new url
  60. * is about to be loaded in the current WebView.
  61. *
  62. * @param view The WebView that is initiating the callback.
  63. * @param url The url to be loaded.
  64. * @return true to override, false for default behavior
  65. */
  66. @Override
  67. @SuppressWarnings("deprecation")
  68. public boolean shouldOverrideUrlLoading(WebView view, String url) {
  69. return parentEngine.client.onNavigationAttempt(url);
  70. }
  71. /**
  72. * On received http auth request.
  73. * The method reacts on all registered authentication tokens. There is one and only one authentication token for any host + realm combination
  74. */
  75. @Override
  76. public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
  77. // Get the authentication token (if specified)
  78. AuthenticationToken token = this.getAuthenticationToken(host, realm);
  79. if (token != null) {
  80. handler.proceed(token.getUserName(), token.getPassword());
  81. return;
  82. }
  83. // Check if there is some plugin which can resolve this auth challenge
  84. PluginManager pluginManager = this.parentEngine.pluginManager;
  85. if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(null, new CordovaHttpAuthHandler(handler), host, realm)) {
  86. parentEngine.client.clearLoadTimeoutTimer();
  87. return;
  88. }
  89. // By default handle 401 like we'd normally do!
  90. super.onReceivedHttpAuthRequest(view, handler, host, realm);
  91. }
  92. /**
  93. * On received client cert request.
  94. * The method forwards the request to any running plugins before using the default implementation.
  95. *
  96. * @param view
  97. * @param request
  98. */
  99. @Override
  100. @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  101. public void onReceivedClientCertRequest (WebView view, ClientCertRequest request)
  102. {
  103. // Check if there is some plugin which can resolve this certificate request
  104. PluginManager pluginManager = this.parentEngine.pluginManager;
  105. if (pluginManager != null && pluginManager.onReceivedClientCertRequest(null, new CordovaClientCertRequest(request))) {
  106. parentEngine.client.clearLoadTimeoutTimer();
  107. return;
  108. }
  109. // By default pass to WebViewClient
  110. super.onReceivedClientCertRequest(view, request);
  111. }
  112. /**
  113. * Notify the host application that a page has started loading.
  114. * This method is called once for each main frame load so a page with iframes or framesets will call onPageStarted
  115. * one time for the main frame. This also means that onPageStarted will not be called when the contents of an
  116. * embedded frame changes, i.e. clicking a link whose target is an iframe.
  117. *
  118. * @param view The webview initiating the callback.
  119. * @param url The url of the page.
  120. */
  121. @Override
  122. public void onPageStarted(WebView view, String url, Bitmap favicon) {
  123. super.onPageStarted(view, url, favicon);
  124. isCurrentlyLoading = true;
  125. // Flush stale messages & reset plugins.
  126. parentEngine.bridge.reset();
  127. parentEngine.client.onPageStarted(url);
  128. }
  129. /**
  130. * Notify the host application that a page has finished loading.
  131. * This method is called only for main frame. When onPageFinished() is called, the rendering picture may not be updated yet.
  132. *
  133. *
  134. * @param view The webview initiating the callback.
  135. * @param url The url of the page.
  136. */
  137. @Override
  138. public void onPageFinished(WebView view, String url) {
  139. super.onPageFinished(view, url);
  140. // Ignore excessive calls, if url is not about:blank (CB-8317).
  141. if (!isCurrentlyLoading && !url.startsWith("about:")) {
  142. return;
  143. }
  144. isCurrentlyLoading = false;
  145. /**
  146. * Because of a timing issue we need to clear this history in onPageFinished as well as
  147. * onPageStarted. However we only want to do this if the doClearHistory boolean is set to
  148. * true. You see when you load a url with a # in it which is common in jQuery applications
  149. * onPageStared is not called. Clearing the history at that point would break jQuery apps.
  150. */
  151. if (this.doClearHistory) {
  152. view.clearHistory();
  153. this.doClearHistory = false;
  154. }
  155. parentEngine.client.onPageFinishedLoading(url);
  156. }
  157. /**
  158. * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
  159. * The errorCode parameter corresponds to one of the ERROR_* constants.
  160. *
  161. * @param view The WebView that is initiating the callback.
  162. * @param errorCode The error code corresponding to an ERROR_* value.
  163. * @param description A String describing the error.
  164. * @param failingUrl The url that failed to load.
  165. */
  166. @Override
  167. @SuppressWarnings("deprecation")
  168. public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
  169. // Ignore error due to stopLoading().
  170. if (!isCurrentlyLoading) {
  171. return;
  172. }
  173. LOG.d(TAG, "CordovaWebViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);
  174. // If this is a "Protocol Not Supported" error, then revert to the previous
  175. // page. If there was no previous page, then punt. The application's config
  176. // is likely incorrect (start page set to sms: or something like that)
  177. if (errorCode == WebViewClient.ERROR_UNSUPPORTED_SCHEME) {
  178. parentEngine.client.clearLoadTimeoutTimer();
  179. if (view.canGoBack()) {
  180. view.goBack();
  181. return;
  182. } else {
  183. super.onReceivedError(view, errorCode, description, failingUrl);
  184. }
  185. }
  186. parentEngine.client.onReceivedError(errorCode, description, failingUrl);
  187. }
  188. /**
  189. * Notify the host application that an SSL error occurred while loading a resource.
  190. * The host application must call either handler.cancel() or handler.proceed().
  191. * Note that the decision may be retained for use in response to future SSL errors.
  192. * The default behavior is to cancel the load.
  193. *
  194. * @param view The WebView that is initiating the callback.
  195. * @param handler An SslErrorHandler object that will handle the user's response.
  196. * @param error The SSL error object.
  197. */
  198. @Override
  199. public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
  200. final String packageName = parentEngine.cordova.getActivity().getPackageName();
  201. final PackageManager pm = parentEngine.cordova.getActivity().getPackageManager();
  202. ApplicationInfo appInfo;
  203. try {
  204. appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
  205. if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
  206. // debug = true
  207. handler.proceed();
  208. return;
  209. } else {
  210. // debug = false
  211. super.onReceivedSslError(view, handler, error);
  212. }
  213. } catch (NameNotFoundException e) {
  214. // When it doubt, lock it out!
  215. super.onReceivedSslError(view, handler, error);
  216. }
  217. }
  218. /**
  219. * Sets the authentication token.
  220. *
  221. * @param authenticationToken
  222. * @param host
  223. * @param realm
  224. */
  225. public void setAuthenticationToken(AuthenticationToken authenticationToken, String host, String realm) {
  226. if (host == null) {
  227. host = "";
  228. }
  229. if (realm == null) {
  230. realm = "";
  231. }
  232. this.authenticationTokens.put(host.concat(realm), authenticationToken);
  233. }
  234. /**
  235. * Removes the authentication token.
  236. *
  237. * @param host
  238. * @param realm
  239. *
  240. * @return the authentication token or null if did not exist
  241. */
  242. public AuthenticationToken removeAuthenticationToken(String host, String realm) {
  243. return this.authenticationTokens.remove(host.concat(realm));
  244. }
  245. /**
  246. * Gets the authentication token.
  247. *
  248. * In order it tries:
  249. * 1- host + realm
  250. * 2- host
  251. * 3- realm
  252. * 4- no host, no realm
  253. *
  254. * @param host
  255. * @param realm
  256. *
  257. * @return the authentication token
  258. */
  259. public AuthenticationToken getAuthenticationToken(String host, String realm) {
  260. AuthenticationToken token = null;
  261. token = this.authenticationTokens.get(host.concat(realm));
  262. if (token == null) {
  263. // try with just the host
  264. token = this.authenticationTokens.get(host);
  265. // Try the realm
  266. if (token == null) {
  267. token = this.authenticationTokens.get(realm);
  268. }
  269. // if no host found, just query for default
  270. if (token == null) {
  271. token = this.authenticationTokens.get("");
  272. }
  273. }
  274. return token;
  275. }
  276. /**
  277. * Clear all authentication tokens.
  278. */
  279. public void clearAuthenticationTokens() {
  280. this.authenticationTokens.clear();
  281. }
  282. @Override
  283. @SuppressWarnings("deprecation")
  284. public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
  285. try {
  286. // Check the against the whitelist and lock out access to the WebView directory
  287. // Changing this will cause problems for your application
  288. if (!parentEngine.pluginManager.shouldAllowRequest(url)) {
  289. LOG.w(TAG, "URL blocked by whitelist: " + url);
  290. // Results in a 404.
  291. return new WebResourceResponse("text/plain", "UTF-8", null);
  292. }
  293. CordovaResourceApi resourceApi = parentEngine.resourceApi;
  294. Uri origUri = Uri.parse(url);
  295. // Allow plugins to intercept WebView requests.
  296. Uri remappedUri = resourceApi.remapUri(origUri);
  297. if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri) || needsKitKatContentUrlFix(origUri)) {
  298. CordovaResourceApi.OpenForReadResult result = resourceApi.openForRead(remappedUri, true);
  299. return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
  300. }
  301. // If we don't need to special-case the request, let the browser load it.
  302. return null;
  303. } catch (IOException e) {
  304. if (!(e instanceof FileNotFoundException)) {
  305. LOG.e(TAG, "Error occurred while loading a file (returning a 404).", e);
  306. }
  307. // Results in a 404.
  308. return new WebResourceResponse("text/plain", "UTF-8", null);
  309. }
  310. }
  311. private static boolean needsKitKatContentUrlFix(Uri uri) {
  312. return "content".equals(uri.getScheme());
  313. }
  314. private static boolean needsSpecialsInAssetUrlFix(Uri uri) {
  315. if (CordovaResourceApi.getUriType(uri) != CordovaResourceApi.URI_TYPE_ASSET) {
  316. return false;
  317. }
  318. if (uri.getQuery() != null || uri.getFragment() != null) {
  319. return true;
  320. }
  321. if (!uri.toString().contains("%")) {
  322. return false;
  323. }
  324. return false;
  325. }
  326. }