blob: 9efbbda63357af6ed8ba190992f9fbe01c9e3271 [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;
20import static com.android.internal.telephony.uicc.IccCardProxy.ACTION_INTERNAL_SIM_STATE_CHANGED;
21
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 Basseri6b50e9f2015-05-12 20:18:31 -070030import android.content.pm.PackageInfo;
Jonathan Basseric31f1f32015-05-12 10:13:03 -070031import android.content.pm.PackageManager;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080032import android.database.sqlite.SQLiteDatabase;
33import android.database.sqlite.SQLiteOpenHelper;
34import android.os.AsyncResult;
Junda Liu43d723a2015-05-12 17:23:45 -070035import android.os.Binder;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080036import android.os.Handler;
37import android.os.IBinder;
38import android.os.Message;
Jonathan Basseric31f1f32015-05-12 10:13:03 -070039import android.os.PersistableBundle;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080040import android.os.RemoteException;
41import android.os.ServiceManager;
42import android.os.UserHandle;
43import android.service.carrier.CarrierConfigService;
44import android.service.carrier.CarrierIdentifier;
45import android.service.carrier.ICarrierConfigService;
46import android.telephony.CarrierConfigManager;
47import android.telephony.SubscriptionManager;
48import android.telephony.TelephonyManager;
49import android.util.Log;
50
51import com.android.internal.telephony.ICarrierConfigLoader;
52import com.android.internal.telephony.IccCardConstants;
53import com.android.internal.telephony.Phone;
54import com.android.internal.telephony.PhoneConstants;
55import com.android.internal.telephony.PhoneFactory;
56import com.android.internal.telephony.TelephonyIntents;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070057import com.android.internal.util.FastXmlSerializer;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080058
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070059import org.xmlpull.v1.XmlPullParser;
60import org.xmlpull.v1.XmlPullParserException;
61import org.xmlpull.v1.XmlPullParserFactory;
62
63import java.io.File;
Junda Liu43d723a2015-05-12 17:23:45 -070064import java.io.FileDescriptor;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070065import java.io.FileInputStream;
66import java.io.FileNotFoundException;
67import java.io.FileOutputStream;
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -070068import java.io.FilenameFilter;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070069import java.io.IOException;
Junda Liu43d723a2015-05-12 17:23:45 -070070import java.io.PrintWriter;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080071import java.util.List;
72
73/**
74 * CarrierConfigLoader binds to privileged carrier apps to fetch carrier config overlays.
Jonathan Basseri6465afd2015-02-25 13:05:57 -080075 * TODO: handle package install/uninstall events
76 */
77
78public class CarrierConfigLoader extends ICarrierConfigLoader.Stub {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070079 private static final String LOG_TAG = "CarrierConfigLoader";
Jonathan Basseri6465afd2015-02-25 13:05:57 -080080 // Package name for default carrier config app, bundled with system image.
81 private static final String DEFAULT_CARRIER_CONFIG_PACKAGE = "com.android.carrierconfig";
82
83 /** The singleton instance. */
84 private static CarrierConfigLoader sInstance;
85 // The context for phone app, passed from PhoneGlobals.
86 private Context mContext;
87 // Carrier configs from default app, indexed by phoneID.
Jonathan Basseric31f1f32015-05-12 10:13:03 -070088 private PersistableBundle[] mConfigFromDefaultApp;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080089 // Carrier configs from privileged carrier config app, indexed by phoneID.
Jonathan Basseric31f1f32015-05-12 10:13:03 -070090 private PersistableBundle[] mConfigFromCarrierApp;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080091 // Service connection for binding to config app.
92 private ConfigServiceConnection[] mServiceConnection;
93
94 // Broadcast receiver for SIM and pkg intents, register intent filter in constructor.
95 private final BroadcastReceiver mReceiver = new ConfigLoaderBroadcastReceiver();
96
97 // Message codes; see mHandler below.
98 // Request from SubscriptionInfoUpdater when SIM becomes absent or error.
99 private static final int EVENT_CLEAR_CONFIG = 0;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800100 // Has connected to default app.
101 private static final int EVENT_CONNECTED_TO_DEFAULT = 3;
102 // Has connected to carrier app.
103 private static final int EVENT_CONNECTED_TO_CARRIER = 4;
104 // Config has been loaded from default app.
105 private static final int EVENT_LOADED_FROM_DEFAULT = 5;
106 // Config has been loaded from carrier app.
107 private static final int EVENT_LOADED_FROM_CARRIER = 6;
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700108 // Attempt to fetch from default app or read from XML.
109 private static final int EVENT_FETCH_DEFAULT = 7;
110 // Attempt to fetch from carrier app or read from XML.
111 private static final int EVENT_FETCH_CARRIER = 8;
112 // A package has been installed, uninstalled, or updated.
113 private static final int EVENT_PACKAGE_CHANGED = 9;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800114
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700115 // Tags used for saving and restoring XML documents.
116 private static final String TAG_DOCUMENT = "carrier_config";
117 private static final String TAG_VERSION = "package_version";
118 private static final String TAG_BUNDLE = "bundle_data";
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800119
120 // Handler to process various events.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700121 //
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700122 // For each phoneId, the event sequence should be:
123 // fetch default, connected to default, loaded from default,
124 // fetch carrier, connected to carrier, loaded from carrier.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700125 //
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700126 // If there is a saved config file for either the default app or the carrier app, we skip
127 // binding to the app and go straight from fetch to loaded.
128 //
129 // At any time, at most one connection is active. If events are not in this order, previous
130 // connection will be unbind, so only latest event takes effect.
131 //
132 // We broadcast ACTION_CARRIER_CONFIG_CHANGED after:
133 // 1. loading from carrier app (even if read from a file)
134 // 2. loading from default app if there is no carrier app (even if read from a file)
135 // 3. clearing config (e.g. due to sim removal)
136 // 4. encountering bind or IPC error
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800137 private Handler mHandler = new Handler() {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700138 @Override
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800139 public void handleMessage(Message msg) {
140 int phoneId = msg.arg1;
141 log("mHandler: " + msg.what + " phoneId: " + phoneId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700142 String iccid;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800143 CarrierIdentifier carrierId;
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700144 String carrierPackageName;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800145 ConfigServiceConnection conn;
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700146 PersistableBundle config;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800147 switch (msg.what) {
148 case EVENT_CLEAR_CONFIG:
149 mConfigFromDefaultApp[phoneId] = null;
150 mConfigFromCarrierApp[phoneId] = null;
151 mServiceConnection[phoneId] = null;
152 broadcastConfigChangedIntent(phoneId);
153 break;
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700154
155 case EVENT_PACKAGE_CHANGED:
156 carrierPackageName = (String) msg.obj;
157 deleteConfigForPackage(carrierPackageName);
158 int numPhones = TelephonyManager.from(mContext).getPhoneCount();
159 for (int i = 0; i < numPhones; ++i) {
160 updateConfigForPhoneId(i);
161 }
162 break;
163
164 case EVENT_FETCH_DEFAULT:
165 iccid = getIccIdForPhoneId(phoneId);
166 config = restoreConfigFromXml(DEFAULT_CARRIER_CONFIG_PACKAGE, iccid);
167 if (config != null) {
168 log("Loaded config from XML. package=" + DEFAULT_CARRIER_CONFIG_PACKAGE
169 + " phoneId=" + phoneId);
170 mConfigFromDefaultApp[phoneId] = config;
171 Message newMsg = obtainMessage(EVENT_LOADED_FROM_DEFAULT, phoneId, -1);
172 newMsg.getData().putBoolean("loaded_from_xml", true);
173 mHandler.sendMessage(newMsg);
174 } else {
175 if (!bindToConfigPackage(DEFAULT_CARRIER_CONFIG_PACKAGE,
176 phoneId, EVENT_CONNECTED_TO_DEFAULT)) {
177 // Send bcast if bind fails
178 broadcastConfigChangedIntent(phoneId);
179 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800180 }
181 break;
182
183 case EVENT_CONNECTED_TO_DEFAULT:
184 carrierId = getCarrierIdForPhoneId(phoneId);
185 conn = (ConfigServiceConnection) msg.obj;
186 // If new service connection has been created, unbind.
187 if (mServiceConnection[phoneId] != conn || conn.service == null) {
188 mContext.unbindService(conn);
189 break;
190 }
191 try {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700192 ICarrierConfigService configService = ICarrierConfigService.Stub
193 .asInterface(conn.service);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800194 config = configService.getCarrierConfig(carrierId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700195 iccid = getIccIdForPhoneId(phoneId);
196 saveConfigToXml(DEFAULT_CARRIER_CONFIG_PACKAGE, iccid, config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800197 mConfigFromDefaultApp[phoneId] = config;
Junda Liu9f2d2712015-05-15 14:22:45 -0700198 sendMessage(obtainMessage(EVENT_LOADED_FROM_DEFAULT, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800199 } catch (RemoteException ex) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700200 loge("Failed to get carrier config: " + ex.toString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800201 } finally {
202 mContext.unbindService(mServiceConnection[phoneId]);
203 }
204 break;
205
206 case EVENT_LOADED_FROM_DEFAULT:
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700207 // If we did not load from XML and the service connection is null, do not
208 // continue.
209 if (!msg.getData().getBoolean("loaded_from_xml", false)
210 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800211 break;
212 }
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700213 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
214 if (carrierPackageName != null) {
215 log("Found carrier config app: " + carrierPackageName);
216 sendMessage(obtainMessage(EVENT_FETCH_CARRIER, phoneId));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800217 } else {
218 broadcastConfigChangedIntent(phoneId);
219 }
220 break;
221
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700222 case EVENT_FETCH_CARRIER:
223 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
224 iccid = getIccIdForPhoneId(phoneId);
225 config = restoreConfigFromXml(carrierPackageName, iccid);
226 if (config != null) {
227 log("Loaded config from XML. package=" + carrierPackageName + " phoneId="
228 + phoneId);
229 mConfigFromCarrierApp[phoneId] = config;
230 Message newMsg = obtainMessage(EVENT_LOADED_FROM_CARRIER, phoneId, -1);
231 newMsg.getData().putBoolean("loaded_from_xml", true);
232 sendMessage(newMsg);
233 } else {
234 if (!bindToConfigPackage(carrierPackageName, phoneId,
235 EVENT_CONNECTED_TO_CARRIER)) {
236 // Send bcast if bind fails
237 broadcastConfigChangedIntent(phoneId);
238 }
239 }
240 break;
241
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800242 case EVENT_CONNECTED_TO_CARRIER:
243 carrierId = getCarrierIdForPhoneId(phoneId);
244 conn = (ConfigServiceConnection) msg.obj;
245 // If new service connection has been created, unbind.
246 if (mServiceConnection[phoneId] != conn ||
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700247 conn.service == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800248 mContext.unbindService(conn);
249 break;
250 }
251 try {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700252 ICarrierConfigService configService = ICarrierConfigService.Stub
253 .asInterface(conn.service);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800254 config = configService.getCarrierConfig(carrierId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700255 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
256 iccid = getIccIdForPhoneId(phoneId);
257 saveConfigToXml(carrierPackageName, iccid, config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800258 mConfigFromCarrierApp[phoneId] = config;
Junda Liu9f2d2712015-05-15 14:22:45 -0700259 sendMessage(obtainMessage(EVENT_LOADED_FROM_CARRIER, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800260 } catch (RemoteException ex) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700261 loge("Failed to get carrier config: " + ex.toString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800262 } finally {
263 mContext.unbindService(mServiceConnection[phoneId]);
264 }
265 break;
266
267 case EVENT_LOADED_FROM_CARRIER:
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700268 // If we did not load from XML and the service connection is null, do not
269 // continue.
270 if (!msg.getData().getBoolean("loaded_from_xml", false)
271 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800272 break;
273 }
274 broadcastConfigChangedIntent(phoneId);
275 break;
276 }
277 }
278 };
279
280 /**
281 * Constructs a CarrierConfigLoader, registers it as a service, and registers a broadcast
282 * receiver for relevant events.
283 */
284 private CarrierConfigLoader(Context context) {
285 mContext = context;
286
287 // Register for package updates.
288 IntentFilter triggers = new IntentFilter();
289 triggers.addAction(Intent.ACTION_PACKAGE_ADDED);
290 triggers.addAction(Intent.ACTION_PACKAGE_CHANGED);
291 triggers.addAction(Intent.ACTION_PACKAGE_REMOVED);
292 mContext.registerReceiver(mReceiver, triggers);
293
294 int numPhones = TelephonyManager.from(context).getPhoneCount();
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700295 mConfigFromDefaultApp = new PersistableBundle[numPhones];
296 mConfigFromCarrierApp = new PersistableBundle[numPhones];
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800297 mServiceConnection = new ConfigServiceConnection[numPhones];
298 // Make this service available through ServiceManager.
299 ServiceManager.addService(Context.CARRIER_CONFIG_SERVICE, this);
300 log("CarrierConfigLoader has started");
301 }
302
303 /**
304 * Initialize the singleton CarrierConfigLoader instance.
305 *
306 * This is only done once, at startup, from {@link com.android.phone.PhoneApp#onCreate}.
307 */
308 /* package */
309 static CarrierConfigLoader init(Context context) {
310 synchronized (CarrierConfigLoader.class) {
311 if (sInstance == null) {
312 sInstance = new CarrierConfigLoader(context);
313 } else {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700314 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800315 }
316 return sInstance;
317 }
318 }
319
320 private void broadcastConfigChangedIntent(int phoneId) {
321 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
322 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
323 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, phoneId);
324 ActivityManagerNative.broadcastStickyIntent(intent, READ_PHONE_STATE,
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700325 UserHandle.USER_ALL);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800326 }
327
328 /** Binds to the default or carrier config app. */
329 private boolean bindToConfigPackage(String pkgName, int phoneId, int eventId) {
330 log("Binding to " + pkgName + " for phone " + phoneId);
331 Intent carrierConfigService = new Intent(CarrierConfigService.SERVICE_INTERFACE);
332 carrierConfigService.setPackage(pkgName);
333 mServiceConnection[phoneId] = new ConfigServiceConnection(phoneId, eventId);
334 try {
335 return mContext.bindService(carrierConfigService, mServiceConnection[phoneId],
336 Context.BIND_AUTO_CREATE);
337 } catch (SecurityException ex) {
338 return false;
339 }
340 }
341
342 private CarrierIdentifier getCarrierIdForPhoneId(int phoneId) {
343 String mcc = "";
344 String mnc = "";
345 String imsi = "";
346 String gid1 = "";
347 String gid2 = "";
348 String spn = TelephonyManager.from(mContext).getSimOperatorNameForPhone(phoneId);
349 String simOperator = TelephonyManager.from(mContext).getSimOperatorNumericForPhone(phoneId);
Jonathan Basseri1fa437c2015-04-20 11:08:18 -0700350 // A valid simOperator should be 5 or 6 digits, depending on the length of the MNC.
351 if (simOperator != null && simOperator.length() >= 3) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800352 mcc = simOperator.substring(0, 3);
353 mnc = simOperator.substring(3);
354 }
355 Phone phone = PhoneFactory.getPhone(phoneId);
356 if (phone != null) {
357 imsi = phone.getSubscriberId();
358 gid1 = phone.getGroupIdLevel1();
Junda Liu73183532015-05-14 13:55:40 -0700359 gid2 = phone.getGroupIdLevel2();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800360 }
361
362 return new CarrierIdentifier(mcc, mnc, spn, imsi, gid1, gid2);
363 }
364
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700365 /** Returns the package name of a priveleged carrier app, or null if there is none. */
366 private String getCarrierPackageForPhoneId(int phoneId) {
367 List<String> carrierPackageNames = TelephonyManager.from(mContext)
368 .getCarrierPackageNamesForIntentAndPhone(
369 new Intent(CarrierConfigService.SERVICE_INTERFACE), phoneId);
370 if (carrierPackageNames != null && carrierPackageNames.size() > 0) {
371 return carrierPackageNames.get(0);
372 } else {
373 return null;
374 }
375 }
376
377 private String getIccIdForPhoneId(int phoneId) {
378 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
379 return null;
380 }
381 Phone phone = PhoneFactory.getPhone(phoneId);
382 if (phone == null) {
383 return null;
384 }
385 return phone.getIccSerialNumber();
386 }
387
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700388 /**
389 * Writes a bundle to an XML file.
390 *
391 * The bundle will be written to a file named after the package name and ICCID, so that it can
392 * be restored later with {@link @restoreConfigFromXml}. The XML output will include the bundle
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700393 * and the current version of the specified package.
394 *
395 * In case of errors or invalid input, no file will be written.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700396 *
397 * @param packageName the name of the package from which we fetched this bundle.
398 * @param iccid the ICCID of the subscription for which this bundle was fetched.
399 * @param config the bundle to be written.
400 */
401 private void saveConfigToXml(String packageName, String iccid, PersistableBundle config) {
402 final String version = getPackageVersion(packageName);
403 if (version == null) {
404 loge("Failed to get package version for: " + packageName);
405 return;
406 }
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700407 if (packageName == null || iccid == null) {
408 loge("Cannot save config with null packageName or iccid.");
409 return;
410 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700411
412 FileOutputStream outFile = null;
413 try {
414 outFile = new FileOutputStream(
415 new File(mContext.getFilesDir(), getFilenameForConfig(packageName, iccid)));
416 FastXmlSerializer out = new FastXmlSerializer();
417 out.setOutput(outFile, "utf-8");
418 out.startDocument("utf-8", true);
419 out.startTag(null, TAG_DOCUMENT);
420 out.startTag(null, TAG_VERSION);
421 out.text(version);
422 out.endTag(null, TAG_VERSION);
423 out.startTag(null, TAG_BUNDLE);
424 config.saveToXml(out);
425 out.endTag(null, TAG_BUNDLE);
426 out.endTag(null, TAG_DOCUMENT);
427 out.endDocument();
428 out.flush();
429 outFile.close();
430 }
431 catch (IOException e) {
432 loge(e.toString());
433 }
434 catch (XmlPullParserException e) {
435 loge(e.toString());
436 }
437 }
438
439 /**
440 * Reads a bundle from an XML file.
441 *
442 * This restores a bundle that was written with {@link #saveConfigToXml}. This returns the saved
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700443 * config bundle for the given package and ICCID.
444 *
445 * In case of errors, or if the saved config is from a different package version than the
446 * current version, then null will be returned.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700447 *
448 * @param packageName the name of the package from which we fetched this bundle.
449 * @param iccid the ICCID of the subscription for which this bundle was fetched.
450 * @return the bundle from the XML file. Returns null if there is no saved config, the saved
451 * version does not match, or reading config fails.
452 */
453 private PersistableBundle restoreConfigFromXml(String packageName, String iccid) {
454 final String version = getPackageVersion(packageName);
455 if (version == null) {
456 loge("Failed to get package version for: " + packageName);
457 return null;
458 }
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700459 if (packageName == null || iccid == null) {
460 loge("Cannot restore config with null packageName or iccid.");
461 return null;
462 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700463
464 PersistableBundle restoredBundle = null;
465 FileInputStream inFile = null;
466 try {
467 inFile = new FileInputStream(
468 new File(mContext.getFilesDir(), getFilenameForConfig(packageName, iccid)));
469 XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
470 parser.setInput(inFile, "utf-8");
471
472 int event;
473 while (((event = parser.next()) != XmlPullParser.END_DOCUMENT)) {
474
475 if (event == XmlPullParser.START_TAG && TAG_VERSION.equals(parser.getName())) {
476 String savedVersion = parser.nextText();
477 if (!version.equals(savedVersion)) {
478 log("Saved version mismatch: " + version + " vs " + savedVersion);
479 break;
480 }
481 }
482
483 if (event == XmlPullParser.START_TAG && TAG_BUNDLE.equals(parser.getName())) {
484 restoredBundle = PersistableBundle.restoreFromXml(parser);
485 }
486 }
487 inFile.close();
488 }
489 catch (FileNotFoundException e) {
490 loge(e.toString());
491 }
492 catch (XmlPullParserException e) {
493 loge(e.toString());
494 }
495 catch (IOException e) {
496 loge(e.toString());
497 }
498
499 return restoredBundle;
500 }
501
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700502 /** Deletes all saved XML files associated with the given package name. */
503 private void deleteConfigForPackage(final String packageName) {
504 File dir = mContext.getFilesDir();
505 File[] packageFiles = dir.listFiles(new FilenameFilter() {
506 public boolean accept(File dir, String filename) {
507 return filename.startsWith("carrierconfig-" + packageName + "-");
508 }
509 });
510 for (File f : packageFiles) {
511 log("deleting " + f.getName());
512 f.delete();
513 }
514 }
515
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700516 /** Builds a canonical file name for a config file. */
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700517 private String getFilenameForConfig(@NonNull String packageName, @NonNull String iccid) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700518 return "carrierconfig-" + packageName + "-" + iccid + ".xml";
519 }
520
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700521 /** Return the current version code of a package, or null if the name is not found. */
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700522 private String getPackageVersion(String packageName) {
523 try {
524 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700525 return Integer.toString(info.versionCode);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700526 } catch (PackageManager.NameNotFoundException e) {
527 return null;
528 }
529 }
530
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700531 /** Read up to date config.
532 *
533 * This reads config bundles for the given phoneId. That means getting the latest bundle from
534 * the default app and a privileged carrier app, if present. This will not bind to an app if we
535 * have a saved config file to use instead.
536 */
537 private void updateConfigForPhoneId(int phoneId) {
538 mHandler.sendMessage(mHandler.obtainMessage(EVENT_FETCH_DEFAULT, phoneId, -1));
539 }
540
541 @Override public
542 @NonNull
543 PersistableBundle getConfigForSubId(int subId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800544 int phoneId = SubscriptionManager.getPhoneId(subId);
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700545 PersistableBundle retConfig = CarrierConfigManager.getDefaultConfig();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800546 if (SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700547 PersistableBundle config = mConfigFromDefaultApp[phoneId];
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700548 if (config != null)
549 retConfig.putAll(config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800550 config = mConfigFromCarrierApp[phoneId];
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700551 if (config != null)
552 retConfig.putAll(config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800553 }
554 return retConfig;
555 }
556
557 @Override
558 public void reloadCarrierConfigForSubId(int subId) {
559 int phoneId = SubscriptionManager.getPhoneId(subId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700560 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800561 log("Ignore invalid phoneId: " + phoneId + " for subId: " + subId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700562 return;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800563 }
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700564 String callingPackageName = mContext.getPackageManager().getNameForUid(
565 Binder.getCallingUid());
566 // TODO: This check isn't per subId.
567 int privilegeStatus = TelephonyManager.from(mContext).checkCarrierPrivilegesForPackage(
568 callingPackageName);
569 if (privilegeStatus != TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) {
570 throw new SecurityException(
571 "Package is not privileged for subId=" + subId + ": " + callingPackageName);
572 }
573
574 // This method should block until deleting has completed, so that an error which prevents us
575 // from clearing the cache is passed back to the carrier app. With the files successfully
576 // deleted, this can return and we will eventually bind to the carrier app.
577 deleteConfigForPackage(callingPackageName);
578 updateConfigForPhoneId(phoneId);
579
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800580 }
581
582 @Override
583 public void updateConfigForPhoneId(int phoneId, String simState) {
584 log("update config for phoneId: " + phoneId + " simState: " + simState);
585 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
586 return;
587 }
588 // requires Java 7 for switch on string.
589 switch (simState) {
590 case IccCardConstants.INTENT_VALUE_ICC_ABSENT:
591 case IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR:
592 case IccCardConstants.INTENT_VALUE_ICC_UNKNOWN:
Junda Liu9f2d2712015-05-15 14:22:45 -0700593 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CLEAR_CONFIG, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800594 break;
595 case IccCardConstants.INTENT_VALUE_ICC_LOADED:
596 case IccCardConstants.INTENT_VALUE_ICC_LOCKED:
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700597 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800598 break;
599 }
600 }
601
Junda Liu43d723a2015-05-12 17:23:45 -0700602 @Override
603 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
604 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
605 != PackageManager.PERMISSION_GRANTED) {
606 pw.println("Permission Denial: can't dump carrierconfig from from pid="
607 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
608 return;
609 }
610 pw.println("CarrierConfigLoader: " + this);
611 for (int i = 0; i < TelephonyManager.getDefault().getPhoneCount(); i++) {
612 pw.println(" Phone Id=" + i);
613 pw.println(" mConfigFromDefaultApp=" + mConfigFromDefaultApp[i]);
614 pw.println(" mConfigFromCarrierApp=" + mConfigFromCarrierApp[i]);
615 }
616 }
617
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800618 private class ConfigServiceConnection implements ServiceConnection {
619 int phoneId;
620 int eventId;
621 IBinder service;
622
623 public ConfigServiceConnection(int phoneId, int eventId) {
624 this.phoneId = phoneId;
625 this.eventId = eventId;
626 }
627
628 @Override
629 public void onServiceConnected(ComponentName name, IBinder service) {
630 log("Connected to config app: " + name.flattenToString());
631 this.service = service;
632 mHandler.sendMessage(mHandler.obtainMessage(eventId, phoneId, -1, this));
633 }
634
635 @Override
636 public void onServiceDisconnected(ComponentName name) {
637 this.service = null;
638 }
639 }
640
641 private class ConfigLoaderBroadcastReceiver extends BroadcastReceiver {
642 @Override
643 public void onReceive(Context context, Intent intent) {
644 String action = intent.getAction();
645 log("Receive action: " + action);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700646 switch (action) {
647 case Intent.ACTION_PACKAGE_ADDED:
648 case Intent.ACTION_PACKAGE_CHANGED:
649 case Intent.ACTION_PACKAGE_REMOVED:
650 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
651 String packageName = mContext.getPackageManager().getNameForUid(uid);
652 // We don't have a phoneId for arg1.
653 mHandler.sendMessage(
654 mHandler.obtainMessage(EVENT_PACKAGE_CHANGED, packageName));
655 break;
656
657 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800658 }
659 }
660
661 private static void log(String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700662 Log.d(LOG_TAG, msg);
663 }
664
665 private static void loge(String msg) {
666 Log.e(LOG_TAG, msg);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800667 }
668}