1/*
2 * Copyright (C) 2014 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;
18
19import android.Manifest.permission;
20import android.annotation.Nullable;
21import android.content.ComponentName;
22import android.content.Context;
23import android.content.Intent;
24import android.content.pm.PackageManager;
25import android.content.pm.ResolveInfo;
26import android.content.pm.ServiceInfo;
27import android.net.NetworkScoreManager;
28import android.net.NetworkScorerAppData;
29import android.provider.Settings;
30import android.text.TextUtils;
31import android.util.Log;
32
33import com.android.internal.R;
34import com.android.internal.annotations.VisibleForTesting;
35
36import java.util.ArrayList;
37import java.util.Collections;
38import java.util.List;
39
40/**
41 * Internal class for discovering and managing the network scorer/recommendation application.
42 *
43 * @hide
44 */
45@VisibleForTesting
46public class NetworkScorerAppManager {
47    private static final String TAG = "NetworkScorerAppManager";
48    private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
49    private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
50    private final Context mContext;
51    private final SettingsFacade mSettingsFacade;
52
53    public NetworkScorerAppManager(Context context) {
54      this(context, new SettingsFacade());
55    }
56
57    @VisibleForTesting
58    public NetworkScorerAppManager(Context context, SettingsFacade settingsFacade) {
59        mContext = context;
60        mSettingsFacade = settingsFacade;
61    }
62
63    /**
64     * Returns the list of available scorer apps. The list will be empty if there are
65     * no valid scorers.
66     */
67    @VisibleForTesting
68    public List<NetworkScorerAppData> getAllValidScorers() {
69        if (VERBOSE) Log.v(TAG, "getAllValidScorers()");
70        final PackageManager pm = mContext.getPackageManager();
71        final Intent serviceIntent = new Intent(NetworkScoreManager.ACTION_RECOMMEND_NETWORKS);
72        final List<ResolveInfo> resolveInfos =
73                pm.queryIntentServices(serviceIntent, PackageManager.GET_META_DATA);
74        if (resolveInfos == null || resolveInfos.isEmpty()) {
75            if (DEBUG) Log.d(TAG, "Found 0 Services able to handle " + serviceIntent);
76            return Collections.emptyList();
77        }
78
79        List<NetworkScorerAppData> appDataList = new ArrayList<>();
80        for (int i = 0; i < resolveInfos.size(); i++) {
81            final ServiceInfo serviceInfo = resolveInfos.get(i).serviceInfo;
82            if (hasPermissions(serviceInfo.packageName)) {
83                if (VERBOSE) {
84                    Log.v(TAG, serviceInfo.packageName + " is a valid scorer/recommender.");
85                }
86                final ComponentName serviceComponentName =
87                        new ComponentName(serviceInfo.packageName, serviceInfo.name);
88                final String serviceLabel = getRecommendationServiceLabel(serviceInfo, pm);
89                final ComponentName useOpenWifiNetworksActivity =
90                        findUseOpenWifiNetworksActivity(serviceInfo);
91                final String networkAvailableNotificationChannelId =
92                        getNetworkAvailableNotificationChannelId(serviceInfo);
93                appDataList.add(
94                        new NetworkScorerAppData(serviceInfo.applicationInfo.uid,
95                                serviceComponentName, serviceLabel, useOpenWifiNetworksActivity,
96                                networkAvailableNotificationChannelId));
97            } else {
98                if (VERBOSE) Log.v(TAG, serviceInfo.packageName
99                        + " is NOT a valid scorer/recommender.");
100            }
101        }
102
103        return appDataList;
104    }
105
106    @Nullable
107    private String getRecommendationServiceLabel(ServiceInfo serviceInfo, PackageManager pm) {
108        if (serviceInfo.metaData != null) {
109            final String label = serviceInfo.metaData
110                    .getString(NetworkScoreManager.RECOMMENDATION_SERVICE_LABEL_META_DATA);
111            if (!TextUtils.isEmpty(label)) {
112                return label;
113            }
114        }
115        CharSequence label = serviceInfo.loadLabel(pm);
116        return label == null ? null : label.toString();
117    }
118
119    @Nullable
120    private ComponentName findUseOpenWifiNetworksActivity(ServiceInfo serviceInfo) {
121        if (serviceInfo.metaData == null) {
122            if (DEBUG) {
123                Log.d(TAG, "No metadata found on " + serviceInfo.getComponentName());
124            }
125            return null;
126        }
127        final String useOpenWifiPackage = serviceInfo.metaData
128                .getString(NetworkScoreManager.USE_OPEN_WIFI_PACKAGE_META_DATA);
129        if (TextUtils.isEmpty(useOpenWifiPackage)) {
130            if (DEBUG) {
131                Log.d(TAG, "No use_open_wifi_package metadata found on "
132                        + serviceInfo.getComponentName());
133            }
134            return null;
135        }
136        final Intent enableUseOpenWifiIntent = new Intent(NetworkScoreManager.ACTION_CUSTOM_ENABLE)
137                .setPackage(useOpenWifiPackage);
138        final ResolveInfo resolveActivityInfo = mContext.getPackageManager()
139                .resolveActivity(enableUseOpenWifiIntent, 0 /* flags */);
140        if (VERBOSE) {
141            Log.d(TAG, "Resolved " + enableUseOpenWifiIntent + " to " + resolveActivityInfo);
142        }
143
144        if (resolveActivityInfo != null && resolveActivityInfo.activityInfo != null) {
145            return resolveActivityInfo.activityInfo.getComponentName();
146        }
147
148        return null;
149    }
150
151    @Nullable
152    private static String getNetworkAvailableNotificationChannelId(ServiceInfo serviceInfo) {
153        if (serviceInfo.metaData == null) {
154            if (DEBUG) {
155                Log.d(TAG, "No metadata found on " + serviceInfo.getComponentName());
156            }
157            return null;
158        }
159
160        return serviceInfo.metaData.getString(
161                NetworkScoreManager.NETWORK_AVAILABLE_NOTIFICATION_CHANNEL_ID_META_DATA);
162    }
163
164
165    /**
166     * Get the application to use for scoring networks.
167     *
168     * @return the scorer app info or null if scoring is disabled (including if no scorer was ever
169     *     selected) or if the previously-set scorer is no longer a valid scorer app (e.g. because
170     *     it was disabled or uninstalled).
171     */
172    @Nullable
173    @VisibleForTesting
174    public NetworkScorerAppData getActiveScorer() {
175        final int enabledSetting = getNetworkRecommendationsEnabledSetting();
176        if (enabledSetting == NetworkScoreManager.RECOMMENDATIONS_ENABLED_FORCED_OFF) {
177            return null;
178        }
179
180        return getScorer(getNetworkRecommendationsPackage());
181    }
182
183    private NetworkScorerAppData getScorer(String packageName) {
184        if (TextUtils.isEmpty(packageName)) {
185            return null;
186        }
187
188        // Otherwise return the recommendation provider (which may be null).
189        List<NetworkScorerAppData> apps = getAllValidScorers();
190        for (int i = 0; i < apps.size(); i++) {
191            NetworkScorerAppData app = apps.get(i);
192            if (app.getRecommendationServicePackageName().equals(packageName)) {
193                return app;
194            }
195        }
196
197        return null;
198    }
199
200    private boolean hasPermissions(String packageName) {
201        final PackageManager pm = mContext.getPackageManager();
202        return pm.checkPermission(permission.SCORE_NETWORKS, packageName)
203                == PackageManager.PERMISSION_GRANTED;
204    }
205
206    /**
207     * Set the specified package as the default scorer application.
208     *
209     * <p>The caller must have permission to write to {@link Settings.Global}.
210     *
211     * @param packageName the packageName of the new scorer to use. If null, scoring will be forced
212     *                    off, otherwise the scorer will only be set if it is a valid scorer
213     *                    application.
214     * @return true if the package was a valid scorer (including <code>null</code>) and now
215     *         represents the active scorer, false otherwise.
216     */
217    @VisibleForTesting
218    public boolean setActiveScorer(String packageName) {
219        final String oldPackageName = getNetworkRecommendationsPackage();
220
221        if (TextUtils.equals(oldPackageName, packageName)) {
222            // No change.
223            return true;
224        }
225
226        if (TextUtils.isEmpty(packageName)) {
227            Log.i(TAG, "Network scorer forced off, was: " + oldPackageName);
228            setNetworkRecommendationsPackage(null);
229            setNetworkRecommendationsEnabledSetting(
230                    NetworkScoreManager.RECOMMENDATIONS_ENABLED_FORCED_OFF);
231            return true;
232        }
233
234        // We only make the change if the new package is valid.
235        if (getScorer(packageName) != null) {
236            Log.i(TAG, "Changing network scorer from " + oldPackageName + " to " + packageName);
237            setNetworkRecommendationsPackage(packageName);
238            setNetworkRecommendationsEnabledSetting(NetworkScoreManager.RECOMMENDATIONS_ENABLED_ON);
239            return true;
240        } else {
241            Log.w(TAG, "Requested network scorer is not valid: " + packageName);
242            return false;
243        }
244    }
245
246    /**
247     * Ensures the {@link Settings.Global#NETWORK_RECOMMENDATIONS_PACKAGE} setting points to a valid
248     * package and {@link Settings.Global#NETWORK_RECOMMENDATIONS_ENABLED} is consistent.
249     *
250     * If {@link Settings.Global#NETWORK_RECOMMENDATIONS_PACKAGE} doesn't point to a valid package
251     * then it will be reverted to the default package specified by
252     * {@link R.string#config_defaultNetworkRecommendationProviderPackage}. If the default package
253     * is no longer valid then {@link Settings.Global#NETWORK_RECOMMENDATIONS_ENABLED} will be set
254     * to <code>0</code> (disabled).
255     */
256    @VisibleForTesting
257    public void updateState() {
258        final int enabledSetting = getNetworkRecommendationsEnabledSetting();
259        if (enabledSetting == NetworkScoreManager.RECOMMENDATIONS_ENABLED_FORCED_OFF) {
260            // Don't change anything if it's forced off.
261            if (DEBUG) Log.d(TAG, "Recommendations forced off.");
262            return;
263        }
264
265        // First, see if the current package is still valid. If so, then we can exit early.
266        final String currentPackageName = getNetworkRecommendationsPackage();
267        if (getScorer(currentPackageName) != null) {
268            if (VERBOSE) Log.v(TAG, currentPackageName + " is the active scorer.");
269            setNetworkRecommendationsEnabledSetting(NetworkScoreManager.RECOMMENDATIONS_ENABLED_ON);
270            return;
271        }
272
273        // the active scorer isn't valid, revert to the default if it's different
274        final String defaultPackageName = getDefaultPackageSetting();
275        if (!TextUtils.equals(currentPackageName, defaultPackageName)) {
276            setNetworkRecommendationsPackage(defaultPackageName);
277            if (DEBUG) {
278                Log.d(TAG, "Defaulted the network recommendations app to: " + defaultPackageName);
279            }
280            if (getScorer(defaultPackageName) != null) { // the default is valid
281                if (DEBUG) Log.d(TAG, defaultPackageName + " is now the active scorer.");
282                setNetworkRecommendationsEnabledSetting(
283                        NetworkScoreManager.RECOMMENDATIONS_ENABLED_ON);
284            } else { // the default isn't valid either, we're disabled at this point
285                if (DEBUG) Log.d(TAG, defaultPackageName + " is not an active scorer.");
286                setNetworkRecommendationsEnabledSetting(
287                        NetworkScoreManager.RECOMMENDATIONS_ENABLED_OFF);
288            }
289        }
290    }
291
292    /**
293     * Migrates the NETWORK_SCORER_APP Setting to the USE_OPEN_WIFI_PACKAGE Setting.
294     */
295    @VisibleForTesting
296    public void migrateNetworkScorerAppSettingIfNeeded() {
297        final String scorerAppPkgNameSetting =
298                mSettingsFacade.getString(mContext, Settings.Global.NETWORK_SCORER_APP);
299        if (TextUtils.isEmpty(scorerAppPkgNameSetting)) {
300            // Early exit, nothing to do.
301            return;
302        }
303
304        final NetworkScorerAppData currentAppData = getActiveScorer();
305        if (currentAppData == null) {
306            // Don't touch anything until we have an active scorer to work with.
307            return;
308        }
309
310        if (DEBUG) {
311            Log.d(TAG, "Migrating Settings.Global.NETWORK_SCORER_APP "
312                    + "(" + scorerAppPkgNameSetting + ")...");
313        }
314
315        // If the new (useOpenWifi) Setting isn't set and the old Setting's value matches the
316        // new metadata value then update the new Setting with the old value. Otherwise it's a
317        // mismatch so we shouldn't enable the Setting automatically.
318        final ComponentName enableUseOpenWifiActivity =
319                currentAppData.getEnableUseOpenWifiActivity();
320        final String useOpenWifiSetting =
321                mSettingsFacade.getString(mContext, Settings.Global.USE_OPEN_WIFI_PACKAGE);
322        if (TextUtils.isEmpty(useOpenWifiSetting)
323                && enableUseOpenWifiActivity != null
324                && scorerAppPkgNameSetting.equals(enableUseOpenWifiActivity.getPackageName())) {
325            mSettingsFacade.putString(mContext, Settings.Global.USE_OPEN_WIFI_PACKAGE,
326                    scorerAppPkgNameSetting);
327            if (DEBUG) {
328                Log.d(TAG, "Settings.Global.USE_OPEN_WIFI_PACKAGE set to "
329                        + "'" + scorerAppPkgNameSetting + "'.");
330            }
331        }
332
333        // Clear out the old setting so we don't run through the migration code again.
334        mSettingsFacade.putString(mContext, Settings.Global.NETWORK_SCORER_APP, null);
335        if (DEBUG) {
336            Log.d(TAG, "Settings.Global.NETWORK_SCORER_APP migration complete.");
337            final String setting =
338                    mSettingsFacade.getString(mContext, Settings.Global.USE_OPEN_WIFI_PACKAGE);
339            Log.d(TAG, "Settings.Global.USE_OPEN_WIFI_PACKAGE is: '" + setting + "'.");
340        }
341    }
342
343    private String getDefaultPackageSetting() {
344        return mContext.getResources().getString(
345                R.string.config_defaultNetworkRecommendationProviderPackage);
346    }
347
348    private String getNetworkRecommendationsPackage() {
349        return mSettingsFacade.getString(mContext, Settings.Global.NETWORK_RECOMMENDATIONS_PACKAGE);
350    }
351
352    private void setNetworkRecommendationsPackage(String packageName) {
353        mSettingsFacade.putString(mContext,
354                Settings.Global.NETWORK_RECOMMENDATIONS_PACKAGE, packageName);
355    }
356
357    private int getNetworkRecommendationsEnabledSetting() {
358        return mSettingsFacade.getInt(mContext, Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED, 0);
359    }
360
361    private void setNetworkRecommendationsEnabledSetting(int value) {
362        mSettingsFacade.putInt(mContext,
363                Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED, value);
364    }
365
366    /**
367     * Wrapper around Settings to make testing easier.
368     */
369    public static class SettingsFacade {
370        public boolean putString(Context context, String name, String value) {
371            return Settings.Global.putString(context.getContentResolver(), name, value);
372        }
373
374        public String getString(Context context, String name) {
375            return Settings.Global.getString(context.getContentResolver(), name);
376        }
377
378        public boolean putInt(Context context, String name, int value) {
379            return Settings.Global.putInt(context.getContentResolver(), name, value);
380        }
381
382        public int getInt(Context context, String name, int defaultValue) {
383            return Settings.Global.getInt(context.getContentResolver(), name, defaultValue);
384        }
385    }
386}
387