SystemImpl.java revision 631de99ef99dddde939aa5132e89625e35e77046
1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.webkit;
18
19import android.app.ActivityManagerNative;
20import android.app.AppGlobals;
21import android.content.Context;
22import android.content.pm.ApplicationInfo;
23import android.content.pm.IPackageDeleteObserver;
24import android.content.pm.PackageInfo;
25import android.content.pm.PackageManager;
26import android.content.pm.PackageManager.NameNotFoundException;
27import android.content.pm.UserInfo;
28import android.content.res.XmlResourceParser;
29import android.os.Build;
30import android.os.RemoteException;
31import android.os.UserHandle;
32import android.os.UserManager;
33import android.provider.Settings.Global;
34import android.provider.Settings;
35import android.util.AndroidRuntimeException;
36import android.util.Log;
37import android.webkit.WebViewFactory;
38import android.webkit.WebViewProviderInfo;
39
40import com.android.internal.util.XmlUtils;
41
42import java.io.IOException;
43import java.util.ArrayList;
44import java.util.List;
45
46import org.xmlpull.v1.XmlPullParserException;
47
48/**
49 * Default implementation for the WebView preparation Utility interface.
50 * @hide
51 */
52public class SystemImpl implements SystemInterface {
53    private static final String TAG = SystemImpl.class.getSimpleName();
54    private static final String TAG_START = "webviewproviders";
55    private static final String TAG_WEBVIEW_PROVIDER = "webviewprovider";
56    private static final String TAG_PACKAGE_NAME = "packageName";
57    private static final String TAG_DESCRIPTION = "description";
58    // Whether or not the provider must be explicitly chosen by the user to be used.
59    private static final String TAG_AVAILABILITY = "availableByDefault";
60    private static final String TAG_SIGNATURE = "signature";
61    private static final String TAG_FALLBACK = "isFallback";
62
63    /**
64     * Returns all packages declared in the framework resources as potential WebView providers.
65     * @hide
66     * */
67    @Override
68    public WebViewProviderInfo[] getWebViewPackages() {
69        int numFallbackPackages = 0;
70        int numAvailableByDefaultPackages = 0;
71        XmlResourceParser parser = null;
72        List<WebViewProviderInfo> webViewProviders = new ArrayList<WebViewProviderInfo>();
73        try {
74            parser = AppGlobals.getInitialApplication().getResources().getXml(
75                    com.android.internal.R.xml.config_webview_packages);
76            XmlUtils.beginDocument(parser, TAG_START);
77            while(true) {
78                XmlUtils.nextElement(parser);
79                String element = parser.getName();
80                if (element == null) {
81                    break;
82                }
83                if (element.equals(TAG_WEBVIEW_PROVIDER)) {
84                    String packageName = parser.getAttributeValue(null, TAG_PACKAGE_NAME);
85                    if (packageName == null) {
86                        throw new AndroidRuntimeException(
87                                "WebView provider in framework resources missing package name");
88                    }
89                    String description = parser.getAttributeValue(null, TAG_DESCRIPTION);
90                    if (description == null) {
91                        throw new AndroidRuntimeException(
92                                "WebView provider in framework resources missing description");
93                    }
94                    boolean availableByDefault = "true".equals(
95                            parser.getAttributeValue(null, TAG_AVAILABILITY));
96                    boolean isFallback = "true".equals(
97                            parser.getAttributeValue(null, TAG_FALLBACK));
98                    WebViewProviderInfo currentProvider = new WebViewProviderInfo(
99                            packageName, description, availableByDefault, isFallback,
100                            readSignatures(parser));
101                    if (currentProvider.isFallback) {
102                        numFallbackPackages++;
103                        if (!currentProvider.availableByDefault) {
104                            throw new AndroidRuntimeException(
105                                    "Each WebView fallback package must be available by default.");
106                        }
107                        if (numFallbackPackages > 1) {
108                            throw new AndroidRuntimeException(
109                                    "There can be at most one WebView fallback package.");
110                        }
111                    }
112                    if (currentProvider.availableByDefault) {
113                        numAvailableByDefaultPackages++;
114                    }
115                    webViewProviders.add(currentProvider);
116                }
117                else {
118                    Log.e(TAG, "Found an element that is not a WebView provider");
119                }
120            }
121        } catch (XmlPullParserException | IOException e) {
122            throw new AndroidRuntimeException("Error when parsing WebView config " + e);
123        } finally {
124            if (parser != null) parser.close();
125        }
126        if (numAvailableByDefaultPackages == 0) {
127            throw new AndroidRuntimeException("There must be at least one WebView package "
128                    + "that is available by default");
129        }
130        return webViewProviders.toArray(new WebViewProviderInfo[webViewProviders.size()]);
131    }
132
133    public int getFactoryPackageVersion(String packageName) throws NameNotFoundException {
134        PackageManager pm = AppGlobals.getInitialApplication().getPackageManager();
135        return pm.getPackageInfo(packageName, PackageManager.MATCH_FACTORY_ONLY).versionCode;
136    }
137
138    /**
139     * Reads all signatures at the current depth (within the current provider) from the XML parser.
140     */
141    private static String[] readSignatures(XmlResourceParser parser) throws IOException,
142            XmlPullParserException {
143        List<String> signatures = new ArrayList<String>();
144        int outerDepth = parser.getDepth();
145        while(XmlUtils.nextElementWithin(parser, outerDepth)) {
146            if (parser.getName().equals(TAG_SIGNATURE)) {
147                // Parse the value within the signature tag
148                String signature = parser.nextText();
149                signatures.add(signature);
150            } else {
151                Log.e(TAG, "Found an element in a webview provider that is not a signature");
152            }
153        }
154        return signatures.toArray(new String[signatures.size()]);
155    }
156
157    @Override
158    public int onWebViewProviderChanged(PackageInfo packageInfo) {
159        return WebViewFactory.onWebViewProviderChanged(packageInfo);
160    }
161
162    @Override
163    public String getUserChosenWebViewProvider(Context context) {
164        return Settings.Global.getString(context.getContentResolver(),
165                Settings.Global.WEBVIEW_PROVIDER);
166    }
167
168    @Override
169    public void updateUserSetting(Context context, String newProviderName) {
170        Settings.Global.putString(context.getContentResolver(),
171                Settings.Global.WEBVIEW_PROVIDER,
172                newProviderName == null ? "" : newProviderName);
173    }
174
175    @Override
176    public void killPackageDependents(String packageName) {
177        try {
178            ActivityManagerNative.getDefault().killPackageDependents(packageName,
179                    UserHandle.USER_ALL);
180        } catch (RemoteException e) {
181        }
182    }
183
184    @Override
185    public boolean isFallbackLogicEnabled() {
186        // Note that this is enabled by default (i.e. if the setting hasn't been set).
187        return Settings.Global.getInt(AppGlobals.getInitialApplication().getContentResolver(),
188                Settings.Global.WEBVIEW_FALLBACK_LOGIC_ENABLED, 1) == 1;
189    }
190
191    @Override
192    public void enableFallbackLogic(boolean enable) {
193        Settings.Global.putInt(AppGlobals.getInitialApplication().getContentResolver(),
194                Settings.Global.WEBVIEW_FALLBACK_LOGIC_ENABLED, enable ? 1 : 0);
195    }
196
197    @Override
198    public void uninstallAndDisablePackageForAllUsers(Context context, String packageName) {
199        enablePackageForAllUsers(context, packageName, false);
200        try {
201            PackageManager pm = AppGlobals.getInitialApplication().getPackageManager();
202            ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
203            if (applicationInfo != null && applicationInfo.isUpdatedSystemApp()) {
204                pm.deletePackage(packageName, new IPackageDeleteObserver.Stub() {
205                        public void packageDeleted(String packageName, int returnCode) {
206                            enablePackageForAllUsers(context, packageName, false);
207                        }
208                    }, PackageManager.DELETE_SYSTEM_APP | PackageManager.DELETE_ALL_USERS);
209            }
210        } catch (NameNotFoundException e) {
211        }
212    }
213
214    @Override
215    public void enablePackageForAllUsers(Context context, String packageName, boolean enable) {
216        UserManager userManager = (UserManager)context.getSystemService(Context.USER_SERVICE);
217        for(UserInfo userInfo : userManager.getUsers()) {
218            enablePackageForUser(packageName, enable, userInfo.id);
219        }
220    }
221
222    @Override
223    public void enablePackageForUser(String packageName, boolean enable, int userId) {
224        try {
225            AppGlobals.getPackageManager().setApplicationEnabledSetting(
226                    packageName,
227                    enable ? PackageManager.COMPONENT_ENABLED_STATE_DEFAULT :
228                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER, 0,
229                    userId, null);
230        } catch (RemoteException | IllegalArgumentException e) {
231            Log.w(TAG, "Tried to " + (enable ? "enable " : "disable ") + packageName
232                    + " for user " + userId + ": " + e);
233        }
234    }
235
236    @Override
237    public boolean systemIsDebuggable() {
238        return Build.IS_DEBUGGABLE;
239    }
240
241    @Override
242    public PackageInfo getPackageInfoForProvider(WebViewProviderInfo configInfo)
243            throws NameNotFoundException {
244        PackageManager pm = AppGlobals.getInitialApplication().getPackageManager();
245        return pm.getPackageInfo(configInfo.packageName, PACKAGE_FLAGS);
246    }
247
248    // flags declaring we want extra info from the package manager for webview providers
249    private final static int PACKAGE_FLAGS = PackageManager.GET_META_DATA
250            | PackageManager.GET_SIGNATURES | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
251}
252