blob: 3eafb2477cd8cb7d465b3b569bd588148d16bab5 [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;
Jack Yu9be55d32023-08-10 13:47:46 -070071import com.android.internal.telephony.util.TelephonyUtils;
shuoq26a3a4c2016-12-16 11:06:48 -080072import com.android.internal.util.IndentingPrintWriter;
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;
Jack Yu9be55d32023-08-10 13:47:46 -070082import java.nio.file.Files;
83import java.nio.file.Paths;
84import java.nio.file.attribute.BasicFileAttributes;
85import java.text.SimpleDateFormat;
shuoq26a3a4c2016-12-16 11:06:48 -080086import java.util.ArrayList;
87import java.util.Arrays;
88import java.util.Collections;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080089import java.util.List;
Jack Yu9be55d32023-08-10 13:47:46 -070090import java.util.Locale;
rambowang14757c22022-10-03 11:54:56 -050091import java.util.Objects;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -080092import java.util.Set;
Jack Yu9be55d32023-08-10 13:47:46 -070093import java.util.stream.Collectors;
94import java.util.stream.Stream;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080095
96/**
97 * CarrierConfigLoader binds to privileged carrier apps to fetch carrier config overlays.
Jonathan Basseri6465afd2015-02-25 13:05:57 -080098 */
Jonathan Basseri6465afd2015-02-25 13:05:57 -080099public class CarrierConfigLoader extends ICarrierConfigLoader.Stub {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700100 private static final String LOG_TAG = "CarrierConfigLoader";
Meng Wang33ad2bc2017-03-16 20:21:20 -0700101
Jack Yu9be55d32023-08-10 13:47:46 -0700102 private static final SimpleDateFormat TIME_FORMAT =
103 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
104
Meng Wang33ad2bc2017-03-16 20:21:20 -0700105 // Package name for platform carrier config app, bundled with system image.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000106 @NonNull private final String mPlatformCarrierConfigPackage;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800107
108 /** The singleton instance. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000109 @Nullable private static CarrierConfigLoader sInstance;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800110 // The context for phone app, passed from PhoneGlobals.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000111 @NonNull private Context mContext;
112
113 // All the states below (array indexed by phoneId) are non-null. But the member of the array
114 // is nullable, when e.g. the config for the phone is not loaded yet
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800115 // Carrier configs from default app, indexed by phoneID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000116 @NonNull private PersistableBundle[] mConfigFromDefaultApp;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800117 // Carrier configs from privileged carrier config app, indexed by phoneID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000118 @NonNull private PersistableBundle[] mConfigFromCarrierApp;
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100119 // Persistent Carrier configs that are provided via the override test API, indexed by phone ID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000120 @NonNull private PersistableBundle[] mPersistentOverrideConfigs;
Hall Liu506724b2018-10-22 18:16:14 -0700121 // Carrier configs that are provided via the override test API, indexed by phone ID.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000122 @NonNull private PersistableBundle[] mOverrideConfigs;
Jayachandran C645ec612020-01-10 10:30:25 -0800123 // Carrier configs to override code default when there is no SIM inserted
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000124 @NonNull private PersistableBundle mNoSimConfig;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800125 // Service connection for binding to config app.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000126 @NonNull private CarrierServiceConnection[] mServiceConnection;
Jayachandran C645ec612020-01-10 10:30:25 -0800127 // Service connection for binding to carrier config app for no SIM config.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000128 @NonNull private CarrierServiceConnection[] mServiceConnectionForNoSimConfig;
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700129 // Whether we are bound to a service for each phone
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000130 @NonNull private boolean[] mServiceBound;
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700131 // Whether we are bound to a service for no SIM config
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000132 @NonNull private boolean[] mServiceBoundForNoSimConfig;
Sarah Chin807d5c62020-03-30 17:21:09 -0700133 // Whether we have sent config change broadcast for each phone id.
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000134 @NonNull private boolean[] mHasSentConfigChange;
Sarah Chin807d5c62020-03-30 17:21:09 -0700135 // Whether the broadcast was sent from EVENT_SYSTEM_UNLOCKED, to track rebroadcasts
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000136 @NonNull private boolean[] mFromSystemUnlocked;
Rambo Wanga27fbe52022-04-12 19:09:07 +0000137 // CarrierService change monitoring
138 @NonNull private CarrierServiceChangeCallback[] mCarrierServiceChangeCallbacks;
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000139
Jack Yu771c6ce2023-02-02 17:51:42 -0800140 // Broadcast receiver for system events
Rambo Wanga27fbe52022-04-12 19:09:07 +0000141 @NonNull
142 private final BroadcastReceiver mSystemBroadcastReceiver = new ConfigLoaderBroadcastReceiver();
Jack Yu9be55d32023-08-10 13:47:46 -0700143 @NonNull private final LocalLog mCarrierConfigLoadingLog = new LocalLog(256);
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000144 // Number of phone instances (active modem count)
145 private int mNumPhones;
chen xudb04c292019-03-26 17:01:15 -0700146
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800147
148 // Message codes; see mHandler below.
Jack Yu3beaf9d2023-04-14 09:17:27 -0700149 // Request from UiccController when SIM becomes absent or error.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800150 private static final int EVENT_CLEAR_CONFIG = 0;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800151 // Has connected to default app.
152 private static final int EVENT_CONNECTED_TO_DEFAULT = 3;
153 // Has connected to carrier app.
154 private static final int EVENT_CONNECTED_TO_CARRIER = 4;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700155 // Config has been loaded from default app (or cache).
156 private static final int EVENT_FETCH_DEFAULT_DONE = 5;
157 // Config has been loaded from carrier app (or cache).
158 private static final int EVENT_FETCH_CARRIER_DONE = 6;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700159 // Attempt to fetch from default app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700160 private static final int EVENT_DO_FETCH_DEFAULT = 7;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700161 // Attempt to fetch from carrier app or read from XML.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700162 private static final int EVENT_DO_FETCH_CARRIER = 8;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700163 // A package has been installed, uninstalled, or updated.
164 private static final int EVENT_PACKAGE_CHANGED = 9;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700165 // Bind timed out for the default app.
166 private static final int EVENT_BIND_DEFAULT_TIMEOUT = 10;
167 // Bind timed out for a carrier app.
168 private static final int EVENT_BIND_CARRIER_TIMEOUT = 11;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700169 // Check if the system fingerprint has changed.
170 private static final int EVENT_CHECK_SYSTEM_UPDATE = 12;
Nanxi Chen3d670502016-03-17 16:32:09 -0700171 // Rerun carrier config binding after system is unlocked.
172 private static final int EVENT_SYSTEM_UNLOCKED = 13;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700173 // Fetching config timed out from the default app.
174 private static final int EVENT_FETCH_DEFAULT_TIMEOUT = 14;
175 // Fetching config timed out from a carrier app.
176 private static final int EVENT_FETCH_CARRIER_TIMEOUT = 15;
Jack Yu3beaf9d2023-04-14 09:17:27 -0700177 // SubscriptionManagerService has finished updating the sub for the carrier config.
Nathan Harold48ac0972019-03-13 22:33:01 -0700178 private static final int EVENT_SUBSCRIPTION_INFO_UPDATED = 16;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700179 // Multi-SIM config changed.
180 private static final int EVENT_MULTI_SIM_CONFIG_CHANGED = 17;
Jayachandran C645ec612020-01-10 10:30:25 -0800181 // Attempt to fetch from default app or read from XML for no SIM case.
182 private static final int EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG = 18;
183 // No SIM config has been loaded from default app (or cache).
184 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE = 19;
185 // Has connected to default app for no SIM config.
186 private static final int EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG = 20;
187 // Bind timed out for the default app when trying to fetch no SIM config.
188 private static final int EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 21;
189 // Fetching config timed out from the default app for no SIM config.
190 private static final int EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT = 22;
Rambo Wangab13e3e2021-04-08 15:01:06 -0700191 // NOTE: any new EVENT_* values must be added to method eventToString().
Jonathan Basseri930701e2015-06-11 20:56:43 -0700192
Junda Liu6cb45002016-03-22 17:18:20 -0700193 private static final int BIND_TIMEOUT_MILLIS = 30000;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800194
Meng Wang0f6b2ea2020-01-06 18:31:16 -0800195 // Keys used for saving and restoring config bundle from file.
196 private static final String KEY_VERSION = "__carrier_config_package_version__";
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800197
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100198 private static final String OVERRIDE_PACKAGE_ADDITION = "-override";
199
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700200 // SharedPreferences key for last known build fingerprint.
201 private static final String KEY_FINGERPRINT = "build_fingerprint";
202
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -0800203 // Argument for #dump that indicates we should also call the default and specified carrier
204 // service's #dump method. In multi-SIM devices, it's possible that carrier A is on SIM 1 and
205 // carrier B is on SIM 2, in which case we should not dump carrier B's service when carrier A
206 // requested the dump.
207 private static final String DUMP_ARG_REQUESTING_PACKAGE = "--requesting-package";
208
rambowang14757c22022-10-03 11:54:56 -0500209 // Configs that should always be included when clients calls getConfig[ForSubId] with specified
210 // keys (even configs are not explicitly specified). Those configs have special purpose for the
211 // carrier config APIs to work correctly.
212 private static final String[] CONFIG_SUBSET_METADATA_KEYS = new String[] {
213 CarrierConfigManager.KEY_CARRIER_CONFIG_VERSION_STRING,
214 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL
215 };
216
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800217 // Handler to process various events.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700218 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700219 // For each phoneId, the event sequence should be:
Jonathan Basseri65273c82017-07-25 15:08:42 -0700220 // fetch default, connected to default, fetch default (async), fetch default done,
221 // fetch carrier, connected to carrier, fetch carrier (async), fetch carrier done.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700222 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700223 // If there is a saved config file for either the default app or the carrier app, we skip
224 // binding to the app and go straight from fetch to loaded.
225 //
226 // At any time, at most one connection is active. If events are not in this order, previous
227 // connection will be unbound, so only latest event takes effect.
228 //
229 // We broadcast ACTION_CARRIER_CONFIG_CHANGED after:
230 // 1. loading from carrier app (even if read from a file)
231 // 2. loading from default app if there is no carrier app (even if read from a file)
232 // 3. clearing config (e.g. due to sim removal)
233 // 4. encountering bind or IPC error
Jonathan Basseri65273c82017-07-25 15:08:42 -0700234 private class ConfigHandler extends Handler {
Rambo Wang7e3bc122021-03-23 09:24:38 -0700235 ConfigHandler(@NonNull Looper looper) {
236 super(looper);
237 }
238
Jonathan Basseri65273c82017-07-25 15:08:42 -0700239 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000240 public void handleMessage(@NonNull Message msg) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700241 final int phoneId = msg.arg1;
Jack Yu9be55d32023-08-10 13:47:46 -0700242 logd(eventToString(msg.what) + " phoneId: " + phoneId);
Malcolm Chen5ea18532019-10-24 19:55:44 -0700243 if (!SubscriptionManager.isValidPhoneId(phoneId)
244 && msg.what != EVENT_MULTI_SIM_CONFIG_CHANGED) {
245 return;
246 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800247 switch (msg.what) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800248 case EVENT_CLEAR_CONFIG: {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700249 clearConfigForPhone(phoneId, true);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800250 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700251 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700252
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800253 case EVENT_SYSTEM_UNLOCKED: {
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000254 for (int i = 0; i < mNumPhones; ++i) {
Sarah Chin807d5c62020-03-30 17:21:09 -0700255 // When the user unlocks the device, send the broadcast again (with a
256 // rebroadcast extra) if we have sent it before unlock. This will avoid
257 // trying to load the carrier config when the SIM is still loading when the
258 // unlock happens.
Junda Liu03aad762017-07-21 13:32:17 -0700259 if (mHasSentConfigChange[i]) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800260 logdWithLocalLog("System unlocked");
Sarah Chin807d5c62020-03-30 17:21:09 -0700261 mFromSystemUnlocked[i] = true;
Junda Liu03aad762017-07-21 13:32:17 -0700262 updateConfigForPhoneId(i);
263 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700264 }
265 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700266 }
Nanxi Chen3d670502016-03-17 16:32:09 -0700267
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800268 case EVENT_PACKAGE_CHANGED: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700269 final String carrierPackageName = (String) msg.obj;
Rambo Wanga27fbe52022-04-12 19:09:07 +0000270 // Always clear up the cache and re-load config from scratch since the carrier
271 // service change is reliable and specific to the phoneId now.
272 clearCachedConfigForPackage(carrierPackageName);
273 logdWithLocalLog("Package changed: " + carrierPackageName
274 + ", phone=" + phoneId);
275 updateConfigForPhoneId(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700276 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700277 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700278
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800279 case EVENT_DO_FETCH_DEFAULT: {
Rambo Wang9bc7d362021-03-09 09:10:58 -0800280 // Clear in-memory cache for carrier app config, so when carrier app gets
281 // uninstalled, no stale config is left.
282 if (mConfigFromCarrierApp[phoneId] != null
283 && getCarrierPackageForPhoneId(phoneId) == null) {
284 mConfigFromCarrierApp[phoneId] = null;
285 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100286 // Restore persistent override values.
287 PersistableBundle config = restoreConfigFromXml(
288 mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION, phoneId);
289 if (config != null) {
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100290 mPersistentOverrideConfigs[phoneId] = config;
291 }
292
293 config = restoreConfigFromXml(mPlatformCarrierConfigPackage, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700294 if (config != null) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700295 mConfigFromDefaultApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700296 Message newMsg = obtainMessage(EVENT_FETCH_DEFAULT_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700297 newMsg.getData().putBoolean("loaded_from_xml", true);
298 mHandler.sendMessage(newMsg);
299 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700300 // No cached config, so fetch it from the default app.
301 if (bindToConfigPackage(
302 mPlatformCarrierConfigPackage,
303 phoneId,
304 EVENT_CONNECTED_TO_DEFAULT)) {
305 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800306 obtainMessage(EVENT_BIND_DEFAULT_TIMEOUT, phoneId, -1 /*arg2*/,
307 getMessageToken(phoneId)),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700308 BIND_TIMEOUT_MILLIS);
309 } else {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800310 // Put a stub bundle in place so that the rest of the logic continues
311 // smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000312 mConfigFromDefaultApp[phoneId] = new PersistableBundle();
Jonathan Basseri65273c82017-07-25 15:08:42 -0700313 // Send broadcast if bind fails.
Jack Yue37dd262022-12-16 11:53:37 -0800314 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700315 // TODO: We *must* call unbindService even if bindService returns false.
316 // (And possibly if SecurityException was thrown.)
chen xudb04c292019-03-26 17:01:15 -0700317 loge("binding to default app: "
318 + mPlatformCarrierConfigPackage + " fails");
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700319 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800320 }
321 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700322 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800323
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800324 case EVENT_CONNECTED_TO_DEFAULT: {
Rambo Wang610fdf62021-03-08 21:37:11 -0800325 removeMessages(EVENT_BIND_DEFAULT_TIMEOUT, getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700326 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800327 // If new service connection has been created, unbind.
328 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700329 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800330 break;
331 }
chen xu02581692018-11-11 19:03:44 -0800332 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700333 // ResultReceiver callback will execute in this Handler's thread.
334 final ResultReceiver resultReceiver =
335 new ResultReceiver(this) {
336 @Override
337 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700338 unbindIfBound(mContext, conn, phoneId);
Rambo Wanga9d27a52021-04-09 16:17:33 -0700339 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT,
340 getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700341 // If new service connection has been created, this is stale.
342 if (mServiceConnection[phoneId] != conn) {
343 loge("Received response for stale request.");
344 return;
345 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700346 if (resultCode == RESULT_ERROR || resultData == null) {
347 // On error, abort config fetching.
348 loge("Failed to get carrier config");
Jack Yue37dd262022-12-16 11:53:37 -0800349 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700350 return;
351 }
352 PersistableBundle config =
353 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100354 saveConfigToXml(mPlatformCarrierConfigPackage, "", phoneId,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800355 carrierId, config);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700356 mConfigFromDefaultApp[phoneId] = config;
357 sendMessage(
358 obtainMessage(
359 EVENT_FETCH_DEFAULT_DONE, phoneId, -1));
360 }
361 };
362 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800363 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700364 ICarrierService carrierService =
365 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800366 carrierService.getCarrierConfig(phoneId, carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800367 logdWithLocalLog("Fetch config for default app: "
chen xudb04c292019-03-26 17:01:15 -0700368 + mPlatformCarrierConfigPackage
Jack Yu9be55d32023-08-10 13:47:46 -0700369 + ", carrierId=" + carrierId.getSpecificCarrierId());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700370 } catch (RemoteException e) {
chen xudb04c292019-03-26 17:01:15 -0700371 loge("Failed to get carrier config from default app: " +
Jack Yu9be55d32023-08-10 13:47:46 -0700372 mPlatformCarrierConfigPackage + " err: " + e);
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700373 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700374 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800375 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700376 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800377 obtainMessage(EVENT_FETCH_DEFAULT_TIMEOUT, phoneId, -1 /*arg2*/,
378 getMessageToken(phoneId)),
Jonathan Basseri65273c82017-07-25 15:08:42 -0700379 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800380 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700381 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800382
Jonathan Basseri930701e2015-06-11 20:56:43 -0700383 case EVENT_BIND_DEFAULT_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800384 case EVENT_FETCH_DEFAULT_TIMEOUT: {
385 loge("Bind/fetch time out from " + mPlatformCarrierConfigPackage);
Rambo Wang610fdf62021-03-08 21:37:11 -0800386 removeMessages(EVENT_FETCH_DEFAULT_TIMEOUT, getMessageToken(phoneId));
chen xuf60b3162019-05-01 21:31:05 -0700387 // If we attempted to bind to the app, but the service connection is null due to
388 // the race condition that clear config event happens before bind/fetch complete
389 // then config was cleared while we were waiting and we should not continue.
390 if (mServiceConnection[phoneId] != null) {
391 // If a ResponseReceiver callback is in the queue when this happens, we will
392 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700393 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700394 broadcastConfigChangedIntent(phoneId);
395 }
Nathan Harold1122e3d2021-01-22 15:45:24 -0800396 // Put a stub bundle in place so that the rest of the logic continues smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000397 mConfigFromDefaultApp[phoneId] = new PersistableBundle();
Jack Yue37dd262022-12-16 11:53:37 -0800398 updateSubscriptionDatabase(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700399 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700400 }
Jonathan Basseri930701e2015-06-11 20:56:43 -0700401
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800402 case EVENT_FETCH_DEFAULT_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700403 // If we attempted to bind to the app, but the service connection is null, then
404 // config was cleared while we were waiting and we should not continue.
405 if (!msg.getData().getBoolean("loaded_from_xml", false)
406 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800407 break;
408 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700409 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700410 if (carrierPackageName != null) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800411 logd("Found carrier config app: " + carrierPackageName);
Jordan Liu38a614c2019-03-20 15:01:17 -0700412 sendMessage(obtainMessage(EVENT_DO_FETCH_CARRIER, phoneId, -1));
Jonathan Basserib919e932015-05-27 16:53:08 +0000413 } else {
Jack Yue37dd262022-12-16 11:53:37 -0800414 updateSubscriptionDatabase(phoneId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700415 }
416 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700417 }
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700418
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800419 case EVENT_DO_FETCH_CARRIER: {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700420 final String carrierPackageName = getCarrierPackageForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700421 final PersistableBundle config =
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100422 restoreConfigFromXml(carrierPackageName, "", phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700423 if (config != null) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700424 mConfigFromCarrierApp[phoneId] = config;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700425 Message newMsg = obtainMessage(EVENT_FETCH_CARRIER_DONE, phoneId, -1);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700426 newMsg.getData().putBoolean("loaded_from_xml", true);
427 sendMessage(newMsg);
428 } else {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700429 // No cached config, so fetch it from a carrier app.
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800430 if (carrierPackageName != null && bindToConfigPackage(carrierPackageName,
431 phoneId, EVENT_CONNECTED_TO_CARRIER)) {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700432 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800433 obtainMessage(EVENT_BIND_CARRIER_TIMEOUT, phoneId, -1 /*arg2*/,
434 getMessageToken(phoneId)),
Jonathan Basseri930701e2015-06-11 20:56:43 -0700435 BIND_TIMEOUT_MILLIS);
436 } else {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800437 // Put a stub bundle in place so that the rest of the logic continues
438 // smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000439 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
Jonathan Basseri65273c82017-07-25 15:08:42 -0700440 // Send broadcast if bind fails.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700441 broadcastConfigChangedIntent(phoneId);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800442 loge("Bind to carrier app: " + carrierPackageName + " fails");
Jack Yue37dd262022-12-16 11:53:37 -0800443 updateSubscriptionDatabase(phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700444 }
445 }
446 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700447 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700448
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800449 case EVENT_CONNECTED_TO_CARRIER: {
Rambo Wang610fdf62021-03-08 21:37:11 -0800450 removeMessages(EVENT_BIND_CARRIER_TIMEOUT, getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700451 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800452 // If new service connection has been created, unbind.
Jonathan Basseri65273c82017-07-25 15:08:42 -0700453 if (mServiceConnection[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700454 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800455 break;
456 }
chen xu02581692018-11-11 19:03:44 -0800457 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700458 // ResultReceiver callback will execute in this Handler's thread.
459 final ResultReceiver resultReceiver =
460 new ResultReceiver(this) {
461 @Override
462 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700463 unbindIfBound(mContext, conn, phoneId);
Rambo Wanga9d27a52021-04-09 16:17:33 -0700464 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT,
465 getMessageToken(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700466 // If new service connection has been created, this is stale.
467 if (mServiceConnection[phoneId] != conn) {
468 loge("Received response for stale request.");
469 return;
470 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700471 if (resultCode == RESULT_ERROR || resultData == null) {
472 // On error, abort config fetching.
chen xudb04c292019-03-26 17:01:15 -0700473 loge("Failed to get carrier config from carrier app: "
474 + getCarrierPackageForPhoneId(phoneId));
Jonathan Basseri65273c82017-07-25 15:08:42 -0700475 broadcastConfigChangedIntent(phoneId);
Jack Yue37dd262022-12-16 11:53:37 -0800476 updateSubscriptionDatabase(phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700477 return;
478 }
479 PersistableBundle config =
480 resultData.getParcelable(KEY_CONFIG_BUNDLE);
Torbjorn Eklund723527a2019-02-13 11:16:25 +0100481 saveConfigToXml(getCarrierPackageForPhoneId(phoneId), "",
482 phoneId, carrierId, config);
Amit Mahajan304e92b2021-04-08 14:03:30 -0700483 if (config != null) {
484 mConfigFromCarrierApp[phoneId] = config;
485 } else {
486 logdWithLocalLog("Config from carrier app is null "
487 + "for phoneId " + phoneId);
488 // Put a stub bundle in place so that the rest of the logic
489 // continues smoothly.
490 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
491 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700492 sendMessage(
493 obtainMessage(
494 EVENT_FETCH_CARRIER_DONE, phoneId, -1));
495 }
496 };
497 // Now fetch the config asynchronously from the ICarrierService.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800498 try {
Jonathan Basseri65273c82017-07-25 15:08:42 -0700499 ICarrierService carrierService =
500 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800501 carrierService.getCarrierConfig(phoneId, carrierId, resultReceiver);
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800502 logdWithLocalLog("Fetch config for carrier app: "
chen xudb04c292019-03-26 17:01:15 -0700503 + getCarrierPackageForPhoneId(phoneId)
Jack Yu9be55d32023-08-10 13:47:46 -0700504 + ", carrierId=" + carrierId.getSpecificCarrierId());
Jonathan Basseri65273c82017-07-25 15:08:42 -0700505 } catch (RemoteException e) {
Jack Yu9be55d32023-08-10 13:47:46 -0700506 loge("Failed to get carrier config: " + e);
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700507 unbindIfBound(mContext, conn, phoneId);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700508 break; // So we don't set a timeout.
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800509 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700510 sendMessageDelayed(
Rambo Wang610fdf62021-03-08 21:37:11 -0800511 obtainMessage(EVENT_FETCH_CARRIER_TIMEOUT, phoneId, -1 /*arg2*/,
512 getMessageToken(phoneId)),
Jonathan Basseri65273c82017-07-25 15:08:42 -0700513 BIND_TIMEOUT_MILLIS);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800514 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700515 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800516
Jonathan Basseri930701e2015-06-11 20:56:43 -0700517 case EVENT_BIND_CARRIER_TIMEOUT:
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800518 case EVENT_FETCH_CARRIER_TIMEOUT: {
Nathan Harold1122e3d2021-01-22 15:45:24 -0800519 loge("Bind/fetch from carrier app timeout, package="
520 + getCarrierPackageForPhoneId(phoneId));
Rambo Wang610fdf62021-03-08 21:37:11 -0800521 removeMessages(EVENT_FETCH_CARRIER_TIMEOUT, getMessageToken(phoneId));
chen xuf60b3162019-05-01 21:31:05 -0700522 // If we attempted to bind to the app, but the service connection is null due to
523 // the race condition that clear config event happens before bind/fetch complete
524 // then config was cleared while we were waiting and we should not continue.
525 if (mServiceConnection[phoneId] != null) {
526 // If a ResponseReceiver callback is in the queue when this happens, we will
527 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700528 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
chen xuf60b3162019-05-01 21:31:05 -0700529 broadcastConfigChangedIntent(phoneId);
530 }
Nathan Harold1122e3d2021-01-22 15:45:24 -0800531 // Put a stub bundle in place so that the rest of the logic continues smoothly.
Rambo Wang42026112021-04-07 20:57:28 +0000532 mConfigFromCarrierApp[phoneId] = new PersistableBundle();
Jack Yue37dd262022-12-16 11:53:37 -0800533 updateSubscriptionDatabase(phoneId);
Jonathan Basseri930701e2015-06-11 20:56:43 -0700534 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700535 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800536 case EVENT_FETCH_CARRIER_DONE: {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700537 // If we attempted to bind to the app, but the service connection is null, then
538 // config was cleared while we were waiting and we should not continue.
539 if (!msg.getData().getBoolean("loaded_from_xml", false)
540 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800541 break;
542 }
Jack Yue37dd262022-12-16 11:53:37 -0800543 updateSubscriptionDatabase(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800544 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700545 }
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700546
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800547 case EVENT_CHECK_SYSTEM_UPDATE: {
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700548 SharedPreferences sharedPrefs =
549 PreferenceManager.getDefaultSharedPreferences(mContext);
550 final String lastFingerprint = sharedPrefs.getString(KEY_FINGERPRINT, null);
551 if (!Build.FINGERPRINT.equals(lastFingerprint)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800552 logd(
Jonathan Basseri65273c82017-07-25 15:08:42 -0700553 "Build fingerprint changed. old: "
554 + lastFingerprint
555 + " new: "
556 + Build.FINGERPRINT);
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700557 clearCachedConfigForPackage(null);
Jonathan Basseri65273c82017-07-25 15:08:42 -0700558 sharedPrefs
559 .edit()
560 .putString(KEY_FINGERPRINT, Build.FINGERPRINT)
561 .apply();
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700562 }
563 break;
Jonathan Basseri65273c82017-07-25 15:08:42 -0700564 }
Nathan Harold48ac0972019-03-13 22:33:01 -0700565
566 case EVENT_SUBSCRIPTION_INFO_UPDATED:
567 broadcastConfigChangedIntent(phoneId);
568 break;
Malcolm Chen5ea18532019-10-24 19:55:44 -0700569 case EVENT_MULTI_SIM_CONFIG_CHANGED:
570 onMultiSimConfigChanged();
571 break;
Jayachandran C645ec612020-01-10 10:30:25 -0800572
573 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG: {
574 PersistableBundle config =
575 restoreNoSimConfigFromXml(mPlatformCarrierConfigPackage);
576
577 if (config != null) {
Jayachandran C645ec612020-01-10 10:30:25 -0800578 mNoSimConfig = config;
579 sendMessage(
580 obtainMessage(
581 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
582 phoneId, -1));
583 } else {
584 // No cached config, so fetch it from the default app.
585 if (bindToConfigPackage(
586 mPlatformCarrierConfigPackage,
587 phoneId,
588 EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG)) {
589 sendMessageDelayed(
590 obtainMessage(
591 EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
592 phoneId, -1), BIND_TIMEOUT_MILLIS);
593 } else {
594 broadcastConfigChangedIntent(phoneId, false);
595 // TODO: We *must* call unbindService even if bindService returns false.
596 // (And possibly if SecurityException was thrown.)
597 loge("binding to default app to fetch no SIM config: "
598 + mPlatformCarrierConfigPackage + " fails");
599 }
600 }
601 break;
602 }
603
604 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE: {
605 broadcastConfigChangedIntent(phoneId, false);
606 break;
607 }
608
609 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
610 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT: {
611 loge("Bind/fetch time out for no SIM config from "
612 + mPlatformCarrierConfigPackage);
613 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
614 // If we attempted to bind to the app, but the service connection is null due to
615 // the race condition that clear config event happens before bind/fetch complete
616 // then config was cleared while we were waiting and we should not continue.
617 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
618 // If a ResponseReceiver callback is in the queue when this happens, we will
619 // unbind twice and throw an exception.
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700620 unbindIfBoundForNoSimConfig(mContext,
621 mServiceConnectionForNoSimConfig[phoneId], phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800622 }
623 broadcastConfigChangedIntent(phoneId, false);
624 break;
625 }
626
627 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG: {
628 removeMessages(EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
629 final CarrierServiceConnection conn = (CarrierServiceConnection) msg.obj;
630 // If new service connection has been created, unbind.
631 if (mServiceConnectionForNoSimConfig[phoneId] != conn || conn.service == null) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700632 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800633 break;
634 }
635
636 // ResultReceiver callback will execute in this Handler's thread.
637 final ResultReceiver resultReceiver =
638 new ResultReceiver(this) {
639 @Override
640 public void onReceiveResult(int resultCode, Bundle resultData) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700641 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800642 // If new service connection has been created, this is stale.
643 if (mServiceConnectionForNoSimConfig[phoneId] != conn) {
644 loge("Received response for stale request.");
645 return;
646 }
647 removeMessages(EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT);
648 if (resultCode == RESULT_ERROR || resultData == null) {
649 // On error, abort config fetching.
650 loge("Failed to get no SIM carrier config");
651 return;
652 }
653 PersistableBundle config =
654 resultData.getParcelable(KEY_CONFIG_BUNDLE);
655 saveNoSimConfigToXml(mPlatformCarrierConfigPackage, config);
656 mNoSimConfig = config;
657 sendMessage(
658 obtainMessage(
659 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE,
660 phoneId, -1));
661 }
662 };
663 // Now fetch the config asynchronously from the ICarrierService.
664 try {
665 ICarrierService carrierService =
666 ICarrierService.Stub.asInterface(conn.service);
Rambo Wang38bbdbe2021-11-23 13:03:34 -0800667 carrierService.getCarrierConfig(phoneId, null, resultReceiver);
Jayachandran C645ec612020-01-10 10:30:25 -0800668 logdWithLocalLog("Fetch no sim config from default app: "
669 + mPlatformCarrierConfigPackage);
670 } catch (RemoteException e) {
671 loge("Failed to get no sim carrier config from default app: " +
Jack Yu9be55d32023-08-10 13:47:46 -0700672 mPlatformCarrierConfigPackage + " err: " + e);
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700673 unbindIfBoundForNoSimConfig(mContext, conn, phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -0800674 break; // So we don't set a timeout.
675 }
676 sendMessageDelayed(
677 obtainMessage(
678 EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT,
679 phoneId, -1), BIND_TIMEOUT_MILLIS);
680 break;
681 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800682 }
683 }
Jonathan Basseri65273c82017-07-25 15:08:42 -0700684 }
685
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000686 @NonNull private final Handler mHandler;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800687
688 /**
689 * Constructs a CarrierConfigLoader, registers it as a service, and registers a broadcast
690 * receiver for relevant events.
691 */
Rambo Wang7e3bc122021-03-23 09:24:38 -0700692 @VisibleForTesting
Jack Yu3beaf9d2023-04-14 09:17:27 -0700693 /* package */ CarrierConfigLoader(@NonNull Context context, @NonNull Looper looper) {
mattgilbride5b6b7182023-04-03 18:56:44 +0000694 super(PermissionEnforcer.fromContext(context));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800695 mContext = context;
Meng Wang33ad2bc2017-03-16 20:21:20 -0700696 mPlatformCarrierConfigPackage =
697 mContext.getString(R.string.platform_carrier_config_package);
Rambo Wang7e3bc122021-03-23 09:24:38 -0700698 mHandler = new ConfigHandler(looper);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800699
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000700 IntentFilter systemEventsFilter = new IntentFilter();
701 systemEventsFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
Rambo Wanga27fbe52022-04-12 19:09:07 +0000702 context.registerReceiver(mSystemBroadcastReceiver, systemEventsFilter);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800703
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000704 mNumPhones = TelephonyManager.from(context).getActiveModemCount();
705 mConfigFromDefaultApp = new PersistableBundle[mNumPhones];
706 mConfigFromCarrierApp = new PersistableBundle[mNumPhones];
707 mPersistentOverrideConfigs = new PersistableBundle[mNumPhones];
708 mOverrideConfigs = new PersistableBundle[mNumPhones];
Rambo Wang42026112021-04-07 20:57:28 +0000709 mNoSimConfig = new PersistableBundle();
Rambo Wang8f16f3e2022-04-15 01:26:23 +0000710 mServiceConnection = new CarrierServiceConnection[mNumPhones];
711 mServiceBound = new boolean[mNumPhones];
712 mHasSentConfigChange = new boolean[mNumPhones];
713 mFromSystemUnlocked = new boolean[mNumPhones];
714 mServiceConnectionForNoSimConfig = new CarrierServiceConnection[mNumPhones];
715 mServiceBoundForNoSimConfig = new boolean[mNumPhones];
Rambo Wanga27fbe52022-04-12 19:09:07 +0000716 mCarrierServiceChangeCallbacks = new CarrierServiceChangeCallback[mNumPhones];
717 for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
718 mCarrierServiceChangeCallbacks[phoneId] = new CarrierServiceChangeCallback(phoneId);
719 TelephonyManager.from(context).registerCarrierPrivilegesCallback(phoneId,
720 new HandlerExecutor(mHandler), mCarrierServiceChangeCallbacks[phoneId]);
721 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800722 logd("CarrierConfigLoader has started");
Jack Yu771c6ce2023-02-02 17:51:42 -0800723
724 PhoneConfigurationManager.registerForMultiSimConfigChange(
725 mHandler, EVENT_MULTI_SIM_CONFIG_CHANGED, null);
726
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700727 mHandler.sendEmptyMessage(EVENT_CHECK_SYSTEM_UPDATE);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800728 }
729
730 /**
731 * Initialize the singleton CarrierConfigLoader instance.
732 *
733 * This is only done once, at startup, from {@link com.android.phone.PhoneApp#onCreate}.
734 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000735 @NonNull
736 /* package */ static CarrierConfigLoader init(@NonNull Context context) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800737 synchronized (CarrierConfigLoader.class) {
738 if (sInstance == null) {
Jack Yu3beaf9d2023-04-14 09:17:27 -0700739 sInstance = new CarrierConfigLoader(context, Looper.myLooper());
Brad Ebingerfa6575f2021-05-04 00:29:50 +0000740 // Make this service available through ServiceManager.
741 TelephonyFrameworkInitializer.getTelephonyServiceManager()
742 .getCarrierConfigServiceRegisterer().register(sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800743 } else {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700744 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800745 }
746 return sInstance;
747 }
748 }
749
Rambo Wang7e3bc122021-03-23 09:24:38 -0700750 @VisibleForTesting
751 /* package */ void clearConfigForPhone(int phoneId, boolean fetchNoSimConfig) {
Malcolm Chen5ea18532019-10-24 19:55:44 -0700752 /* Ignore clear configuration request if device is being shutdown. */
753 Phone phone = PhoneFactory.getPhone(phoneId);
754 if (phone != null) {
755 if (phone.isShuttingDown()) {
756 return;
757 }
758 }
759
Jack Yu771c6ce2023-02-02 17:51:42 -0800760 if (mConfigFromDefaultApp.length <= phoneId) {
761 Log.wtf(LOG_TAG, "Invalid phone id " + phoneId);
762 return;
763 }
764
Malcolm Chen5ea18532019-10-24 19:55:44 -0700765 mConfigFromDefaultApp[phoneId] = null;
766 mConfigFromCarrierApp[phoneId] = null;
767 mServiceConnection[phoneId] = null;
768 mHasSentConfigChange[phoneId] = false;
769
Jayachandran C645ec612020-01-10 10:30:25 -0800770 if (fetchNoSimConfig) {
771 // To fetch no SIM config
772 mHandler.sendMessage(
773 mHandler.obtainMessage(
774 EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG, phoneId, -1));
775 }
Malcolm Chen5ea18532019-10-24 19:55:44 -0700776 }
777
Jack Yue37dd262022-12-16 11:53:37 -0800778 private void updateSubscriptionDatabase(int phoneId) {
Jack Yu90813e62023-01-17 17:46:27 -0800779 logd("updateSubscriptionDatabase: phoneId=" + phoneId);
Jack Yue37dd262022-12-16 11:53:37 -0800780 String configPackageName;
Nathan Harold48ac0972019-03-13 22:33:01 -0700781 PersistableBundle configToSend;
782 int carrierId = getSpecificCarrierIdForPhoneId(phoneId);
783 // Prefer the carrier privileged carrier app, but if there is not one, use the platform
784 // default carrier app.
785 if (mConfigFromCarrierApp[phoneId] != null) {
Jack Yue37dd262022-12-16 11:53:37 -0800786 configPackageName = getCarrierPackageForPhoneId(phoneId);
Nathan Harold48ac0972019-03-13 22:33:01 -0700787 configToSend = mConfigFromCarrierApp[phoneId];
788 } else {
Jack Yue37dd262022-12-16 11:53:37 -0800789 configPackageName = mPlatformCarrierConfigPackage;
Nathan Harold48ac0972019-03-13 22:33:01 -0700790 configToSend = mConfigFromDefaultApp[phoneId];
791 }
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700792
Malcolm Chenefafd1c2020-02-20 13:27:08 -0800793 if (configToSend == null) {
Rambo Wang42026112021-04-07 20:57:28 +0000794 configToSend = new PersistableBundle();
Malcolm Chenefafd1c2020-02-20 13:27:08 -0800795 }
796
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700797 // mOverrideConfigs is for testing. And it will override current configs.
798 PersistableBundle config = mOverrideConfigs[phoneId];
799 if (config != null) {
Torbjorn Eklund1050cb02018-11-16 14:05:38 +0100800 configToSend = new PersistableBundle(configToSend);
Nazanin Bakhshi6fcc3342019-09-18 17:54:01 -0700801 configToSend.putAll(config);
802 }
803
Jack Yu3beaf9d2023-04-14 09:17:27 -0700804 SubscriptionManagerService.getInstance().updateSubscriptionByCarrierConfig(
805 phoneId, configPackageName, configToSend,
806 () -> mHandler.obtainMessage(EVENT_SUBSCRIPTION_INFO_UPDATED, phoneId, -1)
807 .sendToTarget());
Nathan Harold48ac0972019-03-13 22:33:01 -0700808 }
809
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800810 private void broadcastConfigChangedIntent(int phoneId) {
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800811 broadcastConfigChangedIntent(phoneId, true);
812 }
813
814 private void broadcastConfigChangedIntent(int phoneId, boolean addSubIdExtra) {
rambowangd63ba342022-10-02 11:21:08 -0500815 int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
816 int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
817 int specificCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
818
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800819 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
Christopher Tate38f55eb2017-02-14 14:43:49 -0800820 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT |
chen xuf9db49f2019-03-31 23:04:42 -0700821 Intent.FLAG_RECEIVER_FOREGROUND);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800822 if (addSubIdExtra) {
rambowangd63ba342022-10-02 11:21:08 -0500823 int simApplicationState = getSimApplicationStateForPhone(phoneId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800824 // Include subId/carrier id extra only if SIM records are loaded
825 if (simApplicationState != TelephonyManager.SIM_STATE_UNKNOWN
826 && simApplicationState != TelephonyManager.SIM_STATE_NOT_READY) {
rambowangd63ba342022-10-02 11:21:08 -0500827 subId = SubscriptionManager.getSubscriptionId(phoneId);
828 carrierId = getCarrierIdForPhoneId(phoneId);
829 specificCarrierId = getSpecificCarrierIdForPhoneId(phoneId);
830 intent.putExtra(TelephonyManager.EXTRA_SPECIFIC_CARRIER_ID, specificCarrierId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800831 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, phoneId);
rambowangd63ba342022-10-02 11:21:08 -0500832 intent.putExtra(TelephonyManager.EXTRA_CARRIER_ID, carrierId);
Qiongcheng Luoe7de61b2018-08-06 10:20:09 +0800833 }
Amit Mahajanf8088ab2018-03-02 15:24:07 -0800834 }
Amit Mahajanb33bcda2018-01-24 12:56:44 -0800835 intent.putExtra(CarrierConfigManager.EXTRA_SLOT_INDEX, phoneId);
Sarah Chin807d5c62020-03-30 17:21:09 -0700836 intent.putExtra(CarrierConfigManager.EXTRA_REBROADCAST_ON_UNLOCK,
837 mFromSystemUnlocked[phoneId]);
rambowangd63ba342022-10-02 11:21:08 -0500838
839 TelephonyRegistryManager trm = mContext.getSystemService(TelephonyRegistryManager.class);
840 // Unlike broadcast, we wouldn't notify registrants on carrier config change when device is
841 // unlocked. Only real carrier config change will send the notification to registrants.
842 if (trm != null && !mFromSystemUnlocked[phoneId]) {
843 trm.notifyCarrierConfigChanged(phoneId, subId, carrierId, specificCarrierId);
844 }
845
Meng Wang97a6a462020-01-23 16:22:16 -0800846 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
rambowangd63ba342022-10-02 11:21:08 -0500847
Jack Yu00ece8c2022-11-19 22:29:12 -0800848 if (SubscriptionManager.isValidSubscriptionId(subId)) {
849 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId + ", subId=" + subId);
Jack Yue9e95be2020-03-22 10:56:06 -0700850 } else {
851 logd("Broadcast CARRIER_CONFIG_CHANGED for phone " + phoneId);
852 }
Junda Liu03aad762017-07-21 13:32:17 -0700853 mHasSentConfigChange[phoneId] = true;
Sarah Chin807d5c62020-03-30 17:21:09 -0700854 mFromSystemUnlocked[phoneId] = false;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800855 }
856
rambowangd63ba342022-10-02 11:21:08 -0500857 private int getSimApplicationStateForPhone(int phoneId) {
858 int simApplicationState = TelephonyManager.SIM_STATE_UNKNOWN;
859 int subId = SubscriptionManager.getSubscriptionId(phoneId);
860 if (SubscriptionManager.isValidSubscriptionId(subId)) {
861 TelephonyManager telMgr = TelephonyManager.from(mContext)
862 .createForSubscriptionId(subId);
863 simApplicationState = telMgr.getSimApplicationState();
864 }
865 return simApplicationState;
866 }
867
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800868 /** Binds to the default or carrier config app. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000869 private boolean bindToConfigPackage(@NonNull String pkgName, int phoneId, int eventId) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -0800870 logdWithLocalLog("Binding to " + pkgName + " for phone " + phoneId);
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700871 Intent carrierService = new Intent(CarrierService.CARRIER_SERVICE_INTERFACE);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700872 carrierService.setPackage(pkgName);
Jayachandran C645ec612020-01-10 10:30:25 -0800873 CarrierServiceConnection serviceConnection = new CarrierServiceConnection(
874 phoneId, pkgName, eventId);
875 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
876 mServiceConnectionForNoSimConfig[phoneId] = serviceConnection;
877 } else {
878 mServiceConnection[phoneId] = serviceConnection;
879 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800880 try {
Jayachandran C645ec612020-01-10 10:30:25 -0800881 if (mContext.bindService(carrierService, serviceConnection,
Jordan Liu178430d2020-02-10 14:32:15 -0800882 Context.BIND_AUTO_CREATE)) {
Rambo Wangb0f3e2f2021-10-28 12:40:12 -0700883 if (eventId == EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG) {
884 mServiceBoundForNoSimConfig[phoneId] = true;
885 } else {
886 mServiceBound[phoneId] = true;
887 }
Jordan Liu178430d2020-02-10 14:32:15 -0800888 return true;
889 } else {
890 return false;
891 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800892 } catch (SecurityException ex) {
893 return false;
894 }
895 }
896
Rambo Wang7e3bc122021-03-23 09:24:38 -0700897 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000898 @NonNull
Rambo Wang7e3bc122021-03-23 09:24:38 -0700899 /* package */ CarrierIdentifier getCarrierIdentifierForPhoneId(int phoneId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800900 String mcc = "";
901 String mnc = "";
902 String imsi = "";
903 String gid1 = "";
904 String gid2 = "";
905 String spn = TelephonyManager.from(mContext).getSimOperatorNameForPhone(phoneId);
906 String simOperator = TelephonyManager.from(mContext).getSimOperatorNumericForPhone(phoneId);
chen xu02581692018-11-11 19:03:44 -0800907 int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
chen xua31f22b2019-03-06 15:28:50 -0800908 int specificCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
Jonathan Basseri1fa437c2015-04-20 11:08:18 -0700909 // A valid simOperator should be 5 or 6 digits, depending on the length of the MNC.
910 if (simOperator != null && simOperator.length() >= 3) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800911 mcc = simOperator.substring(0, 3);
912 mnc = simOperator.substring(3);
913 }
914 Phone phone = PhoneFactory.getPhone(phoneId);
915 if (phone != null) {
916 imsi = phone.getSubscriberId();
917 gid1 = phone.getGroupIdLevel1();
Junda Liu73183532015-05-14 13:55:40 -0700918 gid2 = phone.getGroupIdLevel2();
chen xu02581692018-11-11 19:03:44 -0800919 carrierId = phone.getCarrierId();
chen xua31f22b2019-03-06 15:28:50 -0800920 specificCarrierId = phone.getSpecificCarrierId();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800921 }
chen xua31f22b2019-03-06 15:28:50 -0800922 return new CarrierIdentifier(mcc, mnc, spn, imsi, gid1, gid2, carrierId, specificCarrierId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800923 }
924
Rambo Wangf7c214a2022-03-17 12:36:22 -0700925 /** Returns the package name of a privileged carrier app, or null if there is none. */
Nathan Harold1122e3d2021-01-22 15:45:24 -0800926 @Nullable
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700927 private String getCarrierPackageForPhoneId(int phoneId) {
Nazanin1adf4562021-03-29 15:35:30 -0700928 final long token = Binder.clearCallingIdentity();
929 try {
Rambo Wangf7c214a2022-03-17 12:36:22 -0700930 return TelephonyManager.from(mContext)
931 .getCarrierServicePackageNameForLogicalSlot(phoneId);
Nazanin1adf4562021-03-29 15:35:30 -0700932 } finally {
933 Binder.restoreCallingIdentity(token);
934 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700935 }
936
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000937 @Nullable
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700938 private String getIccIdForPhoneId(int phoneId) {
939 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
940 return null;
941 }
942 Phone phone = PhoneFactory.getPhone(phoneId);
943 if (phone == null) {
944 return null;
945 }
946 return phone.getIccSerialNumber();
947 }
948
chen xu02581692018-11-11 19:03:44 -0800949 /**
chen xua31f22b2019-03-06 15:28:50 -0800950 * Get the sim specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}
chen xu02581692018-11-11 19:03:44 -0800951 */
chen xua31f22b2019-03-06 15:28:50 -0800952 private int getSpecificCarrierIdForPhoneId(int phoneId) {
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700953 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
chen xu02581692018-11-11 19:03:44 -0800954 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700955 }
956 Phone phone = PhoneFactory.getPhone(phoneId);
957 if (phone == null) {
chen xu02581692018-11-11 19:03:44 -0800958 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700959 }
chen xua31f22b2019-03-06 15:28:50 -0800960 return phone.getSpecificCarrierId();
chen xu02581692018-11-11 19:03:44 -0800961 }
962
963 /**
964 * Get the sim carrier id {@link TelephonyManager#getSimCarrierId() }
965 */
966 private int getCarrierIdForPhoneId(int phoneId) {
967 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
968 return TelephonyManager.UNKNOWN_CARRIER_ID;
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700969 }
chen xu02581692018-11-11 19:03:44 -0800970 Phone phone = PhoneFactory.getPhone(phoneId);
971 if (phone == null) {
972 return TelephonyManager.UNKNOWN_CARRIER_ID;
973 }
974 return phone.getCarrierId();
Naina Nalluri86fc7b02018-08-03 10:38:30 -0700975 }
976
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700977 /**
978 * Writes a bundle to an XML file.
979 *
chen xu02581692018-11-11 19:03:44 -0800980 * The bundle will be written to a file named after the package name, ICCID and
chen xua31f22b2019-03-06 15:28:50 -0800981 * specific carrier id {@link TelephonyManager#getSimSpecificCarrierId()}. the same carrier
chen xu02581692018-11-11 19:03:44 -0800982 * should have a single copy of XML file named after carrier id. However, it's still possible
983 * that platform doesn't recognize the current sim carrier, we will use iccid + carrierid as
984 * the canonical file name. carrierid can also handle the cases SIM OTA resolves to different
985 * carrier while iccid remains the same.
986 *
987 * The file can be restored later with {@link @restoreConfigFromXml}. The XML output will
988 * include the bundle and the current version of the specified package.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700989 *
990 * In case of errors or invalid input, no file will be written.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700991 *
Jayachandran C645ec612020-01-10 10:30:25 -0800992 * @param packageName the name of the package from which we fetched this bundle.
993 * @param extraString An extra string to be used in the XML file name.
994 * @param phoneId the phone ID.
995 * @param carrierId contains all carrier-identifying information.
996 * @param config the bundle to be written. Null will be treated as an empty bundle.
997 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700998 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +0000999 private void saveConfigToXml(@Nullable String packageName, @NonNull String extraString,
1000 int phoneId, @Nullable CarrierIdentifier carrierId, @NonNull PersistableBundle config,
1001 boolean isNoSimConfig) {
Jayachandran C645ec612020-01-10 10:30:25 -08001002 if (packageName == null) {
Jack Yu9be55d32023-08-10 13:47:46 -07001003 loge("Cannot save config with null packageName. phoneId=" + phoneId);
Yuchen Dongc15afed2018-04-26 17:05:22 +08001004 return;
1005 }
1006
Jayachandran C645ec612020-01-10 10:30:25 -08001007 String fileName;
1008 if (isNoSimConfig) {
1009 fileName = getFilenameForNoSimConfig(packageName);
1010 } else {
Jack Yuf5badd92022-12-08 00:50:53 -08001011 if (TelephonyManager.getSimStateForSlotIndex(phoneId)
Jayachandran C645ec612020-01-10 10:30:25 -08001012 != TelephonyManager.SIM_STATE_LOADED) {
Jack Yu9be55d32023-08-10 13:47:46 -07001013 loge("Skip saving config because SIM records are not loaded. phoneId=" + phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -08001014 return;
1015 }
1016
1017 final String iccid = getIccIdForPhoneId(phoneId);
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001018 final int cid = carrierId != null ? carrierId.getSpecificCarrierId()
1019 : TelephonyManager.UNKNOWN_CARRIER_ID;
Jayachandran C645ec612020-01-10 10:30:25 -08001020 if (iccid == null) {
Jack Yu9be55d32023-08-10 13:47:46 -07001021 loge("Cannot save config with null iccid. phoneId=" + phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -08001022 return;
1023 }
1024 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001025 }
Jayachandran C645ec612020-01-10 10:30:25 -08001026
Junda Liu02596502016-11-15 13:46:43 -08001027 // b/32668103 Only save to file if config isn't empty.
1028 // In case of failure, not caching an empty bundle will
1029 // try loading config again on next power on or sim loaded.
1030 // Downside is for genuinely empty bundle, will bind and load
1031 // on every power on.
1032 if (config == null || config.isEmpty()) {
1033 return;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001034 }
1035
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001036 final String version = getPackageVersion(packageName);
1037 if (version == null) {
Jack Yu9be55d32023-08-10 13:47:46 -07001038 loge("Failed to get package version for: " + packageName + ", phoneId=" + phoneId);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001039 return;
1040 }
1041
Jack Yu9be55d32023-08-10 13:47:46 -07001042 logdWithLocalLog("Save carrier config to cache. phoneId=" + phoneId
1043 + ", xml=" + getFilePathForLogging(fileName) + ", version=" + version);
chen xudb04c292019-03-26 17:01:15 -07001044
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001045 FileOutputStream outFile = null;
1046 try {
Jayachandran C645ec612020-01-10 10:30:25 -08001047 outFile = new FileOutputStream(new File(mContext.getFilesDir(), fileName));
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001048 config.putString(KEY_VERSION, version);
1049 config.writeToStream(outFile);
1050 outFile.flush();
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001051 outFile.close();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001052 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001053 loge(e.toString());
1054 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001055 }
1056
Rambo Wang7e3bc122021-03-23 09:24:38 -07001057 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001058 /* package */ void saveConfigToXml(@Nullable String packageName, @NonNull String extraString,
1059 int phoneId, @NonNull CarrierIdentifier carrierId, @NonNull PersistableBundle config) {
Jayachandran C645ec612020-01-10 10:30:25 -08001060 saveConfigToXml(packageName, extraString, phoneId, carrierId, config, false);
1061 }
1062
Rambo Wang7e3bc122021-03-23 09:24:38 -07001063 @VisibleForTesting
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001064 /* package */ void saveNoSimConfigToXml(@Nullable String packageName,
1065 @NonNull PersistableBundle config) {
Jayachandran C645ec612020-01-10 10:30:25 -08001066 saveConfigToXml(packageName, "", -1, null, config, true);
1067 }
1068
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001069 /**
1070 * Reads a bundle from an XML file.
1071 *
1072 * This restores a bundle that was written with {@link #saveConfigToXml}. This returns the saved
Yuchen Dongc15afed2018-04-26 17:05:22 +08001073 * config bundle for the given package and phone ID.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001074 *
1075 * In case of errors, or if the saved config is from a different package version than the
1076 * current version, then null will be returned.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001077 *
Jayachandran C645ec612020-01-10 10:30:25 -08001078 * @param packageName the name of the package from which we fetched this bundle.
1079 * @param extraString An extra string to be used in the XML file name.
1080 * @param phoneId the phone ID.
1081 * @param isNoSimConfig whether this is invoked for noSimConfig or not.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001082 * @return the bundle from the XML file. Returns null if there is no saved config, the saved
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001083 * version does not match, or reading config fails.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001084 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001085 @Nullable
1086 private PersistableBundle restoreConfigFromXml(@Nullable String packageName,
1087 @NonNull String extraString, int phoneId, boolean isNoSimConfig) {
Jayachandran C645ec612020-01-10 10:30:25 -08001088 if (packageName == null) {
1089 loge("Cannot restore config with null packageName");
1090 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001091 final String version = getPackageVersion(packageName);
1092 if (version == null) {
1093 loge("Failed to get package version for: " + packageName);
1094 return null;
1095 }
Yuchen Dongc15afed2018-04-26 17:05:22 +08001096
Jayachandran C645ec612020-01-10 10:30:25 -08001097 String fileName;
arunvoddu664c36a2021-10-11 20:09:28 +00001098 String iccid = null;
Jayachandran C645ec612020-01-10 10:30:25 -08001099 if (isNoSimConfig) {
1100 fileName = getFilenameForNoSimConfig(packageName);
1101 } else {
Jack Yuf5badd92022-12-08 00:50:53 -08001102 if (TelephonyManager.getSimStateForSlotIndex(phoneId)
Jayachandran C645ec612020-01-10 10:30:25 -08001103 != TelephonyManager.SIM_STATE_LOADED) {
Jack Yu9be55d32023-08-10 13:47:46 -07001104 loge("Skip restore config because SIM records are not loaded. phoneId=" + phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -08001105 return null;
1106 }
1107
arunvoddu664c36a2021-10-11 20:09:28 +00001108 iccid = getIccIdForPhoneId(phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -08001109 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1110 if (iccid == null) {
Jack Yu9be55d32023-08-10 13:47:46 -07001111 loge("Cannot restore config with null iccid. phoneId=" + phoneId);
Jayachandran C645ec612020-01-10 10:30:25 -08001112 return null;
1113 }
1114 fileName = getFilenameForConfig(packageName, extraString, iccid, cid);
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001115 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001116
1117 PersistableBundle restoredBundle = null;
Mateus Azisa13d2502023-05-25 08:44:38 -07001118 File file = new File(mContext.getFilesDir(), fileName);
Jack Yu9be55d32023-08-10 13:47:46 -07001119 String filePath = file.getPath();
1120 String savedVersion = null;
Mateus Azisa13d2502023-05-25 08:44:38 -07001121 try (FileInputStream inFile = new FileInputStream(file)) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001122
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001123 restoredBundle = PersistableBundle.readFromStream(inFile);
Jack Yu9be55d32023-08-10 13:47:46 -07001124 savedVersion = restoredBundle.getString(KEY_VERSION);
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001125 restoredBundle.remove(KEY_VERSION);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001126
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001127 if (!version.equals(savedVersion)) {
Jack Yu9be55d32023-08-10 13:47:46 -07001128 loge("Saved version mismatch: " + version + " vs " + savedVersion
1129 + ", phoneId=" + phoneId);
Meng Wang0f6b2ea2020-01-06 18:31:16 -08001130 restoredBundle = null;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001131 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001132 } catch (FileNotFoundException e) {
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001133 // Missing file is normal occurrence that might occur with a new sim or when restoring
1134 // an override file during boot and should not be treated as an error.
Mateus Azisa13d2502023-05-25 08:44:38 -07001135 if (isNoSimConfig) {
Jack Yu9be55d32023-08-10 13:47:46 -07001136 logd("File not found: " + file.getPath() + ", phoneId=" + phoneId);
Mateus Azisa13d2502023-05-25 08:44:38 -07001137 } else {
Jack Yu9be55d32023-08-10 13:47:46 -07001138 logd("File not found : " + getFilePathForLogging(filePath, iccid)
1139 + ", phoneId=" + phoneId);
arunvoddu664c36a2021-10-11 20:09:28 +00001140 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001141 } catch (IOException e) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001142 loge(e.toString());
1143 }
1144
Jack Yu9be55d32023-08-10 13:47:46 -07001145 if (restoredBundle != null) {
1146 logdWithLocalLog("Restored carrier config from cache. phoneId=" + phoneId + ", xml="
1147 + getFilePathForLogging(fileName) + ", version=" + savedVersion
1148 + ", modified time=" + getFileTime(filePath));
1149 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001150 return restoredBundle;
1151 }
1152
arunvoddu664c36a2021-10-11 20:09:28 +00001153 /**
1154 * This method will mask most part of iccid in the filepath for logging on userbuild
1155 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001156 @NonNull
1157 private String getFilePathForLogging(@Nullable String filePath, @Nullable String iccid) {
arunvoddu664c36a2021-10-11 20:09:28 +00001158 // If loggable then return with actual file path
Jack Yu9be55d32023-08-10 13:47:46 -07001159 if (TelephonyUtils.IS_DEBUGGABLE) {
arunvoddu664c36a2021-10-11 20:09:28 +00001160 return filePath;
1161 }
1162 String path = filePath;
1163 int length = (iccid != null) ? iccid.length() : 0;
1164 if (length > 5 && filePath != null) {
1165 path = filePath.replace(iccid.substring(5), "***************");
1166 }
1167 return path;
1168 }
1169
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001170 @Nullable
1171 private PersistableBundle restoreConfigFromXml(@Nullable String packageName,
1172 @NonNull String extraString, int phoneId) {
Jayachandran C645ec612020-01-10 10:30:25 -08001173 return restoreConfigFromXml(packageName, extraString, phoneId, false);
1174 }
1175
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001176 @Nullable
1177 private PersistableBundle restoreNoSimConfigFromXml(@Nullable String packageName) {
Jayachandran C645ec612020-01-10 10:30:25 -08001178 return restoreConfigFromXml(packageName, "", -1, true);
1179 }
1180
Junda Liu8a8a53a2015-05-15 16:19:57 -07001181 /**
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001182 * Clears cached carrier config.
1183 * This deletes all saved XML files associated with the given package name. If packageName is
1184 * null, then it deletes all saved XML files.
1185 *
1186 * @param packageName the name of a carrier package, or null if all cached config should be
1187 * cleared.
1188 * @return true iff one or more files were deleted.
Junda Liu8a8a53a2015-05-15 16:19:57 -07001189 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001190 private boolean clearCachedConfigForPackage(@Nullable final String packageName) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001191 File dir = mContext.getFilesDir();
1192 File[] packageFiles = dir.listFiles(new FilenameFilter() {
1193 public boolean accept(File dir, String filename) {
Jonathan Basseri7697cae2015-07-06 15:49:23 -07001194 if (packageName != null) {
1195 return filename.startsWith("carrierconfig-" + packageName + "-");
1196 } else {
1197 return filename.startsWith("carrierconfig-");
1198 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001199 }
1200 });
Junda Liu8a8a53a2015-05-15 16:19:57 -07001201 if (packageFiles == null || packageFiles.length < 1) return false;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001202 for (File f : packageFiles) {
Jack Yu9be55d32023-08-10 13:47:46 -07001203 logdWithLocalLog("Deleting " + getFilePathForLogging(f.getName()));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001204 f.delete();
1205 }
Junda Liu8a8a53a2015-05-15 16:19:57 -07001206 return true;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001207 }
1208
arunvoddub7c6e8e2022-09-05 15:48:06 +00001209 private String getFilePathForLogging(String filePath) {
1210 if (!TextUtils.isEmpty(filePath)) {
1211 String[] fileTokens = filePath.split("-");
1212 if (fileTokens != null && fileTokens.length > 2) {
1213 String iccid = fileTokens[fileTokens.length -2];
1214 return getFilePathForLogging(filePath, iccid);
1215 }
1216 return filePath;
1217 }
1218 return filePath;
1219 }
1220
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001221 /** Builds a canonical file name for a config file. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001222 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001223 private static String getFilenameForConfig(
1224 @NonNull String packageName, @NonNull String extraString,
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001225 @NonNull String iccid, int cid) {
chen xu02581692018-11-11 19:03:44 -08001226 // the same carrier should have a single copy of XML file named after carrier id.
1227 // However, it's still possible that platform doesn't recognize the current sim carrier,
1228 // we will use iccid + carrierid as the canonical file name. carrierid can also handle the
1229 // cases SIM OTA resolves to different carrier while iccid remains the same.
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001230 return "carrierconfig-" + packageName + extraString + "-" + iccid + "-" + cid + ".xml";
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001231 }
1232
Jayachandran C645ec612020-01-10 10:30:25 -08001233 /** Builds a canonical file name for no SIM config file. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001234 @NonNull
Jayachandran C645ec612020-01-10 10:30:25 -08001235 private String getFilenameForNoSimConfig(@NonNull String packageName) {
1236 return "carrierconfig-" + packageName + "-" + "nosim" + ".xml";
1237 }
1238
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001239 /** Return the current version code of a package, or null if the name is not found. */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001240 @Nullable
1241 private String getPackageVersion(@NonNull String packageName) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001242 try {
1243 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
Dianne Hackbornb76ab202017-11-28 17:44:50 -08001244 return Long.toString(info.getLongVersionCode());
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001245 } catch (PackageManager.NameNotFoundException e) {
1246 return null;
1247 }
1248 }
1249
Jonathan Basseri65273c82017-07-25 15:08:42 -07001250 /**
1251 * Read up to date config.
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001252 *
1253 * This reads config bundles for the given phoneId. That means getting the latest bundle from
1254 * the default app and a privileged carrier app, if present. This will not bind to an app if we
1255 * have a saved config file to use instead.
1256 */
1257 private void updateConfigForPhoneId(int phoneId) {
Jonathan Basseri65273c82017-07-25 15:08:42 -07001258 mHandler.sendMessage(mHandler.obtainMessage(EVENT_DO_FETCH_DEFAULT, phoneId, -1));
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001259 }
1260
Malcolm Chen5ea18532019-10-24 19:55:44 -07001261 private void onMultiSimConfigChanged() {
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001262 int oldNumPhones = mNumPhones;
1263 mNumPhones = TelephonyManager.from(mContext).getActiveModemCount();
1264 if (mNumPhones == oldNumPhones) {
1265 return;
1266 }
1267 logdWithLocalLog("mNumPhones change from " + oldNumPhones + " to " + mNumPhones);
1268
Rambo Wanga27fbe52022-04-12 19:09:07 +00001269 // If DS -> SS switch, release the resources BEFORE truncating the arrays to avoid leaking
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001270 for (int phoneId = mNumPhones; phoneId < oldNumPhones; phoneId++) {
1271 if (mServiceConnection[phoneId] != null) {
1272 unbindIfBound(mContext, mServiceConnection[phoneId], phoneId);
1273 }
1274 if (mServiceConnectionForNoSimConfig[phoneId] != null) {
1275 unbindIfBoundForNoSimConfig(mContext, mServiceConnectionForNoSimConfig[phoneId],
1276 phoneId);
1277 }
1278 }
1279
Rambo Wanga27fbe52022-04-12 19:09:07 +00001280 // The phone to slot mapping may change, unregister here and re-register callbacks later
1281 for (int phoneId = 0; phoneId < oldNumPhones; phoneId++) {
1282 if (mCarrierServiceChangeCallbacks[phoneId] != null) {
1283 TelephonyManager.from(mContext).unregisterCarrierPrivilegesCallback(
1284 mCarrierServiceChangeCallbacks[phoneId]);
1285 }
1286 }
1287
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001288 // Copy the original arrays, truncate or padding with zeros (if necessary) to new length
1289 mConfigFromDefaultApp = Arrays.copyOf(mConfigFromDefaultApp, mNumPhones);
1290 mConfigFromCarrierApp = Arrays.copyOf(mConfigFromCarrierApp, mNumPhones);
1291 mPersistentOverrideConfigs = Arrays.copyOf(mPersistentOverrideConfigs, mNumPhones);
1292 mOverrideConfigs = Arrays.copyOf(mOverrideConfigs, mNumPhones);
1293 mServiceConnection = Arrays.copyOf(mServiceConnection, mNumPhones);
1294 mServiceConnectionForNoSimConfig =
1295 Arrays.copyOf(mServiceConnectionForNoSimConfig, mNumPhones);
1296 mServiceBound = Arrays.copyOf(mServiceBound, mNumPhones);
1297 mServiceBoundForNoSimConfig = Arrays.copyOf(mServiceBoundForNoSimConfig, mNumPhones);
1298 mHasSentConfigChange = Arrays.copyOf(mHasSentConfigChange, mNumPhones);
1299 mFromSystemUnlocked = Arrays.copyOf(mFromSystemUnlocked, mNumPhones);
Rambo Wanga27fbe52022-04-12 19:09:07 +00001300 mCarrierServiceChangeCallbacks = Arrays.copyOf(mCarrierServiceChangeCallbacks, mNumPhones);
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001301
Rambo Wanga27fbe52022-04-12 19:09:07 +00001302 // Load the config for all the phones and re-register callback AFTER padding the arrays.
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001303 for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
1304 updateConfigForPhoneId(phoneId);
Rambo Wanga27fbe52022-04-12 19:09:07 +00001305 mCarrierServiceChangeCallbacks[phoneId] = new CarrierServiceChangeCallback(phoneId);
1306 TelephonyManager.from(mContext).registerCarrierPrivilegesCallback(phoneId,
1307 new HandlerExecutor(mHandler), mCarrierServiceChangeCallbacks[phoneId]);
Malcolm Chen5ea18532019-10-24 19:55:44 -07001308 }
1309 }
1310
Hall Liu506724b2018-10-22 18:16:14 -07001311 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001312 @NonNull
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001313 public PersistableBundle getConfigForSubId(int subscriptionId, @NonNull String callingPackage) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001314 return getConfigForSubIdWithFeature(subscriptionId, callingPackage, null);
Philip P. Moltmann9797cbb2020-01-07 13:45:00 -08001315 }
1316
1317 @Override
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001318 @NonNull
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001319 public PersistableBundle getConfigForSubIdWithFeature(int subscriptionId,
1320 @NonNull String callingPackage, @Nullable String callingFeatureId) {
Rambo Wangd2b004b2021-03-30 10:10:23 -07001321 if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(mContext, subscriptionId,
1322 callingPackage, callingFeatureId, "getCarrierConfig")) {
Rambo Wang42026112021-04-07 20:57:28 +00001323 return new PersistableBundle();
Amit Mahajan40b3fa52015-07-14 10:27:19 -07001324 }
Jeff Davidsona8e4e242018-03-15 17:16:18 -07001325
Rambo Wangd2b004b2021-03-30 10:10:23 -07001326 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001327 PersistableBundle retConfig = CarrierConfigManager.getDefaultConfig();
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001328 if (SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseric31f1f32015-05-12 10:13:03 -07001329 PersistableBundle config = mConfigFromDefaultApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001330 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001331 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001332 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001333 config = mConfigFromCarrierApp[phoneId];
yinxuc5e27622017-11-29 15:08:50 -08001334 if (config != null) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001335 retConfig.putAll(config);
yinxuc5e27622017-11-29 15:08:50 -08001336 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001337 config = mPersistentOverrideConfigs[phoneId];
1338 if (config != null) {
1339 retConfig.putAll(config);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001340 }
Hall Liu506724b2018-10-22 18:16:14 -07001341 config = mOverrideConfigs[phoneId];
1342 if (config != null) {
1343 retConfig.putAll(config);
Hall Liu506724b2018-10-22 18:16:14 -07001344 }
Nathan Harold1122e3d2021-01-22 15:45:24 -08001345 // Ignore the theoretical case of the default app not being present since that won't
1346 // work in CarrierConfigLoader today.
1347 final boolean allConfigsApplied =
1348 (mConfigFromCarrierApp[phoneId] != null
1349 || getCarrierPackageForPhoneId(phoneId) == null)
1350 && mConfigFromDefaultApp[phoneId] != null;
1351 retConfig.putBoolean(
1352 CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, allConfigsApplied);
Jayachandran C645ec612020-01-10 10:30:25 -08001353 } else {
1354 if (mNoSimConfig != null) {
1355 retConfig.putAll(mNoSimConfig);
1356 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001357 }
1358 return retConfig;
1359 }
1360
1361 @Override
rambowang14757c22022-10-03 11:54:56 -05001362 @NonNull
1363 public PersistableBundle getConfigSubsetForSubIdWithFeature(int subscriptionId,
1364 @NonNull String callingPackage, @Nullable String callingFeatureId,
1365 @NonNull String[] keys) {
1366 Objects.requireNonNull(callingPackage, "Calling package must be non-null");
1367 Objects.requireNonNull(keys, "Config keys must be non-null");
1368 enforceCallerIsSystemOrRequestingPackage(callingPackage);
1369
1370 // Permission check is performed inside and an empty bundle will return on failure.
1371 // No SecurityException thrown here since most clients expect to retrieve the overridden
1372 // value if present or use default one if not
1373 PersistableBundle allConfigs = getConfigForSubIdWithFeature(subscriptionId, callingPackage,
1374 callingFeatureId);
1375 if (allConfigs.isEmpty()) {
1376 return allConfigs;
1377 }
1378 for (String key : keys) {
1379 Objects.requireNonNull(key, "Config key must be non-null");
rambowang14757c22022-10-03 11:54:56 -05001380 }
1381
1382 PersistableBundle configSubset = new PersistableBundle(
1383 keys.length + CONFIG_SUBSET_METADATA_KEYS.length);
1384 for (String carrierConfigKey : keys) {
1385 Object value = allConfigs.get(carrierConfigKey);
rambowangb49e90f2022-12-13 18:29:06 -06001386 if (value == null) {
1387 // Filter out keys without values.
1388 // In history, many AOSP or OEMs/carriers private configs didn't provide default
1389 // values. We have to continue supporting them for now. See b/261776046 for details.
1390 continue;
1391 }
rambowang14757c22022-10-03 11:54:56 -05001392 // Config value itself could be PersistableBundle which requires different API to put
1393 if (value instanceof PersistableBundle) {
1394 configSubset.putPersistableBundle(carrierConfigKey, (PersistableBundle) value);
1395 } else {
1396 configSubset.putObject(carrierConfigKey, value);
1397 }
1398 }
1399
1400 // Configs in CONFIG_SUBSET_ALWAYS_INCLUDED_KEYS should always be included
1401 for (String generalKey : CONFIG_SUBSET_METADATA_KEYS) {
1402 configSubset.putObject(generalKey, allConfigs.get(generalKey));
1403 }
1404
1405 return configSubset;
1406 }
1407
mattgilbride5b6b7182023-04-03 18:56:44 +00001408 @android.annotation.EnforcePermission(android.Manifest.permission.MODIFY_PHONE_STATE)
rambowang14757c22022-10-03 11:54:56 -05001409 @Override
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001410 public void overrideConfig(int subscriptionId, @Nullable PersistableBundle overrides,
1411 boolean persistent) {
mattgilbride5b6b7182023-04-03 18:56:44 +00001412 overrideConfig_enforcePermission();
Hall Liu506724b2018-10-22 18:16:14 -07001413 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1414 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001415 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
Rambo Wangd2b004b2021-03-30 10:10:23 -07001416 throw new IllegalArgumentException(
1417 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
Hall Liu506724b2018-10-22 18:16:14 -07001418 }
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001419 // Post to run on handler thread on which all states should be confined.
1420 mHandler.post(() -> {
1421 overrideConfig(mOverrideConfigs, phoneId, overrides);
Hall Liu506724b2018-10-22 18:16:14 -07001422
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001423 if (persistent) {
1424 overrideConfig(mPersistentOverrideConfigs, phoneId, overrides);
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001425
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001426 if (overrides != null) {
1427 final CarrierIdentifier carrierId = getCarrierIdentifierForPhoneId(phoneId);
1428 saveConfigToXml(mPlatformCarrierConfigPackage, OVERRIDE_PACKAGE_ADDITION,
1429 phoneId,
1430 carrierId, mPersistentOverrideConfigs[phoneId]);
1431 } else {
1432 final String iccid = getIccIdForPhoneId(phoneId);
1433 final int cid = getSpecificCarrierIdForPhoneId(phoneId);
1434 String fileName = getFilenameForConfig(mPlatformCarrierConfigPackage,
1435 OVERRIDE_PACKAGE_ADDITION, iccid, cid);
1436 File fileToDelete = new File(mContext.getFilesDir(), fileName);
1437 fileToDelete.delete();
1438 }
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001439 }
Jack Yu9be55d32023-08-10 13:47:46 -07001440 logdWithLocalLog("overrideConfig: subId=" + subscriptionId + ", persistent="
1441 + persistent + ", overrides=" + overrides);
Jack Yue37dd262022-12-16 11:53:37 -08001442 updateSubscriptionDatabase(phoneId);
Rambo Wang38eb5cd2021-03-29 16:39:14 -07001443 });
Hall Liu506724b2018-10-22 18:16:14 -07001444 }
1445
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001446 private void overrideConfig(@NonNull PersistableBundle[] currentOverrides, int phoneId,
1447 @Nullable PersistableBundle overrides) {
1448 if (overrides == null) {
Rambo Wang42026112021-04-07 20:57:28 +00001449 currentOverrides[phoneId] = new PersistableBundle();
Torbjorn Eklund723527a2019-02-13 11:16:25 +01001450 } else if (currentOverrides[phoneId] == null) {
1451 currentOverrides[phoneId] = overrides;
1452 } else {
1453 currentOverrides[phoneId].putAll(overrides);
1454 }
1455 }
1456
Hall Liu506724b2018-10-22 18:16:14 -07001457 @Override
Rambo Wangd2b004b2021-03-30 10:10:23 -07001458 public void notifyConfigChangedForSubId(int subscriptionId) {
Jordan Liud7d57fe2019-04-16 12:29:43 -07001459 // Requires the calling app to be either a carrier privileged app for this subId or
Junda Liufbd2bcb2016-06-15 11:15:42 -07001460 // system privileged app with MODIFY_PHONE_STATE permission.
Rambo Wangd2b004b2021-03-30 10:10:23 -07001461 TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(mContext,
1462 subscriptionId, "Require carrier privileges or MODIFY_PHONE_STATE permission.");
1463
1464 int phoneId = SubscriptionManager.getPhoneId(subscriptionId);
1465 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
1466 logd("Ignore invalid phoneId: " + phoneId + " for subId: " + subscriptionId);
1467 throw new IllegalArgumentException(
1468 "Invalid phoneId " + phoneId + " for subId " + subscriptionId);
1469 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001470
Jack Yu9be55d32023-08-10 13:47:46 -07001471 logdWithLocalLog("Notified carrier config changed. phoneId=" + phoneId
1472 + ", subId=" + subscriptionId);
1473
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001474 // 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();
Jack Yu9be55d32023-08-10 13:47:46 -07001487 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 /**
Jack Yu9be55d32023-08-10 13:47:46 -07001577 * Get the file time in readable format.
1578 *
1579 * @param filePath The full file path.
1580 *
1581 * @return The time in string format.
1582 */
1583 @Nullable
1584 private String getFileTime(@NonNull String filePath) {
1585 String formattedModifiedTime = null;
1586 try {
1587 // Convert the modified time to a readable format
1588 formattedModifiedTime = TIME_FORMAT.format(Files.readAttributes(Paths.get(filePath),
1589 BasicFileAttributes.class).lastModifiedTime().toMillis());
1590 } catch (Exception e) {
1591 e.printStackTrace();
1592 }
1593
1594 return formattedModifiedTime;
1595 }
1596
1597 /**
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001598 * If {@code args} contains {@link #DUMP_ARG_REQUESTING_PACKAGE} and a following package name,
1599 * we'll also call {@link IBinder#dump} on the default carrier service (if bound) and the
1600 * specified carrier service (if bound). Typically, this is done for connectivity bug reports
1601 * where we don't call {@code dumpsys activity service all-non-platform} because that contains
1602 * too much info, but we still want to let carrier apps include their diagnostics.
1603 */
Jeff Sharkeya6fcfed2017-07-20 14:18:39 -06001604 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001605 public void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter pw, @NonNull String[] args) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001606 IndentingPrintWriter indentPW = new IndentingPrintWriter(pw, " ");
Junda Liu43d723a2015-05-12 17:23:45 -07001607 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1608 != PackageManager.PERMISSION_GRANTED) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001609 indentPW.println("Permission Denial: can't dump carrierconfig from from pid="
Junda Liu43d723a2015-05-12 17:23:45 -07001610 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
1611 return;
1612 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001613 String requestingPackage = null;
1614 int requestingPackageIndex = ArrayUtils.indexOf(args, DUMP_ARG_REQUESTING_PACKAGE);
1615 if (requestingPackageIndex >= 0 && requestingPackageIndex < args.length - 1
1616 && !TextUtils.isEmpty(args[requestingPackageIndex + 1])) {
1617 requestingPackage = args[requestingPackageIndex + 1];
1618 // Throws a SecurityException if the caller is impersonating another app in an effort to
1619 // dump extra info (which may contain PII the caller doesn't have a right to).
1620 enforceCallerIsSystemOrRequestingPackage(requestingPackage);
1621 }
1622
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001623 indentPW.println("CarrierConfigLoader: " + this);
Rambo Wang8f16f3e2022-04-15 01:26:23 +00001624 for (int i = 0; i < mNumPhones; i++) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001625 indentPW.println("Phone Id = " + i);
shuoq26a3a4c2016-12-16 11:06:48 -08001626 // display default values in CarrierConfigManager
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001627 printConfig(CarrierConfigManager.getDefaultConfig(), indentPW,
shuoq26a3a4c2016-12-16 11:06:48 -08001628 "Default Values from CarrierConfigManager");
shuoq26a3a4c2016-12-16 11:06:48 -08001629 // display ConfigFromDefaultApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001630 printConfig(mConfigFromDefaultApp[i], indentPW, "mConfigFromDefaultApp");
shuoq26a3a4c2016-12-16 11:06:48 -08001631 // display ConfigFromCarrierApp
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001632 printConfig(mConfigFromCarrierApp[i], indentPW, "mConfigFromCarrierApp");
1633 printConfig(mPersistentOverrideConfigs[i], indentPW, "mPersistentOverrideConfigs");
1634 printConfig(mOverrideConfigs[i], indentPW, "mOverrideConfigs");
shuoq26a3a4c2016-12-16 11:06:48 -08001635 }
chen xudb04c292019-03-26 17:01:15 -07001636
Jayachandran C645ec612020-01-10 10:30:25 -08001637 printConfig(mNoSimConfig, indentPW, "mNoSimConfig");
Jack Yu9be55d32023-08-10 13:47:46 -07001638 indentPW.println("mNumPhones=" + mNumPhones);
1639 indentPW.println("mPlatformCarrierConfigPackage=" + mPlatformCarrierConfigPackage);
1640 indentPW.println("mServiceConnection=[" + Stream.of(mServiceConnection)
1641 .map(c -> c != null ? c.pkgName : null)
1642 .collect(Collectors.joining(", ")) + "]");
1643 indentPW.println("mServiceBoundForNoSimConfig="
1644 + Arrays.toString(mServiceBoundForNoSimConfig));
1645 indentPW.println("mHasSentConfigChange=" + Arrays.toString(mHasSentConfigChange));
1646 indentPW.println("mFromSystemUnlocked=" + Arrays.toString(mFromSystemUnlocked));
1647 indentPW.println();
1648 indentPW.println("CarrierConfigLoader local log=");
1649 indentPW.increaseIndent();
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001650 mCarrierConfigLoadingLog.dump(fd, indentPW, args);
Jack Yu9be55d32023-08-10 13:47:46 -07001651 indentPW.decreaseIndent();
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001652
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001653 if (requestingPackage != null) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001654 logd("Including default and requesting package " + requestingPackage
1655 + " carrier services in dump");
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001656 indentPW.println("");
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001657 indentPW.println("Connected services");
1658 dumpCarrierServiceIfBound(fd, indentPW, "Default config package",
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001659 mPlatformCarrierConfigPackage, false /* considerCarrierPrivileges */);
1660 dumpCarrierServiceIfBound(fd, indentPW, "Requesting package", requestingPackage,
1661 true /* considerCarrierPrivileges */);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001662 }
Jack Yu9be55d32023-08-10 13:47:46 -07001663
1664 indentPW.println();
1665 indentPW.println("Cached config files:");
1666 indentPW.increaseIndent();
1667 for (File f : mContext.getFilesDir().listFiles((FilenameFilter) (d, filename)
1668 -> filename.startsWith("carrierconfig-"))) {
1669 indentPW.println(getFilePathForLogging(f.getName()) + ", modified time="
1670 + getFileTime(f.getAbsolutePath()));
1671 }
1672 indentPW.decreaseIndent();
shuoq26a3a4c2016-12-16 11:06:48 -08001673 }
1674
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001675 private void printConfig(@NonNull PersistableBundle configApp,
1676 @NonNull IndentingPrintWriter indentPW, @NonNull String name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001677 indentPW.increaseIndent();
shuoq26a3a4c2016-12-16 11:06:48 -08001678 if (configApp == null) {
shuoq26a3a4c2016-12-16 11:06:48 -08001679 indentPW.println(name + " : null ");
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001680 indentPW.decreaseIndent();
1681 indentPW.println("");
shuoq26a3a4c2016-12-16 11:06:48 -08001682 return;
1683 }
shuoq26a3a4c2016-12-16 11:06:48 -08001684 indentPW.println(name + " : ");
1685 List<String> sortedKeys = new ArrayList<String>(configApp.keySet());
1686 Collections.sort(sortedKeys);
1687 indentPW.increaseIndent();
1688 indentPW.increaseIndent();
1689 for (String key : sortedKeys) {
1690 if (configApp.get(key) != null && configApp.get(key) instanceof Object[]) {
1691 indentPW.println(key + " = " +
1692 Arrays.toString((Object[]) configApp.get(key)));
1693 } else if (configApp.get(key) != null && configApp.get(key) instanceof int[]) {
1694 indentPW.println(key + " = " + Arrays.toString((int[]) configApp.get(key)));
1695 } else {
1696 indentPW.println(key + " = " + configApp.get(key));
1697 }
Junda Liu43d723a2015-05-12 17:23:45 -07001698 }
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001699 indentPW.decreaseIndent();
1700 indentPW.decreaseIndent();
1701 indentPW.decreaseIndent();
1702 indentPW.println("");
Junda Liu43d723a2015-05-12 17:23:45 -07001703 }
1704
Hunter Knepshielde601f432020-02-19 10:16:04 -08001705 /**
1706 * Passes without problem when one of these conditions is true:
1707 * - The caller is a privileged UID (e.g. for dumpstate.cpp generating a bug report, where the
1708 * system knows the true caller plumbed in through the {@link android.os.BugreportManager} API).
1709 * - The caller's UID matches the supplied package.
1710 *
1711 * @throws SecurityException if none of the above conditions are met.
1712 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001713 private void enforceCallerIsSystemOrRequestingPackage(@NonNull String requestingPackage)
Hunter Knepshielde601f432020-02-19 10:16:04 -08001714 throws SecurityException {
1715 final int callingUid = Binder.getCallingUid();
1716 if (callingUid == Process.ROOT_UID || callingUid == Process.SYSTEM_UID
1717 || callingUid == Process.SHELL_UID || callingUid == Process.PHONE_UID) {
1718 // Bug reports (dumpstate.cpp) run as SHELL, and let some other privileged UIDs through
1719 // as well.
1720 return;
1721 }
1722 // An app is trying to dump extra detail, block it if they aren't who they claim to be.
1723 AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
1724 if (appOps == null) {
1725 throw new SecurityException("No AppOps");
1726 }
1727 // Will throw a SecurityException if the UID and package don't match.
1728 appOps.checkPackage(callingUid, requestingPackage);
1729 }
1730
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001731 /**
1732 * Searches for one or more appropriate {@link CarrierService} instances to dump based on the
1733 * current connections.
1734 *
1735 * @param targetPkgName the target package name to dump carrier services for
1736 * @param considerCarrierPrivileges if true, allow a carrier service to be dumped if it shares
1737 * carrier privileges with {@code targetPkgName};
1738 * otherwise, only dump a carrier service if it is {@code
1739 * targetPkgName}
1740 */
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001741 private void dumpCarrierServiceIfBound(@NonNull FileDescriptor fd,
1742 @NonNull IndentingPrintWriter indentPW, @NonNull String prefix,
1743 @NonNull String targetPkgName, boolean considerCarrierPrivileges) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001744 // Null package is possible if it's early in the boot process, there was a recent crash, we
1745 // loaded the config from XML most recently, or a SIM slot is empty. Carrier apps with
1746 // long-lived bindings should typically get dumped here regardless. Even if an app is being
1747 // used for multiple phoneIds, we assume that it's smart enough to handle that on its own,
1748 // and that in most cases we'd just be dumping duplicate information and bloating a report.
1749 indentPW.increaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001750 indentPW.println(prefix + " : " + targetPkgName);
1751 Set<String> dumpedPkgNames = new ArraySet<>(mServiceConnection.length);
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001752 for (CarrierServiceConnection connection : mServiceConnection) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001753 if (connection == null || !SubscriptionManager.isValidPhoneId(connection.phoneId)
1754 || TextUtils.isEmpty(connection.pkgName)) {
1755 continue;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001756 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001757 final String servicePkgName = connection.pkgName;
1758 // Note: we intentionally ignore system components here because we should NOT match the
1759 // shell caller that's typically used for bug reports via non-BugreportManager triggers.
1760 final boolean exactPackageMatch = TextUtils.equals(targetPkgName, servicePkgName);
1761 final boolean carrierPrivilegesMatch =
1762 considerCarrierPrivileges && hasCarrierPrivileges(targetPkgName,
1763 connection.phoneId);
1764 if (!exactPackageMatch && !carrierPrivilegesMatch) continue;
1765 // Make sure this service is actually alive before trying to dump it. We don't pay
1766 // attention to mServiceBound[connection.phoneId] because typically carrier apps will
1767 // request long-lived bindings, and even if we unbind the app, it may still be alive due
1768 // to CarrierServiceBindHelper. Pull it out as a reference so even if it gets set to
1769 // null within the ServiceConnection during unbinding we can avoid an NPE.
1770 final IBinder service = connection.service;
1771 if (service == null || !service.isBinderAlive() || !service.pingBinder()) continue;
1772 // We've got a live service. Last check is just to make sure we don't dump a package
1773 // multiple times.
1774 if (!dumpedPkgNames.add(servicePkgName)) continue;
1775 if (!exactPackageMatch) {
1776 logd(targetPkgName + " has carrier privileges on phoneId " + connection.phoneId
1777 + ", service provided by " + servicePkgName);
1778 indentPW.increaseIndent();
1779 indentPW.println("Proxy : " + servicePkgName);
1780 indentPW.decreaseIndent();
1781 }
1782 // Flush before we let the app output anything to ensure correct ordering of output.
1783 // Internally, Binder#dump calls flush on its printer after finishing so we don't
1784 // need to do anything after.
1785 indentPW.flush();
1786 try {
1787 logd("Dumping " + servicePkgName);
1788 // We don't need to give the carrier service any args.
1789 connection.service.dump(fd, null /* args */);
1790 logd("Done with " + servicePkgName);
1791 } catch (RemoteException e) {
1792 logd("RemoteException from " + servicePkgName, e);
1793 indentPW.increaseIndent();
1794 indentPW.println("RemoteException");
1795 indentPW.increaseIndent();
1796 e.printStackTrace(indentPW);
1797 indentPW.decreaseIndent();
1798 indentPW.decreaseIndent();
1799 // We won't retry this package again because now it's in dumpedPkgNames.
1800 }
1801 indentPW.println("");
Jordan Liu46ed5db2020-01-28 08:55:20 -08001802 }
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001803 if (dumpedPkgNames.isEmpty()) {
1804 indentPW.increaseIndent();
1805 indentPW.println("Not bound");
1806 indentPW.decreaseIndent();
1807 indentPW.println("");
1808 }
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001809 indentPW.decreaseIndent();
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001810 }
1811
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001812 private boolean hasCarrierPrivileges(@NonNull String pkgName, int phoneId) {
Jack Yu00ece8c2022-11-19 22:29:12 -08001813 int subId = SubscriptionManager.getSubscriptionId(phoneId);
1814 if (!SubscriptionManager.isValidSubscriptionId(subId)) {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001815 return false;
1816 }
Jack Yu00ece8c2022-11-19 22:29:12 -08001817 return TelephonyManager.from(mContext).createForSubscriptionId(subId)
1818 .checkCarrierPrivilegesForPackage(pkgName)
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001819 == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001820 }
1821
Zach Johnson36d7aab2015-05-22 15:43:00 -07001822 private class CarrierServiceConnection implements ServiceConnection {
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001823 final int phoneId;
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001824 @NonNull final String pkgName;
Hunter Knepshieldeefb31b2020-02-19 15:30:54 -08001825 final int eventId;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001826 IBinder service;
1827
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001828 CarrierServiceConnection(int phoneId, @NonNull String pkgName, int eventId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001829 this.phoneId = phoneId;
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001830 this.pkgName = pkgName;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001831 this.eventId = eventId;
1832 }
1833
1834 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001835 public void onServiceConnected(@NonNull ComponentName name, @NonNull IBinder service) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001836 logd("Connected to config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001837 this.service = service;
1838 mHandler.sendMessage(mHandler.obtainMessage(eventId, phoneId, -1, this));
1839 }
1840
1841 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001842 public void onServiceDisconnected(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001843 logd("Disconnected from config app: " + name.flattenToShortString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001844 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001845 }
1846
1847 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001848 public void onBindingDied(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001849 logd("Binding died from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001850 this.service = null;
Jordan Liu46ed5db2020-01-28 08:55:20 -08001851 }
1852
1853 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001854 public void onNullBinding(@NonNull ComponentName name) {
Hunter Knepshield9f091fc2020-01-28 17:41:43 -08001855 logd("Null binding from config app: " + name.flattenToShortString());
Jordan Liu46ed5db2020-01-28 08:55:20 -08001856 this.service = null;
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001857 }
1858 }
1859
1860 private class ConfigLoaderBroadcastReceiver extends BroadcastReceiver {
1861 @Override
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001862 public void onReceive(@NonNull Context context, @NonNull Intent intent) {
Rambo Wanga27fbe52022-04-12 19:09:07 +00001863 switch (intent.getAction()) {
Nanxi Chen3d670502016-03-17 16:32:09 -07001864 case Intent.ACTION_BOOT_COMPLETED:
1865 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_UNLOCKED, null));
1866 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -07001867 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001868 }
1869 }
1870
Rambo Wanga27fbe52022-04-12 19:09:07 +00001871 private class CarrierServiceChangeCallback implements
1872 TelephonyManager.CarrierPrivilegesCallback {
1873 final int mPhoneId;
1874 // CarrierPrivilegesCallback will be triggered upon registration. Filter the first callback
1875 // here since we really care of the *change* of carrier service instead of the content
1876 private boolean mHasSentServiceChangeCallback;
1877
1878 CarrierServiceChangeCallback(int phoneId) {
1879 this.mPhoneId = phoneId;
1880 this.mHasSentServiceChangeCallback = false;
1881 }
1882
1883 @Override
1884 public void onCarrierPrivilegesChanged(
1885 @androidx.annotation.NonNull Set<String> privilegedPackageNames,
1886 @androidx.annotation.NonNull Set<Integer> privilegedUids) {
1887 // Ignored, not interested here
1888 }
1889
1890 @Override
1891 public void onCarrierServiceChanged(
1892 @androidx.annotation.Nullable String carrierServicePackageName,
1893 int carrierServiceUid) {
1894 // Ignore the first callback which is triggered upon registration
1895 if (!mHasSentServiceChangeCallback) {
1896 mHasSentServiceChangeCallback = true;
1897 return;
1898 }
1899 mHandler.sendMessage(
1900 mHandler.obtainMessage(EVENT_PACKAGE_CHANGED, mPhoneId, -1,
1901 carrierServicePackageName));
1902 }
1903 }
1904
Rambo Wangab13e3e2021-04-08 15:01:06 -07001905 // Get readable string for the message code supported in this class.
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001906 @NonNull
Rambo Wangab13e3e2021-04-08 15:01:06 -07001907 private static String eventToString(int code) {
1908 switch (code) {
1909 case EVENT_CLEAR_CONFIG:
1910 return "EVENT_CLEAR_CONFIG";
1911 case EVENT_CONNECTED_TO_DEFAULT:
1912 return "EVENT_CONNECTED_TO_DEFAULT";
1913 case EVENT_CONNECTED_TO_CARRIER:
1914 return "EVENT_CONNECTED_TO_CARRIER";
1915 case EVENT_FETCH_DEFAULT_DONE:
1916 return "EVENT_FETCH_DEFAULT_DONE";
1917 case EVENT_FETCH_CARRIER_DONE:
1918 return "EVENT_FETCH_CARRIER_DONE";
1919 case EVENT_DO_FETCH_DEFAULT:
1920 return "EVENT_DO_FETCH_DEFAULT";
1921 case EVENT_DO_FETCH_CARRIER:
1922 return "EVENT_DO_FETCH_CARRIER";
1923 case EVENT_PACKAGE_CHANGED:
1924 return "EVENT_PACKAGE_CHANGED";
1925 case EVENT_BIND_DEFAULT_TIMEOUT:
1926 return "EVENT_BIND_DEFAULT_TIMEOUT";
1927 case EVENT_BIND_CARRIER_TIMEOUT:
1928 return "EVENT_BIND_CARRIER_TIMEOUT";
1929 case EVENT_CHECK_SYSTEM_UPDATE:
1930 return "EVENT_CHECK_SYSTEM_UPDATE";
1931 case EVENT_SYSTEM_UNLOCKED:
1932 return "EVENT_SYSTEM_UNLOCKED";
1933 case EVENT_FETCH_DEFAULT_TIMEOUT:
1934 return "EVENT_FETCH_DEFAULT_TIMEOUT";
1935 case EVENT_FETCH_CARRIER_TIMEOUT:
1936 return "EVENT_FETCH_CARRIER_TIMEOUT";
1937 case EVENT_SUBSCRIPTION_INFO_UPDATED:
1938 return "EVENT_SUBSCRIPTION_INFO_UPDATED";
1939 case EVENT_MULTI_SIM_CONFIG_CHANGED:
1940 return "EVENT_MULTI_SIM_CONFIG_CHANGED";
1941 case EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG:
1942 return "EVENT_DO_FETCH_DEFAULT_FOR_NO_SIM_CONFIG";
1943 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE:
1944 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_DONE";
1945 case EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG:
1946 return "EVENT_CONNECTED_TO_DEFAULT_FOR_NO_SIM_CONFIG";
1947 case EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1948 return "EVENT_BIND_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1949 case EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT:
1950 return "EVENT_FETCH_DEFAULT_FOR_NO_SIM_CONFIG_TIMEOUT";
1951 default:
1952 return "UNKNOWN(" + code + ")";
1953 }
1954 }
1955
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001956 private void logd(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001957 Log.d(LOG_TAG, msg);
1958 }
1959
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001960 private void logd(@NonNull String msg, Throwable tr) {
Hunter Knepshieldd0ed6212020-01-28 17:43:16 -08001961 Log.d(LOG_TAG, msg, tr);
1962 }
1963
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001964 private void logdWithLocalLog(@NonNull String msg) {
chen xudb04c292019-03-26 17:01:15 -07001965 Log.d(LOG_TAG, msg);
1966 mCarrierConfigLoadingLog.log(msg);
1967 }
1968
Rambo Wangfe0d7c12022-04-15 03:00:32 +00001969 private void loge(@NonNull String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -07001970 Log.e(LOG_TAG, msg);
chen xudb04c292019-03-26 17:01:15 -07001971 mCarrierConfigLoadingLog.log(msg);
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001972 }
1973}