blob: 5a40322019d48e79af0fec73a8c083f2bb5304c3 [file] [log] [blame]
Jonathan Basseri6465afd2015-02-25 13:05:57 -08001/**
2 * 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
19import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan40b3fa52015-07-14 10:27:19 -070020import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080021
Jonathan Basseri11f89572015-05-05 11:57:39 -070022import android.annotation.NonNull;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080023import android.app.ActivityManagerNative;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
26import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
29import android.content.ServiceConnection;
Jonathan Basseri7697cae2015-07-06 15:49:23 -070030import android.content.SharedPreferences;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070031import android.content.pm.PackageInfo;
Jonathan Basseric31f1f32015-05-12 10:13:03 -070032import android.content.pm.PackageManager;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080033import android.database.sqlite.SQLiteDatabase;
34import android.database.sqlite.SQLiteOpenHelper;
35import android.os.AsyncResult;
Junda Liu43d723a2015-05-12 17:23:45 -070036import android.os.Binder;
Jonathan Basseri7697cae2015-07-06 15:49:23 -070037import android.os.Build;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080038import android.os.Handler;
39import android.os.IBinder;
40import android.os.Message;
Jonathan Basseric31f1f32015-05-12 10:13:03 -070041import android.os.PersistableBundle;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080042import android.os.RemoteException;
43import android.os.ServiceManager;
44import android.os.UserHandle;
Jonathan Basseri7697cae2015-07-06 15:49:23 -070045import android.preference.PreferenceManager;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080046import android.service.carrier.CarrierIdentifier;
Zach Johnson36d7aab2015-05-22 15:43:00 -070047import android.service.carrier.CarrierService;
48import android.service.carrier.ICarrierService;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080049import android.telephony.CarrierConfigManager;
50import android.telephony.SubscriptionManager;
51import android.telephony.TelephonyManager;
52import android.util.Log;
53
54import com.android.internal.telephony.ICarrierConfigLoader;
55import com.android.internal.telephony.IccCardConstants;
56import com.android.internal.telephony.Phone;
57import com.android.internal.telephony.PhoneConstants;
58import com.android.internal.telephony.PhoneFactory;
59import com.android.internal.telephony.TelephonyIntents;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070060import com.android.internal.util.FastXmlSerializer;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080061
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070062import org.xmlpull.v1.XmlPullParser;
63import org.xmlpull.v1.XmlPullParserException;
64import org.xmlpull.v1.XmlPullParserFactory;
65
66import java.io.File;
Junda Liu43d723a2015-05-12 17:23:45 -070067import java.io.FileDescriptor;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070068import java.io.FileInputStream;
69import java.io.FileNotFoundException;
70import java.io.FileOutputStream;
Jonathan Basseri1f743c92015-05-15 00:19:46 -070071import java.io.FilenameFilter;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070072import java.io.IOException;
Junda Liu43d723a2015-05-12 17:23:45 -070073import java.io.PrintWriter;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080074import java.util.List;
75
76/**
77 * CarrierConfigLoader binds to privileged carrier apps to fetch carrier config overlays.
Jonathan Basseri6465afd2015-02-25 13:05:57 -080078 */
79
80public class CarrierConfigLoader extends ICarrierConfigLoader.Stub {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070081 private static final String LOG_TAG = "CarrierConfigLoader";
Jonathan Basseri6465afd2015-02-25 13:05:57 -080082 // Package name for default carrier config app, bundled with system image.
83 private static final String DEFAULT_CARRIER_CONFIG_PACKAGE = "com.android.carrierconfig";
84
85 /** The singleton instance. */
86 private static CarrierConfigLoader sInstance;
87 // The context for phone app, passed from PhoneGlobals.
88 private Context mContext;
89 // Carrier configs from default app, indexed by phoneID.
Jonathan Basseric31f1f32015-05-12 10:13:03 -070090 private PersistableBundle[] mConfigFromDefaultApp;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080091 // Carrier configs from privileged carrier config app, indexed by phoneID.
Jonathan Basseric31f1f32015-05-12 10:13:03 -070092 private PersistableBundle[] mConfigFromCarrierApp;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080093 // Service connection for binding to config app.
Zach Johnson36d7aab2015-05-22 15:43:00 -070094 private CarrierServiceConnection[] mServiceConnection;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080095
Nanxi Chen3d670502016-03-17 16:32:09 -070096 // Broadcast receiver for Boot intents, register intent filter in construtor.
97 private final BroadcastReceiver mBootReceiver = new ConfigLoaderBroadcastReceiver();
Jonathan Basseri6465afd2015-02-25 13:05:57 -080098 // Broadcast receiver for SIM and pkg intents, register intent filter in constructor.
Nanxi Chen3d670502016-03-17 16:32:09 -070099 private final BroadcastReceiver mPackageReceiver = new ConfigLoaderBroadcastReceiver();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800100
101 // Message codes; see mHandler below.
102 // Request from SubscriptionInfoUpdater when SIM becomes absent or error.
103 private static final int EVENT_CLEAR_CONFIG = 0;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800104 // Has connected to default app.
105 private static final int EVENT_CONNECTED_TO_DEFAULT = 3;
106 // Has connected to carrier app.
107 private static final int EVENT_CONNECTED_TO_CARRIER = 4;
108 // Config has been loaded from default app.
109 private static final int EVENT_LOADED_FROM_DEFAULT = 5;
110 // Config has been loaded from carrier app.
111 private static final int EVENT_LOADED_FROM_CARRIER = 6;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700112 // Attempt to fetch from default app or read from XML.
113 private static final int EVENT_FETCH_DEFAULT = 7;
114 // Attempt to fetch from carrier app or read from XML.
115 private static final int EVENT_FETCH_CARRIER = 8;
116 // A package has been installed, uninstalled, or updated.
117 private static final int EVENT_PACKAGE_CHANGED = 9;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700118 // Bind timed out for the default app.
119 private static final int EVENT_BIND_DEFAULT_TIMEOUT = 10;
120 // Bind timed out for a carrier app.
121 private static final int EVENT_BIND_CARRIER_TIMEOUT = 11;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700122 // Check if the system fingerprint has changed.
123 private static final int EVENT_CHECK_SYSTEM_UPDATE = 12;
Nanxi Chen3d670502016-03-17 16:32:09 -0700124 // Rerun carrier config binding after system is unlocked.
125 private static final int EVENT_SYSTEM_UNLOCKED = 13;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700126
Junda Liu6cb45002016-03-22 17:18:20 -0700127 private static final int BIND_TIMEOUT_MILLIS = 30000;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800128
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700129 // Tags used for saving and restoring XML documents.
130 private static final String TAG_DOCUMENT = "carrier_config";
131 private static final String TAG_VERSION = "package_version";
132 private static final String TAG_BUNDLE = "bundle_data";
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800133
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700134 // SharedPreferences key for last known build fingerprint.
135 private static final String KEY_FINGERPRINT = "build_fingerprint";
136
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800137 // Handler to process various events.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700138 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700139 // For each phoneId, the event sequence should be:
140 // fetch default, connected to default, loaded from default,
141 // fetch carrier, connected to carrier, loaded from carrier.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700142 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700143 // If there is a saved config file for either the default app or the carrier app, we skip
144 // binding to the app and go straight from fetch to loaded.
145 //
146 // At any time, at most one connection is active. If events are not in this order, previous
147 // connection will be unbound, so only latest event takes effect.
148 //
149 // We broadcast ACTION_CARRIER_CONFIG_CHANGED after:
150 // 1. loading from carrier app (even if read from a file)
151 // 2. loading from default app if there is no carrier app (even if read from a file)
152 // 3. clearing config (e.g. due to sim removal)
153 // 4. encountering bind or IPC error
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800154 private Handler mHandler = new Handler() {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700155 @Override
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800156 public void handleMessage(Message msg) {
157 int phoneId = msg.arg1;
158 log("mHandler: " + msg.what + " phoneId: " + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700159 String iccid;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800160 CarrierIdentifier carrierId;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700161 String carrierPackageName;
Zach Johnson36d7aab2015-05-22 15:43:00 -0700162 CarrierServiceConnection conn;
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700163 PersistableBundle config;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800164 switch (msg.what) {
165 case EVENT_CLEAR_CONFIG:
Junda Liu0486bdb2015-05-22 15:01:35 -0700166 if (mConfigFromDefaultApp[phoneId] == null &&
167 mConfigFromCarrierApp[phoneId] == null)
168 break;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800169 mConfigFromDefaultApp[phoneId] = null;
170 mConfigFromCarrierApp[phoneId] = null;
171 mServiceConnection[phoneId] = null;
172 broadcastConfigChangedIntent(phoneId);
173 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700174
Nanxi Chen3d670502016-03-17 16:32:09 -0700175 case EVENT_SYSTEM_UNLOCKED:
176 for (int i = 0; i < TelephonyManager.from(mContext).getPhoneCount(); ++i) {
177 updateConfigForPhoneId(i);
178 }
179 break;
180
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700181 case EVENT_PACKAGE_CHANGED:
182 carrierPackageName = (String) msg.obj;
Junda Liu8a8a53a2015-05-15 16:19:57 -0700183 // Only update if there are cached config removed to avoid updating config
184 // for unrelated packages.
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700185 if (clearCachedConfigForPackage(carrierPackageName)) {
Junda Liu8a8a53a2015-05-15 16:19:57 -0700186 int numPhones = TelephonyManager.from(mContext).getPhoneCount();
187 for (int i = 0; i < numPhones; ++i) {
188 updateConfigForPhoneId(i);
189 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700190 }
191 break;
192
193 case EVENT_FETCH_DEFAULT:
194 iccid = getIccIdForPhoneId(phoneId);
195 config = restoreConfigFromXml(DEFAULT_CARRIER_CONFIG_PACKAGE, iccid);
196 if (config != null) {
197 log("Loaded config from XML. package=" + DEFAULT_CARRIER_CONFIG_PACKAGE
198 + " phoneId=" + phoneId);
199 mConfigFromDefaultApp[phoneId] = config;
200 Message newMsg = obtainMessage(EVENT_LOADED_FROM_DEFAULT, phoneId, -1);
201 newMsg.getData().putBoolean("loaded_from_xml", true);
202 mHandler.sendMessage(newMsg);
203 } else {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700204 if (bindToConfigPackage(DEFAULT_CARRIER_CONFIG_PACKAGE,
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700205 phoneId, EVENT_CONNECTED_TO_DEFAULT)) {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700206 sendMessageDelayed(obtainMessage(EVENT_BIND_DEFAULT_TIMEOUT, phoneId, -1),
207 BIND_TIMEOUT_MILLIS);
208 } else {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700209 // Send bcast if bind fails
210 broadcastConfigChangedIntent(phoneId);
211 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800212 }
213 break;
214
215 case EVENT_CONNECTED_TO_DEFAULT:
Jonathan Basseri930701e2015-06-11 20:56:43 -0700216 removeMessages(EVENT_BIND_DEFAULT_TIMEOUT);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800217 carrierId = getCarrierIdForPhoneId(phoneId);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700218 conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800219 // If new service connection has been created, unbind.
220 if (mServiceConnection[phoneId] != conn || conn.service == null) {
221 mContext.unbindService(conn);
222 break;
223 }
224 try {
Zach Johnson36d7aab2015-05-22 15:43:00 -0700225 ICarrierService carrierService = ICarrierService.Stub
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700226 .asInterface(conn.service);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700227 config = carrierService.getCarrierConfig(carrierId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700228 iccid = getIccIdForPhoneId(phoneId);
229 saveConfigToXml(DEFAULT_CARRIER_CONFIG_PACKAGE, iccid, config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800230 mConfigFromDefaultApp[phoneId] = config;
Junda Liu9f2d2712015-05-15 14:22:45 -0700231 sendMessage(obtainMessage(EVENT_LOADED_FROM_DEFAULT, phoneId, -1));
Junda Liu66d9f2c2016-03-28 17:00:25 -0700232 } catch (Exception ex) {
233 // The bound app could throw exceptions that binder will pass to us.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700234 loge("Failed to get carrier config: " + ex.toString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800235 } finally {
236 mContext.unbindService(mServiceConnection[phoneId]);
237 }
238 break;
239
Jonathan Basseri930701e2015-06-11 20:56:43 -0700240 case EVENT_BIND_DEFAULT_TIMEOUT:
241 mContext.unbindService(mServiceConnection[phoneId]);
242 broadcastConfigChangedIntent(phoneId);
243 break;
244
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800245 case EVENT_LOADED_FROM_DEFAULT:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700246 // If we attempted to bind to the app, but the service connection is null, then
247 // config was cleared while we were waiting and we should not continue.
248 if (!msg.getData().getBoolean("loaded_from_xml", false)
249 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800250 break;
251 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700252 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
253 if (carrierPackageName != null) {
254 log("Found carrier config app: " + carrierPackageName);
255 sendMessage(obtainMessage(EVENT_FETCH_CARRIER, phoneId));
Jonathan Basserib919e932015-05-27 16:53:08 +0000256 } else {
257 broadcastConfigChangedIntent(phoneId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700258 }
259 break;
260
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700261 case EVENT_FETCH_CARRIER:
262 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
263 iccid = getIccIdForPhoneId(phoneId);
264 config = restoreConfigFromXml(carrierPackageName, iccid);
265 if (config != null) {
266 log("Loaded config from XML. package=" + carrierPackageName + " phoneId="
267 + phoneId);
268 mConfigFromCarrierApp[phoneId] = config;
269 Message newMsg = obtainMessage(EVENT_LOADED_FROM_CARRIER, phoneId, -1);
270 newMsg.getData().putBoolean("loaded_from_xml", true);
271 sendMessage(newMsg);
272 } else {
Jonathan Basseri40473a52015-08-14 14:36:29 -0700273 if (carrierPackageName != null
274 && bindToConfigPackage(carrierPackageName, phoneId,
275 EVENT_CONNECTED_TO_CARRIER)) {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700276 sendMessageDelayed(obtainMessage(EVENT_BIND_CARRIER_TIMEOUT, phoneId, -1),
277 BIND_TIMEOUT_MILLIS);
278 } else {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700279 // Send bcast if bind fails
280 broadcastConfigChangedIntent(phoneId);
281 }
282 }
283 break;
284
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800285 case EVENT_CONNECTED_TO_CARRIER:
Jonathan Basseri930701e2015-06-11 20:56:43 -0700286 removeMessages(EVENT_BIND_CARRIER_TIMEOUT);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800287 carrierId = getCarrierIdForPhoneId(phoneId);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700288 conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800289 // If new service connection has been created, unbind.
290 if (mServiceConnection[phoneId] != conn ||
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700291 conn.service == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800292 mContext.unbindService(conn);
293 break;
294 }
295 try {
Zach Johnson36d7aab2015-05-22 15:43:00 -0700296 ICarrierService carrierService = ICarrierService.Stub
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700297 .asInterface(conn.service);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700298 config = carrierService.getCarrierConfig(carrierId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700299 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
300 iccid = getIccIdForPhoneId(phoneId);
301 saveConfigToXml(carrierPackageName, iccid, config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800302 mConfigFromCarrierApp[phoneId] = config;
Junda Liu9f2d2712015-05-15 14:22:45 -0700303 sendMessage(obtainMessage(EVENT_LOADED_FROM_CARRIER, phoneId, -1));
Junda Liu66d9f2c2016-03-28 17:00:25 -0700304 } catch (Exception ex) {
305 // The bound app could throw exceptions that binder will pass to us.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700306 loge("Failed to get carrier config: " + ex.toString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800307 } finally {
308 mContext.unbindService(mServiceConnection[phoneId]);
309 }
310 break;
311
Jonathan Basseri930701e2015-06-11 20:56:43 -0700312 case EVENT_BIND_CARRIER_TIMEOUT:
313 mContext.unbindService(mServiceConnection[phoneId]);
314 broadcastConfigChangedIntent(phoneId);
315 break;
316
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800317 case EVENT_LOADED_FROM_CARRIER:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700318 // If we attempted to bind to the app, but the service connection is null, then
319 // config was cleared while we were waiting and we should not continue.
320 if (!msg.getData().getBoolean("loaded_from_xml", false)
321 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800322 break;
323 }
324 broadcastConfigChangedIntent(phoneId);
325 break;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700326
327 case EVENT_CHECK_SYSTEM_UPDATE:
328 SharedPreferences sharedPrefs =
329 PreferenceManager.getDefaultSharedPreferences(mContext);
330 final String lastFingerprint = sharedPrefs.getString(KEY_FINGERPRINT, null);
331 if (!Build.FINGERPRINT.equals(lastFingerprint)) {
332 log("Build fingerprint changed. old: "
333 + lastFingerprint + " new: " + Build.FINGERPRINT);
334 clearCachedConfigForPackage(null);
335 sharedPrefs.edit().putString(KEY_FINGERPRINT, Build.FINGERPRINT).apply();
336 }
337 break;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800338 }
339 }
340 };
341
342 /**
343 * Constructs a CarrierConfigLoader, registers it as a service, and registers a broadcast
344 * receiver for relevant events.
345 */
346 private CarrierConfigLoader(Context context) {
347 mContext = context;
348
Nanxi Chen3d670502016-03-17 16:32:09 -0700349 IntentFilter bootFilter = new IntentFilter();
350 bootFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
351 context.registerReceiver(mBootReceiver, bootFilter);
352
Junda Liu8a8a53a2015-05-15 16:19:57 -0700353 // Register for package updates. Update app or uninstall app update will have all 3 intents,
354 // in the order or removed, added, replaced, all with extra_replace set to true.
355 IntentFilter pkgFilter = new IntentFilter();
356 pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
357 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
358 pkgFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
359 pkgFilter.addDataScheme("package");
Nanxi Chen3d670502016-03-17 16:32:09 -0700360 context.registerReceiverAsUser(mPackageReceiver, UserHandle.ALL, pkgFilter, null, null);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800361
362 int numPhones = TelephonyManager.from(context).getPhoneCount();
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700363 mConfigFromDefaultApp = new PersistableBundle[numPhones];
364 mConfigFromCarrierApp = new PersistableBundle[numPhones];
Zach Johnson36d7aab2015-05-22 15:43:00 -0700365 mServiceConnection = new CarrierServiceConnection[numPhones];
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800366 // Make this service available through ServiceManager.
367 ServiceManager.addService(Context.CARRIER_CONFIG_SERVICE, this);
368 log("CarrierConfigLoader has started");
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700369 mHandler.sendEmptyMessage(EVENT_CHECK_SYSTEM_UPDATE);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800370 }
371
372 /**
373 * Initialize the singleton CarrierConfigLoader instance.
374 *
375 * This is only done once, at startup, from {@link com.android.phone.PhoneApp#onCreate}.
376 */
377 /* package */
378 static CarrierConfigLoader init(Context context) {
379 synchronized (CarrierConfigLoader.class) {
380 if (sInstance == null) {
381 sInstance = new CarrierConfigLoader(context);
382 } else {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700383 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800384 }
385 return sInstance;
386 }
387 }
388
389 private void broadcastConfigChangedIntent(int phoneId) {
390 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
391 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
392 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, phoneId);
393 ActivityManagerNative.broadcastStickyIntent(intent, READ_PHONE_STATE,
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700394 UserHandle.USER_ALL);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800395 }
396
397 /** Binds to the default or carrier config app. */
398 private boolean bindToConfigPackage(String pkgName, int phoneId, int eventId) {
399 log("Binding to " + pkgName + " for phone " + phoneId);
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700400 Intent carrierService = new Intent(CarrierService.CARRIER_SERVICE_INTERFACE);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700401 carrierService.setPackage(pkgName);
402 mServiceConnection[phoneId] = new CarrierServiceConnection(phoneId, eventId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800403 try {
Zach Johnson36d7aab2015-05-22 15:43:00 -0700404 return mContext.bindService(carrierService, mServiceConnection[phoneId],
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800405 Context.BIND_AUTO_CREATE);
406 } catch (SecurityException ex) {
407 return false;
408 }
409 }
410
411 private CarrierIdentifier getCarrierIdForPhoneId(int phoneId) {
412 String mcc = "";
413 String mnc = "";
414 String imsi = "";
415 String gid1 = "";
416 String gid2 = "";
417 String spn = TelephonyManager.from(mContext).getSimOperatorNameForPhone(phoneId);
418 String simOperator = TelephonyManager.from(mContext).getSimOperatorNumericForPhone(phoneId);
Jonathan Basseri1fa437c2015-04-20 11:08:18 -0700419 // A valid simOperator should be 5 or 6 digits, depending on the length of the MNC.
420 if (simOperator != null && simOperator.length() >= 3) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800421 mcc = simOperator.substring(0, 3);
422 mnc = simOperator.substring(3);
423 }
424 Phone phone = PhoneFactory.getPhone(phoneId);
425 if (phone != null) {
426 imsi = phone.getSubscriberId();
427 gid1 = phone.getGroupIdLevel1();
Junda Liu73183532015-05-14 13:55:40 -0700428 gid2 = phone.getGroupIdLevel2();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800429 }
430
431 return new CarrierIdentifier(mcc, mnc, spn, imsi, gid1, gid2);
432 }
433
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700434 /** Returns the package name of a priveleged carrier app, or null if there is none. */
435 private String getCarrierPackageForPhoneId(int phoneId) {
436 List<String> carrierPackageNames = TelephonyManager.from(mContext)
437 .getCarrierPackageNamesForIntentAndPhone(
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700438 new Intent(CarrierService.CARRIER_SERVICE_INTERFACE), phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700439 if (carrierPackageNames != null && carrierPackageNames.size() > 0) {
440 return carrierPackageNames.get(0);
441 } else {
442 return null;
443 }
444 }
445
446 private String getIccIdForPhoneId(int phoneId) {
447 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
448 return null;
449 }
450 Phone phone = PhoneFactory.getPhone(phoneId);
451 if (phone == null) {
452 return null;
453 }
454 return phone.getIccSerialNumber();
455 }
456
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700457 /**
458 * Writes a bundle to an XML file.
459 *
460 * The bundle will be written to a file named after the package name and ICCID, so that it can
461 * be restored later with {@link @restoreConfigFromXml}. The XML output will include the bundle
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700462 * and the current version of the specified package.
463 *
464 * In case of errors or invalid input, no file will be written.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700465 *
466 * @param packageName the name of the package from which we fetched this bundle.
467 * @param iccid the ICCID of the subscription for which this bundle was fetched.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700468 * @param config the bundle to be written. Null will be treated as an empty bundle.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700469 */
470 private void saveConfigToXml(String packageName, String iccid, PersistableBundle config) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700471 if (packageName == null || iccid == null) {
472 loge("Cannot save config with null packageName or iccid.");
473 return;
474 }
475 if (config == null) {
476 config = new PersistableBundle();
477 }
478
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700479 final String version = getPackageVersion(packageName);
480 if (version == null) {
481 loge("Failed to get package version for: " + packageName);
482 return;
483 }
484
485 FileOutputStream outFile = null;
486 try {
487 outFile = new FileOutputStream(
488 new File(mContext.getFilesDir(), getFilenameForConfig(packageName, iccid)));
489 FastXmlSerializer out = new FastXmlSerializer();
490 out.setOutput(outFile, "utf-8");
491 out.startDocument("utf-8", true);
492 out.startTag(null, TAG_DOCUMENT);
493 out.startTag(null, TAG_VERSION);
494 out.text(version);
495 out.endTag(null, TAG_VERSION);
496 out.startTag(null, TAG_BUNDLE);
497 config.saveToXml(out);
498 out.endTag(null, TAG_BUNDLE);
499 out.endTag(null, TAG_DOCUMENT);
500 out.endDocument();
501 out.flush();
502 outFile.close();
503 }
504 catch (IOException e) {
505 loge(e.toString());
506 }
507 catch (XmlPullParserException e) {
508 loge(e.toString());
509 }
510 }
511
512 /**
513 * Reads a bundle from an XML file.
514 *
515 * This restores a bundle that was written with {@link #saveConfigToXml}. This returns the saved
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700516 * config bundle for the given package and ICCID.
517 *
518 * In case of errors, or if the saved config is from a different package version than the
519 * current version, then null will be returned.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700520 *
521 * @param packageName the name of the package from which we fetched this bundle.
522 * @param iccid the ICCID of the subscription for which this bundle was fetched.
523 * @return the bundle from the XML file. Returns null if there is no saved config, the saved
524 * version does not match, or reading config fails.
525 */
526 private PersistableBundle restoreConfigFromXml(String packageName, String iccid) {
527 final String version = getPackageVersion(packageName);
528 if (version == null) {
529 loge("Failed to get package version for: " + packageName);
530 return null;
531 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700532 if (packageName == null || iccid == null) {
533 loge("Cannot restore config with null packageName or iccid.");
534 return null;
535 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700536
537 PersistableBundle restoredBundle = null;
538 FileInputStream inFile = null;
539 try {
540 inFile = new FileInputStream(
541 new File(mContext.getFilesDir(), getFilenameForConfig(packageName, iccid)));
542 XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
543 parser.setInput(inFile, "utf-8");
544
545 int event;
546 while (((event = parser.next()) != XmlPullParser.END_DOCUMENT)) {
547
548 if (event == XmlPullParser.START_TAG && TAG_VERSION.equals(parser.getName())) {
549 String savedVersion = parser.nextText();
550 if (!version.equals(savedVersion)) {
551 log("Saved version mismatch: " + version + " vs " + savedVersion);
552 break;
553 }
554 }
555
556 if (event == XmlPullParser.START_TAG && TAG_BUNDLE.equals(parser.getName())) {
557 restoredBundle = PersistableBundle.restoreFromXml(parser);
558 }
559 }
560 inFile.close();
561 }
562 catch (FileNotFoundException e) {
563 loge(e.toString());
564 }
565 catch (XmlPullParserException e) {
566 loge(e.toString());
567 }
568 catch (IOException e) {
569 loge(e.toString());
570 }
571
572 return restoredBundle;
573 }
574
Junda Liu8a8a53a2015-05-15 16:19:57 -0700575 /**
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700576 * Clears cached carrier config.
577 * This deletes all saved XML files associated with the given package name. If packageName is
578 * null, then it deletes all saved XML files.
579 *
580 * @param packageName the name of a carrier package, or null if all cached config should be
581 * cleared.
582 * @return true iff one or more files were deleted.
Junda Liu8a8a53a2015-05-15 16:19:57 -0700583 */
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700584 private boolean clearCachedConfigForPackage(final String packageName) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700585 File dir = mContext.getFilesDir();
586 File[] packageFiles = dir.listFiles(new FilenameFilter() {
587 public boolean accept(File dir, String filename) {
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700588 if (packageName != null) {
589 return filename.startsWith("carrierconfig-" + packageName + "-");
590 } else {
591 return filename.startsWith("carrierconfig-");
592 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700593 }
594 });
Junda Liu8a8a53a2015-05-15 16:19:57 -0700595 if (packageFiles == null || packageFiles.length < 1) return false;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700596 for (File f : packageFiles) {
597 log("deleting " + f.getName());
598 f.delete();
599 }
Junda Liu8a8a53a2015-05-15 16:19:57 -0700600 return true;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700601 }
602
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700603 /** Builds a canonical file name for a config file. */
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700604 private String getFilenameForConfig(@NonNull String packageName, @NonNull String iccid) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700605 return "carrierconfig-" + packageName + "-" + iccid + ".xml";
606 }
607
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700608 /** Return the current version code of a package, or null if the name is not found. */
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700609 private String getPackageVersion(String packageName) {
610 try {
611 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700612 return Integer.toString(info.versionCode);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700613 } catch (PackageManager.NameNotFoundException e) {
614 return null;
615 }
616 }
617
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700618 /** Read up to date config.
619 *
620 * This reads config bundles for the given phoneId. That means getting the latest bundle from
621 * the default app and a privileged carrier app, if present. This will not bind to an app if we
622 * have a saved config file to use instead.
623 */
624 private void updateConfigForPhoneId(int phoneId) {
Junda Liu8a8a53a2015-05-15 16:19:57 -0700625 // Clear in-memory cache for carrier app config, so when carrier app gets uninstalled, no
626 // stale config is left.
627 if (mConfigFromCarrierApp[phoneId] != null &&
628 getCarrierPackageForPhoneId(phoneId) == null) {
629 mConfigFromCarrierApp[phoneId] = null;
630 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700631 mHandler.sendMessage(mHandler.obtainMessage(EVENT_FETCH_DEFAULT, phoneId, -1));
632 }
633
634 @Override public
635 @NonNull
636 PersistableBundle getConfigForSubId(int subId) {
Amit Mahajan40b3fa52015-07-14 10:27:19 -0700637 try {
638 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, null);
639 // SKIP checking run-time READ_PHONE_STATE since using PRIVILEGED
640 } catch (SecurityException e) {
641 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, null);
642 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800643 int phoneId = SubscriptionManager.getPhoneId(subId);
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700644 PersistableBundle retConfig = CarrierConfigManager.getDefaultConfig();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800645 if (SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700646 PersistableBundle config = mConfigFromDefaultApp[phoneId];
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700647 if (config != null)
648 retConfig.putAll(config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800649 config = mConfigFromCarrierApp[phoneId];
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700650 if (config != null)
651 retConfig.putAll(config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800652 }
653 return retConfig;
654 }
655
656 @Override
Jonathan Basseri86030352015-06-08 12:27:56 -0700657 public void notifyConfigChangedForSubId(int subId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800658 int phoneId = SubscriptionManager.getPhoneId(subId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700659 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800660 log("Ignore invalid phoneId: " + phoneId + " for subId: " + subId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700661 return;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800662 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700663 String callingPackageName = mContext.getPackageManager().getNameForUid(
664 Binder.getCallingUid());
665 // TODO: Check that the calling packages is privileged for subId specifically.
666 int privilegeStatus = TelephonyManager.from(mContext).checkCarrierPrivilegesForPackage(
667 callingPackageName);
Junda Liufbd2bcb2016-06-15 11:15:42 -0700668 // Requires the calling app to be either a carrier privileged app or
669 // system privileged app with MODIFY_PHONE_STATE permission.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700670 if (privilegeStatus != TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) {
Junda Liufbd2bcb2016-06-15 11:15:42 -0700671 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MODIFY_PHONE_STATE,
672 "Require carrier privileges or MODIFY_PHONE_STATE permission.");
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700673 }
674
675 // This method should block until deleting has completed, so that an error which prevents us
676 // from clearing the cache is passed back to the carrier app. With the files successfully
677 // deleted, this can return and we will eventually bind to the carrier app.
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700678 clearCachedConfigForPackage(callingPackageName);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700679 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800680 }
681
682 @Override
683 public void updateConfigForPhoneId(int phoneId, String simState) {
Junda Liu1f2b34d2015-06-18 15:26:56 -0700684 mContext.enforceCallingOrSelfPermission(
685 android.Manifest.permission.MODIFY_PHONE_STATE, null);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800686 log("update config for phoneId: " + phoneId + " simState: " + simState);
687 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
688 return;
689 }
690 // requires Java 7 for switch on string.
691 switch (simState) {
692 case IccCardConstants.INTENT_VALUE_ICC_ABSENT:
693 case IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR:
Junda Liu6f5fddf2016-05-24 16:14:41 -0700694 case IccCardConstants.INTENT_VALUE_ICC_CARD_RESTRICTED:
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800695 case IccCardConstants.INTENT_VALUE_ICC_UNKNOWN:
Junda Liu9f2d2712015-05-15 14:22:45 -0700696 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CLEAR_CONFIG, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800697 break;
698 case IccCardConstants.INTENT_VALUE_ICC_LOADED:
699 case IccCardConstants.INTENT_VALUE_ICC_LOCKED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700700 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800701 break;
702 }
703 }
704
Junda Liu43d723a2015-05-12 17:23:45 -0700705 @Override
706 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
707 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
708 != PackageManager.PERMISSION_GRANTED) {
709 pw.println("Permission Denial: can't dump carrierconfig from from pid="
710 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
711 return;
712 }
713 pw.println("CarrierConfigLoader: " + this);
714 for (int i = 0; i < TelephonyManager.getDefault().getPhoneCount(); i++) {
715 pw.println(" Phone Id=" + i);
716 pw.println(" mConfigFromDefaultApp=" + mConfigFromDefaultApp[i]);
717 pw.println(" mConfigFromCarrierApp=" + mConfigFromCarrierApp[i]);
718 }
719 }
720
Zach Johnson36d7aab2015-05-22 15:43:00 -0700721 private class CarrierServiceConnection implements ServiceConnection {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800722 int phoneId;
723 int eventId;
724 IBinder service;
725
Zach Johnson36d7aab2015-05-22 15:43:00 -0700726 public CarrierServiceConnection(int phoneId, int eventId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800727 this.phoneId = phoneId;
728 this.eventId = eventId;
729 }
730
731 @Override
732 public void onServiceConnected(ComponentName name, IBinder service) {
733 log("Connected to config app: " + name.flattenToString());
734 this.service = service;
735 mHandler.sendMessage(mHandler.obtainMessage(eventId, phoneId, -1, this));
736 }
737
738 @Override
739 public void onServiceDisconnected(ComponentName name) {
740 this.service = null;
741 }
742 }
743
744 private class ConfigLoaderBroadcastReceiver extends BroadcastReceiver {
745 @Override
746 public void onReceive(Context context, Intent intent) {
747 String action = intent.getAction();
Junda Liu8a8a53a2015-05-15 16:19:57 -0700748 boolean replace = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
749 // If replace is true, only care ACTION_PACKAGE_REPLACED.
750 if (replace && !Intent.ACTION_PACKAGE_REPLACED.equals(action))
751 return;
752
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700753 switch (action) {
Nanxi Chen3d670502016-03-17 16:32:09 -0700754 case Intent.ACTION_BOOT_COMPLETED:
755 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_UNLOCKED, null));
756 break;
757
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700758 case Intent.ACTION_PACKAGE_ADDED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700759 case Intent.ACTION_PACKAGE_REMOVED:
Junda Liu8a8a53a2015-05-15 16:19:57 -0700760 case Intent.ACTION_PACKAGE_REPLACED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700761 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
762 String packageName = mContext.getPackageManager().getNameForUid(uid);
Junda Liu8a8a53a2015-05-15 16:19:57 -0700763 if (packageName != null) {
764 // We don't have a phoneId for arg1.
765 mHandler.sendMessage(
766 mHandler.obtainMessage(EVENT_PACKAGE_CHANGED, packageName));
767 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700768 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700769 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800770 }
771 }
772
773 private static void log(String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700774 Log.d(LOG_TAG, msg);
775 }
776
777 private static void loge(String msg) {
778 Log.e(LOG_TAG, msg);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800779 }
780}