blob: 9d11dfc0ca93489536f85b47c0af08c394d1484a [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;
Nathan Harold48ac0972019-03-13 22:33:01 -070067import com.android.internal.telephony.SubscriptionInfoUpdater;
Jeff Davidsona8e4e242018-03-15 17:16:18 -070068import com.android.internal.telephony.TelephonyPermissions;
Jack Yue37dd262022-12-16 11:53:37 -080069import com.android.internal.telephony.subscription.SubscriptionManagerService;
Meng Wanga320b942019-11-25 11:21:26 -080070import com.android.internal.telephony.util.ArrayUtils;
shuoq26a3a4c2016-12-16 11:06:48 -080071import com.android.internal.util.IndentingPrintWriter;
arunvoddu664c36a2021-10-11 20:09:28 +000072import com.android.telephony.Rlog;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080073
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070074import java.io.File;
Junda Liu43d723a2015-05-12 17:23:45 -070075import java.io.FileDescriptor;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070076import java.io.FileInputStream;
77import java.io.FileNotFoundException;
78import java.io.FileOutputStream;
Jonathan Basseri1f743c92015-05-15 00:19:46 -070079import java.io.FilenameFilter;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070080import java.io.IOException;
Junda Liu43d723a2015-05-12 17:23:45 -070081import java.io.PrintWriter;
shuoq26a3a4c2016-12-16 11:06:48 -080082import java.util.ArrayList;
83import java.util.Arrays;
84import java.util.Collections;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080085import java.util.List;
rambowang14757c22022-10-03 11:54:56 -050086import java.util.Objects;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -080087import java.util.Set;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080088
89/**
90 * CarrierConfigLoader binds to privileged carrier apps to fetch carrier config overlays.
Jonathan Basseri6465afd2015-02-25 13:05:57 -080091 */
Jonathan Basseri6465afd2015-02-25 13:05:57 -080092public class CarrierConfigLoader extends ICarrierConfigLoader.Stub {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070093 private static final String LOG_TAG = "CarrierConfigLoader";
Meng Wang33ad2bc2017-03-16 20:21:20 -070094
95 // Package name for platform carrier config app, bundled with system image.
Rambo Wangfe0d7c12022-04-15 03:00:32 +000096 @NonNull private final String mPlatformCarrierConfigPackage;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080097
98 /** The singleton instance. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +000099 @Nullable private static CarrierConfigLoader sInstance;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800100 // The context for phone app, passed from PhoneGlobals.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000101 @NonNull private Context mContext;
102
103 // All the states below (array indexed by phoneId) are non-null. But the member of the array
104 // is nullable, when e.g. the config for the phone is not loaded yet
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800105 // Carrier configs from default app, indexed by phoneID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000106 @NonNull private PersistableBundle[] mConfigFromDefaultApp;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800107 // Carrier configs from privileged carrier config app, indexed by phoneID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000108 @NonNull private PersistableBundle[] mConfigFromCarrierApp;
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100109 // Persistent Carrier configs that are provided via the override test API, indexed by phone ID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000110 @NonNull private PersistableBundle[] mPersistentOverrideConfigs;
Hall Liu506724b2018-10-22 18:16:14 -0700111 // Carrier configs that are provided via the override test API, indexed by phone ID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000112 @NonNull private PersistableBundle[] mOverrideConfigs;
Jayachandran C645ec612020-01-10 10:30:25 -0800113 // Carrier configs to override code default when there is no SIM inserted
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000114 @NonNull private PersistableBundle mNoSimConfig;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800115 // Service connection for binding to config app.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000116 @NonNull private CarrierServiceConnection[] mServiceConnection;
Jayachandran C645ec612020-01-10 10:30:25 -0800117 // Service connection for binding to carrier config app for no SIM config.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000118 @NonNull private CarrierServiceConnection[] mServiceConnectionForNoSimConfig;
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700119 // Whether we are bound to a service for each phone
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000120 @NonNull private boolean[] mServiceBound;
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700121 // Whether we are bound to a service for no SIM config
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000122 @NonNull private boolean[] mServiceBoundForNoSimConfig;
Sarah Chin807d5c62020-03-30 17:21:09 -0700123 // Whether we have sent config change broadcast for each phone id.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000124 @NonNull private boolean[] mHasSentConfigChange;
Sarah Chin807d5c62020-03-30 17:21:09 -0700125 // Whether the broadcast was sent from EVENT_SYSTEM_UNLOCKED, to track rebroadcasts
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000126 @NonNull private boolean[] mFromSystemUnlocked;
Rambo Wanga27fbe52022-04-12 19:09:07 +0000127 // CarrierService change monitoring
128 @NonNull private CarrierServiceChangeCallback[] mCarrierServiceChangeCallbacks;
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000129
Nathan Harold48ac0972019-03-13 22:33:01 -0700130 // SubscriptionInfoUpdater
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000131 @NonNull private final SubscriptionInfoUpdater mSubscriptionInfoUpdater;
Jack Yu771c6ce2023-02-02 17:51:42 -0800132 // Broadcast receiver for system events
Rambo Wanga27fbe52022-04-12 19:09:07 +0000133 @NonNull
134 private final BroadcastReceiver mSystemBroadcastReceiver = new ConfigLoaderBroadcastReceiver();
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000135 @NonNull private final LocalLog mCarrierConfigLoadingLog = new LocalLog(100);
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000136 // Number of phone instances (active modem count)
137 private int mNumPhones;
chen xudb04c292019-03-26 17:01:15 -0700138
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800139
140 // Message codes; see mHandler below.
141 // Request from SubscriptionInfoUpdater when SIM becomes absent or error.
142 private static final int EVENT_CLEAR_CONFIG = 0;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800143 // Has connected to default app.
144 private static final int EVENT_CONNECTED_TO_DEFAULT = 3;
145 // Has connected to carrier app.
146 private static final int EVENT_CONNECTED_TO_CARRIER = 4;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700147 // Config has been loaded from default app (or cache).
148 private static final int EVENT_FETCH_DEFAULT_DONE = 5;
149 // Config has been loaded from carrier app (or cache).
150 private static final int EVENT_FETCH_CARRIER_DONE = 6;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700151 // Attempt to fetch from default app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700152 private static final int EVENT_DO_FETCH_DEFAULT = 7;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700153 // Attempt to fetch from carrier app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700154 private static final int EVENT_DO_FETCH_CARRIER = 8;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700155 // A package has been installed, uninstalled, or updated.
156 private static final int EVENT_PACKAGE_CHANGED = 9;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700157 // Bind timed out for the default app.
158 private static final int EVENT_BIND_DEFAULT_TIMEOUT = 10;
159 // Bind timed out for a carrier app.
160 private static final int EVENT_BIND_CARRIER_TIMEOUT = 11;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700161 // Check if the system fingerprint has changed.
162 private static final int EVENT_CHECK_SYSTEM_UPDATE = 12;
Nanxi Chen3d670502016-03-17 16:32:09 -0700163 // Rerun carrier config binding after system is unlocked.
164 private static final int EVENT_SYSTEM_UNLOCKED = 13;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700165 // Fetching config timed out from the default app.
166 private static final int EVENT_FETCH_DEFAULT_TIMEOUT = 14;
167 // Fetching config timed out from a carrier app.
168 private static final int EVENT_FETCH_CARRIER_TIMEOUT = 15;
Nathan Harold48ac0972019-03-13 22:33:01 -0700169 // SubscriptionInfoUpdater has finished updating the sub for the carrier config.
170 private static final int EVENT_SUBSCRIPTION_INFO_UPDATED = 16;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700171 // Multi-SIM config changed.
172 private static final int EVENT_MULTI_SIM_CONFIG_CHANGED = 17;
Jayachandran C645ec612020-01-10 10:30:25 -0800173 // Attempt to fetch from default app or read from XML for no SIM case.
174 private static final int EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG = 18;
175 // No SIM config has been loaded from default app (or cache).
176 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE = 19;
177 // Has connected to default app for no SIM config.
178 private static final int EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG = 20;
179 // Bind timed out for the default app when trying to fetch no SIM config.
180 private static final int EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 21;
181 // Fetching config timed out from the default app for no SIM config.
182 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 22;
Rambo Wangab13e3e2021-04-08 15:01:06 -0700183 // NOTE: any new EVENT_* values must be added to method eventToString().
Jonathan Basseri930701e2015-06-11 20:56:43 -0700184
Junda Liu6cb45002016-03-22 17:18:20 -0700185 private static final int BIND_TIMEOUT_MILLIS = 30000;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800186
Meng Wang0f6b2ea2020-01-06 18:31:16 -0800187 // Keys used for saving and restoring config bundle from file.
188 private static final String KEY_VERSION = "__carrier_config_package_version__";
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800189
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100190 private static final String OVERRIDE_PACKAGE_ADDITION = "-override";
191
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700192 // SharedPreferences key for last known build fingerprint.
193 private static final String KEY_FINGERPRINT = "build_fingerprint";
194
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -0800195 // Argument for #dump that indicates we should also call the default and specified carrier
196 // service's #dump method. In multi-SIM devices, it's possible that carrier A is on SIM 1 and
197 // carrier B is on SIM 2, in which case we should not dump carrier B's service when carrier A
198 // requested the dump.
199 private static final String DUMP_ARG_REQUESTING_PACKAGE = "--requesting-package";
200
rambowang14757c22022-10-03 11:54:56 -0500201 // Configs that should always be included when clients calls getConfig[ForSubId] with specified
202 // keys (even configs are not explicitly specified). Those configs have special purpose for the
203 // carrier config APIs to work correctly.
204 private static final String[] CONFIG_SUBSET_METADATA_KEYS = new String[] {
205 CarrierConfigManager.KEY_CARRIER_CONFIG_VERSION_STRING,
206 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL
207 };
208
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800209 // Handler to process various events.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700210 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700211 // For each phoneId, the event sequence should be:
Jonathan Basseri65273c82017-07-25 15:08:42 -0700212 // fetch default, connected to default, fetch default (async), fetch default done,
213 // fetch carrier, connected to carrier, fetch carrier (async), fetch carrier done.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700214 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700215 // If there is a saved config file for either the default app or the carrier app, we skip
216 // binding to the app and go straight from fetch to loaded.
217 //
218 // At any time, at most one connection is active. If events are not in this order, previous
219 // connection will be unbound, so only latest event takes effect.
220 //
221 // We broadcast ACTION_CARRIER_CONFIG_CHANGED after:
222 // 1. loading from carrier app (even if read from a file)
223 // 2. loading from default app if there is no carrier app (even if read from a file)
224 // 3. clearing config (e.g. due to sim removal)
225 // 4. encountering bind or IPC error
Jonathan Basseri65273c82017-07-25 15:08:42 -0700226 private class ConfigHandler extends Handler {
Rambo Wang7e3bc122021-03-23 09:24:38 -0700227 ConfigHandler(@NonNull Looper looper) {
228 super(looper);
229 }
230
Jonathan Basseri65273c82017-07-25 15:08:42 -0700231 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000232 public void handleMessage(@NonNull Message msg) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700233 final int phoneId = msg.arg1;
Rambo Wangab13e3e2021-04-08 15:01:06 -0700234 logdWithLocalLog("mHandler: " + eventToString(msg.what) + " phoneId: " + phoneId);
Malcolm Chen5ea18532019-10-24 19:55:44 -0700235 if (!SubscriptionManager.isValidPhoneId(phoneId)
236 && msg.what != EVENT_MULTI_SIM_CONFIG_CHANGED) {
237 return;
238 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800239 switch (msg.what) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800240 case EVENT_CLEAR_CONFIG: {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700241 clearConfigForPhone(phoneId, true);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800242 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700243 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700244
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800245 case EVENT_SYSTEM_UNLOCKED: {
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000246 for (int i = 0; i < mNumPhones; ++i) {
Sarah Chin807d5c62020-03-30 17:21:09 -0700247 // When the user unlocks the device, send the broadcast again (with a
248 // rebroadcast extra) if we have sent it before unlock. This will avoid
249 // trying to load the carrier config when the SIM is still loading when the
250 // unlock happens.
Junda Liu03aad762017-07-21 13:32:17 -0700251 if (mHasSentConfigChange[i]) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800252 logdWithLocalLog("System unlocked");
Sarah Chin807d5c62020-03-30 17:21:09 -0700253 mFromSystemUnlocked[i] = true;
Junda Liu03aad762017-07-21 13:32:17 -0700254 updateConfigForPhoneId(i);
255 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700256 }
257 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700258 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700259
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800260 case EVENT_PACKAGE_CHANGED: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700261 final String carrierPackageName = (String) msg.obj;
Rambo Wanga27fbe52022-04-12 19:09:07 +0000262 // Always clear up the cache and re-load config from scratch since the carrier
263 // service change is reliable and specific to the phoneId now.
264 clearCachedConfigForPackage(carrierPackageName);
265 logdWithLocalLog("Package changed: " + carrierPackageName
266 + ", phone=" + phoneId);
267 updateConfigForPhoneId(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700268 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700269 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700270
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800271 case EVENT_DO_FETCH_DEFAULT: {
Rambo Wang9bc7d362021-03-09 09:10:58 -0800272 // Clear in-memory cache for carrier app config, so when carrier app gets
273 // uninstalled, no stale config is left.
274 if (mConfigFromCarrierApp[phoneId] != null
275 && getCarrierPackageForPhoneId(phoneId) == null) {
276 mConfigFromCarrierApp[phoneId] = null;
277 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100278 // Restore persistent override values.
279 PersistableBundle config = restoreConfigFromXml(
280 mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION, phoneId);
281 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800282 logd("Loaded persistent override config from XML. package="
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100283 + mPlatformCarrierConfigPackage
284 + " phoneId=" + phoneId);
285 mPersistentOverrideConfigs[phoneId] = config;
286 }
287
288 config = restoreConfigFromXml(mPlatformCarrierConfigPackage, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700289 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800290 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700291 "Loaded config from XML. package="
292 + mPlatformCarrierConfigPackage
293 + " phoneId="
294 + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700295 mConfigFromDefaultApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700296 Message newMsg = obtainMessage(EVENT_FETCH_DEFAULT_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700297 newMsg.getData().putBoolean("loaded_from_xml", true);
298 mHandler.sendMessage(newMsg);
299 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700300 // No cached config, so fetch it from the default app.
301 if (bindToConfigPackage(
302 mPlatformCarrierConfigPackage,
303 phoneId,
304 EVENT_CONNECTED_TO_DEFAULT)) {
305 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800306 obtainMessage(EVENT_BIND_DEFAULT_TIMEOUT, phoneId, -1 /*arg2*/,
307 getMessageToken(phoneId)),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700308 BIND_TIMEOUT_MILLIS);
309 } else {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800310 // Put a stub bundle in place so that the rest of the logic continues
311 // smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000312 mConfigFromDefaultApp[phoneId] = new PersistableBundle();
Jonathan Basseri65273c82017-07-25 15:08:42 -0700313 // Send broadcast if bind fails.
Jack Yue37dd262022-12-16 11:53:37 -0800314 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700315 // TODO: We *must* call unbindService even if bindService returns false.
316 // (And possibly if SecurityException was thrown.)
chen xudb04c292019-03-26 17:01:15 -0700317 loge("binding to default app: "
318 + mPlatformCarrierConfigPackage + " fails");
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700319 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800320 }
321 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700322 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800323
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800324 case EVENT_CONNECTED_TO_DEFAULT: {
Rambo Wang610fdf62021-03-08 21:37:11 -0800325 removeMessages(EVENT_BIND_DEFAULT_TIMEOUT, getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700326 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800327 // If new service connection has been created, unbind.
328 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700329 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800330 break;
331 }
chen xu02581692018-11-11 19:03:44 -0800332 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700333 // ResultReceiver callback will execute in this Handler's thread.
334 final ResultReceiver resultReceiver =
335 new ResultReceiver(this) {
336 @Override
337 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700338 unbindIfBound(mContext, conn, phoneId);
Rambo Wanga9d27a52021-04-09 16:17:33 -0700339 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT,
340 getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700341 // If new service connection has been created, this is stale.
342 if (mServiceConnection[phoneId] != conn) {
343 loge("Received response for stale request.");
344 return;
345 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700346 if (resultCode == RESULT_ERROR || resultData == null) {
347 // On error, abort config fetching.
348 loge("Failed to get carrier config");
Jack Yue37dd262022-12-16 11:53:37 -0800349 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700350 return;
351 }
352 PersistableBundle config =
353 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100354 saveConfigToXml(mPlatformCarrierConfigPackage, "", phoneId,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800355 carrierId, config);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700356 mConfigFromDefaultApp[phoneId] = config;
357 sendMessage(
358 obtainMessage(
359 EVENT_FETCH_DEFAULT_DONE, phoneId, -1));
360 }
361 };
362 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800363 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700364 ICarrierService carrierService =
365 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800366 carrierService.getCarrierConfig(phoneId, carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800367 logdWithLocalLog("Fetch config for default app: "
chen xudb04c292019-03-26 17:01:15 -0700368 + mPlatformCarrierConfigPackage
369 + " carrierid: " + carrierId.toString());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700370 } catch (RemoteException e) {
chen xudb04c292019-03-26 17:01:15 -0700371 loge("Failed to get carrier config from default app: " +
372 mPlatformCarrierConfigPackage + " err: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700373 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700374 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800375 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700376 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800377 obtainMessage(EVENT_FETCH_DEFAULT_TIMEOUT, phoneId, -1 /*arg2*/,
378 getMessageToken(phoneId)),
Jonathan Basseri65273c82017-07-25 15:08:42 -0700379 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800380 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700381 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800382
Jonathan Basseri930701e2015-06-11 20:56:43 -0700383 case EVENT_BIND_DEFAULT_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800384 case EVENT_FETCH_DEFAULT_TIMEOUT: {
385 loge("Bind/fetch time out from " + mPlatformCarrierConfigPackage);
Rambo Wang610fdf62021-03-08 21:37:11 -0800386 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT, getMessageToken(phoneId));
chen xuf60b3162019-05-01 21:31:05 -0700387 // If we attempted to bind to the app, but the service connection is null due to
388 // the race condition that clear config event happens before bind/fetch complete
389 // then config was cleared while we were waiting and we should not continue.
390 if (mServiceConnection[phoneId] != null) {
391 // If a ResponseReceiver callback is in the queue when this happens, we will
392 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700393 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700394 broadcastConfigChangedIntent(phoneId);
395 }
Nathan Harold1122e3d2021-01-22 15:45:24 -0800396 // Put a stub bundle in place so that the rest of the logic continues smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000397 mConfigFromDefaultApp[phoneId] = new PersistableBundle();
Jack Yue37dd262022-12-16 11:53:37 -0800398 updateSubscriptionDatabase(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700399 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700400 }
Jonathan Basseri930701e2015-06-11 20:56:43 -0700401
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800402 case EVENT_FETCH_DEFAULT_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700403 // If we attempted to bind to the app, but the service connection is null, then
404 // config was cleared while we were waiting and we should not continue.
405 if (!msg.getData().getBoolean("loaded_from_xml", false)
406 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800407 break;
408 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700409 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700410 if (carrierPackageName != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800411 logd("Found carrier config app: " + carrierPackageName);
Jordan Liu38a614c2019-03-20 15:01:17 -0700412 sendMessage(obtainMessage(EVENT_DO_FETCH_CARRIER, phoneId, -1));
Jonathan Basserib919e932015-05-27 16:53:08 +0000413 } else {
Jack Yue37dd262022-12-16 11:53:37 -0800414 updateSubscriptionDatabase(phoneId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700415 }
416 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700417 }
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700418
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800419 case EVENT_DO_FETCH_CARRIER: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700420 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700421 final PersistableBundle config =
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100422 restoreConfigFromXml(carrierPackageName, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700423 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800424 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700425 "Loaded config from XML. package="
426 + carrierPackageName
427 + " phoneId="
428 + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700429 mConfigFromCarrierApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700430 Message newMsg = obtainMessage(EVENT_FETCH_CARRIER_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700431 newMsg.getData().putBoolean("loaded_from_xml", true);
432 sendMessage(newMsg);
433 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700434 // No cached config, so fetch it from a carrier app.
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800435 if (carrierPackageName != null && bindToConfigPackage(carrierPackageName,
436 phoneId, EVENT_CONNECTED_TO_CARRIER)) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700437 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800438 obtainMessage(EVENT_BIND_CARRIER_TIMEOUT, phoneId, -1 /*arg2*/,
439 getMessageToken(phoneId)),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700440 BIND_TIMEOUT_MILLIS);
441 } else {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800442 // Put a stub bundle in place so that the rest of the logic continues
443 // smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000444 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
Jonathan Basseri65273c82017-07-25 15:08:42 -0700445 // Send broadcast if bind fails.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700446 broadcastConfigChangedIntent(phoneId);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800447 loge("Bind to carrier app: " + carrierPackageName + " fails");
Jack Yue37dd262022-12-16 11:53:37 -0800448 updateSubscriptionDatabase(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700449 }
450 }
451 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700452 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700453
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800454 case EVENT_CONNECTED_TO_CARRIER: {
Rambo Wang610fdf62021-03-08 21:37:11 -0800455 removeMessages(EVENT_BIND_CARRIER_TIMEOUT, getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700456 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800457 // If new service connection has been created, unbind.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700458 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700459 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800460 break;
461 }
chen xu02581692018-11-11 19:03:44 -0800462 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700463 // ResultReceiver callback will execute in this Handler's thread.
464 final ResultReceiver resultReceiver =
465 new ResultReceiver(this) {
466 @Override
467 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700468 unbindIfBound(mContext, conn, phoneId);
Rambo Wanga9d27a52021-04-09 16:17:33 -0700469 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT,
470 getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700471 // If new service connection has been created, this is stale.
472 if (mServiceConnection[phoneId] != conn) {
473 loge("Received response for stale request.");
474 return;
475 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700476 if (resultCode == RESULT_ERROR || resultData == null) {
477 // On error, abort config fetching.
chen xudb04c292019-03-26 17:01:15 -0700478 loge("Failed to get carrier config from carrier app: "
479 + getCarrierPackageForPhoneId(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700480 broadcastConfigChangedIntent(phoneId);
Jack Yue37dd262022-12-16 11:53:37 -0800481 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700482 return;
483 }
484 PersistableBundle config =
485 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100486 saveConfigToXml(getCarrierPackageForPhoneId(phoneId), "",
487 phoneId, carrierId, config);
Amit Mahajan304e92b2021-04-08 14:03:30 -0700488 if (config != null) {
489 mConfigFromCarrierApp[phoneId] = config;
490 } else {
491 logdWithLocalLog("Config from carrier app is null "
492 + "for phoneId " + phoneId);
493 // Put a stub bundle in place so that the rest of the logic
494 // continues smoothly.
495 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
496 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700497 sendMessage(
498 obtainMessage(
499 EVENT_FETCH_CARRIER_DONE, phoneId, -1));
500 }
501 };
502 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800503 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700504 ICarrierService carrierService =
505 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800506 carrierService.getCarrierConfig(phoneId, carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800507 logdWithLocalLog("Fetch config for carrier app: "
chen xudb04c292019-03-26 17:01:15 -0700508 + getCarrierPackageForPhoneId(phoneId)
509 + " carrierid: " + carrierId.toString());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700510 } catch (RemoteException e) {
511 loge("Failed to get carrier config: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700512 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700513 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800514 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700515 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800516 obtainMessage(EVENT_FETCH_CARRIER_TIMEOUT, phoneId, -1 /*arg2*/,
517 getMessageToken(phoneId)),
Jonathan Basseri65273c82017-07-25 15:08:42 -0700518 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800519 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700520 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800521
Jonathan Basseri930701e2015-06-11 20:56:43 -0700522 case EVENT_BIND_CARRIER_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800523 case EVENT_FETCH_CARRIER_TIMEOUT: {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800524 loge("Bind/fetch from carrier app timeout, package="
525 + getCarrierPackageForPhoneId(phoneId));
Rambo Wang610fdf62021-03-08 21:37:11 -0800526 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT, getMessageToken(phoneId));
chen xuf60b3162019-05-01 21:31:05 -0700527 // If we attempted to bind to the app, but the service connection is null due to
528 // the race condition that clear config event happens before bind/fetch complete
529 // then config was cleared while we were waiting and we should not continue.
530 if (mServiceConnection[phoneId] != null) {
531 // If a ResponseReceiver callback is in the queue when this happens, we will
532 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700533 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700534 broadcastConfigChangedIntent(phoneId);
535 }
Nathan Harold1122e3d2021-01-22 15:45:24 -0800536 // Put a stub bundle in place so that the rest of the logic continues smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000537 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
Jack Yue37dd262022-12-16 11:53:37 -0800538 updateSubscriptionDatabase(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700539 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700540 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800541 case EVENT_FETCH_CARRIER_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700542 // If we attempted to bind to the app, but the service connection is null, then
543 // config was cleared while we were waiting and we should not continue.
544 if (!msg.getData().getBoolean("loaded_from_xml", false)
545 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800546 break;
547 }
Jack Yue37dd262022-12-16 11:53:37 -0800548 updateSubscriptionDatabase(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800549 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700550 }
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700551
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800552 case EVENT_CHECK_SYSTEM_UPDATE: {
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700553 SharedPreferences sharedPrefs =
554 PreferenceManager.getDefaultSharedPreferences(mContext);
555 final String lastFingerprint = sharedPrefs.getString(KEY_FINGERPRINT, null);
556 if (!Build.FINGERPRINT.equals(lastFingerprint)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800557 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700558 "Build fingerprint changed. old: "
559 + lastFingerprint
560 + " new: "
561 + Build.FINGERPRINT);
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700562 clearCachedConfigForPackage(null);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700563 sharedPrefs
564 .edit()
565 .putString(KEY_FINGERPRINT, Build.FINGERPRINT)
566 .apply();
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700567 }
568 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700569 }
Nathan Harold48ac0972019-03-13 22:33:01 -0700570
571 case EVENT_SUBSCRIPTION_INFO_UPDATED:
572 broadcastConfigChangedIntent(phoneId);
573 break;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700574 case EVENT_MULTI_SIM_CONFIG_CHANGED:
575 onMultiSimConfigChanged();
576 break;
Jayachandran C645ec612020-01-10 10:30:25 -0800577
578 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG: {
579 PersistableBundle config =
580 restoreNoSimConfigFromXml(mPlatformCarrierConfigPackage);
581
582 if (config != null) {
583 logd("Loaded no SIM config from XML. package="
584 + mPlatformCarrierConfigPackage);
585 mNoSimConfig = config;
586 sendMessage(
587 obtainMessage(
588 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
589 phoneId, -1));
590 } else {
591 // No cached config, so fetch it from the default app.
592 if (bindToConfigPackage(
593 mPlatformCarrierConfigPackage,
594 phoneId,
595 EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG)) {
596 sendMessageDelayed(
597 obtainMessage(
598 EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
599 phoneId, -1), BIND_TIMEOUT_MILLIS);
600 } else {
601 broadcastConfigChangedIntent(phoneId, false);
602 // TODO: We *must* call unbindService even if bindService returns false.
603 // (And possibly if SecurityException was thrown.)
604 loge("binding to default app to fetch no SIM config: "
605 + mPlatformCarrierConfigPackage + " fails");
606 }
607 }
608 break;
609 }
610
611 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE: {
612 broadcastConfigChangedIntent(phoneId, false);
613 break;
614 }
615
616 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
617 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT: {
618 loge("Bind/fetch time out for no SIM config from "
619 + mPlatformCarrierConfigPackage);
620 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
621 // If we attempted to bind to the app, but the service connection is null due to
622 // the race condition that clear config event happens before bind/fetch complete
623 // then config was cleared while we were waiting and we should not continue.
624 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
625 // If a ResponseReceiver callback is in the queue when this happens, we will
626 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700627 unbindIfBoundForNoSimConfig(mContext,
628 mServiceConnectionForNoSimConfig[phoneId], phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800629 }
630 broadcastConfigChangedIntent(phoneId, false);
631 break;
632 }
633
634 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG: {
635 removeMessages(EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
636 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
637 // If new service connection has been created, unbind.
638 if (mServiceConnectionForNoSimConfig[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700639 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800640 break;
641 }
642
643 // ResultReceiver callback will execute in this Handler's thread.
644 final ResultReceiver resultReceiver =
645 new ResultReceiver(this) {
646 @Override
647 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700648 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800649 // If new service connection has been created, this is stale.
650 if (mServiceConnectionForNoSimConfig[phoneId] != conn) {
651 loge("Received response for stale request.");
652 return;
653 }
654 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
655 if (resultCode == RESULT_ERROR || resultData == null) {
656 // On error, abort config fetching.
657 loge("Failed to get no SIM carrier config");
658 return;
659 }
660 PersistableBundle config =
661 resultData.getParcelable(KEY_CONFIG_BUNDLE);
662 saveNoSimConfigToXml(mPlatformCarrierConfigPackage, config);
663 mNoSimConfig = config;
664 sendMessage(
665 obtainMessage(
666 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
667 phoneId, -1));
668 }
669 };
670 // Now fetch the config asynchronously from the ICarrierService.
671 try {
672 ICarrierService carrierService =
673 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800674 carrierService.getCarrierConfig(phoneId, null, resultReceiver);
Jayachandran C645ec612020-01-10 10:30:25 -0800675 logdWithLocalLog("Fetch no sim config from default app: "
676 + mPlatformCarrierConfigPackage);
677 } catch (RemoteException e) {
678 loge("Failed to get no sim carrier config from default app: " +
679 mPlatformCarrierConfigPackage + " err: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700680 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800681 break; // So we don't set a timeout.
682 }
683 sendMessageDelayed(
684 obtainMessage(
685 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
686 phoneId, -1), BIND_TIMEOUT_MILLIS);
687 break;
688 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800689 }
690 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700691 }
692
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000693 @NonNull private final Handler mHandler;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800694
695 /**
696 * Constructs a CarrierConfigLoader, registers it as a service, and registers a broadcast
697 * receiver for relevant events.
698 */
Rambo Wang7e3bc122021-03-23 09:24:38 -0700699 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000700 /* package */ CarrierConfigLoader(@NonNull Context context,
Jack Yue37dd262022-12-16 11:53:37 -0800701 //TODO: Remove SubscriptionInfoUpdater.
702 @Nullable SubscriptionInfoUpdater subscriptionInfoUpdater, @NonNull Looper looper) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800703 mContext = context;
Meng Wang33ad2bc2017-03-16 20:21:20 -0700704 mPlatformCarrierConfigPackage =
705 mContext.getString(R.string.platform_carrier_config_package);
Rambo Wang7e3bc122021-03-23 09:24:38 -0700706 mHandler = new ConfigHandler(looper);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800707
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000708 IntentFilter systemEventsFilter = new IntentFilter();
709 systemEventsFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
Rambo Wanga27fbe52022-04-12 19:09:07 +0000710 context.registerReceiver(mSystemBroadcastReceiver, systemEventsFilter);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800711
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000712 mNumPhones = TelephonyManager.from(context).getActiveModemCount();
713 mConfigFromDefaultApp = new PersistableBundle[mNumPhones];
714 mConfigFromCarrierApp = new PersistableBundle[mNumPhones];
715 mPersistentOverrideConfigs = new PersistableBundle[mNumPhones];
716 mOverrideConfigs = new PersistableBundle[mNumPhones];
Rambo Wang42026112021-04-07 20:57:28 +0000717 mNoSimConfig = new PersistableBundle();
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000718 mServiceConnection = new CarrierServiceConnection[mNumPhones];
719 mServiceBound = new boolean[mNumPhones];
720 mHasSentConfigChange = new boolean[mNumPhones];
721 mFromSystemUnlocked = new boolean[mNumPhones];
722 mServiceConnectionForNoSimConfig = new CarrierServiceConnection[mNumPhones];
723 mServiceBoundForNoSimConfig = new boolean[mNumPhones];
Rambo Wanga27fbe52022-04-12 19:09:07 +0000724 mCarrierServiceChangeCallbacks = new CarrierServiceChangeCallback[mNumPhones];
725 for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
726 mCarrierServiceChangeCallbacks[phoneId] = new CarrierServiceChangeCallback(phoneId);
727 TelephonyManager.from(context).registerCarrierPrivilegesCallback(phoneId,
728 new HandlerExecutor(mHandler), mCarrierServiceChangeCallbacks[phoneId]);
729 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800730 logd("CarrierConfigLoader has started");
Rambo Wang7e3bc122021-03-23 09:24:38 -0700731 mSubscriptionInfoUpdater = subscriptionInfoUpdater;
Jack Yu771c6ce2023-02-02 17:51:42 -0800732
733 PhoneConfigurationManager.registerForMultiSimConfigChange(
734 mHandler, EVENT_MULTI_SIM_CONFIG_CHANGED, null);
735
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700736 mHandler.sendEmptyMessage(EVENT_CHECK_SYSTEM_UPDATE);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800737 }
738
739 /**
740 * Initialize the singleton CarrierConfigLoader instance.
741 *
742 * This is only done once, at startup, from {@link com.android.phone.PhoneApp#onCreate}.
743 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000744 @NonNull
745 /* package */ static CarrierConfigLoader init(@NonNull Context context) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800746 synchronized (CarrierConfigLoader.class) {
747 if (sInstance == null) {
Rambo Wang7e3bc122021-03-23 09:24:38 -0700748 sInstance = new CarrierConfigLoader(context,
749 PhoneFactory.getSubscriptionInfoUpdater(), Looper.myLooper());
Brad Ebingerfa6575f2021-05-04 00:29:50 +0000750 // Make this service available through ServiceManager.
751 TelephonyFrameworkInitializer.getTelephonyServiceManager()
752 .getCarrierConfigServiceRegisterer().register(sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800753 } else {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700754 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800755 }
756 return sInstance;
757 }
758 }
759
Rambo Wang7e3bc122021-03-23 09:24:38 -0700760 @VisibleForTesting
761 /* package */ void clearConfigForPhone(int phoneId, boolean fetchNoSimConfig) {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700762 /* Ignore clear configuration request if device is being shutdown. */
763 Phone phone = PhoneFactory.getPhone(phoneId);
764 if (phone != null) {
765 if (phone.isShuttingDown()) {
766 return;
767 }
768 }
769
Jack Yu771c6ce2023-02-02 17:51:42 -0800770 if (mConfigFromDefaultApp.length <= phoneId) {
771 Log.wtf(LOG_TAG, "Invalid phone id " + phoneId);
772 return;
773 }
774
Malcolm Chen5ea18532019-10-24 19:55:44 -0700775 mConfigFromDefaultApp[phoneId] = null;
776 mConfigFromCarrierApp[phoneId] = null;
777 mServiceConnection[phoneId] = null;
778 mHasSentConfigChange[phoneId] = false;
779
Jayachandran C645ec612020-01-10 10:30:25 -0800780 if (fetchNoSimConfig) {
781 // To fetch no SIM config
782 mHandler.sendMessage(
783 mHandler.obtainMessage(
784 EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG, phoneId, -1));
785 }
Malcolm Chen5ea18532019-10-24 19:55:44 -0700786 }
787
Jack Yue37dd262022-12-16 11:53:37 -0800788 private void updateSubscriptionDatabase(int phoneId) {
Jack Yu90813e62023-01-17 17:46:27 -0800789 logd("updateSubscriptionDatabase: phoneId=" + phoneId);
Jack Yue37dd262022-12-16 11:53:37 -0800790 String configPackageName;
Nathan Harold48ac0972019-03-13 22:33:01 -0700791 PersistableBundle configToSend;
792 int carrierId = getSpecificCarrierIdForPhoneId(phoneId);
793 // Prefer the carrier privileged carrier app, but if there is not one, use the platform
794 // default carrier app.
795 if (mConfigFromCarrierApp[phoneId] != null) {
Jack Yue37dd262022-12-16 11:53:37 -0800796 configPackageName = getCarrierPackageForPhoneId(phoneId);
Nathan Harold48ac0972019-03-13 22:33:01 -0700797 configToSend = mConfigFromCarrierApp[phoneId];
798 } else {
Jack Yue37dd262022-12-16 11:53:37 -0800799 configPackageName = mPlatformCarrierConfigPackage;
Nathan Harold48ac0972019-03-13 22:33:01 -0700800 configToSend = mConfigFromDefaultApp[phoneId];
801 }
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700802
Malcolm Chenefafd1c2020-02-20 13:27:08 -0800803 if (configToSend == null) {
Rambo Wang42026112021-04-07 20:57:28 +0000804 configToSend = new PersistableBundle();
Malcolm Chenefafd1c2020-02-20 13:27:08 -0800805 }
806
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700807 // mOverrideConfigs is for testing. And it will override current configs.
808 PersistableBundle config = mOverrideConfigs[phoneId];
809 if (config != null) {
Torbjorn Eklund1050cb02018-11-16 14:05:38 +0100810 configToSend = new PersistableBundle(configToSend);
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700811 configToSend.putAll(config);
812 }
813
Jack Yue37dd262022-12-16 11:53:37 -0800814 if (PhoneFactory.isSubscriptionManagerServiceEnabled()) {
815 SubscriptionManagerService.getInstance().updateSubscriptionByCarrierConfig(
816 phoneId, configPackageName, configToSend,
817 () -> mHandler.obtainMessage(EVENT_SUBSCRIPTION_INFO_UPDATED, phoneId, -1)
818 .sendToTarget());
819 } else {
820 mSubscriptionInfoUpdater.updateSubscriptionByCarrierConfigAndNotifyComplete(
821 phoneId, configPackageName, configToSend,
822 mHandler.obtainMessage(EVENT_SUBSCRIPTION_INFO_UPDATED, phoneId, -1));
823 }
Nathan Harold48ac0972019-03-13 22:33:01 -0700824 }
825
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800826 private void broadcastConfigChangedIntent(int phoneId) {
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800827 broadcastConfigChangedIntent(phoneId, true);
828 }
829
830 private void broadcastConfigChangedIntent(int phoneId, boolean addSubIdExtra) {
rambowangd63ba342022-10-02 11:21:08 -0500831 int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
832 int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
833 int specificCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
834
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800835 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
Christopher Tate38f55eb2017-02-14 14:43:49 -0800836 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT |
chen xuf9db49f2019-03-31 23:04:42 -0700837 Intent.FLAG_RECEIVER_FOREGROUND);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800838 if (addSubIdExtra) {
rambowangd63ba342022-10-02 11:21:08 -0500839 int simApplicationState = getSimApplicationStateForPhone(phoneId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800840 // Include subId/carrier id extra only if SIM records are loaded
841 if (simApplicationState != TelephonyManager.SIM_STATE_UNKNOWN
842 && simApplicationState != TelephonyManager.SIM_STATE_NOT_READY) {
rambowangd63ba342022-10-02 11:21:08 -0500843 subId = SubscriptionManager.getSubscriptionId(phoneId);
844 carrierId = getCarrierIdForPhoneId(phoneId);
845 specificCarrierId = getSpecificCarrierIdForPhoneId(phoneId);
846 intent.putExtra(TelephonyManager.EXTRA_SPECIFIC_CARRIER_ID, specificCarrierId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800847 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, phoneId);
rambowangd63ba342022-10-02 11:21:08 -0500848 intent.putExtra(TelephonyManager.EXTRA_CARRIER_ID, carrierId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800849 }
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800850 }
Amit Mahajanb33bcda2018-01-24 12:56:44 -0800851 intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, phoneId);
Sarah Chin807d5c62020-03-30 17:21:09 -0700852 intent.putExtra(CarrierConfigManager.EXTRA_REBROADCAST_ON_UNLOCK,
853 mFromSystemUnlocked[phoneId]);
rambowangd63ba342022-10-02 11:21:08 -0500854
855 TelephonyRegistryManager trm = mContext.getSystemService(TelephonyRegistryManager.class);
856 // Unlike broadcast, we wouldn't notify registrants on carrier config change when device is
857 // unlocked. Only real carrier config change will send the notification to registrants.
858 if (trm != null && !mFromSystemUnlocked[phoneId]) {
859 trm.notifyCarrierConfigChanged(phoneId, subId, carrierId, specificCarrierId);
860 }
861
Meng Wang97a6a462020-01-23 16:22:16 -0800862 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
rambowangd63ba342022-10-02 11:21:08 -0500863
Jack Yu00ece8c2022-11-19 22:29:12 -0800864 if (SubscriptionManager.isValidSubscriptionId(subId)) {
865 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId + ", subId=" + subId);
Jack Yue9e95be2020-03-22 10:56:06 -0700866 } else {
867 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId);
868 }
Junda Liu03aad762017-07-21 13:32:17 -0700869 mHasSentConfigChange[phoneId] = true;
Sarah Chin807d5c62020-03-30 17:21:09 -0700870 mFromSystemUnlocked[phoneId] = false;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800871 }
872
rambowangd63ba342022-10-02 11:21:08 -0500873 private int getSimApplicationStateForPhone(int phoneId) {
874 int simApplicationState = TelephonyManager.SIM_STATE_UNKNOWN;
875 int subId = SubscriptionManager.getSubscriptionId(phoneId);
876 if (SubscriptionManager.isValidSubscriptionId(subId)) {
877 TelephonyManager telMgr = TelephonyManager.from(mContext)
878 .createForSubscriptionId(subId);
879 simApplicationState = telMgr.getSimApplicationState();
880 }
881 return simApplicationState;
882 }
883
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800884 /** Binds to the default or carrier config app. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000885 private boolean bindToConfigPackage(@NonNull String pkgName, int phoneId, int eventId) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800886 logdWithLocalLog("Binding to " + pkgName + " for phone " + phoneId);
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700887 Intent carrierService = new Intent(CarrierService.CARRIER_SERVICE_INTERFACE);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700888 carrierService.setPackage(pkgName);
Jayachandran C645ec612020-01-10 10:30:25 -0800889 CarrierServiceConnection serviceConnection = new CarrierServiceConnection(
890 phoneId, pkgName, eventId);
891 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
892 mServiceConnectionForNoSimConfig[phoneId] = serviceConnection;
893 } else {
894 mServiceConnection[phoneId] = serviceConnection;
895 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800896 try {
Jayachandran C645ec612020-01-10 10:30:25 -0800897 if (mContext.bindService(carrierService, serviceConnection,
Jordan Liu178430d2020-02-10 14:32:15 -0800898 Context.BIND_AUTO_CREATE)) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700899 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
900 mServiceBoundForNoSimConfig[phoneId] = true;
901 } else {
902 mServiceBound[phoneId] = true;
903 }
Jordan Liu178430d2020-02-10 14:32:15 -0800904 return true;
905 } else {
906 return false;
907 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800908 } catch (SecurityException ex) {
909 return false;
910 }
911 }
912
Rambo Wang7e3bc122021-03-23 09:24:38 -0700913 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000914 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -0700915 /* package */ CarrierIdentifier getCarrierIdentifierForPhoneId(int phoneId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800916 String mcc = "";
917 String mnc = "";
918 String imsi = "";
919 String gid1 = "";
920 String gid2 = "";
921 String spn = TelephonyManager.from(mContext).getSimOperatorNameForPhone(phoneId);
922 String simOperator = TelephonyManager.from(mContext).getSimOperatorNumericForPhone(phoneId);
chen xu02581692018-11-11 19:03:44 -0800923 int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
chen xua31f22b2019-03-06 15:28:50 -0800924 int specificCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
Jonathan Basseri1fa437c2015-04-20 11:08:18 -0700925 // A valid simOperator should be 5 or 6 digits, depending on the length of the MNC.
926 if (simOperator != null && simOperator.length() >= 3) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800927 mcc = simOperator.substring(0, 3);
928 mnc = simOperator.substring(3);
929 }
930 Phone phone = PhoneFactory.getPhone(phoneId);
931 if (phone != null) {
932 imsi = phone.getSubscriberId();
933 gid1 = phone.getGroupIdLevel1();
Junda Liu73183532015-05-14 13:55:40 -0700934 gid2 = phone.getGroupIdLevel2();
chen xu02581692018-11-11 19:03:44 -0800935 carrierId = phone.getCarrierId();
chen xua31f22b2019-03-06 15:28:50 -0800936 specificCarrierId = phone.getSpecificCarrierId();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800937 }
chen xua31f22b2019-03-06 15:28:50 -0800938 return new CarrierIdentifier(mcc, mnc, spn, imsi, gid1, gid2, carrierId, specificCarrierId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800939 }
940
Rambo Wangf7c214a2022-03-17 12:36:22 -0700941 /** Returns the package name of a privileged carrier app, or null if there is none. */
Nathan Harold1122e3d2021-01-22 15:45:24 -0800942 @Nullable
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700943 private String getCarrierPackageForPhoneId(int phoneId) {
Nazanin1adf4562021-03-29 15:35:30 -0700944 final long token = Binder.clearCallingIdentity();
945 try {
Rambo Wangf7c214a2022-03-17 12:36:22 -0700946 return TelephonyManager.from(mContext)
947 .getCarrierServicePackageNameForLogicalSlot(phoneId);
Nazanin1adf4562021-03-29 15:35:30 -0700948 } finally {
949 Binder.restoreCallingIdentity(token);
950 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700951 }
952
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000953 @Nullable
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700954 private String getIccIdForPhoneId(int phoneId) {
955 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
956 return null;
957 }
958 Phone phone = PhoneFactory.getPhone(phoneId);
959 if (phone == null) {
960 return null;
961 }
962 return phone.getIccSerialNumber();
963 }
964
chen xu02581692018-11-11 19:03:44 -0800965 /**
chen xua31f22b2019-03-06 15:28:50 -0800966 * Get the sim specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}
chen xu02581692018-11-11 19:03:44 -0800967 */
chen xua31f22b2019-03-06 15:28:50 -0800968 private int getSpecificCarrierIdForPhoneId(int phoneId) {
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700969 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
chen xu02581692018-11-11 19:03:44 -0800970 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700971 }
972 Phone phone = PhoneFactory.getPhone(phoneId);
973 if (phone == null) {
chen xu02581692018-11-11 19:03:44 -0800974 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700975 }
chen xua31f22b2019-03-06 15:28:50 -0800976 return phone.getSpecificCarrierId();
chen xu02581692018-11-11 19:03:44 -0800977 }
978
979 /**
980 * Get the sim carrier id {@link TelephonyManager#getSimCarrierId() }
981 */
982 private int getCarrierIdForPhoneId(int phoneId) {
983 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
984 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700985 }
chen xu02581692018-11-11 19:03:44 -0800986 Phone phone = PhoneFactory.getPhone(phoneId);
987 if (phone == null) {
988 return TelephonyManager.UNKNOWN_CARRIER_ID;
989 }
990 return phone.getCarrierId();
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700991 }
992
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700993 /**
994 * Writes a bundle to an XML file.
995 *
chen xu02581692018-11-11 19:03:44 -0800996 * The bundle will be written to a file named after the package name, ICCID and
chen xua31f22b2019-03-06 15:28:50 -0800997 * specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}. the same carrier
chen xu02581692018-11-11 19:03:44 -0800998 * should have a single copy of XML file named after carrier id. However, it's still possible
999 * that platform doesn't recognize the current sim carrier, we will use iccid + carrierid as
1000 * the canonical file name. carrierid can also handle the cases SIM OTA resolves to different
1001 * carrier while iccid remains the same.
1002 *
1003 * The file can be restored later with {@link @restoreConfigFromXml}. The XML output will
1004 * include the bundle and the current version of the specified package.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001005 *
1006 * In case of errors or invalid input, no file will be written.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001007 *
Jayachandran C645ec612020-01-10 10:30:25 -08001008 * @param packageName the name of the package from which we fetched this bundle.
1009 * @param extraString An extra string to be used in the XML file name.
1010 * @param phoneId the phone ID.
1011 * @param carrierId contains all carrier-identifying information.
1012 * @param config the bundle to be written. Null will be treated as an empty bundle.
1013 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001014 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001015 private void saveConfigToXml(@Nullable String packageName, @NonNull String extraString,
1016 int phoneId, @Nullable CarrierIdentifier carrierId, @NonNull PersistableBundle config,
1017 boolean isNoSimConfig) {
Jayachandran C645ec612020-01-10 10:30:25 -08001018 if (packageName == null) {
1019 loge("Cannot save config with null packageName");
Yuchen Dongc15afed2018-04-26 17:05:22 +08001020 return;
1021 }
1022
Jayachandran C645ec612020-01-10 10:30:25 -08001023 String fileName;
1024 if (isNoSimConfig) {
1025 fileName = getFilenameForNoSimConfig(packageName);
1026 } else {
Jack Yuf5badd92022-12-08 00:50:53 -08001027 if (TelephonyManager.getSimStateForSlotIndex(phoneId)
Jayachandran C645ec612020-01-10 10:30:25 -08001028 != TelephonyManager.SIM_STATE_LOADED) {
1029 loge("Skip save config because SIM records are not loaded.");
1030 return;
1031 }
1032
1033 final String iccid = getIccIdForPhoneId(phoneId);
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001034 final int cid = carrierId != null ? carrierId.getSpecificCarrierId()
1035 : TelephonyManager.UNKNOWN_CARRIER_ID;
Jayachandran C645ec612020-01-10 10:30:25 -08001036 if (iccid == null) {
1037 loge("Cannot save config with null iccid.");
1038 return;
1039 }
1040 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001041 }
Jayachandran C645ec612020-01-10 10:30:25 -08001042
Junda Liu02596502016-11-15 13:46:43 -08001043 // b/32668103 Only save to file if config isn't empty.
1044 // In case of failure, not caching an empty bundle will
1045 // try loading config again on next power on or sim loaded.
1046 // Downside is for genuinely empty bundle, will bind and load
1047 // on every power on.
1048 if (config == null || config.isEmpty()) {
1049 return;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001050 }
1051
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001052 final String version = getPackageVersion(packageName);
1053 if (version == null) {
1054 loge("Failed to get package version for: " + packageName);
1055 return;
1056 }
1057
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001058 logdWithLocalLog(
1059 "Save config to xml, packagename: " + packageName + " phoneId: " + phoneId);
chen xudb04c292019-03-26 17:01:15 -07001060
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001061 FileOutputStream outFile = null;
1062 try {
Jayachandran C645ec612020-01-10 10:30:25 -08001063 outFile = new FileOutputStream(new File(mContext.getFilesDir(), fileName));
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001064 config.putString(KEY_VERSION, version);
1065 config.writeToStream(outFile);
1066 outFile.flush();
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001067 outFile.close();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001068 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001069 loge(e.toString());
1070 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001071 }
1072
Rambo Wang7e3bc122021-03-23 09:24:38 -07001073 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001074 /* package */ void saveConfigToXml(@Nullable String packageName, @NonNull String extraString,
1075 int phoneId, @NonNull CarrierIdentifier carrierId, @NonNull PersistableBundle config) {
Jayachandran C645ec612020-01-10 10:30:25 -08001076 saveConfigToXml(packageName, extraString, phoneId, carrierId, config, false);
1077 }
1078
Rambo Wang7e3bc122021-03-23 09:24:38 -07001079 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001080 /* package */ void saveNoSimConfigToXml(@Nullable String packageName,
1081 @NonNull PersistableBundle config) {
Jayachandran C645ec612020-01-10 10:30:25 -08001082 saveConfigToXml(packageName, "", -1, null, config, true);
1083 }
1084
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001085 /**
1086 * Reads a bundle from an XML file.
1087 *
1088 * This restores a bundle that was written with {@link #saveConfigToXml}. This returns the saved
Yuchen Dongc15afed2018-04-26 17:05:22 +08001089 * config bundle for the given package and phone ID.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001090 *
1091 * In case of errors, or if the saved config is from a different package version than the
1092 * current version, then null will be returned.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001093 *
Jayachandran C645ec612020-01-10 10:30:25 -08001094 * @param packageName the name of the package from which we fetched this bundle.
1095 * @param extraString An extra string to be used in the XML file name.
1096 * @param phoneId the phone ID.
1097 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001098 * @return the bundle from the XML file. Returns null if there is no saved config, the saved
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001099 * version does not match, or reading config fails.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001100 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001101 @Nullable
1102 private PersistableBundle restoreConfigFromXml(@Nullable String packageName,
1103 @NonNull String extraString, int phoneId, boolean isNoSimConfig) {
Jayachandran C645ec612020-01-10 10:30:25 -08001104 if (packageName == null) {
1105 loge("Cannot restore config with null packageName");
1106 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001107 final String version = getPackageVersion(packageName);
1108 if (version == null) {
1109 loge("Failed to get package version for: " + packageName);
1110 return null;
1111 }
Yuchen Dongc15afed2018-04-26 17:05:22 +08001112
Jayachandran C645ec612020-01-10 10:30:25 -08001113 String fileName;
arunvoddu664c36a2021-10-11 20:09:28 +00001114 String iccid = null;
Jayachandran C645ec612020-01-10 10:30:25 -08001115 if (isNoSimConfig) {
1116 fileName = getFilenameForNoSimConfig(packageName);
1117 } else {
Jack Yuf5badd92022-12-08 00:50:53 -08001118 if (TelephonyManager.getSimStateForSlotIndex(phoneId)
Jayachandran C645ec612020-01-10 10:30:25 -08001119 != TelephonyManager.SIM_STATE_LOADED) {
1120 loge("Skip restore config because SIM records are not loaded.");
1121 return null;
1122 }
1123
arunvoddu664c36a2021-10-11 20:09:28 +00001124 iccid = getIccIdForPhoneId(phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -08001125 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1126 if (iccid == null) {
1127 loge("Cannot restore config with null iccid.");
1128 return null;
1129 }
1130 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001131 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001132
1133 PersistableBundle restoredBundle = null;
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001134 File file = null;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001135 FileInputStream inFile = null;
1136 try {
Jayachandran C645ec612020-01-10 10:30:25 -08001137 file = new File(mContext.getFilesDir(),fileName);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001138 inFile = new FileInputStream(file);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001139
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001140 restoredBundle = PersistableBundle.readFromStream(inFile);
1141 String savedVersion = restoredBundle.getString(KEY_VERSION);
1142 restoredBundle.remove(KEY_VERSION);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001143
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001144 if (!version.equals(savedVersion)) {
1145 loge("Saved version mismatch: " + version + " vs " + savedVersion);
1146 restoredBundle = null;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001147 }
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001148
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001149 inFile.close();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001150 } catch (FileNotFoundException e) {
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001151 // Missing file is normal occurrence that might occur with a new sim or when restoring
1152 // an override file during boot and should not be treated as an error.
arunvoddu664c36a2021-10-11 20:09:28 +00001153 if (file != null) {
1154 if (isNoSimConfig) {
1155 logd("File not found: " + file.getPath());
1156 } else {
1157 String filePath = file.getPath();
1158 filePath = getFilePathForLogging(filePath, iccid);
1159 logd("File not found : " + filePath);
1160 }
1161 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001162 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001163 loge(e.toString());
1164 }
1165
1166 return restoredBundle;
1167 }
1168
arunvoddu664c36a2021-10-11 20:09:28 +00001169 /**
1170 * This method will mask most part of iccid in the filepath for logging on userbuild
1171 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001172 @NonNull
1173 private String getFilePathForLogging(@Nullable String filePath, @Nullable String iccid) {
arunvoddu664c36a2021-10-11 20:09:28 +00001174 // If loggable then return with actual file path
1175 if (Rlog.isLoggable(LOG_TAG, Log.VERBOSE)) {
1176 return filePath;
1177 }
1178 String path = filePath;
1179 int length = (iccid != null) ? iccid.length() : 0;
1180 if (length > 5 && filePath != null) {
1181 path = filePath.replace(iccid.substring(5), "***************");
1182 }
1183 return path;
1184 }
1185
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001186 @Nullable
1187 private PersistableBundle restoreConfigFromXml(@Nullable String packageName,
1188 @NonNull String extraString, int phoneId) {
Jayachandran C645ec612020-01-10 10:30:25 -08001189 return restoreConfigFromXml(packageName, extraString, phoneId, false);
1190 }
1191
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001192 @Nullable
1193 private PersistableBundle restoreNoSimConfigFromXml(@Nullable String packageName) {
Jayachandran C645ec612020-01-10 10:30:25 -08001194 return restoreConfigFromXml(packageName, "", -1, true);
1195 }
1196
Junda Liu8a8a53a2015-05-15 16:19:57 -07001197 /**
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001198 * Clears cached carrier config.
1199 * This deletes all saved XML files associated with the given package name. If packageName is
1200 * null, then it deletes all saved XML files.
1201 *
1202 * @param packageName the name of a carrier package, or null if all cached config should be
1203 * cleared.
1204 * @return true iff one or more files were deleted.
Junda Liu8a8a53a2015-05-15 16:19:57 -07001205 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001206 private boolean clearCachedConfigForPackage(@Nullable final String packageName) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001207 File dir = mContext.getFilesDir();
1208 File[] packageFiles = dir.listFiles(new FilenameFilter() {
1209 public boolean accept(File dir, String filename) {
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001210 if (packageName != null) {
1211 return filename.startsWith("carrierconfig-" + packageName + "-");
1212 } else {
1213 return filename.startsWith("carrierconfig-");
1214 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001215 }
1216 });
Junda Liu8a8a53a2015-05-15 16:19:57 -07001217 if (packageFiles == null || packageFiles.length < 1) return false;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001218 for (File f : packageFiles) {
arunvoddub7c6e8e2022-09-05 15:48:06 +00001219 logd("Deleting " + getFilePathForLogging(f.getName()));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001220 f.delete();
1221 }
Junda Liu8a8a53a2015-05-15 16:19:57 -07001222 return true;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001223 }
1224
arunvoddub7c6e8e2022-09-05 15:48:06 +00001225 private String getFilePathForLogging(String filePath) {
1226 if (!TextUtils.isEmpty(filePath)) {
1227 String[] fileTokens = filePath.split("-");
1228 if (fileTokens != null && fileTokens.length > 2) {
1229 String iccid = fileTokens[fileTokens.length -2];
1230 return getFilePathForLogging(filePath, iccid);
1231 }
1232 return filePath;
1233 }
1234 return filePath;
1235 }
1236
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001237 /** Builds a canonical file name for a config file. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001238 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001239 private static String getFilenameForConfig(
1240 @NonNull String packageName, @NonNull String extraString,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001241 @NonNull String iccid, int cid) {
chen xu02581692018-11-11 19:03:44 -08001242 // the same carrier should have a single copy of XML file named after carrier id.
1243 // However, it's still possible that platform doesn't recognize the current sim carrier,
1244 // we will use iccid + carrierid as the canonical file name. carrierid can also handle the
1245 // cases SIM OTA resolves to different carrier while iccid remains the same.
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001246 return "carrierconfig-" + packageName + extraString + "-" + iccid + "-" + cid + ".xml";
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001247 }
1248
Jayachandran C645ec612020-01-10 10:30:25 -08001249 /** Builds a canonical file name for no SIM config file. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001250 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001251 private String getFilenameForNoSimConfig(@NonNull String packageName) {
1252 return "carrierconfig-" + packageName + "-" + "nosim" + ".xml";
1253 }
1254
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001255 /** Return the current version code of a package, or null if the name is not found. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001256 @Nullable
1257 private String getPackageVersion(@NonNull String packageName) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001258 try {
1259 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
Dianne Hackbornb76ab202017-11-28 17:44:50 -08001260 return Long.toString(info.getLongVersionCode());
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001261 } catch (PackageManager.NameNotFoundException e) {
1262 return null;
1263 }
1264 }
1265
Jonathan Basseri65273c82017-07-25 15:08:42 -07001266 /**
1267 * Read up to date config.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001268 *
1269 * This reads config bundles for the given phoneId. That means getting the latest bundle from
1270 * the default app and a privileged carrier app, if present. This will not bind to an app if we
1271 * have a saved config file to use instead.
1272 */
1273 private void updateConfigForPhoneId(int phoneId) {
Jonathan Basseri65273c82017-07-25 15:08:42 -07001274 mHandler.sendMessage(mHandler.obtainMessage(EVENT_DO_FETCH_DEFAULT, phoneId, -1));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001275 }
1276
Malcolm Chen5ea18532019-10-24 19:55:44 -07001277 private void onMultiSimConfigChanged() {
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001278 int oldNumPhones = mNumPhones;
1279 mNumPhones = TelephonyManager.from(mContext).getActiveModemCount();
1280 if (mNumPhones == oldNumPhones) {
1281 return;
1282 }
1283 logdWithLocalLog("mNumPhones change from " + oldNumPhones + " to " + mNumPhones);
1284
Rambo Wanga27fbe52022-04-12 19:09:07 +00001285 // If DS -> SS switch, release the resources BEFORE truncating the arrays to avoid leaking
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001286 for (int phoneId = mNumPhones; phoneId < oldNumPhones; phoneId++) {
1287 if (mServiceConnection[phoneId] != null) {
1288 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
1289 }
1290 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
1291 unbindIfBoundForNoSimConfig(mContext, mServiceConnectionForNoSimConfig[phoneId],
1292 phoneId);
1293 }
1294 }
1295
Rambo Wanga27fbe52022-04-12 19:09:07 +00001296 // The phone to slot mapping may change, unregister here and re-register callbacks later
1297 for (int phoneId = 0; phoneId < oldNumPhones; phoneId++) {
1298 if (mCarrierServiceChangeCallbacks[phoneId] != null) {
1299 TelephonyManager.from(mContext).unregisterCarrierPrivilegesCallback(
1300 mCarrierServiceChangeCallbacks[phoneId]);
1301 }
1302 }
1303
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001304 // Copy the original arrays, truncate or padding with zeros (if necessary) to new length
1305 mConfigFromDefaultApp = Arrays.copyOf(mConfigFromDefaultApp, mNumPhones);
1306 mConfigFromCarrierApp = Arrays.copyOf(mConfigFromCarrierApp, mNumPhones);
1307 mPersistentOverrideConfigs = Arrays.copyOf(mPersistentOverrideConfigs, mNumPhones);
1308 mOverrideConfigs = Arrays.copyOf(mOverrideConfigs, mNumPhones);
1309 mServiceConnection = Arrays.copyOf(mServiceConnection, mNumPhones);
1310 mServiceConnectionForNoSimConfig =
1311 Arrays.copyOf(mServiceConnectionForNoSimConfig, mNumPhones);
1312 mServiceBound = Arrays.copyOf(mServiceBound, mNumPhones);
1313 mServiceBoundForNoSimConfig = Arrays.copyOf(mServiceBoundForNoSimConfig, mNumPhones);
1314 mHasSentConfigChange = Arrays.copyOf(mHasSentConfigChange, mNumPhones);
1315 mFromSystemUnlocked = Arrays.copyOf(mFromSystemUnlocked, mNumPhones);
Rambo Wanga27fbe52022-04-12 19:09:07 +00001316 mCarrierServiceChangeCallbacks = Arrays.copyOf(mCarrierServiceChangeCallbacks, mNumPhones);
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001317
Rambo Wanga27fbe52022-04-12 19:09:07 +00001318 // Load the config for all the phones and re-register callback AFTER padding the arrays.
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001319 for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
1320 updateConfigForPhoneId(phoneId);
Rambo Wanga27fbe52022-04-12 19:09:07 +00001321 mCarrierServiceChangeCallbacks[phoneId] = new CarrierServiceChangeCallback(phoneId);
1322 TelephonyManager.from(mContext).registerCarrierPrivilegesCallback(phoneId,
1323 new HandlerExecutor(mHandler), mCarrierServiceChangeCallbacks[phoneId]);
Malcolm Chen5ea18532019-10-24 19:55:44 -07001324 }
1325 }
1326
Hall Liu506724b2018-10-22 18:16:14 -07001327 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001328 @NonNull
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001329 public PersistableBundle getConfigForSubId(int subscriptionId, @NonNull String callingPackage) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001330 return getConfigForSubIdWithFeature(subscriptionId, callingPackage, null);
Philip P. Moltmann9797cbb2020-01-07 13:45:00 -08001331 }
1332
1333 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001334 @NonNull
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001335 public PersistableBundle getConfigForSubIdWithFeature(int subscriptionId,
1336 @NonNull String callingPackage, @Nullable String callingFeatureId) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001337 if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(mContext, subscriptionId,
1338 callingPackage, callingFeatureId, "getCarrierConfig")) {
Rambo Wang42026112021-04-07 20:57:28 +00001339 return new PersistableBundle();
Amit Mahajan40b3fa52015-07-14 10:27:19 -07001340 }
Jeff Davidsona8e4e242018-03-15 17:16:18 -07001341
Rambo Wangd2b004b2021-03-30 10:10:23 -07001342 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001343 PersistableBundle retConfig = CarrierConfigManager.getDefaultConfig();
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001344 if (SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001345 PersistableBundle config = mConfigFromDefaultApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001346 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001347 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001348 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001349 config = mConfigFromCarrierApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001350 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001351 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001352 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001353 config = mPersistentOverrideConfigs[phoneId];
1354 if (config != null) {
1355 retConfig.putAll(config);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001356 }
Hall Liu506724b2018-10-22 18:16:14 -07001357 config = mOverrideConfigs[phoneId];
1358 if (config != null) {
1359 retConfig.putAll(config);
Hall Liu506724b2018-10-22 18:16:14 -07001360 }
Nathan Harold1122e3d2021-01-22 15:45:24 -08001361 // Ignore the theoretical case of the default app not being present since that won't
1362 // work in CarrierConfigLoader today.
1363 final boolean allConfigsApplied =
1364 (mConfigFromCarrierApp[phoneId] != null
1365 || getCarrierPackageForPhoneId(phoneId) == null)
1366 && mConfigFromDefaultApp[phoneId] != null;
1367 retConfig.putBoolean(
1368 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, allConfigsApplied);
Jayachandran C645ec612020-01-10 10:30:25 -08001369 } else {
1370 if (mNoSimConfig != null) {
1371 retConfig.putAll(mNoSimConfig);
1372 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001373 }
1374 return retConfig;
1375 }
1376
1377 @Override
rambowang14757c22022-10-03 11:54:56 -05001378 @NonNull
1379 public PersistableBundle getConfigSubsetForSubIdWithFeature(int subscriptionId,
1380 @NonNull String callingPackage, @Nullable String callingFeatureId,
1381 @NonNull String[] keys) {
1382 Objects.requireNonNull(callingPackage, "Calling package must be non-null");
1383 Objects.requireNonNull(keys, "Config keys must be non-null");
1384 enforceCallerIsSystemOrRequestingPackage(callingPackage);
1385
1386 // Permission check is performed inside and an empty bundle will return on failure.
1387 // No SecurityException thrown here since most clients expect to retrieve the overridden
1388 // value if present or use default one if not
1389 PersistableBundle allConfigs = getConfigForSubIdWithFeature(subscriptionId, callingPackage,
1390 callingFeatureId);
1391 if (allConfigs.isEmpty()) {
1392 return allConfigs;
1393 }
1394 for (String key : keys) {
1395 Objects.requireNonNull(key, "Config key must be non-null");
rambowang14757c22022-10-03 11:54:56 -05001396 }
1397
1398 PersistableBundle configSubset = new PersistableBundle(
1399 keys.length + CONFIG_SUBSET_METADATA_KEYS.length);
1400 for (String carrierConfigKey : keys) {
1401 Object value = allConfigs.get(carrierConfigKey);
rambowangb49e90f2022-12-13 18:29:06 -06001402 if (value == null) {
1403 // Filter out keys without values.
1404 // In history, many AOSP or OEMs/carriers private configs didn't provide default
1405 // values. We have to continue supporting them for now. See b/261776046 for details.
1406 continue;
1407 }
rambowang14757c22022-10-03 11:54:56 -05001408 // Config value itself could be PersistableBundle which requires different API to put
1409 if (value instanceof PersistableBundle) {
1410 configSubset.putPersistableBundle(carrierConfigKey, (PersistableBundle) value);
1411 } else {
1412 configSubset.putObject(carrierConfigKey, value);
1413 }
1414 }
1415
1416 // Configs in CONFIG_SUBSET_ALWAYS_INCLUDED_KEYS should always be included
1417 for (String generalKey : CONFIG_SUBSET_METADATA_KEYS) {
1418 configSubset.putObject(generalKey, allConfigs.get(generalKey));
1419 }
1420
1421 return configSubset;
1422 }
1423
1424 @Override
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001425 public void overrideConfig(int subscriptionId, @Nullable PersistableBundle overrides,
1426 boolean persistent) {
Hall Liu506724b2018-10-22 18:16:14 -07001427 mContext.enforceCallingOrSelfPermission(
1428 android.Manifest.permission.MODIFY_PHONE_STATE, null);
1429 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1430 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001431 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
Rambo Wangd2b004b2021-03-30 10:10:23 -07001432 throw new IllegalArgumentException(
1433 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
Hall Liu506724b2018-10-22 18:16:14 -07001434 }
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001435 // Post to run on handler thread on which all states should be confined.
1436 mHandler.post(() -> {
1437 overrideConfig(mOverrideConfigs, phoneId, overrides);
Hall Liu506724b2018-10-22 18:16:14 -07001438
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001439 if (persistent) {
1440 overrideConfig(mPersistentOverrideConfigs, phoneId, overrides);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001441
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001442 if (overrides != null) {
1443 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
1444 saveConfigToXml(mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION,
1445 phoneId,
1446 carrierId, mPersistentOverrideConfigs[phoneId]);
1447 } else {
1448 final String iccid = getIccIdForPhoneId(phoneId);
1449 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1450 String fileName = getFilenameForConfig(mPlatformCarrierConfigPackage,
1451 OVERRIDE_PACKAGE_ADDITION, iccid, cid);
1452 File fileToDelete = new File(mContext.getFilesDir(), fileName);
1453 fileToDelete.delete();
1454 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001455 }
Jack Yue37dd262022-12-16 11:53:37 -08001456 updateSubscriptionDatabase(phoneId);
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001457 });
Hall Liu506724b2018-10-22 18:16:14 -07001458 }
1459
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001460 private void overrideConfig(@NonNull PersistableBundle[] currentOverrides, int phoneId,
1461 @Nullable PersistableBundle overrides) {
1462 if (overrides == null) {
Rambo Wang42026112021-04-07 20:57:28 +00001463 currentOverrides[phoneId] = new PersistableBundle();
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001464 } else if (currentOverrides[phoneId] == null) {
1465 currentOverrides[phoneId] = overrides;
1466 } else {
1467 currentOverrides[phoneId].putAll(overrides);
1468 }
1469 }
1470
Hall Liu506724b2018-10-22 18:16:14 -07001471 @Override
Rambo Wangd2b004b2021-03-30 10:10:23 -07001472 public void notifyConfigChangedForSubId(int subscriptionId) {
Jordan Liud7d57fe2019-04-16 12:29:43 -07001473 // Requires the calling app to be either a carrier privileged app for this subId or
Junda Liufbd2bcb2016-06-15 11:15:42 -07001474 // system privileged app with MODIFY_PHONE_STATE permission.
Rambo Wangd2b004b2021-03-30 10:10:23 -07001475 TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(mContext,
1476 subscriptionId, "Require carrier privileges or MODIFY_PHONE_STATE permission.");
1477
1478 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1479 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
1480 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
1481 throw new IllegalArgumentException(
1482 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
1483 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001484
1485 // This method should block until deleting has completed, so that an error which prevents us
1486 // from clearing the cache is passed back to the carrier app. With the files successfully
1487 // deleted, this can return and we will eventually bind to the carrier app.
Jordan Liud7d57fe2019-04-16 12:29:43 -07001488 String callingPackageName = mContext.getPackageManager().getNameForUid(
1489 Binder.getCallingUid());
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001490 clearCachedConfigForPackage(callingPackageName);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001491 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001492 }
1493
1494 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001495 public void updateConfigForPhoneId(int phoneId, @NonNull String simState) {
Junda Liu1f2b34d2015-06-18 15:26:56 -07001496 mContext.enforceCallingOrSelfPermission(
1497 android.Manifest.permission.MODIFY_PHONE_STATE, null);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001498 logdWithLocalLog("Update config for phoneId: " + phoneId + " simState: " + simState);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001499 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001500 throw new IllegalArgumentException("Invalid phoneId: " + phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001501 }
1502 // requires Java 7 for switch on string.
1503 switch (simState) {
1504 case IccCardConstants.INTENT_VALUE_ICC_ABSENT:
1505 case IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR:
Junda Liu6f5fddf2016-05-24 16:14:41 -07001506 case IccCardConstants.INTENT_VALUE_ICC_CARD_RESTRICTED:
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001507 case IccCardConstants.INTENT_VALUE_ICC_UNKNOWN:
Malcolm Chendb66de12019-12-09 18:57:07 -08001508 case IccCardConstants.INTENT_VALUE_ICC_NOT_READY:
Junda Liu9f2d2712015-05-15 14:22:45 -07001509 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CLEAR_CONFIG, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001510 break;
1511 case IccCardConstants.INTENT_VALUE_ICC_LOADED:
1512 case IccCardConstants.INTENT_VALUE_ICC_LOCKED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001513 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001514 break;
1515 }
1516 }
1517
Junda Liu43d723a2015-05-12 17:23:45 -07001518 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001519 @NonNull
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001520 public String getDefaultCarrierServicePackageName() {
Shuo Qianefdb7962019-12-19 15:54:27 -08001521 mContext.enforceCallingOrSelfPermission(
1522 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
1523 "getDefaultCarrierServicePackageName");
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001524 return mPlatformCarrierConfigPackage;
1525 }
1526
Rambo Wang7e3bc122021-03-23 09:24:38 -07001527 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001528 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -07001529 /* package */ Handler getHandler() {
1530 return mHandler;
1531 }
1532
1533 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001534 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001535 /* package */ PersistableBundle getConfigFromDefaultApp(int phoneId) {
1536 return mConfigFromDefaultApp[phoneId];
1537 }
1538
1539 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001540 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001541 /* package */ PersistableBundle getConfigFromCarrierApp(int phoneId) {
1542 return mConfigFromCarrierApp[phoneId];
1543 }
1544
1545 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001546 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -07001547 /* package */ PersistableBundle getNoSimConfig() {
1548 return mNoSimConfig;
1549 }
1550
1551 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001552 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001553 /* package */ PersistableBundle getOverrideConfig(int phoneId) {
1554 return mOverrideConfigs[phoneId];
1555 }
1556
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001557 // TODO(b/185129900): always call unbindService after bind, no matter if it succeeded
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001558 private void unbindIfBound(@NonNull Context context, @NonNull CarrierServiceConnection conn,
Rambo Wangb0f3e2f2021-10-28 12:40:12 -07001559 int phoneId) {
1560 if (mServiceBound[phoneId]) {
1561 mServiceBound[phoneId] = false;
1562 context.unbindService(conn);
1563 }
1564 }
1565
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001566 private void unbindIfBoundForNoSimConfig(@NonNull Context context,
1567 @NonNull CarrierServiceConnection conn, int phoneId) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -07001568 if (mServiceBoundForNoSimConfig[phoneId]) {
1569 mServiceBoundForNoSimConfig[phoneId] = false;
Jayachandran C645ec612020-01-10 10:30:25 -08001570 context.unbindService(conn);
1571 }
1572 }
1573
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001574 /**
Rambo Wang610fdf62021-03-08 21:37:11 -08001575 * Returns a boxed Integer object for phoneId, services as message token to distinguish messages
1576 * with same code when calling {@link Handler#removeMessages(int, Object)}.
1577 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001578 @NonNull
Rambo Wang610fdf62021-03-08 21:37:11 -08001579 private Integer getMessageToken(int phoneId) {
1580 if (phoneId < -128 || phoneId > 127) {
1581 throw new IllegalArgumentException("phoneId should be in range [-128, 127], inclusive");
1582 }
1583 // Integer#valueOf guarantees the integers within [-128, 127] are cached and thus memory
1584 // comparison (==) returns true for the same integer.
1585 return Integer.valueOf(phoneId);
1586 }
1587
1588 /**
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001589 * If {@code args} contains {@link #DUMP_ARG_REQUESTING_PACKAGE} and a following package name,
1590 * we'll also call {@link IBinder#dump} on the default carrier service (if bound) and the
1591 * specified carrier service (if bound). Typically, this is done for connectivity bug reports
1592 * where we don't call {@code dumpsys activity service all-non-platform} because that contains
1593 * too much info, but we still want to let carrier apps include their diagnostics.
1594 */
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001595 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001596 public void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter pw, @NonNull String[] args) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001597 IndentingPrintWriter indentPW = new IndentingPrintWriter(pw, " ");
Junda Liu43d723a2015-05-12 17:23:45 -07001598 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1599 != PackageManager.PERMISSION_GRANTED) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001600 indentPW.println("Permission Denial: can't dump carrierconfig from from pid="
Junda Liu43d723a2015-05-12 17:23:45 -07001601 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
1602 return;
1603 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001604 String requestingPackage = null;
1605 int requestingPackageIndex = ArrayUtils.indexOf(args, DUMP_ARG_REQUESTING_PACKAGE);
1606 if (requestingPackageIndex >= 0 && requestingPackageIndex < args.length - 1
1607 && !TextUtils.isEmpty(args[requestingPackageIndex + 1])) {
1608 requestingPackage = args[requestingPackageIndex + 1];
1609 // Throws a SecurityException if the caller is impersonating another app in an effort to
1610 // dump extra info (which may contain PII the caller doesn't have a right to).
1611 enforceCallerIsSystemOrRequestingPackage(requestingPackage);
1612 }
1613
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001614 indentPW.println("CarrierConfigLoader: " + this);
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001615 for (int i = 0; i < mNumPhones; i++) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001616 indentPW.println("Phone Id = " + i);
shuoq26a3a4c2016-12-16 11:06:48 -08001617 // display default values in CarrierConfigManager
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001618 printConfig(CarrierConfigManager.getDefaultConfig(), indentPW,
shuoq26a3a4c2016-12-16 11:06:48 -08001619 "Default Values from CarrierConfigManager");
shuoq26a3a4c2016-12-16 11:06:48 -08001620 // display ConfigFromDefaultApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001621 printConfig(mConfigFromDefaultApp[i], indentPW, "mConfigFromDefaultApp");
shuoq26a3a4c2016-12-16 11:06:48 -08001622 // display ConfigFromCarrierApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001623 printConfig(mConfigFromCarrierApp[i], indentPW, "mConfigFromCarrierApp");
1624 printConfig(mPersistentOverrideConfigs[i], indentPW, "mPersistentOverrideConfigs");
1625 printConfig(mOverrideConfigs[i], indentPW, "mOverrideConfigs");
shuoq26a3a4c2016-12-16 11:06:48 -08001626 }
chen xudb04c292019-03-26 17:01:15 -07001627
Jayachandran C645ec612020-01-10 10:30:25 -08001628 printConfig(mNoSimConfig, indentPW, "mNoSimConfig");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001629 indentPW.println("CarrierConfigLoadingLog=");
1630 mCarrierConfigLoadingLog.dump(fd, indentPW, args);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001631
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001632 if (requestingPackage != null) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001633 logd("Including default and requesting package " + requestingPackage
1634 + " carrier services in dump");
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001635 indentPW.println("");
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001636 indentPW.println("Connected services");
1637 dumpCarrierServiceIfBound(fd, indentPW, "Default config package",
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001638 mPlatformCarrierConfigPackage, false /* considerCarrierPrivileges */);
1639 dumpCarrierServiceIfBound(fd, indentPW, "Requesting package", requestingPackage,
1640 true /* considerCarrierPrivileges */);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001641 }
shuoq26a3a4c2016-12-16 11:06:48 -08001642 }
1643
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001644 private void printConfig(@NonNull PersistableBundle configApp,
1645 @NonNull IndentingPrintWriter indentPW, @NonNull String name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001646 indentPW.increaseIndent();
shuoq26a3a4c2016-12-16 11:06:48 -08001647 if (configApp == null) {
shuoq26a3a4c2016-12-16 11:06:48 -08001648 indentPW.println(name + " : null ");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001649 indentPW.decreaseIndent();
1650 indentPW.println("");
shuoq26a3a4c2016-12-16 11:06:48 -08001651 return;
1652 }
shuoq26a3a4c2016-12-16 11:06:48 -08001653 indentPW.println(name + " : ");
1654 List<String> sortedKeys = new ArrayList<String>(configApp.keySet());
1655 Collections.sort(sortedKeys);
1656 indentPW.increaseIndent();
1657 indentPW.increaseIndent();
1658 for (String key : sortedKeys) {
1659 if (configApp.get(key) != null && configApp.get(key) instanceof Object[]) {
1660 indentPW.println(key + " = " +
1661 Arrays.toString((Object[]) configApp.get(key)));
1662 } else if (configApp.get(key) != null && configApp.get(key) instanceof int[]) {
1663 indentPW.println(key + " = " + Arrays.toString((int[]) configApp.get(key)));
1664 } else {
1665 indentPW.println(key + " = " + configApp.get(key));
1666 }
Junda Liu43d723a2015-05-12 17:23:45 -07001667 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001668 indentPW.decreaseIndent();
1669 indentPW.decreaseIndent();
1670 indentPW.decreaseIndent();
1671 indentPW.println("");
Junda Liu43d723a2015-05-12 17:23:45 -07001672 }
1673
Hunter Knepshielde601f432020-02-19 10:16:04 -08001674 /**
1675 * Passes without problem when one of these conditions is true:
1676 * - The caller is a privileged UID (e.g. for dumpstate.cpp generating a bug report, where the
1677 * system knows the true caller plumbed in through the {@link android.os.BugreportManager} API).
1678 * - The caller's UID matches the supplied package.
1679 *
1680 * @throws SecurityException if none of the above conditions are met.
1681 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001682 private void enforceCallerIsSystemOrRequestingPackage(@NonNull String requestingPackage)
Hunter Knepshielde601f432020-02-19 10:16:04 -08001683 throws SecurityException {
1684 final int callingUid = Binder.getCallingUid();
1685 if (callingUid == Process.ROOT_UID || callingUid == Process.SYSTEM_UID
1686 || callingUid == Process.SHELL_UID || callingUid == Process.PHONE_UID) {
1687 // Bug reports (dumpstate.cpp) run as SHELL, and let some other privileged UIDs through
1688 // as well.
1689 return;
1690 }
1691 // An app is trying to dump extra detail, block it if they aren't who they claim to be.
1692 AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
1693 if (appOps == null) {
1694 throw new SecurityException("No AppOps");
1695 }
1696 // Will throw a SecurityException if the UID and package don't match.
1697 appOps.checkPackage(callingUid, requestingPackage);
1698 }
1699
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001700 /**
1701 * Searches for one or more appropriate {@link CarrierService} instances to dump based on the
1702 * current connections.
1703 *
1704 * @param targetPkgName the target package name to dump carrier services for
1705 * @param considerCarrierPrivileges if true, allow a carrier service to be dumped if it shares
1706 * carrier privileges with {@code targetPkgName};
1707 * otherwise, only dump a carrier service if it is {@code
1708 * targetPkgName}
1709 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001710 private void dumpCarrierServiceIfBound(@NonNull FileDescriptor fd,
1711 @NonNull IndentingPrintWriter indentPW, @NonNull String prefix,
1712 @NonNull String targetPkgName, boolean considerCarrierPrivileges) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001713 // Null package is possible if it's early in the boot process, there was a recent crash, we
1714 // loaded the config from XML most recently, or a SIM slot is empty. Carrier apps with
1715 // long-lived bindings should typically get dumped here regardless. Even if an app is being
1716 // used for multiple phoneIds, we assume that it's smart enough to handle that on its own,
1717 // and that in most cases we'd just be dumping duplicate information and bloating a report.
1718 indentPW.increaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001719 indentPW.println(prefix + " : " + targetPkgName);
1720 Set<String> dumpedPkgNames = new ArraySet<>(mServiceConnection.length);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001721 for (CarrierServiceConnection connection : mServiceConnection) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001722 if (connection == null || !SubscriptionManager.isValidPhoneId(connection.phoneId)
1723 || TextUtils.isEmpty(connection.pkgName)) {
1724 continue;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001725 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001726 final String servicePkgName = connection.pkgName;
1727 // Note: we intentionally ignore system components here because we should NOT match the
1728 // shell caller that's typically used for bug reports via non-BugreportManager triggers.
1729 final boolean exactPackageMatch = TextUtils.equals(targetPkgName, servicePkgName);
1730 final boolean carrierPrivilegesMatch =
1731 considerCarrierPrivileges && hasCarrierPrivileges(targetPkgName,
1732 connection.phoneId);
1733 if (!exactPackageMatch && !carrierPrivilegesMatch) continue;
1734 // Make sure this service is actually alive before trying to dump it. We don't pay
1735 // attention to mServiceBound[connection.phoneId] because typically carrier apps will
1736 // request long-lived bindings, and even if we unbind the app, it may still be alive due
1737 // to CarrierServiceBindHelper. Pull it out as a reference so even if it gets set to
1738 // null within the ServiceConnection during unbinding we can avoid an NPE.
1739 final IBinder service = connection.service;
1740 if (service == null || !service.isBinderAlive() || !service.pingBinder()) continue;
1741 // We've got a live service. Last check is just to make sure we don't dump a package
1742 // multiple times.
1743 if (!dumpedPkgNames.add(servicePkgName)) continue;
1744 if (!exactPackageMatch) {
1745 logd(targetPkgName + " has carrier privileges on phoneId " + connection.phoneId
1746 + ", service provided by " + servicePkgName);
1747 indentPW.increaseIndent();
1748 indentPW.println("Proxy : " + servicePkgName);
1749 indentPW.decreaseIndent();
1750 }
1751 // Flush before we let the app output anything to ensure correct ordering of output.
1752 // Internally, Binder#dump calls flush on its printer after finishing so we don't
1753 // need to do anything after.
1754 indentPW.flush();
1755 try {
1756 logd("Dumping " + servicePkgName);
1757 // We don't need to give the carrier service any args.
1758 connection.service.dump(fd, null /* args */);
1759 logd("Done with " + servicePkgName);
1760 } catch (RemoteException e) {
1761 logd("RemoteException from " + servicePkgName, e);
1762 indentPW.increaseIndent();
1763 indentPW.println("RemoteException");
1764 indentPW.increaseIndent();
1765 e.printStackTrace(indentPW);
1766 indentPW.decreaseIndent();
1767 indentPW.decreaseIndent();
1768 // We won't retry this package again because now it's in dumpedPkgNames.
1769 }
1770 indentPW.println("");
Jordan Liu46ed5db2020-01-28 08:55:20 -08001771 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001772 if (dumpedPkgNames.isEmpty()) {
1773 indentPW.increaseIndent();
1774 indentPW.println("Not bound");
1775 indentPW.decreaseIndent();
1776 indentPW.println("");
1777 }
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001778 indentPW.decreaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001779 }
1780
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001781 private boolean hasCarrierPrivileges(@NonNull String pkgName, int phoneId) {
Jack Yu00ece8c2022-11-19 22:29:12 -08001782 int subId = SubscriptionManager.getSubscriptionId(phoneId);
1783 if (!SubscriptionManager.isValidSubscriptionId(subId)) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001784 return false;
1785 }
Jack Yu00ece8c2022-11-19 22:29:12 -08001786 return TelephonyManager.from(mContext).createForSubscriptionId(subId)
1787 .checkCarrierPrivilegesForPackage(pkgName)
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001788 == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001789 }
1790
Zach Johnson36d7aab2015-05-22 15:43:00 -07001791 private class CarrierServiceConnection implements ServiceConnection {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001792 final int phoneId;
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001793 @NonNull final String pkgName;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001794 final int eventId;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001795 IBinder service;
1796
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001797 CarrierServiceConnection(int phoneId, @NonNull String pkgName, int eventId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001798 this.phoneId = phoneId;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001799 this.pkgName = pkgName;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001800 this.eventId = eventId;
1801 }
1802
1803 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001804 public void onServiceConnected(@NonNull ComponentName name, @NonNull IBinder service) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001805 logd("Connected to config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001806 this.service = service;
1807 mHandler.sendMessage(mHandler.obtainMessage(eventId, phoneId, -1, this));
1808 }
1809
1810 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001811 public void onServiceDisconnected(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001812 logd("Disconnected from config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001813 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001814 }
1815
1816 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001817 public void onBindingDied(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001818 logd("Binding died from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001819 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001820 }
1821
1822 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001823 public void onNullBinding(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001824 logd("Null binding from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001825 this.service = null;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001826 }
1827 }
1828
1829 private class ConfigLoaderBroadcastReceiver extends BroadcastReceiver {
1830 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001831 public void onReceive(@NonNull Context context, @NonNull Intent intent) {
Rambo Wanga27fbe52022-04-12 19:09:07 +00001832 switch (intent.getAction()) {
Nanxi Chen3d670502016-03-17 16:32:09 -07001833 case Intent.ACTION_BOOT_COMPLETED:
1834 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_UNLOCKED, null));
1835 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001836 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001837 }
1838 }
1839
Rambo Wanga27fbe52022-04-12 19:09:07 +00001840 private class CarrierServiceChangeCallback implements
1841 TelephonyManager.CarrierPrivilegesCallback {
1842 final int mPhoneId;
1843 // CarrierPrivilegesCallback will be triggered upon registration. Filter the first callback
1844 // here since we really care of the *change* of carrier service instead of the content
1845 private boolean mHasSentServiceChangeCallback;
1846
1847 CarrierServiceChangeCallback(int phoneId) {
1848 this.mPhoneId = phoneId;
1849 this.mHasSentServiceChangeCallback = false;
1850 }
1851
1852 @Override
1853 public void onCarrierPrivilegesChanged(
1854 @androidx.annotation.NonNull Set<String> privilegedPackageNames,
1855 @androidx.annotation.NonNull Set<Integer> privilegedUids) {
1856 // Ignored, not interested here
1857 }
1858
1859 @Override
1860 public void onCarrierServiceChanged(
1861 @androidx.annotation.Nullable String carrierServicePackageName,
1862 int carrierServiceUid) {
1863 // Ignore the first callback which is triggered upon registration
1864 if (!mHasSentServiceChangeCallback) {
1865 mHasSentServiceChangeCallback = true;
1866 return;
1867 }
1868 mHandler.sendMessage(
1869 mHandler.obtainMessage(EVENT_PACKAGE_CHANGED, mPhoneId, -1,
1870 carrierServicePackageName));
1871 }
1872 }
1873
Rambo Wangab13e3e2021-04-08 15:01:06 -07001874 // Get readable string for the message code supported in this class.
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001875 @NonNull
Rambo Wangab13e3e2021-04-08 15:01:06 -07001876 private static String eventToString(int code) {
1877 switch (code) {
1878 case EVENT_CLEAR_CONFIG:
1879 return "EVENT_CLEAR_CONFIG";
1880 case EVENT_CONNECTED_TO_DEFAULT:
1881 return "EVENT_CONNECTED_TO_DEFAULT";
1882 case EVENT_CONNECTED_TO_CARRIER:
1883 return "EVENT_CONNECTED_TO_CARRIER";
1884 case EVENT_FETCH_DEFAULT_DONE:
1885 return "EVENT_FETCH_DEFAULT_DONE";
1886 case EVENT_FETCH_CARRIER_DONE:
1887 return "EVENT_FETCH_CARRIER_DONE";
1888 case EVENT_DO_FETCH_DEFAULT:
1889 return "EVENT_DO_FETCH_DEFAULT";
1890 case EVENT_DO_FETCH_CARRIER:
1891 return "EVENT_DO_FETCH_CARRIER";
1892 case EVENT_PACKAGE_CHANGED:
1893 return "EVENT_PACKAGE_CHANGED";
1894 case EVENT_BIND_DEFAULT_TIMEOUT:
1895 return "EVENT_BIND_DEFAULT_TIMEOUT";
1896 case EVENT_BIND_CARRIER_TIMEOUT:
1897 return "EVENT_BIND_CARRIER_TIMEOUT";
1898 case EVENT_CHECK_SYSTEM_UPDATE:
1899 return "EVENT_CHECK_SYSTEM_UPDATE";
1900 case EVENT_SYSTEM_UNLOCKED:
1901 return "EVENT_SYSTEM_UNLOCKED";
1902 case EVENT_FETCH_DEFAULT_TIMEOUT:
1903 return "EVENT_FETCH_DEFAULT_TIMEOUT";
1904 case EVENT_FETCH_CARRIER_TIMEOUT:
1905 return "EVENT_FETCH_CARRIER_TIMEOUT";
1906 case EVENT_SUBSCRIPTION_INFO_UPDATED:
1907 return "EVENT_SUBSCRIPTION_INFO_UPDATED";
1908 case EVENT_MULTI_SIM_CONFIG_CHANGED:
1909 return "EVENT_MULTI_SIM_CONFIG_CHANGED";
1910 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG:
1911 return "EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG";
1912 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE:
1913 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE";
1914 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG:
1915 return "EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG";
1916 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1917 return "EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1918 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1919 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1920 default:
1921 return "UNKNOWN(" + code + ")";
1922 }
1923 }
1924
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001925 private void logd(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001926 Log.d(LOG_TAG, msg);
1927 }
1928
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001929 private void logd(@NonNull String msg, Throwable tr) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001930 Log.d(LOG_TAG, msg, tr);
1931 }
1932
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001933 private void logdWithLocalLog(@NonNull String msg) {
chen xudb04c292019-03-26 17:01:15 -07001934 Log.d(LOG_TAG, msg);
1935 mCarrierConfigLoadingLog.log(msg);
1936 }
1937
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001938 private void loge(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001939 Log.e(LOG_TAG, msg);
chen xudb04c292019-03-26 17:01:15 -07001940 mCarrierConfigLoadingLog.log(msg);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001941 }
1942}