blob: 5ba148d39699e351dd8a2862814d535dae20dd02 [file] [log] [blame]
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001/*
Jonathan Basseri6465afd2015-02-25 13:05:57 -08002 * Copyright (c) 2015, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jonathan Basseri6465afd2015-02-25 13:05:57 -080017package com.android.phone;
18
Jonathan Basseri65273c82017-07-25 15:08:42 -070019import static android.service.carrier.CarrierService.ICarrierServiceWrapper.KEY_CONFIG_BUNDLE;
20import static android.service.carrier.CarrierService.ICarrierServiceWrapper.RESULT_ERROR;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080021
Jonathan Basseri11f89572015-05-05 11:57:39 -070022import android.annotation.NonNull;
Torbjorn Eklund723527a2019-02-13 11:16:25 +010023import android.annotation.Nullable;
Hunter Knepshielde601f432020-02-19 10:16:04 -080024import android.app.AppOpsManager;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080025import android.content.BroadcastReceiver;
26import android.content.ComponentName;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.ServiceConnection;
Jonathan Basseri7697cae2015-07-06 15:49:23 -070031import android.content.SharedPreferences;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070032import android.content.pm.PackageInfo;
Jonathan Basseric31f1f32015-05-12 10:13:03 -070033import android.content.pm.PackageManager;
Junda Liu43d723a2015-05-12 17:23:45 -070034import android.os.Binder;
Jonathan Basseri7697cae2015-07-06 15:49:23 -070035import android.os.Build;
Jonathan Basseri65273c82017-07-25 15:08:42 -070036import android.os.Bundle;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080037import android.os.Handler;
Rambo Wanga27fbe52022-04-12 19:09:07 +000038import android.os.HandlerExecutor;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080039import android.os.IBinder;
Rambo Wang7e3bc122021-03-23 09:24:38 -070040import android.os.Looper;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080041import android.os.Message;
Jonathan Basseric31f1f32015-05-12 10:13:03 -070042import android.os.PersistableBundle;
Hunter Knepshielde601f432020-02-19 10:16:04 -080043import android.os.Process;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080044import android.os.RemoteException;
Jonathan Basseri65273c82017-07-25 15:08:42 -070045import android.os.ResultReceiver;
Meng Wang97a6a462020-01-23 16:22:16 -080046import android.os.UserHandle;
Jonathan Basseri7697cae2015-07-06 15:49:23 -070047import android.preference.PreferenceManager;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080048import android.service.carrier.CarrierIdentifier;
Zach Johnson36d7aab2015-05-22 15:43:00 -070049import android.service.carrier.CarrierService;
50import android.service.carrier.ICarrierService;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080051import android.telephony.CarrierConfigManager;
52import android.telephony.SubscriptionManager;
Peter Wangc035ce42020-01-08 21:00:22 -080053import android.telephony.TelephonyFrameworkInitializer;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080054import android.telephony.TelephonyManager;
rambowangd63ba342022-10-02 11:21:08 -050055import android.telephony.TelephonyRegistryManager;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -080056import android.text.TextUtils;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -080057import android.util.ArraySet;
chen xudb04c292019-03-26 17:01:15 -070058import android.util.LocalLog;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080059import android.util.Log;
60
Rambo Wang7e3bc122021-03-23 09:24:38 -070061import com.android.internal.annotations.VisibleForTesting;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080062import com.android.internal.telephony.ICarrierConfigLoader;
63import com.android.internal.telephony.IccCardConstants;
64import com.android.internal.telephony.Phone;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080065import com.android.internal.telephony.PhoneFactory;
Nathan Harold48ac0972019-03-13 22:33:01 -070066import com.android.internal.telephony.SubscriptionInfoUpdater;
Jeff Davidsona8e4e242018-03-15 17:16:18 -070067import com.android.internal.telephony.TelephonyPermissions;
Jack Yue37dd262022-12-16 11:53:37 -080068import com.android.internal.telephony.subscription.SubscriptionManagerService;
Meng Wanga320b942019-11-25 11:21:26 -080069import com.android.internal.telephony.util.ArrayUtils;
shuoq26a3a4c2016-12-16 11:06:48 -080070import com.android.internal.util.IndentingPrintWriter;
arunvoddu664c36a2021-10-11 20:09:28 +000071import com.android.telephony.Rlog;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080072
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070073import java.io.File;
Junda Liu43d723a2015-05-12 17:23:45 -070074import java.io.FileDescriptor;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070075import java.io.FileInputStream;
76import java.io.FileNotFoundException;
77import java.io.FileOutputStream;
Jonathan Basseri1f743c92015-05-15 00:19:46 -070078import java.io.FilenameFilter;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070079import java.io.IOException;
Junda Liu43d723a2015-05-12 17:23:45 -070080import java.io.PrintWriter;
shuoq26a3a4c2016-12-16 11:06:48 -080081import java.util.ArrayList;
82import java.util.Arrays;
83import java.util.Collections;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080084import java.util.List;
rambowang14757c22022-10-03 11:54:56 -050085import java.util.Objects;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -080086import java.util.Set;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080087
88/**
89 * CarrierConfigLoader binds to privileged carrier apps to fetch carrier config overlays.
Jonathan Basseri6465afd2015-02-25 13:05:57 -080090 */
Jonathan Basseri6465afd2015-02-25 13:05:57 -080091public class CarrierConfigLoader extends ICarrierConfigLoader.Stub {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070092 private static final String LOG_TAG = "CarrierConfigLoader";
Meng Wang33ad2bc2017-03-16 20:21:20 -070093
94 // Package name for platform carrier config app, bundled with system image.
Rambo Wangfe0d7c12022-04-15 03:00:32 +000095 @NonNull private final String mPlatformCarrierConfigPackage;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080096
97 /** The singleton instance. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +000098 @Nullable private static CarrierConfigLoader sInstance;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080099 // The context for phone app, passed from PhoneGlobals.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000100 @NonNull private Context mContext;
101
102 // All the states below (array indexed by phoneId) are non-null. But the member of the array
103 // is nullable, when e.g. the config for the phone is not loaded yet
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800104 // Carrier configs from default app, indexed by phoneID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000105 @NonNull private PersistableBundle[] mConfigFromDefaultApp;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800106 // Carrier configs from privileged carrier config app, indexed by phoneID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000107 @NonNull private PersistableBundle[] mConfigFromCarrierApp;
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100108 // Persistent Carrier configs that are provided via the override test API, indexed by phone ID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000109 @NonNull private PersistableBundle[] mPersistentOverrideConfigs;
Hall Liu506724b2018-10-22 18:16:14 -0700110 // Carrier configs that are provided via the override test API, indexed by phone ID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000111 @NonNull private PersistableBundle[] mOverrideConfigs;
Jayachandran C645ec612020-01-10 10:30:25 -0800112 // Carrier configs to override code default when there is no SIM inserted
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000113 @NonNull private PersistableBundle mNoSimConfig;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800114 // Service connection for binding to config app.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000115 @NonNull private CarrierServiceConnection[] mServiceConnection;
Jayachandran C645ec612020-01-10 10:30:25 -0800116 // Service connection for binding to carrier config app for no SIM config.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000117 @NonNull private CarrierServiceConnection[] mServiceConnectionForNoSimConfig;
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700118 // Whether we are bound to a service for each phone
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000119 @NonNull private boolean[] mServiceBound;
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700120 // Whether we are bound to a service for no SIM config
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000121 @NonNull private boolean[] mServiceBoundForNoSimConfig;
Sarah Chin807d5c62020-03-30 17:21:09 -0700122 // Whether we have sent config change broadcast for each phone id.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000123 @NonNull private boolean[] mHasSentConfigChange;
Sarah Chin807d5c62020-03-30 17:21:09 -0700124 // Whether the broadcast was sent from EVENT_SYSTEM_UNLOCKED, to track rebroadcasts
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000125 @NonNull private boolean[] mFromSystemUnlocked;
Rambo Wanga27fbe52022-04-12 19:09:07 +0000126 // CarrierService change monitoring
127 @NonNull private CarrierServiceChangeCallback[] mCarrierServiceChangeCallbacks;
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000128
Nathan Harold48ac0972019-03-13 22:33:01 -0700129 // SubscriptionInfoUpdater
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000130 @NonNull private final SubscriptionInfoUpdater mSubscriptionInfoUpdater;
Rambo Wanga27fbe52022-04-12 19:09:07 +0000131 // Broadcast receiver for system events (BootCompleted, MultiSimConfigChanged etc.)
132 @NonNull
133 private final BroadcastReceiver mSystemBroadcastReceiver = new ConfigLoaderBroadcastReceiver();
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000134 @NonNull private final LocalLog mCarrierConfigLoadingLog = new LocalLog(100);
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000135 // Number of phone instances (active modem count)
136 private int mNumPhones;
chen xudb04c292019-03-26 17:01:15 -0700137
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800138
139 // Message codes; see mHandler below.
140 // Request from SubscriptionInfoUpdater when SIM becomes absent or error.
141 private static final int EVENT_CLEAR_CONFIG = 0;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800142 // Has connected to default app.
143 private static final int EVENT_CONNECTED_TO_DEFAULT = 3;
144 // Has connected to carrier app.
145 private static final int EVENT_CONNECTED_TO_CARRIER = 4;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700146 // Config has been loaded from default app (or cache).
147 private static final int EVENT_FETCH_DEFAULT_DONE = 5;
148 // Config has been loaded from carrier app (or cache).
149 private static final int EVENT_FETCH_CARRIER_DONE = 6;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700150 // Attempt to fetch from default app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700151 private static final int EVENT_DO_FETCH_DEFAULT = 7;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700152 // Attempt to fetch from carrier app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700153 private static final int EVENT_DO_FETCH_CARRIER = 8;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700154 // A package has been installed, uninstalled, or updated.
155 private static final int EVENT_PACKAGE_CHANGED = 9;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700156 // Bind timed out for the default app.
157 private static final int EVENT_BIND_DEFAULT_TIMEOUT = 10;
158 // Bind timed out for a carrier app.
159 private static final int EVENT_BIND_CARRIER_TIMEOUT = 11;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700160 // Check if the system fingerprint has changed.
161 private static final int EVENT_CHECK_SYSTEM_UPDATE = 12;
Nanxi Chen3d670502016-03-17 16:32:09 -0700162 // Rerun carrier config binding after system is unlocked.
163 private static final int EVENT_SYSTEM_UNLOCKED = 13;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700164 // Fetching config timed out from the default app.
165 private static final int EVENT_FETCH_DEFAULT_TIMEOUT = 14;
166 // Fetching config timed out from a carrier app.
167 private static final int EVENT_FETCH_CARRIER_TIMEOUT = 15;
Nathan Harold48ac0972019-03-13 22:33:01 -0700168 // SubscriptionInfoUpdater has finished updating the sub for the carrier config.
169 private static final int EVENT_SUBSCRIPTION_INFO_UPDATED = 16;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700170 // Multi-SIM config changed.
171 private static final int EVENT_MULTI_SIM_CONFIG_CHANGED = 17;
Jayachandran C645ec612020-01-10 10:30:25 -0800172 // Attempt to fetch from default app or read from XML for no SIM case.
173 private static final int EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG = 18;
174 // No SIM config has been loaded from default app (or cache).
175 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE = 19;
176 // Has connected to default app for no SIM config.
177 private static final int EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG = 20;
178 // Bind timed out for the default app when trying to fetch no SIM config.
179 private static final int EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 21;
180 // Fetching config timed out from the default app for no SIM config.
181 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 22;
Rambo Wangab13e3e2021-04-08 15:01:06 -0700182 // NOTE: any new EVENT_* values must be added to method eventToString().
Jonathan Basseri930701e2015-06-11 20:56:43 -0700183
Junda Liu6cb45002016-03-22 17:18:20 -0700184 private static final int BIND_TIMEOUT_MILLIS = 30000;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800185
Meng Wang0f6b2ea2020-01-06 18:31:16 -0800186 // Keys used for saving and restoring config bundle from file.
187 private static final String KEY_VERSION = "__carrier_config_package_version__";
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800188
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100189 private static final String OVERRIDE_PACKAGE_ADDITION = "-override";
190
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700191 // SharedPreferences key for last known build fingerprint.
192 private static final String KEY_FINGERPRINT = "build_fingerprint";
193
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -0800194 // Argument for #dump that indicates we should also call the default and specified carrier
195 // service's #dump method. In multi-SIM devices, it's possible that carrier A is on SIM 1 and
196 // carrier B is on SIM 2, in which case we should not dump carrier B's service when carrier A
197 // requested the dump.
198 private static final String DUMP_ARG_REQUESTING_PACKAGE = "--requesting-package";
199
rambowang14757c22022-10-03 11:54:56 -0500200 // Configs that should always be included when clients calls getConfig[ForSubId] with specified
201 // keys (even configs are not explicitly specified). Those configs have special purpose for the
202 // carrier config APIs to work correctly.
203 private static final String[] CONFIG_SUBSET_METADATA_KEYS = new String[] {
204 CarrierConfigManager.KEY_CARRIER_CONFIG_VERSION_STRING,
205 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL
206 };
207
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800208 // Handler to process various events.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700209 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700210 // For each phoneId, the event sequence should be:
Jonathan Basseri65273c82017-07-25 15:08:42 -0700211 // fetch default, connected to default, fetch default (async), fetch default done,
212 // fetch carrier, connected to carrier, fetch carrier (async), fetch carrier done.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700213 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700214 // If there is a saved config file for either the default app or the carrier app, we skip
215 // binding to the app and go straight from fetch to loaded.
216 //
217 // At any time, at most one connection is active. If events are not in this order, previous
218 // connection will be unbound, so only latest event takes effect.
219 //
220 // We broadcast ACTION_CARRIER_CONFIG_CHANGED after:
221 // 1. loading from carrier app (even if read from a file)
222 // 2. loading from default app if there is no carrier app (even if read from a file)
223 // 3. clearing config (e.g. due to sim removal)
224 // 4. encountering bind or IPC error
Jonathan Basseri65273c82017-07-25 15:08:42 -0700225 private class ConfigHandler extends Handler {
Rambo Wang7e3bc122021-03-23 09:24:38 -0700226 ConfigHandler(@NonNull Looper looper) {
227 super(looper);
228 }
229
Jonathan Basseri65273c82017-07-25 15:08:42 -0700230 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000231 public void handleMessage(@NonNull Message msg) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700232 final int phoneId = msg.arg1;
Rambo Wangab13e3e2021-04-08 15:01:06 -0700233 logdWithLocalLog("mHandler: " + eventToString(msg.what) + " phoneId: " + phoneId);
Malcolm Chen5ea18532019-10-24 19:55:44 -0700234 if (!SubscriptionManager.isValidPhoneId(phoneId)
235 && msg.what != EVENT_MULTI_SIM_CONFIG_CHANGED) {
236 return;
237 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800238 switch (msg.what) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800239 case EVENT_CLEAR_CONFIG: {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700240 clearConfigForPhone(phoneId, true);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800241 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700242 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700243
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800244 case EVENT_SYSTEM_UNLOCKED: {
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000245 for (int i = 0; i < mNumPhones; ++i) {
Sarah Chin807d5c62020-03-30 17:21:09 -0700246 // When the user unlocks the device, send the broadcast again (with a
247 // rebroadcast extra) if we have sent it before unlock. This will avoid
248 // trying to load the carrier config when the SIM is still loading when the
249 // unlock happens.
Junda Liu03aad762017-07-21 13:32:17 -0700250 if (mHasSentConfigChange[i]) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800251 logdWithLocalLog("System unlocked");
Sarah Chin807d5c62020-03-30 17:21:09 -0700252 mFromSystemUnlocked[i] = true;
Junda Liu03aad762017-07-21 13:32:17 -0700253 updateConfigForPhoneId(i);
254 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700255 }
256 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700257 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700258
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800259 case EVENT_PACKAGE_CHANGED: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700260 final String carrierPackageName = (String) msg.obj;
Rambo Wanga27fbe52022-04-12 19:09:07 +0000261 // Always clear up the cache and re-load config from scratch since the carrier
262 // service change is reliable and specific to the phoneId now.
263 clearCachedConfigForPackage(carrierPackageName);
264 logdWithLocalLog("Package changed: " + carrierPackageName
265 + ", phone=" + phoneId);
266 updateConfigForPhoneId(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700267 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700268 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700269
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800270 case EVENT_DO_FETCH_DEFAULT: {
Rambo Wang9bc7d362021-03-09 09:10:58 -0800271 // Clear in-memory cache for carrier app config, so when carrier app gets
272 // uninstalled, no stale config is left.
273 if (mConfigFromCarrierApp[phoneId] != null
274 && getCarrierPackageForPhoneId(phoneId) == null) {
275 mConfigFromCarrierApp[phoneId] = null;
276 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100277 // Restore persistent override values.
278 PersistableBundle config = restoreConfigFromXml(
279 mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION, phoneId);
280 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800281 logd("Loaded persistent override config from XML. package="
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100282 + mPlatformCarrierConfigPackage
283 + " phoneId=" + phoneId);
284 mPersistentOverrideConfigs[phoneId] = config;
285 }
286
287 config = restoreConfigFromXml(mPlatformCarrierConfigPackage, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700288 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800289 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700290 "Loaded config from XML. package="
291 + mPlatformCarrierConfigPackage
292 + " phoneId="
293 + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700294 mConfigFromDefaultApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700295 Message newMsg = obtainMessage(EVENT_FETCH_DEFAULT_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700296 newMsg.getData().putBoolean("loaded_from_xml", true);
297 mHandler.sendMessage(newMsg);
298 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700299 // No cached config, so fetch it from the default app.
300 if (bindToConfigPackage(
301 mPlatformCarrierConfigPackage,
302 phoneId,
303 EVENT_CONNECTED_TO_DEFAULT)) {
304 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800305 obtainMessage(EVENT_BIND_DEFAULT_TIMEOUT, phoneId, -1 /*arg2*/,
306 getMessageToken(phoneId)),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700307 BIND_TIMEOUT_MILLIS);
308 } else {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800309 // Put a stub bundle in place so that the rest of the logic continues
310 // smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000311 mConfigFromDefaultApp[phoneId] = new PersistableBundle();
Jonathan Basseri65273c82017-07-25 15:08:42 -0700312 // Send broadcast if bind fails.
Jack Yue37dd262022-12-16 11:53:37 -0800313 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700314 // TODO: We *must* call unbindService even if bindService returns false.
315 // (And possibly if SecurityException was thrown.)
chen xudb04c292019-03-26 17:01:15 -0700316 loge("binding to default app: "
317 + mPlatformCarrierConfigPackage + " fails");
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700318 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800319 }
320 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700321 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800322
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800323 case EVENT_CONNECTED_TO_DEFAULT: {
Rambo Wang610fdf62021-03-08 21:37:11 -0800324 removeMessages(EVENT_BIND_DEFAULT_TIMEOUT, getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700325 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800326 // If new service connection has been created, unbind.
327 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700328 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800329 break;
330 }
chen xu02581692018-11-11 19:03:44 -0800331 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700332 // ResultReceiver callback will execute in this Handler's thread.
333 final ResultReceiver resultReceiver =
334 new ResultReceiver(this) {
335 @Override
336 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700337 unbindIfBound(mContext, conn, phoneId);
Rambo Wanga9d27a52021-04-09 16:17:33 -0700338 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT,
339 getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700340 // If new service connection has been created, this is stale.
341 if (mServiceConnection[phoneId] != conn) {
342 loge("Received response for stale request.");
343 return;
344 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700345 if (resultCode == RESULT_ERROR || resultData == null) {
346 // On error, abort config fetching.
347 loge("Failed to get carrier config");
Jack Yue37dd262022-12-16 11:53:37 -0800348 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700349 return;
350 }
351 PersistableBundle config =
352 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100353 saveConfigToXml(mPlatformCarrierConfigPackage, "", phoneId,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800354 carrierId, config);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700355 mConfigFromDefaultApp[phoneId] = config;
356 sendMessage(
357 obtainMessage(
358 EVENT_FETCH_DEFAULT_DONE, phoneId, -1));
359 }
360 };
361 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800362 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700363 ICarrierService carrierService =
364 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800365 carrierService.getCarrierConfig(phoneId, carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800366 logdWithLocalLog("Fetch config for default app: "
chen xudb04c292019-03-26 17:01:15 -0700367 + mPlatformCarrierConfigPackage
368 + " carrierid: " + carrierId.toString());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700369 } catch (RemoteException e) {
chen xudb04c292019-03-26 17:01:15 -0700370 loge("Failed to get carrier config from default app: " +
371 mPlatformCarrierConfigPackage + " err: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700372 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700373 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800374 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700375 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800376 obtainMessage(EVENT_FETCH_DEFAULT_TIMEOUT, phoneId, -1 /*arg2*/,
377 getMessageToken(phoneId)),
Jonathan Basseri65273c82017-07-25 15:08:42 -0700378 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800379 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700380 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800381
Jonathan Basseri930701e2015-06-11 20:56:43 -0700382 case EVENT_BIND_DEFAULT_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800383 case EVENT_FETCH_DEFAULT_TIMEOUT: {
384 loge("Bind/fetch time out from " + mPlatformCarrierConfigPackage);
Rambo Wang610fdf62021-03-08 21:37:11 -0800385 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT, getMessageToken(phoneId));
chen xuf60b3162019-05-01 21:31:05 -0700386 // If we attempted to bind to the app, but the service connection is null due to
387 // the race condition that clear config event happens before bind/fetch complete
388 // then config was cleared while we were waiting and we should not continue.
389 if (mServiceConnection[phoneId] != null) {
390 // If a ResponseReceiver callback is in the queue when this happens, we will
391 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700392 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700393 broadcastConfigChangedIntent(phoneId);
394 }
Nathan Harold1122e3d2021-01-22 15:45:24 -0800395 // Put a stub bundle in place so that the rest of the logic continues smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000396 mConfigFromDefaultApp[phoneId] = new PersistableBundle();
Jack Yue37dd262022-12-16 11:53:37 -0800397 updateSubscriptionDatabase(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700398 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700399 }
Jonathan Basseri930701e2015-06-11 20:56:43 -0700400
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800401 case EVENT_FETCH_DEFAULT_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700402 // If we attempted to bind to the app, but the service connection is null, then
403 // config was cleared while we were waiting and we should not continue.
404 if (!msg.getData().getBoolean("loaded_from_xml", false)
405 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800406 break;
407 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700408 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700409 if (carrierPackageName != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800410 logd("Found carrier config app: " + carrierPackageName);
Jordan Liu38a614c2019-03-20 15:01:17 -0700411 sendMessage(obtainMessage(EVENT_DO_FETCH_CARRIER, phoneId, -1));
Jonathan Basserib919e932015-05-27 16:53:08 +0000412 } else {
Jack Yue37dd262022-12-16 11:53:37 -0800413 updateSubscriptionDatabase(phoneId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700414 }
415 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700416 }
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700417
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800418 case EVENT_DO_FETCH_CARRIER: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700419 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700420 final PersistableBundle config =
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100421 restoreConfigFromXml(carrierPackageName, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700422 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800423 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700424 "Loaded config from XML. package="
425 + carrierPackageName
426 + " phoneId="
427 + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700428 mConfigFromCarrierApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700429 Message newMsg = obtainMessage(EVENT_FETCH_CARRIER_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700430 newMsg.getData().putBoolean("loaded_from_xml", true);
431 sendMessage(newMsg);
432 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700433 // No cached config, so fetch it from a carrier app.
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800434 if (carrierPackageName != null && bindToConfigPackage(carrierPackageName,
435 phoneId, EVENT_CONNECTED_TO_CARRIER)) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700436 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800437 obtainMessage(EVENT_BIND_CARRIER_TIMEOUT, phoneId, -1 /*arg2*/,
438 getMessageToken(phoneId)),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700439 BIND_TIMEOUT_MILLIS);
440 } else {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800441 // Put a stub bundle in place so that the rest of the logic continues
442 // smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000443 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
Jonathan Basseri65273c82017-07-25 15:08:42 -0700444 // Send broadcast if bind fails.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700445 broadcastConfigChangedIntent(phoneId);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800446 loge("Bind to carrier app: " + carrierPackageName + " fails");
Jack Yue37dd262022-12-16 11:53:37 -0800447 updateSubscriptionDatabase(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700448 }
449 }
450 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700451 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700452
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800453 case EVENT_CONNECTED_TO_CARRIER: {
Rambo Wang610fdf62021-03-08 21:37:11 -0800454 removeMessages(EVENT_BIND_CARRIER_TIMEOUT, getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700455 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800456 // If new service connection has been created, unbind.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700457 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700458 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800459 break;
460 }
chen xu02581692018-11-11 19:03:44 -0800461 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700462 // ResultReceiver callback will execute in this Handler's thread.
463 final ResultReceiver resultReceiver =
464 new ResultReceiver(this) {
465 @Override
466 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700467 unbindIfBound(mContext, conn, phoneId);
Rambo Wanga9d27a52021-04-09 16:17:33 -0700468 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT,
469 getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700470 // If new service connection has been created, this is stale.
471 if (mServiceConnection[phoneId] != conn) {
472 loge("Received response for stale request.");
473 return;
474 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700475 if (resultCode == RESULT_ERROR || resultData == null) {
476 // On error, abort config fetching.
chen xudb04c292019-03-26 17:01:15 -0700477 loge("Failed to get carrier config from carrier app: "
478 + getCarrierPackageForPhoneId(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700479 broadcastConfigChangedIntent(phoneId);
Jack Yue37dd262022-12-16 11:53:37 -0800480 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700481 return;
482 }
483 PersistableBundle config =
484 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100485 saveConfigToXml(getCarrierPackageForPhoneId(phoneId), "",
486 phoneId, carrierId, config);
Amit Mahajan304e92b2021-04-08 14:03:30 -0700487 if (config != null) {
488 mConfigFromCarrierApp[phoneId] = config;
489 } else {
490 logdWithLocalLog("Config from carrier app is null "
491 + "for phoneId " + phoneId);
492 // Put a stub bundle in place so that the rest of the logic
493 // continues smoothly.
494 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
495 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700496 sendMessage(
497 obtainMessage(
498 EVENT_FETCH_CARRIER_DONE, phoneId, -1));
499 }
500 };
501 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800502 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700503 ICarrierService carrierService =
504 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800505 carrierService.getCarrierConfig(phoneId, carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800506 logdWithLocalLog("Fetch config for carrier app: "
chen xudb04c292019-03-26 17:01:15 -0700507 + getCarrierPackageForPhoneId(phoneId)
508 + " carrierid: " + carrierId.toString());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700509 } catch (RemoteException e) {
510 loge("Failed to get carrier config: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700511 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700512 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800513 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700514 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800515 obtainMessage(EVENT_FETCH_CARRIER_TIMEOUT, phoneId, -1 /*arg2*/,
516 getMessageToken(phoneId)),
Jonathan Basseri65273c82017-07-25 15:08:42 -0700517 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800518 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700519 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800520
Jonathan Basseri930701e2015-06-11 20:56:43 -0700521 case EVENT_BIND_CARRIER_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800522 case EVENT_FETCH_CARRIER_TIMEOUT: {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800523 loge("Bind/fetch from carrier app timeout, package="
524 + getCarrierPackageForPhoneId(phoneId));
Rambo Wang610fdf62021-03-08 21:37:11 -0800525 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT, getMessageToken(phoneId));
chen xuf60b3162019-05-01 21:31:05 -0700526 // If we attempted to bind to the app, but the service connection is null due to
527 // the race condition that clear config event happens before bind/fetch complete
528 // then config was cleared while we were waiting and we should not continue.
529 if (mServiceConnection[phoneId] != null) {
530 // If a ResponseReceiver callback is in the queue when this happens, we will
531 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700532 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700533 broadcastConfigChangedIntent(phoneId);
534 }
Nathan Harold1122e3d2021-01-22 15:45:24 -0800535 // Put a stub bundle in place so that the rest of the logic continues smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000536 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
Jack Yue37dd262022-12-16 11:53:37 -0800537 updateSubscriptionDatabase(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700538 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700539 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800540 case EVENT_FETCH_CARRIER_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700541 // If we attempted to bind to the app, but the service connection is null, then
542 // config was cleared while we were waiting and we should not continue.
543 if (!msg.getData().getBoolean("loaded_from_xml", false)
544 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800545 break;
546 }
Jack Yue37dd262022-12-16 11:53:37 -0800547 updateSubscriptionDatabase(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800548 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700549 }
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700550
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800551 case EVENT_CHECK_SYSTEM_UPDATE: {
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700552 SharedPreferences sharedPrefs =
553 PreferenceManager.getDefaultSharedPreferences(mContext);
554 final String lastFingerprint = sharedPrefs.getString(KEY_FINGERPRINT, null);
555 if (!Build.FINGERPRINT.equals(lastFingerprint)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800556 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700557 "Build fingerprint changed. old: "
558 + lastFingerprint
559 + " new: "
560 + Build.FINGERPRINT);
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700561 clearCachedConfigForPackage(null);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700562 sharedPrefs
563 .edit()
564 .putString(KEY_FINGERPRINT, Build.FINGERPRINT)
565 .apply();
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700566 }
567 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700568 }
Nathan Harold48ac0972019-03-13 22:33:01 -0700569
570 case EVENT_SUBSCRIPTION_INFO_UPDATED:
571 broadcastConfigChangedIntent(phoneId);
572 break;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700573 case EVENT_MULTI_SIM_CONFIG_CHANGED:
574 onMultiSimConfigChanged();
575 break;
Jayachandran C645ec612020-01-10 10:30:25 -0800576
577 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG: {
578 PersistableBundle config =
579 restoreNoSimConfigFromXml(mPlatformCarrierConfigPackage);
580
581 if (config != null) {
582 logd("Loaded no SIM config from XML. package="
583 + mPlatformCarrierConfigPackage);
584 mNoSimConfig = config;
585 sendMessage(
586 obtainMessage(
587 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
588 phoneId, -1));
589 } else {
590 // No cached config, so fetch it from the default app.
591 if (bindToConfigPackage(
592 mPlatformCarrierConfigPackage,
593 phoneId,
594 EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG)) {
595 sendMessageDelayed(
596 obtainMessage(
597 EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
598 phoneId, -1), BIND_TIMEOUT_MILLIS);
599 } else {
600 broadcastConfigChangedIntent(phoneId, false);
601 // TODO: We *must* call unbindService even if bindService returns false.
602 // (And possibly if SecurityException was thrown.)
603 loge("binding to default app to fetch no SIM config: "
604 + mPlatformCarrierConfigPackage + " fails");
605 }
606 }
607 break;
608 }
609
610 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE: {
611 broadcastConfigChangedIntent(phoneId, false);
612 break;
613 }
614
615 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
616 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT: {
617 loge("Bind/fetch time out for no SIM config from "
618 + mPlatformCarrierConfigPackage);
619 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
620 // If we attempted to bind to the app, but the service connection is null due to
621 // the race condition that clear config event happens before bind/fetch complete
622 // then config was cleared while we were waiting and we should not continue.
623 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
624 // If a ResponseReceiver callback is in the queue when this happens, we will
625 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700626 unbindIfBoundForNoSimConfig(mContext,
627 mServiceConnectionForNoSimConfig[phoneId], phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800628 }
629 broadcastConfigChangedIntent(phoneId, false);
630 break;
631 }
632
633 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG: {
634 removeMessages(EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
635 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
636 // If new service connection has been created, unbind.
637 if (mServiceConnectionForNoSimConfig[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700638 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800639 break;
640 }
641
642 // ResultReceiver callback will execute in this Handler's thread.
643 final ResultReceiver resultReceiver =
644 new ResultReceiver(this) {
645 @Override
646 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700647 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800648 // If new service connection has been created, this is stale.
649 if (mServiceConnectionForNoSimConfig[phoneId] != conn) {
650 loge("Received response for stale request.");
651 return;
652 }
653 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
654 if (resultCode == RESULT_ERROR || resultData == null) {
655 // On error, abort config fetching.
656 loge("Failed to get no SIM carrier config");
657 return;
658 }
659 PersistableBundle config =
660 resultData.getParcelable(KEY_CONFIG_BUNDLE);
661 saveNoSimConfigToXml(mPlatformCarrierConfigPackage, config);
662 mNoSimConfig = config;
663 sendMessage(
664 obtainMessage(
665 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
666 phoneId, -1));
667 }
668 };
669 // Now fetch the config asynchronously from the ICarrierService.
670 try {
671 ICarrierService carrierService =
672 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800673 carrierService.getCarrierConfig(phoneId, null, resultReceiver);
Jayachandran C645ec612020-01-10 10:30:25 -0800674 logdWithLocalLog("Fetch no sim config from default app: "
675 + mPlatformCarrierConfigPackage);
676 } catch (RemoteException e) {
677 loge("Failed to get no sim carrier config from default app: " +
678 mPlatformCarrierConfigPackage + " err: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700679 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800680 break; // So we don't set a timeout.
681 }
682 sendMessageDelayed(
683 obtainMessage(
684 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
685 phoneId, -1), BIND_TIMEOUT_MILLIS);
686 break;
687 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800688 }
689 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700690 }
691
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000692 @NonNull private final Handler mHandler;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800693
694 /**
695 * Constructs a CarrierConfigLoader, registers it as a service, and registers a broadcast
696 * receiver for relevant events.
697 */
Rambo Wang7e3bc122021-03-23 09:24:38 -0700698 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000699 /* package */ CarrierConfigLoader(@NonNull Context context,
Jack Yue37dd262022-12-16 11:53:37 -0800700 //TODO: Remove SubscriptionInfoUpdater.
701 @Nullable SubscriptionInfoUpdater subscriptionInfoUpdater, @NonNull Looper looper) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800702 mContext = context;
Meng Wang33ad2bc2017-03-16 20:21:20 -0700703 mPlatformCarrierConfigPackage =
704 mContext.getString(R.string.platform_carrier_config_package);
Rambo Wang7e3bc122021-03-23 09:24:38 -0700705 mHandler = new ConfigHandler(looper);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800706
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000707 IntentFilter systemEventsFilter = new IntentFilter();
708 systemEventsFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
709 systemEventsFilter.addAction(TelephonyManager.ACTION_MULTI_SIM_CONFIG_CHANGED);
Rambo Wanga27fbe52022-04-12 19:09:07 +0000710 context.registerReceiver(mSystemBroadcastReceiver, systemEventsFilter);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800711
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000712 mNumPhones = TelephonyManager.from(context).getActiveModemCount();
713 mConfigFromDefaultApp = new PersistableBundle[mNumPhones];
714 mConfigFromCarrierApp = new PersistableBundle[mNumPhones];
715 mPersistentOverrideConfigs = new PersistableBundle[mNumPhones];
716 mOverrideConfigs = new PersistableBundle[mNumPhones];
Rambo Wang42026112021-04-07 20:57:28 +0000717 mNoSimConfig = new PersistableBundle();
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000718 mServiceConnection = new CarrierServiceConnection[mNumPhones];
719 mServiceBound = new boolean[mNumPhones];
720 mHasSentConfigChange = new boolean[mNumPhones];
721 mFromSystemUnlocked = new boolean[mNumPhones];
722 mServiceConnectionForNoSimConfig = new CarrierServiceConnection[mNumPhones];
723 mServiceBoundForNoSimConfig = new boolean[mNumPhones];
Rambo Wanga27fbe52022-04-12 19:09:07 +0000724 mCarrierServiceChangeCallbacks = new CarrierServiceChangeCallback[mNumPhones];
725 for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
726 mCarrierServiceChangeCallbacks[phoneId] = new CarrierServiceChangeCallback(phoneId);
727 TelephonyManager.from(context).registerCarrierPrivilegesCallback(phoneId,
728 new HandlerExecutor(mHandler), mCarrierServiceChangeCallbacks[phoneId]);
729 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800730 logd("CarrierConfigLoader has started");
Rambo Wang7e3bc122021-03-23 09:24:38 -0700731 mSubscriptionInfoUpdater = subscriptionInfoUpdater;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700732 mHandler.sendEmptyMessage(EVENT_CHECK_SYSTEM_UPDATE);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800733 }
734
735 /**
736 * Initialize the singleton CarrierConfigLoader instance.
737 *
738 * This is only done once, at startup, from {@link com.android.phone.PhoneApp#onCreate}.
739 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000740 @NonNull
741 /* package */ static CarrierConfigLoader init(@NonNull Context context) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800742 synchronized (CarrierConfigLoader.class) {
743 if (sInstance == null) {
Rambo Wang7e3bc122021-03-23 09:24:38 -0700744 sInstance = new CarrierConfigLoader(context,
745 PhoneFactory.getSubscriptionInfoUpdater(), Looper.myLooper());
Brad Ebingerfa6575f2021-05-04 00:29:50 +0000746 // Make this service available through ServiceManager.
747 TelephonyFrameworkInitializer.getTelephonyServiceManager()
748 .getCarrierConfigServiceRegisterer().register(sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800749 } else {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700750 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800751 }
752 return sInstance;
753 }
754 }
755
Rambo Wang7e3bc122021-03-23 09:24:38 -0700756 @VisibleForTesting
757 /* package */ void clearConfigForPhone(int phoneId, boolean fetchNoSimConfig) {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700758 /* Ignore clear configuration request if device is being shutdown. */
759 Phone phone = PhoneFactory.getPhone(phoneId);
760 if (phone != null) {
761 if (phone.isShuttingDown()) {
762 return;
763 }
764 }
765
766 mConfigFromDefaultApp[phoneId] = null;
767 mConfigFromCarrierApp[phoneId] = null;
768 mServiceConnection[phoneId] = null;
769 mHasSentConfigChange[phoneId] = false;
770
Jayachandran C645ec612020-01-10 10:30:25 -0800771 if (fetchNoSimConfig) {
772 // To fetch no SIM config
773 mHandler.sendMessage(
774 mHandler.obtainMessage(
775 EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG, phoneId, -1));
776 }
Malcolm Chen5ea18532019-10-24 19:55:44 -0700777 }
778
Jack Yue37dd262022-12-16 11:53:37 -0800779 private void updateSubscriptionDatabase(int phoneId) {
Jack Yu90813e62023-01-17 17:46:27 -0800780 logd("updateSubscriptionDatabase: phoneId=" + phoneId);
Jack Yue37dd262022-12-16 11:53:37 -0800781 String configPackageName;
Nathan Harold48ac0972019-03-13 22:33:01 -0700782 PersistableBundle configToSend;
783 int carrierId = getSpecificCarrierIdForPhoneId(phoneId);
784 // Prefer the carrier privileged carrier app, but if there is not one, use the platform
785 // default carrier app.
786 if (mConfigFromCarrierApp[phoneId] != null) {
Jack Yue37dd262022-12-16 11:53:37 -0800787 configPackageName = getCarrierPackageForPhoneId(phoneId);
Nathan Harold48ac0972019-03-13 22:33:01 -0700788 configToSend = mConfigFromCarrierApp[phoneId];
789 } else {
Jack Yue37dd262022-12-16 11:53:37 -0800790 configPackageName = mPlatformCarrierConfigPackage;
Nathan Harold48ac0972019-03-13 22:33:01 -0700791 configToSend = mConfigFromDefaultApp[phoneId];
792 }
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700793
Malcolm Chenefafd1c2020-02-20 13:27:08 -0800794 if (configToSend == null) {
Rambo Wang42026112021-04-07 20:57:28 +0000795 configToSend = new PersistableBundle();
Malcolm Chenefafd1c2020-02-20 13:27:08 -0800796 }
797
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700798 // mOverrideConfigs is for testing. And it will override current configs.
799 PersistableBundle config = mOverrideConfigs[phoneId];
800 if (config != null) {
Torbjorn Eklund1050cb02018-11-16 14:05:38 +0100801 configToSend = new PersistableBundle(configToSend);
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700802 configToSend.putAll(config);
803 }
804
Jack Yue37dd262022-12-16 11:53:37 -0800805 if (PhoneFactory.isSubscriptionManagerServiceEnabled()) {
806 SubscriptionManagerService.getInstance().updateSubscriptionByCarrierConfig(
807 phoneId, configPackageName, configToSend,
808 () -> mHandler.obtainMessage(EVENT_SUBSCRIPTION_INFO_UPDATED, phoneId, -1)
809 .sendToTarget());
810 } else {
811 mSubscriptionInfoUpdater.updateSubscriptionByCarrierConfigAndNotifyComplete(
812 phoneId, configPackageName, configToSend,
813 mHandler.obtainMessage(EVENT_SUBSCRIPTION_INFO_UPDATED, phoneId, -1));
814 }
Nathan Harold48ac0972019-03-13 22:33:01 -0700815 }
816
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800817 private void broadcastConfigChangedIntent(int phoneId) {
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800818 broadcastConfigChangedIntent(phoneId, true);
819 }
820
821 private void broadcastConfigChangedIntent(int phoneId, boolean addSubIdExtra) {
rambowangd63ba342022-10-02 11:21:08 -0500822 int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
823 int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
824 int specificCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
825
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800826 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
Christopher Tate38f55eb2017-02-14 14:43:49 -0800827 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT |
chen xuf9db49f2019-03-31 23:04:42 -0700828 Intent.FLAG_RECEIVER_FOREGROUND);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800829 if (addSubIdExtra) {
rambowangd63ba342022-10-02 11:21:08 -0500830 int simApplicationState = getSimApplicationStateForPhone(phoneId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800831 // Include subId/carrier id extra only if SIM records are loaded
832 if (simApplicationState != TelephonyManager.SIM_STATE_UNKNOWN
833 && simApplicationState != TelephonyManager.SIM_STATE_NOT_READY) {
rambowangd63ba342022-10-02 11:21:08 -0500834 subId = SubscriptionManager.getSubscriptionId(phoneId);
835 carrierId = getCarrierIdForPhoneId(phoneId);
836 specificCarrierId = getSpecificCarrierIdForPhoneId(phoneId);
837 intent.putExtra(TelephonyManager.EXTRA_SPECIFIC_CARRIER_ID, specificCarrierId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800838 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, phoneId);
rambowangd63ba342022-10-02 11:21:08 -0500839 intent.putExtra(TelephonyManager.EXTRA_CARRIER_ID, carrierId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800840 }
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800841 }
Amit Mahajanb33bcda2018-01-24 12:56:44 -0800842 intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, phoneId);
Sarah Chin807d5c62020-03-30 17:21:09 -0700843 intent.putExtra(CarrierConfigManager.EXTRA_REBROADCAST_ON_UNLOCK,
844 mFromSystemUnlocked[phoneId]);
rambowangd63ba342022-10-02 11:21:08 -0500845
846 TelephonyRegistryManager trm = mContext.getSystemService(TelephonyRegistryManager.class);
847 // Unlike broadcast, we wouldn't notify registrants on carrier config change when device is
848 // unlocked. Only real carrier config change will send the notification to registrants.
849 if (trm != null && !mFromSystemUnlocked[phoneId]) {
850 trm.notifyCarrierConfigChanged(phoneId, subId, carrierId, specificCarrierId);
851 }
852
Meng Wang97a6a462020-01-23 16:22:16 -0800853 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
rambowangd63ba342022-10-02 11:21:08 -0500854
Jack Yu00ece8c2022-11-19 22:29:12 -0800855 if (SubscriptionManager.isValidSubscriptionId(subId)) {
856 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId + ", subId=" + subId);
Jack Yue9e95be2020-03-22 10:56:06 -0700857 } else {
858 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId);
859 }
Junda Liu03aad762017-07-21 13:32:17 -0700860 mHasSentConfigChange[phoneId] = true;
Sarah Chin807d5c62020-03-30 17:21:09 -0700861 mFromSystemUnlocked[phoneId] = false;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800862 }
863
rambowangd63ba342022-10-02 11:21:08 -0500864 private int getSimApplicationStateForPhone(int phoneId) {
865 int simApplicationState = TelephonyManager.SIM_STATE_UNKNOWN;
866 int subId = SubscriptionManager.getSubscriptionId(phoneId);
867 if (SubscriptionManager.isValidSubscriptionId(subId)) {
868 TelephonyManager telMgr = TelephonyManager.from(mContext)
869 .createForSubscriptionId(subId);
870 simApplicationState = telMgr.getSimApplicationState();
871 }
872 return simApplicationState;
873 }
874
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800875 /** Binds to the default or carrier config app. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000876 private boolean bindToConfigPackage(@NonNull String pkgName, int phoneId, int eventId) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800877 logdWithLocalLog("Binding to " + pkgName + " for phone " + phoneId);
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700878 Intent carrierService = new Intent(CarrierService.CARRIER_SERVICE_INTERFACE);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700879 carrierService.setPackage(pkgName);
Jayachandran C645ec612020-01-10 10:30:25 -0800880 CarrierServiceConnection serviceConnection = new CarrierServiceConnection(
881 phoneId, pkgName, eventId);
882 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
883 mServiceConnectionForNoSimConfig[phoneId] = serviceConnection;
884 } else {
885 mServiceConnection[phoneId] = serviceConnection;
886 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800887 try {
Jayachandran C645ec612020-01-10 10:30:25 -0800888 if (mContext.bindService(carrierService, serviceConnection,
Jordan Liu178430d2020-02-10 14:32:15 -0800889 Context.BIND_AUTO_CREATE)) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700890 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
891 mServiceBoundForNoSimConfig[phoneId] = true;
892 } else {
893 mServiceBound[phoneId] = true;
894 }
Jordan Liu178430d2020-02-10 14:32:15 -0800895 return true;
896 } else {
897 return false;
898 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800899 } catch (SecurityException ex) {
900 return false;
901 }
902 }
903
Rambo Wang7e3bc122021-03-23 09:24:38 -0700904 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000905 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -0700906 /* package */ CarrierIdentifier getCarrierIdentifierForPhoneId(int phoneId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800907 String mcc = "";
908 String mnc = "";
909 String imsi = "";
910 String gid1 = "";
911 String gid2 = "";
912 String spn = TelephonyManager.from(mContext).getSimOperatorNameForPhone(phoneId);
913 String simOperator = TelephonyManager.from(mContext).getSimOperatorNumericForPhone(phoneId);
chen xu02581692018-11-11 19:03:44 -0800914 int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
chen xua31f22b2019-03-06 15:28:50 -0800915 int specificCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
Jonathan Basseri1fa437c2015-04-20 11:08:18 -0700916 // A valid simOperator should be 5 or 6 digits, depending on the length of the MNC.
917 if (simOperator != null && simOperator.length() >= 3) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800918 mcc = simOperator.substring(0, 3);
919 mnc = simOperator.substring(3);
920 }
921 Phone phone = PhoneFactory.getPhone(phoneId);
922 if (phone != null) {
923 imsi = phone.getSubscriberId();
924 gid1 = phone.getGroupIdLevel1();
Junda Liu73183532015-05-14 13:55:40 -0700925 gid2 = phone.getGroupIdLevel2();
chen xu02581692018-11-11 19:03:44 -0800926 carrierId = phone.getCarrierId();
chen xua31f22b2019-03-06 15:28:50 -0800927 specificCarrierId = phone.getSpecificCarrierId();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800928 }
chen xua31f22b2019-03-06 15:28:50 -0800929 return new CarrierIdentifier(mcc, mnc, spn, imsi, gid1, gid2, carrierId, specificCarrierId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800930 }
931
Rambo Wangf7c214a2022-03-17 12:36:22 -0700932 /** Returns the package name of a privileged carrier app, or null if there is none. */
Nathan Harold1122e3d2021-01-22 15:45:24 -0800933 @Nullable
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700934 private String getCarrierPackageForPhoneId(int phoneId) {
Nazanin1adf4562021-03-29 15:35:30 -0700935 final long token = Binder.clearCallingIdentity();
936 try {
Rambo Wangf7c214a2022-03-17 12:36:22 -0700937 return TelephonyManager.from(mContext)
938 .getCarrierServicePackageNameForLogicalSlot(phoneId);
Nazanin1adf4562021-03-29 15:35:30 -0700939 } finally {
940 Binder.restoreCallingIdentity(token);
941 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700942 }
943
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000944 @Nullable
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700945 private String getIccIdForPhoneId(int phoneId) {
946 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
947 return null;
948 }
949 Phone phone = PhoneFactory.getPhone(phoneId);
950 if (phone == null) {
951 return null;
952 }
953 return phone.getIccSerialNumber();
954 }
955
chen xu02581692018-11-11 19:03:44 -0800956 /**
chen xua31f22b2019-03-06 15:28:50 -0800957 * Get the sim specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}
chen xu02581692018-11-11 19:03:44 -0800958 */
chen xua31f22b2019-03-06 15:28:50 -0800959 private int getSpecificCarrierIdForPhoneId(int phoneId) {
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700960 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
chen xu02581692018-11-11 19:03:44 -0800961 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700962 }
963 Phone phone = PhoneFactory.getPhone(phoneId);
964 if (phone == null) {
chen xu02581692018-11-11 19:03:44 -0800965 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700966 }
chen xua31f22b2019-03-06 15:28:50 -0800967 return phone.getSpecificCarrierId();
chen xu02581692018-11-11 19:03:44 -0800968 }
969
970 /**
971 * Get the sim carrier id {@link TelephonyManager#getSimCarrierId() }
972 */
973 private int getCarrierIdForPhoneId(int phoneId) {
974 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
975 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700976 }
chen xu02581692018-11-11 19:03:44 -0800977 Phone phone = PhoneFactory.getPhone(phoneId);
978 if (phone == null) {
979 return TelephonyManager.UNKNOWN_CARRIER_ID;
980 }
981 return phone.getCarrierId();
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700982 }
983
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700984 /**
985 * Writes a bundle to an XML file.
986 *
chen xu02581692018-11-11 19:03:44 -0800987 * The bundle will be written to a file named after the package name, ICCID and
chen xua31f22b2019-03-06 15:28:50 -0800988 * specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}. the same carrier
chen xu02581692018-11-11 19:03:44 -0800989 * should have a single copy of XML file named after carrier id. However, it's still possible
990 * that platform doesn't recognize the current sim carrier, we will use iccid + carrierid as
991 * the canonical file name. carrierid can also handle the cases SIM OTA resolves to different
992 * carrier while iccid remains the same.
993 *
994 * The file can be restored later with {@link @restoreConfigFromXml}. The XML output will
995 * include the bundle and the current version of the specified package.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700996 *
997 * In case of errors or invalid input, no file will be written.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700998 *
Jayachandran C645ec612020-01-10 10:30:25 -0800999 * @param packageName the name of the package from which we fetched this bundle.
1000 * @param extraString An extra string to be used in the XML file name.
1001 * @param phoneId the phone ID.
1002 * @param carrierId contains all carrier-identifying information.
1003 * @param config the bundle to be written. Null will be treated as an empty bundle.
1004 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001005 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001006 private void saveConfigToXml(@Nullable String packageName, @NonNull String extraString,
1007 int phoneId, @Nullable CarrierIdentifier carrierId, @NonNull PersistableBundle config,
1008 boolean isNoSimConfig) {
Jayachandran C645ec612020-01-10 10:30:25 -08001009 if (packageName == null) {
1010 loge("Cannot save config with null packageName");
Yuchen Dongc15afed2018-04-26 17:05:22 +08001011 return;
1012 }
1013
Jayachandran C645ec612020-01-10 10:30:25 -08001014 String fileName;
1015 if (isNoSimConfig) {
1016 fileName = getFilenameForNoSimConfig(packageName);
1017 } else {
Jack Yuf5badd92022-12-08 00:50:53 -08001018 if (TelephonyManager.getSimStateForSlotIndex(phoneId)
Jayachandran C645ec612020-01-10 10:30:25 -08001019 != TelephonyManager.SIM_STATE_LOADED) {
1020 loge("Skip save config because SIM records are not loaded.");
1021 return;
1022 }
1023
1024 final String iccid = getIccIdForPhoneId(phoneId);
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001025 final int cid = carrierId != null ? carrierId.getSpecificCarrierId()
1026 : TelephonyManager.UNKNOWN_CARRIER_ID;
Jayachandran C645ec612020-01-10 10:30:25 -08001027 if (iccid == null) {
1028 loge("Cannot save config with null iccid.");
1029 return;
1030 }
1031 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001032 }
Jayachandran C645ec612020-01-10 10:30:25 -08001033
Junda Liu02596502016-11-15 13:46:43 -08001034 // b/32668103 Only save to file if config isn't empty.
1035 // In case of failure, not caching an empty bundle will
1036 // try loading config again on next power on or sim loaded.
1037 // Downside is for genuinely empty bundle, will bind and load
1038 // on every power on.
1039 if (config == null || config.isEmpty()) {
1040 return;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001041 }
1042
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001043 final String version = getPackageVersion(packageName);
1044 if (version == null) {
1045 loge("Failed to get package version for: " + packageName);
1046 return;
1047 }
1048
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001049 logdWithLocalLog(
1050 "Save config to xml, packagename: " + packageName + " phoneId: " + phoneId);
chen xudb04c292019-03-26 17:01:15 -07001051
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001052 FileOutputStream outFile = null;
1053 try {
Jayachandran C645ec612020-01-10 10:30:25 -08001054 outFile = new FileOutputStream(new File(mContext.getFilesDir(), fileName));
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001055 config.putString(KEY_VERSION, version);
1056 config.writeToStream(outFile);
1057 outFile.flush();
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001058 outFile.close();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001059 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001060 loge(e.toString());
1061 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001062 }
1063
Rambo Wang7e3bc122021-03-23 09:24:38 -07001064 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001065 /* package */ void saveConfigToXml(@Nullable String packageName, @NonNull String extraString,
1066 int phoneId, @NonNull CarrierIdentifier carrierId, @NonNull PersistableBundle config) {
Jayachandran C645ec612020-01-10 10:30:25 -08001067 saveConfigToXml(packageName, extraString, phoneId, carrierId, config, false);
1068 }
1069
Rambo Wang7e3bc122021-03-23 09:24:38 -07001070 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001071 /* package */ void saveNoSimConfigToXml(@Nullable String packageName,
1072 @NonNull PersistableBundle config) {
Jayachandran C645ec612020-01-10 10:30:25 -08001073 saveConfigToXml(packageName, "", -1, null, config, true);
1074 }
1075
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001076 /**
1077 * Reads a bundle from an XML file.
1078 *
1079 * This restores a bundle that was written with {@link #saveConfigToXml}. This returns the saved
Yuchen Dongc15afed2018-04-26 17:05:22 +08001080 * config bundle for the given package and phone ID.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001081 *
1082 * In case of errors, or if the saved config is from a different package version than the
1083 * current version, then null will be returned.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001084 *
Jayachandran C645ec612020-01-10 10:30:25 -08001085 * @param packageName the name of the package from which we fetched this bundle.
1086 * @param extraString An extra string to be used in the XML file name.
1087 * @param phoneId the phone ID.
1088 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001089 * @return the bundle from the XML file. Returns null if there is no saved config, the saved
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001090 * version does not match, or reading config fails.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001091 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001092 @Nullable
1093 private PersistableBundle restoreConfigFromXml(@Nullable String packageName,
1094 @NonNull String extraString, int phoneId, boolean isNoSimConfig) {
Jayachandran C645ec612020-01-10 10:30:25 -08001095 if (packageName == null) {
1096 loge("Cannot restore config with null packageName");
1097 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001098 final String version = getPackageVersion(packageName);
1099 if (version == null) {
1100 loge("Failed to get package version for: " + packageName);
1101 return null;
1102 }
Yuchen Dongc15afed2018-04-26 17:05:22 +08001103
Jayachandran C645ec612020-01-10 10:30:25 -08001104 String fileName;
arunvoddu664c36a2021-10-11 20:09:28 +00001105 String iccid = null;
Jayachandran C645ec612020-01-10 10:30:25 -08001106 if (isNoSimConfig) {
1107 fileName = getFilenameForNoSimConfig(packageName);
1108 } else {
Jack Yuf5badd92022-12-08 00:50:53 -08001109 if (TelephonyManager.getSimStateForSlotIndex(phoneId)
Jayachandran C645ec612020-01-10 10:30:25 -08001110 != TelephonyManager.SIM_STATE_LOADED) {
1111 loge("Skip restore config because SIM records are not loaded.");
1112 return null;
1113 }
1114
arunvoddu664c36a2021-10-11 20:09:28 +00001115 iccid = getIccIdForPhoneId(phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -08001116 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1117 if (iccid == null) {
1118 loge("Cannot restore config with null iccid.");
1119 return null;
1120 }
1121 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001122 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001123
1124 PersistableBundle restoredBundle = null;
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001125 File file = null;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001126 FileInputStream inFile = null;
1127 try {
Jayachandran C645ec612020-01-10 10:30:25 -08001128 file = new File(mContext.getFilesDir(),fileName);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001129 inFile = new FileInputStream(file);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001130
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001131 restoredBundle = PersistableBundle.readFromStream(inFile);
1132 String savedVersion = restoredBundle.getString(KEY_VERSION);
1133 restoredBundle.remove(KEY_VERSION);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001134
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001135 if (!version.equals(savedVersion)) {
1136 loge("Saved version mismatch: " + version + " vs " + savedVersion);
1137 restoredBundle = null;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001138 }
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001139
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001140 inFile.close();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001141 } catch (FileNotFoundException e) {
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001142 // Missing file is normal occurrence that might occur with a new sim or when restoring
1143 // an override file during boot and should not be treated as an error.
arunvoddu664c36a2021-10-11 20:09:28 +00001144 if (file != null) {
1145 if (isNoSimConfig) {
1146 logd("File not found: " + file.getPath());
1147 } else {
1148 String filePath = file.getPath();
1149 filePath = getFilePathForLogging(filePath, iccid);
1150 logd("File not found : " + filePath);
1151 }
1152 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001153 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001154 loge(e.toString());
1155 }
1156
1157 return restoredBundle;
1158 }
1159
arunvoddu664c36a2021-10-11 20:09:28 +00001160 /**
1161 * This method will mask most part of iccid in the filepath for logging on userbuild
1162 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001163 @NonNull
1164 private String getFilePathForLogging(@Nullable String filePath, @Nullable String iccid) {
arunvoddu664c36a2021-10-11 20:09:28 +00001165 // If loggable then return with actual file path
1166 if (Rlog.isLoggable(LOG_TAG, Log.VERBOSE)) {
1167 return filePath;
1168 }
1169 String path = filePath;
1170 int length = (iccid != null) ? iccid.length() : 0;
1171 if (length > 5 && filePath != null) {
1172 path = filePath.replace(iccid.substring(5), "***************");
1173 }
1174 return path;
1175 }
1176
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001177 @Nullable
1178 private PersistableBundle restoreConfigFromXml(@Nullable String packageName,
1179 @NonNull String extraString, int phoneId) {
Jayachandran C645ec612020-01-10 10:30:25 -08001180 return restoreConfigFromXml(packageName, extraString, phoneId, false);
1181 }
1182
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001183 @Nullable
1184 private PersistableBundle restoreNoSimConfigFromXml(@Nullable String packageName) {
Jayachandran C645ec612020-01-10 10:30:25 -08001185 return restoreConfigFromXml(packageName, "", -1, true);
1186 }
1187
Junda Liu8a8a53a2015-05-15 16:19:57 -07001188 /**
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001189 * Clears cached carrier config.
1190 * This deletes all saved XML files associated with the given package name. If packageName is
1191 * null, then it deletes all saved XML files.
1192 *
1193 * @param packageName the name of a carrier package, or null if all cached config should be
1194 * cleared.
1195 * @return true iff one or more files were deleted.
Junda Liu8a8a53a2015-05-15 16:19:57 -07001196 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001197 private boolean clearCachedConfigForPackage(@Nullable final String packageName) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001198 File dir = mContext.getFilesDir();
1199 File[] packageFiles = dir.listFiles(new FilenameFilter() {
1200 public boolean accept(File dir, String filename) {
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001201 if (packageName != null) {
1202 return filename.startsWith("carrierconfig-" + packageName + "-");
1203 } else {
1204 return filename.startsWith("carrierconfig-");
1205 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001206 }
1207 });
Junda Liu8a8a53a2015-05-15 16:19:57 -07001208 if (packageFiles == null || packageFiles.length < 1) return false;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001209 for (File f : packageFiles) {
arunvoddub7c6e8e2022-09-05 15:48:06 +00001210 logd("Deleting " + getFilePathForLogging(f.getName()));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001211 f.delete();
1212 }
Junda Liu8a8a53a2015-05-15 16:19:57 -07001213 return true;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001214 }
1215
arunvoddub7c6e8e2022-09-05 15:48:06 +00001216 private String getFilePathForLogging(String filePath) {
1217 if (!TextUtils.isEmpty(filePath)) {
1218 String[] fileTokens = filePath.split("-");
1219 if (fileTokens != null && fileTokens.length > 2) {
1220 String iccid = fileTokens[fileTokens.length -2];
1221 return getFilePathForLogging(filePath, iccid);
1222 }
1223 return filePath;
1224 }
1225 return filePath;
1226 }
1227
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001228 /** Builds a canonical file name for a config file. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001229 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001230 private static String getFilenameForConfig(
1231 @NonNull String packageName, @NonNull String extraString,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001232 @NonNull String iccid, int cid) {
chen xu02581692018-11-11 19:03:44 -08001233 // the same carrier should have a single copy of XML file named after carrier id.
1234 // However, it's still possible that platform doesn't recognize the current sim carrier,
1235 // we will use iccid + carrierid as the canonical file name. carrierid can also handle the
1236 // cases SIM OTA resolves to different carrier while iccid remains the same.
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001237 return "carrierconfig-" + packageName + extraString + "-" + iccid + "-" + cid + ".xml";
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001238 }
1239
Jayachandran C645ec612020-01-10 10:30:25 -08001240 /** Builds a canonical file name for no SIM config file. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001241 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001242 private String getFilenameForNoSimConfig(@NonNull String packageName) {
1243 return "carrierconfig-" + packageName + "-" + "nosim" + ".xml";
1244 }
1245
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001246 /** Return the current version code of a package, or null if the name is not found. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001247 @Nullable
1248 private String getPackageVersion(@NonNull String packageName) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001249 try {
1250 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
Dianne Hackbornb76ab202017-11-28 17:44:50 -08001251 return Long.toString(info.getLongVersionCode());
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001252 } catch (PackageManager.NameNotFoundException e) {
1253 return null;
1254 }
1255 }
1256
Jonathan Basseri65273c82017-07-25 15:08:42 -07001257 /**
1258 * Read up to date config.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001259 *
1260 * This reads config bundles for the given phoneId. That means getting the latest bundle from
1261 * the default app and a privileged carrier app, if present. This will not bind to an app if we
1262 * have a saved config file to use instead.
1263 */
1264 private void updateConfigForPhoneId(int phoneId) {
Jonathan Basseri65273c82017-07-25 15:08:42 -07001265 mHandler.sendMessage(mHandler.obtainMessage(EVENT_DO_FETCH_DEFAULT, phoneId, -1));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001266 }
1267
Malcolm Chen5ea18532019-10-24 19:55:44 -07001268 private void onMultiSimConfigChanged() {
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001269 int oldNumPhones = mNumPhones;
1270 mNumPhones = TelephonyManager.from(mContext).getActiveModemCount();
1271 if (mNumPhones == oldNumPhones) {
1272 return;
1273 }
1274 logdWithLocalLog("mNumPhones change from " + oldNumPhones + " to " + mNumPhones);
1275
Rambo Wanga27fbe52022-04-12 19:09:07 +00001276 // If DS -> SS switch, release the resources BEFORE truncating the arrays to avoid leaking
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001277 for (int phoneId = mNumPhones; phoneId < oldNumPhones; phoneId++) {
1278 if (mServiceConnection[phoneId] != null) {
1279 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
1280 }
1281 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
1282 unbindIfBoundForNoSimConfig(mContext, mServiceConnectionForNoSimConfig[phoneId],
1283 phoneId);
1284 }
1285 }
1286
Rambo Wanga27fbe52022-04-12 19:09:07 +00001287 // The phone to slot mapping may change, unregister here and re-register callbacks later
1288 for (int phoneId = 0; phoneId < oldNumPhones; phoneId++) {
1289 if (mCarrierServiceChangeCallbacks[phoneId] != null) {
1290 TelephonyManager.from(mContext).unregisterCarrierPrivilegesCallback(
1291 mCarrierServiceChangeCallbacks[phoneId]);
1292 }
1293 }
1294
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001295 // Copy the original arrays, truncate or padding with zeros (if necessary) to new length
1296 mConfigFromDefaultApp = Arrays.copyOf(mConfigFromDefaultApp, mNumPhones);
1297 mConfigFromCarrierApp = Arrays.copyOf(mConfigFromCarrierApp, mNumPhones);
1298 mPersistentOverrideConfigs = Arrays.copyOf(mPersistentOverrideConfigs, mNumPhones);
1299 mOverrideConfigs = Arrays.copyOf(mOverrideConfigs, mNumPhones);
1300 mServiceConnection = Arrays.copyOf(mServiceConnection, mNumPhones);
1301 mServiceConnectionForNoSimConfig =
1302 Arrays.copyOf(mServiceConnectionForNoSimConfig, mNumPhones);
1303 mServiceBound = Arrays.copyOf(mServiceBound, mNumPhones);
1304 mServiceBoundForNoSimConfig = Arrays.copyOf(mServiceBoundForNoSimConfig, mNumPhones);
1305 mHasSentConfigChange = Arrays.copyOf(mHasSentConfigChange, mNumPhones);
1306 mFromSystemUnlocked = Arrays.copyOf(mFromSystemUnlocked, mNumPhones);
Rambo Wanga27fbe52022-04-12 19:09:07 +00001307 mCarrierServiceChangeCallbacks = Arrays.copyOf(mCarrierServiceChangeCallbacks, mNumPhones);
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001308
Rambo Wanga27fbe52022-04-12 19:09:07 +00001309 // Load the config for all the phones and re-register callback AFTER padding the arrays.
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001310 for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
1311 updateConfigForPhoneId(phoneId);
Rambo Wanga27fbe52022-04-12 19:09:07 +00001312 mCarrierServiceChangeCallbacks[phoneId] = new CarrierServiceChangeCallback(phoneId);
1313 TelephonyManager.from(mContext).registerCarrierPrivilegesCallback(phoneId,
1314 new HandlerExecutor(mHandler), mCarrierServiceChangeCallbacks[phoneId]);
Malcolm Chen5ea18532019-10-24 19:55:44 -07001315 }
1316 }
1317
Hall Liu506724b2018-10-22 18:16:14 -07001318 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001319 @NonNull
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001320 public PersistableBundle getConfigForSubId(int subscriptionId, @NonNull String callingPackage) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001321 return getConfigForSubIdWithFeature(subscriptionId, callingPackage, null);
Philip P. Moltmann9797cbb2020-01-07 13:45:00 -08001322 }
1323
1324 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001325 @NonNull
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001326 public PersistableBundle getConfigForSubIdWithFeature(int subscriptionId,
1327 @NonNull String callingPackage, @Nullable String callingFeatureId) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001328 if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(mContext, subscriptionId,
1329 callingPackage, callingFeatureId, "getCarrierConfig")) {
Rambo Wang42026112021-04-07 20:57:28 +00001330 return new PersistableBundle();
Amit Mahajan40b3fa52015-07-14 10:27:19 -07001331 }
Jeff Davidsona8e4e242018-03-15 17:16:18 -07001332
Rambo Wangd2b004b2021-03-30 10:10:23 -07001333 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001334 PersistableBundle retConfig = CarrierConfigManager.getDefaultConfig();
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001335 if (SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001336 PersistableBundle config = mConfigFromDefaultApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001337 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001338 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001339 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001340 config = mConfigFromCarrierApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001341 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001342 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001343 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001344 config = mPersistentOverrideConfigs[phoneId];
1345 if (config != null) {
1346 retConfig.putAll(config);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001347 }
Hall Liu506724b2018-10-22 18:16:14 -07001348 config = mOverrideConfigs[phoneId];
1349 if (config != null) {
1350 retConfig.putAll(config);
Hall Liu506724b2018-10-22 18:16:14 -07001351 }
Nathan Harold1122e3d2021-01-22 15:45:24 -08001352 // Ignore the theoretical case of the default app not being present since that won't
1353 // work in CarrierConfigLoader today.
1354 final boolean allConfigsApplied =
1355 (mConfigFromCarrierApp[phoneId] != null
1356 || getCarrierPackageForPhoneId(phoneId) == null)
1357 && mConfigFromDefaultApp[phoneId] != null;
1358 retConfig.putBoolean(
1359 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, allConfigsApplied);
Jayachandran C645ec612020-01-10 10:30:25 -08001360 } else {
1361 if (mNoSimConfig != null) {
1362 retConfig.putAll(mNoSimConfig);
1363 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001364 }
1365 return retConfig;
1366 }
1367
1368 @Override
rambowang14757c22022-10-03 11:54:56 -05001369 @NonNull
1370 public PersistableBundle getConfigSubsetForSubIdWithFeature(int subscriptionId,
1371 @NonNull String callingPackage, @Nullable String callingFeatureId,
1372 @NonNull String[] keys) {
1373 Objects.requireNonNull(callingPackage, "Calling package must be non-null");
1374 Objects.requireNonNull(keys, "Config keys must be non-null");
1375 enforceCallerIsSystemOrRequestingPackage(callingPackage);
1376
1377 // Permission check is performed inside and an empty bundle will return on failure.
1378 // No SecurityException thrown here since most clients expect to retrieve the overridden
1379 // value if present or use default one if not
1380 PersistableBundle allConfigs = getConfigForSubIdWithFeature(subscriptionId, callingPackage,
1381 callingFeatureId);
1382 if (allConfigs.isEmpty()) {
1383 return allConfigs;
1384 }
1385 for (String key : keys) {
1386 Objects.requireNonNull(key, "Config key must be non-null");
rambowang14757c22022-10-03 11:54:56 -05001387 }
1388
1389 PersistableBundle configSubset = new PersistableBundle(
1390 keys.length + CONFIG_SUBSET_METADATA_KEYS.length);
1391 for (String carrierConfigKey : keys) {
1392 Object value = allConfigs.get(carrierConfigKey);
rambowangb49e90f2022-12-13 18:29:06 -06001393 if (value == null) {
1394 // Filter out keys without values.
1395 // In history, many AOSP or OEMs/carriers private configs didn't provide default
1396 // values. We have to continue supporting them for now. See b/261776046 for details.
1397 continue;
1398 }
rambowang14757c22022-10-03 11:54:56 -05001399 // Config value itself could be PersistableBundle which requires different API to put
1400 if (value instanceof PersistableBundle) {
1401 configSubset.putPersistableBundle(carrierConfigKey, (PersistableBundle) value);
1402 } else {
1403 configSubset.putObject(carrierConfigKey, value);
1404 }
1405 }
1406
1407 // Configs in CONFIG_SUBSET_ALWAYS_INCLUDED_KEYS should always be included
1408 for (String generalKey : CONFIG_SUBSET_METADATA_KEYS) {
1409 configSubset.putObject(generalKey, allConfigs.get(generalKey));
1410 }
1411
1412 return configSubset;
1413 }
1414
1415 @Override
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001416 public void overrideConfig(int subscriptionId, @Nullable PersistableBundle overrides,
1417 boolean persistent) {
Hall Liu506724b2018-10-22 18:16:14 -07001418 mContext.enforceCallingOrSelfPermission(
1419 android.Manifest.permission.MODIFY_PHONE_STATE, null);
1420 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1421 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001422 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
Rambo Wangd2b004b2021-03-30 10:10:23 -07001423 throw new IllegalArgumentException(
1424 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
Hall Liu506724b2018-10-22 18:16:14 -07001425 }
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001426 // Post to run on handler thread on which all states should be confined.
1427 mHandler.post(() -> {
1428 overrideConfig(mOverrideConfigs, phoneId, overrides);
Hall Liu506724b2018-10-22 18:16:14 -07001429
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001430 if (persistent) {
1431 overrideConfig(mPersistentOverrideConfigs, phoneId, overrides);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001432
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001433 if (overrides != null) {
1434 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
1435 saveConfigToXml(mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION,
1436 phoneId,
1437 carrierId, mPersistentOverrideConfigs[phoneId]);
1438 } else {
1439 final String iccid = getIccIdForPhoneId(phoneId);
1440 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1441 String fileName = getFilenameForConfig(mPlatformCarrierConfigPackage,
1442 OVERRIDE_PACKAGE_ADDITION, iccid, cid);
1443 File fileToDelete = new File(mContext.getFilesDir(), fileName);
1444 fileToDelete.delete();
1445 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001446 }
Jack Yue37dd262022-12-16 11:53:37 -08001447 updateSubscriptionDatabase(phoneId);
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001448 });
Hall Liu506724b2018-10-22 18:16:14 -07001449 }
1450
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001451 private void overrideConfig(@NonNull PersistableBundle[] currentOverrides, int phoneId,
1452 @Nullable PersistableBundle overrides) {
1453 if (overrides == null) {
Rambo Wang42026112021-04-07 20:57:28 +00001454 currentOverrides[phoneId] = new PersistableBundle();
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001455 } else if (currentOverrides[phoneId] == null) {
1456 currentOverrides[phoneId] = overrides;
1457 } else {
1458 currentOverrides[phoneId].putAll(overrides);
1459 }
1460 }
1461
Hall Liu506724b2018-10-22 18:16:14 -07001462 @Override
Rambo Wangd2b004b2021-03-30 10:10:23 -07001463 public void notifyConfigChangedForSubId(int subscriptionId) {
Jordan Liud7d57fe2019-04-16 12:29:43 -07001464 // Requires the calling app to be either a carrier privileged app for this subId or
Junda Liufbd2bcb2016-06-15 11:15:42 -07001465 // system privileged app with MODIFY_PHONE_STATE permission.
Rambo Wangd2b004b2021-03-30 10:10:23 -07001466 TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(mContext,
1467 subscriptionId, "Require carrier privileges or MODIFY_PHONE_STATE permission.");
1468
1469 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1470 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
1471 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
1472 throw new IllegalArgumentException(
1473 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
1474 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001475
1476 // This method should block until deleting has completed, so that an error which prevents us
1477 // from clearing the cache is passed back to the carrier app. With the files successfully
1478 // deleted, this can return and we will eventually bind to the carrier app.
Jordan Liud7d57fe2019-04-16 12:29:43 -07001479 String callingPackageName = mContext.getPackageManager().getNameForUid(
1480 Binder.getCallingUid());
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001481 clearCachedConfigForPackage(callingPackageName);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001482 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001483 }
1484
1485 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001486 public void updateConfigForPhoneId(int phoneId, @NonNull String simState) {
Junda Liu1f2b34d2015-06-18 15:26:56 -07001487 mContext.enforceCallingOrSelfPermission(
1488 android.Manifest.permission.MODIFY_PHONE_STATE, null);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001489 logdWithLocalLog("Update config for phoneId: " + phoneId + " simState: " + simState);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001490 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001491 throw new IllegalArgumentException("Invalid phoneId: " + phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001492 }
1493 // requires Java 7 for switch on string.
1494 switch (simState) {
1495 case IccCardConstants.INTENT_VALUE_ICC_ABSENT:
1496 case IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR:
Junda Liu6f5fddf2016-05-24 16:14:41 -07001497 case IccCardConstants.INTENT_VALUE_ICC_CARD_RESTRICTED:
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001498 case IccCardConstants.INTENT_VALUE_ICC_UNKNOWN:
Malcolm Chendb66de12019-12-09 18:57:07 -08001499 case IccCardConstants.INTENT_VALUE_ICC_NOT_READY:
Junda Liu9f2d2712015-05-15 14:22:45 -07001500 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CLEAR_CONFIG, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001501 break;
1502 case IccCardConstants.INTENT_VALUE_ICC_LOADED:
1503 case IccCardConstants.INTENT_VALUE_ICC_LOCKED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001504 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001505 break;
1506 }
1507 }
1508
Junda Liu43d723a2015-05-12 17:23:45 -07001509 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001510 @NonNull
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001511 public String getDefaultCarrierServicePackageName() {
Shuo Qianefdb7962019-12-19 15:54:27 -08001512 mContext.enforceCallingOrSelfPermission(
1513 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
1514 "getDefaultCarrierServicePackageName");
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001515 return mPlatformCarrierConfigPackage;
1516 }
1517
Rambo Wang7e3bc122021-03-23 09:24:38 -07001518 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001519 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -07001520 /* package */ Handler getHandler() {
1521 return mHandler;
1522 }
1523
1524 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001525 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001526 /* package */ PersistableBundle getConfigFromDefaultApp(int phoneId) {
1527 return mConfigFromDefaultApp[phoneId];
1528 }
1529
1530 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001531 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001532 /* package */ PersistableBundle getConfigFromCarrierApp(int phoneId) {
1533 return mConfigFromCarrierApp[phoneId];
1534 }
1535
1536 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001537 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -07001538 /* package */ PersistableBundle getNoSimConfig() {
1539 return mNoSimConfig;
1540 }
1541
1542 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001543 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001544 /* package */ PersistableBundle getOverrideConfig(int phoneId) {
1545 return mOverrideConfigs[phoneId];
1546 }
1547
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001548 // TODO(b/185129900): always call unbindService after bind, no matter if it succeeded
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001549 private void unbindIfBound(@NonNull Context context, @NonNull CarrierServiceConnection conn,
Rambo Wangb0f3e2f2021-10-28 12:40:12 -07001550 int phoneId) {
1551 if (mServiceBound[phoneId]) {
1552 mServiceBound[phoneId] = false;
1553 context.unbindService(conn);
1554 }
1555 }
1556
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001557 private void unbindIfBoundForNoSimConfig(@NonNull Context context,
1558 @NonNull CarrierServiceConnection conn, int phoneId) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -07001559 if (mServiceBoundForNoSimConfig[phoneId]) {
1560 mServiceBoundForNoSimConfig[phoneId] = false;
Jayachandran C645ec612020-01-10 10:30:25 -08001561 context.unbindService(conn);
1562 }
1563 }
1564
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001565 /**
Rambo Wang610fdf62021-03-08 21:37:11 -08001566 * Returns a boxed Integer object for phoneId, services as message token to distinguish messages
1567 * with same code when calling {@link Handler#removeMessages(int, Object)}.
1568 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001569 @NonNull
Rambo Wang610fdf62021-03-08 21:37:11 -08001570 private Integer getMessageToken(int phoneId) {
1571 if (phoneId < -128 || phoneId > 127) {
1572 throw new IllegalArgumentException("phoneId should be in range [-128, 127], inclusive");
1573 }
1574 // Integer#valueOf guarantees the integers within [-128, 127] are cached and thus memory
1575 // comparison (==) returns true for the same integer.
1576 return Integer.valueOf(phoneId);
1577 }
1578
1579 /**
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001580 * If {@code args} contains {@link #DUMP_ARG_REQUESTING_PACKAGE} and a following package name,
1581 * we'll also call {@link IBinder#dump} on the default carrier service (if bound) and the
1582 * specified carrier service (if bound). Typically, this is done for connectivity bug reports
1583 * where we don't call {@code dumpsys activity service all-non-platform} because that contains
1584 * too much info, but we still want to let carrier apps include their diagnostics.
1585 */
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001586 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001587 public void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter pw, @NonNull String[] args) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001588 IndentingPrintWriter indentPW = new IndentingPrintWriter(pw, " ");
Junda Liu43d723a2015-05-12 17:23:45 -07001589 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1590 != PackageManager.PERMISSION_GRANTED) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001591 indentPW.println("Permission Denial: can't dump carrierconfig from from pid="
Junda Liu43d723a2015-05-12 17:23:45 -07001592 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
1593 return;
1594 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001595 String requestingPackage = null;
1596 int requestingPackageIndex = ArrayUtils.indexOf(args, DUMP_ARG_REQUESTING_PACKAGE);
1597 if (requestingPackageIndex >= 0 && requestingPackageIndex < args.length - 1
1598 && !TextUtils.isEmpty(args[requestingPackageIndex + 1])) {
1599 requestingPackage = args[requestingPackageIndex + 1];
1600 // Throws a SecurityException if the caller is impersonating another app in an effort to
1601 // dump extra info (which may contain PII the caller doesn't have a right to).
1602 enforceCallerIsSystemOrRequestingPackage(requestingPackage);
1603 }
1604
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001605 indentPW.println("CarrierConfigLoader: " + this);
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001606 for (int i = 0; i < mNumPhones; i++) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001607 indentPW.println("Phone Id = " + i);
shuoq26a3a4c2016-12-16 11:06:48 -08001608 // display default values in CarrierConfigManager
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001609 printConfig(CarrierConfigManager.getDefaultConfig(), indentPW,
shuoq26a3a4c2016-12-16 11:06:48 -08001610 "Default Values from CarrierConfigManager");
shuoq26a3a4c2016-12-16 11:06:48 -08001611 // display ConfigFromDefaultApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001612 printConfig(mConfigFromDefaultApp[i], indentPW, "mConfigFromDefaultApp");
shuoq26a3a4c2016-12-16 11:06:48 -08001613 // display ConfigFromCarrierApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001614 printConfig(mConfigFromCarrierApp[i], indentPW, "mConfigFromCarrierApp");
1615 printConfig(mPersistentOverrideConfigs[i], indentPW, "mPersistentOverrideConfigs");
1616 printConfig(mOverrideConfigs[i], indentPW, "mOverrideConfigs");
shuoq26a3a4c2016-12-16 11:06:48 -08001617 }
chen xudb04c292019-03-26 17:01:15 -07001618
Jayachandran C645ec612020-01-10 10:30:25 -08001619 printConfig(mNoSimConfig, indentPW, "mNoSimConfig");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001620 indentPW.println("CarrierConfigLoadingLog=");
1621 mCarrierConfigLoadingLog.dump(fd, indentPW, args);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001622
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001623 if (requestingPackage != null) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001624 logd("Including default and requesting package " + requestingPackage
1625 + " carrier services in dump");
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001626 indentPW.println("");
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001627 indentPW.println("Connected services");
1628 dumpCarrierServiceIfBound(fd, indentPW, "Default config package",
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001629 mPlatformCarrierConfigPackage, false /* considerCarrierPrivileges */);
1630 dumpCarrierServiceIfBound(fd, indentPW, "Requesting package", requestingPackage,
1631 true /* considerCarrierPrivileges */);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001632 }
shuoq26a3a4c2016-12-16 11:06:48 -08001633 }
1634
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001635 private void printConfig(@NonNull PersistableBundle configApp,
1636 @NonNull IndentingPrintWriter indentPW, @NonNull String name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001637 indentPW.increaseIndent();
shuoq26a3a4c2016-12-16 11:06:48 -08001638 if (configApp == null) {
shuoq26a3a4c2016-12-16 11:06:48 -08001639 indentPW.println(name + " : null ");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001640 indentPW.decreaseIndent();
1641 indentPW.println("");
shuoq26a3a4c2016-12-16 11:06:48 -08001642 return;
1643 }
shuoq26a3a4c2016-12-16 11:06:48 -08001644 indentPW.println(name + " : ");
1645 List<String> sortedKeys = new ArrayList<String>(configApp.keySet());
1646 Collections.sort(sortedKeys);
1647 indentPW.increaseIndent();
1648 indentPW.increaseIndent();
1649 for (String key : sortedKeys) {
1650 if (configApp.get(key) != null && configApp.get(key) instanceof Object[]) {
1651 indentPW.println(key + " = " +
1652 Arrays.toString((Object[]) configApp.get(key)));
1653 } else if (configApp.get(key) != null && configApp.get(key) instanceof int[]) {
1654 indentPW.println(key + " = " + Arrays.toString((int[]) configApp.get(key)));
1655 } else {
1656 indentPW.println(key + " = " + configApp.get(key));
1657 }
Junda Liu43d723a2015-05-12 17:23:45 -07001658 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001659 indentPW.decreaseIndent();
1660 indentPW.decreaseIndent();
1661 indentPW.decreaseIndent();
1662 indentPW.println("");
Junda Liu43d723a2015-05-12 17:23:45 -07001663 }
1664
Hunter Knepshielde601f432020-02-19 10:16:04 -08001665 /**
1666 * Passes without problem when one of these conditions is true:
1667 * - The caller is a privileged UID (e.g. for dumpstate.cpp generating a bug report, where the
1668 * system knows the true caller plumbed in through the {@link android.os.BugreportManager} API).
1669 * - The caller's UID matches the supplied package.
1670 *
1671 * @throws SecurityException if none of the above conditions are met.
1672 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001673 private void enforceCallerIsSystemOrRequestingPackage(@NonNull String requestingPackage)
Hunter Knepshielde601f432020-02-19 10:16:04 -08001674 throws SecurityException {
1675 final int callingUid = Binder.getCallingUid();
1676 if (callingUid == Process.ROOT_UID || callingUid == Process.SYSTEM_UID
1677 || callingUid == Process.SHELL_UID || callingUid == Process.PHONE_UID) {
1678 // Bug reports (dumpstate.cpp) run as SHELL, and let some other privileged UIDs through
1679 // as well.
1680 return;
1681 }
1682 // An app is trying to dump extra detail, block it if they aren't who they claim to be.
1683 AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
1684 if (appOps == null) {
1685 throw new SecurityException("No AppOps");
1686 }
1687 // Will throw a SecurityException if the UID and package don't match.
1688 appOps.checkPackage(callingUid, requestingPackage);
1689 }
1690
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001691 /**
1692 * Searches for one or more appropriate {@link CarrierService} instances to dump based on the
1693 * current connections.
1694 *
1695 * @param targetPkgName the target package name to dump carrier services for
1696 * @param considerCarrierPrivileges if true, allow a carrier service to be dumped if it shares
1697 * carrier privileges with {@code targetPkgName};
1698 * otherwise, only dump a carrier service if it is {@code
1699 * targetPkgName}
1700 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001701 private void dumpCarrierServiceIfBound(@NonNull FileDescriptor fd,
1702 @NonNull IndentingPrintWriter indentPW, @NonNull String prefix,
1703 @NonNull String targetPkgName, boolean considerCarrierPrivileges) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001704 // Null package is possible if it's early in the boot process, there was a recent crash, we
1705 // loaded the config from XML most recently, or a SIM slot is empty. Carrier apps with
1706 // long-lived bindings should typically get dumped here regardless. Even if an app is being
1707 // used for multiple phoneIds, we assume that it's smart enough to handle that on its own,
1708 // and that in most cases we'd just be dumping duplicate information and bloating a report.
1709 indentPW.increaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001710 indentPW.println(prefix + " : " + targetPkgName);
1711 Set<String> dumpedPkgNames = new ArraySet<>(mServiceConnection.length);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001712 for (CarrierServiceConnection connection : mServiceConnection) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001713 if (connection == null || !SubscriptionManager.isValidPhoneId(connection.phoneId)
1714 || TextUtils.isEmpty(connection.pkgName)) {
1715 continue;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001716 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001717 final String servicePkgName = connection.pkgName;
1718 // Note: we intentionally ignore system components here because we should NOT match the
1719 // shell caller that's typically used for bug reports via non-BugreportManager triggers.
1720 final boolean exactPackageMatch = TextUtils.equals(targetPkgName, servicePkgName);
1721 final boolean carrierPrivilegesMatch =
1722 considerCarrierPrivileges && hasCarrierPrivileges(targetPkgName,
1723 connection.phoneId);
1724 if (!exactPackageMatch && !carrierPrivilegesMatch) continue;
1725 // Make sure this service is actually alive before trying to dump it. We don't pay
1726 // attention to mServiceBound[connection.phoneId] because typically carrier apps will
1727 // request long-lived bindings, and even if we unbind the app, it may still be alive due
1728 // to CarrierServiceBindHelper. Pull it out as a reference so even if it gets set to
1729 // null within the ServiceConnection during unbinding we can avoid an NPE.
1730 final IBinder service = connection.service;
1731 if (service == null || !service.isBinderAlive() || !service.pingBinder()) continue;
1732 // We've got a live service. Last check is just to make sure we don't dump a package
1733 // multiple times.
1734 if (!dumpedPkgNames.add(servicePkgName)) continue;
1735 if (!exactPackageMatch) {
1736 logd(targetPkgName + " has carrier privileges on phoneId " + connection.phoneId
1737 + ", service provided by " + servicePkgName);
1738 indentPW.increaseIndent();
1739 indentPW.println("Proxy : " + servicePkgName);
1740 indentPW.decreaseIndent();
1741 }
1742 // Flush before we let the app output anything to ensure correct ordering of output.
1743 // Internally, Binder#dump calls flush on its printer after finishing so we don't
1744 // need to do anything after.
1745 indentPW.flush();
1746 try {
1747 logd("Dumping " + servicePkgName);
1748 // We don't need to give the carrier service any args.
1749 connection.service.dump(fd, null /* args */);
1750 logd("Done with " + servicePkgName);
1751 } catch (RemoteException e) {
1752 logd("RemoteException from " + servicePkgName, e);
1753 indentPW.increaseIndent();
1754 indentPW.println("RemoteException");
1755 indentPW.increaseIndent();
1756 e.printStackTrace(indentPW);
1757 indentPW.decreaseIndent();
1758 indentPW.decreaseIndent();
1759 // We won't retry this package again because now it's in dumpedPkgNames.
1760 }
1761 indentPW.println("");
Jordan Liu46ed5db2020-01-28 08:55:20 -08001762 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001763 if (dumpedPkgNames.isEmpty()) {
1764 indentPW.increaseIndent();
1765 indentPW.println("Not bound");
1766 indentPW.decreaseIndent();
1767 indentPW.println("");
1768 }
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001769 indentPW.decreaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001770 }
1771
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001772 private boolean hasCarrierPrivileges(@NonNull String pkgName, int phoneId) {
Jack Yu00ece8c2022-11-19 22:29:12 -08001773 int subId = SubscriptionManager.getSubscriptionId(phoneId);
1774 if (!SubscriptionManager.isValidSubscriptionId(subId)) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001775 return false;
1776 }
Jack Yu00ece8c2022-11-19 22:29:12 -08001777 return TelephonyManager.from(mContext).createForSubscriptionId(subId)
1778 .checkCarrierPrivilegesForPackage(pkgName)
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001779 == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001780 }
1781
Zach Johnson36d7aab2015-05-22 15:43:00 -07001782 private class CarrierServiceConnection implements ServiceConnection {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001783 final int phoneId;
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001784 @NonNull final String pkgName;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001785 final int eventId;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001786 IBinder service;
1787
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001788 CarrierServiceConnection(int phoneId, @NonNull String pkgName, int eventId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001789 this.phoneId = phoneId;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001790 this.pkgName = pkgName;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001791 this.eventId = eventId;
1792 }
1793
1794 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001795 public void onServiceConnected(@NonNull ComponentName name, @NonNull IBinder service) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001796 logd("Connected to config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001797 this.service = service;
1798 mHandler.sendMessage(mHandler.obtainMessage(eventId, phoneId, -1, this));
1799 }
1800
1801 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001802 public void onServiceDisconnected(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001803 logd("Disconnected from config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001804 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001805 }
1806
1807 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001808 public void onBindingDied(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001809 logd("Binding died from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001810 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001811 }
1812
1813 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001814 public void onNullBinding(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001815 logd("Null binding from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001816 this.service = null;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001817 }
1818 }
1819
1820 private class ConfigLoaderBroadcastReceiver extends BroadcastReceiver {
1821 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001822 public void onReceive(@NonNull Context context, @NonNull Intent intent) {
Rambo Wanga27fbe52022-04-12 19:09:07 +00001823 switch (intent.getAction()) {
Nanxi Chen3d670502016-03-17 16:32:09 -07001824 case Intent.ACTION_BOOT_COMPLETED:
1825 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_UNLOCKED, null));
1826 break;
1827
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001828 case TelephonyManager.ACTION_MULTI_SIM_CONFIG_CHANGED:
1829 mHandler.sendEmptyMessage(EVENT_MULTI_SIM_CONFIG_CHANGED);
1830 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001831 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001832 }
1833 }
1834
Rambo Wanga27fbe52022-04-12 19:09:07 +00001835 private class CarrierServiceChangeCallback implements
1836 TelephonyManager.CarrierPrivilegesCallback {
1837 final int mPhoneId;
1838 // CarrierPrivilegesCallback will be triggered upon registration. Filter the first callback
1839 // here since we really care of the *change* of carrier service instead of the content
1840 private boolean mHasSentServiceChangeCallback;
1841
1842 CarrierServiceChangeCallback(int phoneId) {
1843 this.mPhoneId = phoneId;
1844 this.mHasSentServiceChangeCallback = false;
1845 }
1846
1847 @Override
1848 public void onCarrierPrivilegesChanged(
1849 @androidx.annotation.NonNull Set<String> privilegedPackageNames,
1850 @androidx.annotation.NonNull Set<Integer> privilegedUids) {
1851 // Ignored, not interested here
1852 }
1853
1854 @Override
1855 public void onCarrierServiceChanged(
1856 @androidx.annotation.Nullable String carrierServicePackageName,
1857 int carrierServiceUid) {
1858 // Ignore the first callback which is triggered upon registration
1859 if (!mHasSentServiceChangeCallback) {
1860 mHasSentServiceChangeCallback = true;
1861 return;
1862 }
1863 mHandler.sendMessage(
1864 mHandler.obtainMessage(EVENT_PACKAGE_CHANGED, mPhoneId, -1,
1865 carrierServicePackageName));
1866 }
1867 }
1868
Rambo Wangab13e3e2021-04-08 15:01:06 -07001869 // Get readable string for the message code supported in this class.
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001870 @NonNull
Rambo Wangab13e3e2021-04-08 15:01:06 -07001871 private static String eventToString(int code) {
1872 switch (code) {
1873 case EVENT_CLEAR_CONFIG:
1874 return "EVENT_CLEAR_CONFIG";
1875 case EVENT_CONNECTED_TO_DEFAULT:
1876 return "EVENT_CONNECTED_TO_DEFAULT";
1877 case EVENT_CONNECTED_TO_CARRIER:
1878 return "EVENT_CONNECTED_TO_CARRIER";
1879 case EVENT_FETCH_DEFAULT_DONE:
1880 return "EVENT_FETCH_DEFAULT_DONE";
1881 case EVENT_FETCH_CARRIER_DONE:
1882 return "EVENT_FETCH_CARRIER_DONE";
1883 case EVENT_DO_FETCH_DEFAULT:
1884 return "EVENT_DO_FETCH_DEFAULT";
1885 case EVENT_DO_FETCH_CARRIER:
1886 return "EVENT_DO_FETCH_CARRIER";
1887 case EVENT_PACKAGE_CHANGED:
1888 return "EVENT_PACKAGE_CHANGED";
1889 case EVENT_BIND_DEFAULT_TIMEOUT:
1890 return "EVENT_BIND_DEFAULT_TIMEOUT";
1891 case EVENT_BIND_CARRIER_TIMEOUT:
1892 return "EVENT_BIND_CARRIER_TIMEOUT";
1893 case EVENT_CHECK_SYSTEM_UPDATE:
1894 return "EVENT_CHECK_SYSTEM_UPDATE";
1895 case EVENT_SYSTEM_UNLOCKED:
1896 return "EVENT_SYSTEM_UNLOCKED";
1897 case EVENT_FETCH_DEFAULT_TIMEOUT:
1898 return "EVENT_FETCH_DEFAULT_TIMEOUT";
1899 case EVENT_FETCH_CARRIER_TIMEOUT:
1900 return "EVENT_FETCH_CARRIER_TIMEOUT";
1901 case EVENT_SUBSCRIPTION_INFO_UPDATED:
1902 return "EVENT_SUBSCRIPTION_INFO_UPDATED";
1903 case EVENT_MULTI_SIM_CONFIG_CHANGED:
1904 return "EVENT_MULTI_SIM_CONFIG_CHANGED";
1905 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG:
1906 return "EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG";
1907 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE:
1908 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE";
1909 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG:
1910 return "EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG";
1911 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1912 return "EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1913 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1914 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1915 default:
1916 return "UNKNOWN(" + code + ")";
1917 }
1918 }
1919
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001920 private void logd(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001921 Log.d(LOG_TAG, msg);
1922 }
1923
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001924 private void logd(@NonNull String msg, Throwable tr) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001925 Log.d(LOG_TAG, msg, tr);
1926 }
1927
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001928 private void logdWithLocalLog(@NonNull String msg) {
chen xudb04c292019-03-26 17:01:15 -07001929 Log.d(LOG_TAG, msg);
1930 mCarrierConfigLoadingLog.log(msg);
1931 }
1932
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001933 private void loge(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001934 Log.e(LOG_TAG, msg);
chen xudb04c292019-03-26 17:01:15 -07001935 mCarrierConfigLoadingLog.log(msg);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001936 }
1937}