/* Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.getcapacitor; import static com.getcapacitor.plugin.util.HttpRequestHandler.isDomainExcludedFromSSL; import android.content.Context; import android.net.Uri; import android.util.Base64; import android.webkit.CookieManager; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import com.getcapacitor.plugin.util.CapacitorHttpUrlConnection; import com.getcapacitor.plugin.util.HttpRequestHandler; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Helper class meant to be used with the android.webkit.WebView class to enable hosting assets, * resources and other data on 'virtual' https:// URL. * Hosting assets and resources on https:// URLs is desirable as it is compatible with the * Same-Origin policy. *
* This class is intended to be used from within the
* {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView, String)} and
* {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView,
* android.webkit.WebResourceRequest)}
* methods.
*/
public class WebViewLocalServer {
private static final String capacitorFileStart = Bridge.CAPACITOR_FILE_START;
private static final String capacitorContentStart = Bridge.CAPACITOR_CONTENT_START;
private String basePath;
private final UriMatcher uriMatcher;
private final AndroidProtocolHandler protocolHandler;
private final ArrayList
* Methods of this handler will be invoked on a background thread and care must be taken to
* correctly synchronize access to any shared state.
*
* On Android KitKat and above these methods may be called on more than one thread. This thread
* may be different than the thread on which the shouldInterceptRequest method was invoke.
* This means that on Android KitKat and above it is possible to block in this method without
* blocking other resources from loading. The number of threads used to parallelize loading
* is an internal implementation detail of the WebView and may change between updates which
* means that the amount of time spend blocking in this method should be kept to an absolute
* minimum.
*/
public abstract static class PathHandler {
protected String mimeType;
private String encoding;
private String charset;
private int statusCode;
private String reasonPhrase;
private Map
* Use {@link #buildDefaultResponseHeaders()} instead, which returns a copy of the map.
* request.
* This method should be invoked from within
* {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView,
* android.webkit.WebResourceRequest)}.
*
* @param request the request to process.
* @return a response if the request URL had a matching handler, null if no handler was found.
*/
public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) {
Uri loadingUrl = request.getUrl();
if (null != loadingUrl.getPath() && loadingUrl.getPath().startsWith(Bridge.CAPACITOR_HTTP_INTERCEPTOR_START)) {
// Only fetch/XHR should reach the proxy; a document would run remote content at the app origin.
boolean httpEnabled = bridge.getConfig().getPluginConfiguration("CapacitorHttp").getBoolean("enabled", false);
if (!httpEnabled || isDocumentRequest(request)) {
return null;
}
Logger.debug("Handling CapacitorHttp request: " + loadingUrl);
try {
return handleCapacitorHttpRequest(request);
} catch (Exception e) {
Logger.error(e.getLocalizedMessage());
return null;
}
}
PathHandler handler;
synchronized (uriMatcher) {
handler = (PathHandler) uriMatcher.match(request.getUrl());
}
if (handler == null) {
return null;
}
if (isLocalFile(loadingUrl) || isMainUrl(loadingUrl) || !isAllowedUrl(loadingUrl) || isErrorUrl(loadingUrl)) {
Logger.debug("Handling local request: " + request.getUrl().toString());
return handleLocalRequest(request, handler);
} else {
return handleProxyRequest(request, handler);
}
}
/** isForMainFrame() is false for an iframe and a fetch alike; only navigations send this header. */
private boolean isDocumentRequest(WebResourceRequest request) {
if (request.isForMainFrame()) {
return true;
}
Mapuri. The handler will be invoked
* every time the shouldInterceptRequest method of the instance is called with
* a matching uri.
*
* @param uri the uri to use the handler for. The scheme and authority (domain) will be matched
* exactly. The path may contain a '*' element which will match a single element of
* a path (so a handler registered for /a/* will be invoked for /a/b and /a/c.html
* but not for /a/b/b) or the '**' element which will match any number of path
* elements.
* @param handler the handler to use for the uri.
*/
void register(Uri uri, PathHandler handler) {
synchronized (uriMatcher) {
uriMatcher.addURI(uri.getScheme(), uri.getAuthority(), uri.getPath(), handler);
}
}
/**
* Hosts the application's assets on an https:// URL. Assets from the local path
* assetPath/... will be available under
* https://{uuid}.androidplatform.net/assets/....
*
* @param assetPath the local path in the application's asset folder which will be made
* available by the server (for example "/www").
* @return prefixes under which the assets are hosted.
*/
public void hostAssets(String assetPath) {
this.isAsset = true;
this.basePath = assetPath;
createHostingDetails();
}
/**
* Hosts the application's files on an https:// URL. Files from the basePath
* basePath/... will be available under
* https://{uuid}.androidplatform.net/....
*
* @param basePath the local path in the application's data folder which will be made
* available by the server (for example "/www").
* @return prefixes under which the assets are hosted.
*/
public void hostFiles(final String basePath) {
this.isAsset = false;
this.basePath = basePath;
createHostingDetails();
}
private void createHostingDetails() {
final String assetPath = this.basePath;
if (assetPath.indexOf('*') != -1) {
throw new IllegalArgumentException("assetPath cannot contain the '*' character.");
}
PathHandler handler = new PathHandler() {
@Override
public InputStream handle(Uri url) {
InputStream stream = null;
String path = url.getPath();
// Pass path to routeProcessor if present
RouteProcessor routeProcessor = bridge.getRouteProcessor();
boolean ignoreAssetPath = false;
if (routeProcessor != null) {
ProcessedRoute processedRoute = bridge.getRouteProcessor().process("", path);
path = processedRoute.getPath();
isAsset = processedRoute.isAsset();
ignoreAssetPath = processedRoute.isIgnoreAssetPath();
}
try {
if (path.startsWith(capacitorContentStart)) {
stream = protocolHandler.openContentUrl(url);
} else if (path.startsWith(capacitorFileStart)) {
stream = protocolHandler.openFile(path);
} else if (!isAsset) {
if (routeProcessor == null) {
path = basePath + url.getPath();
}
stream = protocolHandler.openFile(path);
} else if (ignoreAssetPath) {
stream = protocolHandler.openAsset(path);
} else {
stream = protocolHandler.openAsset(assetPath + path);
}
} catch (IOException e) {
Logger.error("Unable to open asset URL: " + url);
return null;
}
return stream;
}
};
for (String authority : authorities) {
registerUriForScheme(Bridge.CAPACITOR_HTTP_SCHEME, handler, authority);
registerUriForScheme(Bridge.CAPACITOR_HTTPS_SCHEME, handler, authority);
String customScheme = this.bridge.getScheme();
if (!customScheme.equals(Bridge.CAPACITOR_HTTP_SCHEME) && !customScheme.equals(Bridge.CAPACITOR_HTTPS_SCHEME)) {
registerUriForScheme(customScheme, handler, authority);
}
}
}
private void registerUriForScheme(String scheme, PathHandler handler, String authority) {
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(scheme);
uriBuilder.authority(authority);
uriBuilder.path("");
Uri uriPrefix = uriBuilder.build();
register(Uri.withAppendedPath(uriPrefix, "/"), handler);
register(Uri.withAppendedPath(uriPrefix, "**"), handler);
}
/**
* The KitKat WebView reads the InputStream on a separate threadpool. We can use that to
* parallelize loading.
*/
private abstract static class LazyInputStream extends InputStream {
protected final PathHandler handler;
private InputStream is = null;
public LazyInputStream(PathHandler handler) {
this.handler = handler;
}
private InputStream getInputStream() {
if (is == null) {
is = handle();
}
return is;
}
protected abstract InputStream handle();
@Override
public int available() throws IOException {
InputStream is = getInputStream();
return is != null ? is.available() : -1;
}
@Override
public int read() throws IOException {
InputStream is = getInputStream();
return is != null ? is.read() : -1;
}
@Override
public int read(byte[] b) throws IOException {
InputStream is = getInputStream();
return is != null ? is.read(b) : -1;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
InputStream is = getInputStream();
return is != null ? is.read(b, off, len) : -1;
}
@Override
public long skip(long n) throws IOException {
InputStream is = getInputStream();
return is != null ? is.skip(n) : 0;
}
}
// For L and above.
private static class LollipopLazyInputStream extends LazyInputStream {
private WebResourceRequest request;
private InputStream is;
public LollipopLazyInputStream(PathHandler handler, WebResourceRequest request) {
super(handler);
this.request = request;
}
@Override
protected InputStream handle() {
return handler.handle(request);
}
}
public String getBasePath() {
return this.basePath;
}
}