blob: bc42a9328f38a69d780809998b7d681a105fd25b [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;
mattgilbride5b6b7182023-04-03 18:56:44 +000042import android.os.PermissionEnforcer;
Jonathan Basseric31f1f32015-05-12 10:13:03 -070043import android.os.PersistableBundle;
Hunter Knepshielde601f432020-02-19 10:16:04 -080044import android.os.Process;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080045import android.os.RemoteException;
Jonathan Basseri65273c82017-07-25 15:08:42 -070046import android.os.ResultReceiver;
Meng Wang97a6a462020-01-23 16:22:16 -080047import android.os.UserHandle;
Jonathan Basseri7697cae2015-07-06 15:49:23 -070048import android.preference.PreferenceManager;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080049import android.service.carrier.CarrierIdentifier;
Zach Johnson36d7aab2015-05-22 15:43:00 -070050import android.service.carrier.CarrierService;
51import android.service.carrier.ICarrierService;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080052import android.telephony.CarrierConfigManager;
53import android.telephony.SubscriptionManager;
Peter Wangc035ce42020-01-08 21:00:22 -080054import android.telephony.TelephonyFrameworkInitializer;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080055import android.telephony.TelephonyManager;
rambowangd63ba342022-10-02 11:21:08 -050056import android.telephony.TelephonyRegistryManager;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -080057import android.text.TextUtils;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -080058import android.util.ArraySet;
chen xudb04c292019-03-26 17:01:15 -070059import android.util.LocalLog;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080060import android.util.Log;
61
Rambo Wang7e3bc122021-03-23 09:24:38 -070062import com.android.internal.annotations.VisibleForTesting;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080063import com.android.internal.telephony.ICarrierConfigLoader;
64import com.android.internal.telephony.IccCardConstants;
65import com.android.internal.telephony.Phone;
Jack Yu771c6ce2023-02-02 17:51:42 -080066import com.android.internal.telephony.PhoneConfigurationManager;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080067import com.android.internal.telephony.PhoneFactory;
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
Jack Yu771c6ce2023-02-02 17:51:42 -0800130 // Broadcast receiver for system events
Rambo Wanga27fbe52022-04-12 19:09:07 +0000131 @NonNull
132 private final BroadcastReceiver mSystemBroadcastReceiver = new ConfigLoaderBroadcastReceiver();
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000133 @NonNull private final LocalLog mCarrierConfigLoadingLog = new LocalLog(100);
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000134 // Number of phone instances (active modem count)
135 private int mNumPhones;
chen xudb04c292019-03-26 17:01:15 -0700136
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800137
138 // Message codes; see mHandler below.
Jack Yu3beaf9d2023-04-14 09:17:27 -0700139 // Request from UiccController when SIM becomes absent or error.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800140 private static final int EVENT_CLEAR_CONFIG = 0;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800141 // Has connected to default app.
142 private static final int EVENT_CONNECTED_TO_DEFAULT = 3;
143 // Has connected to carrier app.
144 private static final int EVENT_CONNECTED_TO_CARRIER = 4;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700145 // Config has been loaded from default app (or cache).
146 private static final int EVENT_FETCH_DEFAULT_DONE = 5;
147 // Config has been loaded from carrier app (or cache).
148 private static final int EVENT_FETCH_CARRIER_DONE = 6;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700149 // Attempt to fetch from default app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700150 private static final int EVENT_DO_FETCH_DEFAULT = 7;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700151 // Attempt to fetch from carrier app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700152 private static final int EVENT_DO_FETCH_CARRIER = 8;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700153 // A package has been installed, uninstalled, or updated.
154 private static final int EVENT_PACKAGE_CHANGED = 9;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700155 // Bind timed out for the default app.
156 private static final int EVENT_BIND_DEFAULT_TIMEOUT = 10;
157 // Bind timed out for a carrier app.
158 private static final int EVENT_BIND_CARRIER_TIMEOUT = 11;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700159 // Check if the system fingerprint has changed.
160 private static final int EVENT_CHECK_SYSTEM_UPDATE = 12;
Nanxi Chen3d670502016-03-17 16:32:09 -0700161 // Rerun carrier config binding after system is unlocked.
162 private static final int EVENT_SYSTEM_UNLOCKED = 13;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700163 // Fetching config timed out from the default app.
164 private static final int EVENT_FETCH_DEFAULT_TIMEOUT = 14;
165 // Fetching config timed out from a carrier app.
166 private static final int EVENT_FETCH_CARRIER_TIMEOUT = 15;
Jack Yu3beaf9d2023-04-14 09:17:27 -0700167 // SubscriptionManagerService has finished updating the sub for the carrier config.
Nathan Harold48ac0972019-03-13 22:33:01 -0700168 private static final int EVENT_SUBSCRIPTION_INFO_UPDATED = 16;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700169 // Multi-SIM config changed.
170 private static final int EVENT_MULTI_SIM_CONFIG_CHANGED = 17;
Jayachandran C645ec612020-01-10 10:30:25 -0800171 // Attempt to fetch from default app or read from XML for no SIM case.
172 private static final int EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG = 18;
173 // No SIM config has been loaded from default app (or cache).
174 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE = 19;
175 // Has connected to default app for no SIM config.
176 private static final int EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG = 20;
177 // Bind timed out for the default app when trying to fetch no SIM config.
178 private static final int EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 21;
179 // Fetching config timed out from the default app for no SIM config.
180 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 22;
Rambo Wangab13e3e2021-04-08 15:01:06 -0700181 // NOTE: any new EVENT_* values must be added to method eventToString().
Jonathan Basseri930701e2015-06-11 20:56:43 -0700182
Junda Liu6cb45002016-03-22 17:18:20 -0700183 private static final int BIND_TIMEOUT_MILLIS = 30000;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800184
Meng Wang0f6b2ea2020-01-06 18:31:16 -0800185 // Keys used for saving and restoring config bundle from file.
186 private static final String KEY_VERSION = "__carrier_config_package_version__";
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800187
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100188 private static final String OVERRIDE_PACKAGE_ADDITION = "-override";
189
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700190 // SharedPreferences key for last known build fingerprint.
191 private static final String KEY_FINGERPRINT = "build_fingerprint";
192
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -0800193 // Argument for #dump that indicates we should also call the default and specified carrier
194 // service's #dump method. In multi-SIM devices, it's possible that carrier A is on SIM 1 and
195 // carrier B is on SIM 2, in which case we should not dump carrier B's service when carrier A
196 // requested the dump.
197 private static final String DUMP_ARG_REQUESTING_PACKAGE = "--requesting-package";
198
rambowang14757c22022-10-03 11:54:56 -0500199 // Configs that should always be included when clients calls getConfig[ForSubId] with specified
200 // keys (even configs are not explicitly specified). Those configs have special purpose for the
201 // carrier config APIs to work correctly.
202 private static final String[] CONFIG_SUBSET_METADATA_KEYS = new String[] {
203 CarrierConfigManager.KEY_CARRIER_CONFIG_VERSION_STRING,
204 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL
205 };
206
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800207 // Handler to process various events.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700208 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700209 // For each phoneId, the event sequence should be:
Jonathan Basseri65273c82017-07-25 15:08:42 -0700210 // fetch default, connected to default, fetch default (async), fetch default done,
211 // fetch carrier, connected to carrier, fetch carrier (async), fetch carrier done.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700212 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700213 // If there is a saved config file for either the default app or the carrier app, we skip
214 // binding to the app and go straight from fetch to loaded.
215 //
216 // At any time, at most one connection is active. If events are not in this order, previous
217 // connection will be unbound, so only latest event takes effect.
218 //
219 // We broadcast ACTION_CARRIER_CONFIG_CHANGED after:
220 // 1. loading from carrier app (even if read from a file)
221 // 2. loading from default app if there is no carrier app (even if read from a file)
222 // 3. clearing config (e.g. due to sim removal)
223 // 4. encountering bind or IPC error
Jonathan Basseri65273c82017-07-25 15:08:42 -0700224 private class ConfigHandler extends Handler {
Rambo Wang7e3bc122021-03-23 09:24:38 -0700225 ConfigHandler(@NonNull Looper looper) {
226 super(looper);
227 }
228
Jonathan Basseri65273c82017-07-25 15:08:42 -0700229 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000230 public void handleMessage(@NonNull Message msg) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700231 final int phoneId = msg.arg1;
Rambo Wangab13e3e2021-04-08 15:01:06 -0700232 logdWithLocalLog("mHandler: " + eventToString(msg.what) + " phoneId: " + phoneId);
Malcolm Chen5ea18532019-10-24 19:55:44 -0700233 if (!SubscriptionManager.isValidPhoneId(phoneId)
234 && msg.what != EVENT_MULTI_SIM_CONFIG_CHANGED) {
235 return;
236 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800237 switch (msg.what) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800238 case EVENT_CLEAR_CONFIG: {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700239 clearConfigForPhone(phoneId, true);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800240 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700241 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700242
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800243 case EVENT_SYSTEM_UNLOCKED: {
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000244 for (int i = 0; i < mNumPhones; ++i) {
Sarah Chin807d5c62020-03-30 17:21:09 -0700245 // When the user unlocks the device, send the broadcast again (with a
246 // rebroadcast extra) if we have sent it before unlock. This will avoid
247 // trying to load the carrier config when the SIM is still loading when the
248 // unlock happens.
Junda Liu03aad762017-07-21 13:32:17 -0700249 if (mHasSentConfigChange[i]) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800250 logdWithLocalLog("System unlocked");
Sarah Chin807d5c62020-03-30 17:21:09 -0700251 mFromSystemUnlocked[i] = true;
Junda Liu03aad762017-07-21 13:32:17 -0700252 updateConfigForPhoneId(i);
253 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700254 }
255 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700256 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700257
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800258 case EVENT_PACKAGE_CHANGED: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700259 final String carrierPackageName = (String) msg.obj;
Rambo Wanga27fbe52022-04-12 19:09:07 +0000260 // Always clear up the cache and re-load config from scratch since the carrier
261 // service change is reliable and specific to the phoneId now.
262 clearCachedConfigForPackage(carrierPackageName);
263 logdWithLocalLog("Package changed: " + carrierPackageName
264 + ", phone=" + phoneId);
265 updateConfigForPhoneId(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700266 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700267 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700268
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800269 case EVENT_DO_FETCH_DEFAULT: {
Rambo Wang9bc7d362021-03-09 09:10:58 -0800270 // Clear in-memory cache for carrier app config, so when carrier app gets
271 // uninstalled, no stale config is left.
272 if (mConfigFromCarrierApp[phoneId] != null
273 && getCarrierPackageForPhoneId(phoneId) == null) {
274 mConfigFromCarrierApp[phoneId] = null;
275 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100276 // Restore persistent override values.
277 PersistableBundle config = restoreConfigFromXml(
278 mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION, phoneId);
279 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800280 logd("Loaded persistent override config from XML. package="
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100281 + mPlatformCarrierConfigPackage
282 + " phoneId=" + phoneId);
283 mPersistentOverrideConfigs[phoneId] = config;
284 }
285
286 config = restoreConfigFromXml(mPlatformCarrierConfigPackage, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700287 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800288 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700289 "Loaded config from XML. package="
290 + mPlatformCarrierConfigPackage
291 + " phoneId="
292 + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700293 mConfigFromDefaultApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700294 Message newMsg = obtainMessage(EVENT_FETCH_DEFAULT_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700295 newMsg.getData().putBoolean("loaded_from_xml", true);
296 mHandler.sendMessage(newMsg);
297 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700298 // No cached config, so fetch it from the default app.
299 if (bindToConfigPackage(
300 mPlatformCarrierConfigPackage,
301 phoneId,
302 EVENT_CONNECTED_TO_DEFAULT)) {
303 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800304 obtainMessage(EVENT_BIND_DEFAULT_TIMEOUT, phoneId, -1 /*arg2*/,
305 getMessageToken(phoneId)),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700306 BIND_TIMEOUT_MILLIS);
307 } else {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800308 // Put a stub bundle in place so that the rest of the logic continues
309 // smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000310 mConfigFromDefaultApp[phoneId] = new PersistableBundle();
Jonathan Basseri65273c82017-07-25 15:08:42 -0700311 // Send broadcast if bind fails.
Jack Yue37dd262022-12-16 11:53:37 -0800312 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700313 // TODO: We *must* call unbindService even if bindService returns false.
314 // (And possibly if SecurityException was thrown.)
chen xudb04c292019-03-26 17:01:15 -0700315 loge("binding to default app: "
316 + mPlatformCarrierConfigPackage + " fails");
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700317 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800318 }
319 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700320 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800321
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800322 case EVENT_CONNECTED_TO_DEFAULT: {
Rambo Wang610fdf62021-03-08 21:37:11 -0800323 removeMessages(EVENT_BIND_DEFAULT_TIMEOUT, getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700324 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800325 // If new service connection has been created, unbind.
326 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700327 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800328 break;
329 }
chen xu02581692018-11-11 19:03:44 -0800330 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700331 // ResultReceiver callback will execute in this Handler's thread.
332 final ResultReceiver resultReceiver =
333 new ResultReceiver(this) {
334 @Override
335 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700336 unbindIfBound(mContext, conn, phoneId);
Rambo Wanga9d27a52021-04-09 16:17:33 -0700337 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT,
338 getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700339 // If new service connection has been created, this is stale.
340 if (mServiceConnection[phoneId] != conn) {
341 loge("Received response for stale request.");
342 return;
343 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700344 if (resultCode == RESULT_ERROR || resultData == null) {
345 // On error, abort config fetching.
346 loge("Failed to get carrier config");
Jack Yue37dd262022-12-16 11:53:37 -0800347 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700348 return;
349 }
350 PersistableBundle config =
351 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100352 saveConfigToXml(mPlatformCarrierConfigPackage, "", phoneId,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800353 carrierId, config);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700354 mConfigFromDefaultApp[phoneId] = config;
355 sendMessage(
356 obtainMessage(
357 EVENT_FETCH_DEFAULT_DONE, phoneId, -1));
358 }
359 };
360 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800361 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700362 ICarrierService carrierService =
363 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800364 carrierService.getCarrierConfig(phoneId, carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800365 logdWithLocalLog("Fetch config for default app: "
chen xudb04c292019-03-26 17:01:15 -0700366 + mPlatformCarrierConfigPackage
367 + " carrierid: " + carrierId.toString());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700368 } catch (RemoteException e) {
chen xudb04c292019-03-26 17:01:15 -0700369 loge("Failed to get carrier config from default app: " +
370 mPlatformCarrierConfigPackage + " err: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700371 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700372 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800373 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700374 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800375 obtainMessage(EVENT_FETCH_DEFAULT_TIMEOUT, phoneId, -1 /*arg2*/,
376 getMessageToken(phoneId)),
Jonathan Basseri65273c82017-07-25 15:08:42 -0700377 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800378 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700379 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800380
Jonathan Basseri930701e2015-06-11 20:56:43 -0700381 case EVENT_BIND_DEFAULT_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800382 case EVENT_FETCH_DEFAULT_TIMEOUT: {
383 loge("Bind/fetch time out from " + mPlatformCarrierConfigPackage);
Rambo Wang610fdf62021-03-08 21:37:11 -0800384 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT, getMessageToken(phoneId));
chen xuf60b3162019-05-01 21:31:05 -0700385 // If we attempted to bind to the app, but the service connection is null due to
386 // the race condition that clear config event happens before bind/fetch complete
387 // then config was cleared while we were waiting and we should not continue.
388 if (mServiceConnection[phoneId] != null) {
389 // If a ResponseReceiver callback is in the queue when this happens, we will
390 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700391 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700392 broadcastConfigChangedIntent(phoneId);
393 }
Nathan Harold1122e3d2021-01-22 15:45:24 -0800394 // Put a stub bundle in place so that the rest of the logic continues smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000395 mConfigFromDefaultApp[phoneId] = new PersistableBundle();
Jack Yue37dd262022-12-16 11:53:37 -0800396 updateSubscriptionDatabase(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700397 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700398 }
Jonathan Basseri930701e2015-06-11 20:56:43 -0700399
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800400 case EVENT_FETCH_DEFAULT_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700401 // If we attempted to bind to the app, but the service connection is null, then
402 // config was cleared while we were waiting and we should not continue.
403 if (!msg.getData().getBoolean("loaded_from_xml", false)
404 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800405 break;
406 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700407 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700408 if (carrierPackageName != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800409 logd("Found carrier config app: " + carrierPackageName);
Jordan Liu38a614c2019-03-20 15:01:17 -0700410 sendMessage(obtainMessage(EVENT_DO_FETCH_CARRIER, phoneId, -1));
Jonathan Basserib919e932015-05-27 16:53:08 +0000411 } else {
Jack Yue37dd262022-12-16 11:53:37 -0800412 updateSubscriptionDatabase(phoneId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700413 }
414 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700415 }
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700416
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800417 case EVENT_DO_FETCH_CARRIER: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700418 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700419 final PersistableBundle config =
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100420 restoreConfigFromXml(carrierPackageName, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700421 if (config != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800422 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700423 "Loaded config from XML. package="
424 + carrierPackageName
425 + " phoneId="
426 + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700427 mConfigFromCarrierApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700428 Message newMsg = obtainMessage(EVENT_FETCH_CARRIER_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700429 newMsg.getData().putBoolean("loaded_from_xml", true);
430 sendMessage(newMsg);
431 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700432 // No cached config, so fetch it from a carrier app.
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800433 if (carrierPackageName != null && bindToConfigPackage(carrierPackageName,
434 phoneId, EVENT_CONNECTED_TO_CARRIER)) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700435 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800436 obtainMessage(EVENT_BIND_CARRIER_TIMEOUT, phoneId, -1 /*arg2*/,
437 getMessageToken(phoneId)),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700438 BIND_TIMEOUT_MILLIS);
439 } else {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800440 // Put a stub bundle in place so that the rest of the logic continues
441 // smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000442 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
Jonathan Basseri65273c82017-07-25 15:08:42 -0700443 // Send broadcast if bind fails.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700444 broadcastConfigChangedIntent(phoneId);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800445 loge("Bind to carrier app: " + carrierPackageName + " fails");
Jack Yue37dd262022-12-16 11:53:37 -0800446 updateSubscriptionDatabase(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700447 }
448 }
449 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700450 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700451
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800452 case EVENT_CONNECTED_TO_CARRIER: {
Rambo Wang610fdf62021-03-08 21:37:11 -0800453 removeMessages(EVENT_BIND_CARRIER_TIMEOUT, getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700454 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800455 // If new service connection has been created, unbind.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700456 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700457 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800458 break;
459 }
chen xu02581692018-11-11 19:03:44 -0800460 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700461 // ResultReceiver callback will execute in this Handler's thread.
462 final ResultReceiver resultReceiver =
463 new ResultReceiver(this) {
464 @Override
465 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700466 unbindIfBound(mContext, conn, phoneId);
Rambo Wanga9d27a52021-04-09 16:17:33 -0700467 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT,
468 getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700469 // If new service connection has been created, this is stale.
470 if (mServiceConnection[phoneId] != conn) {
471 loge("Received response for stale request.");
472 return;
473 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700474 if (resultCode == RESULT_ERROR || resultData == null) {
475 // On error, abort config fetching.
chen xudb04c292019-03-26 17:01:15 -0700476 loge("Failed to get carrier config from carrier app: "
477 + getCarrierPackageForPhoneId(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700478 broadcastConfigChangedIntent(phoneId);
Jack Yue37dd262022-12-16 11:53:37 -0800479 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700480 return;
481 }
482 PersistableBundle config =
483 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100484 saveConfigToXml(getCarrierPackageForPhoneId(phoneId), "",
485 phoneId, carrierId, config);
Amit Mahajan304e92b2021-04-08 14:03:30 -0700486 if (config != null) {
487 mConfigFromCarrierApp[phoneId] = config;
488 } else {
489 logdWithLocalLog("Config from carrier app is null "
490 + "for phoneId " + phoneId);
491 // Put a stub bundle in place so that the rest of the logic
492 // continues smoothly.
493 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
494 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700495 sendMessage(
496 obtainMessage(
497 EVENT_FETCH_CARRIER_DONE, phoneId, -1));
498 }
499 };
500 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800501 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700502 ICarrierService carrierService =
503 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800504 carrierService.getCarrierConfig(phoneId, carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800505 logdWithLocalLog("Fetch config for carrier app: "
chen xudb04c292019-03-26 17:01:15 -0700506 + getCarrierPackageForPhoneId(phoneId)
507 + " carrierid: " + carrierId.toString());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700508 } catch (RemoteException e) {
509 loge("Failed to get carrier config: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700510 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700511 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800512 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700513 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800514 obtainMessage(EVENT_FETCH_CARRIER_TIMEOUT, phoneId, -1 /*arg2*/,
515 getMessageToken(phoneId)),
Jonathan Basseri65273c82017-07-25 15:08:42 -0700516 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800517 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700518 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800519
Jonathan Basseri930701e2015-06-11 20:56:43 -0700520 case EVENT_BIND_CARRIER_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800521 case EVENT_FETCH_CARRIER_TIMEOUT: {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800522 loge("Bind/fetch from carrier app timeout, package="
523 + getCarrierPackageForPhoneId(phoneId));
Rambo Wang610fdf62021-03-08 21:37:11 -0800524 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT, getMessageToken(phoneId));
chen xuf60b3162019-05-01 21:31:05 -0700525 // If we attempted to bind to the app, but the service connection is null due to
526 // the race condition that clear config event happens before bind/fetch complete
527 // then config was cleared while we were waiting and we should not continue.
528 if (mServiceConnection[phoneId] != null) {
529 // If a ResponseReceiver callback is in the queue when this happens, we will
530 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700531 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700532 broadcastConfigChangedIntent(phoneId);
533 }
Nathan Harold1122e3d2021-01-22 15:45:24 -0800534 // Put a stub bundle in place so that the rest of the logic continues smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000535 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
Jack Yue37dd262022-12-16 11:53:37 -0800536 updateSubscriptionDatabase(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700537 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700538 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800539 case EVENT_FETCH_CARRIER_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700540 // If we attempted to bind to the app, but the service connection is null, then
541 // config was cleared while we were waiting and we should not continue.
542 if (!msg.getData().getBoolean("loaded_from_xml", false)
543 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800544 break;
545 }
Jack Yue37dd262022-12-16 11:53:37 -0800546 updateSubscriptionDatabase(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800547 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700548 }
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700549
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800550 case EVENT_CHECK_SYSTEM_UPDATE: {
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700551 SharedPreferences sharedPrefs =
552 PreferenceManager.getDefaultSharedPreferences(mContext);
553 final String lastFingerprint = sharedPrefs.getString(KEY_FINGERPRINT, null);
554 if (!Build.FINGERPRINT.equals(lastFingerprint)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800555 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700556 "Build fingerprint changed. old: "
557 + lastFingerprint
558 + " new: "
559 + Build.FINGERPRINT);
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700560 clearCachedConfigForPackage(null);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700561 sharedPrefs
562 .edit()
563 .putString(KEY_FINGERPRINT, Build.FINGERPRINT)
564 .apply();
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700565 }
566 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700567 }
Nathan Harold48ac0972019-03-13 22:33:01 -0700568
569 case EVENT_SUBSCRIPTION_INFO_UPDATED:
570 broadcastConfigChangedIntent(phoneId);
571 break;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700572 case EVENT_MULTI_SIM_CONFIG_CHANGED:
573 onMultiSimConfigChanged();
574 break;
Jayachandran C645ec612020-01-10 10:30:25 -0800575
576 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG: {
577 PersistableBundle config =
578 restoreNoSimConfigFromXml(mPlatformCarrierConfigPackage);
579
580 if (config != null) {
581 logd("Loaded no SIM config from XML. package="
582 + mPlatformCarrierConfigPackage);
583 mNoSimConfig = config;
584 sendMessage(
585 obtainMessage(
586 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
587 phoneId, -1));
588 } else {
589 // No cached config, so fetch it from the default app.
590 if (bindToConfigPackage(
591 mPlatformCarrierConfigPackage,
592 phoneId,
593 EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG)) {
594 sendMessageDelayed(
595 obtainMessage(
596 EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
597 phoneId, -1), BIND_TIMEOUT_MILLIS);
598 } else {
599 broadcastConfigChangedIntent(phoneId, false);
600 // TODO: We *must* call unbindService even if bindService returns false.
601 // (And possibly if SecurityException was thrown.)
602 loge("binding to default app to fetch no SIM config: "
603 + mPlatformCarrierConfigPackage + " fails");
604 }
605 }
606 break;
607 }
608
609 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE: {
610 broadcastConfigChangedIntent(phoneId, false);
611 break;
612 }
613
614 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
615 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT: {
616 loge("Bind/fetch time out for no SIM config from "
617 + mPlatformCarrierConfigPackage);
618 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
619 // If we attempted to bind to the app, but the service connection is null due to
620 // the race condition that clear config event happens before bind/fetch complete
621 // then config was cleared while we were waiting and we should not continue.
622 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
623 // If a ResponseReceiver callback is in the queue when this happens, we will
624 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700625 unbindIfBoundForNoSimConfig(mContext,
626 mServiceConnectionForNoSimConfig[phoneId], phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800627 }
628 broadcastConfigChangedIntent(phoneId, false);
629 break;
630 }
631
632 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG: {
633 removeMessages(EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
634 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
635 // If new service connection has been created, unbind.
636 if (mServiceConnectionForNoSimConfig[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700637 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800638 break;
639 }
640
641 // ResultReceiver callback will execute in this Handler's thread.
642 final ResultReceiver resultReceiver =
643 new ResultReceiver(this) {
644 @Override
645 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700646 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800647 // If new service connection has been created, this is stale.
648 if (mServiceConnectionForNoSimConfig[phoneId] != conn) {
649 loge("Received response for stale request.");
650 return;
651 }
652 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
653 if (resultCode == RESULT_ERROR || resultData == null) {
654 // On error, abort config fetching.
655 loge("Failed to get no SIM carrier config");
656 return;
657 }
658 PersistableBundle config =
659 resultData.getParcelable(KEY_CONFIG_BUNDLE);
660 saveNoSimConfigToXml(mPlatformCarrierConfigPackage, config);
661 mNoSimConfig = config;
662 sendMessage(
663 obtainMessage(
664 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
665 phoneId, -1));
666 }
667 };
668 // Now fetch the config asynchronously from the ICarrierService.
669 try {
670 ICarrierService carrierService =
671 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800672 carrierService.getCarrierConfig(phoneId, null, resultReceiver);
Jayachandran C645ec612020-01-10 10:30:25 -0800673 logdWithLocalLog("Fetch no sim config from default app: "
674 + mPlatformCarrierConfigPackage);
675 } catch (RemoteException e) {
676 loge("Failed to get no sim carrier config from default app: " +
677 mPlatformCarrierConfigPackage + " err: " + e.toString());
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700678 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800679 break; // So we don't set a timeout.
680 }
681 sendMessageDelayed(
682 obtainMessage(
683 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
684 phoneId, -1), BIND_TIMEOUT_MILLIS);
685 break;
686 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800687 }
688 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700689 }
690
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000691 @NonNull private final Handler mHandler;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800692
693 /**
694 * Constructs a CarrierConfigLoader, registers it as a service, and registers a broadcast
695 * receiver for relevant events.
696 */
Rambo Wang7e3bc122021-03-23 09:24:38 -0700697 @VisibleForTesting
Jack Yu3beaf9d2023-04-14 09:17:27 -0700698 /* package */ CarrierConfigLoader(@NonNull Context context, @NonNull Looper looper) {
mattgilbride5b6b7182023-04-03 18:56:44 +0000699 super(PermissionEnforcer.fromContext(context));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800700 mContext = context;
Meng Wang33ad2bc2017-03-16 20:21:20 -0700701 mPlatformCarrierConfigPackage =
702 mContext.getString(R.string.platform_carrier_config_package);
Rambo Wang7e3bc122021-03-23 09:24:38 -0700703 mHandler = new ConfigHandler(looper);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800704
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000705 IntentFilter systemEventsFilter = new IntentFilter();
706 systemEventsFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
Rambo Wanga27fbe52022-04-12 19:09:07 +0000707 context.registerReceiver(mSystemBroadcastReceiver, systemEventsFilter);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800708
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000709 mNumPhones = TelephonyManager.from(context).getActiveModemCount();
710 mConfigFromDefaultApp = new PersistableBundle[mNumPhones];
711 mConfigFromCarrierApp = new PersistableBundle[mNumPhones];
712 mPersistentOverrideConfigs = new PersistableBundle[mNumPhones];
713 mOverrideConfigs = new PersistableBundle[mNumPhones];
Rambo Wang42026112021-04-07 20:57:28 +0000714 mNoSimConfig = new PersistableBundle();
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000715 mServiceConnection = new CarrierServiceConnection[mNumPhones];
716 mServiceBound = new boolean[mNumPhones];
717 mHasSentConfigChange = new boolean[mNumPhones];
718 mFromSystemUnlocked = new boolean[mNumPhones];
719 mServiceConnectionForNoSimConfig = new CarrierServiceConnection[mNumPhones];
720 mServiceBoundForNoSimConfig = new boolean[mNumPhones];
Rambo Wanga27fbe52022-04-12 19:09:07 +0000721 mCarrierServiceChangeCallbacks = new CarrierServiceChangeCallback[mNumPhones];
722 for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
723 mCarrierServiceChangeCallbacks[phoneId] = new CarrierServiceChangeCallback(phoneId);
724 TelephonyManager.from(context).registerCarrierPrivilegesCallback(phoneId,
725 new HandlerExecutor(mHandler), mCarrierServiceChangeCallbacks[phoneId]);
726 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800727 logd("CarrierConfigLoader has started");
Jack Yu771c6ce2023-02-02 17:51:42 -0800728
729 PhoneConfigurationManager.registerForMultiSimConfigChange(
730 mHandler, EVENT_MULTI_SIM_CONFIG_CHANGED, null);
731
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700732 mHandler.sendEmptyMessage(EVENT_CHECK_SYSTEM_UPDATE);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800733 }
734
735 /**
736 * Initialize the singleton CarrierConfigLoader instance.
737 *
738 * This is only done once, at startup, from {@link com.android.phone.PhoneApp#onCreate}.
739 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000740 @NonNull
741 /* package */ static CarrierConfigLoader init(@NonNull Context context) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800742 synchronized (CarrierConfigLoader.class) {
743 if (sInstance == null) {
Jack Yu3beaf9d2023-04-14 09:17:27 -0700744 sInstance = new CarrierConfigLoader(context, Looper.myLooper());
Brad Ebingerfa6575f2021-05-04 00:29:50 +0000745 // Make this service available through ServiceManager.
746 TelephonyFrameworkInitializer.getTelephonyServiceManager()
747 .getCarrierConfigServiceRegisterer().register(sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800748 } else {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700749 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800750 }
751 return sInstance;
752 }
753 }
754
Rambo Wang7e3bc122021-03-23 09:24:38 -0700755 @VisibleForTesting
756 /* package */ void clearConfigForPhone(int phoneId, boolean fetchNoSimConfig) {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700757 /* Ignore clear configuration request if device is being shutdown. */
758 Phone phone = PhoneFactory.getPhone(phoneId);
759 if (phone != null) {
760 if (phone.isShuttingDown()) {
761 return;
762 }
763 }
764
Jack Yu771c6ce2023-02-02 17:51:42 -0800765 if (mConfigFromDefaultApp.length <= phoneId) {
766 Log.wtf(LOG_TAG, "Invalid phone id " + phoneId);
767 return;
768 }
769
Malcolm Chen5ea18532019-10-24 19:55:44 -0700770 mConfigFromDefaultApp[phoneId] = null;
771 mConfigFromCarrierApp[phoneId] = null;
772 mServiceConnection[phoneId] = null;
773 mHasSentConfigChange[phoneId] = false;
774
Jayachandran C645ec612020-01-10 10:30:25 -0800775 if (fetchNoSimConfig) {
776 // To fetch no SIM config
777 mHandler.sendMessage(
778 mHandler.obtainMessage(
779 EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG, phoneId, -1));
780 }
Malcolm Chen5ea18532019-10-24 19:55:44 -0700781 }
782
Jack Yue37dd262022-12-16 11:53:37 -0800783 private void updateSubscriptionDatabase(int phoneId) {
Jack Yu90813e62023-01-17 17:46:27 -0800784 logd("updateSubscriptionDatabase: phoneId=" + phoneId);
Jack Yue37dd262022-12-16 11:53:37 -0800785 String configPackageName;
Nathan Harold48ac0972019-03-13 22:33:01 -0700786 PersistableBundle configToSend;
787 int carrierId = getSpecificCarrierIdForPhoneId(phoneId);
788 // Prefer the carrier privileged carrier app, but if there is not one, use the platform
789 // default carrier app.
790 if (mConfigFromCarrierApp[phoneId] != null) {
Jack Yue37dd262022-12-16 11:53:37 -0800791 configPackageName = getCarrierPackageForPhoneId(phoneId);
Nathan Harold48ac0972019-03-13 22:33:01 -0700792 configToSend = mConfigFromCarrierApp[phoneId];
793 } else {
Jack Yue37dd262022-12-16 11:53:37 -0800794 configPackageName = mPlatformCarrierConfigPackage;
Nathan Harold48ac0972019-03-13 22:33:01 -0700795 configToSend = mConfigFromDefaultApp[phoneId];
796 }
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700797
Malcolm Chenefafd1c2020-02-20 13:27:08 -0800798 if (configToSend == null) {
Rambo Wang42026112021-04-07 20:57:28 +0000799 configToSend = new PersistableBundle();
Malcolm Chenefafd1c2020-02-20 13:27:08 -0800800 }
801
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700802 // mOverrideConfigs is for testing. And it will override current configs.
803 PersistableBundle config = mOverrideConfigs[phoneId];
804 if (config != null) {
Torbjorn Eklund1050cb02018-11-16 14:05:38 +0100805 configToSend = new PersistableBundle(configToSend);
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700806 configToSend.putAll(config);
807 }
808
Jack Yu3beaf9d2023-04-14 09:17:27 -0700809 SubscriptionManagerService.getInstance().updateSubscriptionByCarrierConfig(
810 phoneId, configPackageName, configToSend,
811 () -> mHandler.obtainMessage(EVENT_SUBSCRIPTION_INFO_UPDATED, phoneId, -1)
812 .sendToTarget());
Nathan Harold48ac0972019-03-13 22:33:01 -0700813 }
814
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800815 private void broadcastConfigChangedIntent(int phoneId) {
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800816 broadcastConfigChangedIntent(phoneId, true);
817 }
818
819 private void broadcastConfigChangedIntent(int phoneId, boolean addSubIdExtra) {
rambowangd63ba342022-10-02 11:21:08 -0500820 int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
821 int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
822 int specificCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
823
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800824 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
Christopher Tate38f55eb2017-02-14 14:43:49 -0800825 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT |
chen xuf9db49f2019-03-31 23:04:42 -0700826 Intent.FLAG_RECEIVER_FOREGROUND);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800827 if (addSubIdExtra) {
rambowangd63ba342022-10-02 11:21:08 -0500828 int simApplicationState = getSimApplicationStateForPhone(phoneId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800829 // Include subId/carrier id extra only if SIM records are loaded
830 if (simApplicationState != TelephonyManager.SIM_STATE_UNKNOWN
831 && simApplicationState != TelephonyManager.SIM_STATE_NOT_READY) {
rambowangd63ba342022-10-02 11:21:08 -0500832 subId = SubscriptionManager.getSubscriptionId(phoneId);
833 carrierId = getCarrierIdForPhoneId(phoneId);
834 specificCarrierId = getSpecificCarrierIdForPhoneId(phoneId);
835 intent.putExtra(TelephonyManager.EXTRA_SPECIFIC_CARRIER_ID, specificCarrierId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800836 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, phoneId);
rambowangd63ba342022-10-02 11:21:08 -0500837 intent.putExtra(TelephonyManager.EXTRA_CARRIER_ID, carrierId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800838 }
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800839 }
Amit Mahajanb33bcda2018-01-24 12:56:44 -0800840 intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, phoneId);
Sarah Chin807d5c62020-03-30 17:21:09 -0700841 intent.putExtra(CarrierConfigManager.EXTRA_REBROADCAST_ON_UNLOCK,
842 mFromSystemUnlocked[phoneId]);
rambowangd63ba342022-10-02 11:21:08 -0500843
844 TelephonyRegistryManager trm = mContext.getSystemService(TelephonyRegistryManager.class);
845 // Unlike broadcast, we wouldn't notify registrants on carrier config change when device is
846 // unlocked. Only real carrier config change will send the notification to registrants.
847 if (trm != null && !mFromSystemUnlocked[phoneId]) {
848 trm.notifyCarrierConfigChanged(phoneId, subId, carrierId, specificCarrierId);
849 }
850
Meng Wang97a6a462020-01-23 16:22:16 -0800851 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
rambowangd63ba342022-10-02 11:21:08 -0500852
Jack Yu00ece8c2022-11-19 22:29:12 -0800853 if (SubscriptionManager.isValidSubscriptionId(subId)) {
854 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId + ", subId=" + subId);
Jack Yue9e95be2020-03-22 10:56:06 -0700855 } else {
856 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId);
857 }
Junda Liu03aad762017-07-21 13:32:17 -0700858 mHasSentConfigChange[phoneId] = true;
Sarah Chin807d5c62020-03-30 17:21:09 -0700859 mFromSystemUnlocked[phoneId] = false;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800860 }
861
rambowangd63ba342022-10-02 11:21:08 -0500862 private int getSimApplicationStateForPhone(int phoneId) {
863 int simApplicationState = TelephonyManager.SIM_STATE_UNKNOWN;
864 int subId = SubscriptionManager.getSubscriptionId(phoneId);
865 if (SubscriptionManager.isValidSubscriptionId(subId)) {
866 TelephonyManager telMgr = TelephonyManager.from(mContext)
867 .createForSubscriptionId(subId);
868 simApplicationState = telMgr.getSimApplicationState();
869 }
870 return simApplicationState;
871 }
872
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800873 /** Binds to the default or carrier config app. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000874 private boolean bindToConfigPackage(@NonNull String pkgName, int phoneId, int eventId) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800875 logdWithLocalLog("Binding to " + pkgName + " for phone " + phoneId);
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700876 Intent carrierService = new Intent(CarrierService.CARRIER_SERVICE_INTERFACE);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700877 carrierService.setPackage(pkgName);
Jayachandran C645ec612020-01-10 10:30:25 -0800878 CarrierServiceConnection serviceConnection = new CarrierServiceConnection(
879 phoneId, pkgName, eventId);
880 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
881 mServiceConnectionForNoSimConfig[phoneId] = serviceConnection;
882 } else {
883 mServiceConnection[phoneId] = serviceConnection;
884 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800885 try {
Jayachandran C645ec612020-01-10 10:30:25 -0800886 if (mContext.bindService(carrierService, serviceConnection,
Jordan Liu178430d2020-02-10 14:32:15 -0800887 Context.BIND_AUTO_CREATE)) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700888 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
889 mServiceBoundForNoSimConfig[phoneId] = true;
890 } else {
891 mServiceBound[phoneId] = true;
892 }
Jordan Liu178430d2020-02-10 14:32:15 -0800893 return true;
894 } else {
895 return false;
896 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800897 } catch (SecurityException ex) {
898 return false;
899 }
900 }
901
Rambo Wang7e3bc122021-03-23 09:24:38 -0700902 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000903 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -0700904 /* package */ CarrierIdentifier getCarrierIdentifierForPhoneId(int phoneId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800905 String mcc = "";
906 String mnc = "";
907 String imsi = "";
908 String gid1 = "";
909 String gid2 = "";
910 String spn = TelephonyManager.from(mContext).getSimOperatorNameForPhone(phoneId);
911 String simOperator = TelephonyManager.from(mContext).getSimOperatorNumericForPhone(phoneId);
chen xu02581692018-11-11 19:03:44 -0800912 int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
chen xua31f22b2019-03-06 15:28:50 -0800913 int specificCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
Jonathan Basseri1fa437c2015-04-20 11:08:18 -0700914 // A valid simOperator should be 5 or 6 digits, depending on the length of the MNC.
915 if (simOperator != null && simOperator.length() >= 3) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800916 mcc = simOperator.substring(0, 3);
917 mnc = simOperator.substring(3);
918 }
919 Phone phone = PhoneFactory.getPhone(phoneId);
920 if (phone != null) {
921 imsi = phone.getSubscriberId();
922 gid1 = phone.getGroupIdLevel1();
Junda Liu73183532015-05-14 13:55:40 -0700923 gid2 = phone.getGroupIdLevel2();
chen xu02581692018-11-11 19:03:44 -0800924 carrierId = phone.getCarrierId();
chen xua31f22b2019-03-06 15:28:50 -0800925 specificCarrierId = phone.getSpecificCarrierId();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800926 }
chen xua31f22b2019-03-06 15:28:50 -0800927 return new CarrierIdentifier(mcc, mnc, spn, imsi, gid1, gid2, carrierId, specificCarrierId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800928 }
929
Rambo Wangf7c214a2022-03-17 12:36:22 -0700930 /** Returns the package name of a privileged carrier app, or null if there is none. */
Nathan Harold1122e3d2021-01-22 15:45:24 -0800931 @Nullable
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700932 private String getCarrierPackageForPhoneId(int phoneId) {
Nazanin1adf4562021-03-29 15:35:30 -0700933 final long token = Binder.clearCallingIdentity();
934 try {
Rambo Wangf7c214a2022-03-17 12:36:22 -0700935 return TelephonyManager.from(mContext)
936 .getCarrierServicePackageNameForLogicalSlot(phoneId);
Nazanin1adf4562021-03-29 15:35:30 -0700937 } finally {
938 Binder.restoreCallingIdentity(token);
939 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700940 }
941
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000942 @Nullable
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700943 private String getIccIdForPhoneId(int phoneId) {
944 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
945 return null;
946 }
947 Phone phone = PhoneFactory.getPhone(phoneId);
948 if (phone == null) {
949 return null;
950 }
951 return phone.getIccSerialNumber();
952 }
953
chen xu02581692018-11-11 19:03:44 -0800954 /**
chen xua31f22b2019-03-06 15:28:50 -0800955 * Get the sim specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}
chen xu02581692018-11-11 19:03:44 -0800956 */
chen xua31f22b2019-03-06 15:28:50 -0800957 private int getSpecificCarrierIdForPhoneId(int phoneId) {
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700958 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
chen xu02581692018-11-11 19:03:44 -0800959 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700960 }
961 Phone phone = PhoneFactory.getPhone(phoneId);
962 if (phone == null) {
chen xu02581692018-11-11 19:03:44 -0800963 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700964 }
chen xua31f22b2019-03-06 15:28:50 -0800965 return phone.getSpecificCarrierId();
chen xu02581692018-11-11 19:03:44 -0800966 }
967
968 /**
969 * Get the sim carrier id {@link TelephonyManager#getSimCarrierId() }
970 */
971 private int getCarrierIdForPhoneId(int phoneId) {
972 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
973 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700974 }
chen xu02581692018-11-11 19:03:44 -0800975 Phone phone = PhoneFactory.getPhone(phoneId);
976 if (phone == null) {
977 return TelephonyManager.UNKNOWN_CARRIER_ID;
978 }
979 return phone.getCarrierId();
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700980 }
981
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700982 /**
983 * Writes a bundle to an XML file.
984 *
chen xu02581692018-11-11 19:03:44 -0800985 * The bundle will be written to a file named after the package name, ICCID and
chen xua31f22b2019-03-06 15:28:50 -0800986 * specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}. the same carrier
chen xu02581692018-11-11 19:03:44 -0800987 * should have a single copy of XML file named after carrier id. However, it's still possible
988 * that platform doesn't recognize the current sim carrier, we will use iccid + carrierid as
989 * the canonical file name. carrierid can also handle the cases SIM OTA resolves to different
990 * carrier while iccid remains the same.
991 *
992 * The file can be restored later with {@link @restoreConfigFromXml}. The XML output will
993 * include the bundle and the current version of the specified package.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700994 *
995 * In case of errors or invalid input, no file will be written.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700996 *
Jayachandran C645ec612020-01-10 10:30:25 -0800997 * @param packageName the name of the package from which we fetched this bundle.
998 * @param extraString An extra string to be used in the XML file name.
999 * @param phoneId the phone ID.
1000 * @param carrierId contains all carrier-identifying information.
1001 * @param config the bundle to be written. Null will be treated as an empty bundle.
1002 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001003 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001004 private void saveConfigToXml(@Nullable String packageName, @NonNull String extraString,
1005 int phoneId, @Nullable CarrierIdentifier carrierId, @NonNull PersistableBundle config,
1006 boolean isNoSimConfig) {
Jayachandran C645ec612020-01-10 10:30:25 -08001007 if (packageName == null) {
1008 loge("Cannot save config with null packageName");
Yuchen Dongc15afed2018-04-26 17:05:22 +08001009 return;
1010 }
1011
Jayachandran C645ec612020-01-10 10:30:25 -08001012 String fileName;
1013 if (isNoSimConfig) {
1014 fileName = getFilenameForNoSimConfig(packageName);
1015 } else {
Jack Yuf5badd92022-12-08 00:50:53 -08001016 if (TelephonyManager.getSimStateForSlotIndex(phoneId)
Jayachandran C645ec612020-01-10 10:30:25 -08001017 != TelephonyManager.SIM_STATE_LOADED) {
1018 loge("Skip save config because SIM records are not loaded.");
1019 return;
1020 }
1021
1022 final String iccid = getIccIdForPhoneId(phoneId);
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001023 final int cid = carrierId != null ? carrierId.getSpecificCarrierId()
1024 : TelephonyManager.UNKNOWN_CARRIER_ID;
Jayachandran C645ec612020-01-10 10:30:25 -08001025 if (iccid == null) {
1026 loge("Cannot save config with null iccid.");
1027 return;
1028 }
1029 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001030 }
Jayachandran C645ec612020-01-10 10:30:25 -08001031
Junda Liu02596502016-11-15 13:46:43 -08001032 // b/32668103 Only save to file if config isn't empty.
1033 // In case of failure, not caching an empty bundle will
1034 // try loading config again on next power on or sim loaded.
1035 // Downside is for genuinely empty bundle, will bind and load
1036 // on every power on.
1037 if (config == null || config.isEmpty()) {
1038 return;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001039 }
1040
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001041 final String version = getPackageVersion(packageName);
1042 if (version == null) {
1043 loge("Failed to get package version for: " + packageName);
1044 return;
1045 }
1046
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001047 logdWithLocalLog(
1048 "Save config to xml, packagename: " + packageName + " phoneId: " + phoneId);
chen xudb04c292019-03-26 17:01:15 -07001049
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001050 FileOutputStream outFile = null;
1051 try {
Jayachandran C645ec612020-01-10 10:30:25 -08001052 outFile = new FileOutputStream(new File(mContext.getFilesDir(), fileName));
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001053 config.putString(KEY_VERSION, version);
1054 config.writeToStream(outFile);
1055 outFile.flush();
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001056 outFile.close();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001057 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001058 loge(e.toString());
1059 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001060 }
1061
Rambo Wang7e3bc122021-03-23 09:24:38 -07001062 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001063 /* package */ void saveConfigToXml(@Nullable String packageName, @NonNull String extraString,
1064 int phoneId, @NonNull CarrierIdentifier carrierId, @NonNull PersistableBundle config) {
Jayachandran C645ec612020-01-10 10:30:25 -08001065 saveConfigToXml(packageName, extraString, phoneId, carrierId, config, false);
1066 }
1067
Rambo Wang7e3bc122021-03-23 09:24:38 -07001068 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001069 /* package */ void saveNoSimConfigToXml(@Nullable String packageName,
1070 @NonNull PersistableBundle config) {
Jayachandran C645ec612020-01-10 10:30:25 -08001071 saveConfigToXml(packageName, "", -1, null, config, true);
1072 }
1073
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001074 /**
1075 * Reads a bundle from an XML file.
1076 *
1077 * This restores a bundle that was written with {@link #saveConfigToXml}. This returns the saved
Yuchen Dongc15afed2018-04-26 17:05:22 +08001078 * config bundle for the given package and phone ID.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001079 *
1080 * In case of errors, or if the saved config is from a different package version than the
1081 * current version, then null will be returned.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001082 *
Jayachandran C645ec612020-01-10 10:30:25 -08001083 * @param packageName the name of the package from which we fetched this bundle.
1084 * @param extraString An extra string to be used in the XML file name.
1085 * @param phoneId the phone ID.
1086 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001087 * @return the bundle from the XML file. Returns null if there is no saved config, the saved
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001088 * version does not match, or reading config fails.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001089 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001090 @Nullable
1091 private PersistableBundle restoreConfigFromXml(@Nullable String packageName,
1092 @NonNull String extraString, int phoneId, boolean isNoSimConfig) {
Jayachandran C645ec612020-01-10 10:30:25 -08001093 if (packageName == null) {
1094 loge("Cannot restore config with null packageName");
1095 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001096 final String version = getPackageVersion(packageName);
1097 if (version == null) {
1098 loge("Failed to get package version for: " + packageName);
1099 return null;
1100 }
Yuchen Dongc15afed2018-04-26 17:05:22 +08001101
Jayachandran C645ec612020-01-10 10:30:25 -08001102 String fileName;
arunvoddu664c36a2021-10-11 20:09:28 +00001103 String iccid = null;
Jayachandran C645ec612020-01-10 10:30:25 -08001104 if (isNoSimConfig) {
1105 fileName = getFilenameForNoSimConfig(packageName);
1106 } else {
Jack Yuf5badd92022-12-08 00:50:53 -08001107 if (TelephonyManager.getSimStateForSlotIndex(phoneId)
Jayachandran C645ec612020-01-10 10:30:25 -08001108 != TelephonyManager.SIM_STATE_LOADED) {
1109 loge("Skip restore config because SIM records are not loaded.");
1110 return null;
1111 }
1112
arunvoddu664c36a2021-10-11 20:09:28 +00001113 iccid = getIccIdForPhoneId(phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -08001114 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1115 if (iccid == null) {
1116 loge("Cannot restore config with null iccid.");
1117 return null;
1118 }
1119 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001120 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001121
1122 PersistableBundle restoredBundle = null;
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001123 File file = null;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001124 FileInputStream inFile = null;
1125 try {
Jayachandran C645ec612020-01-10 10:30:25 -08001126 file = new File(mContext.getFilesDir(),fileName);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001127 inFile = new FileInputStream(file);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001128
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001129 restoredBundle = PersistableBundle.readFromStream(inFile);
1130 String savedVersion = restoredBundle.getString(KEY_VERSION);
1131 restoredBundle.remove(KEY_VERSION);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001132
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001133 if (!version.equals(savedVersion)) {
1134 loge("Saved version mismatch: " + version + " vs " + savedVersion);
1135 restoredBundle = null;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001136 }
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001137
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001138 inFile.close();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001139 } catch (FileNotFoundException e) {
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001140 // Missing file is normal occurrence that might occur with a new sim or when restoring
1141 // an override file during boot and should not be treated as an error.
arunvoddu664c36a2021-10-11 20:09:28 +00001142 if (file != null) {
1143 if (isNoSimConfig) {
1144 logd("File not found: " + file.getPath());
1145 } else {
1146 String filePath = file.getPath();
1147 filePath = getFilePathForLogging(filePath, iccid);
1148 logd("File not found : " + filePath);
1149 }
1150 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001151 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001152 loge(e.toString());
1153 }
1154
1155 return restoredBundle;
1156 }
1157
arunvoddu664c36a2021-10-11 20:09:28 +00001158 /**
1159 * This method will mask most part of iccid in the filepath for logging on userbuild
1160 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001161 @NonNull
1162 private String getFilePathForLogging(@Nullable String filePath, @Nullable String iccid) {
arunvoddu664c36a2021-10-11 20:09:28 +00001163 // If loggable then return with actual file path
1164 if (Rlog.isLoggable(LOG_TAG, Log.VERBOSE)) {
1165 return filePath;
1166 }
1167 String path = filePath;
1168 int length = (iccid != null) ? iccid.length() : 0;
1169 if (length > 5 && filePath != null) {
1170 path = filePath.replace(iccid.substring(5), "***************");
1171 }
1172 return path;
1173 }
1174
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001175 @Nullable
1176 private PersistableBundle restoreConfigFromXml(@Nullable String packageName,
1177 @NonNull String extraString, int phoneId) {
Jayachandran C645ec612020-01-10 10:30:25 -08001178 return restoreConfigFromXml(packageName, extraString, phoneId, false);
1179 }
1180
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001181 @Nullable
1182 private PersistableBundle restoreNoSimConfigFromXml(@Nullable String packageName) {
Jayachandran C645ec612020-01-10 10:30:25 -08001183 return restoreConfigFromXml(packageName, "", -1, true);
1184 }
1185
Junda Liu8a8a53a2015-05-15 16:19:57 -07001186 /**
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001187 * Clears cached carrier config.
1188 * This deletes all saved XML files associated with the given package name. If packageName is
1189 * null, then it deletes all saved XML files.
1190 *
1191 * @param packageName the name of a carrier package, or null if all cached config should be
1192 * cleared.
1193 * @return true iff one or more files were deleted.
Junda Liu8a8a53a2015-05-15 16:19:57 -07001194 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001195 private boolean clearCachedConfigForPackage(@Nullable final String packageName) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001196 File dir = mContext.getFilesDir();
1197 File[] packageFiles = dir.listFiles(new FilenameFilter() {
1198 public boolean accept(File dir, String filename) {
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001199 if (packageName != null) {
1200 return filename.startsWith("carrierconfig-" + packageName + "-");
1201 } else {
1202 return filename.startsWith("carrierconfig-");
1203 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001204 }
1205 });
Junda Liu8a8a53a2015-05-15 16:19:57 -07001206 if (packageFiles == null || packageFiles.length < 1) return false;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001207 for (File f : packageFiles) {
arunvoddub7c6e8e2022-09-05 15:48:06 +00001208 logd("Deleting " + getFilePathForLogging(f.getName()));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001209 f.delete();
1210 }
Junda Liu8a8a53a2015-05-15 16:19:57 -07001211 return true;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001212 }
1213
arunvoddub7c6e8e2022-09-05 15:48:06 +00001214 private String getFilePathForLogging(String filePath) {
1215 if (!TextUtils.isEmpty(filePath)) {
1216 String[] fileTokens = filePath.split("-");
1217 if (fileTokens != null && fileTokens.length > 2) {
1218 String iccid = fileTokens[fileTokens.length -2];
1219 return getFilePathForLogging(filePath, iccid);
1220 }
1221 return filePath;
1222 }
1223 return filePath;
1224 }
1225
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001226 /** Builds a canonical file name for a config file. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001227 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001228 private static String getFilenameForConfig(
1229 @NonNull String packageName, @NonNull String extraString,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001230 @NonNull String iccid, int cid) {
chen xu02581692018-11-11 19:03:44 -08001231 // the same carrier should have a single copy of XML file named after carrier id.
1232 // However, it's still possible that platform doesn't recognize the current sim carrier,
1233 // we will use iccid + carrierid as the canonical file name. carrierid can also handle the
1234 // cases SIM OTA resolves to different carrier while iccid remains the same.
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001235 return "carrierconfig-" + packageName + extraString + "-" + iccid + "-" + cid + ".xml";
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001236 }
1237
Jayachandran C645ec612020-01-10 10:30:25 -08001238 /** Builds a canonical file name for no SIM config file. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001239 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001240 private String getFilenameForNoSimConfig(@NonNull String packageName) {
1241 return "carrierconfig-" + packageName + "-" + "nosim" + ".xml";
1242 }
1243
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001244 /** Return the current version code of a package, or null if the name is not found. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001245 @Nullable
1246 private String getPackageVersion(@NonNull String packageName) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001247 try {
1248 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
Dianne Hackbornb76ab202017-11-28 17:44:50 -08001249 return Long.toString(info.getLongVersionCode());
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001250 } catch (PackageManager.NameNotFoundException e) {
1251 return null;
1252 }
1253 }
1254
Jonathan Basseri65273c82017-07-25 15:08:42 -07001255 /**
1256 * Read up to date config.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001257 *
1258 * This reads config bundles for the given phoneId. That means getting the latest bundle from
1259 * the default app and a privileged carrier app, if present. This will not bind to an app if we
1260 * have a saved config file to use instead.
1261 */
1262 private void updateConfigForPhoneId(int phoneId) {
Jonathan Basseri65273c82017-07-25 15:08:42 -07001263 mHandler.sendMessage(mHandler.obtainMessage(EVENT_DO_FETCH_DEFAULT, phoneId, -1));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001264 }
1265
Malcolm Chen5ea18532019-10-24 19:55:44 -07001266 private void onMultiSimConfigChanged() {
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001267 int oldNumPhones = mNumPhones;
1268 mNumPhones = TelephonyManager.from(mContext).getActiveModemCount();
1269 if (mNumPhones == oldNumPhones) {
1270 return;
1271 }
1272 logdWithLocalLog("mNumPhones change from " + oldNumPhones + " to " + mNumPhones);
1273
Rambo Wanga27fbe52022-04-12 19:09:07 +00001274 // If DS -> SS switch, release the resources BEFORE truncating the arrays to avoid leaking
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001275 for (int phoneId = mNumPhones; phoneId < oldNumPhones; phoneId++) {
1276 if (mServiceConnection[phoneId] != null) {
1277 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
1278 }
1279 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
1280 unbindIfBoundForNoSimConfig(mContext, mServiceConnectionForNoSimConfig[phoneId],
1281 phoneId);
1282 }
1283 }
1284
Rambo Wanga27fbe52022-04-12 19:09:07 +00001285 // The phone to slot mapping may change, unregister here and re-register callbacks later
1286 for (int phoneId = 0; phoneId < oldNumPhones; phoneId++) {
1287 if (mCarrierServiceChangeCallbacks[phoneId] != null) {
1288 TelephonyManager.from(mContext).unregisterCarrierPrivilegesCallback(
1289 mCarrierServiceChangeCallbacks[phoneId]);
1290 }
1291 }
1292
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001293 // Copy the original arrays, truncate or padding with zeros (if necessary) to new length
1294 mConfigFromDefaultApp = Arrays.copyOf(mConfigFromDefaultApp, mNumPhones);
1295 mConfigFromCarrierApp = Arrays.copyOf(mConfigFromCarrierApp, mNumPhones);
1296 mPersistentOverrideConfigs = Arrays.copyOf(mPersistentOverrideConfigs, mNumPhones);
1297 mOverrideConfigs = Arrays.copyOf(mOverrideConfigs, mNumPhones);
1298 mServiceConnection = Arrays.copyOf(mServiceConnection, mNumPhones);
1299 mServiceConnectionForNoSimConfig =
1300 Arrays.copyOf(mServiceConnectionForNoSimConfig, mNumPhones);
1301 mServiceBound = Arrays.copyOf(mServiceBound, mNumPhones);
1302 mServiceBoundForNoSimConfig = Arrays.copyOf(mServiceBoundForNoSimConfig, mNumPhones);
1303 mHasSentConfigChange = Arrays.copyOf(mHasSentConfigChange, mNumPhones);
1304 mFromSystemUnlocked = Arrays.copyOf(mFromSystemUnlocked, mNumPhones);
Rambo Wanga27fbe52022-04-12 19:09:07 +00001305 mCarrierServiceChangeCallbacks = Arrays.copyOf(mCarrierServiceChangeCallbacks, mNumPhones);
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001306
Rambo Wanga27fbe52022-04-12 19:09:07 +00001307 // Load the config for all the phones and re-register callback AFTER padding the arrays.
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001308 for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
1309 updateConfigForPhoneId(phoneId);
Rambo Wanga27fbe52022-04-12 19:09:07 +00001310 mCarrierServiceChangeCallbacks[phoneId] = new CarrierServiceChangeCallback(phoneId);
1311 TelephonyManager.from(mContext).registerCarrierPrivilegesCallback(phoneId,
1312 new HandlerExecutor(mHandler), mCarrierServiceChangeCallbacks[phoneId]);
Malcolm Chen5ea18532019-10-24 19:55:44 -07001313 }
1314 }
1315
Hall Liu506724b2018-10-22 18:16:14 -07001316 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001317 @NonNull
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001318 public PersistableBundle getConfigForSubId(int subscriptionId, @NonNull String callingPackage) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001319 return getConfigForSubIdWithFeature(subscriptionId, callingPackage, null);
Philip P. Moltmann9797cbb2020-01-07 13:45:00 -08001320 }
1321
1322 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001323 @NonNull
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001324 public PersistableBundle getConfigForSubIdWithFeature(int subscriptionId,
1325 @NonNull String callingPackage, @Nullable String callingFeatureId) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001326 if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(mContext, subscriptionId,
1327 callingPackage, callingFeatureId, "getCarrierConfig")) {
Rambo Wang42026112021-04-07 20:57:28 +00001328 return new PersistableBundle();
Amit Mahajan40b3fa52015-07-14 10:27:19 -07001329 }
Jeff Davidsona8e4e242018-03-15 17:16:18 -07001330
Rambo Wangd2b004b2021-03-30 10:10:23 -07001331 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001332 PersistableBundle retConfig = CarrierConfigManager.getDefaultConfig();
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001333 if (SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001334 PersistableBundle config = mConfigFromDefaultApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001335 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001336 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001337 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001338 config = mConfigFromCarrierApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001339 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001340 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001341 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001342 config = mPersistentOverrideConfigs[phoneId];
1343 if (config != null) {
1344 retConfig.putAll(config);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001345 }
Hall Liu506724b2018-10-22 18:16:14 -07001346 config = mOverrideConfigs[phoneId];
1347 if (config != null) {
1348 retConfig.putAll(config);
Hall Liu506724b2018-10-22 18:16:14 -07001349 }
Nathan Harold1122e3d2021-01-22 15:45:24 -08001350 // Ignore the theoretical case of the default app not being present since that won't
1351 // work in CarrierConfigLoader today.
1352 final boolean allConfigsApplied =
1353 (mConfigFromCarrierApp[phoneId] != null
1354 || getCarrierPackageForPhoneId(phoneId) == null)
1355 && mConfigFromDefaultApp[phoneId] != null;
1356 retConfig.putBoolean(
1357 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, allConfigsApplied);
Jayachandran C645ec612020-01-10 10:30:25 -08001358 } else {
1359 if (mNoSimConfig != null) {
1360 retConfig.putAll(mNoSimConfig);
1361 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001362 }
1363 return retConfig;
1364 }
1365
1366 @Override
rambowang14757c22022-10-03 11:54:56 -05001367 @NonNull
1368 public PersistableBundle getConfigSubsetForSubIdWithFeature(int subscriptionId,
1369 @NonNull String callingPackage, @Nullable String callingFeatureId,
1370 @NonNull String[] keys) {
1371 Objects.requireNonNull(callingPackage, "Calling package must be non-null");
1372 Objects.requireNonNull(keys, "Config keys must be non-null");
1373 enforceCallerIsSystemOrRequestingPackage(callingPackage);
1374
1375 // Permission check is performed inside and an empty bundle will return on failure.
1376 // No SecurityException thrown here since most clients expect to retrieve the overridden
1377 // value if present or use default one if not
1378 PersistableBundle allConfigs = getConfigForSubIdWithFeature(subscriptionId, callingPackage,
1379 callingFeatureId);
1380 if (allConfigs.isEmpty()) {
1381 return allConfigs;
1382 }
1383 for (String key : keys) {
1384 Objects.requireNonNull(key, "Config key must be non-null");
rambowang14757c22022-10-03 11:54:56 -05001385 }
1386
1387 PersistableBundle configSubset = new PersistableBundle(
1388 keys.length + CONFIG_SUBSET_METADATA_KEYS.length);
1389 for (String carrierConfigKey : keys) {
1390 Object value = allConfigs.get(carrierConfigKey);
rambowangb49e90f2022-12-13 18:29:06 -06001391 if (value == null) {
1392 // Filter out keys without values.
1393 // In history, many AOSP or OEMs/carriers private configs didn't provide default
1394 // values. We have to continue supporting them for now. See b/261776046 for details.
1395 continue;
1396 }
rambowang14757c22022-10-03 11:54:56 -05001397 // Config value itself could be PersistableBundle which requires different API to put
1398 if (value instanceof PersistableBundle) {
1399 configSubset.putPersistableBundle(carrierConfigKey, (PersistableBundle) value);
1400 } else {
1401 configSubset.putObject(carrierConfigKey, value);
1402 }
1403 }
1404
1405 // Configs in CONFIG_SUBSET_ALWAYS_INCLUDED_KEYS should always be included
1406 for (String generalKey : CONFIG_SUBSET_METADATA_KEYS) {
1407 configSubset.putObject(generalKey, allConfigs.get(generalKey));
1408 }
1409
1410 return configSubset;
1411 }
1412
mattgilbride5b6b7182023-04-03 18:56:44 +00001413 @android.annotation.EnforcePermission(android.Manifest.permission.MODIFY_PHONE_STATE)
rambowang14757c22022-10-03 11:54:56 -05001414 @Override
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001415 public void overrideConfig(int subscriptionId, @Nullable PersistableBundle overrides,
1416 boolean persistent) {
mattgilbride5b6b7182023-04-03 18:56:44 +00001417 overrideConfig_enforcePermission();
Hall Liu506724b2018-10-22 18:16:14 -07001418 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1419 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001420 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
Rambo Wangd2b004b2021-03-30 10:10:23 -07001421 throw new IllegalArgumentException(
1422 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
Hall Liu506724b2018-10-22 18:16:14 -07001423 }
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001424 // Post to run on handler thread on which all states should be confined.
1425 mHandler.post(() -> {
1426 overrideConfig(mOverrideConfigs, phoneId, overrides);
Hall Liu506724b2018-10-22 18:16:14 -07001427
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001428 if (persistent) {
1429 overrideConfig(mPersistentOverrideConfigs, phoneId, overrides);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001430
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001431 if (overrides != null) {
1432 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
1433 saveConfigToXml(mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION,
1434 phoneId,
1435 carrierId, mPersistentOverrideConfigs[phoneId]);
1436 } else {
1437 final String iccid = getIccIdForPhoneId(phoneId);
1438 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1439 String fileName = getFilenameForConfig(mPlatformCarrierConfigPackage,
1440 OVERRIDE_PACKAGE_ADDITION, iccid, cid);
1441 File fileToDelete = new File(mContext.getFilesDir(), fileName);
1442 fileToDelete.delete();
1443 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001444 }
Jack Yue37dd262022-12-16 11:53:37 -08001445 updateSubscriptionDatabase(phoneId);
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001446 });
Hall Liu506724b2018-10-22 18:16:14 -07001447 }
1448
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001449 private void overrideConfig(@NonNull PersistableBundle[] currentOverrides, int phoneId,
1450 @Nullable PersistableBundle overrides) {
1451 if (overrides == null) {
Rambo Wang42026112021-04-07 20:57:28 +00001452 currentOverrides[phoneId] = new PersistableBundle();
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001453 } else if (currentOverrides[phoneId] == null) {
1454 currentOverrides[phoneId] = overrides;
1455 } else {
1456 currentOverrides[phoneId].putAll(overrides);
1457 }
1458 }
1459
Hall Liu506724b2018-10-22 18:16:14 -07001460 @Override
Rambo Wangd2b004b2021-03-30 10:10:23 -07001461 public void notifyConfigChangedForSubId(int subscriptionId) {
Jordan Liud7d57fe2019-04-16 12:29:43 -07001462 // Requires the calling app to be either a carrier privileged app for this subId or
Junda Liufbd2bcb2016-06-15 11:15:42 -07001463 // system privileged app with MODIFY_PHONE_STATE permission.
Rambo Wangd2b004b2021-03-30 10:10:23 -07001464 TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(mContext,
1465 subscriptionId, "Require carrier privileges or MODIFY_PHONE_STATE permission.");
1466
1467 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1468 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
1469 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
1470 throw new IllegalArgumentException(
1471 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
1472 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001473
1474 // This method should block until deleting has completed, so that an error which prevents us
1475 // from clearing the cache is passed back to the carrier app. With the files successfully
1476 // deleted, this can return and we will eventually bind to the carrier app.
Jordan Liud7d57fe2019-04-16 12:29:43 -07001477 String callingPackageName = mContext.getPackageManager().getNameForUid(
1478 Binder.getCallingUid());
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001479 clearCachedConfigForPackage(callingPackageName);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001480 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001481 }
1482
mattgilbride5b6b7182023-04-03 18:56:44 +00001483 @android.annotation.EnforcePermission(android.Manifest.permission.MODIFY_PHONE_STATE)
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001484 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001485 public void updateConfigForPhoneId(int phoneId, @NonNull String simState) {
mattgilbride5b6b7182023-04-03 18:56:44 +00001486 updateConfigForPhoneId_enforcePermission();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001487 logdWithLocalLog("Update config for phoneId: " + phoneId + " simState: " + simState);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001488 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001489 throw new IllegalArgumentException("Invalid phoneId: " + phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001490 }
1491 // requires Java 7 for switch on string.
1492 switch (simState) {
1493 case IccCardConstants.INTENT_VALUE_ICC_ABSENT:
1494 case IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR:
Junda Liu6f5fddf2016-05-24 16:14:41 -07001495 case IccCardConstants.INTENT_VALUE_ICC_CARD_RESTRICTED:
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001496 case IccCardConstants.INTENT_VALUE_ICC_UNKNOWN:
Malcolm Chendb66de12019-12-09 18:57:07 -08001497 case IccCardConstants.INTENT_VALUE_ICC_NOT_READY:
Junda Liu9f2d2712015-05-15 14:22:45 -07001498 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CLEAR_CONFIG, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001499 break;
1500 case IccCardConstants.INTENT_VALUE_ICC_LOADED:
1501 case IccCardConstants.INTENT_VALUE_ICC_LOCKED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001502 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001503 break;
1504 }
1505 }
1506
mattgilbride5b6b7182023-04-03 18:56:44 +00001507 @android.annotation.EnforcePermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
Junda Liu43d723a2015-05-12 17:23:45 -07001508 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001509 @NonNull
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001510 public String getDefaultCarrierServicePackageName() {
mattgilbride5b6b7182023-04-03 18:56:44 +00001511 getDefaultCarrierServicePackageName_enforcePermission();
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001512 return mPlatformCarrierConfigPackage;
1513 }
1514
Rambo Wang7e3bc122021-03-23 09:24:38 -07001515 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001516 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -07001517 /* package */ Handler getHandler() {
1518 return mHandler;
1519 }
1520
1521 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001522 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001523 /* package */ PersistableBundle getConfigFromDefaultApp(int phoneId) {
1524 return mConfigFromDefaultApp[phoneId];
1525 }
1526
1527 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001528 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001529 /* package */ PersistableBundle getConfigFromCarrierApp(int phoneId) {
1530 return mConfigFromCarrierApp[phoneId];
1531 }
1532
1533 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001534 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -07001535 /* package */ PersistableBundle getNoSimConfig() {
1536 return mNoSimConfig;
1537 }
1538
1539 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001540 @Nullable
Rambo Wang7e3bc122021-03-23 09:24:38 -07001541 /* package */ PersistableBundle getOverrideConfig(int phoneId) {
1542 return mOverrideConfigs[phoneId];
1543 }
1544
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001545 // TODO(b/185129900): always call unbindService after bind, no matter if it succeeded
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001546 private void unbindIfBound(@NonNull Context context, @NonNull CarrierServiceConnection conn,
Rambo Wangb0f3e2f2021-10-28 12:40:12 -07001547 int phoneId) {
1548 if (mServiceBound[phoneId]) {
1549 mServiceBound[phoneId] = false;
1550 context.unbindService(conn);
1551 }
1552 }
1553
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001554 private void unbindIfBoundForNoSimConfig(@NonNull Context context,
1555 @NonNull CarrierServiceConnection conn, int phoneId) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -07001556 if (mServiceBoundForNoSimConfig[phoneId]) {
1557 mServiceBoundForNoSimConfig[phoneId] = false;
Jayachandran C645ec612020-01-10 10:30:25 -08001558 context.unbindService(conn);
1559 }
1560 }
1561
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001562 /**
Rambo Wang610fdf62021-03-08 21:37:11 -08001563 * Returns a boxed Integer object for phoneId, services as message token to distinguish messages
1564 * with same code when calling {@link Handler#removeMessages(int, Object)}.
1565 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001566 @NonNull
Rambo Wang610fdf62021-03-08 21:37:11 -08001567 private Integer getMessageToken(int phoneId) {
1568 if (phoneId < -128 || phoneId > 127) {
1569 throw new IllegalArgumentException("phoneId should be in range [-128, 127], inclusive");
1570 }
1571 // Integer#valueOf guarantees the integers within [-128, 127] are cached and thus memory
1572 // comparison (==) returns true for the same integer.
1573 return Integer.valueOf(phoneId);
1574 }
1575
1576 /**
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001577 * If {@code args} contains {@link #DUMP_ARG_REQUESTING_PACKAGE} and a following package name,
1578 * we'll also call {@link IBinder#dump} on the default carrier service (if bound) and the
1579 * specified carrier service (if bound). Typically, this is done for connectivity bug reports
1580 * where we don't call {@code dumpsys activity service all-non-platform} because that contains
1581 * too much info, but we still want to let carrier apps include their diagnostics.
1582 */
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001583 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001584 public void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter pw, @NonNull String[] args) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001585 IndentingPrintWriter indentPW = new IndentingPrintWriter(pw, " ");
Junda Liu43d723a2015-05-12 17:23:45 -07001586 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1587 != PackageManager.PERMISSION_GRANTED) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001588 indentPW.println("Permission Denial: can't dump carrierconfig from from pid="
Junda Liu43d723a2015-05-12 17:23:45 -07001589 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
1590 return;
1591 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001592 String requestingPackage = null;
1593 int requestingPackageIndex = ArrayUtils.indexOf(args, DUMP_ARG_REQUESTING_PACKAGE);
1594 if (requestingPackageIndex >= 0 && requestingPackageIndex < args.length - 1
1595 && !TextUtils.isEmpty(args[requestingPackageIndex + 1])) {
1596 requestingPackage = args[requestingPackageIndex + 1];
1597 // Throws a SecurityException if the caller is impersonating another app in an effort to
1598 // dump extra info (which may contain PII the caller doesn't have a right to).
1599 enforceCallerIsSystemOrRequestingPackage(requestingPackage);
1600 }
1601
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001602 indentPW.println("CarrierConfigLoader: " + this);
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001603 for (int i = 0; i < mNumPhones; i++) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001604 indentPW.println("Phone Id = " + i);
shuoq26a3a4c2016-12-16 11:06:48 -08001605 // display default values in CarrierConfigManager
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001606 printConfig(CarrierConfigManager.getDefaultConfig(), indentPW,
shuoq26a3a4c2016-12-16 11:06:48 -08001607 "Default Values from CarrierConfigManager");
shuoq26a3a4c2016-12-16 11:06:48 -08001608 // display ConfigFromDefaultApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001609 printConfig(mConfigFromDefaultApp[i], indentPW, "mConfigFromDefaultApp");
shuoq26a3a4c2016-12-16 11:06:48 -08001610 // display ConfigFromCarrierApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001611 printConfig(mConfigFromCarrierApp[i], indentPW, "mConfigFromCarrierApp");
1612 printConfig(mPersistentOverrideConfigs[i], indentPW, "mPersistentOverrideConfigs");
1613 printConfig(mOverrideConfigs[i], indentPW, "mOverrideConfigs");
shuoq26a3a4c2016-12-16 11:06:48 -08001614 }
chen xudb04c292019-03-26 17:01:15 -07001615
Jayachandran C645ec612020-01-10 10:30:25 -08001616 printConfig(mNoSimConfig, indentPW, "mNoSimConfig");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001617 indentPW.println("CarrierConfigLoadingLog=");
1618 mCarrierConfigLoadingLog.dump(fd, indentPW, args);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001619
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001620 if (requestingPackage != null) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001621 logd("Including default and requesting package " + requestingPackage
1622 + " carrier services in dump");
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001623 indentPW.println("");
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001624 indentPW.println("Connected services");
1625 dumpCarrierServiceIfBound(fd, indentPW, "Default config package",
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001626 mPlatformCarrierConfigPackage, false /* considerCarrierPrivileges */);
1627 dumpCarrierServiceIfBound(fd, indentPW, "Requesting package", requestingPackage,
1628 true /* considerCarrierPrivileges */);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001629 }
shuoq26a3a4c2016-12-16 11:06:48 -08001630 }
1631
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001632 private void printConfig(@NonNull PersistableBundle configApp,
1633 @NonNull IndentingPrintWriter indentPW, @NonNull String name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001634 indentPW.increaseIndent();
shuoq26a3a4c2016-12-16 11:06:48 -08001635 if (configApp == null) {
shuoq26a3a4c2016-12-16 11:06:48 -08001636 indentPW.println(name + " : null ");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001637 indentPW.decreaseIndent();
1638 indentPW.println("");
shuoq26a3a4c2016-12-16 11:06:48 -08001639 return;
1640 }
shuoq26a3a4c2016-12-16 11:06:48 -08001641 indentPW.println(name + " : ");
1642 List<String> sortedKeys = new ArrayList<String>(configApp.keySet());
1643 Collections.sort(sortedKeys);
1644 indentPW.increaseIndent();
1645 indentPW.increaseIndent();
1646 for (String key : sortedKeys) {
1647 if (configApp.get(key) != null && configApp.get(key) instanceof Object[]) {
1648 indentPW.println(key + " = " +
1649 Arrays.toString((Object[]) configApp.get(key)));
1650 } else if (configApp.get(key) != null && configApp.get(key) instanceof int[]) {
1651 indentPW.println(key + " = " + Arrays.toString((int[]) configApp.get(key)));
1652 } else {
1653 indentPW.println(key + " = " + configApp.get(key));
1654 }
Junda Liu43d723a2015-05-12 17:23:45 -07001655 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001656 indentPW.decreaseIndent();
1657 indentPW.decreaseIndent();
1658 indentPW.decreaseIndent();
1659 indentPW.println("");
Junda Liu43d723a2015-05-12 17:23:45 -07001660 }
1661
Hunter Knepshielde601f432020-02-19 10:16:04 -08001662 /**
1663 * Passes without problem when one of these conditions is true:
1664 * - The caller is a privileged UID (e.g. for dumpstate.cpp generating a bug report, where the
1665 * system knows the true caller plumbed in through the {@link android.os.BugreportManager} API).
1666 * - The caller's UID matches the supplied package.
1667 *
1668 * @throws SecurityException if none of the above conditions are met.
1669 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001670 private void enforceCallerIsSystemOrRequestingPackage(@NonNull String requestingPackage)
Hunter Knepshielde601f432020-02-19 10:16:04 -08001671 throws SecurityException {
1672 final int callingUid = Binder.getCallingUid();
1673 if (callingUid == Process.ROOT_UID || callingUid == Process.SYSTEM_UID
1674 || callingUid == Process.SHELL_UID || callingUid == Process.PHONE_UID) {
1675 // Bug reports (dumpstate.cpp) run as SHELL, and let some other privileged UIDs through
1676 // as well.
1677 return;
1678 }
1679 // An app is trying to dump extra detail, block it if they aren't who they claim to be.
1680 AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
1681 if (appOps == null) {
1682 throw new SecurityException("No AppOps");
1683 }
1684 // Will throw a SecurityException if the UID and package don't match.
1685 appOps.checkPackage(callingUid, requestingPackage);
1686 }
1687
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001688 /**
1689 * Searches for one or more appropriate {@link CarrierService} instances to dump based on the
1690 * current connections.
1691 *
1692 * @param targetPkgName the target package name to dump carrier services for
1693 * @param considerCarrierPrivileges if true, allow a carrier service to be dumped if it shares
1694 * carrier privileges with {@code targetPkgName};
1695 * otherwise, only dump a carrier service if it is {@code
1696 * targetPkgName}
1697 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001698 private void dumpCarrierServiceIfBound(@NonNull FileDescriptor fd,
1699 @NonNull IndentingPrintWriter indentPW, @NonNull String prefix,
1700 @NonNull String targetPkgName, boolean considerCarrierPrivileges) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001701 // Null package is possible if it's early in the boot process, there was a recent crash, we
1702 // loaded the config from XML most recently, or a SIM slot is empty. Carrier apps with
1703 // long-lived bindings should typically get dumped here regardless. Even if an app is being
1704 // used for multiple phoneIds, we assume that it's smart enough to handle that on its own,
1705 // and that in most cases we'd just be dumping duplicate information and bloating a report.
1706 indentPW.increaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001707 indentPW.println(prefix + " : " + targetPkgName);
1708 Set<String> dumpedPkgNames = new ArraySet<>(mServiceConnection.length);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001709 for (CarrierServiceConnection connection : mServiceConnection) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001710 if (connection == null || !SubscriptionManager.isValidPhoneId(connection.phoneId)
1711 || TextUtils.isEmpty(connection.pkgName)) {
1712 continue;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001713 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001714 final String servicePkgName = connection.pkgName;
1715 // Note: we intentionally ignore system components here because we should NOT match the
1716 // shell caller that's typically used for bug reports via non-BugreportManager triggers.
1717 final boolean exactPackageMatch = TextUtils.equals(targetPkgName, servicePkgName);
1718 final boolean carrierPrivilegesMatch =
1719 considerCarrierPrivileges && hasCarrierPrivileges(targetPkgName,
1720 connection.phoneId);
1721 if (!exactPackageMatch && !carrierPrivilegesMatch) continue;
1722 // Make sure this service is actually alive before trying to dump it. We don't pay
1723 // attention to mServiceBound[connection.phoneId] because typically carrier apps will
1724 // request long-lived bindings, and even if we unbind the app, it may still be alive due
1725 // to CarrierServiceBindHelper. Pull it out as a reference so even if it gets set to
1726 // null within the ServiceConnection during unbinding we can avoid an NPE.
1727 final IBinder service = connection.service;
1728 if (service == null || !service.isBinderAlive() || !service.pingBinder()) continue;
1729 // We've got a live service. Last check is just to make sure we don't dump a package
1730 // multiple times.
1731 if (!dumpedPkgNames.add(servicePkgName)) continue;
1732 if (!exactPackageMatch) {
1733 logd(targetPkgName + " has carrier privileges on phoneId " + connection.phoneId
1734 + ", service provided by " + servicePkgName);
1735 indentPW.increaseIndent();
1736 indentPW.println("Proxy : " + servicePkgName);
1737 indentPW.decreaseIndent();
1738 }
1739 // Flush before we let the app output anything to ensure correct ordering of output.
1740 // Internally, Binder#dump calls flush on its printer after finishing so we don't
1741 // need to do anything after.
1742 indentPW.flush();
1743 try {
1744 logd("Dumping " + servicePkgName);
1745 // We don't need to give the carrier service any args.
1746 connection.service.dump(fd, null /* args */);
1747 logd("Done with " + servicePkgName);
1748 } catch (RemoteException e) {
1749 logd("RemoteException from " + servicePkgName, e);
1750 indentPW.increaseIndent();
1751 indentPW.println("RemoteException");
1752 indentPW.increaseIndent();
1753 e.printStackTrace(indentPW);
1754 indentPW.decreaseIndent();
1755 indentPW.decreaseIndent();
1756 // We won't retry this package again because now it's in dumpedPkgNames.
1757 }
1758 indentPW.println("");
Jordan Liu46ed5db2020-01-28 08:55:20 -08001759 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001760 if (dumpedPkgNames.isEmpty()) {
1761 indentPW.increaseIndent();
1762 indentPW.println("Not bound");
1763 indentPW.decreaseIndent();
1764 indentPW.println("");
1765 }
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001766 indentPW.decreaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001767 }
1768
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001769 private boolean hasCarrierPrivileges(@NonNull String pkgName, int phoneId) {
Jack Yu00ece8c2022-11-19 22:29:12 -08001770 int subId = SubscriptionManager.getSubscriptionId(phoneId);
1771 if (!SubscriptionManager.isValidSubscriptionId(subId)) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001772 return false;
1773 }
Jack Yu00ece8c2022-11-19 22:29:12 -08001774 return TelephonyManager.from(mContext).createForSubscriptionId(subId)
1775 .checkCarrierPrivilegesForPackage(pkgName)
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001776 == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001777 }
1778
Zach Johnson36d7aab2015-05-22 15:43:00 -07001779 private class CarrierServiceConnection implements ServiceConnection {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001780 final int phoneId;
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001781 @NonNull final String pkgName;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001782 final int eventId;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001783 IBinder service;
1784
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001785 CarrierServiceConnection(int phoneId, @NonNull String pkgName, int eventId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001786 this.phoneId = phoneId;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001787 this.pkgName = pkgName;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001788 this.eventId = eventId;
1789 }
1790
1791 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001792 public void onServiceConnected(@NonNull ComponentName name, @NonNull IBinder service) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001793 logd("Connected to config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001794 this.service = service;
1795 mHandler.sendMessage(mHandler.obtainMessage(eventId, phoneId, -1, this));
1796 }
1797
1798 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001799 public void onServiceDisconnected(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001800 logd("Disconnected from config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001801 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001802 }
1803
1804 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001805 public void onBindingDied(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001806 logd("Binding died from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001807 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001808 }
1809
1810 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001811 public void onNullBinding(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001812 logd("Null binding from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001813 this.service = null;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001814 }
1815 }
1816
1817 private class ConfigLoaderBroadcastReceiver extends BroadcastReceiver {
1818 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001819 public void onReceive(@NonNull Context context, @NonNull Intent intent) {
Rambo Wanga27fbe52022-04-12 19:09:07 +00001820 switch (intent.getAction()) {
Nanxi Chen3d670502016-03-17 16:32:09 -07001821 case Intent.ACTION_BOOT_COMPLETED:
1822 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_UNLOCKED, null));
1823 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001824 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001825 }
1826 }
1827
Rambo Wanga27fbe52022-04-12 19:09:07 +00001828 private class CarrierServiceChangeCallback implements
1829 TelephonyManager.CarrierPrivilegesCallback {
1830 final int mPhoneId;
1831 // CarrierPrivilegesCallback will be triggered upon registration. Filter the first callback
1832 // here since we really care of the *change* of carrier service instead of the content
1833 private boolean mHasSentServiceChangeCallback;
1834
1835 CarrierServiceChangeCallback(int phoneId) {
1836 this.mPhoneId = phoneId;
1837 this.mHasSentServiceChangeCallback = false;
1838 }
1839
1840 @Override
1841 public void onCarrierPrivilegesChanged(
1842 @androidx.annotation.NonNull Set<String> privilegedPackageNames,
1843 @androidx.annotation.NonNull Set<Integer> privilegedUids) {
1844 // Ignored, not interested here
1845 }
1846
1847 @Override
1848 public void onCarrierServiceChanged(
1849 @androidx.annotation.Nullable String carrierServicePackageName,
1850 int carrierServiceUid) {
1851 // Ignore the first callback which is triggered upon registration
1852 if (!mHasSentServiceChangeCallback) {
1853 mHasSentServiceChangeCallback = true;
1854 return;
1855 }
1856 mHandler.sendMessage(
1857 mHandler.obtainMessage(EVENT_PACKAGE_CHANGED, mPhoneId, -1,
1858 carrierServicePackageName));
1859 }
1860 }
1861
Rambo Wangab13e3e2021-04-08 15:01:06 -07001862 // Get readable string for the message code supported in this class.
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001863 @NonNull
Rambo Wangab13e3e2021-04-08 15:01:06 -07001864 private static String eventToString(int code) {
1865 switch (code) {
1866 case EVENT_CLEAR_CONFIG:
1867 return "EVENT_CLEAR_CONFIG";
1868 case EVENT_CONNECTED_TO_DEFAULT:
1869 return "EVENT_CONNECTED_TO_DEFAULT";
1870 case EVENT_CONNECTED_TO_CARRIER:
1871 return "EVENT_CONNECTED_TO_CARRIER";
1872 case EVENT_FETCH_DEFAULT_DONE:
1873 return "EVENT_FETCH_DEFAULT_DONE";
1874 case EVENT_FETCH_CARRIER_DONE:
1875 return "EVENT_FETCH_CARRIER_DONE";
1876 case EVENT_DO_FETCH_DEFAULT:
1877 return "EVENT_DO_FETCH_DEFAULT";
1878 case EVENT_DO_FETCH_CARRIER:
1879 return "EVENT_DO_FETCH_CARRIER";
1880 case EVENT_PACKAGE_CHANGED:
1881 return "EVENT_PACKAGE_CHANGED";
1882 case EVENT_BIND_DEFAULT_TIMEOUT:
1883 return "EVENT_BIND_DEFAULT_TIMEOUT";
1884 case EVENT_BIND_CARRIER_TIMEOUT:
1885 return "EVENT_BIND_CARRIER_TIMEOUT";
1886 case EVENT_CHECK_SYSTEM_UPDATE:
1887 return "EVENT_CHECK_SYSTEM_UPDATE";
1888 case EVENT_SYSTEM_UNLOCKED:
1889 return "EVENT_SYSTEM_UNLOCKED";
1890 case EVENT_FETCH_DEFAULT_TIMEOUT:
1891 return "EVENT_FETCH_DEFAULT_TIMEOUT";
1892 case EVENT_FETCH_CARRIER_TIMEOUT:
1893 return "EVENT_FETCH_CARRIER_TIMEOUT";
1894 case EVENT_SUBSCRIPTION_INFO_UPDATED:
1895 return "EVENT_SUBSCRIPTION_INFO_UPDATED";
1896 case EVENT_MULTI_SIM_CONFIG_CHANGED:
1897 return "EVENT_MULTI_SIM_CONFIG_CHANGED";
1898 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG:
1899 return "EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG";
1900 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE:
1901 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE";
1902 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG:
1903 return "EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG";
1904 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1905 return "EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1906 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1907 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1908 default:
1909 return "UNKNOWN(" + code + ")";
1910 }
1911 }
1912
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001913 private void logd(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001914 Log.d(LOG_TAG, msg);
1915 }
1916
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001917 private void logd(@NonNull String msg, Throwable tr) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001918 Log.d(LOG_TAG, msg, tr);
1919 }
1920
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001921 private void logdWithLocalLog(@NonNull String msg) {
chen xudb04c292019-03-26 17:01:15 -07001922 Log.d(LOG_TAG, msg);
1923 mCarrierConfigLoadingLog.log(msg);
1924 }
1925
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001926 private void loge(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001927 Log.e(LOG_TAG, msg);
chen xudb04c292019-03-26 17:01:15 -07001928 mCarrierConfigLoadingLog.log(msg);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001929 }
1930}