blob: 58b829909872ddee03fc8d28d6866fbfc2f0e5a1 [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;
Rambo Wanga27fbe52022-04-12 19:09:07 +000038import android.os.HandlerExecutor;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080039import android.os.IBinder;
Rambo Wang7e3bc122021-03-23 09:24:38 -070040import android.os.Looper;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080041import android.os.Message;
Jonathan Basseric31f1f32015-05-12 10:13:03 -070042import android.os.PersistableBundle;
Hunter Knepshielde601f432020-02-19 10:16:04 -080043import android.os.Process;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080044import android.os.RemoteException;
Jonathan Basseri65273c82017-07-25 15:08:42 -070045import android.os.ResultReceiver;
Meng Wang97a6a462020-01-23 16:22:16 -080046import android.os.UserHandle;
Jonathan Basseri7697cae2015-07-06 15:49:23 -070047import android.preference.PreferenceManager;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080048import android.service.carrier.CarrierIdentifier;
Zach Johnson36d7aab2015-05-22 15:43:00 -070049import android.service.carrier.CarrierService;
50import android.service.carrier.ICarrierService;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080051import android.telephony.CarrierConfigManager;
52import android.telephony.SubscriptionManager;
Peter Wangc035ce42020-01-08 21:00:22 -080053import android.telephony.TelephonyFrameworkInitializer;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080054import android.telephony.TelephonyManager;
rambowangd63ba342022-10-02 11:21:08 -050055import android.telephony.TelephonyRegistryManager;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -080056import android.text.TextUtils;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -080057import android.util.ArraySet;
chen xudb04c292019-03-26 17:01:15 -070058import android.util.LocalLog;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080059import android.util.Log;
60
Rambo Wang7e3bc122021-03-23 09:24:38 -070061import com.android.internal.annotations.VisibleForTesting;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080062import com.android.internal.telephony.ICarrierConfigLoader;
63import com.android.internal.telephony.IccCardConstants;
64import com.android.internal.telephony.Phone;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080065import com.android.internal.telephony.PhoneFactory;
Nathan Harold48ac0972019-03-13 22:33:01 -070066import com.android.internal.telephony.SubscriptionInfoUpdater;
Jeff Davidsona8e4e242018-03-15 17:16:18 -070067import com.android.internal.telephony.TelephonyPermissions;
Jack Yue37dd262022-12-16 11:53:37 -080068import com.android.internal.telephony.subscription.SubscriptionManagerService;
Meng Wanga320b942019-11-25 11:21:26 -080069import com.android.internal.telephony.util.ArrayUtils;
shuoq26a3a4c2016-12-16 11:06:48 -080070import com.android.internal.util.IndentingPrintWriter;
arunvoddu664c36a2021-10-11 20:09:28 +000071import com.android.telephony.Rlog;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080072
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070073import java.io.File;
Junda Liu43d723a2015-05-12 17:23:45 -070074import java.io.FileDescriptor;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070075import java.io.FileInputStream;
76import java.io.FileNotFoundException;
77import java.io.FileOutputStream;
Jonathan Basseri1f743c92015-05-15 00:19:46 -070078import java.io.FilenameFilter;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070079import java.io.IOException;
Junda Liu43d723a2015-05-12 17:23:45 -070080import java.io.PrintWriter;
shuoq26a3a4c2016-12-16 11:06:48 -080081import java.util.ArrayList;
82import java.util.Arrays;
83import java.util.Collections;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080084import java.util.List;
rambowang14757c22022-10-03 11:54:56 -050085import java.util.Objects;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -080086import java.util.Set;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080087
88/**
89 * CarrierConfigLoader binds to privileged carrier apps to fetch carrier config overlays.
Jonathan Basseri6465afd2015-02-25 13:05:57 -080090 */
Jonathan Basseri6465afd2015-02-25 13:05:57 -080091public class CarrierConfigLoader extends ICarrierConfigLoader.Stub {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070092 private static final String LOG_TAG = "CarrierConfigLoader";
Meng Wang33ad2bc2017-03-16 20:21:20 -070093
94 // Package name for platform carrier config app, bundled with system image.
Rambo Wangfe0d7c12022-04-15 03:00:32 +000095 @NonNull private final String mPlatformCarrierConfigPackage;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080096
97 /** The singleton instance. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +000098 @Nullable private static CarrierConfigLoader sInstance;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080099 // The context for phone app, passed from PhoneGlobals.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000100 @NonNull private Context mContext;
101
102 // All the states below (array indexed by phoneId) are non-null. But the member of the array
103 // is nullable, when e.g. the config for the phone is not loaded yet
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800104 // Carrier configs from default app, indexed by phoneID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000105 @NonNull private PersistableBundle[] mConfigFromDefaultApp;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800106 // Carrier configs from privileged carrier config app, indexed by phoneID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000107 @NonNull private PersistableBundle[] mConfigFromCarrierApp;
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100108 // Persistent Carrier configs that are provided via the override test API, indexed by phone ID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000109 @NonNull private PersistableBundle[] mPersistentOverrideConfigs;
Hall Liu506724b2018-10-22 18:16:14 -0700110 // Carrier configs that are provided via the override test API, indexed by phone ID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000111 @NonNull private PersistableBundle[] mOverrideConfigs;
Jayachandran C645ec612020-01-10 10:30:25 -0800112 // Carrier configs to override code default when there is no SIM inserted
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000113 @NonNull private PersistableBundle mNoSimConfig;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800114 // Service connection for binding to config app.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000115 @NonNull private CarrierServiceConnection[] mServiceConnection;
Jayachandran C645ec612020-01-10 10:30:25 -0800116 // Service connection for binding to carrier config app for no SIM config.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000117 @NonNull private CarrierServiceConnection[] mServiceConnectionForNoSimConfig;
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700118 // Whether we are bound to a service for each phone
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000119 @NonNull private boolean[] mServiceBound;
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700120 // Whether we are bound to a service for no SIM config
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000121 @NonNull private boolean[] mServiceBoundForNoSimConfig;
Sarah Chin807d5c62020-03-30 17:21:09 -0700122 // Whether we have sent config change broadcast for each phone id.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000123 @NonNull private boolean[] mHasSentConfigChange;
Sarah Chin807d5c62020-03-30 17:21:09 -0700124 // Whether the broadcast was sent from EVENT_SYSTEM_UNLOCKED, to track rebroadcasts
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000125 @NonNull private boolean[] mFromSystemUnlocked;
Rambo Wanga27fbe52022-04-12 19:09:07 +0000126 // CarrierService change monitoring
127 @NonNull private CarrierServiceChangeCallback[] mCarrierServiceChangeCallbacks;
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000128
Nathan Harold48ac0972019-03-13 22:33:01 -0700129 // SubscriptionInfoUpdater
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000130 @NonNull private final SubscriptionInfoUpdater mSubscriptionInfoUpdater;
Rambo Wanga27fbe52022-04-12 19:09:07 +0000131 // Broadcast receiver for system events (BootCompleted, MultiSimConfigChanged etc.)
132 @NonNull
133 private final BroadcastReceiver mSystemBroadcastReceiver = new ConfigLoaderBroadcastReceiver();
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000134 @NonNull private final LocalLog mCarrierConfigLoadingLog = new LocalLog(100);
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000135 // Number of phone instances (active modem count)
136 private int mNumPhones;
chen xudb04c292019-03-26 17:01:15 -0700137
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800138
139 // Message codes; see mHandler below.
140 // Request from SubscriptionInfoUpdater when SIM becomes absent or error.
141 private static final int EVENT_CLEAR_CONFIG = 0;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800142 // Has connected to default app.
143 private static final int EVENT_CONNECTED_TO_DEFAULT = 3;
144 // Has connected to carrier app.
145 private static final int EVENT_CONNECTED_TO_CARRIER = 4;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700146 // Config has been loaded from default app (or cache).
147 private static final int EVENT_FETCH_DEFAULT_DONE = 5;
148 // Config has been loaded from carrier app (or cache).
149 private static final int EVENT_FETCH_CARRIER_DONE = 6;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700150 // Attempt to fetch from default app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700151 private static final int EVENT_DO_FETCH_DEFAULT = 7;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700152 // Attempt to fetch from carrier app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700153 private static final int EVENT_DO_FETCH_CARRIER = 8;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700154 // A package has been installed, uninstalled, or updated.
155 private static final int EVENT_PACKAGE_CHANGED = 9;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700156 // Bind timed out for the default app.
157 private static final int EVENT_BIND_DEFAULT_TIMEOUT = 10;
158 // Bind timed out for a carrier app.
159 private static final int EVENT_BIND_CARRIER_TIMEOUT = 11;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700160 // Check if the system fingerprint has changed.
161 private static final int EVENT_CHECK_SYSTEM_UPDATE = 12;
Nanxi Chen3d670502016-03-17 16:32:09 -0700162 // Rerun carrier config binding after system is unlocked.
163 private static final int EVENT_SYSTEM_UNLOCKED = 13;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700164 // Fetching config timed out from the default app.
165 private static final int EVENT_FETCH_DEFAULT_TIMEOUT = 14;
166 // Fetching config timed out from a carrier app.
167 private static final int EVENT_FETCH_CARRIER_TIMEOUT = 15;
Nathan Harold48ac0972019-03-13 22:33:01 -0700168 // SubscriptionInfoUpdater has finished updating the sub for the carrier config.
169 private static final int EVENT_SUBSCRIPTION_INFO_UPDATED = 16;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700170 // Multi-SIM config changed.
171 private static final int EVENT_MULTI_SIM_CONFIG_CHANGED = 17;
Jayachandran C645ec612020-01-10 10:30:25 -0800172 // Attempt to fetch from default app or read from XML for no SIM case.
173 private static final int EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG = 18;
174 // No SIM config has been loaded from default app (or cache).
175 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE = 19;
176 // Has connected to default app for no SIM config.
177 private static final int EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG = 20;
178 // Bind timed out for the default app when trying to fetch no SIM config.
179 private static final int EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 21;
180 // Fetching config timed out from the default app for no SIM config.
181 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 22;
Rambo Wangab13e3e2021-04-08 15:01:06 -0700182 // NOTE: any new EVENT_* values must be added to method eventToString().
Jonathan Basseri930701e2015-06-11 20:56:43 -0700183
Junda Liu6cb45002016-03-22 17:18:20 -0700184 private static final int BIND_TIMEOUT_MILLIS = 30000;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800185
Meng Wang0f6b2ea2020-01-06 18:31:16 -0800186 // Keys used for saving and restoring config bundle from file.
187 private static final String KEY_VERSION = "__carrier_config_package_version__";
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800188
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100189 private static final String OVERRIDE_PACKAGE_ADDITION = "-override";
190
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700191 // SharedPreferences key for last known build fingerprint.
192 private static final String KEY_FINGERPRINT = "build_fingerprint";
193
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -0800194 // Argument for #dump that indicates we should also call the default and specified carrier
195 // service's #dump method. In multi-SIM devices, it's possible that carrier A is on SIM 1 and
196 // carrier B is on SIM 2, in which case we should not dump carrier B's service when carrier A
197 // requested the dump.
198 private static final String DUMP_ARG_REQUESTING_PACKAGE = "--requesting-package";
199
rambowang14757c22022-10-03 11:54:56 -0500200 // Configs that should always be included when clients calls getConfig[ForSubId] with specified
201 // keys (even configs are not explicitly specified). Those configs have special purpose for the
202 // carrier config APIs to work correctly.
203 private static final String[] CONFIG_SUBSET_METADATA_KEYS = new String[] {
204 CarrierConfigManager.KEY_CARRIER_CONFIG_VERSION_STRING,
205 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL
206 };
207
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800208 // Handler to process various events.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700209 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700210 // For each phoneId, the event sequence should be:
Jonathan Basseri65273c82017-07-25 15:08:42 -0700211 // fetch default, connected to default, fetch default (async), fetch default done,
212 // fetch carrier, connected to carrier, fetch carrier (async), fetch carrier done.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700213 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700214 // If there is a saved config file for either the default app or the carrier app, we skip
215 // binding to the app and go straight from fetch to loaded.
216 //
217 // At any time, at most one connection is active. If events are not in this order, previous
218 // connection will be unbound, so only latest event takes effect.
219 //
220 // We broadcast ACTION_CARRIER_CONFIG_CHANGED after:
221 // 1. loading from carrier app (even if read from a file)
222 // 2. loading from default app if there is no carrier app (even if read from a file)
223 // 3. clearing config (e.g. due to sim removal)
224 // 4. encountering bind or IPC error
Jonathan Basseri65273c82017-07-25 15:08:42 -0700225 private class ConfigHandler extends Handler {
Rambo Wang7e3bc122021-03-23 09:24:38 -0700226 ConfigHandler(@NonNull Looper looper) {
227 super(looper);
228 }
229
Jonathan Basseri65273c82017-07-25 15:08:42 -0700230 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000231 public void handleMessage(@NonNull Message msg) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700232 final int phoneId = msg.arg1;
Rambo Wangab13e3e2021-04-08 15:01:06 -0700233 logdWithLocalLog("mHandler: " + eventToString(msg.what) + " phoneId: " + phoneId);
Malcolm Chen5ea18532019-10-24 19:55:44 -0700234 if (!SubscriptionManager.isValidPhoneId(phoneId)
235 && msg.what != EVENT_MULTI_SIM_CONFIG_CHANGED) {
236 return;
237 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800238 switch (msg.what) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800239 case EVENT_CLEAR_CONFIG: {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700240 clearConfigForPhone(phoneId, true);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800241 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700242 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700243
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800244 case EVENT_SYSTEM_UNLOCKED: {
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000245 for (int i = 0; i < mNumPhones; ++i) {
Sarah Chin807d5c62020-03-30 17:21:09 -0700246 // When the user unlocks the device, send the broadcast again (with a
247 // rebroadcast extra) if we have sent it before unlock. This will avoid
248 // trying to load the carrier config when the SIM is still loading when the
249 // unlock happens.
Junda Liu03aad762017-07-21 13:32:17 -0700250 if (mHasSentConfigChange[i]) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800251 logdWithLocalLog("System unlocked");
Sarah Chin807d5c62020-03-30 17:21:09 -0700252 mFromSystemUnlocked[i] = true;
Junda Liu03aad762017-07-21 13:32:17 -0700253 updateConfigForPhoneId(i);
254 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700255 }
256 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700257 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700258
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800259 case EVENT_PACKAGE_CHANGED: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700260 final String carrierPackageName = (String) msg.obj;
Rambo Wanga27fbe52022-04-12 19:09:07 +0000261 // Always clear up the cache and re-load config from scratch since the carrier
262 // service change is reliable and specific to the phoneId now.
263 clearCachedConfigForPackage(carrierPackageName);
264 logdWithLocalLog("Package changed: " + carrierPackageName
265 + ", phone=" + phoneId);
266 updateConfigForPhoneId(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700267 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700268 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700269
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800270 case EVENT_DO_FETCH_DEFAULT: {
Rambo Wang9bc7d362021-03-09 09:10:58 -0800271 // Clear in-memory cache for carrier app config, so when carrier app gets
272 // uninstalled, no stale config is left.
273 if (mConfigFromCarrierApp[phoneId] != null
274 && getCarrierPackageForPhoneId(phoneId) == null) {
275 mConfigFromCarrierApp[phoneId] = null;
276 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100277 // Restore persistent override values.
278 PersistableBundle config = restoreConfigFromXml(
279 mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION, phoneId);
280 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800281 logd("Loaded persistent override config from XML. package="
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100282 + mPlatformCarrierConfigPackage
283 + " phoneId=" + phoneId);
284 mPersistentOverrideConfigs[phoneId] = config;
285 }
286
287 config = restoreConfigFromXml(mPlatformCarrierConfigPackage, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700288 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800289 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700290 "Loaded config from XML. package="
291 + mPlatformCarrierConfigPackage
292 + " phoneId="
293 + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700294 mConfigFromDefaultApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700295 Message newMsg = obtainMessage(EVENT_FETCH_DEFAULT_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700296 newMsg.getData().putBoolean("loaded_from_xml", true);
297 mHandler.sendMessage(newMsg);
298 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700299 // No cached config, so fetch it from the default app.
300 if (bindToConfigPackage(
301 mPlatformCarrierConfigPackage,
302 phoneId,
303 EVENT_CONNECTED_TO_DEFAULT)) {
304 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800305 obtainMessage(EVENT_BIND_DEFAULT_TIMEOUT, phoneId, -1 /*arg2*/,
306 getMessageToken(phoneId)),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700307 BIND_TIMEOUT_MILLIS);
308 } else {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800309 // Put a stub bundle in place so that the rest of the logic continues
310 // smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000311 mConfigFromDefaultApp[phoneId] = new PersistableBundle();
Jonathan Basseri65273c82017-07-25 15:08:42 -0700312 // Send broadcast if bind fails.
Jack Yue37dd262022-12-16 11:53:37 -0800313 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700314 // TODO: We *must* call unbindService even if bindService returns false.
315 // (And possibly if SecurityException was thrown.)
chen xudb04c292019-03-26 17:01:15 -0700316 loge("binding to default app: "
317 + mPlatformCarrierConfigPackage + " fails");
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700318 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800319 }
320 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700321 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800322
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800323 case EVENT_CONNECTED_TO_DEFAULT: {
Rambo Wang610fdf62021-03-08 21:37:11 -0800324 removeMessages(EVENT_BIND_DEFAULT_TIMEOUT, getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700325 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800326 // If new service connection has been created, unbind.
327 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700328 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800329 break;
330 }
chen xu02581692018-11-11 19:03:44 -0800331 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700332 // ResultReceiver callback will execute in this Handler's thread.
333 final ResultReceiver resultReceiver =
334 new ResultReceiver(this) {
335 @Override
336 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700337 unbindIfBound(mContext, conn, phoneId);
Rambo Wanga9d27a52021-04-09 16:17:33 -0700338 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT,
339 getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700340 // If new service connection has been created, this is stale.
341 if (mServiceConnection[phoneId] != conn) {
342 loge("Received response for stale request.");
343 return;
344 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700345 if (resultCode == RESULT_ERROR || resultData == null) {
346 // On error, abort config fetching.
347 loge("Failed to get carrier config");
Jack Yue37dd262022-12-16 11:53:37 -0800348 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700349 return;
350 }
351 PersistableBundle config =
352 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100353 saveConfigToXml(mPlatformCarrierConfigPackage, "", phoneId,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800354 carrierId, config);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700355 mConfigFromDefaultApp[phoneId] = config;
356 sendMessage(
357 obtainMessage(
358 EVENT_FETCH_DEFAULT_DONE, phoneId, -1));
359 }
360 };
361 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800362 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700363 ICarrierService carrierService =
364 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800365 carrierService.getCarrierConfig(phoneId, carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800366 logdWithLocalLog("Fetch config for default app: "
chen xudb04c292019-03-26 17:01:15 -0700367 + mPlatformCarrierConfigPackage
368 + " carrierid: " + carrierId.toString());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700369 } catch (RemoteException e) {
chen xudb04c292019-03-26 17:01:15 -0700370 loge("Failed to get carrier config from default app: " +
371 mPlatformCarrierConfigPackage + " err: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700372 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700373 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800374 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700375 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800376 obtainMessage(EVENT_FETCH_DEFAULT_TIMEOUT, phoneId, -1 /*arg2*/,
377 getMessageToken(phoneId)),
Jonathan Basseri65273c82017-07-25 15:08:42 -0700378 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800379 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700380 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800381
Jonathan Basseri930701e2015-06-11 20:56:43 -0700382 case EVENT_BIND_DEFAULT_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800383 case EVENT_FETCH_DEFAULT_TIMEOUT: {
384 loge("Bind/fetch time out from " + mPlatformCarrierConfigPackage);
Rambo Wang610fdf62021-03-08 21:37:11 -0800385 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT, getMessageToken(phoneId));
chen xuf60b3162019-05-01 21:31:05 -0700386 // If we attempted to bind to the app, but the service connection is null due to
387 // the race condition that clear config event happens before bind/fetch complete
388 // then config was cleared while we were waiting and we should not continue.
389 if (mServiceConnection[phoneId] != null) {
390 // If a ResponseReceiver callback is in the queue when this happens, we will
391 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700392 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700393 broadcastConfigChangedIntent(phoneId);
394 }
Nathan Harold1122e3d2021-01-22 15:45:24 -0800395 // Put a stub bundle in place so that the rest of the logic continues smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000396 mConfigFromDefaultApp[phoneId] = new PersistableBundle();
Jack Yue37dd262022-12-16 11:53:37 -0800397 updateSubscriptionDatabase(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700398 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700399 }
Jonathan Basseri930701e2015-06-11 20:56:43 -0700400
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800401 case EVENT_FETCH_DEFAULT_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700402 // If we attempted to bind to the app, but the service connection is null, then
403 // config was cleared while we were waiting and we should not continue.
404 if (!msg.getData().getBoolean("loaded_from_xml", false)
405 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800406 break;
407 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700408 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700409 if (carrierPackageName != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800410 logd("Found carrier config app: " + carrierPackageName);
Jordan Liu38a614c2019-03-20 15:01:17 -0700411 sendMessage(obtainMessage(EVENT_DO_FETCH_CARRIER, phoneId, -1));
Jonathan Basserib919e932015-05-27 16:53:08 +0000412 } else {
Jack Yue37dd262022-12-16 11:53:37 -0800413 updateSubscriptionDatabase(phoneId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700414 }
415 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700416 }
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700417
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800418 case EVENT_DO_FETCH_CARRIER: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700419 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700420 final PersistableBundle config =
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100421 restoreConfigFromXml(carrierPackageName, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700422 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800423 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700424 "Loaded config from XML. package="
425 + carrierPackageName
426 + " phoneId="
427 + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700428 mConfigFromCarrierApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700429 Message newMsg = obtainMessage(EVENT_FETCH_CARRIER_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700430 newMsg.getData().putBoolean("loaded_from_xml", true);
431 sendMessage(newMsg);
432 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700433 // No cached config, so fetch it from a carrier app.
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800434 if (carrierPackageName != null && bindToConfigPackage(carrierPackageName,
435 phoneId, EVENT_CONNECTED_TO_CARRIER)) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700436 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800437 obtainMessage(EVENT_BIND_CARRIER_TIMEOUT, phoneId, -1 /*arg2*/,
438 getMessageToken(phoneId)),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700439 BIND_TIMEOUT_MILLIS);
440 } else {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800441 // Put a stub bundle in place so that the rest of the logic continues
442 // smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000443 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
Jonathan Basseri65273c82017-07-25 15:08:42 -0700444 // Send broadcast if bind fails.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700445 broadcastConfigChangedIntent(phoneId);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800446 loge("Bind to carrier app: " + carrierPackageName + " fails");
Jack Yue37dd262022-12-16 11:53:37 -0800447 updateSubscriptionDatabase(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700448 }
449 }
450 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700451 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700452
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800453 case EVENT_CONNECTED_TO_CARRIER: {
Rambo Wang610fdf62021-03-08 21:37:11 -0800454 removeMessages(EVENT_BIND_CARRIER_TIMEOUT, getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700455 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800456 // If new service connection has been created, unbind.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700457 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700458 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800459 break;
460 }
chen xu02581692018-11-11 19:03:44 -0800461 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700462 // ResultReceiver callback will execute in this Handler's thread.
463 final ResultReceiver resultReceiver =
464 new ResultReceiver(this) {
465 @Override
466 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700467 unbindIfBound(mContext, conn, phoneId);
Rambo Wanga9d27a52021-04-09 16:17:33 -0700468 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT,
469 getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700470 // If new service connection has been created, this is stale.
471 if (mServiceConnection[phoneId] != conn) {
472 loge("Received response for stale request.");
473 return;
474 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700475 if (resultCode == RESULT_ERROR || resultData == null) {
476 // On error, abort config fetching.
chen xudb04c292019-03-26 17:01:15 -0700477 loge("Failed to get carrier config from carrier app: "
478 + getCarrierPackageForPhoneId(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700479 broadcastConfigChangedIntent(phoneId);
Jack Yue37dd262022-12-16 11:53:37 -0800480 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700481 return;
482 }
483 PersistableBundle config =
484 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100485 saveConfigToXml(getCarrierPackageForPhoneId(phoneId), "",
486 phoneId, carrierId, config);
Amit Mahajan304e92b2021-04-08 14:03:30 -0700487 if (config != null) {
488 mConfigFromCarrierApp[phoneId] = config;
489 } else {
490 logdWithLocalLog("Config from carrier app is null "
491 + "for phoneId " + phoneId);
492 // Put a stub bundle in place so that the rest of the logic
493 // continues smoothly.
494 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
495 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700496 sendMessage(
497 obtainMessage(
498 EVENT_FETCH_CARRIER_DONE, phoneId, -1));
499 }
500 };
501 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800502 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700503 ICarrierService carrierService =
504 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800505 carrierService.getCarrierConfig(phoneId, carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800506 logdWithLocalLog("Fetch config for carrier app: "
chen xudb04c292019-03-26 17:01:15 -0700507 + getCarrierPackageForPhoneId(phoneId)
508 + " carrierid: " + carrierId.toString());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700509 } catch (RemoteException e) {
510 loge("Failed to get carrier config: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700511 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700512 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800513 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700514 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800515 obtainMessage(EVENT_FETCH_CARRIER_TIMEOUT, phoneId, -1 /*arg2*/,
516 getMessageToken(phoneId)),
Jonathan Basseri65273c82017-07-25 15:08:42 -0700517 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800518 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700519 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800520
Jonathan Basseri930701e2015-06-11 20:56:43 -0700521 case EVENT_BIND_CARRIER_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800522 case EVENT_FETCH_CARRIER_TIMEOUT: {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800523 loge("Bind/fetch from carrier app timeout, package="
524 + getCarrierPackageForPhoneId(phoneId));
Rambo Wang610fdf62021-03-08 21:37:11 -0800525 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT, getMessageToken(phoneId));
chen xuf60b3162019-05-01 21:31:05 -0700526 // If we attempted to bind to the app, but the service connection is null due to
527 // the race condition that clear config event happens before bind/fetch complete
528 // then config was cleared while we were waiting and we should not continue.
529 if (mServiceConnection[phoneId] != null) {
530 // If a ResponseReceiver callback is in the queue when this happens, we will
531 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700532 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700533 broadcastConfigChangedIntent(phoneId);
534 }
Nathan Harold1122e3d2021-01-22 15:45:24 -0800535 // Put a stub bundle in place so that the rest of the logic continues smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000536 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
Jack Yue37dd262022-12-16 11:53:37 -0800537 updateSubscriptionDatabase(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700538 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700539 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800540 case EVENT_FETCH_CARRIER_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700541 // If we attempted to bind to the app, but the service connection is null, then
542 // config was cleared while we were waiting and we should not continue.
543 if (!msg.getData().getBoolean("loaded_from_xml", false)
544 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800545 break;
546 }
Jack Yue37dd262022-12-16 11:53:37 -0800547 updateSubscriptionDatabase(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800548 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700549 }
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700550
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800551 case EVENT_CHECK_SYSTEM_UPDATE: {
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700552 SharedPreferences sharedPrefs =
553 PreferenceManager.getDefaultSharedPreferences(mContext);
554 final String lastFingerprint = sharedPrefs.getString(KEY_FINGERPRINT, null);
555 if (!Build.FINGERPRINT.equals(lastFingerprint)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800556 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700557 "Build fingerprint changed. old: "
558 + lastFingerprint
559 + " new: "
560 + Build.FINGERPRINT);
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700561 clearCachedConfigForPackage(null);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700562 sharedPrefs
563 .edit()
564 .putString(KEY_FINGERPRINT, Build.FINGERPRINT)
565 .apply();
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700566 }
567 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700568 }
Nathan Harold48ac0972019-03-13 22:33:01 -0700569
570 case EVENT_SUBSCRIPTION_INFO_UPDATED:
571 broadcastConfigChangedIntent(phoneId);
572 break;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700573 case EVENT_MULTI_SIM_CONFIG_CHANGED:
574 onMultiSimConfigChanged();
575 break;
Jayachandran C645ec612020-01-10 10:30:25 -0800576
577 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG: {
578 PersistableBundle config =
579 restoreNoSimConfigFromXml(mPlatformCarrierConfigPackage);
580
581 if (config != null) {
582 logd("Loaded no SIM config from XML. package="
583 + mPlatformCarrierConfigPackage);
584 mNoSimConfig = config;
585 sendMessage(
586 obtainMessage(
587 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
588 phoneId, -1));
589 } else {
590 // No cached config, so fetch it from the default app.
591 if (bindToConfigPackage(
592 mPlatformCarrierConfigPackage,
593 phoneId,
594 EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG)) {
595 sendMessageDelayed(
596 obtainMessage(
597 EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
598 phoneId, -1), BIND_TIMEOUT_MILLIS);
599 } else {
600 broadcastConfigChangedIntent(phoneId, false);
601 // TODO: We *must* call unbindService even if bindService returns false.
602 // (And possibly if SecurityException was thrown.)
603 loge("binding to default app to fetch no SIM config: "
604 + mPlatformCarrierConfigPackage + " fails");
605 }
606 }
607 break;
608 }
609
610 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE: {
611 broadcastConfigChangedIntent(phoneId, false);
612 break;
613 }
614
615 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
616 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT: {
617 loge("Bind/fetch time out for no SIM config from "
618 + mPlatformCarrierConfigPackage);
619 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
620 // If we attempted to bind to the app, but the service connection is null due to
621 // the race condition that clear config event happens before bind/fetch complete
622 // then config was cleared while we were waiting and we should not continue.
623 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
624 // If a ResponseReceiver callback is in the queue when this happens, we will
625 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700626 unbindIfBoundForNoSimConfig(mContext,
627 mServiceConnectionForNoSimConfig[phoneId], phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800628 }
629 broadcastConfigChangedIntent(phoneId, false);
630 break;
631 }
632
633 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG: {
634 removeMessages(EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
635 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
636 // If new service connection has been created, unbind.
637 if (mServiceConnectionForNoSimConfig[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700638 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800639 break;
640 }
641
642 // ResultReceiver callback will execute in this Handler's thread.
643 final ResultReceiver resultReceiver =
644 new ResultReceiver(this) {
645 @Override
646 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700647 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800648 // If new service connection has been created, this is stale.
649 if (mServiceConnectionForNoSimConfig[phoneId] != conn) {
650 loge("Received response for stale request.");
651 return;
652 }
653 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
654 if (resultCode == RESULT_ERROR || resultData == null) {
655 // On error, abort config fetching.
656 loge("Failed to get no SIM carrier config");
657 return;
658 }
659 PersistableBundle config =
660 resultData.getParcelable(KEY_CONFIG_BUNDLE);
661 saveNoSimConfigToXml(mPlatformCarrierConfigPackage, config);
662 mNoSimConfig = config;
663 sendMessage(
664 obtainMessage(
665 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
666 phoneId, -1));
667 }
668 };
669 // Now fetch the config asynchronously from the ICarrierService.
670 try {
671 ICarrierService carrierService =
672 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800673 carrierService.getCarrierConfig(phoneId, null, resultReceiver);
Jayachandran C645ec612020-01-10 10:30:25 -0800674 logdWithLocalLog("Fetch no sim config from default app: "
675 + mPlatformCarrierConfigPackage);
676 } catch (RemoteException e) {
677 loge("Failed to get no sim carrier config from default app: " +
678 mPlatformCarrierConfigPackage + " err: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700679 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800680 break; // So we don't set a timeout.
681 }
682 sendMessageDelayed(
683 obtainMessage(
684 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
685 phoneId, -1), BIND_TIMEOUT_MILLIS);
686 break;
687 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800688 }
689 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700690 }
691
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000692 @NonNull private final Handler mHandler;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800693
694 /**
695 * Constructs a CarrierConfigLoader, registers it as a service, and registers a broadcast
696 * receiver for relevant events.
697 */
Rambo Wang7e3bc122021-03-23 09:24:38 -0700698 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000699 /* package */ CarrierConfigLoader(@NonNull Context context,
Jack Yue37dd262022-12-16 11:53:37 -0800700 //TODO: Remove SubscriptionInfoUpdater.
701 @Nullable SubscriptionInfoUpdater subscriptionInfoUpdater, @NonNull Looper looper) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800702 mContext = context;
Meng Wang33ad2bc2017-03-16 20:21:20 -0700703 mPlatformCarrierConfigPackage =
704 mContext.getString(R.string.platform_carrier_config_package);
Rambo Wang7e3bc122021-03-23 09:24:38 -0700705 mHandler = new ConfigHandler(looper);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800706
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000707 IntentFilter systemEventsFilter = new IntentFilter();
708 systemEventsFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
709 systemEventsFilter.addAction(TelephonyManager.ACTION_MULTI_SIM_CONFIG_CHANGED);
Rambo Wanga27fbe52022-04-12 19:09:07 +0000710 context.registerReceiver(mSystemBroadcastReceiver, systemEventsFilter);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800711
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000712 mNumPhones = TelephonyManager.from(context).getActiveModemCount();
713 mConfigFromDefaultApp = new PersistableBundle[mNumPhones];
714 mConfigFromCarrierApp = new PersistableBundle[mNumPhones];
715 mPersistentOverrideConfigs = new PersistableBundle[mNumPhones];
716 mOverrideConfigs = new PersistableBundle[mNumPhones];
Rambo Wang42026112021-04-07 20:57:28 +0000717 mNoSimConfig = new PersistableBundle();
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000718 mServiceConnection = new CarrierServiceConnection[mNumPhones];
719 mServiceBound = new boolean[mNumPhones];
720 mHasSentConfigChange = new boolean[mNumPhones];
721 mFromSystemUnlocked = new boolean[mNumPhones];
722 mServiceConnectionForNoSimConfig = new CarrierServiceConnection[mNumPhones];
723 mServiceBoundForNoSimConfig = new boolean[mNumPhones];
Rambo Wanga27fbe52022-04-12 19:09:07 +0000724 mCarrierServiceChangeCallbacks = new CarrierServiceChangeCallback[mNumPhones];
725 for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
726 mCarrierServiceChangeCallbacks[phoneId] = new CarrierServiceChangeCallback(phoneId);
727 TelephonyManager.from(context).registerCarrierPrivilegesCallback(phoneId,
728 new HandlerExecutor(mHandler), mCarrierServiceChangeCallbacks[phoneId]);
729 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800730 logd("CarrierConfigLoader has started");
Rambo Wang7e3bc122021-03-23 09:24:38 -0700731 mSubscriptionInfoUpdater = subscriptionInfoUpdater;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700732 mHandler.sendEmptyMessage(EVENT_CHECK_SYSTEM_UPDATE);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800733 }
734
735 /**
736 * Initialize the singleton CarrierConfigLoader instance.
737 *
738 * This is only done once, at startup, from {@link com.android.phone.PhoneApp#onCreate}.
739 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000740 @NonNull
741 /* package */ static CarrierConfigLoader init(@NonNull Context context) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800742 synchronized (CarrierConfigLoader.class) {
743 if (sInstance == null) {
Rambo Wang7e3bc122021-03-23 09:24:38 -0700744 sInstance = new CarrierConfigLoader(context,
745 PhoneFactory.getSubscriptionInfoUpdater(), Looper.myLooper());
Brad Ebingerfa6575f2021-05-04 00:29:50 +0000746 // Make this service available through ServiceManager.
747 TelephonyFrameworkInitializer.getTelephonyServiceManager()
748 .getCarrierConfigServiceRegisterer().register(sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800749 } else {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700750 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800751 }
752 return sInstance;
753 }
754 }
755
Rambo Wang7e3bc122021-03-23 09:24:38 -0700756 @VisibleForTesting
757 /* package */ void clearConfigForPhone(int phoneId, boolean fetchNoSimConfig) {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700758 /* Ignore clear configuration request if device is being shutdown. */
759 Phone phone = PhoneFactory.getPhone(phoneId);
760 if (phone != null) {
761 if (phone.isShuttingDown()) {
762 return;
763 }
764 }
765
766 mConfigFromDefaultApp[phoneId] = null;
767 mConfigFromCarrierApp[phoneId] = null;
768 mServiceConnection[phoneId] = null;
769 mHasSentConfigChange[phoneId] = false;
770
Jayachandran C645ec612020-01-10 10:30:25 -0800771 if (fetchNoSimConfig) {
772 // To fetch no SIM config
773 mHandler.sendMessage(
774 mHandler.obtainMessage(
775 EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG, phoneId, -1));
776 }
Malcolm Chen5ea18532019-10-24 19:55:44 -0700777 }
778
Jack Yue37dd262022-12-16 11:53:37 -0800779 private void updateSubscriptionDatabase(int phoneId) {
780 String configPackageName;
Nathan Harold48ac0972019-03-13 22:33:01 -0700781 PersistableBundle configToSend;
782 int carrierId = getSpecificCarrierIdForPhoneId(phoneId);
783 // Prefer the carrier privileged carrier app, but if there is not one, use the platform
784 // default carrier app.
785 if (mConfigFromCarrierApp[phoneId] != null) {
Jack Yue37dd262022-12-16 11:53:37 -0800786 configPackageName = getCarrierPackageForPhoneId(phoneId);
Nathan Harold48ac0972019-03-13 22:33:01 -0700787 configToSend = mConfigFromCarrierApp[phoneId];
788 } else {
Jack Yue37dd262022-12-16 11:53:37 -0800789 configPackageName = mPlatformCarrierConfigPackage;
Nathan Harold48ac0972019-03-13 22:33:01 -0700790 configToSend = mConfigFromDefaultApp[phoneId];
791 }
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700792
Malcolm Chenefafd1c2020-02-20 13:27:08 -0800793 if (configToSend == null) {
Rambo Wang42026112021-04-07 20:57:28 +0000794 configToSend = new PersistableBundle();
Malcolm Chenefafd1c2020-02-20 13:27:08 -0800795 }
796
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700797 // mOverrideConfigs is for testing. And it will override current configs.
798 PersistableBundle config = mOverrideConfigs[phoneId];
799 if (config != null) {
Torbjorn Eklund1050cb02018-11-16 14:05:38 +0100800 configToSend = new PersistableBundle(configToSend);
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700801 configToSend.putAll(config);
802 }
803
Jack Yue37dd262022-12-16 11:53:37 -0800804 if (PhoneFactory.isSubscriptionManagerServiceEnabled()) {
805 SubscriptionManagerService.getInstance().updateSubscriptionByCarrierConfig(
806 phoneId, configPackageName, configToSend,
807 () -> mHandler.obtainMessage(EVENT_SUBSCRIPTION_INFO_UPDATED, phoneId, -1)
808 .sendToTarget());
809 } else {
810 mSubscriptionInfoUpdater.updateSubscriptionByCarrierConfigAndNotifyComplete(
811 phoneId, configPackageName, configToSend,
812 mHandler.obtainMessage(EVENT_SUBSCRIPTION_INFO_UPDATED, phoneId, -1));
813 }
Nathan Harold48ac0972019-03-13 22:33:01 -0700814 }
815
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800816 private void broadcastConfigChangedIntent(int phoneId) {
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800817 broadcastConfigChangedIntent(phoneId, true);
818 }
819
820 private void broadcastConfigChangedIntent(int phoneId, boolean addSubIdExtra) {
rambowangd63ba342022-10-02 11:21:08 -0500821 int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
822 int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
823 int specificCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
824
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800825 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
Christopher Tate38f55eb2017-02-14 14:43:49 -0800826 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT |
chen xuf9db49f2019-03-31 23:04:42 -0700827 Intent.FLAG_RECEIVER_FOREGROUND);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800828 if (addSubIdExtra) {
rambowangd63ba342022-10-02 11:21:08 -0500829 int simApplicationState = getSimApplicationStateForPhone(phoneId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800830 // Include subId/carrier id extra only if SIM records are loaded
831 if (simApplicationState != TelephonyManager.SIM_STATE_UNKNOWN
832 && simApplicationState != TelephonyManager.SIM_STATE_NOT_READY) {
rambowangd63ba342022-10-02 11:21:08 -0500833 subId = SubscriptionManager.getSubscriptionId(phoneId);
834 carrierId = getCarrierIdForPhoneId(phoneId);
835 specificCarrierId = getSpecificCarrierIdForPhoneId(phoneId);
836 intent.putExtra(TelephonyManager.EXTRA_SPECIFIC_CARRIER_ID, specificCarrierId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800837 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, phoneId);
rambowangd63ba342022-10-02 11:21:08 -0500838 intent.putExtra(TelephonyManager.EXTRA_CARRIER_ID, carrierId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800839 }
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800840 }
Amit Mahajanb33bcda2018-01-24 12:56:44 -0800841 intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, phoneId);
Sarah Chin807d5c62020-03-30 17:21:09 -0700842 intent.putExtra(CarrierConfigManager.EXTRA_REBROADCAST_ON_UNLOCK,
843 mFromSystemUnlocked[phoneId]);
rambowangd63ba342022-10-02 11:21:08 -0500844
845 TelephonyRegistryManager trm = mContext.getSystemService(TelephonyRegistryManager.class);
846 // Unlike broadcast, we wouldn't notify registrants on carrier config change when device is
847 // unlocked. Only real carrier config change will send the notification to registrants.
848 if (trm != null && !mFromSystemUnlocked[phoneId]) {
849 trm.notifyCarrierConfigChanged(phoneId, subId, carrierId, specificCarrierId);
850 }
851
Meng Wang97a6a462020-01-23 16:22:16 -0800852 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
rambowangd63ba342022-10-02 11:21:08 -0500853
Jack Yu00ece8c2022-11-19 22:29:12 -0800854 if (SubscriptionManager.isValidSubscriptionId(subId)) {
855 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId + ", subId=" + subId);
Jack Yue9e95be2020-03-22 10:56:06 -0700856 } else {
857 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId);
858 }
Junda Liu03aad762017-07-21 13:32:17 -0700859 mHasSentConfigChange[phoneId] = true;
Sarah Chin807d5c62020-03-30 17:21:09 -0700860 mFromSystemUnlocked[phoneId] = false;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800861 }
862
rambowangd63ba342022-10-02 11:21:08 -0500863 private int getSimApplicationStateForPhone(int phoneId) {
864 int simApplicationState = TelephonyManager.SIM_STATE_UNKNOWN;
865 int subId = SubscriptionManager.getSubscriptionId(phoneId);
866 if (SubscriptionManager.isValidSubscriptionId(subId)) {
867 TelephonyManager telMgr = TelephonyManager.from(mContext)
868 .createForSubscriptionId(subId);
869 simApplicationState = telMgr.getSimApplicationState();
870 }
871 return simApplicationState;
872 }
873
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800874 /** Binds to the default or carrier config app. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000875 private boolean bindToConfigPackage(@NonNull String pkgName, int phoneId, int eventId) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800876 logdWithLocalLog("Binding to " + pkgName + " for phone " + phoneId);
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700877 Intent carrierService = new Intent(CarrierService.CARRIER_SERVICE_INTERFACE);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700878 carrierService.setPackage(pkgName);
Jayachandran C645ec612020-01-10 10:30:25 -0800879 CarrierServiceConnection serviceConnection = new CarrierServiceConnection(
880 phoneId, pkgName, eventId);
881 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
882 mServiceConnectionForNoSimConfig[phoneId] = serviceConnection;
883 } else {
884 mServiceConnection[phoneId] = serviceConnection;
885 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800886 try {
Jayachandran C645ec612020-01-10 10:30:25 -0800887 if (mContext.bindService(carrierService, serviceConnection,
Jordan Liu178430d2020-02-10 14:32:15 -0800888 Context.BIND_AUTO_CREATE)) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700889 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
890 mServiceBoundForNoSimConfig[phoneId] = true;
891 } else {
892 mServiceBound[phoneId] = true;
893 }
Jordan Liu178430d2020-02-10 14:32:15 -0800894 return true;
895 } else {
896 return false;
897 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800898 } catch (SecurityException ex) {
899 return false;
900 }
901 }
902
Rambo Wang7e3bc122021-03-23 09:24:38 -0700903 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000904 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -0700905 /* package */ CarrierIdentifier getCarrierIdentifierForPhoneId(int phoneId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800906 String mcc = "";
907 String mnc = "";
908 String imsi = "";
909 String gid1 = "";
910 String gid2 = "";
911 String spn = TelephonyManager.from(mContext).getSimOperatorNameForPhone(phoneId);
912 String simOperator = TelephonyManager.from(mContext).getSimOperatorNumericForPhone(phoneId);
chen xu02581692018-11-11 19:03:44 -0800913 int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
chen xua31f22b2019-03-06 15:28:50 -0800914 int specificCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
Jonathan Basseri1fa437c2015-04-20 11:08:18 -0700915 // A valid simOperator should be 5 or 6 digits, depending on the length of the MNC.
916 if (simOperator != null && simOperator.length() >= 3) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800917 mcc = simOperator.substring(0, 3);
918 mnc = simOperator.substring(3);
919 }
920 Phone phone = PhoneFactory.getPhone(phoneId);
921 if (phone != null) {
922 imsi = phone.getSubscriberId();
923 gid1 = phone.getGroupIdLevel1();
Junda Liu73183532015-05-14 13:55:40 -0700924 gid2 = phone.getGroupIdLevel2();
chen xu02581692018-11-11 19:03:44 -0800925 carrierId = phone.getCarrierId();
chen xua31f22b2019-03-06 15:28:50 -0800926 specificCarrierId = phone.getSpecificCarrierId();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800927 }
chen xua31f22b2019-03-06 15:28:50 -0800928 return new CarrierIdentifier(mcc, mnc, spn, imsi, gid1, gid2, carrierId, specificCarrierId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800929 }
930
Rambo Wangf7c214a2022-03-17 12:36:22 -0700931 /** Returns the package name of a privileged carrier app, or null if there is none. */
Nathan Harold1122e3d2021-01-22 15:45:24 -0800932 @Nullable
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700933 private String getCarrierPackageForPhoneId(int phoneId) {
Nazanin1adf4562021-03-29 15:35:30 -0700934 final long token = Binder.clearCallingIdentity();
935 try {
Rambo Wangf7c214a2022-03-17 12:36:22 -0700936 return TelephonyManager.from(mContext)
937 .getCarrierServicePackageNameForLogicalSlot(phoneId);
Nazanin1adf4562021-03-29 15:35:30 -0700938 } finally {
939 Binder.restoreCallingIdentity(token);
940 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700941 }
942
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000943 @Nullable
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700944 private String getIccIdForPhoneId(int phoneId) {
945 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
946 return null;
947 }
948 Phone phone = PhoneFactory.getPhone(phoneId);
949 if (phone == null) {
950 return null;
951 }
952 return phone.getIccSerialNumber();
953 }
954
chen xu02581692018-11-11 19:03:44 -0800955 /**
chen xua31f22b2019-03-06 15:28:50 -0800956 * Get the sim specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}
chen xu02581692018-11-11 19:03:44 -0800957 */
chen xua31f22b2019-03-06 15:28:50 -0800958 private int getSpecificCarrierIdForPhoneId(int phoneId) {
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700959 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
chen xu02581692018-11-11 19:03:44 -0800960 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700961 }
962 Phone phone = PhoneFactory.getPhone(phoneId);
963 if (phone == null) {
chen xu02581692018-11-11 19:03:44 -0800964 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700965 }
chen xua31f22b2019-03-06 15:28:50 -0800966 return phone.getSpecificCarrierId();
chen xu02581692018-11-11 19:03:44 -0800967 }
968
969 /**
970 * Get the sim carrier id {@link TelephonyManager#getSimCarrierId() }
971 */
972 private int getCarrierIdForPhoneId(int phoneId) {
973 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
974 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700975 }
chen xu02581692018-11-11 19:03:44 -0800976 Phone phone = PhoneFactory.getPhone(phoneId);
977 if (phone == null) {
978 return TelephonyManager.UNKNOWN_CARRIER_ID;
979 }
980 return phone.getCarrierId();
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700981 }
982
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700983 /**
984 * Writes a bundle to an XML file.
985 *
chen xu02581692018-11-11 19:03:44 -0800986 * The bundle will be written to a file named after the package name, ICCID and
chen xua31f22b2019-03-06 15:28:50 -0800987 * specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}. the same carrier
chen xu02581692018-11-11 19:03:44 -0800988 * should have a single copy of XML file named after carrier id. However, it's still possible
989 * that platform doesn't recognize the current sim carrier, we will use iccid + carrierid as
990 * the canonical file name. carrierid can also handle the cases SIM OTA resolves to different
991 * carrier while iccid remains the same.
992 *
993 * The file can be restored later with {@link @restoreConfigFromXml}. The XML output will
994 * include the bundle and the current version of the specified package.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700995 *
996 * In case of errors or invalid input, no file will be written.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700997 *
Jayachandran C645ec612020-01-10 10:30:25 -0800998 * @param packageName the name of the package from which we fetched this bundle.
999 * @param extraString An extra string to be used in the XML file name.
1000 * @param phoneId the phone ID.
1001 * @param carrierId contains all carrier-identifying information.
1002 * @param config the bundle to be written. Null will be treated as an empty bundle.
1003 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001004 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001005 private void saveConfigToXml(@Nullable String packageName, @NonNull String extraString,
1006 int phoneId, @Nullable CarrierIdentifier carrierId, @NonNull PersistableBundle config,
1007 boolean isNoSimConfig) {
Jayachandran C645ec612020-01-10 10:30:25 -08001008 if (packageName == null) {
1009 loge("Cannot save config with null packageName");
Yuchen Dongc15afed2018-04-26 17:05:22 +08001010 return;
1011 }
1012
Jayachandran C645ec612020-01-10 10:30:25 -08001013 String fileName;
1014 if (isNoSimConfig) {
1015 fileName = getFilenameForNoSimConfig(packageName);
1016 } else {
Jack Yuf5badd92022-12-08 00:50:53 -08001017 if (TelephonyManager.getSimStateForSlotIndex(phoneId)
Jayachandran C645ec612020-01-10 10:30:25 -08001018 != TelephonyManager.SIM_STATE_LOADED) {
1019 loge("Skip save config because SIM records are not loaded.");
1020 return;
1021 }
1022
1023 final String iccid = getIccIdForPhoneId(phoneId);
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001024 final int cid = carrierId != null ? carrierId.getSpecificCarrierId()
1025 : TelephonyManager.UNKNOWN_CARRIER_ID;
Jayachandran C645ec612020-01-10 10:30:25 -08001026 if (iccid == null) {
1027 loge("Cannot save config with null iccid.");
1028 return;
1029 }
1030 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001031 }
Jayachandran C645ec612020-01-10 10:30:25 -08001032
Junda Liu02596502016-11-15 13:46:43 -08001033 // b/32668103 Only save to file if config isn't empty.
1034 // In case of failure, not caching an empty bundle will
1035 // try loading config again on next power on or sim loaded.
1036 // Downside is for genuinely empty bundle, will bind and load
1037 // on every power on.
1038 if (config == null || config.isEmpty()) {
1039 return;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001040 }
1041
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001042 final String version = getPackageVersion(packageName);
1043 if (version == null) {
1044 loge("Failed to get package version for: " + packageName);
1045 return;
1046 }
1047
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001048 logdWithLocalLog(
1049 "Save config to xml, packagename: " + packageName + " phoneId: " + phoneId);
chen xudb04c292019-03-26 17:01:15 -07001050
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001051 FileOutputStream outFile = null;
1052 try {
Jayachandran C645ec612020-01-10 10:30:25 -08001053 outFile = new FileOutputStream(new File(mContext.getFilesDir(), fileName));
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001054 config.putString(KEY_VERSION, version);
1055 config.writeToStream(outFile);
1056 outFile.flush();
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001057 outFile.close();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001058 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001059 loge(e.toString());
1060 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001061 }
1062
Rambo Wang7e3bc122021-03-23 09:24:38 -07001063 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001064 /* package */ void saveConfigToXml(@Nullable String packageName, @NonNull String extraString,
1065 int phoneId, @NonNull CarrierIdentifier carrierId, @NonNull PersistableBundle config) {
Jayachandran C645ec612020-01-10 10:30:25 -08001066 saveConfigToXml(packageName, extraString, phoneId, carrierId, config, false);
1067 }
1068
Rambo Wang7e3bc122021-03-23 09:24:38 -07001069 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001070 /* package */ void saveNoSimConfigToXml(@Nullable String packageName,
1071 @NonNull PersistableBundle config) {
Jayachandran C645ec612020-01-10 10:30:25 -08001072 saveConfigToXml(packageName, "", -1, null, config, true);
1073 }
1074
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001075 /**
1076 * Reads a bundle from an XML file.
1077 *
1078 * This restores a bundle that was written with {@link #saveConfigToXml}. This returns the saved
Yuchen Dongc15afed2018-04-26 17:05:22 +08001079 * config bundle for the given package and phone ID.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001080 *
1081 * In case of errors, or if the saved config is from a different package version than the
1082 * current version, then null will be returned.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001083 *
Jayachandran C645ec612020-01-10 10:30:25 -08001084 * @param packageName the name of the package from which we fetched this bundle.
1085 * @param extraString An extra string to be used in the XML file name.
1086 * @param phoneId the phone ID.
1087 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001088 * @return the bundle from the XML file. Returns null if there is no saved config, the saved
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001089 * version does not match, or reading config fails.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001090 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001091 @Nullable
1092 private PersistableBundle restoreConfigFromXml(@Nullable String packageName,
1093 @NonNull String extraString, int phoneId, boolean isNoSimConfig) {
Jayachandran C645ec612020-01-10 10:30:25 -08001094 if (packageName == null) {
1095 loge("Cannot restore config with null packageName");
1096 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001097 final String version = getPackageVersion(packageName);
1098 if (version == null) {
1099 loge("Failed to get package version for: " + packageName);
1100 return null;
1101 }
Yuchen Dongc15afed2018-04-26 17:05:22 +08001102
Jayachandran C645ec612020-01-10 10:30:25 -08001103 String fileName;
arunvoddu664c36a2021-10-11 20:09:28 +00001104 String iccid = null;
Jayachandran C645ec612020-01-10 10:30:25 -08001105 if (isNoSimConfig) {
1106 fileName = getFilenameForNoSimConfig(packageName);
1107 } else {
Jack Yuf5badd92022-12-08 00:50:53 -08001108 if (TelephonyManager.getSimStateForSlotIndex(phoneId)
Jayachandran C645ec612020-01-10 10:30:25 -08001109 != TelephonyManager.SIM_STATE_LOADED) {
1110 loge("Skip restore config because SIM records are not loaded.");
1111 return null;
1112 }
1113
arunvoddu664c36a2021-10-11 20:09:28 +00001114 iccid = getIccIdForPhoneId(phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -08001115 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1116 if (iccid == null) {
1117 loge("Cannot restore config with null iccid.");
1118 return null;
1119 }
1120 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001121 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001122
1123 PersistableBundle restoredBundle = null;
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001124 File file = null;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001125 FileInputStream inFile = null;
1126 try {
Jayachandran C645ec612020-01-10 10:30:25 -08001127 file = new File(mContext.getFilesDir(),fileName);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001128 inFile = new FileInputStream(file);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001129
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001130 restoredBundle = PersistableBundle.readFromStream(inFile);
1131 String savedVersion = restoredBundle.getString(KEY_VERSION);
1132 restoredBundle.remove(KEY_VERSION);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001133
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001134 if (!version.equals(savedVersion)) {
1135 loge("Saved version mismatch: " + version + " vs " + savedVersion);
1136 restoredBundle = null;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001137 }
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001138
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001139 inFile.close();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001140 } catch (FileNotFoundException e) {
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001141 // Missing file is normal occurrence that might occur with a new sim or when restoring
1142 // an override file during boot and should not be treated as an error.
arunvoddu664c36a2021-10-11 20:09:28 +00001143 if (file != null) {
1144 if (isNoSimConfig) {
1145 logd("File not found: " + file.getPath());
1146 } else {
1147 String filePath = file.getPath();
1148 filePath = getFilePathForLogging(filePath, iccid);
1149 logd("File not found : " + filePath);
1150 }
1151 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001152 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001153 loge(e.toString());
1154 }
1155
1156 return restoredBundle;
1157 }
1158
arunvoddu664c36a2021-10-11 20:09:28 +00001159 /**
1160 * This method will mask most part of iccid in the filepath for logging on userbuild
1161 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001162 @NonNull
1163 private String getFilePathForLogging(@Nullable String filePath, @Nullable String iccid) {
arunvoddu664c36a2021-10-11 20:09:28 +00001164 // If loggable then return with actual file path
1165 if (Rlog.isLoggable(LOG_TAG, Log.VERBOSE)) {
1166 return filePath;
1167 }
1168 String path = filePath;
1169 int length = (iccid != null) ? iccid.length() : 0;
1170 if (length > 5 && filePath != null) {
1171 path = filePath.replace(iccid.substring(5), "***************");
1172 }
1173 return path;
1174 }
1175
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001176 @Nullable
1177 private PersistableBundle restoreConfigFromXml(@Nullable String packageName,
1178 @NonNull String extraString, int phoneId) {
Jayachandran C645ec612020-01-10 10:30:25 -08001179 return restoreConfigFromXml(packageName, extraString, phoneId, false);
1180 }
1181
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001182 @Nullable
1183 private PersistableBundle restoreNoSimConfigFromXml(@Nullable String packageName) {
Jayachandran C645ec612020-01-10 10:30:25 -08001184 return restoreConfigFromXml(packageName, "", -1, true);
1185 }
1186
Junda Liu8a8a53a2015-05-15 16:19:57 -07001187 /**
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001188 * Clears cached carrier config.
1189 * This deletes all saved XML files associated with the given package name. If packageName is
1190 * null, then it deletes all saved XML files.
1191 *
1192 * @param packageName the name of a carrier package, or null if all cached config should be
1193 * cleared.
1194 * @return true iff one or more files were deleted.
Junda Liu8a8a53a2015-05-15 16:19:57 -07001195 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001196 private boolean clearCachedConfigForPackage(@Nullable final String packageName) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001197 File dir = mContext.getFilesDir();
1198 File[] packageFiles = dir.listFiles(new FilenameFilter() {
1199 public boolean accept(File dir, String filename) {
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001200 if (packageName != null) {
1201 return filename.startsWith("carrierconfig-" + packageName + "-");
1202 } else {
1203 return filename.startsWith("carrierconfig-");
1204 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001205 }
1206 });
Junda Liu8a8a53a2015-05-15 16:19:57 -07001207 if (packageFiles == null || packageFiles.length < 1) return false;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001208 for (File f : packageFiles) {
arunvoddub7c6e8e2022-09-05 15:48:06 +00001209 logd("Deleting " + getFilePathForLogging(f.getName()));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001210 f.delete();
1211 }
Junda Liu8a8a53a2015-05-15 16:19:57 -07001212 return true;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001213 }
1214
arunvoddub7c6e8e2022-09-05 15:48:06 +00001215 private String getFilePathForLogging(String filePath) {
1216 if (!TextUtils.isEmpty(filePath)) {
1217 String[] fileTokens = filePath.split("-");
1218 if (fileTokens != null && fileTokens.length > 2) {
1219 String iccid = fileTokens[fileTokens.length -2];
1220 return getFilePathForLogging(filePath, iccid);
1221 }
1222 return filePath;
1223 }
1224 return filePath;
1225 }
1226
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001227 /** Builds a canonical file name for a config file. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001228 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001229 private static String getFilenameForConfig(
1230 @NonNull String packageName, @NonNull String extraString,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001231 @NonNull String iccid, int cid) {
chen xu02581692018-11-11 19:03:44 -08001232 // the same carrier should have a single copy of XML file named after carrier id.
1233 // However, it's still possible that platform doesn't recognize the current sim carrier,
1234 // we will use iccid + carrierid as the canonical file name. carrierid can also handle the
1235 // cases SIM OTA resolves to different carrier while iccid remains the same.
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001236 return "carrierconfig-" + packageName + extraString + "-" + iccid + "-" + cid + ".xml";
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001237 }
1238
Jayachandran C645ec612020-01-10 10:30:25 -08001239 /** Builds a canonical file name for no SIM config file. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001240 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001241 private String getFilenameForNoSimConfig(@NonNull String packageName) {
1242 return "carrierconfig-" + packageName + "-" + "nosim" + ".xml";
1243 }
1244
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001245 /** Return the current version code of a package, or null if the name is not found. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001246 @Nullable
1247 private String getPackageVersion(@NonNull String packageName) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001248 try {
1249 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
Dianne Hackbornb76ab202017-11-28 17:44:50 -08001250 return Long.toString(info.getLongVersionCode());
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001251 } catch (PackageManager.NameNotFoundException e) {
1252 return null;
1253 }
1254 }
1255
Jonathan Basseri65273c82017-07-25 15:08:42 -07001256 /**
1257 * Read up to date config.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001258 *
1259 * This reads config bundles for the given phoneId. That means getting the latest bundle from
1260 * the default app and a privileged carrier app, if present. This will not bind to an app if we
1261 * have a saved config file to use instead.
1262 */
1263 private void updateConfigForPhoneId(int phoneId) {
Jonathan Basseri65273c82017-07-25 15:08:42 -07001264 mHandler.sendMessage(mHandler.obtainMessage(EVENT_DO_FETCH_DEFAULT, phoneId, -1));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001265 }
1266
Malcolm Chen5ea18532019-10-24 19:55:44 -07001267 private void onMultiSimConfigChanged() {
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001268 int oldNumPhones = mNumPhones;
1269 mNumPhones = TelephonyManager.from(mContext).getActiveModemCount();
1270 if (mNumPhones == oldNumPhones) {
1271 return;
1272 }
1273 logdWithLocalLog("mNumPhones change from " + oldNumPhones + " to " + mNumPhones);
1274
Rambo Wanga27fbe52022-04-12 19:09:07 +00001275 // If DS -> SS switch, release the resources BEFORE truncating the arrays to avoid leaking
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001276 for (int phoneId = mNumPhones; phoneId < oldNumPhones; phoneId++) {
1277 if (mServiceConnection[phoneId] != null) {
1278 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
1279 }
1280 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
1281 unbindIfBoundForNoSimConfig(mContext, mServiceConnectionForNoSimConfig[phoneId],
1282 phoneId);
1283 }
1284 }
1285
Rambo Wanga27fbe52022-04-12 19:09:07 +00001286 // The phone to slot mapping may change, unregister here and re-register callbacks later
1287 for (int phoneId = 0; phoneId < oldNumPhones; phoneId++) {
1288 if (mCarrierServiceChangeCallbacks[phoneId] != null) {
1289 TelephonyManager.from(mContext).unregisterCarrierPrivilegesCallback(
1290 mCarrierServiceChangeCallbacks[phoneId]);
1291 }
1292 }
1293
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001294 // Copy the original arrays, truncate or padding with zeros (if necessary) to new length
1295 mConfigFromDefaultApp = Arrays.copyOf(mConfigFromDefaultApp, mNumPhones);
1296 mConfigFromCarrierApp = Arrays.copyOf(mConfigFromCarrierApp, mNumPhones);
1297 mPersistentOverrideConfigs = Arrays.copyOf(mPersistentOverrideConfigs, mNumPhones);
1298 mOverrideConfigs = Arrays.copyOf(mOverrideConfigs, mNumPhones);
1299 mServiceConnection = Arrays.copyOf(mServiceConnection, mNumPhones);
1300 mServiceConnectionForNoSimConfig =
1301 Arrays.copyOf(mServiceConnectionForNoSimConfig, mNumPhones);
1302 mServiceBound = Arrays.copyOf(mServiceBound, mNumPhones);
1303 mServiceBoundForNoSimConfig = Arrays.copyOf(mServiceBoundForNoSimConfig, mNumPhones);
1304 mHasSentConfigChange = Arrays.copyOf(mHasSentConfigChange, mNumPhones);
1305 mFromSystemUnlocked = Arrays.copyOf(mFromSystemUnlocked, mNumPhones);
Rambo Wanga27fbe52022-04-12 19:09:07 +00001306 mCarrierServiceChangeCallbacks = Arrays.copyOf(mCarrierServiceChangeCallbacks, mNumPhones);
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001307
Rambo Wanga27fbe52022-04-12 19:09:07 +00001308 // Load the config for all the phones and re-register callback AFTER padding the arrays.
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001309 for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
1310 updateConfigForPhoneId(phoneId);
Rambo Wanga27fbe52022-04-12 19:09:07 +00001311 mCarrierServiceChangeCallbacks[phoneId] = new CarrierServiceChangeCallback(phoneId);
1312 TelephonyManager.from(mContext).registerCarrierPrivilegesCallback(phoneId,
1313 new HandlerExecutor(mHandler), mCarrierServiceChangeCallbacks[phoneId]);
Malcolm Chen5ea18532019-10-24 19:55:44 -07001314 }
1315 }
1316
Hall Liu506724b2018-10-22 18:16:14 -07001317 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001318 @NonNull
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001319 public PersistableBundle getConfigForSubId(int subscriptionId, @NonNull String callingPackage) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001320 return getConfigForSubIdWithFeature(subscriptionId, callingPackage, null);
Philip P. Moltmann9797cbb2020-01-07 13:45:00 -08001321 }
1322
1323 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001324 @NonNull
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001325 public PersistableBundle getConfigForSubIdWithFeature(int subscriptionId,
1326 @NonNull String callingPackage, @Nullable String callingFeatureId) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001327 if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(mContext, subscriptionId,
1328 callingPackage, callingFeatureId, "getCarrierConfig")) {
Rambo Wang42026112021-04-07 20:57:28 +00001329 return new PersistableBundle();
Amit Mahajan40b3fa52015-07-14 10:27:19 -07001330 }
Jeff Davidsona8e4e242018-03-15 17:16:18 -07001331
Rambo Wangd2b004b2021-03-30 10:10:23 -07001332 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001333 PersistableBundle retConfig = CarrierConfigManager.getDefaultConfig();
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001334 if (SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001335 PersistableBundle config = mConfigFromDefaultApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001336 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001337 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001338 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001339 config = mConfigFromCarrierApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001340 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001341 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001342 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001343 config = mPersistentOverrideConfigs[phoneId];
1344 if (config != null) {
1345 retConfig.putAll(config);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001346 }
Hall Liu506724b2018-10-22 18:16:14 -07001347 config = mOverrideConfigs[phoneId];
1348 if (config != null) {
1349 retConfig.putAll(config);
Hall Liu506724b2018-10-22 18:16:14 -07001350 }
Nathan Harold1122e3d2021-01-22 15:45:24 -08001351 // Ignore the theoretical case of the default app not being present since that won't
1352 // work in CarrierConfigLoader today.
1353 final boolean allConfigsApplied =
1354 (mConfigFromCarrierApp[phoneId] != null
1355 || getCarrierPackageForPhoneId(phoneId) == null)
1356 && mConfigFromDefaultApp[phoneId] != null;
1357 retConfig.putBoolean(
1358 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, allConfigsApplied);
Jayachandran C645ec612020-01-10 10:30:25 -08001359 } else {
1360 if (mNoSimConfig != null) {
1361 retConfig.putAll(mNoSimConfig);
1362 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001363 }
1364 return retConfig;
1365 }
1366
1367 @Override
rambowang14757c22022-10-03 11:54:56 -05001368 @NonNull
1369 public PersistableBundle getConfigSubsetForSubIdWithFeature(int subscriptionId,
1370 @NonNull String callingPackage, @Nullable String callingFeatureId,
1371 @NonNull String[] keys) {
1372 Objects.requireNonNull(callingPackage, "Calling package must be non-null");
1373 Objects.requireNonNull(keys, "Config keys must be non-null");
1374 enforceCallerIsSystemOrRequestingPackage(callingPackage);
1375
1376 // Permission check is performed inside and an empty bundle will return on failure.
1377 // No SecurityException thrown here since most clients expect to retrieve the overridden
1378 // value if present or use default one if not
1379 PersistableBundle allConfigs = getConfigForSubIdWithFeature(subscriptionId, callingPackage,
1380 callingFeatureId);
1381 if (allConfigs.isEmpty()) {
1382 return allConfigs;
1383 }
1384 for (String key : keys) {
1385 Objects.requireNonNull(key, "Config key must be non-null");
rambowang14757c22022-10-03 11:54:56 -05001386 }
1387
1388 PersistableBundle configSubset = new PersistableBundle(
1389 keys.length + CONFIG_SUBSET_METADATA_KEYS.length);
1390 for (String carrierConfigKey : keys) {
1391 Object value = allConfigs.get(carrierConfigKey);
rambowangb49e90f2022-12-13 18:29:06 -06001392 if (value == null) {
1393 // Filter out keys without values.
1394 // In history, many AOSP or OEMs/carriers private configs didn't provide default
1395 // values. We have to continue supporting them for now. See b/261776046 for details.
1396 continue;
1397 }
rambowang14757c22022-10-03 11:54:56 -05001398 // Config value itself could be PersistableBundle which requires different API to put
1399 if (value instanceof PersistableBundle) {
1400 configSubset.putPersistableBundle(carrierConfigKey, (PersistableBundle) value);
1401 } else {
1402 configSubset.putObject(carrierConfigKey, value);
1403 }
1404 }
1405
1406 // Configs in CONFIG_SUBSET_ALWAYS_INCLUDED_KEYS should always be included
1407 for (String generalKey : CONFIG_SUBSET_METADATA_KEYS) {
1408 configSubset.putObject(generalKey, allConfigs.get(generalKey));
1409 }
1410
1411 return configSubset;
1412 }
1413
1414 @Override
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001415 public void overrideConfig(int subscriptionId, @Nullable PersistableBundle overrides,
1416 boolean persistent) {
Hall Liu506724b2018-10-22 18:16:14 -07001417 mContext.enforceCallingOrSelfPermission(
1418 android.Manifest.permission.MODIFY_PHONE_STATE, null);
1419 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1420 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001421 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
Rambo Wangd2b004b2021-03-30 10:10:23 -07001422 throw new IllegalArgumentException(
1423 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
Hall Liu506724b2018-10-22 18:16:14 -07001424 }
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001425 // Post to run on handler thread on which all states should be confined.
1426 mHandler.post(() -> {
1427 overrideConfig(mOverrideConfigs, phoneId, overrides);
Hall Liu506724b2018-10-22 18:16:14 -07001428
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001429 if (persistent) {
1430 overrideConfig(mPersistentOverrideConfigs, phoneId, overrides);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001431
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001432 if (overrides != null) {
1433 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
1434 saveConfigToXml(mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION,
1435 phoneId,
1436 carrierId, mPersistentOverrideConfigs[phoneId]);
1437 } else {
1438 final String iccid = getIccIdForPhoneId(phoneId);
1439 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1440 String fileName = getFilenameForConfig(mPlatformCarrierConfigPackage,
1441 OVERRIDE_PACKAGE_ADDITION, iccid, cid);
1442 File fileToDelete = new File(mContext.getFilesDir(), fileName);
1443 fileToDelete.delete();
1444 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001445 }
Jack Yue37dd262022-12-16 11:53:37 -08001446 updateSubscriptionDatabase(phoneId);
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001447 });
Hall Liu506724b2018-10-22 18:16:14 -07001448 }
1449
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001450 private void overrideConfig(@NonNull PersistableBundle[] currentOverrides, int phoneId,
1451 @Nullable PersistableBundle overrides) {
1452 if (overrides == null) {
Rambo Wang42026112021-04-07 20:57:28 +00001453 currentOverrides[phoneId] = new PersistableBundle();
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001454 } else if (currentOverrides[phoneId] == null) {
1455 currentOverrides[phoneId] = overrides;
1456 } else {
1457 currentOverrides[phoneId].putAll(overrides);
1458 }
1459 }
1460
Hall Liu506724b2018-10-22 18:16:14 -07001461 @Override
Rambo Wangd2b004b2021-03-30 10:10:23 -07001462 public void notifyConfigChangedForSubId(int subscriptionId) {
Jordan Liud7d57fe2019-04-16 12:29:43 -07001463 // Requires the calling app to be either a carrier privileged app for this subId or
Junda Liufbd2bcb2016-06-15 11:15:42 -07001464 // system privileged app with MODIFY_PHONE_STATE permission.
Rambo Wangd2b004b2021-03-30 10:10:23 -07001465 TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(mContext,
1466 subscriptionId, "Require carrier privileges or MODIFY_PHONE_STATE permission.");
1467
1468 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1469 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
1470 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
1471 throw new IllegalArgumentException(
1472 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
1473 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001474
1475 // This method should block until deleting has completed, so that an error which prevents us
1476 // from clearing the cache is passed back to the carrier app. With the files successfully
1477 // deleted, this can return and we will eventually bind to the carrier app.
Jordan Liud7d57fe2019-04-16 12:29:43 -07001478 String callingPackageName = mContext.getPackageManager().getNameForUid(
1479 Binder.getCallingUid());
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001480 clearCachedConfigForPackage(callingPackageName);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001481 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001482 }
1483
1484 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001485 public void updateConfigForPhoneId(int phoneId, @NonNull String simState) {
Junda Liu1f2b34d2015-06-18 15:26:56 -07001486 mContext.enforceCallingOrSelfPermission(
1487 android.Manifest.permission.MODIFY_PHONE_STATE, null);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001488 logdWithLocalLog("Update config for phoneId: " + phoneId + " simState: " + simState);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001489 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001490 throw new IllegalArgumentException("Invalid phoneId: " + phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001491 }
1492 // requires Java 7 for switch on string.
1493 switch (simState) {
1494 case IccCardConstants.INTENT_VALUE_ICC_ABSENT:
1495 case IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR:
Junda Liu6f5fddf2016-05-24 16:14:41 -07001496 case IccCardConstants.INTENT_VALUE_ICC_CARD_RESTRICTED:
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001497 case IccCardConstants.INTENT_VALUE_ICC_UNKNOWN:
Malcolm Chendb66de12019-12-09 18:57:07 -08001498 case IccCardConstants.INTENT_VALUE_ICC_NOT_READY:
Junda Liu9f2d2712015-05-15 14:22:45 -07001499 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CLEAR_CONFIG, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001500 break;
1501 case IccCardConstants.INTENT_VALUE_ICC_LOADED:
1502 case IccCardConstants.INTENT_VALUE_ICC_LOCKED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001503 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001504 break;
1505 }
1506 }
1507
Junda Liu43d723a2015-05-12 17:23:45 -07001508 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001509 @NonNull
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001510 public String getDefaultCarrierServicePackageName() {
Shuo Qianefdb7962019-12-19 15:54:27 -08001511 mContext.enforceCallingOrSelfPermission(
1512 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
1513 "getDefaultCarrierServicePackageName");
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001514 return mPlatformCarrierConfigPackage;
1515 }
1516
Rambo Wang7e3bc122021-03-23 09:24:38 -07001517 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001518 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -07001519 /* package */ Handler getHandler() {
1520 return mHandler;
1521 }
1522
1523 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001524 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001525 /* package */ PersistableBundle getConfigFromDefaultApp(int phoneId) {
1526 return mConfigFromDefaultApp[phoneId];
1527 }
1528
1529 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001530 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001531 /* package */ PersistableBundle getConfigFromCarrierApp(int phoneId) {
1532 return mConfigFromCarrierApp[phoneId];
1533 }
1534
1535 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001536 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -07001537 /* package */ PersistableBundle getNoSimConfig() {
1538 return mNoSimConfig;
1539 }
1540
1541 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001542 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001543 /* package */ PersistableBundle getOverrideConfig(int phoneId) {
1544 return mOverrideConfigs[phoneId];
1545 }
1546
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001547 // TODO(b/185129900): always call unbindService after bind, no matter if it succeeded
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001548 private void unbindIfBound(@NonNull Context context, @NonNull CarrierServiceConnection conn,
Rambo Wangb0f3e2f2021-10-28 12:40:12 -07001549 int phoneId) {
1550 if (mServiceBound[phoneId]) {
1551 mServiceBound[phoneId] = false;
1552 context.unbindService(conn);
1553 }
1554 }
1555
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001556 private void unbindIfBoundForNoSimConfig(@NonNull Context context,
1557 @NonNull CarrierServiceConnection conn, int phoneId) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -07001558 if (mServiceBoundForNoSimConfig[phoneId]) {
1559 mServiceBoundForNoSimConfig[phoneId] = false;
Jayachandran C645ec612020-01-10 10:30:25 -08001560 context.unbindService(conn);
1561 }
1562 }
1563
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001564 /**
Rambo Wang610fdf62021-03-08 21:37:11 -08001565 * Returns a boxed Integer object for phoneId, services as message token to distinguish messages
1566 * with same code when calling {@link Handler#removeMessages(int, Object)}.
1567 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001568 @NonNull
Rambo Wang610fdf62021-03-08 21:37:11 -08001569 private Integer getMessageToken(int phoneId) {
1570 if (phoneId < -128 || phoneId > 127) {
1571 throw new IllegalArgumentException("phoneId should be in range [-128, 127], inclusive");
1572 }
1573 // Integer#valueOf guarantees the integers within [-128, 127] are cached and thus memory
1574 // comparison (==) returns true for the same integer.
1575 return Integer.valueOf(phoneId);
1576 }
1577
1578 /**
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001579 * If {@code args} contains {@link #DUMP_ARG_REQUESTING_PACKAGE} and a following package name,
1580 * we'll also call {@link IBinder#dump} on the default carrier service (if bound) and the
1581 * specified carrier service (if bound). Typically, this is done for connectivity bug reports
1582 * where we don't call {@code dumpsys activity service all-non-platform} because that contains
1583 * too much info, but we still want to let carrier apps include their diagnostics.
1584 */
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001585 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001586 public void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter pw, @NonNull String[] args) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001587 IndentingPrintWriter indentPW = new IndentingPrintWriter(pw, " ");
Junda Liu43d723a2015-05-12 17:23:45 -07001588 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1589 != PackageManager.PERMISSION_GRANTED) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001590 indentPW.println("Permission Denial: can't dump carrierconfig from from pid="
Junda Liu43d723a2015-05-12 17:23:45 -07001591 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
1592 return;
1593 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001594 String requestingPackage = null;
1595 int requestingPackageIndex = ArrayUtils.indexOf(args, DUMP_ARG_REQUESTING_PACKAGE);
1596 if (requestingPackageIndex >= 0 && requestingPackageIndex < args.length - 1
1597 && !TextUtils.isEmpty(args[requestingPackageIndex + 1])) {
1598 requestingPackage = args[requestingPackageIndex + 1];
1599 // Throws a SecurityException if the caller is impersonating another app in an effort to
1600 // dump extra info (which may contain PII the caller doesn't have a right to).
1601 enforceCallerIsSystemOrRequestingPackage(requestingPackage);
1602 }
1603
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001604 indentPW.println("CarrierConfigLoader: " + this);
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001605 for (int i = 0; i < mNumPhones; i++) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001606 indentPW.println("Phone Id = " + i);
shuoq26a3a4c2016-12-16 11:06:48 -08001607 // display default values in CarrierConfigManager
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001608 printConfig(CarrierConfigManager.getDefaultConfig(), indentPW,
shuoq26a3a4c2016-12-16 11:06:48 -08001609 "Default Values from CarrierConfigManager");
shuoq26a3a4c2016-12-16 11:06:48 -08001610 // display ConfigFromDefaultApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001611 printConfig(mConfigFromDefaultApp[i], indentPW, "mConfigFromDefaultApp");
shuoq26a3a4c2016-12-16 11:06:48 -08001612 // display ConfigFromCarrierApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001613 printConfig(mConfigFromCarrierApp[i], indentPW, "mConfigFromCarrierApp");
1614 printConfig(mPersistentOverrideConfigs[i], indentPW, "mPersistentOverrideConfigs");
1615 printConfig(mOverrideConfigs[i], indentPW, "mOverrideConfigs");
shuoq26a3a4c2016-12-16 11:06:48 -08001616 }
chen xudb04c292019-03-26 17:01:15 -07001617
Jayachandran C645ec612020-01-10 10:30:25 -08001618 printConfig(mNoSimConfig, indentPW, "mNoSimConfig");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001619 indentPW.println("CarrierConfigLoadingLog=");
1620 mCarrierConfigLoadingLog.dump(fd, indentPW, args);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001621
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001622 if (requestingPackage != null) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001623 logd("Including default and requesting package " + requestingPackage
1624 + " carrier services in dump");
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001625 indentPW.println("");
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001626 indentPW.println("Connected services");
1627 dumpCarrierServiceIfBound(fd, indentPW, "Default config package",
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001628 mPlatformCarrierConfigPackage, false /* considerCarrierPrivileges */);
1629 dumpCarrierServiceIfBound(fd, indentPW, "Requesting package", requestingPackage,
1630 true /* considerCarrierPrivileges */);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001631 }
shuoq26a3a4c2016-12-16 11:06:48 -08001632 }
1633
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001634 private void printConfig(@NonNull PersistableBundle configApp,
1635 @NonNull IndentingPrintWriter indentPW, @NonNull String name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001636 indentPW.increaseIndent();
shuoq26a3a4c2016-12-16 11:06:48 -08001637 if (configApp == null) {
shuoq26a3a4c2016-12-16 11:06:48 -08001638 indentPW.println(name + " : null ");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001639 indentPW.decreaseIndent();
1640 indentPW.println("");
shuoq26a3a4c2016-12-16 11:06:48 -08001641 return;
1642 }
shuoq26a3a4c2016-12-16 11:06:48 -08001643 indentPW.println(name + " : ");
1644 List<String> sortedKeys = new ArrayList<String>(configApp.keySet());
1645 Collections.sort(sortedKeys);
1646 indentPW.increaseIndent();
1647 indentPW.increaseIndent();
1648 for (String key : sortedKeys) {
1649 if (configApp.get(key) != null && configApp.get(key) instanceof Object[]) {
1650 indentPW.println(key + " = " +
1651 Arrays.toString((Object[]) configApp.get(key)));
1652 } else if (configApp.get(key) != null && configApp.get(key) instanceof int[]) {
1653 indentPW.println(key + " = " + Arrays.toString((int[]) configApp.get(key)));
1654 } else {
1655 indentPW.println(key + " = " + configApp.get(key));
1656 }
Junda Liu43d723a2015-05-12 17:23:45 -07001657 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001658 indentPW.decreaseIndent();
1659 indentPW.decreaseIndent();
1660 indentPW.decreaseIndent();
1661 indentPW.println("");
Junda Liu43d723a2015-05-12 17:23:45 -07001662 }
1663
Hunter Knepshielde601f432020-02-19 10:16:04 -08001664 /**
1665 * Passes without problem when one of these conditions is true:
1666 * - The caller is a privileged UID (e.g. for dumpstate.cpp generating a bug report, where the
1667 * system knows the true caller plumbed in through the {@link android.os.BugreportManager} API).
1668 * - The caller's UID matches the supplied package.
1669 *
1670 * @throws SecurityException if none of the above conditions are met.
1671 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001672 private void enforceCallerIsSystemOrRequestingPackage(@NonNull String requestingPackage)
Hunter Knepshielde601f432020-02-19 10:16:04 -08001673 throws SecurityException {
1674 final int callingUid = Binder.getCallingUid();
1675 if (callingUid == Process.ROOT_UID || callingUid == Process.SYSTEM_UID
1676 || callingUid == Process.SHELL_UID || callingUid == Process.PHONE_UID) {
1677 // Bug reports (dumpstate.cpp) run as SHELL, and let some other privileged UIDs through
1678 // as well.
1679 return;
1680 }
1681 // An app is trying to dump extra detail, block it if they aren't who they claim to be.
1682 AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
1683 if (appOps == null) {
1684 throw new SecurityException("No AppOps");
1685 }
1686 // Will throw a SecurityException if the UID and package don't match.
1687 appOps.checkPackage(callingUid, requestingPackage);
1688 }
1689
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001690 /**
1691 * Searches for one or more appropriate {@link CarrierService} instances to dump based on the
1692 * current connections.
1693 *
1694 * @param targetPkgName the target package name to dump carrier services for
1695 * @param considerCarrierPrivileges if true, allow a carrier service to be dumped if it shares
1696 * carrier privileges with {@code targetPkgName};
1697 * otherwise, only dump a carrier service if it is {@code
1698 * targetPkgName}
1699 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001700 private void dumpCarrierServiceIfBound(@NonNull FileDescriptor fd,
1701 @NonNull IndentingPrintWriter indentPW, @NonNull String prefix,
1702 @NonNull String targetPkgName, boolean considerCarrierPrivileges) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001703 // Null package is possible if it's early in the boot process, there was a recent crash, we
1704 // loaded the config from XML most recently, or a SIM slot is empty. Carrier apps with
1705 // long-lived bindings should typically get dumped here regardless. Even if an app is being
1706 // used for multiple phoneIds, we assume that it's smart enough to handle that on its own,
1707 // and that in most cases we'd just be dumping duplicate information and bloating a report.
1708 indentPW.increaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001709 indentPW.println(prefix + " : " + targetPkgName);
1710 Set<String> dumpedPkgNames = new ArraySet<>(mServiceConnection.length);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001711 for (CarrierServiceConnection connection : mServiceConnection) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001712 if (connection == null || !SubscriptionManager.isValidPhoneId(connection.phoneId)
1713 || TextUtils.isEmpty(connection.pkgName)) {
1714 continue;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001715 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001716 final String servicePkgName = connection.pkgName;
1717 // Note: we intentionally ignore system components here because we should NOT match the
1718 // shell caller that's typically used for bug reports via non-BugreportManager triggers.
1719 final boolean exactPackageMatch = TextUtils.equals(targetPkgName, servicePkgName);
1720 final boolean carrierPrivilegesMatch =
1721 considerCarrierPrivileges && hasCarrierPrivileges(targetPkgName,
1722 connection.phoneId);
1723 if (!exactPackageMatch && !carrierPrivilegesMatch) continue;
1724 // Make sure this service is actually alive before trying to dump it. We don't pay
1725 // attention to mServiceBound[connection.phoneId] because typically carrier apps will
1726 // request long-lived bindings, and even if we unbind the app, it may still be alive due
1727 // to CarrierServiceBindHelper. Pull it out as a reference so even if it gets set to
1728 // null within the ServiceConnection during unbinding we can avoid an NPE.
1729 final IBinder service = connection.service;
1730 if (service == null || !service.isBinderAlive() || !service.pingBinder()) continue;
1731 // We've got a live service. Last check is just to make sure we don't dump a package
1732 // multiple times.
1733 if (!dumpedPkgNames.add(servicePkgName)) continue;
1734 if (!exactPackageMatch) {
1735 logd(targetPkgName + " has carrier privileges on phoneId " + connection.phoneId
1736 + ", service provided by " + servicePkgName);
1737 indentPW.increaseIndent();
1738 indentPW.println("Proxy : " + servicePkgName);
1739 indentPW.decreaseIndent();
1740 }
1741 // Flush before we let the app output anything to ensure correct ordering of output.
1742 // Internally, Binder#dump calls flush on its printer after finishing so we don't
1743 // need to do anything after.
1744 indentPW.flush();
1745 try {
1746 logd("Dumping " + servicePkgName);
1747 // We don't need to give the carrier service any args.
1748 connection.service.dump(fd, null /* args */);
1749 logd("Done with " + servicePkgName);
1750 } catch (RemoteException e) {
1751 logd("RemoteException from " + servicePkgName, e);
1752 indentPW.increaseIndent();
1753 indentPW.println("RemoteException");
1754 indentPW.increaseIndent();
1755 e.printStackTrace(indentPW);
1756 indentPW.decreaseIndent();
1757 indentPW.decreaseIndent();
1758 // We won't retry this package again because now it's in dumpedPkgNames.
1759 }
1760 indentPW.println("");
Jordan Liu46ed5db2020-01-28 08:55:20 -08001761 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001762 if (dumpedPkgNames.isEmpty()) {
1763 indentPW.increaseIndent();
1764 indentPW.println("Not bound");
1765 indentPW.decreaseIndent();
1766 indentPW.println("");
1767 }
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001768 indentPW.decreaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001769 }
1770
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001771 private boolean hasCarrierPrivileges(@NonNull String pkgName, int phoneId) {
Jack Yu00ece8c2022-11-19 22:29:12 -08001772 int subId = SubscriptionManager.getSubscriptionId(phoneId);
1773 if (!SubscriptionManager.isValidSubscriptionId(subId)) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001774 return false;
1775 }
Jack Yu00ece8c2022-11-19 22:29:12 -08001776 return TelephonyManager.from(mContext).createForSubscriptionId(subId)
1777 .checkCarrierPrivilegesForPackage(pkgName)
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001778 == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001779 }
1780
Zach Johnson36d7aab2015-05-22 15:43:00 -07001781 private class CarrierServiceConnection implements ServiceConnection {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001782 final int phoneId;
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001783 @NonNull final String pkgName;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001784 final int eventId;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001785 IBinder service;
1786
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001787 CarrierServiceConnection(int phoneId, @NonNull String pkgName, int eventId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001788 this.phoneId = phoneId;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001789 this.pkgName = pkgName;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001790 this.eventId = eventId;
1791 }
1792
1793 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001794 public void onServiceConnected(@NonNull ComponentName name, @NonNull IBinder service) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001795 logd("Connected to config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001796 this.service = service;
1797 mHandler.sendMessage(mHandler.obtainMessage(eventId, phoneId, -1, this));
1798 }
1799
1800 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001801 public void onServiceDisconnected(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001802 logd("Disconnected from config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001803 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001804 }
1805
1806 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001807 public void onBindingDied(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001808 logd("Binding died from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001809 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001810 }
1811
1812 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001813 public void onNullBinding(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001814 logd("Null binding from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001815 this.service = null;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001816 }
1817 }
1818
1819 private class ConfigLoaderBroadcastReceiver extends BroadcastReceiver {
1820 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001821 public void onReceive(@NonNull Context context, @NonNull Intent intent) {
Rambo Wanga27fbe52022-04-12 19:09:07 +00001822 switch (intent.getAction()) {
Nanxi Chen3d670502016-03-17 16:32:09 -07001823 case Intent.ACTION_BOOT_COMPLETED:
1824 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_UNLOCKED, null));
1825 break;
1826
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001827 case TelephonyManager.ACTION_MULTI_SIM_CONFIG_CHANGED:
1828 mHandler.sendEmptyMessage(EVENT_MULTI_SIM_CONFIG_CHANGED);
1829 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001830 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001831 }
1832 }
1833
Rambo Wanga27fbe52022-04-12 19:09:07 +00001834 private class CarrierServiceChangeCallback implements
1835 TelephonyManager.CarrierPrivilegesCallback {
1836 final int mPhoneId;
1837 // CarrierPrivilegesCallback will be triggered upon registration. Filter the first callback
1838 // here since we really care of the *change* of carrier service instead of the content
1839 private boolean mHasSentServiceChangeCallback;
1840
1841 CarrierServiceChangeCallback(int phoneId) {
1842 this.mPhoneId = phoneId;
1843 this.mHasSentServiceChangeCallback = false;
1844 }
1845
1846 @Override
1847 public void onCarrierPrivilegesChanged(
1848 @androidx.annotation.NonNull Set<String> privilegedPackageNames,
1849 @androidx.annotation.NonNull Set<Integer> privilegedUids) {
1850 // Ignored, not interested here
1851 }
1852
1853 @Override
1854 public void onCarrierServiceChanged(
1855 @androidx.annotation.Nullable String carrierServicePackageName,
1856 int carrierServiceUid) {
1857 // Ignore the first callback which is triggered upon registration
1858 if (!mHasSentServiceChangeCallback) {
1859 mHasSentServiceChangeCallback = true;
1860 return;
1861 }
1862 mHandler.sendMessage(
1863 mHandler.obtainMessage(EVENT_PACKAGE_CHANGED, mPhoneId, -1,
1864 carrierServicePackageName));
1865 }
1866 }
1867
Rambo Wangab13e3e2021-04-08 15:01:06 -07001868 // Get readable string for the message code supported in this class.
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001869 @NonNull
Rambo Wangab13e3e2021-04-08 15:01:06 -07001870 private static String eventToString(int code) {
1871 switch (code) {
1872 case EVENT_CLEAR_CONFIG:
1873 return "EVENT_CLEAR_CONFIG";
1874 case EVENT_CONNECTED_TO_DEFAULT:
1875 return "EVENT_CONNECTED_TO_DEFAULT";
1876 case EVENT_CONNECTED_TO_CARRIER:
1877 return "EVENT_CONNECTED_TO_CARRIER";
1878 case EVENT_FETCH_DEFAULT_DONE:
1879 return "EVENT_FETCH_DEFAULT_DONE";
1880 case EVENT_FETCH_CARRIER_DONE:
1881 return "EVENT_FETCH_CARRIER_DONE";
1882 case EVENT_DO_FETCH_DEFAULT:
1883 return "EVENT_DO_FETCH_DEFAULT";
1884 case EVENT_DO_FETCH_CARRIER:
1885 return "EVENT_DO_FETCH_CARRIER";
1886 case EVENT_PACKAGE_CHANGED:
1887 return "EVENT_PACKAGE_CHANGED";
1888 case EVENT_BIND_DEFAULT_TIMEOUT:
1889 return "EVENT_BIND_DEFAULT_TIMEOUT";
1890 case EVENT_BIND_CARRIER_TIMEOUT:
1891 return "EVENT_BIND_CARRIER_TIMEOUT";
1892 case EVENT_CHECK_SYSTEM_UPDATE:
1893 return "EVENT_CHECK_SYSTEM_UPDATE";
1894 case EVENT_SYSTEM_UNLOCKED:
1895 return "EVENT_SYSTEM_UNLOCKED";
1896 case EVENT_FETCH_DEFAULT_TIMEOUT:
1897 return "EVENT_FETCH_DEFAULT_TIMEOUT";
1898 case EVENT_FETCH_CARRIER_TIMEOUT:
1899 return "EVENT_FETCH_CARRIER_TIMEOUT";
1900 case EVENT_SUBSCRIPTION_INFO_UPDATED:
1901 return "EVENT_SUBSCRIPTION_INFO_UPDATED";
1902 case EVENT_MULTI_SIM_CONFIG_CHANGED:
1903 return "EVENT_MULTI_SIM_CONFIG_CHANGED";
1904 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG:
1905 return "EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG";
1906 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE:
1907 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE";
1908 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG:
1909 return "EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG";
1910 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1911 return "EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1912 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1913 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1914 default:
1915 return "UNKNOWN(" + code + ")";
1916 }
1917 }
1918
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001919 private void logd(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001920 Log.d(LOG_TAG, msg);
1921 }
1922
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001923 private void logd(@NonNull String msg, Throwable tr) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001924 Log.d(LOG_TAG, msg, tr);
1925 }
1926
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001927 private void logdWithLocalLog(@NonNull String msg) {
chen xudb04c292019-03-26 17:01:15 -07001928 Log.d(LOG_TAG, msg);
1929 mCarrierConfigLoadingLog.log(msg);
1930 }
1931
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001932 private void loge(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001933 Log.e(LOG_TAG, msg);
chen xudb04c292019-03-26 17:01:15 -07001934 mCarrierConfigLoadingLog.log(msg);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001935 }
1936}