blob: fa85f27cf205c02eb8b6d67b8af1c1aeef6047f8 [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;
Jack Yu771c6ce2023-02-02 17:51:42 -080065import com.android.internal.telephony.PhoneConfigurationManager;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080066import com.android.internal.telephony.PhoneFactory;
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
Jack Yu771c6ce2023-02-02 17:51:42 -0800129 // Broadcast receiver for system events
Rambo Wanga27fbe52022-04-12 19:09:07 +0000130 @NonNull
131 private final BroadcastReceiver mSystemBroadcastReceiver = new ConfigLoaderBroadcastReceiver();
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000132 @NonNull private final LocalLog mCarrierConfigLoadingLog = new LocalLog(100);
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000133 // Number of phone instances (active modem count)
134 private int mNumPhones;
chen xudb04c292019-03-26 17:01:15 -0700135
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800136
137 // Message codes; see mHandler below.
Jack Yu3beaf9d2023-04-14 09:17:27 -0700138 // Request from UiccController when SIM becomes absent or error.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800139 private static final int EVENT_CLEAR_CONFIG = 0;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800140 // Has connected to default app.
141 private static final int EVENT_CONNECTED_TO_DEFAULT = 3;
142 // Has connected to carrier app.
143 private static final int EVENT_CONNECTED_TO_CARRIER = 4;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700144 // Config has been loaded from default app (or cache).
145 private static final int EVENT_FETCH_DEFAULT_DONE = 5;
146 // Config has been loaded from carrier app (or cache).
147 private static final int EVENT_FETCH_CARRIER_DONE = 6;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700148 // Attempt to fetch from default app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700149 private static final int EVENT_DO_FETCH_DEFAULT = 7;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700150 // Attempt to fetch from carrier app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700151 private static final int EVENT_DO_FETCH_CARRIER = 8;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700152 // A package has been installed, uninstalled, or updated.
153 private static final int EVENT_PACKAGE_CHANGED = 9;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700154 // Bind timed out for the default app.
155 private static final int EVENT_BIND_DEFAULT_TIMEOUT = 10;
156 // Bind timed out for a carrier app.
157 private static final int EVENT_BIND_CARRIER_TIMEOUT = 11;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700158 // Check if the system fingerprint has changed.
159 private static final int EVENT_CHECK_SYSTEM_UPDATE = 12;
Nanxi Chen3d670502016-03-17 16:32:09 -0700160 // Rerun carrier config binding after system is unlocked.
161 private static final int EVENT_SYSTEM_UNLOCKED = 13;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700162 // Fetching config timed out from the default app.
163 private static final int EVENT_FETCH_DEFAULT_TIMEOUT = 14;
164 // Fetching config timed out from a carrier app.
165 private static final int EVENT_FETCH_CARRIER_TIMEOUT = 15;
Jack Yu3beaf9d2023-04-14 09:17:27 -0700166 // SubscriptionManagerService has finished updating the sub for the carrier config.
Nathan Harold48ac0972019-03-13 22:33:01 -0700167 private static final int EVENT_SUBSCRIPTION_INFO_UPDATED = 16;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700168 // Multi-SIM config changed.
169 private static final int EVENT_MULTI_SIM_CONFIG_CHANGED = 17;
Jayachandran C645ec612020-01-10 10:30:25 -0800170 // Attempt to fetch from default app or read from XML for no SIM case.
171 private static final int EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG = 18;
172 // No SIM config has been loaded from default app (or cache).
173 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE = 19;
174 // Has connected to default app for no SIM config.
175 private static final int EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG = 20;
176 // Bind timed out for the default app when trying to fetch no SIM config.
177 private static final int EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 21;
178 // Fetching config timed out from the default app for no SIM config.
179 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 22;
Rambo Wangab13e3e2021-04-08 15:01:06 -0700180 // NOTE: any new EVENT_* values must be added to method eventToString().
Jonathan Basseri930701e2015-06-11 20:56:43 -0700181
Junda Liu6cb45002016-03-22 17:18:20 -0700182 private static final int BIND_TIMEOUT_MILLIS = 30000;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800183
Meng Wang0f6b2ea2020-01-06 18:31:16 -0800184 // Keys used for saving and restoring config bundle from file.
185 private static final String KEY_VERSION = "__carrier_config_package_version__";
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800186
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100187 private static final String OVERRIDE_PACKAGE_ADDITION = "-override";
188
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700189 // SharedPreferences key for last known build fingerprint.
190 private static final String KEY_FINGERPRINT = "build_fingerprint";
191
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -0800192 // Argument for #dump that indicates we should also call the default and specified carrier
193 // service's #dump method. In multi-SIM devices, it's possible that carrier A is on SIM 1 and
194 // carrier B is on SIM 2, in which case we should not dump carrier B's service when carrier A
195 // requested the dump.
196 private static final String DUMP_ARG_REQUESTING_PACKAGE = "--requesting-package";
197
rambowang14757c22022-10-03 11:54:56 -0500198 // Configs that should always be included when clients calls getConfig[ForSubId] with specified
199 // keys (even configs are not explicitly specified). Those configs have special purpose for the
200 // carrier config APIs to work correctly.
201 private static final String[] CONFIG_SUBSET_METADATA_KEYS = new String[] {
202 CarrierConfigManager.KEY_CARRIER_CONFIG_VERSION_STRING,
203 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL
204 };
205
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800206 // Handler to process various events.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700207 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700208 // For each phoneId, the event sequence should be:
Jonathan Basseri65273c82017-07-25 15:08:42 -0700209 // fetch default, connected to default, fetch default (async), fetch default done,
210 // fetch carrier, connected to carrier, fetch carrier (async), fetch carrier done.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700211 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700212 // If there is a saved config file for either the default app or the carrier app, we skip
213 // binding to the app and go straight from fetch to loaded.
214 //
215 // At any time, at most one connection is active. If events are not in this order, previous
216 // connection will be unbound, so only latest event takes effect.
217 //
218 // We broadcast ACTION_CARRIER_CONFIG_CHANGED after:
219 // 1. loading from carrier app (even if read from a file)
220 // 2. loading from default app if there is no carrier app (even if read from a file)
221 // 3. clearing config (e.g. due to sim removal)
222 // 4. encountering bind or IPC error
Jonathan Basseri65273c82017-07-25 15:08:42 -0700223 private class ConfigHandler extends Handler {
Rambo Wang7e3bc122021-03-23 09:24:38 -0700224 ConfigHandler(@NonNull Looper looper) {
225 super(looper);
226 }
227
Jonathan Basseri65273c82017-07-25 15:08:42 -0700228 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000229 public void handleMessage(@NonNull Message msg) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700230 final int phoneId = msg.arg1;
Rambo Wangab13e3e2021-04-08 15:01:06 -0700231 logdWithLocalLog("mHandler: " + eventToString(msg.what) + " phoneId: " + phoneId);
Malcolm Chen5ea18532019-10-24 19:55:44 -0700232 if (!SubscriptionManager.isValidPhoneId(phoneId)
233 && msg.what != EVENT_MULTI_SIM_CONFIG_CHANGED) {
234 return;
235 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800236 switch (msg.what) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800237 case EVENT_CLEAR_CONFIG: {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700238 clearConfigForPhone(phoneId, true);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800239 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700240 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700241
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800242 case EVENT_SYSTEM_UNLOCKED: {
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000243 for (int i = 0; i < mNumPhones; ++i) {
Sarah Chin807d5c62020-03-30 17:21:09 -0700244 // When the user unlocks the device, send the broadcast again (with a
245 // rebroadcast extra) if we have sent it before unlock. This will avoid
246 // trying to load the carrier config when the SIM is still loading when the
247 // unlock happens.
Junda Liu03aad762017-07-21 13:32:17 -0700248 if (mHasSentConfigChange[i]) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800249 logdWithLocalLog("System unlocked");
Sarah Chin807d5c62020-03-30 17:21:09 -0700250 mFromSystemUnlocked[i] = true;
Junda Liu03aad762017-07-21 13:32:17 -0700251 updateConfigForPhoneId(i);
252 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700253 }
254 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700255 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700256
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800257 case EVENT_PACKAGE_CHANGED: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700258 final String carrierPackageName = (String) msg.obj;
Rambo Wanga27fbe52022-04-12 19:09:07 +0000259 // Always clear up the cache and re-load config from scratch since the carrier
260 // service change is reliable and specific to the phoneId now.
261 clearCachedConfigForPackage(carrierPackageName);
262 logdWithLocalLog("Package changed: " + carrierPackageName
263 + ", phone=" + phoneId);
264 updateConfigForPhoneId(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700265 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700266 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700267
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800268 case EVENT_DO_FETCH_DEFAULT: {
Rambo Wang9bc7d362021-03-09 09:10:58 -0800269 // Clear in-memory cache for carrier app config, so when carrier app gets
270 // uninstalled, no stale config is left.
271 if (mConfigFromCarrierApp[phoneId] != null
272 && getCarrierPackageForPhoneId(phoneId) == null) {
273 mConfigFromCarrierApp[phoneId] = null;
274 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100275 // Restore persistent override values.
276 PersistableBundle config = restoreConfigFromXml(
277 mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION, phoneId);
278 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800279 logd("Loaded persistent override config from XML. package="
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100280 + mPlatformCarrierConfigPackage
281 + " phoneId=" + phoneId);
282 mPersistentOverrideConfigs[phoneId] = config;
283 }
284
285 config = restoreConfigFromXml(mPlatformCarrierConfigPackage, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700286 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800287 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700288 "Loaded config from XML. package="
289 + mPlatformCarrierConfigPackage
290 + " phoneId="
291 + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700292 mConfigFromDefaultApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700293 Message newMsg = obtainMessage(EVENT_FETCH_DEFAULT_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700294 newMsg.getData().putBoolean("loaded_from_xml", true);
295 mHandler.sendMessage(newMsg);
296 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700297 // No cached config, so fetch it from the default app.
298 if (bindToConfigPackage(
299 mPlatformCarrierConfigPackage,
300 phoneId,
301 EVENT_CONNECTED_TO_DEFAULT)) {
302 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800303 obtainMessage(EVENT_BIND_DEFAULT_TIMEOUT, phoneId, -1 /*arg2*/,
304 getMessageToken(phoneId)),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700305 BIND_TIMEOUT_MILLIS);
306 } else {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800307 // Put a stub bundle in place so that the rest of the logic continues
308 // smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000309 mConfigFromDefaultApp[phoneId] = new PersistableBundle();
Jonathan Basseri65273c82017-07-25 15:08:42 -0700310 // Send broadcast if bind fails.
Jack Yue37dd262022-12-16 11:53:37 -0800311 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700312 // TODO: We *must* call unbindService even if bindService returns false.
313 // (And possibly if SecurityException was thrown.)
chen xudb04c292019-03-26 17:01:15 -0700314 loge("binding to default app: "
315 + mPlatformCarrierConfigPackage + " fails");
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700316 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800317 }
318 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700319 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800320
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800321 case EVENT_CONNECTED_TO_DEFAULT: {
Rambo Wang610fdf62021-03-08 21:37:11 -0800322 removeMessages(EVENT_BIND_DEFAULT_TIMEOUT, getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700323 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800324 // If new service connection has been created, unbind.
325 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700326 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800327 break;
328 }
chen xu02581692018-11-11 19:03:44 -0800329 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700330 // ResultReceiver callback will execute in this Handler's thread.
331 final ResultReceiver resultReceiver =
332 new ResultReceiver(this) {
333 @Override
334 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700335 unbindIfBound(mContext, conn, phoneId);
Rambo Wanga9d27a52021-04-09 16:17:33 -0700336 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT,
337 getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700338 // If new service connection has been created, this is stale.
339 if (mServiceConnection[phoneId] != conn) {
340 loge("Received response for stale request.");
341 return;
342 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700343 if (resultCode == RESULT_ERROR || resultData == null) {
344 // On error, abort config fetching.
345 loge("Failed to get carrier config");
Jack Yue37dd262022-12-16 11:53:37 -0800346 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700347 return;
348 }
349 PersistableBundle config =
350 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100351 saveConfigToXml(mPlatformCarrierConfigPackage, "", phoneId,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800352 carrierId, config);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700353 mConfigFromDefaultApp[phoneId] = config;
354 sendMessage(
355 obtainMessage(
356 EVENT_FETCH_DEFAULT_DONE, phoneId, -1));
357 }
358 };
359 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800360 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700361 ICarrierService carrierService =
362 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800363 carrierService.getCarrierConfig(phoneId, carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800364 logdWithLocalLog("Fetch config for default app: "
chen xudb04c292019-03-26 17:01:15 -0700365 + mPlatformCarrierConfigPackage
366 + " carrierid: " + carrierId.toString());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700367 } catch (RemoteException e) {
chen xudb04c292019-03-26 17:01:15 -0700368 loge("Failed to get carrier config from default app: " +
369 mPlatformCarrierConfigPackage + " err: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700370 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700371 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800372 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700373 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800374 obtainMessage(EVENT_FETCH_DEFAULT_TIMEOUT, phoneId, -1 /*arg2*/,
375 getMessageToken(phoneId)),
Jonathan Basseri65273c82017-07-25 15:08:42 -0700376 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800377 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700378 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800379
Jonathan Basseri930701e2015-06-11 20:56:43 -0700380 case EVENT_BIND_DEFAULT_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800381 case EVENT_FETCH_DEFAULT_TIMEOUT: {
382 loge("Bind/fetch time out from " + mPlatformCarrierConfigPackage);
Rambo Wang610fdf62021-03-08 21:37:11 -0800383 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT, getMessageToken(phoneId));
chen xuf60b3162019-05-01 21:31:05 -0700384 // If we attempted to bind to the app, but the service connection is null due to
385 // the race condition that clear config event happens before bind/fetch complete
386 // then config was cleared while we were waiting and we should not continue.
387 if (mServiceConnection[phoneId] != null) {
388 // If a ResponseReceiver callback is in the queue when this happens, we will
389 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700390 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700391 broadcastConfigChangedIntent(phoneId);
392 }
Nathan Harold1122e3d2021-01-22 15:45:24 -0800393 // Put a stub bundle in place so that the rest of the logic continues smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000394 mConfigFromDefaultApp[phoneId] = new PersistableBundle();
Jack Yue37dd262022-12-16 11:53:37 -0800395 updateSubscriptionDatabase(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700396 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700397 }
Jonathan Basseri930701e2015-06-11 20:56:43 -0700398
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800399 case EVENT_FETCH_DEFAULT_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700400 // If we attempted to bind to the app, but the service connection is null, then
401 // config was cleared while we were waiting and we should not continue.
402 if (!msg.getData().getBoolean("loaded_from_xml", false)
403 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800404 break;
405 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700406 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700407 if (carrierPackageName != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800408 logd("Found carrier config app: " + carrierPackageName);
Jordan Liu38a614c2019-03-20 15:01:17 -0700409 sendMessage(obtainMessage(EVENT_DO_FETCH_CARRIER, phoneId, -1));
Jonathan Basserib919e932015-05-27 16:53:08 +0000410 } else {
Jack Yue37dd262022-12-16 11:53:37 -0800411 updateSubscriptionDatabase(phoneId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700412 }
413 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700414 }
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700415
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800416 case EVENT_DO_FETCH_CARRIER: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700417 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700418 final PersistableBundle config =
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100419 restoreConfigFromXml(carrierPackageName, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700420 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800421 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700422 "Loaded config from XML. package="
423 + carrierPackageName
424 + " phoneId="
425 + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700426 mConfigFromCarrierApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700427 Message newMsg = obtainMessage(EVENT_FETCH_CARRIER_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700428 newMsg.getData().putBoolean("loaded_from_xml", true);
429 sendMessage(newMsg);
430 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700431 // No cached config, so fetch it from a carrier app.
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800432 if (carrierPackageName != null && bindToConfigPackage(carrierPackageName,
433 phoneId, EVENT_CONNECTED_TO_CARRIER)) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700434 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800435 obtainMessage(EVENT_BIND_CARRIER_TIMEOUT, phoneId, -1 /*arg2*/,
436 getMessageToken(phoneId)),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700437 BIND_TIMEOUT_MILLIS);
438 } else {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800439 // Put a stub bundle in place so that the rest of the logic continues
440 // smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000441 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
Jonathan Basseri65273c82017-07-25 15:08:42 -0700442 // Send broadcast if bind fails.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700443 broadcastConfigChangedIntent(phoneId);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800444 loge("Bind to carrier app: " + carrierPackageName + " fails");
Jack Yue37dd262022-12-16 11:53:37 -0800445 updateSubscriptionDatabase(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700446 }
447 }
448 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700449 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700450
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800451 case EVENT_CONNECTED_TO_CARRIER: {
Rambo Wang610fdf62021-03-08 21:37:11 -0800452 removeMessages(EVENT_BIND_CARRIER_TIMEOUT, getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700453 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800454 // If new service connection has been created, unbind.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700455 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700456 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800457 break;
458 }
chen xu02581692018-11-11 19:03:44 -0800459 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700460 // ResultReceiver callback will execute in this Handler's thread.
461 final ResultReceiver resultReceiver =
462 new ResultReceiver(this) {
463 @Override
464 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700465 unbindIfBound(mContext, conn, phoneId);
Rambo Wanga9d27a52021-04-09 16:17:33 -0700466 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT,
467 getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700468 // If new service connection has been created, this is stale.
469 if (mServiceConnection[phoneId] != conn) {
470 loge("Received response for stale request.");
471 return;
472 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700473 if (resultCode == RESULT_ERROR || resultData == null) {
474 // On error, abort config fetching.
chen xudb04c292019-03-26 17:01:15 -0700475 loge("Failed to get carrier config from carrier app: "
476 + getCarrierPackageForPhoneId(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700477 broadcastConfigChangedIntent(phoneId);
Jack Yue37dd262022-12-16 11:53:37 -0800478 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700479 return;
480 }
481 PersistableBundle config =
482 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100483 saveConfigToXml(getCarrierPackageForPhoneId(phoneId), "",
484 phoneId, carrierId, config);
Amit Mahajan304e92b2021-04-08 14:03:30 -0700485 if (config != null) {
486 mConfigFromCarrierApp[phoneId] = config;
487 } else {
488 logdWithLocalLog("Config from carrier app is null "
489 + "for phoneId " + phoneId);
490 // Put a stub bundle in place so that the rest of the logic
491 // continues smoothly.
492 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
493 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700494 sendMessage(
495 obtainMessage(
496 EVENT_FETCH_CARRIER_DONE, phoneId, -1));
497 }
498 };
499 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800500 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700501 ICarrierService carrierService =
502 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800503 carrierService.getCarrierConfig(phoneId, carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800504 logdWithLocalLog("Fetch config for carrier app: "
chen xudb04c292019-03-26 17:01:15 -0700505 + getCarrierPackageForPhoneId(phoneId)
506 + " carrierid: " + carrierId.toString());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700507 } catch (RemoteException e) {
508 loge("Failed to get carrier config: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700509 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700510 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800511 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700512 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800513 obtainMessage(EVENT_FETCH_CARRIER_TIMEOUT, phoneId, -1 /*arg2*/,
514 getMessageToken(phoneId)),
Jonathan Basseri65273c82017-07-25 15:08:42 -0700515 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800516 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700517 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800518
Jonathan Basseri930701e2015-06-11 20:56:43 -0700519 case EVENT_BIND_CARRIER_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800520 case EVENT_FETCH_CARRIER_TIMEOUT: {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800521 loge("Bind/fetch from carrier app timeout, package="
522 + getCarrierPackageForPhoneId(phoneId));
Rambo Wang610fdf62021-03-08 21:37:11 -0800523 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT, getMessageToken(phoneId));
chen xuf60b3162019-05-01 21:31:05 -0700524 // If we attempted to bind to the app, but the service connection is null due to
525 // the race condition that clear config event happens before bind/fetch complete
526 // then config was cleared while we were waiting and we should not continue.
527 if (mServiceConnection[phoneId] != null) {
528 // If a ResponseReceiver callback is in the queue when this happens, we will
529 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700530 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700531 broadcastConfigChangedIntent(phoneId);
532 }
Nathan Harold1122e3d2021-01-22 15:45:24 -0800533 // Put a stub bundle in place so that the rest of the logic continues smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000534 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
Jack Yue37dd262022-12-16 11:53:37 -0800535 updateSubscriptionDatabase(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700536 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700537 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800538 case EVENT_FETCH_CARRIER_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700539 // If we attempted to bind to the app, but the service connection is null, then
540 // config was cleared while we were waiting and we should not continue.
541 if (!msg.getData().getBoolean("loaded_from_xml", false)
542 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800543 break;
544 }
Jack Yue37dd262022-12-16 11:53:37 -0800545 updateSubscriptionDatabase(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800546 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700547 }
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700548
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800549 case EVENT_CHECK_SYSTEM_UPDATE: {
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700550 SharedPreferences sharedPrefs =
551 PreferenceManager.getDefaultSharedPreferences(mContext);
552 final String lastFingerprint = sharedPrefs.getString(KEY_FINGERPRINT, null);
553 if (!Build.FINGERPRINT.equals(lastFingerprint)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800554 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700555 "Build fingerprint changed. old: "
556 + lastFingerprint
557 + " new: "
558 + Build.FINGERPRINT);
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700559 clearCachedConfigForPackage(null);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700560 sharedPrefs
561 .edit()
562 .putString(KEY_FINGERPRINT, Build.FINGERPRINT)
563 .apply();
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700564 }
565 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700566 }
Nathan Harold48ac0972019-03-13 22:33:01 -0700567
568 case EVENT_SUBSCRIPTION_INFO_UPDATED:
569 broadcastConfigChangedIntent(phoneId);
570 break;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700571 case EVENT_MULTI_SIM_CONFIG_CHANGED:
572 onMultiSimConfigChanged();
573 break;
Jayachandran C645ec612020-01-10 10:30:25 -0800574
575 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG: {
576 PersistableBundle config =
577 restoreNoSimConfigFromXml(mPlatformCarrierConfigPackage);
578
579 if (config != null) {
580 logd("Loaded no SIM config from XML. package="
581 + mPlatformCarrierConfigPackage);
582 mNoSimConfig = config;
583 sendMessage(
584 obtainMessage(
585 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
586 phoneId, -1));
587 } else {
588 // No cached config, so fetch it from the default app.
589 if (bindToConfigPackage(
590 mPlatformCarrierConfigPackage,
591 phoneId,
592 EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG)) {
593 sendMessageDelayed(
594 obtainMessage(
595 EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
596 phoneId, -1), BIND_TIMEOUT_MILLIS);
597 } else {
598 broadcastConfigChangedIntent(phoneId, false);
599 // TODO: We *must* call unbindService even if bindService returns false.
600 // (And possibly if SecurityException was thrown.)
601 loge("binding to default app to fetch no SIM config: "
602 + mPlatformCarrierConfigPackage + " fails");
603 }
604 }
605 break;
606 }
607
608 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE: {
609 broadcastConfigChangedIntent(phoneId, false);
610 break;
611 }
612
613 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
614 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT: {
615 loge("Bind/fetch time out for no SIM config from "
616 + mPlatformCarrierConfigPackage);
617 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
618 // If we attempted to bind to the app, but the service connection is null due to
619 // the race condition that clear config event happens before bind/fetch complete
620 // then config was cleared while we were waiting and we should not continue.
621 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
622 // If a ResponseReceiver callback is in the queue when this happens, we will
623 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700624 unbindIfBoundForNoSimConfig(mContext,
625 mServiceConnectionForNoSimConfig[phoneId], phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800626 }
627 broadcastConfigChangedIntent(phoneId, false);
628 break;
629 }
630
631 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG: {
632 removeMessages(EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
633 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
634 // If new service connection has been created, unbind.
635 if (mServiceConnectionForNoSimConfig[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700636 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800637 break;
638 }
639
640 // ResultReceiver callback will execute in this Handler's thread.
641 final ResultReceiver resultReceiver =
642 new ResultReceiver(this) {
643 @Override
644 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700645 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800646 // If new service connection has been created, this is stale.
647 if (mServiceConnectionForNoSimConfig[phoneId] != conn) {
648 loge("Received response for stale request.");
649 return;
650 }
651 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
652 if (resultCode == RESULT_ERROR || resultData == null) {
653 // On error, abort config fetching.
654 loge("Failed to get no SIM carrier config");
655 return;
656 }
657 PersistableBundle config =
658 resultData.getParcelable(KEY_CONFIG_BUNDLE);
659 saveNoSimConfigToXml(mPlatformCarrierConfigPackage, config);
660 mNoSimConfig = config;
661 sendMessage(
662 obtainMessage(
663 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
664 phoneId, -1));
665 }
666 };
667 // Now fetch the config asynchronously from the ICarrierService.
668 try {
669 ICarrierService carrierService =
670 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800671 carrierService.getCarrierConfig(phoneId, null, resultReceiver);
Jayachandran C645ec612020-01-10 10:30:25 -0800672 logdWithLocalLog("Fetch no sim config from default app: "
673 + mPlatformCarrierConfigPackage);
674 } catch (RemoteException e) {
675 loge("Failed to get no sim carrier config from default app: " +
676 mPlatformCarrierConfigPackage + " err: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700677 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800678 break; // So we don't set a timeout.
679 }
680 sendMessageDelayed(
681 obtainMessage(
682 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
683 phoneId, -1), BIND_TIMEOUT_MILLIS);
684 break;
685 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800686 }
687 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700688 }
689
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000690 @NonNull private final Handler mHandler;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800691
692 /**
693 * Constructs a CarrierConfigLoader, registers it as a service, and registers a broadcast
694 * receiver for relevant events.
695 */
Rambo Wang7e3bc122021-03-23 09:24:38 -0700696 @VisibleForTesting
Jack Yu3beaf9d2023-04-14 09:17:27 -0700697 /* package */ CarrierConfigLoader(@NonNull Context context, @NonNull Looper looper) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800698 mContext = context;
Meng Wang33ad2bc2017-03-16 20:21:20 -0700699 mPlatformCarrierConfigPackage =
700 mContext.getString(R.string.platform_carrier_config_package);
Rambo Wang7e3bc122021-03-23 09:24:38 -0700701 mHandler = new ConfigHandler(looper);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800702
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000703 IntentFilter systemEventsFilter = new IntentFilter();
704 systemEventsFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
Rambo Wanga27fbe52022-04-12 19:09:07 +0000705 context.registerReceiver(mSystemBroadcastReceiver, systemEventsFilter);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800706
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000707 mNumPhones = TelephonyManager.from(context).getActiveModemCount();
708 mConfigFromDefaultApp = new PersistableBundle[mNumPhones];
709 mConfigFromCarrierApp = new PersistableBundle[mNumPhones];
710 mPersistentOverrideConfigs = new PersistableBundle[mNumPhones];
711 mOverrideConfigs = new PersistableBundle[mNumPhones];
Rambo Wang42026112021-04-07 20:57:28 +0000712 mNoSimConfig = new PersistableBundle();
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000713 mServiceConnection = new CarrierServiceConnection[mNumPhones];
714 mServiceBound = new boolean[mNumPhones];
715 mHasSentConfigChange = new boolean[mNumPhones];
716 mFromSystemUnlocked = new boolean[mNumPhones];
717 mServiceConnectionForNoSimConfig = new CarrierServiceConnection[mNumPhones];
718 mServiceBoundForNoSimConfig = new boolean[mNumPhones];
Rambo Wanga27fbe52022-04-12 19:09:07 +0000719 mCarrierServiceChangeCallbacks = new CarrierServiceChangeCallback[mNumPhones];
720 for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
721 mCarrierServiceChangeCallbacks[phoneId] = new CarrierServiceChangeCallback(phoneId);
722 TelephonyManager.from(context).registerCarrierPrivilegesCallback(phoneId,
723 new HandlerExecutor(mHandler), mCarrierServiceChangeCallbacks[phoneId]);
724 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800725 logd("CarrierConfigLoader has started");
Jack Yu771c6ce2023-02-02 17:51:42 -0800726
727 PhoneConfigurationManager.registerForMultiSimConfigChange(
728 mHandler, EVENT_MULTI_SIM_CONFIG_CHANGED, null);
729
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700730 mHandler.sendEmptyMessage(EVENT_CHECK_SYSTEM_UPDATE);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800731 }
732
733 /**
734 * Initialize the singleton CarrierConfigLoader instance.
735 *
736 * This is only done once, at startup, from {@link com.android.phone.PhoneApp#onCreate}.
737 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000738 @NonNull
739 /* package */ static CarrierConfigLoader init(@NonNull Context context) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800740 synchronized (CarrierConfigLoader.class) {
741 if (sInstance == null) {
Jack Yu3beaf9d2023-04-14 09:17:27 -0700742 sInstance = new CarrierConfigLoader(context, Looper.myLooper());
Brad Ebingerfa6575f2021-05-04 00:29:50 +0000743 // Make this service available through ServiceManager.
744 TelephonyFrameworkInitializer.getTelephonyServiceManager()
745 .getCarrierConfigServiceRegisterer().register(sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800746 } else {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700747 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800748 }
749 return sInstance;
750 }
751 }
752
Rambo Wang7e3bc122021-03-23 09:24:38 -0700753 @VisibleForTesting
754 /* package */ void clearConfigForPhone(int phoneId, boolean fetchNoSimConfig) {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700755 /* Ignore clear configuration request if device is being shutdown. */
756 Phone phone = PhoneFactory.getPhone(phoneId);
757 if (phone != null) {
758 if (phone.isShuttingDown()) {
759 return;
760 }
761 }
762
Jack Yu771c6ce2023-02-02 17:51:42 -0800763 if (mConfigFromDefaultApp.length <= phoneId) {
764 Log.wtf(LOG_TAG, "Invalid phone id " + phoneId);
765 return;
766 }
767
Malcolm Chen5ea18532019-10-24 19:55:44 -0700768 mConfigFromDefaultApp[phoneId] = null;
769 mConfigFromCarrierApp[phoneId] = null;
770 mServiceConnection[phoneId] = null;
771 mHasSentConfigChange[phoneId] = false;
772
Jayachandran C645ec612020-01-10 10:30:25 -0800773 if (fetchNoSimConfig) {
774 // To fetch no SIM config
775 mHandler.sendMessage(
776 mHandler.obtainMessage(
777 EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG, phoneId, -1));
778 }
Malcolm Chen5ea18532019-10-24 19:55:44 -0700779 }
780
Jack Yue37dd262022-12-16 11:53:37 -0800781 private void updateSubscriptionDatabase(int phoneId) {
Jack Yu90813e62023-01-17 17:46:27 -0800782 logd("updateSubscriptionDatabase: phoneId=" + phoneId);
Jack Yue37dd262022-12-16 11:53:37 -0800783 String configPackageName;
Nathan Harold48ac0972019-03-13 22:33:01 -0700784 PersistableBundle configToSend;
785 int carrierId = getSpecificCarrierIdForPhoneId(phoneId);
786 // Prefer the carrier privileged carrier app, but if there is not one, use the platform
787 // default carrier app.
788 if (mConfigFromCarrierApp[phoneId] != null) {
Jack Yue37dd262022-12-16 11:53:37 -0800789 configPackageName = getCarrierPackageForPhoneId(phoneId);
Nathan Harold48ac0972019-03-13 22:33:01 -0700790 configToSend = mConfigFromCarrierApp[phoneId];
791 } else {
Jack Yue37dd262022-12-16 11:53:37 -0800792 configPackageName = mPlatformCarrierConfigPackage;
Nathan Harold48ac0972019-03-13 22:33:01 -0700793 configToSend = mConfigFromDefaultApp[phoneId];
794 }
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700795
Malcolm Chenefafd1c2020-02-20 13:27:08 -0800796 if (configToSend == null) {
Rambo Wang42026112021-04-07 20:57:28 +0000797 configToSend = new PersistableBundle();
Malcolm Chenefafd1c2020-02-20 13:27:08 -0800798 }
799
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700800 // mOverrideConfigs is for testing. And it will override current configs.
801 PersistableBundle config = mOverrideConfigs[phoneId];
802 if (config != null) {
Torbjorn Eklund1050cb02018-11-16 14:05:38 +0100803 configToSend = new PersistableBundle(configToSend);
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700804 configToSend.putAll(config);
805 }
806
Jack Yu3beaf9d2023-04-14 09:17:27 -0700807 SubscriptionManagerService.getInstance().updateSubscriptionByCarrierConfig(
808 phoneId, configPackageName, configToSend,
809 () -> mHandler.obtainMessage(EVENT_SUBSCRIPTION_INFO_UPDATED, phoneId, -1)
810 .sendToTarget());
Nathan Harold48ac0972019-03-13 22:33:01 -0700811 }
812
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800813 private void broadcastConfigChangedIntent(int phoneId) {
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800814 broadcastConfigChangedIntent(phoneId, true);
815 }
816
817 private void broadcastConfigChangedIntent(int phoneId, boolean addSubIdExtra) {
rambowangd63ba342022-10-02 11:21:08 -0500818 int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
819 int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
820 int specificCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
821
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800822 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
Christopher Tate38f55eb2017-02-14 14:43:49 -0800823 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT |
chen xuf9db49f2019-03-31 23:04:42 -0700824 Intent.FLAG_RECEIVER_FOREGROUND);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800825 if (addSubIdExtra) {
rambowangd63ba342022-10-02 11:21:08 -0500826 int simApplicationState = getSimApplicationStateForPhone(phoneId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800827 // Include subId/carrier id extra only if SIM records are loaded
828 if (simApplicationState != TelephonyManager.SIM_STATE_UNKNOWN
829 && simApplicationState != TelephonyManager.SIM_STATE_NOT_READY) {
rambowangd63ba342022-10-02 11:21:08 -0500830 subId = SubscriptionManager.getSubscriptionId(phoneId);
831 carrierId = getCarrierIdForPhoneId(phoneId);
832 specificCarrierId = getSpecificCarrierIdForPhoneId(phoneId);
833 intent.putExtra(TelephonyManager.EXTRA_SPECIFIC_CARRIER_ID, specificCarrierId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800834 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, phoneId);
rambowangd63ba342022-10-02 11:21:08 -0500835 intent.putExtra(TelephonyManager.EXTRA_CARRIER_ID, carrierId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800836 }
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800837 }
Amit Mahajanb33bcda2018-01-24 12:56:44 -0800838 intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, phoneId);
Sarah Chin807d5c62020-03-30 17:21:09 -0700839 intent.putExtra(CarrierConfigManager.EXTRA_REBROADCAST_ON_UNLOCK,
840 mFromSystemUnlocked[phoneId]);
rambowangd63ba342022-10-02 11:21:08 -0500841
842 TelephonyRegistryManager trm = mContext.getSystemService(TelephonyRegistryManager.class);
843 // Unlike broadcast, we wouldn't notify registrants on carrier config change when device is
844 // unlocked. Only real carrier config change will send the notification to registrants.
845 if (trm != null && !mFromSystemUnlocked[phoneId]) {
846 trm.notifyCarrierConfigChanged(phoneId, subId, carrierId, specificCarrierId);
847 }
848
Meng Wang97a6a462020-01-23 16:22:16 -0800849 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
rambowangd63ba342022-10-02 11:21:08 -0500850
Jack Yu00ece8c2022-11-19 22:29:12 -0800851 if (SubscriptionManager.isValidSubscriptionId(subId)) {
852 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId + ", subId=" + subId);
Jack Yue9e95be2020-03-22 10:56:06 -0700853 } else {
854 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId);
855 }
Junda Liu03aad762017-07-21 13:32:17 -0700856 mHasSentConfigChange[phoneId] = true;
Sarah Chin807d5c62020-03-30 17:21:09 -0700857 mFromSystemUnlocked[phoneId] = false;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800858 }
859
rambowangd63ba342022-10-02 11:21:08 -0500860 private int getSimApplicationStateForPhone(int phoneId) {
861 int simApplicationState = TelephonyManager.SIM_STATE_UNKNOWN;
862 int subId = SubscriptionManager.getSubscriptionId(phoneId);
863 if (SubscriptionManager.isValidSubscriptionId(subId)) {
864 TelephonyManager telMgr = TelephonyManager.from(mContext)
865 .createForSubscriptionId(subId);
866 simApplicationState = telMgr.getSimApplicationState();
867 }
868 return simApplicationState;
869 }
870
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800871 /** Binds to the default or carrier config app. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000872 private boolean bindToConfigPackage(@NonNull String pkgName, int phoneId, int eventId) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800873 logdWithLocalLog("Binding to " + pkgName + " for phone " + phoneId);
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700874 Intent carrierService = new Intent(CarrierService.CARRIER_SERVICE_INTERFACE);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700875 carrierService.setPackage(pkgName);
Jayachandran C645ec612020-01-10 10:30:25 -0800876 CarrierServiceConnection serviceConnection = new CarrierServiceConnection(
877 phoneId, pkgName, eventId);
878 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
879 mServiceConnectionForNoSimConfig[phoneId] = serviceConnection;
880 } else {
881 mServiceConnection[phoneId] = serviceConnection;
882 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800883 try {
Jayachandran C645ec612020-01-10 10:30:25 -0800884 if (mContext.bindService(carrierService, serviceConnection,
Jordan Liu178430d2020-02-10 14:32:15 -0800885 Context.BIND_AUTO_CREATE)) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700886 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
887 mServiceBoundForNoSimConfig[phoneId] = true;
888 } else {
889 mServiceBound[phoneId] = true;
890 }
Jordan Liu178430d2020-02-10 14:32:15 -0800891 return true;
892 } else {
893 return false;
894 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800895 } catch (SecurityException ex) {
896 return false;
897 }
898 }
899
Rambo Wang7e3bc122021-03-23 09:24:38 -0700900 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000901 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -0700902 /* package */ CarrierIdentifier getCarrierIdentifierForPhoneId(int phoneId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800903 String mcc = "";
904 String mnc = "";
905 String imsi = "";
906 String gid1 = "";
907 String gid2 = "";
908 String spn = TelephonyManager.from(mContext).getSimOperatorNameForPhone(phoneId);
909 String simOperator = TelephonyManager.from(mContext).getSimOperatorNumericForPhone(phoneId);
chen xu02581692018-11-11 19:03:44 -0800910 int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
chen xua31f22b2019-03-06 15:28:50 -0800911 int specificCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
Jonathan Basseri1fa437c2015-04-20 11:08:18 -0700912 // A valid simOperator should be 5 or 6 digits, depending on the length of the MNC.
913 if (simOperator != null && simOperator.length() >= 3) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800914 mcc = simOperator.substring(0, 3);
915 mnc = simOperator.substring(3);
916 }
917 Phone phone = PhoneFactory.getPhone(phoneId);
918 if (phone != null) {
919 imsi = phone.getSubscriberId();
920 gid1 = phone.getGroupIdLevel1();
Junda Liu73183532015-05-14 13:55:40 -0700921 gid2 = phone.getGroupIdLevel2();
chen xu02581692018-11-11 19:03:44 -0800922 carrierId = phone.getCarrierId();
chen xua31f22b2019-03-06 15:28:50 -0800923 specificCarrierId = phone.getSpecificCarrierId();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800924 }
chen xua31f22b2019-03-06 15:28:50 -0800925 return new CarrierIdentifier(mcc, mnc, spn, imsi, gid1, gid2, carrierId, specificCarrierId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800926 }
927
Rambo Wangf7c214a2022-03-17 12:36:22 -0700928 /** Returns the package name of a privileged carrier app, or null if there is none. */
Nathan Harold1122e3d2021-01-22 15:45:24 -0800929 @Nullable
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700930 private String getCarrierPackageForPhoneId(int phoneId) {
Nazanin1adf4562021-03-29 15:35:30 -0700931 final long token = Binder.clearCallingIdentity();
932 try {
Rambo Wangf7c214a2022-03-17 12:36:22 -0700933 return TelephonyManager.from(mContext)
934 .getCarrierServicePackageNameForLogicalSlot(phoneId);
Nazanin1adf4562021-03-29 15:35:30 -0700935 } finally {
936 Binder.restoreCallingIdentity(token);
937 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700938 }
939
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000940 @Nullable
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700941 private String getIccIdForPhoneId(int phoneId) {
942 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
943 return null;
944 }
945 Phone phone = PhoneFactory.getPhone(phoneId);
946 if (phone == null) {
947 return null;
948 }
949 return phone.getIccSerialNumber();
950 }
951
chen xu02581692018-11-11 19:03:44 -0800952 /**
chen xua31f22b2019-03-06 15:28:50 -0800953 * Get the sim specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}
chen xu02581692018-11-11 19:03:44 -0800954 */
chen xua31f22b2019-03-06 15:28:50 -0800955 private int getSpecificCarrierIdForPhoneId(int phoneId) {
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700956 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
chen xu02581692018-11-11 19:03:44 -0800957 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700958 }
959 Phone phone = PhoneFactory.getPhone(phoneId);
960 if (phone == null) {
chen xu02581692018-11-11 19:03:44 -0800961 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700962 }
chen xua31f22b2019-03-06 15:28:50 -0800963 return phone.getSpecificCarrierId();
chen xu02581692018-11-11 19:03:44 -0800964 }
965
966 /**
967 * Get the sim carrier id {@link TelephonyManager#getSimCarrierId() }
968 */
969 private int getCarrierIdForPhoneId(int phoneId) {
970 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
971 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700972 }
chen xu02581692018-11-11 19:03:44 -0800973 Phone phone = PhoneFactory.getPhone(phoneId);
974 if (phone == null) {
975 return TelephonyManager.UNKNOWN_CARRIER_ID;
976 }
977 return phone.getCarrierId();
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700978 }
979
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700980 /**
981 * Writes a bundle to an XML file.
982 *
chen xu02581692018-11-11 19:03:44 -0800983 * The bundle will be written to a file named after the package name, ICCID and
chen xua31f22b2019-03-06 15:28:50 -0800984 * specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}. the same carrier
chen xu02581692018-11-11 19:03:44 -0800985 * should have a single copy of XML file named after carrier id. However, it's still possible
986 * that platform doesn't recognize the current sim carrier, we will use iccid + carrierid as
987 * the canonical file name. carrierid can also handle the cases SIM OTA resolves to different
988 * carrier while iccid remains the same.
989 *
990 * The file can be restored later with {@link @restoreConfigFromXml}. The XML output will
991 * include the bundle and the current version of the specified package.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700992 *
993 * In case of errors or invalid input, no file will be written.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700994 *
Jayachandran C645ec612020-01-10 10:30:25 -0800995 * @param packageName the name of the package from which we fetched this bundle.
996 * @param extraString An extra string to be used in the XML file name.
997 * @param phoneId the phone ID.
998 * @param carrierId contains all carrier-identifying information.
999 * @param config the bundle to be written. Null will be treated as an empty bundle.
1000 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001001 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001002 private void saveConfigToXml(@Nullable String packageName, @NonNull String extraString,
1003 int phoneId, @Nullable CarrierIdentifier carrierId, @NonNull PersistableBundle config,
1004 boolean isNoSimConfig) {
Jayachandran C645ec612020-01-10 10:30:25 -08001005 if (packageName == null) {
1006 loge("Cannot save config with null packageName");
Yuchen Dongc15afed2018-04-26 17:05:22 +08001007 return;
1008 }
1009
Jayachandran C645ec612020-01-10 10:30:25 -08001010 String fileName;
1011 if (isNoSimConfig) {
1012 fileName = getFilenameForNoSimConfig(packageName);
1013 } else {
Jack Yuf5badd92022-12-08 00:50:53 -08001014 if (TelephonyManager.getSimStateForSlotIndex(phoneId)
Jayachandran C645ec612020-01-10 10:30:25 -08001015 != TelephonyManager.SIM_STATE_LOADED) {
1016 loge("Skip save config because SIM records are not loaded.");
1017 return;
1018 }
1019
1020 final String iccid = getIccIdForPhoneId(phoneId);
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001021 final int cid = carrierId != null ? carrierId.getSpecificCarrierId()
1022 : TelephonyManager.UNKNOWN_CARRIER_ID;
Jayachandran C645ec612020-01-10 10:30:25 -08001023 if (iccid == null) {
1024 loge("Cannot save config with null iccid.");
1025 return;
1026 }
1027 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001028 }
Jayachandran C645ec612020-01-10 10:30:25 -08001029
Junda Liu02596502016-11-15 13:46:43 -08001030 // b/32668103 Only save to file if config isn't empty.
1031 // In case of failure, not caching an empty bundle will
1032 // try loading config again on next power on or sim loaded.
1033 // Downside is for genuinely empty bundle, will bind and load
1034 // on every power on.
1035 if (config == null || config.isEmpty()) {
1036 return;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001037 }
1038
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001039 final String version = getPackageVersion(packageName);
1040 if (version == null) {
1041 loge("Failed to get package version for: " + packageName);
1042 return;
1043 }
1044
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001045 logdWithLocalLog(
1046 "Save config to xml, packagename: " + packageName + " phoneId: " + phoneId);
chen xudb04c292019-03-26 17:01:15 -07001047
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001048 FileOutputStream outFile = null;
1049 try {
Jayachandran C645ec612020-01-10 10:30:25 -08001050 outFile = new FileOutputStream(new File(mContext.getFilesDir(), fileName));
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001051 config.putString(KEY_VERSION, version);
1052 config.writeToStream(outFile);
1053 outFile.flush();
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001054 outFile.close();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001055 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001056 loge(e.toString());
1057 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001058 }
1059
Rambo Wang7e3bc122021-03-23 09:24:38 -07001060 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001061 /* package */ void saveConfigToXml(@Nullable String packageName, @NonNull String extraString,
1062 int phoneId, @NonNull CarrierIdentifier carrierId, @NonNull PersistableBundle config) {
Jayachandran C645ec612020-01-10 10:30:25 -08001063 saveConfigToXml(packageName, extraString, phoneId, carrierId, config, false);
1064 }
1065
Rambo Wang7e3bc122021-03-23 09:24:38 -07001066 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001067 /* package */ void saveNoSimConfigToXml(@Nullable String packageName,
1068 @NonNull PersistableBundle config) {
Jayachandran C645ec612020-01-10 10:30:25 -08001069 saveConfigToXml(packageName, "", -1, null, config, true);
1070 }
1071
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001072 /**
1073 * Reads a bundle from an XML file.
1074 *
1075 * This restores a bundle that was written with {@link #saveConfigToXml}. This returns the saved
Yuchen Dongc15afed2018-04-26 17:05:22 +08001076 * config bundle for the given package and phone ID.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001077 *
1078 * In case of errors, or if the saved config is from a different package version than the
1079 * current version, then null will be returned.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001080 *
Jayachandran C645ec612020-01-10 10:30:25 -08001081 * @param packageName the name of the package from which we fetched this bundle.
1082 * @param extraString An extra string to be used in the XML file name.
1083 * @param phoneId the phone ID.
1084 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001085 * @return the bundle from the XML file. Returns null if there is no saved config, the saved
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001086 * version does not match, or reading config fails.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001087 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001088 @Nullable
1089 private PersistableBundle restoreConfigFromXml(@Nullable String packageName,
1090 @NonNull String extraString, int phoneId, boolean isNoSimConfig) {
Jayachandran C645ec612020-01-10 10:30:25 -08001091 if (packageName == null) {
1092 loge("Cannot restore config with null packageName");
1093 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001094 final String version = getPackageVersion(packageName);
1095 if (version == null) {
1096 loge("Failed to get package version for: " + packageName);
1097 return null;
1098 }
Yuchen Dongc15afed2018-04-26 17:05:22 +08001099
Jayachandran C645ec612020-01-10 10:30:25 -08001100 String fileName;
arunvoddu664c36a2021-10-11 20:09:28 +00001101 String iccid = null;
Jayachandran C645ec612020-01-10 10:30:25 -08001102 if (isNoSimConfig) {
1103 fileName = getFilenameForNoSimConfig(packageName);
1104 } else {
Jack Yuf5badd92022-12-08 00:50:53 -08001105 if (TelephonyManager.getSimStateForSlotIndex(phoneId)
Jayachandran C645ec612020-01-10 10:30:25 -08001106 != TelephonyManager.SIM_STATE_LOADED) {
1107 loge("Skip restore config because SIM records are not loaded.");
1108 return null;
1109 }
1110
arunvoddu664c36a2021-10-11 20:09:28 +00001111 iccid = getIccIdForPhoneId(phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -08001112 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1113 if (iccid == null) {
1114 loge("Cannot restore config with null iccid.");
1115 return null;
1116 }
1117 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001118 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001119
1120 PersistableBundle restoredBundle = null;
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001121 File file = null;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001122 FileInputStream inFile = null;
1123 try {
Jayachandran C645ec612020-01-10 10:30:25 -08001124 file = new File(mContext.getFilesDir(),fileName);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001125 inFile = new FileInputStream(file);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001126
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001127 restoredBundle = PersistableBundle.readFromStream(inFile);
1128 String savedVersion = restoredBundle.getString(KEY_VERSION);
1129 restoredBundle.remove(KEY_VERSION);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001130
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001131 if (!version.equals(savedVersion)) {
1132 loge("Saved version mismatch: " + version + " vs " + savedVersion);
1133 restoredBundle = null;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001134 }
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001135
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001136 inFile.close();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001137 } catch (FileNotFoundException e) {
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001138 // Missing file is normal occurrence that might occur with a new sim or when restoring
1139 // an override file during boot and should not be treated as an error.
arunvoddu664c36a2021-10-11 20:09:28 +00001140 if (file != null) {
1141 if (isNoSimConfig) {
1142 logd("File not found: " + file.getPath());
1143 } else {
1144 String filePath = file.getPath();
1145 filePath = getFilePathForLogging(filePath, iccid);
1146 logd("File not found : " + filePath);
1147 }
1148 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001149 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001150 loge(e.toString());
1151 }
1152
1153 return restoredBundle;
1154 }
1155
arunvoddu664c36a2021-10-11 20:09:28 +00001156 /**
1157 * This method will mask most part of iccid in the filepath for logging on userbuild
1158 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001159 @NonNull
1160 private String getFilePathForLogging(@Nullable String filePath, @Nullable String iccid) {
arunvoddu664c36a2021-10-11 20:09:28 +00001161 // If loggable then return with actual file path
1162 if (Rlog.isLoggable(LOG_TAG, Log.VERBOSE)) {
1163 return filePath;
1164 }
1165 String path = filePath;
1166 int length = (iccid != null) ? iccid.length() : 0;
1167 if (length > 5 && filePath != null) {
1168 path = filePath.replace(iccid.substring(5), "***************");
1169 }
1170 return path;
1171 }
1172
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001173 @Nullable
1174 private PersistableBundle restoreConfigFromXml(@Nullable String packageName,
1175 @NonNull String extraString, int phoneId) {
Jayachandran C645ec612020-01-10 10:30:25 -08001176 return restoreConfigFromXml(packageName, extraString, phoneId, false);
1177 }
1178
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001179 @Nullable
1180 private PersistableBundle restoreNoSimConfigFromXml(@Nullable String packageName) {
Jayachandran C645ec612020-01-10 10:30:25 -08001181 return restoreConfigFromXml(packageName, "", -1, true);
1182 }
1183
Junda Liu8a8a53a2015-05-15 16:19:57 -07001184 /**
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001185 * Clears cached carrier config.
1186 * This deletes all saved XML files associated with the given package name. If packageName is
1187 * null, then it deletes all saved XML files.
1188 *
1189 * @param packageName the name of a carrier package, or null if all cached config should be
1190 * cleared.
1191 * @return true iff one or more files were deleted.
Junda Liu8a8a53a2015-05-15 16:19:57 -07001192 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001193 private boolean clearCachedConfigForPackage(@Nullable final String packageName) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001194 File dir = mContext.getFilesDir();
1195 File[] packageFiles = dir.listFiles(new FilenameFilter() {
1196 public boolean accept(File dir, String filename) {
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001197 if (packageName != null) {
1198 return filename.startsWith("carrierconfig-" + packageName + "-");
1199 } else {
1200 return filename.startsWith("carrierconfig-");
1201 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001202 }
1203 });
Junda Liu8a8a53a2015-05-15 16:19:57 -07001204 if (packageFiles == null || packageFiles.length < 1) return false;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001205 for (File f : packageFiles) {
arunvoddub7c6e8e2022-09-05 15:48:06 +00001206 logd("Deleting " + getFilePathForLogging(f.getName()));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001207 f.delete();
1208 }
Junda Liu8a8a53a2015-05-15 16:19:57 -07001209 return true;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001210 }
1211
arunvoddub7c6e8e2022-09-05 15:48:06 +00001212 private String getFilePathForLogging(String filePath) {
1213 if (!TextUtils.isEmpty(filePath)) {
1214 String[] fileTokens = filePath.split("-");
1215 if (fileTokens != null && fileTokens.length > 2) {
1216 String iccid = fileTokens[fileTokens.length -2];
1217 return getFilePathForLogging(filePath, iccid);
1218 }
1219 return filePath;
1220 }
1221 return filePath;
1222 }
1223
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001224 /** Builds a canonical file name for a config file. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001225 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001226 private static String getFilenameForConfig(
1227 @NonNull String packageName, @NonNull String extraString,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001228 @NonNull String iccid, int cid) {
chen xu02581692018-11-11 19:03:44 -08001229 // the same carrier should have a single copy of XML file named after carrier id.
1230 // However, it's still possible that platform doesn't recognize the current sim carrier,
1231 // we will use iccid + carrierid as the canonical file name. carrierid can also handle the
1232 // cases SIM OTA resolves to different carrier while iccid remains the same.
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001233 return "carrierconfig-" + packageName + extraString + "-" + iccid + "-" + cid + ".xml";
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001234 }
1235
Jayachandran C645ec612020-01-10 10:30:25 -08001236 /** Builds a canonical file name for no SIM config file. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001237 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001238 private String getFilenameForNoSimConfig(@NonNull String packageName) {
1239 return "carrierconfig-" + packageName + "-" + "nosim" + ".xml";
1240 }
1241
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001242 /** Return the current version code of a package, or null if the name is not found. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001243 @Nullable
1244 private String getPackageVersion(@NonNull String packageName) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001245 try {
1246 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
Dianne Hackbornb76ab202017-11-28 17:44:50 -08001247 return Long.toString(info.getLongVersionCode());
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001248 } catch (PackageManager.NameNotFoundException e) {
1249 return null;
1250 }
1251 }
1252
Jonathan Basseri65273c82017-07-25 15:08:42 -07001253 /**
1254 * Read up to date config.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001255 *
1256 * This reads config bundles for the given phoneId. That means getting the latest bundle from
1257 * the default app and a privileged carrier app, if present. This will not bind to an app if we
1258 * have a saved config file to use instead.
1259 */
1260 private void updateConfigForPhoneId(int phoneId) {
Jonathan Basseri65273c82017-07-25 15:08:42 -07001261 mHandler.sendMessage(mHandler.obtainMessage(EVENT_DO_FETCH_DEFAULT, phoneId, -1));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001262 }
1263
Malcolm Chen5ea18532019-10-24 19:55:44 -07001264 private void onMultiSimConfigChanged() {
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001265 int oldNumPhones = mNumPhones;
1266 mNumPhones = TelephonyManager.from(mContext).getActiveModemCount();
1267 if (mNumPhones == oldNumPhones) {
1268 return;
1269 }
1270 logdWithLocalLog("mNumPhones change from " + oldNumPhones + " to " + mNumPhones);
1271
Rambo Wanga27fbe52022-04-12 19:09:07 +00001272 // If DS -> SS switch, release the resources BEFORE truncating the arrays to avoid leaking
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001273 for (int phoneId = mNumPhones; phoneId < oldNumPhones; phoneId++) {
1274 if (mServiceConnection[phoneId] != null) {
1275 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
1276 }
1277 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
1278 unbindIfBoundForNoSimConfig(mContext, mServiceConnectionForNoSimConfig[phoneId],
1279 phoneId);
1280 }
1281 }
1282
Rambo Wanga27fbe52022-04-12 19:09:07 +00001283 // The phone to slot mapping may change, unregister here and re-register callbacks later
1284 for (int phoneId = 0; phoneId < oldNumPhones; phoneId++) {
1285 if (mCarrierServiceChangeCallbacks[phoneId] != null) {
1286 TelephonyManager.from(mContext).unregisterCarrierPrivilegesCallback(
1287 mCarrierServiceChangeCallbacks[phoneId]);
1288 }
1289 }
1290
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001291 // Copy the original arrays, truncate or padding with zeros (if necessary) to new length
1292 mConfigFromDefaultApp = Arrays.copyOf(mConfigFromDefaultApp, mNumPhones);
1293 mConfigFromCarrierApp = Arrays.copyOf(mConfigFromCarrierApp, mNumPhones);
1294 mPersistentOverrideConfigs = Arrays.copyOf(mPersistentOverrideConfigs, mNumPhones);
1295 mOverrideConfigs = Arrays.copyOf(mOverrideConfigs, mNumPhones);
1296 mServiceConnection = Arrays.copyOf(mServiceConnection, mNumPhones);
1297 mServiceConnectionForNoSimConfig =
1298 Arrays.copyOf(mServiceConnectionForNoSimConfig, mNumPhones);
1299 mServiceBound = Arrays.copyOf(mServiceBound, mNumPhones);
1300 mServiceBoundForNoSimConfig = Arrays.copyOf(mServiceBoundForNoSimConfig, mNumPhones);
1301 mHasSentConfigChange = Arrays.copyOf(mHasSentConfigChange, mNumPhones);
1302 mFromSystemUnlocked = Arrays.copyOf(mFromSystemUnlocked, mNumPhones);
Rambo Wanga27fbe52022-04-12 19:09:07 +00001303 mCarrierServiceChangeCallbacks = Arrays.copyOf(mCarrierServiceChangeCallbacks, mNumPhones);
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001304
Rambo Wanga27fbe52022-04-12 19:09:07 +00001305 // Load the config for all the phones and re-register callback AFTER padding the arrays.
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001306 for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
1307 updateConfigForPhoneId(phoneId);
Rambo Wanga27fbe52022-04-12 19:09:07 +00001308 mCarrierServiceChangeCallbacks[phoneId] = new CarrierServiceChangeCallback(phoneId);
1309 TelephonyManager.from(mContext).registerCarrierPrivilegesCallback(phoneId,
1310 new HandlerExecutor(mHandler), mCarrierServiceChangeCallbacks[phoneId]);
Malcolm Chen5ea18532019-10-24 19:55:44 -07001311 }
1312 }
1313
Hall Liu506724b2018-10-22 18:16:14 -07001314 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001315 @NonNull
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001316 public PersistableBundle getConfigForSubId(int subscriptionId, @NonNull String callingPackage) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001317 return getConfigForSubIdWithFeature(subscriptionId, callingPackage, null);
Philip P. Moltmann9797cbb2020-01-07 13:45:00 -08001318 }
1319
1320 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001321 @NonNull
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001322 public PersistableBundle getConfigForSubIdWithFeature(int subscriptionId,
1323 @NonNull String callingPackage, @Nullable String callingFeatureId) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001324 if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(mContext, subscriptionId,
1325 callingPackage, callingFeatureId, "getCarrierConfig")) {
Rambo Wang42026112021-04-07 20:57:28 +00001326 return new PersistableBundle();
Amit Mahajan40b3fa52015-07-14 10:27:19 -07001327 }
Jeff Davidsona8e4e242018-03-15 17:16:18 -07001328
Rambo Wangd2b004b2021-03-30 10:10:23 -07001329 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001330 PersistableBundle retConfig = CarrierConfigManager.getDefaultConfig();
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001331 if (SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001332 PersistableBundle config = mConfigFromDefaultApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001333 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001334 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001335 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001336 config = mConfigFromCarrierApp[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 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001340 config = mPersistentOverrideConfigs[phoneId];
1341 if (config != null) {
1342 retConfig.putAll(config);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001343 }
Hall Liu506724b2018-10-22 18:16:14 -07001344 config = mOverrideConfigs[phoneId];
1345 if (config != null) {
1346 retConfig.putAll(config);
Hall Liu506724b2018-10-22 18:16:14 -07001347 }
Nathan Harold1122e3d2021-01-22 15:45:24 -08001348 // Ignore the theoretical case of the default app not being present since that won't
1349 // work in CarrierConfigLoader today.
1350 final boolean allConfigsApplied =
1351 (mConfigFromCarrierApp[phoneId] != null
1352 || getCarrierPackageForPhoneId(phoneId) == null)
1353 && mConfigFromDefaultApp[phoneId] != null;
1354 retConfig.putBoolean(
1355 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, allConfigsApplied);
Jayachandran C645ec612020-01-10 10:30:25 -08001356 } else {
1357 if (mNoSimConfig != null) {
1358 retConfig.putAll(mNoSimConfig);
1359 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001360 }
1361 return retConfig;
1362 }
1363
1364 @Override
rambowang14757c22022-10-03 11:54:56 -05001365 @NonNull
1366 public PersistableBundle getConfigSubsetForSubIdWithFeature(int subscriptionId,
1367 @NonNull String callingPackage, @Nullable String callingFeatureId,
1368 @NonNull String[] keys) {
1369 Objects.requireNonNull(callingPackage, "Calling package must be non-null");
1370 Objects.requireNonNull(keys, "Config keys must be non-null");
1371 enforceCallerIsSystemOrRequestingPackage(callingPackage);
1372
1373 // Permission check is performed inside and an empty bundle will return on failure.
1374 // No SecurityException thrown here since most clients expect to retrieve the overridden
1375 // value if present or use default one if not
1376 PersistableBundle allConfigs = getConfigForSubIdWithFeature(subscriptionId, callingPackage,
1377 callingFeatureId);
1378 if (allConfigs.isEmpty()) {
1379 return allConfigs;
1380 }
1381 for (String key : keys) {
1382 Objects.requireNonNull(key, "Config key must be non-null");
rambowang14757c22022-10-03 11:54:56 -05001383 }
1384
1385 PersistableBundle configSubset = new PersistableBundle(
1386 keys.length + CONFIG_SUBSET_METADATA_KEYS.length);
1387 for (String carrierConfigKey : keys) {
1388 Object value = allConfigs.get(carrierConfigKey);
rambowangb49e90f2022-12-13 18:29:06 -06001389 if (value == null) {
1390 // Filter out keys without values.
1391 // In history, many AOSP or OEMs/carriers private configs didn't provide default
1392 // values. We have to continue supporting them for now. See b/261776046 for details.
1393 continue;
1394 }
rambowang14757c22022-10-03 11:54:56 -05001395 // Config value itself could be PersistableBundle which requires different API to put
1396 if (value instanceof PersistableBundle) {
1397 configSubset.putPersistableBundle(carrierConfigKey, (PersistableBundle) value);
1398 } else {
1399 configSubset.putObject(carrierConfigKey, value);
1400 }
1401 }
1402
1403 // Configs in CONFIG_SUBSET_ALWAYS_INCLUDED_KEYS should always be included
1404 for (String generalKey : CONFIG_SUBSET_METADATA_KEYS) {
1405 configSubset.putObject(generalKey, allConfigs.get(generalKey));
1406 }
1407
1408 return configSubset;
1409 }
1410
1411 @Override
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001412 public void overrideConfig(int subscriptionId, @Nullable PersistableBundle overrides,
1413 boolean persistent) {
Hall Liu506724b2018-10-22 18:16:14 -07001414 mContext.enforceCallingOrSelfPermission(
1415 android.Manifest.permission.MODIFY_PHONE_STATE, null);
1416 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1417 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001418 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
Rambo Wangd2b004b2021-03-30 10:10:23 -07001419 throw new IllegalArgumentException(
1420 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
Hall Liu506724b2018-10-22 18:16:14 -07001421 }
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001422 // Post to run on handler thread on which all states should be confined.
1423 mHandler.post(() -> {
1424 overrideConfig(mOverrideConfigs, phoneId, overrides);
Hall Liu506724b2018-10-22 18:16:14 -07001425
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001426 if (persistent) {
1427 overrideConfig(mPersistentOverrideConfigs, phoneId, overrides);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001428
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001429 if (overrides != null) {
1430 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
1431 saveConfigToXml(mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION,
1432 phoneId,
1433 carrierId, mPersistentOverrideConfigs[phoneId]);
1434 } else {
1435 final String iccid = getIccIdForPhoneId(phoneId);
1436 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1437 String fileName = getFilenameForConfig(mPlatformCarrierConfigPackage,
1438 OVERRIDE_PACKAGE_ADDITION, iccid, cid);
1439 File fileToDelete = new File(mContext.getFilesDir(), fileName);
1440 fileToDelete.delete();
1441 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001442 }
Jack Yue37dd262022-12-16 11:53:37 -08001443 updateSubscriptionDatabase(phoneId);
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001444 });
Hall Liu506724b2018-10-22 18:16:14 -07001445 }
1446
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001447 private void overrideConfig(@NonNull PersistableBundle[] currentOverrides, int phoneId,
1448 @Nullable PersistableBundle overrides) {
1449 if (overrides == null) {
Rambo Wang42026112021-04-07 20:57:28 +00001450 currentOverrides[phoneId] = new PersistableBundle();
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001451 } else if (currentOverrides[phoneId] == null) {
1452 currentOverrides[phoneId] = overrides;
1453 } else {
1454 currentOverrides[phoneId].putAll(overrides);
1455 }
1456 }
1457
Hall Liu506724b2018-10-22 18:16:14 -07001458 @Override
Rambo Wangd2b004b2021-03-30 10:10:23 -07001459 public void notifyConfigChangedForSubId(int subscriptionId) {
Jordan Liud7d57fe2019-04-16 12:29:43 -07001460 // Requires the calling app to be either a carrier privileged app for this subId or
Junda Liufbd2bcb2016-06-15 11:15:42 -07001461 // system privileged app with MODIFY_PHONE_STATE permission.
Rambo Wangd2b004b2021-03-30 10:10:23 -07001462 TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(mContext,
1463 subscriptionId, "Require carrier privileges or MODIFY_PHONE_STATE permission.");
1464
1465 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1466 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
1467 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
1468 throw new IllegalArgumentException(
1469 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
1470 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001471
1472 // This method should block until deleting has completed, so that an error which prevents us
1473 // from clearing the cache is passed back to the carrier app. With the files successfully
1474 // deleted, this can return and we will eventually bind to the carrier app.
Jordan Liud7d57fe2019-04-16 12:29:43 -07001475 String callingPackageName = mContext.getPackageManager().getNameForUid(
1476 Binder.getCallingUid());
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001477 clearCachedConfigForPackage(callingPackageName);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001478 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001479 }
1480
1481 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001482 public void updateConfigForPhoneId(int phoneId, @NonNull String simState) {
Junda Liu1f2b34d2015-06-18 15:26:56 -07001483 mContext.enforceCallingOrSelfPermission(
1484 android.Manifest.permission.MODIFY_PHONE_STATE, null);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001485 logdWithLocalLog("Update config for phoneId: " + phoneId + " simState: " + simState);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001486 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001487 throw new IllegalArgumentException("Invalid phoneId: " + phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001488 }
1489 // requires Java 7 for switch on string.
1490 switch (simState) {
1491 case IccCardConstants.INTENT_VALUE_ICC_ABSENT:
1492 case IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR:
Junda Liu6f5fddf2016-05-24 16:14:41 -07001493 case IccCardConstants.INTENT_VALUE_ICC_CARD_RESTRICTED:
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001494 case IccCardConstants.INTENT_VALUE_ICC_UNKNOWN:
Malcolm Chendb66de12019-12-09 18:57:07 -08001495 case IccCardConstants.INTENT_VALUE_ICC_NOT_READY:
Junda Liu9f2d2712015-05-15 14:22:45 -07001496 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CLEAR_CONFIG, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001497 break;
1498 case IccCardConstants.INTENT_VALUE_ICC_LOADED:
1499 case IccCardConstants.INTENT_VALUE_ICC_LOCKED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001500 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001501 break;
1502 }
1503 }
1504
Junda Liu43d723a2015-05-12 17:23:45 -07001505 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001506 @NonNull
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001507 public String getDefaultCarrierServicePackageName() {
Shuo Qianefdb7962019-12-19 15:54:27 -08001508 mContext.enforceCallingOrSelfPermission(
1509 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
1510 "getDefaultCarrierServicePackageName");
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001511 return mPlatformCarrierConfigPackage;
1512 }
1513
Rambo Wang7e3bc122021-03-23 09:24:38 -07001514 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001515 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -07001516 /* package */ Handler getHandler() {
1517 return mHandler;
1518 }
1519
1520 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001521 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001522 /* package */ PersistableBundle getConfigFromDefaultApp(int phoneId) {
1523 return mConfigFromDefaultApp[phoneId];
1524 }
1525
1526 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001527 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001528 /* package */ PersistableBundle getConfigFromCarrierApp(int phoneId) {
1529 return mConfigFromCarrierApp[phoneId];
1530 }
1531
1532 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001533 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -07001534 /* package */ PersistableBundle getNoSimConfig() {
1535 return mNoSimConfig;
1536 }
1537
1538 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001539 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001540 /* package */ PersistableBundle getOverrideConfig(int phoneId) {
1541 return mOverrideConfigs[phoneId];
1542 }
1543
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001544 // TODO(b/185129900): always call unbindService after bind, no matter if it succeeded
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001545 private void unbindIfBound(@NonNull Context context, @NonNull CarrierServiceConnection conn,
Rambo Wangb0f3e2f2021-10-28 12:40:12 -07001546 int phoneId) {
1547 if (mServiceBound[phoneId]) {
1548 mServiceBound[phoneId] = false;
1549 context.unbindService(conn);
1550 }
1551 }
1552
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001553 private void unbindIfBoundForNoSimConfig(@NonNull Context context,
1554 @NonNull CarrierServiceConnection conn, int phoneId) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -07001555 if (mServiceBoundForNoSimConfig[phoneId]) {
1556 mServiceBoundForNoSimConfig[phoneId] = false;
Jayachandran C645ec612020-01-10 10:30:25 -08001557 context.unbindService(conn);
1558 }
1559 }
1560
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001561 /**
Rambo Wang610fdf62021-03-08 21:37:11 -08001562 * Returns a boxed Integer object for phoneId, services as message token to distinguish messages
1563 * with same code when calling {@link Handler#removeMessages(int, Object)}.
1564 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001565 @NonNull
Rambo Wang610fdf62021-03-08 21:37:11 -08001566 private Integer getMessageToken(int phoneId) {
1567 if (phoneId < -128 || phoneId > 127) {
1568 throw new IllegalArgumentException("phoneId should be in range [-128, 127], inclusive");
1569 }
1570 // Integer#valueOf guarantees the integers within [-128, 127] are cached and thus memory
1571 // comparison (==) returns true for the same integer.
1572 return Integer.valueOf(phoneId);
1573 }
1574
1575 /**
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001576 * If {@code args} contains {@link #DUMP_ARG_REQUESTING_PACKAGE} and a following package name,
1577 * we'll also call {@link IBinder#dump} on the default carrier service (if bound) and the
1578 * specified carrier service (if bound). Typically, this is done for connectivity bug reports
1579 * where we don't call {@code dumpsys activity service all-non-platform} because that contains
1580 * too much info, but we still want to let carrier apps include their diagnostics.
1581 */
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001582 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001583 public void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter pw, @NonNull String[] args) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001584 IndentingPrintWriter indentPW = new IndentingPrintWriter(pw, " ");
Junda Liu43d723a2015-05-12 17:23:45 -07001585 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1586 != PackageManager.PERMISSION_GRANTED) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001587 indentPW.println("Permission Denial: can't dump carrierconfig from from pid="
Junda Liu43d723a2015-05-12 17:23:45 -07001588 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
1589 return;
1590 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001591 String requestingPackage = null;
1592 int requestingPackageIndex = ArrayUtils.indexOf(args, DUMP_ARG_REQUESTING_PACKAGE);
1593 if (requestingPackageIndex >= 0 && requestingPackageIndex < args.length - 1
1594 && !TextUtils.isEmpty(args[requestingPackageIndex + 1])) {
1595 requestingPackage = args[requestingPackageIndex + 1];
1596 // Throws a SecurityException if the caller is impersonating another app in an effort to
1597 // dump extra info (which may contain PII the caller doesn't have a right to).
1598 enforceCallerIsSystemOrRequestingPackage(requestingPackage);
1599 }
1600
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001601 indentPW.println("CarrierConfigLoader: " + this);
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001602 for (int i = 0; i < mNumPhones; i++) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001603 indentPW.println("Phone Id = " + i);
shuoq26a3a4c2016-12-16 11:06:48 -08001604 // display default values in CarrierConfigManager
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001605 printConfig(CarrierConfigManager.getDefaultConfig(), indentPW,
shuoq26a3a4c2016-12-16 11:06:48 -08001606 "Default Values from CarrierConfigManager");
shuoq26a3a4c2016-12-16 11:06:48 -08001607 // display ConfigFromDefaultApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001608 printConfig(mConfigFromDefaultApp[i], indentPW, "mConfigFromDefaultApp");
shuoq26a3a4c2016-12-16 11:06:48 -08001609 // display ConfigFromCarrierApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001610 printConfig(mConfigFromCarrierApp[i], indentPW, "mConfigFromCarrierApp");
1611 printConfig(mPersistentOverrideConfigs[i], indentPW, "mPersistentOverrideConfigs");
1612 printConfig(mOverrideConfigs[i], indentPW, "mOverrideConfigs");
shuoq26a3a4c2016-12-16 11:06:48 -08001613 }
chen xudb04c292019-03-26 17:01:15 -07001614
Jayachandran C645ec612020-01-10 10:30:25 -08001615 printConfig(mNoSimConfig, indentPW, "mNoSimConfig");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001616 indentPW.println("CarrierConfigLoadingLog=");
1617 mCarrierConfigLoadingLog.dump(fd, indentPW, args);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001618
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001619 if (requestingPackage != null) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001620 logd("Including default and requesting package " + requestingPackage
1621 + " carrier services in dump");
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001622 indentPW.println("");
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001623 indentPW.println("Connected services");
1624 dumpCarrierServiceIfBound(fd, indentPW, "Default config package",
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001625 mPlatformCarrierConfigPackage, false /* considerCarrierPrivileges */);
1626 dumpCarrierServiceIfBound(fd, indentPW, "Requesting package", requestingPackage,
1627 true /* considerCarrierPrivileges */);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001628 }
shuoq26a3a4c2016-12-16 11:06:48 -08001629 }
1630
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001631 private void printConfig(@NonNull PersistableBundle configApp,
1632 @NonNull IndentingPrintWriter indentPW, @NonNull String name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001633 indentPW.increaseIndent();
shuoq26a3a4c2016-12-16 11:06:48 -08001634 if (configApp == null) {
shuoq26a3a4c2016-12-16 11:06:48 -08001635 indentPW.println(name + " : null ");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001636 indentPW.decreaseIndent();
1637 indentPW.println("");
shuoq26a3a4c2016-12-16 11:06:48 -08001638 return;
1639 }
shuoq26a3a4c2016-12-16 11:06:48 -08001640 indentPW.println(name + " : ");
1641 List<String> sortedKeys = new ArrayList<String>(configApp.keySet());
1642 Collections.sort(sortedKeys);
1643 indentPW.increaseIndent();
1644 indentPW.increaseIndent();
1645 for (String key : sortedKeys) {
1646 if (configApp.get(key) != null && configApp.get(key) instanceof Object[]) {
1647 indentPW.println(key + " = " +
1648 Arrays.toString((Object[]) configApp.get(key)));
1649 } else if (configApp.get(key) != null && configApp.get(key) instanceof int[]) {
1650 indentPW.println(key + " = " + Arrays.toString((int[]) configApp.get(key)));
1651 } else {
1652 indentPW.println(key + " = " + configApp.get(key));
1653 }
Junda Liu43d723a2015-05-12 17:23:45 -07001654 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001655 indentPW.decreaseIndent();
1656 indentPW.decreaseIndent();
1657 indentPW.decreaseIndent();
1658 indentPW.println("");
Junda Liu43d723a2015-05-12 17:23:45 -07001659 }
1660
Hunter Knepshielde601f432020-02-19 10:16:04 -08001661 /**
1662 * Passes without problem when one of these conditions is true:
1663 * - The caller is a privileged UID (e.g. for dumpstate.cpp generating a bug report, where the
1664 * system knows the true caller plumbed in through the {@link android.os.BugreportManager} API).
1665 * - The caller's UID matches the supplied package.
1666 *
1667 * @throws SecurityException if none of the above conditions are met.
1668 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001669 private void enforceCallerIsSystemOrRequestingPackage(@NonNull String requestingPackage)
Hunter Knepshielde601f432020-02-19 10:16:04 -08001670 throws SecurityException {
1671 final int callingUid = Binder.getCallingUid();
1672 if (callingUid == Process.ROOT_UID || callingUid == Process.SYSTEM_UID
1673 || callingUid == Process.SHELL_UID || callingUid == Process.PHONE_UID) {
1674 // Bug reports (dumpstate.cpp) run as SHELL, and let some other privileged UIDs through
1675 // as well.
1676 return;
1677 }
1678 // An app is trying to dump extra detail, block it if they aren't who they claim to be.
1679 AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
1680 if (appOps == null) {
1681 throw new SecurityException("No AppOps");
1682 }
1683 // Will throw a SecurityException if the UID and package don't match.
1684 appOps.checkPackage(callingUid, requestingPackage);
1685 }
1686
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001687 /**
1688 * Searches for one or more appropriate {@link CarrierService} instances to dump based on the
1689 * current connections.
1690 *
1691 * @param targetPkgName the target package name to dump carrier services for
1692 * @param considerCarrierPrivileges if true, allow a carrier service to be dumped if it shares
1693 * carrier privileges with {@code targetPkgName};
1694 * otherwise, only dump a carrier service if it is {@code
1695 * targetPkgName}
1696 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001697 private void dumpCarrierServiceIfBound(@NonNull FileDescriptor fd,
1698 @NonNull IndentingPrintWriter indentPW, @NonNull String prefix,
1699 @NonNull String targetPkgName, boolean considerCarrierPrivileges) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001700 // Null package is possible if it's early in the boot process, there was a recent crash, we
1701 // loaded the config from XML most recently, or a SIM slot is empty. Carrier apps with
1702 // long-lived bindings should typically get dumped here regardless. Even if an app is being
1703 // used for multiple phoneIds, we assume that it's smart enough to handle that on its own,
1704 // and that in most cases we'd just be dumping duplicate information and bloating a report.
1705 indentPW.increaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001706 indentPW.println(prefix + " : " + targetPkgName);
1707 Set<String> dumpedPkgNames = new ArraySet<>(mServiceConnection.length);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001708 for (CarrierServiceConnection connection : mServiceConnection) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001709 if (connection == null || !SubscriptionManager.isValidPhoneId(connection.phoneId)
1710 || TextUtils.isEmpty(connection.pkgName)) {
1711 continue;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001712 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001713 final String servicePkgName = connection.pkgName;
1714 // Note: we intentionally ignore system components here because we should NOT match the
1715 // shell caller that's typically used for bug reports via non-BugreportManager triggers.
1716 final boolean exactPackageMatch = TextUtils.equals(targetPkgName, servicePkgName);
1717 final boolean carrierPrivilegesMatch =
1718 considerCarrierPrivileges && hasCarrierPrivileges(targetPkgName,
1719 connection.phoneId);
1720 if (!exactPackageMatch && !carrierPrivilegesMatch) continue;
1721 // Make sure this service is actually alive before trying to dump it. We don't pay
1722 // attention to mServiceBound[connection.phoneId] because typically carrier apps will
1723 // request long-lived bindings, and even if we unbind the app, it may still be alive due
1724 // to CarrierServiceBindHelper. Pull it out as a reference so even if it gets set to
1725 // null within the ServiceConnection during unbinding we can avoid an NPE.
1726 final IBinder service = connection.service;
1727 if (service == null || !service.isBinderAlive() || !service.pingBinder()) continue;
1728 // We've got a live service. Last check is just to make sure we don't dump a package
1729 // multiple times.
1730 if (!dumpedPkgNames.add(servicePkgName)) continue;
1731 if (!exactPackageMatch) {
1732 logd(targetPkgName + " has carrier privileges on phoneId " + connection.phoneId
1733 + ", service provided by " + servicePkgName);
1734 indentPW.increaseIndent();
1735 indentPW.println("Proxy : " + servicePkgName);
1736 indentPW.decreaseIndent();
1737 }
1738 // Flush before we let the app output anything to ensure correct ordering of output.
1739 // Internally, Binder#dump calls flush on its printer after finishing so we don't
1740 // need to do anything after.
1741 indentPW.flush();
1742 try {
1743 logd("Dumping " + servicePkgName);
1744 // We don't need to give the carrier service any args.
1745 connection.service.dump(fd, null /* args */);
1746 logd("Done with " + servicePkgName);
1747 } catch (RemoteException e) {
1748 logd("RemoteException from " + servicePkgName, e);
1749 indentPW.increaseIndent();
1750 indentPW.println("RemoteException");
1751 indentPW.increaseIndent();
1752 e.printStackTrace(indentPW);
1753 indentPW.decreaseIndent();
1754 indentPW.decreaseIndent();
1755 // We won't retry this package again because now it's in dumpedPkgNames.
1756 }
1757 indentPW.println("");
Jordan Liu46ed5db2020-01-28 08:55:20 -08001758 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001759 if (dumpedPkgNames.isEmpty()) {
1760 indentPW.increaseIndent();
1761 indentPW.println("Not bound");
1762 indentPW.decreaseIndent();
1763 indentPW.println("");
1764 }
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001765 indentPW.decreaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001766 }
1767
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001768 private boolean hasCarrierPrivileges(@NonNull String pkgName, int phoneId) {
Jack Yu00ece8c2022-11-19 22:29:12 -08001769 int subId = SubscriptionManager.getSubscriptionId(phoneId);
1770 if (!SubscriptionManager.isValidSubscriptionId(subId)) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001771 return false;
1772 }
Jack Yu00ece8c2022-11-19 22:29:12 -08001773 return TelephonyManager.from(mContext).createForSubscriptionId(subId)
1774 .checkCarrierPrivilegesForPackage(pkgName)
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001775 == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001776 }
1777
Zach Johnson36d7aab2015-05-22 15:43:00 -07001778 private class CarrierServiceConnection implements ServiceConnection {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001779 final int phoneId;
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001780 @NonNull final String pkgName;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001781 final int eventId;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001782 IBinder service;
1783
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001784 CarrierServiceConnection(int phoneId, @NonNull String pkgName, int eventId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001785 this.phoneId = phoneId;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001786 this.pkgName = pkgName;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001787 this.eventId = eventId;
1788 }
1789
1790 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001791 public void onServiceConnected(@NonNull ComponentName name, @NonNull IBinder service) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001792 logd("Connected to config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001793 this.service = service;
1794 mHandler.sendMessage(mHandler.obtainMessage(eventId, phoneId, -1, this));
1795 }
1796
1797 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001798 public void onServiceDisconnected(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001799 logd("Disconnected from config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001800 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001801 }
1802
1803 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001804 public void onBindingDied(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001805 logd("Binding died from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001806 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001807 }
1808
1809 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001810 public void onNullBinding(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001811 logd("Null binding from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001812 this.service = null;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001813 }
1814 }
1815
1816 private class ConfigLoaderBroadcastReceiver extends BroadcastReceiver {
1817 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001818 public void onReceive(@NonNull Context context, @NonNull Intent intent) {
Rambo Wanga27fbe52022-04-12 19:09:07 +00001819 switch (intent.getAction()) {
Nanxi Chen3d670502016-03-17 16:32:09 -07001820 case Intent.ACTION_BOOT_COMPLETED:
1821 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_UNLOCKED, null));
1822 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001823 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001824 }
1825 }
1826
Rambo Wanga27fbe52022-04-12 19:09:07 +00001827 private class CarrierServiceChangeCallback implements
1828 TelephonyManager.CarrierPrivilegesCallback {
1829 final int mPhoneId;
1830 // CarrierPrivilegesCallback will be triggered upon registration. Filter the first callback
1831 // here since we really care of the *change* of carrier service instead of the content
1832 private boolean mHasSentServiceChangeCallback;
1833
1834 CarrierServiceChangeCallback(int phoneId) {
1835 this.mPhoneId = phoneId;
1836 this.mHasSentServiceChangeCallback = false;
1837 }
1838
1839 @Override
1840 public void onCarrierPrivilegesChanged(
1841 @androidx.annotation.NonNull Set<String> privilegedPackageNames,
1842 @androidx.annotation.NonNull Set<Integer> privilegedUids) {
1843 // Ignored, not interested here
1844 }
1845
1846 @Override
1847 public void onCarrierServiceChanged(
1848 @androidx.annotation.Nullable String carrierServicePackageName,
1849 int carrierServiceUid) {
1850 // Ignore the first callback which is triggered upon registration
1851 if (!mHasSentServiceChangeCallback) {
1852 mHasSentServiceChangeCallback = true;
1853 return;
1854 }
1855 mHandler.sendMessage(
1856 mHandler.obtainMessage(EVENT_PACKAGE_CHANGED, mPhoneId, -1,
1857 carrierServicePackageName));
1858 }
1859 }
1860
Rambo Wangab13e3e2021-04-08 15:01:06 -07001861 // Get readable string for the message code supported in this class.
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001862 @NonNull
Rambo Wangab13e3e2021-04-08 15:01:06 -07001863 private static String eventToString(int code) {
1864 switch (code) {
1865 case EVENT_CLEAR_CONFIG:
1866 return "EVENT_CLEAR_CONFIG";
1867 case EVENT_CONNECTED_TO_DEFAULT:
1868 return "EVENT_CONNECTED_TO_DEFAULT";
1869 case EVENT_CONNECTED_TO_CARRIER:
1870 return "EVENT_CONNECTED_TO_CARRIER";
1871 case EVENT_FETCH_DEFAULT_DONE:
1872 return "EVENT_FETCH_DEFAULT_DONE";
1873 case EVENT_FETCH_CARRIER_DONE:
1874 return "EVENT_FETCH_CARRIER_DONE";
1875 case EVENT_DO_FETCH_DEFAULT:
1876 return "EVENT_DO_FETCH_DEFAULT";
1877 case EVENT_DO_FETCH_CARRIER:
1878 return "EVENT_DO_FETCH_CARRIER";
1879 case EVENT_PACKAGE_CHANGED:
1880 return "EVENT_PACKAGE_CHANGED";
1881 case EVENT_BIND_DEFAULT_TIMEOUT:
1882 return "EVENT_BIND_DEFAULT_TIMEOUT";
1883 case EVENT_BIND_CARRIER_TIMEOUT:
1884 return "EVENT_BIND_CARRIER_TIMEOUT";
1885 case EVENT_CHECK_SYSTEM_UPDATE:
1886 return "EVENT_CHECK_SYSTEM_UPDATE";
1887 case EVENT_SYSTEM_UNLOCKED:
1888 return "EVENT_SYSTEM_UNLOCKED";
1889 case EVENT_FETCH_DEFAULT_TIMEOUT:
1890 return "EVENT_FETCH_DEFAULT_TIMEOUT";
1891 case EVENT_FETCH_CARRIER_TIMEOUT:
1892 return "EVENT_FETCH_CARRIER_TIMEOUT";
1893 case EVENT_SUBSCRIPTION_INFO_UPDATED:
1894 return "EVENT_SUBSCRIPTION_INFO_UPDATED";
1895 case EVENT_MULTI_SIM_CONFIG_CHANGED:
1896 return "EVENT_MULTI_SIM_CONFIG_CHANGED";
1897 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG:
1898 return "EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG";
1899 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE:
1900 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE";
1901 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG:
1902 return "EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG";
1903 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1904 return "EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1905 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1906 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1907 default:
1908 return "UNKNOWN(" + code + ")";
1909 }
1910 }
1911
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001912 private void logd(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001913 Log.d(LOG_TAG, msg);
1914 }
1915
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001916 private void logd(@NonNull String msg, Throwable tr) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001917 Log.d(LOG_TAG, msg, tr);
1918 }
1919
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001920 private void logdWithLocalLog(@NonNull String msg) {
chen xudb04c292019-03-26 17:01:15 -07001921 Log.d(LOG_TAG, msg);
1922 mCarrierConfigLoadingLog.log(msg);
1923 }
1924
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001925 private void loge(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001926 Log.e(LOG_TAG, msg);
chen xudb04c292019-03-26 17:01:15 -07001927 mCarrierConfigLoadingLog.log(msg);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001928 }
1929}