1 /*
2  * Copyright (C) 2008 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 
17 package com.android.settings;
18 
19 import android.app.Activity;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.pm.ApplicationInfo;
23 import android.content.pm.PackageManager;
24 import android.content.pm.ResolveInfo;
25 import android.os.Binder;
26 import android.os.Build;
27 import android.os.Bundle;
28 import android.os.Parcel;
29 import android.os.RemoteException;
30 import android.os.SELinux;
31 import android.os.SystemClock;
32 import android.os.SystemProperties;
33 import android.os.UserHandle;
34 import android.os.UserManager;
35 import android.preference.Preference;
36 import android.preference.PreferenceGroup;
37 import android.preference.PreferenceScreen;
38 import android.provider.SearchIndexableResource;
39 import android.provider.Settings;
40 import android.text.TextUtils;
41 import android.util.Log;
42 import android.widget.Toast;
43 import com.android.settings.search.BaseSearchIndexProvider;
44 import com.android.settings.search.Index;
45 import com.android.settings.search.Indexable;
46 
47 import java.io.BufferedReader;
48 import java.io.FileReader;
49 import java.io.IOException;
50 import java.util.ArrayList;
51 import java.util.Arrays;
52 import java.util.List;
53 import java.util.regex.Matcher;
54 import java.util.regex.Pattern;
55 
56 public class DeviceInfoSettings extends SettingsPreferenceFragment implements Indexable {
57 
58     private static final String LOG_TAG = "DeviceInfoSettings";
59     private static final String FILENAME_PROC_VERSION = "/proc/version";
60     private static final String FILENAME_MSV = "/sys/board_properties/soc/msv";
61 
62     private static final String KEY_CONTAINER = "container";
63     private static final String KEY_REGULATORY_INFO = "regulatory_info";
64     private static final String KEY_TERMS = "terms";
65     private static final String KEY_LICENSE = "license";
66     private static final String KEY_COPYRIGHT = "copyright";
67     private static final String KEY_WEBVIEW_LICENSE = "webview_license";
68     private static final String KEY_SYSTEM_UPDATE_SETTINGS = "system_update_settings";
69     private static final String PROPERTY_URL_SAFETYLEGAL = "ro.url.safetylegal";
70     private static final String PROPERTY_SELINUX_STATUS = "ro.build.selinux";
71     private static final String KEY_KERNEL_VERSION = "kernel_version";
72     private static final String KEY_BUILD_NUMBER = "build_number";
73     private static final String KEY_DEVICE_MODEL = "device_model";
74     private static final String KEY_SELINUX_STATUS = "selinux_status";
75     private static final String KEY_BASEBAND_VERSION = "baseband_version";
76     private static final String KEY_FIRMWARE_VERSION = "firmware_version";
77     private static final String KEY_UPDATE_SETTING = "additional_system_update_settings";
78     private static final String KEY_EQUIPMENT_ID = "fcc_equipment_id";
79     private static final String PROPERTY_EQUIPMENT_ID = "ro.ril.fccid";
80     private static final String KEY_DEVICE_FEEDBACK = "device_feedback";
81     private static final String KEY_SAFETY_LEGAL = "safetylegal";
82 
83     static final int TAPS_TO_BE_A_DEVELOPER = 7;
84 
85     long[] mHits = new long[3];
86     int mDevHitCountdown;
87     Toast mDevHitToast;
88 
89     @Override
onCreate(Bundle icicle)90     public void onCreate(Bundle icicle) {
91         super.onCreate(icicle);
92 
93         addPreferencesFromResource(R.xml.device_info_settings);
94 
95         setStringSummary(KEY_FIRMWARE_VERSION, Build.VERSION.RELEASE);
96         findPreference(KEY_FIRMWARE_VERSION).setEnabled(true);
97         setValueSummary(KEY_BASEBAND_VERSION, "gsm.version.baseband");
98         setStringSummary(KEY_DEVICE_MODEL, Build.MODEL + getMsvSuffix());
99         setValueSummary(KEY_EQUIPMENT_ID, PROPERTY_EQUIPMENT_ID);
100         setStringSummary(KEY_DEVICE_MODEL, Build.MODEL);
101         setStringSummary(KEY_BUILD_NUMBER, Build.DISPLAY);
102         findPreference(KEY_BUILD_NUMBER).setEnabled(true);
103         findPreference(KEY_KERNEL_VERSION).setSummary(getFormattedKernelVersion());
104 
105         if (!SELinux.isSELinuxEnabled()) {
106             String status = getResources().getString(R.string.selinux_status_disabled);
107             setStringSummary(KEY_SELINUX_STATUS, status);
108         } else if (!SELinux.isSELinuxEnforced()) {
109             String status = getResources().getString(R.string.selinux_status_permissive);
110             setStringSummary(KEY_SELINUX_STATUS, status);
111         }
112 
113         // Remove selinux information if property is not present
114         removePreferenceIfPropertyMissing(getPreferenceScreen(), KEY_SELINUX_STATUS,
115                 PROPERTY_SELINUX_STATUS);
116 
117         // Remove Safety information preference if PROPERTY_URL_SAFETYLEGAL is not set
118         removePreferenceIfPropertyMissing(getPreferenceScreen(), KEY_SAFETY_LEGAL,
119                 PROPERTY_URL_SAFETYLEGAL);
120 
121         // Remove Equipment id preference if FCC ID is not set by RIL
122         removePreferenceIfPropertyMissing(getPreferenceScreen(), KEY_EQUIPMENT_ID,
123                 PROPERTY_EQUIPMENT_ID);
124 
125         // Remove Baseband version if wifi-only device
126         if (Utils.isWifiOnly(getActivity())) {
127             getPreferenceScreen().removePreference(findPreference(KEY_BASEBAND_VERSION));
128         }
129 
130         // Dont show feedback option if there is no reporter.
131         if (TextUtils.isEmpty(getFeedbackReporterPackage(getActivity()))) {
132             getPreferenceScreen().removePreference(findPreference(KEY_DEVICE_FEEDBACK));
133         }
134 
135         /*
136          * Settings is a generic app and should not contain any device-specific
137          * info.
138          */
139         final Activity act = getActivity();
140         // These are contained in the "container" preference group
141         PreferenceGroup parentPreference = (PreferenceGroup) findPreference(KEY_CONTAINER);
142         Utils.updatePreferenceToSpecificActivityOrRemove(act, parentPreference, KEY_TERMS,
143                 Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
144         Utils.updatePreferenceToSpecificActivityOrRemove(act, parentPreference, KEY_LICENSE,
145                 Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
146         Utils.updatePreferenceToSpecificActivityOrRemove(act, parentPreference, KEY_COPYRIGHT,
147                 Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
148         Utils.updatePreferenceToSpecificActivityOrRemove(act, parentPreference, KEY_WEBVIEW_LICENSE,
149                 Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
150 
151         // These are contained by the root preference screen
152         parentPreference = getPreferenceScreen();
153         if (UserHandle.myUserId() == UserHandle.USER_OWNER) {
154             Utils.updatePreferenceToSpecificActivityOrRemove(act, parentPreference,
155                     KEY_SYSTEM_UPDATE_SETTINGS,
156                     Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
157         } else {
158             // Remove for secondary users
159             removePreference(KEY_SYSTEM_UPDATE_SETTINGS);
160         }
161 
162         // Read platform settings for additional system update setting
163         removePreferenceIfBoolFalse(KEY_UPDATE_SETTING,
164                 R.bool.config_additional_system_update_setting_enable);
165 
166         // Remove regulatory information if none present.
167         final Intent intent = new Intent(Settings.ACTION_SHOW_REGULATORY_INFO);
168         if (getPackageManager().queryIntentActivities(intent, 0).isEmpty()) {
169             Preference pref = findPreference(KEY_REGULATORY_INFO);
170             if (pref != null) {
171                 getPreferenceScreen().removePreference(pref);
172             }
173         }
174     }
175 
176     @Override
onResume()177     public void onResume() {
178         super.onResume();
179         mDevHitCountdown = getActivity().getSharedPreferences(DevelopmentSettings.PREF_FILE,
180                 Context.MODE_PRIVATE).getBoolean(DevelopmentSettings.PREF_SHOW,
181                         android.os.Build.TYPE.equals("eng")) ? -1 : TAPS_TO_BE_A_DEVELOPER;
182         mDevHitToast = null;
183     }
184 
185     @Override
onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference)186     public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
187         if (preference.getKey().equals(KEY_FIRMWARE_VERSION)) {
188             System.arraycopy(mHits, 1, mHits, 0, mHits.length-1);
189             mHits[mHits.length-1] = SystemClock.uptimeMillis();
190             if (mHits[0] >= (SystemClock.uptimeMillis()-500)) {
191                 Intent intent = new Intent(Intent.ACTION_MAIN);
192                 intent.setClassName("android",
193                         com.android.internal.app.PlatLogoActivity.class.getName());
194                 try {
195                     startActivity(intent);
196                 } catch (Exception e) {
197                     Log.e(LOG_TAG, "Unable to start activity " + intent.toString());
198                 }
199             }
200         } else if (preference.getKey().equals(KEY_BUILD_NUMBER)) {
201             // Don't enable developer options for secondary users.
202             if (UserHandle.myUserId() != UserHandle.USER_OWNER) return true;
203 
204             final UserManager um = (UserManager) getSystemService(Context.USER_SERVICE);
205             if (um.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES)) return true;
206 
207             if (mDevHitCountdown > 0) {
208                 mDevHitCountdown--;
209                 if (mDevHitCountdown == 0) {
210                     getActivity().getSharedPreferences(DevelopmentSettings.PREF_FILE,
211                             Context.MODE_PRIVATE).edit().putBoolean(
212                                     DevelopmentSettings.PREF_SHOW, true).apply();
213                     if (mDevHitToast != null) {
214                         mDevHitToast.cancel();
215                     }
216                     mDevHitToast = Toast.makeText(getActivity(), R.string.show_dev_on,
217                             Toast.LENGTH_LONG);
218                     mDevHitToast.show();
219                     // This is good time to index the Developer Options
220                     Index.getInstance(
221                             getActivity().getApplicationContext()).updateFromClassNameResource(
222                                     DevelopmentSettings.class.getName(), true, true);
223 
224                 } else if (mDevHitCountdown > 0
225                         && mDevHitCountdown < (TAPS_TO_BE_A_DEVELOPER-2)) {
226                     if (mDevHitToast != null) {
227                         mDevHitToast.cancel();
228                     }
229                     mDevHitToast = Toast.makeText(getActivity(), getResources().getQuantityString(
230                             R.plurals.show_dev_countdown, mDevHitCountdown, mDevHitCountdown),
231                             Toast.LENGTH_SHORT);
232                     mDevHitToast.show();
233                 }
234             } else if (mDevHitCountdown < 0) {
235                 if (mDevHitToast != null) {
236                     mDevHitToast.cancel();
237                 }
238                 mDevHitToast = Toast.makeText(getActivity(), R.string.show_dev_already,
239                         Toast.LENGTH_LONG);
240                 mDevHitToast.show();
241             }
242         } else if (preference.getKey().equals(KEY_DEVICE_FEEDBACK)) {
243             sendFeedback();
244         }
245         return super.onPreferenceTreeClick(preferenceScreen, preference);
246     }
247 
removePreferenceIfPropertyMissing(PreferenceGroup preferenceGroup, String preference, String property )248     private void removePreferenceIfPropertyMissing(PreferenceGroup preferenceGroup,
249             String preference, String property ) {
250         if (SystemProperties.get(property).equals("")) {
251             // Property is missing so remove preference from group
252             try {
253                 preferenceGroup.removePreference(findPreference(preference));
254             } catch (RuntimeException e) {
255                 Log.d(LOG_TAG, "Property '" + property + "' missing and no '"
256                         + preference + "' preference");
257             }
258         }
259     }
260 
removePreferenceIfBoolFalse(String preference, int resId)261     private void removePreferenceIfBoolFalse(String preference, int resId) {
262         if (!getResources().getBoolean(resId)) {
263             Preference pref = findPreference(preference);
264             if (pref != null) {
265                 getPreferenceScreen().removePreference(pref);
266             }
267         }
268     }
269 
setStringSummary(String preference, String value)270     private void setStringSummary(String preference, String value) {
271         try {
272             findPreference(preference).setSummary(value);
273         } catch (RuntimeException e) {
274             findPreference(preference).setSummary(
275                 getResources().getString(R.string.device_info_default));
276         }
277     }
278 
setValueSummary(String preference, String property)279     private void setValueSummary(String preference, String property) {
280         try {
281             findPreference(preference).setSummary(
282                     SystemProperties.get(property,
283                             getResources().getString(R.string.device_info_default)));
284         } catch (RuntimeException e) {
285             // No recovery
286         }
287     }
288 
sendFeedback()289     private void sendFeedback() {
290         String reporterPackage = getFeedbackReporterPackage(getActivity());
291         if (TextUtils.isEmpty(reporterPackage)) {
292             return;
293         }
294         Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
295         intent.setPackage(reporterPackage);
296         startActivityForResult(intent, 0);
297     }
298 
299     /**
300      * Reads a line from the specified file.
301      * @param filename the file to read from
302      * @return the first line, if any.
303      * @throws IOException if the file couldn't be read
304      */
readLine(String filename)305     private static String readLine(String filename) throws IOException {
306         BufferedReader reader = new BufferedReader(new FileReader(filename), 256);
307         try {
308             return reader.readLine();
309         } finally {
310             reader.close();
311         }
312     }
313 
getFormattedKernelVersion()314     public static String getFormattedKernelVersion() {
315         try {
316             return formatKernelVersion(readLine(FILENAME_PROC_VERSION));
317 
318         } catch (IOException e) {
319             Log.e(LOG_TAG,
320                 "IO Exception when getting kernel version for Device Info screen",
321                 e);
322 
323             return "Unavailable";
324         }
325     }
326 
formatKernelVersion(String rawKernelVersion)327     public static String formatKernelVersion(String rawKernelVersion) {
328         // Example (see tests for more):
329         // Linux version 3.0.31-g6fb96c9 (android-build@xxx.xxx.xxx.xxx.com) \
330         //     (gcc version 4.6.x-xxx 20120106 (prerelease) (GCC) ) #1 SMP PREEMPT \
331         //     Thu Jun 28 11:02:39 PDT 2012
332 
333         final String PROC_VERSION_REGEX =
334             "Linux version (\\S+) " + /* group 1: "3.0.31-g6fb96c9" */
335             "\\((\\S+?)\\) " +        /* group 2: "x@y.com" (kernel builder) */
336             "(?:\\(gcc.+? \\)) " +    /* ignore: GCC version information */
337             "(#\\d+) " +              /* group 3: "#1" */
338             "(?:.*?)?" +              /* ignore: optional SMP, PREEMPT, and any CONFIG_FLAGS */
339             "((Sun|Mon|Tue|Wed|Thu|Fri|Sat).+)"; /* group 4: "Thu Jun 28 11:02:39 PDT 2012" */
340 
341         Matcher m = Pattern.compile(PROC_VERSION_REGEX).matcher(rawKernelVersion);
342         if (!m.matches()) {
343             Log.e(LOG_TAG, "Regex did not match on /proc/version: " + rawKernelVersion);
344             return "Unavailable";
345         } else if (m.groupCount() < 4) {
346             Log.e(LOG_TAG, "Regex match on /proc/version only returned " + m.groupCount()
347                     + " groups");
348             return "Unavailable";
349         }
350         return m.group(1) + "\n" +                 // 3.0.31-g6fb96c9
351             m.group(2) + " " + m.group(3) + "\n" + // x@y.com #1
352             m.group(4);                            // Thu Jun 28 11:02:39 PDT 2012
353     }
354 
355     /**
356      * Returns " (ENGINEERING)" if the msv file has a zero value, else returns "".
357      * @return a string to append to the model number description.
358      */
getMsvSuffix()359     private String getMsvSuffix() {
360         // Production devices should have a non-zero value. If we can't read it, assume it's a
361         // production device so that we don't accidentally show that it's an ENGINEERING device.
362         try {
363             String msv = readLine(FILENAME_MSV);
364             // Parse as a hex number. If it evaluates to a zero, then it's an engineering build.
365             if (Long.parseLong(msv, 16) == 0) {
366                 return " (ENGINEERING)";
367             }
368         } catch (IOException ioe) {
369             // Fail quietly, as the file may not exist on some devices.
370         } catch (NumberFormatException nfe) {
371             // Fail quietly, returning empty string should be sufficient
372         }
373         return "";
374     }
375 
getFeedbackReporterPackage(Context context)376     private static String getFeedbackReporterPackage(Context context) {
377         final String feedbackReporter =
378                 context.getResources().getString(R.string.oem_preferred_feedback_reporter);
379         if (TextUtils.isEmpty(feedbackReporter)) {
380             // Reporter not configured. Return.
381             return feedbackReporter;
382         }
383         // Additional checks to ensure the reporter is on system image, and reporter is
384         // configured to listen to the intent. Otherwise, dont show the "send feedback" option.
385         final Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
386 
387         PackageManager pm = context.getPackageManager();
388         List<ResolveInfo> resolvedPackages =
389                 pm.queryIntentActivities(intent, PackageManager.GET_RESOLVED_FILTER);
390         for (ResolveInfo info : resolvedPackages) {
391             if (info.activityInfo != null) {
392                 if (!TextUtils.isEmpty(info.activityInfo.packageName)) {
393                     try {
394                         ApplicationInfo ai = pm.getApplicationInfo(info.activityInfo.packageName, 0);
395                         if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
396                             // Package is on the system image
397                             if (TextUtils.equals(
398                                         info.activityInfo.packageName, feedbackReporter)) {
399                                 return feedbackReporter;
400                             }
401                         }
402                     } catch (PackageManager.NameNotFoundException e) {
403                          // No need to do anything here.
404                     }
405                 }
406             }
407         }
408         return null;
409     }
410 
411     /**
412      * For Search.
413      */
414     public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
415         new BaseSearchIndexProvider() {
416 
417             @Override
418             public List<SearchIndexableResource> getXmlResourcesToIndex(
419                     Context context, boolean enabled) {
420                 final SearchIndexableResource sir = new SearchIndexableResource(context);
421                 sir.xmlResId = R.xml.device_info_settings;
422                 return Arrays.asList(sir);
423             }
424 
425             @Override
426             public List<String> getNonIndexableKeys(Context context) {
427                 final List<String> keys = new ArrayList<String>();
428                 if (isPropertyMissing(PROPERTY_SELINUX_STATUS)) {
429                     keys.add(KEY_SELINUX_STATUS);
430                 }
431                 if (isPropertyMissing(PROPERTY_URL_SAFETYLEGAL)) {
432                     keys.add(KEY_SAFETY_LEGAL);
433                 }
434                 if (isPropertyMissing(PROPERTY_EQUIPMENT_ID)) {
435                     keys.add(KEY_EQUIPMENT_ID);
436                 }
437                 // Remove Baseband version if wifi-only device
438                 if (Utils.isWifiOnly(context)) {
439                     keys.add((KEY_BASEBAND_VERSION));
440                 }
441                 // Dont show feedback option if there is no reporter.
442                 if (TextUtils.isEmpty(getFeedbackReporterPackage(context))) {
443                     keys.add(KEY_DEVICE_FEEDBACK);
444                 }
445                 if (!checkIntentAction(context, "android.settings.TERMS")) {
446                     keys.add(KEY_TERMS);
447                 }
448                 if (!checkIntentAction(context, "android.settings.LICENSE")) {
449                     keys.add(KEY_LICENSE);
450                 }
451                 if (!checkIntentAction(context, "android.settings.COPYRIGHT")) {
452                     keys.add(KEY_COPYRIGHT);
453                 }
454                 if (!checkIntentAction(context, "android.settings.WEBVIEW_LICENSE")) {
455                     keys.add(KEY_WEBVIEW_LICENSE);
456                 }
457                 if (UserHandle.myUserId() != UserHandle.USER_OWNER) {
458                     keys.add(KEY_SYSTEM_UPDATE_SETTINGS);
459                 }
460                 if (!context.getResources().getBoolean(
461                         R.bool.config_additional_system_update_setting_enable)) {
462                     keys.add(KEY_UPDATE_SETTING);
463                 }
464                 return keys;
465             }
466 
467             private boolean isPropertyMissing(String property) {
468                 return SystemProperties.get(property).equals("");
469             }
470 
471             private boolean checkIntentAction(Context context, String action) {
472                 final Intent intent = new Intent(action);
473 
474                 // Find the activity that is in the system image
475                 final PackageManager pm = context.getPackageManager();
476                 final List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
477                 final int listSize = list.size();
478 
479                 for (int i = 0; i < listSize; i++) {
480                     ResolveInfo resolveInfo = list.get(i);
481                     if ((resolveInfo.activityInfo.applicationInfo.flags &
482                             ApplicationInfo.FLAG_SYSTEM) != 0) {
483                         return true;
484                     }
485                 }
486 
487                 return false;
488             }
489         };
490 
491 }
492 
493