blob: 4cb2c5d639930ff9d761574109e593be03ad8814 [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 Wang1cf71512022-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;
rambowangc2ab1202022-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 Yu5e360c42022-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;
rambowang63f4fc42022-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 Wang1b89db32022-04-15 03:00:32 +000095 @NonNull private final String mPlatformCarrierConfigPackage;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080096
97 /** The singleton instance. */
Rambo Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-04-15 03:00:32 +0000125 @NonNull private boolean[] mFromSystemUnlocked;
Rambo Wang1cf71512022-04-12 19:09:07 +0000126 // CarrierService change monitoring
127 @NonNull private CarrierServiceChangeCallback[] mCarrierServiceChangeCallbacks;
Rambo Wang1b89db32022-04-15 03:00:32 +0000128
Nathan Harold48ac0972019-03-13 22:33:01 -0700129 // SubscriptionInfoUpdater
Rambo Wang1b89db32022-04-15 03:00:32 +0000130 @NonNull private final SubscriptionInfoUpdater mSubscriptionInfoUpdater;
Rambo Wang1cf71512022-04-12 19:09:07 +0000131 // Broadcast receiver for system events (BootCompleted, MultiSimConfigChanged etc.)
132 @NonNull
133 private final BroadcastReceiver mSystemBroadcastReceiver = new ConfigLoaderBroadcastReceiver();
Rambo Wang1b89db32022-04-15 03:00:32 +0000134 @NonNull private final LocalLog mCarrierConfigLoadingLog = new LocalLog(100);
Rambo Wang6f8328d2022-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
rambowang63f4fc42022-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 Wang1b89db32022-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 Wang6f8328d2022-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 Wang1cf71512022-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 Yu5e360c42022-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 Yu5e360c42022-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 Yu5e360c42022-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 Yu5e360c42022-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 Yu5e360c42022-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 Yu5e360c42022-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 Yu5e360c42022-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 Yu5e360c42022-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 Wang1b89db32022-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 Wang1b89db32022-04-15 03:00:32 +0000699 /* package */ CarrierConfigLoader(@NonNull Context context,
Jack Yu5e360c42022-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 Wang6f8328d2022-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 Wang1cf71512022-04-12 19:09:07 +0000710 context.registerReceiver(mSystemBroadcastReceiver, systemEventsFilter);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800711
Rambo Wang6f8328d2022-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 Wang6f8328d2022-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 Wang1cf71512022-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 Wang1b89db32022-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 Yu5e360c42022-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 Yu5e360c42022-12-16 11:53:37 -0800786 configPackageName = getCarrierPackageForPhoneId(phoneId);
Nathan Harold48ac0972019-03-13 22:33:01 -0700787 configToSend = mConfigFromCarrierApp[phoneId];
788 } else {
Jack Yu5e360c42022-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 Yu5e360c42022-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) {
rambowangc2ab1202022-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) {
rambowangc2ab1202022-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) {
rambowangc2ab1202022-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);
rambowangc2ab1202022-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]);
rambowangc2ab1202022-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);
rambowangc2ab1202022-10-02 11:21:08 -0500853
Jack Yude40a3f2022-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
rambowangc2ab1202022-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 Wang1b89db32022-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 Wang1b89db32022-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 Wang76e83b52022-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 Wang76e83b52022-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 Wang1b89db32022-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 Wang1b89db32022-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 {
Ryan Savitskicab25c52023-03-14 14:23:49 +00001017 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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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 {
Ryan Savitskicab25c52023-03-14 14:23:49 +00001108 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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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 Wang1b89db32022-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) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001209 logd("Deleting " + 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
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001215 /** Builds a canonical file name for a config file. */
Rambo Wang1b89db32022-04-15 03:00:32 +00001216 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001217 private static String getFilenameForConfig(
1218 @NonNull String packageName, @NonNull String extraString,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001219 @NonNull String iccid, int cid) {
chen xu02581692018-11-11 19:03:44 -08001220 // the same carrier should have a single copy of XML file named after carrier id.
1221 // However, it's still possible that platform doesn't recognize the current sim carrier,
1222 // we will use iccid + carrierid as the canonical file name. carrierid can also handle the
1223 // cases SIM OTA resolves to different carrier while iccid remains the same.
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001224 return "carrierconfig-" + packageName + extraString + "-" + iccid + "-" + cid + ".xml";
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001225 }
1226
Jayachandran C645ec612020-01-10 10:30:25 -08001227 /** Builds a canonical file name for no SIM config file. */
Rambo Wang1b89db32022-04-15 03:00:32 +00001228 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001229 private String getFilenameForNoSimConfig(@NonNull String packageName) {
1230 return "carrierconfig-" + packageName + "-" + "nosim" + ".xml";
1231 }
1232
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001233 /** Return the current version code of a package, or null if the name is not found. */
Rambo Wang1b89db32022-04-15 03:00:32 +00001234 @Nullable
1235 private String getPackageVersion(@NonNull String packageName) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001236 try {
1237 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
Dianne Hackbornb76ab202017-11-28 17:44:50 -08001238 return Long.toString(info.getLongVersionCode());
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001239 } catch (PackageManager.NameNotFoundException e) {
1240 return null;
1241 }
1242 }
1243
Jonathan Basseri65273c82017-07-25 15:08:42 -07001244 /**
1245 * Read up to date config.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001246 *
1247 * This reads config bundles for the given phoneId. That means getting the latest bundle from
1248 * the default app and a privileged carrier app, if present. This will not bind to an app if we
1249 * have a saved config file to use instead.
1250 */
1251 private void updateConfigForPhoneId(int phoneId) {
Jonathan Basseri65273c82017-07-25 15:08:42 -07001252 mHandler.sendMessage(mHandler.obtainMessage(EVENT_DO_FETCH_DEFAULT, phoneId, -1));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001253 }
1254
Malcolm Chen5ea18532019-10-24 19:55:44 -07001255 private void onMultiSimConfigChanged() {
Rambo Wang6f8328d2022-04-15 01:26:23 +00001256 int oldNumPhones = mNumPhones;
1257 mNumPhones = TelephonyManager.from(mContext).getActiveModemCount();
1258 if (mNumPhones == oldNumPhones) {
1259 return;
1260 }
1261 logdWithLocalLog("mNumPhones change from " + oldNumPhones + " to " + mNumPhones);
1262
Rambo Wang1cf71512022-04-12 19:09:07 +00001263 // If DS -> SS switch, release the resources BEFORE truncating the arrays to avoid leaking
Rambo Wang6f8328d2022-04-15 01:26:23 +00001264 for (int phoneId = mNumPhones; phoneId < oldNumPhones; phoneId++) {
1265 if (mServiceConnection[phoneId] != null) {
1266 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
1267 }
1268 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
1269 unbindIfBoundForNoSimConfig(mContext, mServiceConnectionForNoSimConfig[phoneId],
1270 phoneId);
1271 }
1272 }
1273
Rambo Wang1cf71512022-04-12 19:09:07 +00001274 // The phone to slot mapping may change, unregister here and re-register callbacks later
1275 for (int phoneId = 0; phoneId < oldNumPhones; phoneId++) {
1276 if (mCarrierServiceChangeCallbacks[phoneId] != null) {
1277 TelephonyManager.from(mContext).unregisterCarrierPrivilegesCallback(
1278 mCarrierServiceChangeCallbacks[phoneId]);
1279 }
1280 }
1281
Rambo Wang6f8328d2022-04-15 01:26:23 +00001282 // Copy the original arrays, truncate or padding with zeros (if necessary) to new length
1283 mConfigFromDefaultApp = Arrays.copyOf(mConfigFromDefaultApp, mNumPhones);
1284 mConfigFromCarrierApp = Arrays.copyOf(mConfigFromCarrierApp, mNumPhones);
1285 mPersistentOverrideConfigs = Arrays.copyOf(mPersistentOverrideConfigs, mNumPhones);
1286 mOverrideConfigs = Arrays.copyOf(mOverrideConfigs, mNumPhones);
1287 mServiceConnection = Arrays.copyOf(mServiceConnection, mNumPhones);
1288 mServiceConnectionForNoSimConfig =
1289 Arrays.copyOf(mServiceConnectionForNoSimConfig, mNumPhones);
1290 mServiceBound = Arrays.copyOf(mServiceBound, mNumPhones);
1291 mServiceBoundForNoSimConfig = Arrays.copyOf(mServiceBoundForNoSimConfig, mNumPhones);
1292 mHasSentConfigChange = Arrays.copyOf(mHasSentConfigChange, mNumPhones);
1293 mFromSystemUnlocked = Arrays.copyOf(mFromSystemUnlocked, mNumPhones);
Rambo Wang1cf71512022-04-12 19:09:07 +00001294 mCarrierServiceChangeCallbacks = Arrays.copyOf(mCarrierServiceChangeCallbacks, mNumPhones);
Rambo Wang6f8328d2022-04-15 01:26:23 +00001295
Rambo Wang1cf71512022-04-12 19:09:07 +00001296 // Load the config for all the phones and re-register callback AFTER padding the arrays.
Rambo Wang6f8328d2022-04-15 01:26:23 +00001297 for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
1298 updateConfigForPhoneId(phoneId);
Rambo Wang1cf71512022-04-12 19:09:07 +00001299 mCarrierServiceChangeCallbacks[phoneId] = new CarrierServiceChangeCallback(phoneId);
1300 TelephonyManager.from(mContext).registerCarrierPrivilegesCallback(phoneId,
1301 new HandlerExecutor(mHandler), mCarrierServiceChangeCallbacks[phoneId]);
Malcolm Chen5ea18532019-10-24 19:55:44 -07001302 }
1303 }
1304
Hall Liu506724b2018-10-22 18:16:14 -07001305 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001306 @NonNull
Rambo Wang1b89db32022-04-15 03:00:32 +00001307 public PersistableBundle getConfigForSubId(int subscriptionId, @NonNull String callingPackage) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001308 return getConfigForSubIdWithFeature(subscriptionId, callingPackage, null);
Philip P. Moltmann9797cbb2020-01-07 13:45:00 -08001309 }
1310
1311 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001312 @NonNull
Rambo Wang1b89db32022-04-15 03:00:32 +00001313 public PersistableBundle getConfigForSubIdWithFeature(int subscriptionId,
1314 @NonNull String callingPackage, @Nullable String callingFeatureId) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001315 if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(mContext, subscriptionId,
1316 callingPackage, callingFeatureId, "getCarrierConfig")) {
Rambo Wang42026112021-04-07 20:57:28 +00001317 return new PersistableBundle();
Amit Mahajan40b3fa52015-07-14 10:27:19 -07001318 }
Jeff Davidsona8e4e242018-03-15 17:16:18 -07001319
Rambo Wangd2b004b2021-03-30 10:10:23 -07001320 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001321 PersistableBundle retConfig = CarrierConfigManager.getDefaultConfig();
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001322 if (SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001323 PersistableBundle config = mConfigFromDefaultApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001324 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001325 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001326 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001327 config = mConfigFromCarrierApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001328 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001329 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001330 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001331 config = mPersistentOverrideConfigs[phoneId];
1332 if (config != null) {
1333 retConfig.putAll(config);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001334 }
Hall Liu506724b2018-10-22 18:16:14 -07001335 config = mOverrideConfigs[phoneId];
1336 if (config != null) {
1337 retConfig.putAll(config);
Hall Liu506724b2018-10-22 18:16:14 -07001338 }
Nathan Harold1122e3d2021-01-22 15:45:24 -08001339 // Ignore the theoretical case of the default app not being present since that won't
1340 // work in CarrierConfigLoader today.
1341 final boolean allConfigsApplied =
1342 (mConfigFromCarrierApp[phoneId] != null
1343 || getCarrierPackageForPhoneId(phoneId) == null)
1344 && mConfigFromDefaultApp[phoneId] != null;
1345 retConfig.putBoolean(
1346 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, allConfigsApplied);
Jayachandran C645ec612020-01-10 10:30:25 -08001347 } else {
1348 if (mNoSimConfig != null) {
1349 retConfig.putAll(mNoSimConfig);
1350 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001351 }
1352 return retConfig;
1353 }
1354
1355 @Override
rambowang63f4fc42022-10-03 11:54:56 -05001356 @NonNull
1357 public PersistableBundle getConfigSubsetForSubIdWithFeature(int subscriptionId,
1358 @NonNull String callingPackage, @Nullable String callingFeatureId,
1359 @NonNull String[] keys) {
1360 Objects.requireNonNull(callingPackage, "Calling package must be non-null");
1361 Objects.requireNonNull(keys, "Config keys must be non-null");
1362 enforceCallerIsSystemOrRequestingPackage(callingPackage);
1363
1364 // Permission check is performed inside and an empty bundle will return on failure.
1365 // No SecurityException thrown here since most clients expect to retrieve the overridden
1366 // value if present or use default one if not
1367 PersistableBundle allConfigs = getConfigForSubIdWithFeature(subscriptionId, callingPackage,
1368 callingFeatureId);
1369 if (allConfigs.isEmpty()) {
1370 return allConfigs;
1371 }
1372 for (String key : keys) {
1373 Objects.requireNonNull(key, "Config key must be non-null");
rambowang63f4fc42022-10-03 11:54:56 -05001374 }
1375
1376 PersistableBundle configSubset = new PersistableBundle(
1377 keys.length + CONFIG_SUBSET_METADATA_KEYS.length);
1378 for (String carrierConfigKey : keys) {
1379 Object value = allConfigs.get(carrierConfigKey);
Rambo Wang3b0d3562023-03-09 01:30:35 +00001380 if (value == null) {
1381 // Filter out keys without values.
1382 // In history, many AOSP or OEMs/carriers private configs didn't provide default
1383 // values. We have to continue supporting them for now. See b/261776046 for details.
1384 continue;
1385 }
rambowang63f4fc42022-10-03 11:54:56 -05001386 // Config value itself could be PersistableBundle which requires different API to put
1387 if (value instanceof PersistableBundle) {
1388 configSubset.putPersistableBundle(carrierConfigKey, (PersistableBundle) value);
1389 } else {
1390 configSubset.putObject(carrierConfigKey, value);
1391 }
1392 }
1393
1394 // Configs in CONFIG_SUBSET_ALWAYS_INCLUDED_KEYS should always be included
1395 for (String generalKey : CONFIG_SUBSET_METADATA_KEYS) {
1396 configSubset.putObject(generalKey, allConfigs.get(generalKey));
1397 }
1398
1399 return configSubset;
1400 }
1401
1402 @Override
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001403 public void overrideConfig(int subscriptionId, @Nullable PersistableBundle overrides,
1404 boolean persistent) {
Hall Liu506724b2018-10-22 18:16:14 -07001405 mContext.enforceCallingOrSelfPermission(
1406 android.Manifest.permission.MODIFY_PHONE_STATE, null);
Brad Ebingerf6281ad2019-04-25 11:02:04 -07001407 //TODO: Also check for SHELL UID to restrict this method to testing only (b/131326259)
Hall Liu506724b2018-10-22 18:16:14 -07001408 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1409 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001410 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
Rambo Wangd2b004b2021-03-30 10:10:23 -07001411 throw new IllegalArgumentException(
1412 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
Hall Liu506724b2018-10-22 18:16:14 -07001413 }
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001414 // Post to run on handler thread on which all states should be confined.
1415 mHandler.post(() -> {
1416 overrideConfig(mOverrideConfigs, phoneId, overrides);
Hall Liu506724b2018-10-22 18:16:14 -07001417
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001418 if (persistent) {
1419 overrideConfig(mPersistentOverrideConfigs, phoneId, overrides);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001420
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001421 if (overrides != null) {
1422 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
1423 saveConfigToXml(mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION,
1424 phoneId,
1425 carrierId, mPersistentOverrideConfigs[phoneId]);
1426 } else {
1427 final String iccid = getIccIdForPhoneId(phoneId);
1428 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1429 String fileName = getFilenameForConfig(mPlatformCarrierConfigPackage,
1430 OVERRIDE_PACKAGE_ADDITION, iccid, cid);
1431 File fileToDelete = new File(mContext.getFilesDir(), fileName);
1432 fileToDelete.delete();
1433 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001434 }
Jack Yu5e360c42022-12-16 11:53:37 -08001435 updateSubscriptionDatabase(phoneId);
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001436 });
Hall Liu506724b2018-10-22 18:16:14 -07001437 }
1438
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001439 private void overrideConfig(@NonNull PersistableBundle[] currentOverrides, int phoneId,
1440 @Nullable PersistableBundle overrides) {
1441 if (overrides == null) {
Rambo Wang42026112021-04-07 20:57:28 +00001442 currentOverrides[phoneId] = new PersistableBundle();
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001443 } else if (currentOverrides[phoneId] == null) {
1444 currentOverrides[phoneId] = overrides;
1445 } else {
1446 currentOverrides[phoneId].putAll(overrides);
1447 }
1448 }
1449
Hall Liu506724b2018-10-22 18:16:14 -07001450 @Override
Rambo Wangd2b004b2021-03-30 10:10:23 -07001451 public void notifyConfigChangedForSubId(int subscriptionId) {
Jordan Liud7d57fe2019-04-16 12:29:43 -07001452 // Requires the calling app to be either a carrier privileged app for this subId or
Junda Liufbd2bcb2016-06-15 11:15:42 -07001453 // system privileged app with MODIFY_PHONE_STATE permission.
Rambo Wangd2b004b2021-03-30 10:10:23 -07001454 TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(mContext,
1455 subscriptionId, "Require carrier privileges or MODIFY_PHONE_STATE permission.");
1456
1457 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1458 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
1459 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
1460 throw new IllegalArgumentException(
1461 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
1462 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001463
1464 // This method should block until deleting has completed, so that an error which prevents us
1465 // from clearing the cache is passed back to the carrier app. With the files successfully
1466 // deleted, this can return and we will eventually bind to the carrier app.
Jordan Liud7d57fe2019-04-16 12:29:43 -07001467 String callingPackageName = mContext.getPackageManager().getNameForUid(
1468 Binder.getCallingUid());
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001469 clearCachedConfigForPackage(callingPackageName);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001470 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001471 }
1472
1473 @Override
Rambo Wang1b89db32022-04-15 03:00:32 +00001474 public void updateConfigForPhoneId(int phoneId, @NonNull String simState) {
Junda Liu1f2b34d2015-06-18 15:26:56 -07001475 mContext.enforceCallingOrSelfPermission(
1476 android.Manifest.permission.MODIFY_PHONE_STATE, null);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001477 logdWithLocalLog("Update config for phoneId: " + phoneId + " simState: " + simState);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001478 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001479 throw new IllegalArgumentException("Invalid phoneId: " + phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001480 }
1481 // requires Java 7 for switch on string.
1482 switch (simState) {
1483 case IccCardConstants.INTENT_VALUE_ICC_ABSENT:
1484 case IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR:
Junda Liu6f5fddf2016-05-24 16:14:41 -07001485 case IccCardConstants.INTENT_VALUE_ICC_CARD_RESTRICTED:
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001486 case IccCardConstants.INTENT_VALUE_ICC_UNKNOWN:
Malcolm Chendb66de12019-12-09 18:57:07 -08001487 case IccCardConstants.INTENT_VALUE_ICC_NOT_READY:
Junda Liu9f2d2712015-05-15 14:22:45 -07001488 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CLEAR_CONFIG, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001489 break;
1490 case IccCardConstants.INTENT_VALUE_ICC_LOADED:
1491 case IccCardConstants.INTENT_VALUE_ICC_LOCKED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001492 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001493 break;
1494 }
1495 }
1496
Junda Liu43d723a2015-05-12 17:23:45 -07001497 @Override
Rambo Wang1b89db32022-04-15 03:00:32 +00001498 @NonNull
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001499 public String getDefaultCarrierServicePackageName() {
Shuo Qianefdb7962019-12-19 15:54:27 -08001500 mContext.enforceCallingOrSelfPermission(
1501 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
1502 "getDefaultCarrierServicePackageName");
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001503 return mPlatformCarrierConfigPackage;
1504 }
1505
Rambo Wang7e3bc122021-03-23 09:24:38 -07001506 @VisibleForTesting
Rambo Wang1b89db32022-04-15 03:00:32 +00001507 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -07001508 /* package */ Handler getHandler() {
1509 return mHandler;
1510 }
1511
1512 @VisibleForTesting
Rambo Wang1b89db32022-04-15 03:00:32 +00001513 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001514 /* package */ PersistableBundle getConfigFromDefaultApp(int phoneId) {
1515 return mConfigFromDefaultApp[phoneId];
1516 }
1517
1518 @VisibleForTesting
Rambo Wang1b89db32022-04-15 03:00:32 +00001519 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001520 /* package */ PersistableBundle getConfigFromCarrierApp(int phoneId) {
1521 return mConfigFromCarrierApp[phoneId];
1522 }
1523
1524 @VisibleForTesting
Rambo Wang1b89db32022-04-15 03:00:32 +00001525 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -07001526 /* package */ PersistableBundle getNoSimConfig() {
1527 return mNoSimConfig;
1528 }
1529
1530 @VisibleForTesting
Rambo Wang1b89db32022-04-15 03:00:32 +00001531 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001532 /* package */ PersistableBundle getOverrideConfig(int phoneId) {
1533 return mOverrideConfigs[phoneId];
1534 }
1535
Rambo Wang6f8328d2022-04-15 01:26:23 +00001536 // TODO(b/185129900): always call unbindService after bind, no matter if it succeeded
Rambo Wang1b89db32022-04-15 03:00:32 +00001537 private void unbindIfBound(@NonNull Context context, @NonNull CarrierServiceConnection conn,
Rambo Wangb0f3e2f2021-10-28 12:40:12 -07001538 int phoneId) {
1539 if (mServiceBound[phoneId]) {
1540 mServiceBound[phoneId] = false;
1541 context.unbindService(conn);
1542 }
1543 }
1544
Rambo Wang1b89db32022-04-15 03:00:32 +00001545 private void unbindIfBoundForNoSimConfig(@NonNull Context context,
1546 @NonNull CarrierServiceConnection conn, int phoneId) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -07001547 if (mServiceBoundForNoSimConfig[phoneId]) {
1548 mServiceBoundForNoSimConfig[phoneId] = false;
Jayachandran C645ec612020-01-10 10:30:25 -08001549 context.unbindService(conn);
1550 }
1551 }
1552
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001553 /**
Rambo Wang610fdf62021-03-08 21:37:11 -08001554 * Returns a boxed Integer object for phoneId, services as message token to distinguish messages
1555 * with same code when calling {@link Handler#removeMessages(int, Object)}.
1556 */
Rambo Wang1b89db32022-04-15 03:00:32 +00001557 @NonNull
Rambo Wang610fdf62021-03-08 21:37:11 -08001558 private Integer getMessageToken(int phoneId) {
1559 if (phoneId < -128 || phoneId > 127) {
1560 throw new IllegalArgumentException("phoneId should be in range [-128, 127], inclusive");
1561 }
1562 // Integer#valueOf guarantees the integers within [-128, 127] are cached and thus memory
1563 // comparison (==) returns true for the same integer.
1564 return Integer.valueOf(phoneId);
1565 }
1566
1567 /**
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001568 * If {@code args} contains {@link #DUMP_ARG_REQUESTING_PACKAGE} and a following package name,
1569 * we'll also call {@link IBinder#dump} on the default carrier service (if bound) and the
1570 * specified carrier service (if bound). Typically, this is done for connectivity bug reports
1571 * where we don't call {@code dumpsys activity service all-non-platform} because that contains
1572 * too much info, but we still want to let carrier apps include their diagnostics.
1573 */
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001574 @Override
Rambo Wang1b89db32022-04-15 03:00:32 +00001575 public void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter pw, @NonNull String[] args) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001576 IndentingPrintWriter indentPW = new IndentingPrintWriter(pw, " ");
Junda Liu43d723a2015-05-12 17:23:45 -07001577 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1578 != PackageManager.PERMISSION_GRANTED) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001579 indentPW.println("Permission Denial: can't dump carrierconfig from from pid="
Junda Liu43d723a2015-05-12 17:23:45 -07001580 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
1581 return;
1582 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001583 String requestingPackage = null;
1584 int requestingPackageIndex = ArrayUtils.indexOf(args, DUMP_ARG_REQUESTING_PACKAGE);
1585 if (requestingPackageIndex >= 0 && requestingPackageIndex < args.length - 1
1586 && !TextUtils.isEmpty(args[requestingPackageIndex + 1])) {
1587 requestingPackage = args[requestingPackageIndex + 1];
1588 // Throws a SecurityException if the caller is impersonating another app in an effort to
1589 // dump extra info (which may contain PII the caller doesn't have a right to).
1590 enforceCallerIsSystemOrRequestingPackage(requestingPackage);
1591 }
1592
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001593 indentPW.println("CarrierConfigLoader: " + this);
Rambo Wang6f8328d2022-04-15 01:26:23 +00001594 for (int i = 0; i < mNumPhones; i++) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001595 indentPW.println("Phone Id = " + i);
shuoq26a3a4c2016-12-16 11:06:48 -08001596 // display default values in CarrierConfigManager
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001597 printConfig(CarrierConfigManager.getDefaultConfig(), indentPW,
shuoq26a3a4c2016-12-16 11:06:48 -08001598 "Default Values from CarrierConfigManager");
shuoq26a3a4c2016-12-16 11:06:48 -08001599 // display ConfigFromDefaultApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001600 printConfig(mConfigFromDefaultApp[i], indentPW, "mConfigFromDefaultApp");
shuoq26a3a4c2016-12-16 11:06:48 -08001601 // display ConfigFromCarrierApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001602 printConfig(mConfigFromCarrierApp[i], indentPW, "mConfigFromCarrierApp");
1603 printConfig(mPersistentOverrideConfigs[i], indentPW, "mPersistentOverrideConfigs");
1604 printConfig(mOverrideConfigs[i], indentPW, "mOverrideConfigs");
shuoq26a3a4c2016-12-16 11:06:48 -08001605 }
chen xudb04c292019-03-26 17:01:15 -07001606
Jayachandran C645ec612020-01-10 10:30:25 -08001607 printConfig(mNoSimConfig, indentPW, "mNoSimConfig");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001608 indentPW.println("CarrierConfigLoadingLog=");
1609 mCarrierConfigLoadingLog.dump(fd, indentPW, args);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001610
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001611 if (requestingPackage != null) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001612 logd("Including default and requesting package " + requestingPackage
1613 + " carrier services in dump");
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001614 indentPW.println("");
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001615 indentPW.println("Connected services");
1616 dumpCarrierServiceIfBound(fd, indentPW, "Default config package",
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001617 mPlatformCarrierConfigPackage, false /* considerCarrierPrivileges */);
1618 dumpCarrierServiceIfBound(fd, indentPW, "Requesting package", requestingPackage,
1619 true /* considerCarrierPrivileges */);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001620 }
shuoq26a3a4c2016-12-16 11:06:48 -08001621 }
1622
Rambo Wang1b89db32022-04-15 03:00:32 +00001623 private void printConfig(@NonNull PersistableBundle configApp,
1624 @NonNull IndentingPrintWriter indentPW, @NonNull String name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001625 indentPW.increaseIndent();
shuoq26a3a4c2016-12-16 11:06:48 -08001626 if (configApp == null) {
shuoq26a3a4c2016-12-16 11:06:48 -08001627 indentPW.println(name + " : null ");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001628 indentPW.decreaseIndent();
1629 indentPW.println("");
shuoq26a3a4c2016-12-16 11:06:48 -08001630 return;
1631 }
shuoq26a3a4c2016-12-16 11:06:48 -08001632 indentPW.println(name + " : ");
1633 List<String> sortedKeys = new ArrayList<String>(configApp.keySet());
1634 Collections.sort(sortedKeys);
1635 indentPW.increaseIndent();
1636 indentPW.increaseIndent();
1637 for (String key : sortedKeys) {
1638 if (configApp.get(key) != null && configApp.get(key) instanceof Object[]) {
1639 indentPW.println(key + " = " +
1640 Arrays.toString((Object[]) configApp.get(key)));
1641 } else if (configApp.get(key) != null && configApp.get(key) instanceof int[]) {
1642 indentPW.println(key + " = " + Arrays.toString((int[]) configApp.get(key)));
1643 } else {
1644 indentPW.println(key + " = " + configApp.get(key));
1645 }
Junda Liu43d723a2015-05-12 17:23:45 -07001646 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001647 indentPW.decreaseIndent();
1648 indentPW.decreaseIndent();
1649 indentPW.decreaseIndent();
1650 indentPW.println("");
Junda Liu43d723a2015-05-12 17:23:45 -07001651 }
1652
Hunter Knepshielde601f432020-02-19 10:16:04 -08001653 /**
1654 * Passes without problem when one of these conditions is true:
1655 * - The caller is a privileged UID (e.g. for dumpstate.cpp generating a bug report, where the
1656 * system knows the true caller plumbed in through the {@link android.os.BugreportManager} API).
1657 * - The caller's UID matches the supplied package.
1658 *
1659 * @throws SecurityException if none of the above conditions are met.
1660 */
Rambo Wang1b89db32022-04-15 03:00:32 +00001661 private void enforceCallerIsSystemOrRequestingPackage(@NonNull String requestingPackage)
Hunter Knepshielde601f432020-02-19 10:16:04 -08001662 throws SecurityException {
1663 final int callingUid = Binder.getCallingUid();
1664 if (callingUid == Process.ROOT_UID || callingUid == Process.SYSTEM_UID
1665 || callingUid == Process.SHELL_UID || callingUid == Process.PHONE_UID) {
1666 // Bug reports (dumpstate.cpp) run as SHELL, and let some other privileged UIDs through
1667 // as well.
1668 return;
1669 }
1670 // An app is trying to dump extra detail, block it if they aren't who they claim to be.
1671 AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
1672 if (appOps == null) {
1673 throw new SecurityException("No AppOps");
1674 }
1675 // Will throw a SecurityException if the UID and package don't match.
1676 appOps.checkPackage(callingUid, requestingPackage);
1677 }
1678
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001679 /**
1680 * Searches for one or more appropriate {@link CarrierService} instances to dump based on the
1681 * current connections.
1682 *
1683 * @param targetPkgName the target package name to dump carrier services for
1684 * @param considerCarrierPrivileges if true, allow a carrier service to be dumped if it shares
1685 * carrier privileges with {@code targetPkgName};
1686 * otherwise, only dump a carrier service if it is {@code
1687 * targetPkgName}
1688 */
Rambo Wang1b89db32022-04-15 03:00:32 +00001689 private void dumpCarrierServiceIfBound(@NonNull FileDescriptor fd,
1690 @NonNull IndentingPrintWriter indentPW, @NonNull String prefix,
1691 @NonNull String targetPkgName, boolean considerCarrierPrivileges) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001692 // Null package is possible if it's early in the boot process, there was a recent crash, we
1693 // loaded the config from XML most recently, or a SIM slot is empty. Carrier apps with
1694 // long-lived bindings should typically get dumped here regardless. Even if an app is being
1695 // used for multiple phoneIds, we assume that it's smart enough to handle that on its own,
1696 // and that in most cases we'd just be dumping duplicate information and bloating a report.
1697 indentPW.increaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001698 indentPW.println(prefix + " : " + targetPkgName);
1699 Set<String> dumpedPkgNames = new ArraySet<>(mServiceConnection.length);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001700 for (CarrierServiceConnection connection : mServiceConnection) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001701 if (connection == null || !SubscriptionManager.isValidPhoneId(connection.phoneId)
1702 || TextUtils.isEmpty(connection.pkgName)) {
1703 continue;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001704 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001705 final String servicePkgName = connection.pkgName;
1706 // Note: we intentionally ignore system components here because we should NOT match the
1707 // shell caller that's typically used for bug reports via non-BugreportManager triggers.
1708 final boolean exactPackageMatch = TextUtils.equals(targetPkgName, servicePkgName);
1709 final boolean carrierPrivilegesMatch =
1710 considerCarrierPrivileges && hasCarrierPrivileges(targetPkgName,
1711 connection.phoneId);
1712 if (!exactPackageMatch && !carrierPrivilegesMatch) continue;
1713 // Make sure this service is actually alive before trying to dump it. We don't pay
1714 // attention to mServiceBound[connection.phoneId] because typically carrier apps will
1715 // request long-lived bindings, and even if we unbind the app, it may still be alive due
1716 // to CarrierServiceBindHelper. Pull it out as a reference so even if it gets set to
1717 // null within the ServiceConnection during unbinding we can avoid an NPE.
1718 final IBinder service = connection.service;
1719 if (service == null || !service.isBinderAlive() || !service.pingBinder()) continue;
1720 // We've got a live service. Last check is just to make sure we don't dump a package
1721 // multiple times.
1722 if (!dumpedPkgNames.add(servicePkgName)) continue;
1723 if (!exactPackageMatch) {
1724 logd(targetPkgName + " has carrier privileges on phoneId " + connection.phoneId
1725 + ", service provided by " + servicePkgName);
1726 indentPW.increaseIndent();
1727 indentPW.println("Proxy : " + servicePkgName);
1728 indentPW.decreaseIndent();
1729 }
1730 // Flush before we let the app output anything to ensure correct ordering of output.
1731 // Internally, Binder#dump calls flush on its printer after finishing so we don't
1732 // need to do anything after.
1733 indentPW.flush();
1734 try {
1735 logd("Dumping " + servicePkgName);
1736 // We don't need to give the carrier service any args.
1737 connection.service.dump(fd, null /* args */);
1738 logd("Done with " + servicePkgName);
1739 } catch (RemoteException e) {
1740 logd("RemoteException from " + servicePkgName, e);
1741 indentPW.increaseIndent();
1742 indentPW.println("RemoteException");
1743 indentPW.increaseIndent();
1744 e.printStackTrace(indentPW);
1745 indentPW.decreaseIndent();
1746 indentPW.decreaseIndent();
1747 // We won't retry this package again because now it's in dumpedPkgNames.
1748 }
1749 indentPW.println("");
Jordan Liu46ed5db2020-01-28 08:55:20 -08001750 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001751 if (dumpedPkgNames.isEmpty()) {
1752 indentPW.increaseIndent();
1753 indentPW.println("Not bound");
1754 indentPW.decreaseIndent();
1755 indentPW.println("");
1756 }
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001757 indentPW.decreaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001758 }
1759
Rambo Wang1b89db32022-04-15 03:00:32 +00001760 private boolean hasCarrierPrivileges(@NonNull String pkgName, int phoneId) {
Jack Yude40a3f2022-11-19 22:29:12 -08001761 int subId = SubscriptionManager.getSubscriptionId(phoneId);
1762 if (!SubscriptionManager.isValidSubscriptionId(subId)) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001763 return false;
1764 }
Jack Yude40a3f2022-11-19 22:29:12 -08001765 return TelephonyManager.from(mContext).createForSubscriptionId(subId)
1766 .checkCarrierPrivilegesForPackage(pkgName)
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001767 == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001768 }
1769
Zach Johnson36d7aab2015-05-22 15:43:00 -07001770 private class CarrierServiceConnection implements ServiceConnection {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001771 final int phoneId;
Rambo Wang1b89db32022-04-15 03:00:32 +00001772 @NonNull final String pkgName;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001773 final int eventId;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001774 IBinder service;
1775
Rambo Wang1b89db32022-04-15 03:00:32 +00001776 CarrierServiceConnection(int phoneId, @NonNull String pkgName, int eventId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001777 this.phoneId = phoneId;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001778 this.pkgName = pkgName;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001779 this.eventId = eventId;
1780 }
1781
1782 @Override
Rambo Wang1b89db32022-04-15 03:00:32 +00001783 public void onServiceConnected(@NonNull ComponentName name, @NonNull IBinder service) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001784 logd("Connected to config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001785 this.service = service;
1786 mHandler.sendMessage(mHandler.obtainMessage(eventId, phoneId, -1, this));
1787 }
1788
1789 @Override
Rambo Wang1b89db32022-04-15 03:00:32 +00001790 public void onServiceDisconnected(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001791 logd("Disconnected from config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001792 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001793 }
1794
1795 @Override
Rambo Wang1b89db32022-04-15 03:00:32 +00001796 public void onBindingDied(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001797 logd("Binding died from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001798 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001799 }
1800
1801 @Override
Rambo Wang1b89db32022-04-15 03:00:32 +00001802 public void onNullBinding(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001803 logd("Null binding from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001804 this.service = null;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001805 }
1806 }
1807
1808 private class ConfigLoaderBroadcastReceiver extends BroadcastReceiver {
1809 @Override
Rambo Wang1b89db32022-04-15 03:00:32 +00001810 public void onReceive(@NonNull Context context, @NonNull Intent intent) {
Rambo Wang1cf71512022-04-12 19:09:07 +00001811 switch (intent.getAction()) {
Nanxi Chen3d670502016-03-17 16:32:09 -07001812 case Intent.ACTION_BOOT_COMPLETED:
1813 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_UNLOCKED, null));
1814 break;
1815
Rambo Wang6f8328d2022-04-15 01:26:23 +00001816 case TelephonyManager.ACTION_MULTI_SIM_CONFIG_CHANGED:
1817 mHandler.sendEmptyMessage(EVENT_MULTI_SIM_CONFIG_CHANGED);
1818 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001819 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001820 }
1821 }
1822
Rambo Wang1cf71512022-04-12 19:09:07 +00001823 private class CarrierServiceChangeCallback implements
1824 TelephonyManager.CarrierPrivilegesCallback {
1825 final int mPhoneId;
1826 // CarrierPrivilegesCallback will be triggered upon registration. Filter the first callback
1827 // here since we really care of the *change* of carrier service instead of the content
1828 private boolean mHasSentServiceChangeCallback;
1829
1830 CarrierServiceChangeCallback(int phoneId) {
1831 this.mPhoneId = phoneId;
1832 this.mHasSentServiceChangeCallback = false;
1833 }
1834
1835 @Override
1836 public void onCarrierPrivilegesChanged(
1837 @androidx.annotation.NonNull Set<String> privilegedPackageNames,
1838 @androidx.annotation.NonNull Set<Integer> privilegedUids) {
1839 // Ignored, not interested here
1840 }
1841
1842 @Override
1843 public void onCarrierServiceChanged(
1844 @androidx.annotation.Nullable String carrierServicePackageName,
1845 int carrierServiceUid) {
1846 // Ignore the first callback which is triggered upon registration
1847 if (!mHasSentServiceChangeCallback) {
1848 mHasSentServiceChangeCallback = true;
1849 return;
1850 }
1851 mHandler.sendMessage(
1852 mHandler.obtainMessage(EVENT_PACKAGE_CHANGED, mPhoneId, -1,
1853 carrierServicePackageName));
1854 }
1855 }
1856
Rambo Wangab13e3e2021-04-08 15:01:06 -07001857 // Get readable string for the message code supported in this class.
Rambo Wang1b89db32022-04-15 03:00:32 +00001858 @NonNull
Rambo Wangab13e3e2021-04-08 15:01:06 -07001859 private static String eventToString(int code) {
1860 switch (code) {
1861 case EVENT_CLEAR_CONFIG:
1862 return "EVENT_CLEAR_CONFIG";
1863 case EVENT_CONNECTED_TO_DEFAULT:
1864 return "EVENT_CONNECTED_TO_DEFAULT";
1865 case EVENT_CONNECTED_TO_CARRIER:
1866 return "EVENT_CONNECTED_TO_CARRIER";
1867 case EVENT_FETCH_DEFAULT_DONE:
1868 return "EVENT_FETCH_DEFAULT_DONE";
1869 case EVENT_FETCH_CARRIER_DONE:
1870 return "EVENT_FETCH_CARRIER_DONE";
1871 case EVENT_DO_FETCH_DEFAULT:
1872 return "EVENT_DO_FETCH_DEFAULT";
1873 case EVENT_DO_FETCH_CARRIER:
1874 return "EVENT_DO_FETCH_CARRIER";
1875 case EVENT_PACKAGE_CHANGED:
1876 return "EVENT_PACKAGE_CHANGED";
1877 case EVENT_BIND_DEFAULT_TIMEOUT:
1878 return "EVENT_BIND_DEFAULT_TIMEOUT";
1879 case EVENT_BIND_CARRIER_TIMEOUT:
1880 return "EVENT_BIND_CARRIER_TIMEOUT";
1881 case EVENT_CHECK_SYSTEM_UPDATE:
1882 return "EVENT_CHECK_SYSTEM_UPDATE";
1883 case EVENT_SYSTEM_UNLOCKED:
1884 return "EVENT_SYSTEM_UNLOCKED";
1885 case EVENT_FETCH_DEFAULT_TIMEOUT:
1886 return "EVENT_FETCH_DEFAULT_TIMEOUT";
1887 case EVENT_FETCH_CARRIER_TIMEOUT:
1888 return "EVENT_FETCH_CARRIER_TIMEOUT";
1889 case EVENT_SUBSCRIPTION_INFO_UPDATED:
1890 return "EVENT_SUBSCRIPTION_INFO_UPDATED";
1891 case EVENT_MULTI_SIM_CONFIG_CHANGED:
1892 return "EVENT_MULTI_SIM_CONFIG_CHANGED";
1893 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG:
1894 return "EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG";
1895 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE:
1896 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE";
1897 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG:
1898 return "EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG";
1899 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1900 return "EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1901 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1902 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1903 default:
1904 return "UNKNOWN(" + code + ")";
1905 }
1906 }
1907
Rambo Wang1b89db32022-04-15 03:00:32 +00001908 private void logd(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001909 Log.d(LOG_TAG, msg);
1910 }
1911
Rambo Wang1b89db32022-04-15 03:00:32 +00001912 private void logd(@NonNull String msg, Throwable tr) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001913 Log.d(LOG_TAG, msg, tr);
1914 }
1915
Rambo Wang1b89db32022-04-15 03:00:32 +00001916 private void logdWithLocalLog(@NonNull String msg) {
chen xudb04c292019-03-26 17:01:15 -07001917 Log.d(LOG_TAG, msg);
1918 mCarrierConfigLoadingLog.log(msg);
1919 }
1920
Rambo Wang1b89db32022-04-15 03:00:32 +00001921 private void loge(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001922 Log.e(LOG_TAG, msg);
chen xudb04c292019-03-26 17:01:15 -07001923 mCarrierConfigLoadingLog.log(msg);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001924 }
1925}