blob: 37a0618646df456b875e0cc1b2e952413ee7794d [file] [log] [blame]
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001/*
Jonathan Basseri6465afd2015-02-25 13:05:57 -08002 * Copyright (c) 2015, 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
Jonathan Basseri6465afd2015-02-25 13:05:57 -080017package com.android.phone;
18
Jonathan Basseri65273c82017-07-25 15:08:42 -070019import static android.service.carrier.CarrierService.ICarrierServiceWrapper.KEY_CONFIG_BUNDLE;
20import static android.service.carrier.CarrierService.ICarrierServiceWrapper.RESULT_ERROR;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080021
Jonathan Basseri11f89572015-05-05 11:57:39 -070022import android.annotation.NonNull;
Torbjorn Eklund723527a2019-02-13 11:16:25 +010023import android.annotation.Nullable;
Hunter Knepshielde601f432020-02-19 10:16:04 -080024import android.app.AppOpsManager;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080025import android.content.BroadcastReceiver;
26import android.content.ComponentName;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.ServiceConnection;
Jonathan Basseri7697cae2015-07-06 15:49:23 -070031import android.content.SharedPreferences;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070032import android.content.pm.PackageInfo;
Jonathan Basseric31f1f32015-05-12 10:13:03 -070033import android.content.pm.PackageManager;
Junda Liu43d723a2015-05-12 17:23:45 -070034import android.os.Binder;
Jonathan Basseri7697cae2015-07-06 15:49:23 -070035import android.os.Build;
Jonathan Basseri65273c82017-07-25 15:08:42 -070036import android.os.Bundle;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080037import android.os.Handler;
38import android.os.IBinder;
39import android.os.Message;
Jonathan Basseric31f1f32015-05-12 10:13:03 -070040import android.os.PersistableBundle;
Hunter Knepshielde601f432020-02-19 10:16:04 -080041import android.os.Process;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080042import android.os.RemoteException;
Jonathan Basseri65273c82017-07-25 15:08:42 -070043import android.os.ResultReceiver;
Meng Wang97a6a462020-01-23 16:22:16 -080044import android.os.UserHandle;
Jonathan Basseri7697cae2015-07-06 15:49:23 -070045import android.preference.PreferenceManager;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080046import android.service.carrier.CarrierIdentifier;
Zach Johnson36d7aab2015-05-22 15:43:00 -070047import android.service.carrier.CarrierService;
48import android.service.carrier.ICarrierService;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080049import android.telephony.CarrierConfigManager;
50import android.telephony.SubscriptionManager;
Peter Wangc035ce42020-01-08 21:00:22 -080051import android.telephony.TelephonyFrameworkInitializer;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080052import android.telephony.TelephonyManager;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -080053import android.text.TextUtils;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -080054import android.util.ArraySet;
chen xudb04c292019-03-26 17:01:15 -070055import android.util.LocalLog;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080056import android.util.Log;
57
58import com.android.internal.telephony.ICarrierConfigLoader;
59import com.android.internal.telephony.IccCardConstants;
60import com.android.internal.telephony.Phone;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080061import com.android.internal.telephony.PhoneFactory;
Nathan Harold48ac0972019-03-13 22:33:01 -070062import com.android.internal.telephony.SubscriptionInfoUpdater;
Jeff Davidsona8e4e242018-03-15 17:16:18 -070063import com.android.internal.telephony.TelephonyPermissions;
Meng Wanga320b942019-11-25 11:21:26 -080064import com.android.internal.telephony.util.ArrayUtils;
shuoq26a3a4c2016-12-16 11:06:48 -080065import com.android.internal.util.IndentingPrintWriter;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080066
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070067import java.io.File;
Junda Liu43d723a2015-05-12 17:23:45 -070068import java.io.FileDescriptor;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070069import java.io.FileInputStream;
70import java.io.FileNotFoundException;
71import java.io.FileOutputStream;
Jonathan Basseri1f743c92015-05-15 00:19:46 -070072import java.io.FilenameFilter;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070073import java.io.IOException;
Junda Liu43d723a2015-05-12 17:23:45 -070074import java.io.PrintWriter;
shuoq26a3a4c2016-12-16 11:06:48 -080075import java.util.ArrayList;
76import java.util.Arrays;
77import java.util.Collections;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080078import java.util.List;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -080079import java.util.Set;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080080
81/**
82 * CarrierConfigLoader binds to privileged carrier apps to fetch carrier config overlays.
Jonathan Basseri6465afd2015-02-25 13:05:57 -080083 */
Jonathan Basseri6465afd2015-02-25 13:05:57 -080084public class CarrierConfigLoader extends ICarrierConfigLoader.Stub {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070085 private static final String LOG_TAG = "CarrierConfigLoader";
Meng Wang33ad2bc2017-03-16 20:21:20 -070086
87 // Package name for platform carrier config app, bundled with system image.
88 private final String mPlatformCarrierConfigPackage;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080089
90 /** The singleton instance. */
91 private static CarrierConfigLoader sInstance;
92 // The context for phone app, passed from PhoneGlobals.
93 private Context mContext;
94 // Carrier configs from default app, indexed by phoneID.
Jonathan Basseric31f1f32015-05-12 10:13:03 -070095 private PersistableBundle[] mConfigFromDefaultApp;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080096 // Carrier configs from privileged carrier config app, indexed by phoneID.
Jonathan Basseric31f1f32015-05-12 10:13:03 -070097 private PersistableBundle[] mConfigFromCarrierApp;
Torbjorn Eklund723527a2019-02-13 11:16:25 +010098 // Persistent Carrier configs that are provided via the override test API, indexed by phone ID.
99 private PersistableBundle[] mPersistentOverrideConfigs;
Hall Liu506724b2018-10-22 18:16:14 -0700100 // Carrier configs that are provided via the override test API, indexed by phone ID.
101 private PersistableBundle[] mOverrideConfigs;
Jayachandran C645ec612020-01-10 10:30:25 -0800102 // Carrier configs to override code default when there is no SIM inserted
103 private PersistableBundle mNoSimConfig;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800104 // Service connection for binding to config app.
Zach Johnson36d7aab2015-05-22 15:43:00 -0700105 private CarrierServiceConnection[] mServiceConnection;
Jayachandran C645ec612020-01-10 10:30:25 -0800106 // Service connection for binding to carrier config app for no SIM config.
107 private CarrierServiceConnection[] mServiceConnectionForNoSimConfig;
Jordan Liu178430d2020-02-10 14:32:15 -0800108 // Whether we are bound to a service for each phone
109 private boolean[] mServiceBound;
Jayachandran C645ec612020-01-10 10:30:25 -0800110 // Whether we are bound to a service for no SIM config
111 private boolean[] mServiceBoundForNoSimConfig;
Sarah Chin807d5c62020-03-30 17:21:09 -0700112 // Whether we have sent config change broadcast for each phone id.
Junda Liu03aad762017-07-21 13:32:17 -0700113 private boolean[] mHasSentConfigChange;
Sarah Chin807d5c62020-03-30 17:21:09 -0700114 // Whether the broadcast was sent from EVENT_SYSTEM_UNLOCKED, to track rebroadcasts
115 private boolean[] mFromSystemUnlocked;
Nathan Harold48ac0972019-03-13 22:33:01 -0700116 // SubscriptionInfoUpdater
117 private final SubscriptionInfoUpdater mSubscriptionInfoUpdater;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800118
Nanxi Chen3d670502016-03-17 16:32:09 -0700119 // Broadcast receiver for Boot intents, register intent filter in construtor.
120 private final BroadcastReceiver mBootReceiver = new ConfigLoaderBroadcastReceiver();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800121 // Broadcast receiver for SIM and pkg intents, register intent filter in constructor.
Nanxi Chen3d670502016-03-17 16:32:09 -0700122 private final BroadcastReceiver mPackageReceiver = new ConfigLoaderBroadcastReceiver();
Jack Yu67663de2019-10-17 15:19:48 -0700123 private final LocalLog mCarrierConfigLoadingLog = new LocalLog(100);
chen xudb04c292019-03-26 17:01:15 -0700124
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800125
126 // Message codes; see mHandler below.
127 // Request from SubscriptionInfoUpdater when SIM becomes absent or error.
128 private static final int EVENT_CLEAR_CONFIG = 0;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800129 // Has connected to default app.
130 private static final int EVENT_CONNECTED_TO_DEFAULT = 3;
131 // Has connected to carrier app.
132 private static final int EVENT_CONNECTED_TO_CARRIER = 4;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700133 // Config has been loaded from default app (or cache).
134 private static final int EVENT_FETCH_DEFAULT_DONE = 5;
135 // Config has been loaded from carrier app (or cache).
136 private static final int EVENT_FETCH_CARRIER_DONE = 6;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700137 // Attempt to fetch from default app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700138 private static final int EVENT_DO_FETCH_DEFAULT = 7;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700139 // Attempt to fetch from carrier app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700140 private static final int EVENT_DO_FETCH_CARRIER = 8;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700141 // A package has been installed, uninstalled, or updated.
142 private static final int EVENT_PACKAGE_CHANGED = 9;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700143 // Bind timed out for the default app.
144 private static final int EVENT_BIND_DEFAULT_TIMEOUT = 10;
145 // Bind timed out for a carrier app.
146 private static final int EVENT_BIND_CARRIER_TIMEOUT = 11;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700147 // Check if the system fingerprint has changed.
148 private static final int EVENT_CHECK_SYSTEM_UPDATE = 12;
Nanxi Chen3d670502016-03-17 16:32:09 -0700149 // Rerun carrier config binding after system is unlocked.
150 private static final int EVENT_SYSTEM_UNLOCKED = 13;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700151 // Fetching config timed out from the default app.
152 private static final int EVENT_FETCH_DEFAULT_TIMEOUT = 14;
153 // Fetching config timed out from a carrier app.
154 private static final int EVENT_FETCH_CARRIER_TIMEOUT = 15;
Nathan Harold48ac0972019-03-13 22:33:01 -0700155 // SubscriptionInfoUpdater has finished updating the sub for the carrier config.
156 private static final int EVENT_SUBSCRIPTION_INFO_UPDATED = 16;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700157 // Multi-SIM config changed.
158 private static final int EVENT_MULTI_SIM_CONFIG_CHANGED = 17;
Jayachandran C645ec612020-01-10 10:30:25 -0800159 // Attempt to fetch from default app or read from XML for no SIM case.
160 private static final int EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG = 18;
161 // No SIM config has been loaded from default app (or cache).
162 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE = 19;
163 // Has connected to default app for no SIM config.
164 private static final int EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG = 20;
165 // Bind timed out for the default app when trying to fetch no SIM config.
166 private static final int EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 21;
167 // Fetching config timed out from the default app for no SIM config.
168 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 22;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700169
Junda Liu6cb45002016-03-22 17:18:20 -0700170 private static final int BIND_TIMEOUT_MILLIS = 30000;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800171
Meng Wang0f6b2ea2020-01-06 18:31:16 -0800172 // Keys used for saving and restoring config bundle from file.
173 private static final String KEY_VERSION = "__carrier_config_package_version__";
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800174
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100175 private static final String OVERRIDE_PACKAGE_ADDITION = "-override";
176
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700177 // SharedPreferences key for last known build fingerprint.
178 private static final String KEY_FINGERPRINT = "build_fingerprint";
179
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -0800180 // Argument for #dump that indicates we should also call the default and specified carrier
181 // service's #dump method. In multi-SIM devices, it's possible that carrier A is on SIM 1 and
182 // carrier B is on SIM 2, in which case we should not dump carrier B's service when carrier A
183 // requested the dump.
184 private static final String DUMP_ARG_REQUESTING_PACKAGE = "--requesting-package";
185
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800186 // Handler to process various events.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700187 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700188 // For each phoneId, the event sequence should be:
Jonathan Basseri65273c82017-07-25 15:08:42 -0700189 // fetch default, connected to default, fetch default (async), fetch default done,
190 // fetch carrier, connected to carrier, fetch carrier (async), fetch carrier done.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700191 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700192 // If there is a saved config file for either the default app or the carrier app, we skip
193 // binding to the app and go straight from fetch to loaded.
194 //
195 // At any time, at most one connection is active. If events are not in this order, previous
196 // connection will be unbound, so only latest event takes effect.
197 //
198 // We broadcast ACTION_CARRIER_CONFIG_CHANGED after:
199 // 1. loading from carrier app (even if read from a file)
200 // 2. loading from default app if there is no carrier app (even if read from a file)
201 // 3. clearing config (e.g. due to sim removal)
202 // 4. encountering bind or IPC error
Jonathan Basseri65273c82017-07-25 15:08:42 -0700203 private class ConfigHandler extends Handler {
204 @Override
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800205 public void handleMessage(Message msg) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700206 final int phoneId = msg.arg1;
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800207 logdWithLocalLog("mHandler: " + msg.what + " phoneId: " + phoneId);
Malcolm Chen5ea18532019-10-24 19:55:44 -0700208 if (!SubscriptionManager.isValidPhoneId(phoneId)
209 && msg.what != EVENT_MULTI_SIM_CONFIG_CHANGED) {
210 return;
211 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800212 switch (msg.what) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800213 case EVENT_CLEAR_CONFIG: {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700214 clearConfigForPhone(phoneId, true);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800215 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700216 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700217
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800218 case EVENT_SYSTEM_UNLOCKED: {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700219 for (int i = 0; i < TelephonyManager.from(mContext).getActiveModemCount();
220 ++i) {
Sarah Chin807d5c62020-03-30 17:21:09 -0700221 // When the user unlocks the device, send the broadcast again (with a
222 // rebroadcast extra) if we have sent it before unlock. This will avoid
223 // trying to load the carrier config when the SIM is still loading when the
224 // unlock happens.
Junda Liu03aad762017-07-21 13:32:17 -0700225 if (mHasSentConfigChange[i]) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800226 logdWithLocalLog("System unlocked");
Sarah Chin807d5c62020-03-30 17:21:09 -0700227 mFromSystemUnlocked[i] = true;
Junda Liu03aad762017-07-21 13:32:17 -0700228 updateConfigForPhoneId(i);
229 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700230 }
231 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700232 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700233
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800234 case EVENT_PACKAGE_CHANGED: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700235 final String carrierPackageName = (String) msg.obj;
236 // Only update if there are cached config removed to avoid updating config for
237 // unrelated packages.
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700238 if (clearCachedConfigForPackage(carrierPackageName)) {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700239 int numPhones = TelephonyManager.from(mContext).getActiveModemCount();
Junda Liu8a8a53a2015-05-15 16:19:57 -0700240 for (int i = 0; i < numPhones; ++i) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800241 logdWithLocalLog("Package changed: " + carrierPackageName
Jack Yu67663de2019-10-17 15:19:48 -0700242 + ", phone=" + i);
Junda Liu8a8a53a2015-05-15 16:19:57 -0700243 updateConfigForPhoneId(i);
244 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700245 }
246 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700247 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700248
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800249 case EVENT_DO_FETCH_DEFAULT: {
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100250 // Restore persistent override values.
251 PersistableBundle config = restoreConfigFromXml(
252 mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION, phoneId);
253 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800254 logd("Loaded persistent override config from XML. package="
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100255 + mPlatformCarrierConfigPackage
256 + " phoneId=" + phoneId);
257 mPersistentOverrideConfigs[phoneId] = config;
258 }
259
260 config = restoreConfigFromXml(mPlatformCarrierConfigPackage, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700261 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800262 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700263 "Loaded config from XML. package="
264 + mPlatformCarrierConfigPackage
265 + " phoneId="
266 + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700267 mConfigFromDefaultApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700268 Message newMsg = obtainMessage(EVENT_FETCH_DEFAULT_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700269 newMsg.getData().putBoolean("loaded_from_xml", true);
270 mHandler.sendMessage(newMsg);
271 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700272 // No cached config, so fetch it from the default app.
273 if (bindToConfigPackage(
274 mPlatformCarrierConfigPackage,
275 phoneId,
276 EVENT_CONNECTED_TO_DEFAULT)) {
277 sendMessageDelayed(
278 obtainMessage(EVENT_BIND_DEFAULT_TIMEOUT, phoneId, -1),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700279 BIND_TIMEOUT_MILLIS);
280 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700281 // Send broadcast if bind fails.
Nathan Harold48ac0972019-03-13 22:33:01 -0700282 notifySubscriptionInfoUpdater(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700283 // TODO: We *must* call unbindService even if bindService returns false.
284 // (And possibly if SecurityException was thrown.)
chen xudb04c292019-03-26 17:01:15 -0700285 loge("binding to default app: "
286 + mPlatformCarrierConfigPackage + " fails");
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700287 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800288 }
289 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700290 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800291
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800292 case EVENT_CONNECTED_TO_DEFAULT: {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700293 removeMessages(EVENT_BIND_DEFAULT_TIMEOUT);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700294 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800295 // If new service connection has been created, unbind.
296 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Jordan Liu178430d2020-02-10 14:32:15 -0800297 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800298 break;
299 }
chen xu02581692018-11-11 19:03:44 -0800300 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700301 // ResultReceiver callback will execute in this Handler's thread.
302 final ResultReceiver resultReceiver =
303 new ResultReceiver(this) {
304 @Override
305 public void onReceiveResult(int resultCode, Bundle resultData) {
Jordan Liu178430d2020-02-10 14:32:15 -0800306 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700307 // If new service connection has been created, this is stale.
308 if (mServiceConnection[phoneId] != conn) {
309 loge("Received response for stale request.");
310 return;
311 }
312 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT);
313 if (resultCode == RESULT_ERROR || resultData == null) {
314 // On error, abort config fetching.
315 loge("Failed to get carrier config");
Nathan Harold48ac0972019-03-13 22:33:01 -0700316 notifySubscriptionInfoUpdater(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700317 return;
318 }
319 PersistableBundle config =
320 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100321 saveConfigToXml(mPlatformCarrierConfigPackage, "", phoneId,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800322 carrierId, config);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700323 mConfigFromDefaultApp[phoneId] = config;
324 sendMessage(
325 obtainMessage(
326 EVENT_FETCH_DEFAULT_DONE, phoneId, -1));
327 }
328 };
329 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800330 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700331 ICarrierService carrierService =
332 ICarrierService.Stub.asInterface(conn.service);
333 carrierService.getCarrierConfig(carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800334 logdWithLocalLog("Fetch config for default app: "
chen xudb04c292019-03-26 17:01:15 -0700335 + mPlatformCarrierConfigPackage
336 + " carrierid: " + carrierId.toString());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700337 } catch (RemoteException e) {
chen xudb04c292019-03-26 17:01:15 -0700338 loge("Failed to get carrier config from default app: " +
339 mPlatformCarrierConfigPackage + " err: " + e.toString());
Jordan Liu178430d2020-02-10 14:32:15 -0800340 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700341 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800342 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700343 sendMessageDelayed(
344 obtainMessage(EVENT_FETCH_DEFAULT_TIMEOUT, phoneId, -1),
345 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800346 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700347 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800348
Jonathan Basseri930701e2015-06-11 20:56:43 -0700349 case EVENT_BIND_DEFAULT_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800350 case EVENT_FETCH_DEFAULT_TIMEOUT: {
351 loge("Bind/fetch time out from " + mPlatformCarrierConfigPackage);
chen xuf60b3162019-05-01 21:31:05 -0700352 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT);
353 // If we attempted to bind to the app, but the service connection is null due to
354 // the race condition that clear config event happens before bind/fetch complete
355 // then config was cleared while we were waiting and we should not continue.
356 if (mServiceConnection[phoneId] != null) {
357 // If a ResponseReceiver callback is in the queue when this happens, we will
358 // unbind twice and throw an exception.
Jordan Liu178430d2020-02-10 14:32:15 -0800359 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700360 broadcastConfigChangedIntent(phoneId);
361 }
Nathan Harold48ac0972019-03-13 22:33:01 -0700362 notifySubscriptionInfoUpdater(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700363 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700364 }
Jonathan Basseri930701e2015-06-11 20:56:43 -0700365
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800366 case EVENT_FETCH_DEFAULT_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700367 // If we attempted to bind to the app, but the service connection is null, then
368 // config was cleared while we were waiting and we should not continue.
369 if (!msg.getData().getBoolean("loaded_from_xml", false)
370 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800371 break;
372 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700373 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700374 if (carrierPackageName != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800375 logd("Found carrier config app: " + carrierPackageName);
Jordan Liu38a614c2019-03-20 15:01:17 -0700376 sendMessage(obtainMessage(EVENT_DO_FETCH_CARRIER, phoneId, -1));
Jonathan Basserib919e932015-05-27 16:53:08 +0000377 } else {
Nathan Harold48ac0972019-03-13 22:33:01 -0700378 notifySubscriptionInfoUpdater(phoneId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700379 }
380 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700381 }
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700382
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800383 case EVENT_DO_FETCH_CARRIER: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700384 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700385 final PersistableBundle config =
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100386 restoreConfigFromXml(carrierPackageName, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700387 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800388 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700389 "Loaded config from XML. package="
390 + carrierPackageName
391 + " phoneId="
392 + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700393 mConfigFromCarrierApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700394 Message newMsg = obtainMessage(EVENT_FETCH_CARRIER_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700395 newMsg.getData().putBoolean("loaded_from_xml", true);
396 sendMessage(newMsg);
397 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700398 // No cached config, so fetch it from a carrier app.
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800399 if (carrierPackageName != null && bindToConfigPackage(carrierPackageName,
400 phoneId, EVENT_CONNECTED_TO_CARRIER)) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700401 sendMessageDelayed(
402 obtainMessage(EVENT_BIND_CARRIER_TIMEOUT, phoneId, -1),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700403 BIND_TIMEOUT_MILLIS);
404 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700405 // Send broadcast if bind fails.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700406 broadcastConfigChangedIntent(phoneId);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800407 loge("Bind to carrier app: " + carrierPackageName + " fails");
Nathan Harold48ac0972019-03-13 22:33:01 -0700408 notifySubscriptionInfoUpdater(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700409 }
410 }
411 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700412 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700413
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800414 case EVENT_CONNECTED_TO_CARRIER: {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700415 removeMessages(EVENT_BIND_CARRIER_TIMEOUT);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700416 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800417 // If new service connection has been created, unbind.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700418 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Jordan Liu178430d2020-02-10 14:32:15 -0800419 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800420 break;
421 }
chen xu02581692018-11-11 19:03:44 -0800422 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700423 // ResultReceiver callback will execute in this Handler's thread.
424 final ResultReceiver resultReceiver =
425 new ResultReceiver(this) {
426 @Override
427 public void onReceiveResult(int resultCode, Bundle resultData) {
Jordan Liu178430d2020-02-10 14:32:15 -0800428 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700429 // If new service connection has been created, this is stale.
430 if (mServiceConnection[phoneId] != conn) {
431 loge("Received response for stale request.");
432 return;
433 }
434 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT);
435 if (resultCode == RESULT_ERROR || resultData == null) {
436 // On error, abort config fetching.
chen xudb04c292019-03-26 17:01:15 -0700437 loge("Failed to get carrier config from carrier app: "
438 + getCarrierPackageForPhoneId(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700439 broadcastConfigChangedIntent(phoneId);
Nathan Harold48ac0972019-03-13 22:33:01 -0700440 notifySubscriptionInfoUpdater(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700441 return;
442 }
443 PersistableBundle config =
444 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100445 saveConfigToXml(getCarrierPackageForPhoneId(phoneId), "",
446 phoneId, carrierId, config);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700447 mConfigFromCarrierApp[phoneId] = config;
448 sendMessage(
449 obtainMessage(
450 EVENT_FETCH_CARRIER_DONE, phoneId, -1));
451 }
452 };
453 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800454 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700455 ICarrierService carrierService =
456 ICarrierService.Stub.asInterface(conn.service);
457 carrierService.getCarrierConfig(carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800458 logdWithLocalLog("Fetch config for carrier app: "
chen xudb04c292019-03-26 17:01:15 -0700459 + getCarrierPackageForPhoneId(phoneId)
460 + " carrierid: " + carrierId.toString());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700461 } catch (RemoteException e) {
462 loge("Failed to get carrier config: " + e.toString());
Jordan Liu178430d2020-02-10 14:32:15 -0800463 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700464 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800465 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700466 sendMessageDelayed(
467 obtainMessage(EVENT_FETCH_CARRIER_TIMEOUT, phoneId, -1),
468 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800469 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700470 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800471
Jonathan Basseri930701e2015-06-11 20:56:43 -0700472 case EVENT_BIND_CARRIER_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800473 case EVENT_FETCH_CARRIER_TIMEOUT: {
474 loge("Bind/fetch from carrier app timeout");
chen xuf60b3162019-05-01 21:31:05 -0700475 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT);
476 // If we attempted to bind to the app, but the service connection is null due to
477 // the race condition that clear config event happens before bind/fetch complete
478 // then config was cleared while we were waiting and we should not continue.
479 if (mServiceConnection[phoneId] != null) {
480 // If a ResponseReceiver callback is in the queue when this happens, we will
481 // unbind twice and throw an exception.
Jordan Liu178430d2020-02-10 14:32:15 -0800482 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700483 broadcastConfigChangedIntent(phoneId);
484 }
Nathan Harold48ac0972019-03-13 22:33:01 -0700485 notifySubscriptionInfoUpdater(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700486 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700487 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800488 case EVENT_FETCH_CARRIER_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700489 // If we attempted to bind to the app, but the service connection is null, then
490 // config was cleared while we were waiting and we should not continue.
491 if (!msg.getData().getBoolean("loaded_from_xml", false)
492 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800493 break;
494 }
Nathan Harold48ac0972019-03-13 22:33:01 -0700495 notifySubscriptionInfoUpdater(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800496 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700497 }
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700498
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800499 case EVENT_CHECK_SYSTEM_UPDATE: {
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700500 SharedPreferences sharedPrefs =
501 PreferenceManager.getDefaultSharedPreferences(mContext);
502 final String lastFingerprint = sharedPrefs.getString(KEY_FINGERPRINT, null);
503 if (!Build.FINGERPRINT.equals(lastFingerprint)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800504 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700505 "Build fingerprint changed. old: "
506 + lastFingerprint
507 + " new: "
508 + Build.FINGERPRINT);
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700509 clearCachedConfigForPackage(null);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700510 sharedPrefs
511 .edit()
512 .putString(KEY_FINGERPRINT, Build.FINGERPRINT)
513 .apply();
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700514 }
515 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700516 }
Nathan Harold48ac0972019-03-13 22:33:01 -0700517
518 case EVENT_SUBSCRIPTION_INFO_UPDATED:
519 broadcastConfigChangedIntent(phoneId);
520 break;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700521 case EVENT_MULTI_SIM_CONFIG_CHANGED:
522 onMultiSimConfigChanged();
523 break;
Jayachandran C645ec612020-01-10 10:30:25 -0800524
525 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG: {
526 PersistableBundle config =
527 restoreNoSimConfigFromXml(mPlatformCarrierConfigPackage);
528
529 if (config != null) {
530 logd("Loaded no SIM config from XML. package="
531 + mPlatformCarrierConfigPackage);
532 mNoSimConfig = config;
533 sendMessage(
534 obtainMessage(
535 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
536 phoneId, -1));
537 } else {
538 // No cached config, so fetch it from the default app.
539 if (bindToConfigPackage(
540 mPlatformCarrierConfigPackage,
541 phoneId,
542 EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG)) {
543 sendMessageDelayed(
544 obtainMessage(
545 EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
546 phoneId, -1), BIND_TIMEOUT_MILLIS);
547 } else {
548 broadcastConfigChangedIntent(phoneId, false);
549 // TODO: We *must* call unbindService even if bindService returns false.
550 // (And possibly if SecurityException was thrown.)
551 loge("binding to default app to fetch no SIM config: "
552 + mPlatformCarrierConfigPackage + " fails");
553 }
554 }
555 break;
556 }
557
558 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE: {
559 broadcastConfigChangedIntent(phoneId, false);
560 break;
561 }
562
563 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
564 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT: {
565 loge("Bind/fetch time out for no SIM config from "
566 + mPlatformCarrierConfigPackage);
567 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
568 // If we attempted to bind to the app, but the service connection is null due to
569 // the race condition that clear config event happens before bind/fetch complete
570 // then config was cleared while we were waiting and we should not continue.
571 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
572 // If a ResponseReceiver callback is in the queue when this happens, we will
573 // unbind twice and throw an exception.
574 unbindIfBoundForNoSimConfig(mContext,
575 mServiceConnectionForNoSimConfig[phoneId], phoneId);
576 }
577 broadcastConfigChangedIntent(phoneId, false);
578 break;
579 }
580
581 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG: {
582 removeMessages(EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
583 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
584 // If new service connection has been created, unbind.
585 if (mServiceConnectionForNoSimConfig[phoneId] != conn || conn.service == null) {
586 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
587 break;
588 }
589
590 // ResultReceiver callback will execute in this Handler's thread.
591 final ResultReceiver resultReceiver =
592 new ResultReceiver(this) {
593 @Override
594 public void onReceiveResult(int resultCode, Bundle resultData) {
595 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
596 // If new service connection has been created, this is stale.
597 if (mServiceConnectionForNoSimConfig[phoneId] != conn) {
598 loge("Received response for stale request.");
599 return;
600 }
601 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
602 if (resultCode == RESULT_ERROR || resultData == null) {
603 // On error, abort config fetching.
604 loge("Failed to get no SIM carrier config");
605 return;
606 }
607 PersistableBundle config =
608 resultData.getParcelable(KEY_CONFIG_BUNDLE);
609 saveNoSimConfigToXml(mPlatformCarrierConfigPackage, config);
610 mNoSimConfig = config;
611 sendMessage(
612 obtainMessage(
613 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
614 phoneId, -1));
615 }
616 };
617 // Now fetch the config asynchronously from the ICarrierService.
618 try {
619 ICarrierService carrierService =
620 ICarrierService.Stub.asInterface(conn.service);
621 carrierService.getCarrierConfig(null, resultReceiver);
622 logdWithLocalLog("Fetch no sim config from default app: "
623 + mPlatformCarrierConfigPackage);
624 } catch (RemoteException e) {
625 loge("Failed to get no sim carrier config from default app: " +
626 mPlatformCarrierConfigPackage + " err: " + e.toString());
627 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
628 break; // So we don't set a timeout.
629 }
630 sendMessageDelayed(
631 obtainMessage(
632 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
633 phoneId, -1), BIND_TIMEOUT_MILLIS);
634 break;
635 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800636 }
637 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700638 }
639
640 private final Handler mHandler;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800641
642 /**
643 * Constructs a CarrierConfigLoader, registers it as a service, and registers a broadcast
644 * receiver for relevant events.
645 */
646 private CarrierConfigLoader(Context context) {
647 mContext = context;
Meng Wang33ad2bc2017-03-16 20:21:20 -0700648 mPlatformCarrierConfigPackage =
649 mContext.getString(R.string.platform_carrier_config_package);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700650 mHandler = new ConfigHandler();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800651
Nanxi Chen3d670502016-03-17 16:32:09 -0700652 IntentFilter bootFilter = new IntentFilter();
653 bootFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
654 context.registerReceiver(mBootReceiver, bootFilter);
655
Junda Liu8a8a53a2015-05-15 16:19:57 -0700656 // Register for package updates. Update app or uninstall app update will have all 3 intents,
657 // in the order or removed, added, replaced, all with extra_replace set to true.
658 IntentFilter pkgFilter = new IntentFilter();
659 pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
660 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
661 pkgFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
662 pkgFilter.addDataScheme("package");
Jordan Liu5ca24762019-07-10 12:51:09 -0700663 context.registerReceiver(mPackageReceiver, pkgFilter);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800664
Malcolm Chen978dda52019-10-08 18:15:25 -0700665 int numPhones = TelephonyManager.from(context).getSupportedModemCount();
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700666 mConfigFromDefaultApp = new PersistableBundle[numPhones];
667 mConfigFromCarrierApp = new PersistableBundle[numPhones];
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100668 mPersistentOverrideConfigs = new PersistableBundle[numPhones];
Hall Liu506724b2018-10-22 18:16:14 -0700669 mOverrideConfigs = new PersistableBundle[numPhones];
Jayachandran C645ec612020-01-10 10:30:25 -0800670 mNoSimConfig = new PersistableBundle();
Zach Johnson36d7aab2015-05-22 15:43:00 -0700671 mServiceConnection = new CarrierServiceConnection[numPhones];
Jordan Liu178430d2020-02-10 14:32:15 -0800672 mServiceBound = new boolean[numPhones];
Junda Liu03aad762017-07-21 13:32:17 -0700673 mHasSentConfigChange = new boolean[numPhones];
Sarah Chin807d5c62020-03-30 17:21:09 -0700674 mFromSystemUnlocked = new boolean[numPhones];
Jayachandran C645ec612020-01-10 10:30:25 -0800675 mServiceConnectionForNoSimConfig = new CarrierServiceConnection[numPhones];
676 mServiceBoundForNoSimConfig = new boolean[numPhones];
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800677 // Make this service available through ServiceManager.
Peter Wangc035ce42020-01-08 21:00:22 -0800678 TelephonyFrameworkInitializer
679 .getTelephonyServiceManager().getCarrierConfigServiceRegisterer().register(this);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800680 logd("CarrierConfigLoader has started");
Nathan Harold48ac0972019-03-13 22:33:01 -0700681 mSubscriptionInfoUpdater = PhoneFactory.getSubscriptionInfoUpdater();
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700682 mHandler.sendEmptyMessage(EVENT_CHECK_SYSTEM_UPDATE);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800683 }
684
685 /**
686 * Initialize the singleton CarrierConfigLoader instance.
687 *
688 * This is only done once, at startup, from {@link com.android.phone.PhoneApp#onCreate}.
689 */
690 /* package */
691 static CarrierConfigLoader init(Context context) {
692 synchronized (CarrierConfigLoader.class) {
693 if (sInstance == null) {
694 sInstance = new CarrierConfigLoader(context);
695 } else {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700696 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800697 }
698 return sInstance;
699 }
700 }
701
Jayachandran C645ec612020-01-10 10:30:25 -0800702 private void clearConfigForPhone(int phoneId, boolean fetchNoSimConfig) {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700703 /* Ignore clear configuration request if device is being shutdown. */
704 Phone phone = PhoneFactory.getPhone(phoneId);
705 if (phone != null) {
706 if (phone.isShuttingDown()) {
707 return;
708 }
709 }
710
711 mConfigFromDefaultApp[phoneId] = null;
712 mConfigFromCarrierApp[phoneId] = null;
713 mServiceConnection[phoneId] = null;
714 mHasSentConfigChange[phoneId] = false;
715
Jayachandran C645ec612020-01-10 10:30:25 -0800716 if (fetchNoSimConfig) {
717 // To fetch no SIM config
718 mHandler.sendMessage(
719 mHandler.obtainMessage(
720 EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG, phoneId, -1));
721 }
Malcolm Chen5ea18532019-10-24 19:55:44 -0700722 }
723
Nathan Harold48ac0972019-03-13 22:33:01 -0700724 private void notifySubscriptionInfoUpdater(int phoneId) {
725 String configPackagename;
726 PersistableBundle configToSend;
727 int carrierId = getSpecificCarrierIdForPhoneId(phoneId);
728 // Prefer the carrier privileged carrier app, but if there is not one, use the platform
729 // default carrier app.
730 if (mConfigFromCarrierApp[phoneId] != null) {
731 configPackagename = getCarrierPackageForPhoneId(phoneId);
732 configToSend = mConfigFromCarrierApp[phoneId];
733 } else {
734 configPackagename = mPlatformCarrierConfigPackage;
735 configToSend = mConfigFromDefaultApp[phoneId];
736 }
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700737
Malcolm Chenefafd1c2020-02-20 13:27:08 -0800738 if (configToSend == null) {
739 configToSend = new PersistableBundle();
740 }
741
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700742 // mOverrideConfigs is for testing. And it will override current configs.
743 PersistableBundle config = mOverrideConfigs[phoneId];
744 if (config != null) {
Torbjorn Eklund1050cb02018-11-16 14:05:38 +0100745 configToSend = new PersistableBundle(configToSend);
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700746 configToSend.putAll(config);
747 }
748
Nathan Harold48ac0972019-03-13 22:33:01 -0700749 mSubscriptionInfoUpdater.updateSubscriptionByCarrierConfigAndNotifyComplete(
750 phoneId, configPackagename, configToSend,
751 mHandler.obtainMessage(EVENT_SUBSCRIPTION_INFO_UPDATED, phoneId, -1));
752 }
753
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800754 private void broadcastConfigChangedIntent(int phoneId) {
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800755 broadcastConfigChangedIntent(phoneId, true);
756 }
757
758 private void broadcastConfigChangedIntent(int phoneId, boolean addSubIdExtra) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800759 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
Christopher Tate38f55eb2017-02-14 14:43:49 -0800760 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT |
chen xuf9db49f2019-03-31 23:04:42 -0700761 Intent.FLAG_RECEIVER_FOREGROUND);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800762 if (addSubIdExtra) {
763 int simApplicationState = TelephonyManager.SIM_STATE_UNKNOWN;
764 int[] subIds = SubscriptionManager.getSubId(phoneId);
765 if (!ArrayUtils.isEmpty(subIds)) {
766 TelephonyManager telMgr = TelephonyManager.from(mContext)
767 .createForSubscriptionId(subIds[0]);
768 simApplicationState = telMgr.getSimApplicationState();
769 }
Malcolm Chenf7635ec2020-04-15 15:45:00 -0700770 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId
771 + " simApplicationState " + simApplicationState);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800772 // Include subId/carrier id extra only if SIM records are loaded
773 if (simApplicationState != TelephonyManager.SIM_STATE_UNKNOWN
774 && simApplicationState != TelephonyManager.SIM_STATE_NOT_READY) {
775 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, phoneId);
776 intent.putExtra(TelephonyManager.EXTRA_SPECIFIC_CARRIER_ID,
777 getSpecificCarrierIdForPhoneId(phoneId));
778 intent.putExtra(TelephonyManager.EXTRA_CARRIER_ID, getCarrierIdForPhoneId(phoneId));
779 }
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800780 }
Amit Mahajanb33bcda2018-01-24 12:56:44 -0800781 intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, phoneId);
Sarah Chin807d5c62020-03-30 17:21:09 -0700782 intent.putExtra(CarrierConfigManager.EXTRA_REBROADCAST_ON_UNLOCK,
783 mFromSystemUnlocked[phoneId]);
Meng Wang97a6a462020-01-23 16:22:16 -0800784 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Jack Yue9e95be2020-03-22 10:56:06 -0700785 int[] subIds = SubscriptionManager.getSubId(phoneId);
786 if (subIds != null && subIds.length > 0) {
787 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId + ", subId=" + subIds[0]);
788 } else {
789 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId);
790 }
Junda Liu03aad762017-07-21 13:32:17 -0700791 mHasSentConfigChange[phoneId] = true;
Sarah Chin807d5c62020-03-30 17:21:09 -0700792 mFromSystemUnlocked[phoneId] = false;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800793 }
794
795 /** Binds to the default or carrier config app. */
796 private boolean bindToConfigPackage(String pkgName, int phoneId, int eventId) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800797 logdWithLocalLog("Binding to " + pkgName + " for phone " + phoneId);
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700798 Intent carrierService = new Intent(CarrierService.CARRIER_SERVICE_INTERFACE);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700799 carrierService.setPackage(pkgName);
Jayachandran C645ec612020-01-10 10:30:25 -0800800 CarrierServiceConnection serviceConnection = new CarrierServiceConnection(
801 phoneId, pkgName, eventId);
802 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
803 mServiceConnectionForNoSimConfig[phoneId] = serviceConnection;
804 } else {
805 mServiceConnection[phoneId] = serviceConnection;
806 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800807 try {
Jayachandran C645ec612020-01-10 10:30:25 -0800808 if (mContext.bindService(carrierService, serviceConnection,
Jordan Liu178430d2020-02-10 14:32:15 -0800809 Context.BIND_AUTO_CREATE)) {
Jayachandran C645ec612020-01-10 10:30:25 -0800810 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
811 mServiceBoundForNoSimConfig[phoneId] = true;
812 } else {
813 mServiceBound[phoneId] = true;
814 }
Jordan Liu178430d2020-02-10 14:32:15 -0800815 return true;
816 } else {
817 return false;
818 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800819 } catch (SecurityException ex) {
820 return false;
821 }
822 }
823
chen xu02581692018-11-11 19:03:44 -0800824 private CarrierIdentifier getCarrierIdentifierForPhoneId(int phoneId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800825 String mcc = "";
826 String mnc = "";
827 String imsi = "";
828 String gid1 = "";
829 String gid2 = "";
830 String spn = TelephonyManager.from(mContext).getSimOperatorNameForPhone(phoneId);
831 String simOperator = TelephonyManager.from(mContext).getSimOperatorNumericForPhone(phoneId);
chen xu02581692018-11-11 19:03:44 -0800832 int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
chen xua31f22b2019-03-06 15:28:50 -0800833 int specificCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
Jonathan Basseri1fa437c2015-04-20 11:08:18 -0700834 // A valid simOperator should be 5 or 6 digits, depending on the length of the MNC.
835 if (simOperator != null && simOperator.length() >= 3) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800836 mcc = simOperator.substring(0, 3);
837 mnc = simOperator.substring(3);
838 }
839 Phone phone = PhoneFactory.getPhone(phoneId);
840 if (phone != null) {
841 imsi = phone.getSubscriberId();
842 gid1 = phone.getGroupIdLevel1();
Junda Liu73183532015-05-14 13:55:40 -0700843 gid2 = phone.getGroupIdLevel2();
chen xu02581692018-11-11 19:03:44 -0800844 carrierId = phone.getCarrierId();
chen xua31f22b2019-03-06 15:28:50 -0800845 specificCarrierId = phone.getSpecificCarrierId();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800846 }
chen xua31f22b2019-03-06 15:28:50 -0800847 return new CarrierIdentifier(mcc, mnc, spn, imsi, gid1, gid2, carrierId, specificCarrierId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800848 }
849
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700850 /** Returns the package name of a priveleged carrier app, or null if there is none. */
851 private String getCarrierPackageForPhoneId(int phoneId) {
852 List<String> carrierPackageNames = TelephonyManager.from(mContext)
853 .getCarrierPackageNamesForIntentAndPhone(
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700854 new Intent(CarrierService.CARRIER_SERVICE_INTERFACE), phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700855 if (carrierPackageNames != null && carrierPackageNames.size() > 0) {
856 return carrierPackageNames.get(0);
857 } else {
858 return null;
859 }
860 }
861
862 private String getIccIdForPhoneId(int phoneId) {
863 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
864 return null;
865 }
866 Phone phone = PhoneFactory.getPhone(phoneId);
867 if (phone == null) {
868 return null;
869 }
870 return phone.getIccSerialNumber();
871 }
872
chen xu02581692018-11-11 19:03:44 -0800873 /**
chen xua31f22b2019-03-06 15:28:50 -0800874 * Get the sim specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}
chen xu02581692018-11-11 19:03:44 -0800875 */
chen xua31f22b2019-03-06 15:28:50 -0800876 private int getSpecificCarrierIdForPhoneId(int phoneId) {
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700877 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
chen xu02581692018-11-11 19:03:44 -0800878 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700879 }
880 Phone phone = PhoneFactory.getPhone(phoneId);
881 if (phone == null) {
chen xu02581692018-11-11 19:03:44 -0800882 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700883 }
chen xua31f22b2019-03-06 15:28:50 -0800884 return phone.getSpecificCarrierId();
chen xu02581692018-11-11 19:03:44 -0800885 }
886
887 /**
888 * Get the sim carrier id {@link TelephonyManager#getSimCarrierId() }
889 */
890 private int getCarrierIdForPhoneId(int phoneId) {
891 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
892 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700893 }
chen xu02581692018-11-11 19:03:44 -0800894 Phone phone = PhoneFactory.getPhone(phoneId);
895 if (phone == null) {
896 return TelephonyManager.UNKNOWN_CARRIER_ID;
897 }
898 return phone.getCarrierId();
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700899 }
900
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700901 /**
902 * Writes a bundle to an XML file.
903 *
chen xu02581692018-11-11 19:03:44 -0800904 * The bundle will be written to a file named after the package name, ICCID and
chen xua31f22b2019-03-06 15:28:50 -0800905 * specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}. the same carrier
chen xu02581692018-11-11 19:03:44 -0800906 * should have a single copy of XML file named after carrier id. However, it's still possible
907 * that platform doesn't recognize the current sim carrier, we will use iccid + carrierid as
908 * the canonical file name. carrierid can also handle the cases SIM OTA resolves to different
909 * carrier while iccid remains the same.
910 *
911 * The file can be restored later with {@link @restoreConfigFromXml}. The XML output will
912 * include the bundle and the current version of the specified package.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700913 *
914 * In case of errors or invalid input, no file will be written.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700915 *
Jayachandran C645ec612020-01-10 10:30:25 -0800916 * @param packageName the name of the package from which we fetched this bundle.
917 * @param extraString An extra string to be used in the XML file name.
918 * @param phoneId the phone ID.
919 * @param carrierId contains all carrier-identifying information.
920 * @param config the bundle to be written. Null will be treated as an empty bundle.
921 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700922 */
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100923 private void saveConfigToXml(String packageName, @NonNull String extraString, int phoneId,
Jayachandran C645ec612020-01-10 10:30:25 -0800924 CarrierIdentifier carrierId, PersistableBundle config, boolean isNoSimConfig) {
925 if (packageName == null) {
926 loge("Cannot save config with null packageName");
Yuchen Dongc15afed2018-04-26 17:05:22 +0800927 return;
928 }
929
Jayachandran C645ec612020-01-10 10:30:25 -0800930 String fileName;
931 if (isNoSimConfig) {
932 fileName = getFilenameForNoSimConfig(packageName);
933 } else {
934 if (SubscriptionManager.getSimStateForSlotIndex(phoneId)
935 != TelephonyManager.SIM_STATE_LOADED) {
936 loge("Skip save config because SIM records are not loaded.");
937 return;
938 }
939
940 final String iccid = getIccIdForPhoneId(phoneId);
941 final int cid = carrierId.getSpecificCarrierId();
942 if (iccid == null) {
943 loge("Cannot save config with null iccid.");
944 return;
945 }
946 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700947 }
Jayachandran C645ec612020-01-10 10:30:25 -0800948
Junda Liu02596502016-11-15 13:46:43 -0800949 // b/32668103 Only save to file if config isn't empty.
950 // In case of failure, not caching an empty bundle will
951 // try loading config again on next power on or sim loaded.
952 // Downside is for genuinely empty bundle, will bind and load
953 // on every power on.
954 if (config == null || config.isEmpty()) {
955 return;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700956 }
957
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700958 final String version = getPackageVersion(packageName);
959 if (version == null) {
960 loge("Failed to get package version for: " + packageName);
961 return;
962 }
963
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800964 logdWithLocalLog(
965 "Save config to xml, packagename: " + packageName + " phoneId: " + phoneId);
chen xudb04c292019-03-26 17:01:15 -0700966
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700967 FileOutputStream outFile = null;
968 try {
Jayachandran C645ec612020-01-10 10:30:25 -0800969 outFile = new FileOutputStream(new File(mContext.getFilesDir(), fileName));
Meng Wang0f6b2ea2020-01-06 18:31:16 -0800970 config.putString(KEY_VERSION, version);
971 config.writeToStream(outFile);
972 outFile.flush();
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700973 outFile.close();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800974 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700975 loge(e.toString());
976 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700977 }
978
Jayachandran C645ec612020-01-10 10:30:25 -0800979 private void saveConfigToXml(String packageName, @NonNull String extraString, int phoneId,
980 CarrierIdentifier carrierId, PersistableBundle config) {
981 saveConfigToXml(packageName, extraString, phoneId, carrierId, config, false);
982 }
983
984 private void saveNoSimConfigToXml(String packageName, PersistableBundle config) {
985 saveConfigToXml(packageName, "", -1, null, config, true);
986 }
987
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700988 /**
989 * Reads a bundle from an XML file.
990 *
991 * This restores a bundle that was written with {@link #saveConfigToXml}. This returns the saved
Yuchen Dongc15afed2018-04-26 17:05:22 +0800992 * config bundle for the given package and phone ID.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700993 *
994 * In case of errors, or if the saved config is from a different package version than the
995 * current version, then null will be returned.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700996 *
Jayachandran C645ec612020-01-10 10:30:25 -0800997 * @param packageName the name of the package from which we fetched this bundle.
998 * @param extraString An extra string to be used in the XML file name.
999 * @param phoneId the phone ID.
1000 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001001 * @return the bundle from the XML file. Returns null if there is no saved config, the saved
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001002 * version does not match, or reading config fails.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001003 */
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001004 private PersistableBundle restoreConfigFromXml(String packageName, @NonNull String extraString,
Jayachandran C645ec612020-01-10 10:30:25 -08001005 int phoneId, boolean isNoSimConfig) {
1006 if (packageName == null) {
1007 loge("Cannot restore config with null packageName");
1008 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001009 final String version = getPackageVersion(packageName);
1010 if (version == null) {
1011 loge("Failed to get package version for: " + packageName);
1012 return null;
1013 }
Yuchen Dongc15afed2018-04-26 17:05:22 +08001014
Jayachandran C645ec612020-01-10 10:30:25 -08001015 String fileName;
1016 if (isNoSimConfig) {
1017 fileName = getFilenameForNoSimConfig(packageName);
1018 } else {
1019 if (SubscriptionManager.getSimStateForSlotIndex(phoneId)
1020 != TelephonyManager.SIM_STATE_LOADED) {
1021 loge("Skip restore config because SIM records are not loaded.");
1022 return null;
1023 }
1024
1025 final String iccid = getIccIdForPhoneId(phoneId);
1026 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1027 if (iccid == null) {
1028 loge("Cannot restore config with null iccid.");
1029 return null;
1030 }
1031 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001032 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001033
1034 PersistableBundle restoredBundle = null;
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001035 File file = null;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001036 FileInputStream inFile = null;
1037 try {
Jayachandran C645ec612020-01-10 10:30:25 -08001038 file = new File(mContext.getFilesDir(),fileName);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001039 inFile = new FileInputStream(file);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001040
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001041 restoredBundle = PersistableBundle.readFromStream(inFile);
1042 String savedVersion = restoredBundle.getString(KEY_VERSION);
1043 restoredBundle.remove(KEY_VERSION);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001044
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001045 if (!version.equals(savedVersion)) {
1046 loge("Saved version mismatch: " + version + " vs " + savedVersion);
1047 restoredBundle = null;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001048 }
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001049
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001050 inFile.close();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001051 } catch (FileNotFoundException e) {
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001052 // Missing file is normal occurrence that might occur with a new sim or when restoring
1053 // an override file during boot and should not be treated as an error.
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001054 if (file != null) logd("File not found: " + file.getPath());
1055 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001056 loge(e.toString());
1057 }
1058
1059 return restoredBundle;
1060 }
1061
Jayachandran C645ec612020-01-10 10:30:25 -08001062 private PersistableBundle restoreConfigFromXml(String packageName, @NonNull String extraString,
1063 int phoneId) {
1064 return restoreConfigFromXml(packageName, extraString, phoneId, false);
1065 }
1066
1067 private PersistableBundle restoreNoSimConfigFromXml(String packageName) {
1068 return restoreConfigFromXml(packageName, "", -1, true);
1069 }
1070
Junda Liu8a8a53a2015-05-15 16:19:57 -07001071 /**
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001072 * Clears cached carrier config.
1073 * This deletes all saved XML files associated with the given package name. If packageName is
1074 * null, then it deletes all saved XML files.
1075 *
1076 * @param packageName the name of a carrier package, or null if all cached config should be
1077 * cleared.
1078 * @return true iff one or more files were deleted.
Junda Liu8a8a53a2015-05-15 16:19:57 -07001079 */
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001080 private boolean clearCachedConfigForPackage(final String packageName) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001081 File dir = mContext.getFilesDir();
1082 File[] packageFiles = dir.listFiles(new FilenameFilter() {
1083 public boolean accept(File dir, String filename) {
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001084 if (packageName != null) {
1085 return filename.startsWith("carrierconfig-" + packageName + "-");
1086 } else {
1087 return filename.startsWith("carrierconfig-");
1088 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001089 }
1090 });
Junda Liu8a8a53a2015-05-15 16:19:57 -07001091 if (packageFiles == null || packageFiles.length < 1) return false;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001092 for (File f : packageFiles) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001093 logd("Deleting " + f.getName());
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001094 f.delete();
1095 }
Junda Liu8a8a53a2015-05-15 16:19:57 -07001096 return true;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001097 }
1098
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001099 /** Builds a canonical file name for a config file. */
Jayachandran C645ec612020-01-10 10:30:25 -08001100 private static String getFilenameForConfig(
1101 @NonNull String packageName, @NonNull String extraString,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001102 @NonNull String iccid, int cid) {
chen xu02581692018-11-11 19:03:44 -08001103 // the same carrier should have a single copy of XML file named after carrier id.
1104 // However, it's still possible that platform doesn't recognize the current sim carrier,
1105 // we will use iccid + carrierid as the canonical file name. carrierid can also handle the
1106 // cases SIM OTA resolves to different carrier while iccid remains the same.
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001107 return "carrierconfig-" + packageName + extraString + "-" + iccid + "-" + cid + ".xml";
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001108 }
1109
Jayachandran C645ec612020-01-10 10:30:25 -08001110 /** Builds a canonical file name for no SIM config file. */
1111 private String getFilenameForNoSimConfig(@NonNull String packageName) {
1112 return "carrierconfig-" + packageName + "-" + "nosim" + ".xml";
1113 }
1114
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001115 /** Return the current version code of a package, or null if the name is not found. */
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001116 private String getPackageVersion(String packageName) {
1117 try {
1118 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
Dianne Hackbornb76ab202017-11-28 17:44:50 -08001119 return Long.toString(info.getLongVersionCode());
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001120 } catch (PackageManager.NameNotFoundException e) {
1121 return null;
1122 }
1123 }
1124
Jonathan Basseri65273c82017-07-25 15:08:42 -07001125 /**
1126 * Read up to date config.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001127 *
1128 * This reads config bundles for the given phoneId. That means getting the latest bundle from
1129 * the default app and a privileged carrier app, if present. This will not bind to an app if we
1130 * have a saved config file to use instead.
1131 */
1132 private void updateConfigForPhoneId(int phoneId) {
Junda Liu8a8a53a2015-05-15 16:19:57 -07001133 // Clear in-memory cache for carrier app config, so when carrier app gets uninstalled, no
1134 // stale config is left.
1135 if (mConfigFromCarrierApp[phoneId] != null &&
1136 getCarrierPackageForPhoneId(phoneId) == null) {
1137 mConfigFromCarrierApp[phoneId] = null;
1138 }
Jonathan Basseri65273c82017-07-25 15:08:42 -07001139 mHandler.sendMessage(mHandler.obtainMessage(EVENT_DO_FETCH_DEFAULT, phoneId, -1));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001140 }
1141
Malcolm Chen5ea18532019-10-24 19:55:44 -07001142 private void onMultiSimConfigChanged() {
1143 for (int i = TelephonyManager.from(mContext).getActiveModemCount();
1144 i < mConfigFromDefaultApp.length; i++) {
1145 clearConfigForPhone(i, false);
1146 }
1147 }
1148
Hall Liu506724b2018-10-22 18:16:14 -07001149 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001150 @NonNull
1151 public PersistableBundle getConfigForSubId(int subId, String callingPackage) {
Philip P. Moltmann9797cbb2020-01-07 13:45:00 -08001152 return getConfigForSubIdWithFeature(subId, callingPackage, null);
1153 }
1154
1155 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001156 @NonNull
1157 public PersistableBundle getConfigForSubIdWithFeature(int subId, String callingPackage,
Philip P. Moltmann9797cbb2020-01-07 13:45:00 -08001158 String callingFeatureId) {
1159 if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(mContext, subId, callingPackage,
1160 callingFeatureId, "getCarrierConfig")) {
Malcolm Chen6d3d6b32018-03-01 13:58:03 -08001161 return new PersistableBundle();
Amit Mahajan40b3fa52015-07-14 10:27:19 -07001162 }
Jeff Davidsona8e4e242018-03-15 17:16:18 -07001163
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001164 int phoneId = SubscriptionManager.getPhoneId(subId);
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001165 PersistableBundle retConfig = CarrierConfigManager.getDefaultConfig();
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001166 if (SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001167 PersistableBundle config = mConfigFromDefaultApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001168 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001169 retConfig.putAll(config);
yinxud0104832019-08-16 14:20:08 -07001170 if (getCarrierPackageForPhoneId(phoneId) == null) {
1171 retConfig.putBoolean(
1172 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
1173 }
yinxuc5e27622017-11-29 15:08:50 -08001174 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001175 config = mConfigFromCarrierApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001176 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001177 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001178 retConfig.putBoolean(CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
1179 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001180 config = mPersistentOverrideConfigs[phoneId];
1181 if (config != null) {
1182 retConfig.putAll(config);
1183 retConfig.putBoolean(CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
1184 }
Hall Liu506724b2018-10-22 18:16:14 -07001185 config = mOverrideConfigs[phoneId];
1186 if (config != null) {
1187 retConfig.putAll(config);
Hall Liu506724b2018-10-22 18:16:14 -07001188 }
Jayachandran C645ec612020-01-10 10:30:25 -08001189 } else {
1190 if (mNoSimConfig != null) {
1191 retConfig.putAll(mNoSimConfig);
1192 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001193 }
1194 return retConfig;
1195 }
1196
1197 @Override
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001198 public void overrideConfig(int subscriptionId, @Nullable PersistableBundle overrides,
1199 boolean persistent) {
Hall Liu506724b2018-10-22 18:16:14 -07001200 mContext.enforceCallingOrSelfPermission(
1201 android.Manifest.permission.MODIFY_PHONE_STATE, null);
Brad Ebingerf6281ad2019-04-25 11:02:04 -07001202 //TODO: Also check for SHELL UID to restrict this method to testing only (b/131326259)
Hall Liu506724b2018-10-22 18:16:14 -07001203 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1204 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001205 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
Hall Liu506724b2018-10-22 18:16:14 -07001206 return;
1207 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001208 overrideConfig(mOverrideConfigs, phoneId, overrides);
Hall Liu506724b2018-10-22 18:16:14 -07001209
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001210 if (persistent) {
1211 overrideConfig(mPersistentOverrideConfigs, phoneId, overrides);
1212
1213 if (overrides != null) {
1214 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
1215 saveConfigToXml(mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION, phoneId,
1216 carrierId, mPersistentOverrideConfigs[phoneId]);
1217 } else {
1218 final String iccid = getIccIdForPhoneId(phoneId);
1219 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1220 String fileName = getFilenameForConfig(mPlatformCarrierConfigPackage,
1221 OVERRIDE_PACKAGE_ADDITION, iccid, cid);
1222 File fileToDelete = new File(mContext.getFilesDir(), fileName);
1223 fileToDelete.delete();
1224 }
Hall Liu506724b2018-10-22 18:16:14 -07001225 }
Brad Ebingerc9d1fa12019-04-17 15:21:18 -07001226 notifySubscriptionInfoUpdater(phoneId);
Hall Liu506724b2018-10-22 18:16:14 -07001227 }
1228
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001229 private void overrideConfig(@NonNull PersistableBundle[] currentOverrides, int phoneId,
1230 @Nullable PersistableBundle overrides) {
1231 if (overrides == null) {
1232 currentOverrides[phoneId] = new PersistableBundle();
1233 } else if (currentOverrides[phoneId] == null) {
1234 currentOverrides[phoneId] = overrides;
1235 } else {
1236 currentOverrides[phoneId].putAll(overrides);
1237 }
1238 }
1239
Hall Liu506724b2018-10-22 18:16:14 -07001240 @Override
Jonathan Basseri86030352015-06-08 12:27:56 -07001241 public void notifyConfigChangedForSubId(int subId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001242 int phoneId = SubscriptionManager.getPhoneId(subId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001243 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001244 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001245 return;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001246 }
Jordan Liud7d57fe2019-04-16 12:29:43 -07001247
1248 // Requires the calling app to be either a carrier privileged app for this subId or
Junda Liufbd2bcb2016-06-15 11:15:42 -07001249 // system privileged app with MODIFY_PHONE_STATE permission.
Jordan Liud7d57fe2019-04-16 12:29:43 -07001250 TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(mContext, subId,
1251 "Require carrier privileges or MODIFY_PHONE_STATE permission.");
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001252
1253 // This method should block until deleting has completed, so that an error which prevents us
1254 // from clearing the cache is passed back to the carrier app. With the files successfully
1255 // deleted, this can return and we will eventually bind to the carrier app.
Jordan Liud7d57fe2019-04-16 12:29:43 -07001256 String callingPackageName = mContext.getPackageManager().getNameForUid(
1257 Binder.getCallingUid());
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001258 clearCachedConfigForPackage(callingPackageName);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001259 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001260 }
1261
1262 @Override
1263 public void updateConfigForPhoneId(int phoneId, String simState) {
Junda Liu1f2b34d2015-06-18 15:26:56 -07001264 mContext.enforceCallingOrSelfPermission(
1265 android.Manifest.permission.MODIFY_PHONE_STATE, null);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001266 logdWithLocalLog("Update config for phoneId: " + phoneId + " simState: " + simState);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001267 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
1268 return;
1269 }
1270 // requires Java 7 for switch on string.
1271 switch (simState) {
1272 case IccCardConstants.INTENT_VALUE_ICC_ABSENT:
1273 case IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR:
Junda Liu6f5fddf2016-05-24 16:14:41 -07001274 case IccCardConstants.INTENT_VALUE_ICC_CARD_RESTRICTED:
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001275 case IccCardConstants.INTENT_VALUE_ICC_UNKNOWN:
Malcolm Chendb66de12019-12-09 18:57:07 -08001276 case IccCardConstants.INTENT_VALUE_ICC_NOT_READY:
Junda Liu9f2d2712015-05-15 14:22:45 -07001277 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CLEAR_CONFIG, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001278 break;
1279 case IccCardConstants.INTENT_VALUE_ICC_LOADED:
1280 case IccCardConstants.INTENT_VALUE_ICC_LOCKED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001281 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001282 break;
1283 }
1284 }
1285
Junda Liu43d723a2015-05-12 17:23:45 -07001286 @Override
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001287 public String getDefaultCarrierServicePackageName() {
Shuo Qianefdb7962019-12-19 15:54:27 -08001288 mContext.enforceCallingOrSelfPermission(
1289 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
1290 "getDefaultCarrierServicePackageName");
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001291 return mPlatformCarrierConfigPackage;
1292 }
1293
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001294 private void unbindIfBound(Context context, CarrierServiceConnection conn,
1295 int phoneId) {
1296 if (mServiceBound[phoneId]) {
1297 mServiceBound[phoneId] = false;
1298 context.unbindService(conn);
1299 }
1300 }
1301
Jayachandran C645ec612020-01-10 10:30:25 -08001302 private void unbindIfBoundForNoSimConfig(Context context, CarrierServiceConnection conn,
1303 int phoneId) {
1304 if (mServiceBoundForNoSimConfig[phoneId]) {
1305 mServiceBoundForNoSimConfig[phoneId] = false;
1306 context.unbindService(conn);
1307 }
1308 }
1309
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001310 /**
1311 * If {@code args} contains {@link #DUMP_ARG_REQUESTING_PACKAGE} and a following package name,
1312 * we'll also call {@link IBinder#dump} on the default carrier service (if bound) and the
1313 * specified carrier service (if bound). Typically, this is done for connectivity bug reports
1314 * where we don't call {@code dumpsys activity service all-non-platform} because that contains
1315 * too much info, but we still want to let carrier apps include their diagnostics.
1316 */
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001317 @Override
Junda Liu43d723a2015-05-12 17:23:45 -07001318 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001319 IndentingPrintWriter indentPW = new IndentingPrintWriter(pw, " ");
Junda Liu43d723a2015-05-12 17:23:45 -07001320 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1321 != PackageManager.PERMISSION_GRANTED) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001322 indentPW.println("Permission Denial: can't dump carrierconfig from from pid="
Junda Liu43d723a2015-05-12 17:23:45 -07001323 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
1324 return;
1325 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001326 String requestingPackage = null;
1327 int requestingPackageIndex = ArrayUtils.indexOf(args, DUMP_ARG_REQUESTING_PACKAGE);
1328 if (requestingPackageIndex >= 0 && requestingPackageIndex < args.length - 1
1329 && !TextUtils.isEmpty(args[requestingPackageIndex + 1])) {
1330 requestingPackage = args[requestingPackageIndex + 1];
1331 // Throws a SecurityException if the caller is impersonating another app in an effort to
1332 // dump extra info (which may contain PII the caller doesn't have a right to).
1333 enforceCallerIsSystemOrRequestingPackage(requestingPackage);
1334 }
1335
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001336 indentPW.println("CarrierConfigLoader: " + this);
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001337 for (int i = 0; i < TelephonyManager.from(mContext).getActiveModemCount(); i++) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001338 indentPW.println("Phone Id = " + i);
shuoq26a3a4c2016-12-16 11:06:48 -08001339 // display default values in CarrierConfigManager
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001340 printConfig(CarrierConfigManager.getDefaultConfig(), indentPW,
shuoq26a3a4c2016-12-16 11:06:48 -08001341 "Default Values from CarrierConfigManager");
shuoq26a3a4c2016-12-16 11:06:48 -08001342 // display ConfigFromDefaultApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001343 printConfig(mConfigFromDefaultApp[i], indentPW, "mConfigFromDefaultApp");
shuoq26a3a4c2016-12-16 11:06:48 -08001344 // display ConfigFromCarrierApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001345 printConfig(mConfigFromCarrierApp[i], indentPW, "mConfigFromCarrierApp");
1346 printConfig(mPersistentOverrideConfigs[i], indentPW, "mPersistentOverrideConfigs");
1347 printConfig(mOverrideConfigs[i], indentPW, "mOverrideConfigs");
shuoq26a3a4c2016-12-16 11:06:48 -08001348 }
chen xudb04c292019-03-26 17:01:15 -07001349
Jayachandran C645ec612020-01-10 10:30:25 -08001350 printConfig(mNoSimConfig, indentPW, "mNoSimConfig");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001351 indentPW.println("CarrierConfigLoadingLog=");
1352 mCarrierConfigLoadingLog.dump(fd, indentPW, args);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001353
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001354 if (requestingPackage != null) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001355 logd("Including default and requesting package " + requestingPackage
1356 + " carrier services in dump");
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001357 indentPW.println("");
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001358 indentPW.println("Connected services");
1359 dumpCarrierServiceIfBound(fd, indentPW, "Default config package",
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001360 mPlatformCarrierConfigPackage, false /* considerCarrierPrivileges */);
1361 dumpCarrierServiceIfBound(fd, indentPW, "Requesting package", requestingPackage,
1362 true /* considerCarrierPrivileges */);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001363 }
shuoq26a3a4c2016-12-16 11:06:48 -08001364 }
1365
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001366 private void printConfig(PersistableBundle configApp, IndentingPrintWriter indentPW,
1367 String name) {
1368 indentPW.increaseIndent();
shuoq26a3a4c2016-12-16 11:06:48 -08001369 if (configApp == null) {
shuoq26a3a4c2016-12-16 11:06:48 -08001370 indentPW.println(name + " : null ");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001371 indentPW.decreaseIndent();
1372 indentPW.println("");
shuoq26a3a4c2016-12-16 11:06:48 -08001373 return;
1374 }
shuoq26a3a4c2016-12-16 11:06:48 -08001375 indentPW.println(name + " : ");
1376 List<String> sortedKeys = new ArrayList<String>(configApp.keySet());
1377 Collections.sort(sortedKeys);
1378 indentPW.increaseIndent();
1379 indentPW.increaseIndent();
1380 for (String key : sortedKeys) {
1381 if (configApp.get(key) != null && configApp.get(key) instanceof Object[]) {
1382 indentPW.println(key + " = " +
1383 Arrays.toString((Object[]) configApp.get(key)));
1384 } else if (configApp.get(key) != null && configApp.get(key) instanceof int[]) {
1385 indentPW.println(key + " = " + Arrays.toString((int[]) configApp.get(key)));
1386 } else {
1387 indentPW.println(key + " = " + configApp.get(key));
1388 }
Junda Liu43d723a2015-05-12 17:23:45 -07001389 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001390 indentPW.decreaseIndent();
1391 indentPW.decreaseIndent();
1392 indentPW.decreaseIndent();
1393 indentPW.println("");
Junda Liu43d723a2015-05-12 17:23:45 -07001394 }
1395
Hunter Knepshielde601f432020-02-19 10:16:04 -08001396 /**
1397 * Passes without problem when one of these conditions is true:
1398 * - The caller is a privileged UID (e.g. for dumpstate.cpp generating a bug report, where the
1399 * system knows the true caller plumbed in through the {@link android.os.BugreportManager} API).
1400 * - The caller's UID matches the supplied package.
1401 *
1402 * @throws SecurityException if none of the above conditions are met.
1403 */
1404 private void enforceCallerIsSystemOrRequestingPackage(String requestingPackage)
1405 throws SecurityException {
1406 final int callingUid = Binder.getCallingUid();
1407 if (callingUid == Process.ROOT_UID || callingUid == Process.SYSTEM_UID
1408 || callingUid == Process.SHELL_UID || callingUid == Process.PHONE_UID) {
1409 // Bug reports (dumpstate.cpp) run as SHELL, and let some other privileged UIDs through
1410 // as well.
1411 return;
1412 }
1413 // An app is trying to dump extra detail, block it if they aren't who they claim to be.
1414 AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
1415 if (appOps == null) {
1416 throw new SecurityException("No AppOps");
1417 }
1418 // Will throw a SecurityException if the UID and package don't match.
1419 appOps.checkPackage(callingUid, requestingPackage);
1420 }
1421
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001422 /**
1423 * Searches for one or more appropriate {@link CarrierService} instances to dump based on the
1424 * current connections.
1425 *
1426 * @param targetPkgName the target package name to dump carrier services for
1427 * @param considerCarrierPrivileges if true, allow a carrier service to be dumped if it shares
1428 * carrier privileges with {@code targetPkgName};
1429 * otherwise, only dump a carrier service if it is {@code
1430 * targetPkgName}
1431 */
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001432 private void dumpCarrierServiceIfBound(FileDescriptor fd, IndentingPrintWriter indentPW,
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001433 String prefix, String targetPkgName, boolean considerCarrierPrivileges) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001434 // Null package is possible if it's early in the boot process, there was a recent crash, we
1435 // loaded the config from XML most recently, or a SIM slot is empty. Carrier apps with
1436 // long-lived bindings should typically get dumped here regardless. Even if an app is being
1437 // used for multiple phoneIds, we assume that it's smart enough to handle that on its own,
1438 // and that in most cases we'd just be dumping duplicate information and bloating a report.
1439 indentPW.increaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001440 indentPW.println(prefix + " : " + targetPkgName);
1441 Set<String> dumpedPkgNames = new ArraySet<>(mServiceConnection.length);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001442 for (CarrierServiceConnection connection : mServiceConnection) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001443 if (connection == null || !SubscriptionManager.isValidPhoneId(connection.phoneId)
1444 || TextUtils.isEmpty(connection.pkgName)) {
1445 continue;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001446 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001447 final String servicePkgName = connection.pkgName;
1448 // Note: we intentionally ignore system components here because we should NOT match the
1449 // shell caller that's typically used for bug reports via non-BugreportManager triggers.
1450 final boolean exactPackageMatch = TextUtils.equals(targetPkgName, servicePkgName);
1451 final boolean carrierPrivilegesMatch =
1452 considerCarrierPrivileges && hasCarrierPrivileges(targetPkgName,
1453 connection.phoneId);
1454 if (!exactPackageMatch && !carrierPrivilegesMatch) continue;
1455 // Make sure this service is actually alive before trying to dump it. We don't pay
1456 // attention to mServiceBound[connection.phoneId] because typically carrier apps will
1457 // request long-lived bindings, and even if we unbind the app, it may still be alive due
1458 // to CarrierServiceBindHelper. Pull it out as a reference so even if it gets set to
1459 // null within the ServiceConnection during unbinding we can avoid an NPE.
1460 final IBinder service = connection.service;
1461 if (service == null || !service.isBinderAlive() || !service.pingBinder()) continue;
1462 // We've got a live service. Last check is just to make sure we don't dump a package
1463 // multiple times.
1464 if (!dumpedPkgNames.add(servicePkgName)) continue;
1465 if (!exactPackageMatch) {
1466 logd(targetPkgName + " has carrier privileges on phoneId " + connection.phoneId
1467 + ", service provided by " + servicePkgName);
1468 indentPW.increaseIndent();
1469 indentPW.println("Proxy : " + servicePkgName);
1470 indentPW.decreaseIndent();
1471 }
1472 // Flush before we let the app output anything to ensure correct ordering of output.
1473 // Internally, Binder#dump calls flush on its printer after finishing so we don't
1474 // need to do anything after.
1475 indentPW.flush();
1476 try {
1477 logd("Dumping " + servicePkgName);
1478 // We don't need to give the carrier service any args.
1479 connection.service.dump(fd, null /* args */);
1480 logd("Done with " + servicePkgName);
1481 } catch (RemoteException e) {
1482 logd("RemoteException from " + servicePkgName, e);
1483 indentPW.increaseIndent();
1484 indentPW.println("RemoteException");
1485 indentPW.increaseIndent();
1486 e.printStackTrace(indentPW);
1487 indentPW.decreaseIndent();
1488 indentPW.decreaseIndent();
1489 // We won't retry this package again because now it's in dumpedPkgNames.
1490 }
1491 indentPW.println("");
Jordan Liu46ed5db2020-01-28 08:55:20 -08001492 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001493 if (dumpedPkgNames.isEmpty()) {
1494 indentPW.increaseIndent();
1495 indentPW.println("Not bound");
1496 indentPW.decreaseIndent();
1497 indentPW.println("");
1498 }
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001499 indentPW.decreaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001500 }
1501
1502 private boolean hasCarrierPrivileges(String pkgName, int phoneId) {
1503 int[] subIds = SubscriptionManager.getSubId(phoneId);
1504 if (ArrayUtils.isEmpty(subIds)) {
1505 return false;
1506 }
1507 return TelephonyManager.from(mContext).createForSubscriptionId(
1508 subIds[0]).checkCarrierPrivilegesForPackage(pkgName)
1509 == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001510 }
1511
Zach Johnson36d7aab2015-05-22 15:43:00 -07001512 private class CarrierServiceConnection implements ServiceConnection {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001513 final int phoneId;
1514 final String pkgName;
1515 final int eventId;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001516 IBinder service;
1517
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001518 CarrierServiceConnection(int phoneId, String pkgName, int eventId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001519 this.phoneId = phoneId;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001520 this.pkgName = pkgName;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001521 this.eventId = eventId;
1522 }
1523
1524 @Override
1525 public void onServiceConnected(ComponentName name, IBinder service) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001526 logd("Connected to config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001527 this.service = service;
1528 mHandler.sendMessage(mHandler.obtainMessage(eventId, phoneId, -1, this));
1529 }
1530
1531 @Override
1532 public void onServiceDisconnected(ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001533 logd("Disconnected from config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001534 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001535 }
1536
1537 @Override
1538 public void onBindingDied(ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001539 logd("Binding died from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001540 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001541 }
1542
1543 @Override
1544 public void onNullBinding(ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001545 logd("Null binding from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001546 this.service = null;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001547 }
1548 }
1549
1550 private class ConfigLoaderBroadcastReceiver extends BroadcastReceiver {
1551 @Override
1552 public void onReceive(Context context, Intent intent) {
1553 String action = intent.getAction();
Junda Liu8a8a53a2015-05-15 16:19:57 -07001554 boolean replace = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1555 // If replace is true, only care ACTION_PACKAGE_REPLACED.
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001556 if (replace && !Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
Junda Liu8a8a53a2015-05-15 16:19:57 -07001557 return;
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001558 }
Junda Liu8a8a53a2015-05-15 16:19:57 -07001559
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001560 switch (action) {
Nanxi Chen3d670502016-03-17 16:32:09 -07001561 case Intent.ACTION_BOOT_COMPLETED:
1562 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_UNLOCKED, null));
1563 break;
1564
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001565 case Intent.ACTION_PACKAGE_ADDED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001566 case Intent.ACTION_PACKAGE_REMOVED:
Junda Liu8a8a53a2015-05-15 16:19:57 -07001567 case Intent.ACTION_PACKAGE_REPLACED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001568 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
1569 String packageName = mContext.getPackageManager().getNameForUid(uid);
Junda Liu8a8a53a2015-05-15 16:19:57 -07001570 if (packageName != null) {
1571 // We don't have a phoneId for arg1.
1572 mHandler.sendMessage(
1573 mHandler.obtainMessage(EVENT_PACKAGE_CHANGED, packageName));
1574 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001575 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001576 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001577 }
1578 }
1579
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001580 private void logd(String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001581 Log.d(LOG_TAG, msg);
1582 }
1583
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001584 private void logd(String msg, Throwable tr) {
1585 Log.d(LOG_TAG, msg, tr);
1586 }
1587
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001588 private void logdWithLocalLog(String msg) {
chen xudb04c292019-03-26 17:01:15 -07001589 Log.d(LOG_TAG, msg);
1590 mCarrierConfigLoadingLog.log(msg);
1591 }
1592
1593 private void loge(String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001594 Log.e(LOG_TAG, msg);
chen xudb04c292019-03-26 17:01:15 -07001595 mCarrierConfigLoadingLog.log(msg);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001596 }
1597}