blob: 2c2e0952a4e261dc15849d5e5e50c8ec7b11d86a [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
96 // Broadcast receiver for SIM and pkg intents, register intent filter in constructor.
97 private final BroadcastReceiver mReceiver = new ConfigLoaderBroadcastReceiver();
98
99 // Message codes; see mHandler below.
100 // Request from SubscriptionInfoUpdater when SIM becomes absent or error.
101 private static final int EVENT_CLEAR_CONFIG = 0;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800102 // Has connected to default app.
103 private static final int EVENT_CONNECTED_TO_DEFAULT = 3;
104 // Has connected to carrier app.
105 private static final int EVENT_CONNECTED_TO_CARRIER = 4;
106 // Config has been loaded from default app.
107 private static final int EVENT_LOADED_FROM_DEFAULT = 5;
108 // Config has been loaded from carrier app.
109 private static final int EVENT_LOADED_FROM_CARRIER = 6;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700110 // Attempt to fetch from default app or read from XML.
111 private static final int EVENT_FETCH_DEFAULT = 7;
112 // Attempt to fetch from carrier app or read from XML.
113 private static final int EVENT_FETCH_CARRIER = 8;
114 // A package has been installed, uninstalled, or updated.
115 private static final int EVENT_PACKAGE_CHANGED = 9;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700116 // Bind timed out for the default app.
117 private static final int EVENT_BIND_DEFAULT_TIMEOUT = 10;
118 // Bind timed out for a carrier app.
119 private static final int EVENT_BIND_CARRIER_TIMEOUT = 11;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700120 // Check if the system fingerprint has changed.
121 private static final int EVENT_CHECK_SYSTEM_UPDATE = 12;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700122
123 private static final int BIND_TIMEOUT_MILLIS = 10000;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800124
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700125 // Tags used for saving and restoring XML documents.
126 private static final String TAG_DOCUMENT = "carrier_config";
127 private static final String TAG_VERSION = "package_version";
128 private static final String TAG_BUNDLE = "bundle_data";
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800129
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700130 // SharedPreferences key for last known build fingerprint.
131 private static final String KEY_FINGERPRINT = "build_fingerprint";
132
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800133 // Handler to process various events.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700134 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700135 // For each phoneId, the event sequence should be:
136 // fetch default, connected to default, loaded from default,
137 // fetch carrier, connected to carrier, loaded from carrier.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700138 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700139 // If there is a saved config file for either the default app or the carrier app, we skip
140 // binding to the app and go straight from fetch to loaded.
141 //
142 // At any time, at most one connection is active. If events are not in this order, previous
143 // connection will be unbound, so only latest event takes effect.
144 //
145 // We broadcast ACTION_CARRIER_CONFIG_CHANGED after:
146 // 1. loading from carrier app (even if read from a file)
147 // 2. loading from default app if there is no carrier app (even if read from a file)
148 // 3. clearing config (e.g. due to sim removal)
149 // 4. encountering bind or IPC error
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800150 private Handler mHandler = new Handler() {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700151 @Override
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800152 public void handleMessage(Message msg) {
153 int phoneId = msg.arg1;
154 log("mHandler: " + msg.what + " phoneId: " + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700155 String iccid;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800156 CarrierIdentifier carrierId;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700157 String carrierPackageName;
Zach Johnson36d7aab2015-05-22 15:43:00 -0700158 CarrierServiceConnection conn;
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700159 PersistableBundle config;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800160 switch (msg.what) {
161 case EVENT_CLEAR_CONFIG:
Junda Liu0486bdb2015-05-22 15:01:35 -0700162 if (mConfigFromDefaultApp[phoneId] == null &&
163 mConfigFromCarrierApp[phoneId] == null)
164 break;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800165 mConfigFromDefaultApp[phoneId] = null;
166 mConfigFromCarrierApp[phoneId] = null;
167 mServiceConnection[phoneId] = null;
168 broadcastConfigChangedIntent(phoneId);
169 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700170
171 case EVENT_PACKAGE_CHANGED:
172 carrierPackageName = (String) msg.obj;
Junda Liu8a8a53a2015-05-15 16:19:57 -0700173 // Only update if there are cached config removed to avoid updating config
174 // for unrelated packages.
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700175 if (clearCachedConfigForPackage(carrierPackageName)) {
Junda Liu8a8a53a2015-05-15 16:19:57 -0700176 int numPhones = TelephonyManager.from(mContext).getPhoneCount();
177 for (int i = 0; i < numPhones; ++i) {
178 updateConfigForPhoneId(i);
179 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700180 }
181 break;
182
183 case EVENT_FETCH_DEFAULT:
184 iccid = getIccIdForPhoneId(phoneId);
185 config = restoreConfigFromXml(DEFAULT_CARRIER_CONFIG_PACKAGE, iccid);
186 if (config != null) {
187 log("Loaded config from XML. package=" + DEFAULT_CARRIER_CONFIG_PACKAGE
188 + " phoneId=" + phoneId);
189 mConfigFromDefaultApp[phoneId] = config;
190 Message newMsg = obtainMessage(EVENT_LOADED_FROM_DEFAULT, phoneId, -1);
191 newMsg.getData().putBoolean("loaded_from_xml", true);
192 mHandler.sendMessage(newMsg);
193 } else {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700194 if (bindToConfigPackage(DEFAULT_CARRIER_CONFIG_PACKAGE,
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700195 phoneId, EVENT_CONNECTED_TO_DEFAULT)) {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700196 sendMessageDelayed(obtainMessage(EVENT_BIND_DEFAULT_TIMEOUT, phoneId, -1),
197 BIND_TIMEOUT_MILLIS);
198 } else {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700199 // Send bcast if bind fails
200 broadcastConfigChangedIntent(phoneId);
201 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800202 }
203 break;
204
205 case EVENT_CONNECTED_TO_DEFAULT:
Jonathan Basseri930701e2015-06-11 20:56:43 -0700206 removeMessages(EVENT_BIND_DEFAULT_TIMEOUT);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800207 carrierId = getCarrierIdForPhoneId(phoneId);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700208 conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800209 // If new service connection has been created, unbind.
210 if (mServiceConnection[phoneId] != conn || conn.service == null) {
211 mContext.unbindService(conn);
212 break;
213 }
214 try {
Zach Johnson36d7aab2015-05-22 15:43:00 -0700215 ICarrierService carrierService = ICarrierService.Stub
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700216 .asInterface(conn.service);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700217 config = carrierService.getCarrierConfig(carrierId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700218 iccid = getIccIdForPhoneId(phoneId);
219 saveConfigToXml(DEFAULT_CARRIER_CONFIG_PACKAGE, iccid, config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800220 mConfigFromDefaultApp[phoneId] = config;
Junda Liu9f2d2712015-05-15 14:22:45 -0700221 sendMessage(obtainMessage(EVENT_LOADED_FROM_DEFAULT, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800222 } catch (RemoteException ex) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700223 loge("Failed to get carrier config: " + ex.toString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800224 } finally {
225 mContext.unbindService(mServiceConnection[phoneId]);
226 }
227 break;
228
Jonathan Basseri930701e2015-06-11 20:56:43 -0700229 case EVENT_BIND_DEFAULT_TIMEOUT:
230 mContext.unbindService(mServiceConnection[phoneId]);
231 broadcastConfigChangedIntent(phoneId);
232 break;
233
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800234 case EVENT_LOADED_FROM_DEFAULT:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700235 // If we attempted to bind to the app, but the service connection is null, then
236 // config was cleared while we were waiting and we should not continue.
237 if (!msg.getData().getBoolean("loaded_from_xml", false)
238 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800239 break;
240 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700241 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
242 if (carrierPackageName != null) {
243 log("Found carrier config app: " + carrierPackageName);
244 sendMessage(obtainMessage(EVENT_FETCH_CARRIER, phoneId));
Jonathan Basserib919e932015-05-27 16:53:08 +0000245 } else {
246 broadcastConfigChangedIntent(phoneId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700247 }
248 break;
249
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700250 case EVENT_FETCH_CARRIER:
251 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
252 iccid = getIccIdForPhoneId(phoneId);
253 config = restoreConfigFromXml(carrierPackageName, iccid);
254 if (config != null) {
255 log("Loaded config from XML. package=" + carrierPackageName + " phoneId="
256 + phoneId);
257 mConfigFromCarrierApp[phoneId] = config;
258 Message newMsg = obtainMessage(EVENT_LOADED_FROM_CARRIER, phoneId, -1);
259 newMsg.getData().putBoolean("loaded_from_xml", true);
260 sendMessage(newMsg);
261 } else {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700262 if (bindToConfigPackage(carrierPackageName, phoneId,
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700263 EVENT_CONNECTED_TO_CARRIER)) {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700264 sendMessageDelayed(obtainMessage(EVENT_BIND_CARRIER_TIMEOUT, phoneId, -1),
265 BIND_TIMEOUT_MILLIS);
266 } else {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700267 // Send bcast if bind fails
268 broadcastConfigChangedIntent(phoneId);
269 }
270 }
271 break;
272
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800273 case EVENT_CONNECTED_TO_CARRIER:
Jonathan Basseri930701e2015-06-11 20:56:43 -0700274 removeMessages(EVENT_BIND_CARRIER_TIMEOUT);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800275 carrierId = getCarrierIdForPhoneId(phoneId);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700276 conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800277 // If new service connection has been created, unbind.
278 if (mServiceConnection[phoneId] != conn ||
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700279 conn.service == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800280 mContext.unbindService(conn);
281 break;
282 }
283 try {
Zach Johnson36d7aab2015-05-22 15:43:00 -0700284 ICarrierService carrierService = ICarrierService.Stub
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700285 .asInterface(conn.service);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700286 config = carrierService.getCarrierConfig(carrierId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700287 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
288 iccid = getIccIdForPhoneId(phoneId);
289 saveConfigToXml(carrierPackageName, iccid, config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800290 mConfigFromCarrierApp[phoneId] = config;
Junda Liu9f2d2712015-05-15 14:22:45 -0700291 sendMessage(obtainMessage(EVENT_LOADED_FROM_CARRIER, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800292 } catch (RemoteException ex) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700293 loge("Failed to get carrier config: " + ex.toString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800294 } finally {
295 mContext.unbindService(mServiceConnection[phoneId]);
296 }
297 break;
298
Jonathan Basseri930701e2015-06-11 20:56:43 -0700299 case EVENT_BIND_CARRIER_TIMEOUT:
300 mContext.unbindService(mServiceConnection[phoneId]);
301 broadcastConfigChangedIntent(phoneId);
302 break;
303
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800304 case EVENT_LOADED_FROM_CARRIER:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700305 // If we attempted to bind to the app, but the service connection is null, then
306 // config was cleared while we were waiting and we should not continue.
307 if (!msg.getData().getBoolean("loaded_from_xml", false)
308 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800309 break;
310 }
311 broadcastConfigChangedIntent(phoneId);
312 break;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700313
314 case EVENT_CHECK_SYSTEM_UPDATE:
315 SharedPreferences sharedPrefs =
316 PreferenceManager.getDefaultSharedPreferences(mContext);
317 final String lastFingerprint = sharedPrefs.getString(KEY_FINGERPRINT, null);
318 if (!Build.FINGERPRINT.equals(lastFingerprint)) {
319 log("Build fingerprint changed. old: "
320 + lastFingerprint + " new: " + Build.FINGERPRINT);
321 clearCachedConfigForPackage(null);
322 sharedPrefs.edit().putString(KEY_FINGERPRINT, Build.FINGERPRINT).apply();
323 }
324 break;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800325 }
326 }
327 };
328
329 /**
330 * Constructs a CarrierConfigLoader, registers it as a service, and registers a broadcast
331 * receiver for relevant events.
332 */
333 private CarrierConfigLoader(Context context) {
334 mContext = context;
335
Junda Liu8a8a53a2015-05-15 16:19:57 -0700336 // Register for package updates. Update app or uninstall app update will have all 3 intents,
337 // in the order or removed, added, replaced, all with extra_replace set to true.
338 IntentFilter pkgFilter = new IntentFilter();
339 pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
340 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
341 pkgFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
342 pkgFilter.addDataScheme("package");
343 context.registerReceiverAsUser(mReceiver, UserHandle.ALL, pkgFilter, null, null);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800344
345 int numPhones = TelephonyManager.from(context).getPhoneCount();
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700346 mConfigFromDefaultApp = new PersistableBundle[numPhones];
347 mConfigFromCarrierApp = new PersistableBundle[numPhones];
Zach Johnson36d7aab2015-05-22 15:43:00 -0700348 mServiceConnection = new CarrierServiceConnection[numPhones];
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800349 // Make this service available through ServiceManager.
350 ServiceManager.addService(Context.CARRIER_CONFIG_SERVICE, this);
351 log("CarrierConfigLoader has started");
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700352 mHandler.sendEmptyMessage(EVENT_CHECK_SYSTEM_UPDATE);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800353 }
354
355 /**
356 * Initialize the singleton CarrierConfigLoader instance.
357 *
358 * This is only done once, at startup, from {@link com.android.phone.PhoneApp#onCreate}.
359 */
360 /* package */
361 static CarrierConfigLoader init(Context context) {
362 synchronized (CarrierConfigLoader.class) {
363 if (sInstance == null) {
364 sInstance = new CarrierConfigLoader(context);
365 } else {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700366 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800367 }
368 return sInstance;
369 }
370 }
371
372 private void broadcastConfigChangedIntent(int phoneId) {
373 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
374 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
375 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, phoneId);
376 ActivityManagerNative.broadcastStickyIntent(intent, READ_PHONE_STATE,
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700377 UserHandle.USER_ALL);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800378 }
379
380 /** Binds to the default or carrier config app. */
381 private boolean bindToConfigPackage(String pkgName, int phoneId, int eventId) {
382 log("Binding to " + pkgName + " for phone " + phoneId);
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700383 Intent carrierService = new Intent(CarrierService.CARRIER_SERVICE_INTERFACE);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700384 carrierService.setPackage(pkgName);
385 mServiceConnection[phoneId] = new CarrierServiceConnection(phoneId, eventId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800386 try {
Zach Johnson36d7aab2015-05-22 15:43:00 -0700387 return mContext.bindService(carrierService, mServiceConnection[phoneId],
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800388 Context.BIND_AUTO_CREATE);
389 } catch (SecurityException ex) {
390 return false;
391 }
392 }
393
394 private CarrierIdentifier getCarrierIdForPhoneId(int phoneId) {
395 String mcc = "";
396 String mnc = "";
397 String imsi = "";
398 String gid1 = "";
399 String gid2 = "";
400 String spn = TelephonyManager.from(mContext).getSimOperatorNameForPhone(phoneId);
401 String simOperator = TelephonyManager.from(mContext).getSimOperatorNumericForPhone(phoneId);
Jonathan Basseri1fa437c2015-04-20 11:08:18 -0700402 // A valid simOperator should be 5 or 6 digits, depending on the length of the MNC.
403 if (simOperator != null && simOperator.length() >= 3) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800404 mcc = simOperator.substring(0, 3);
405 mnc = simOperator.substring(3);
406 }
407 Phone phone = PhoneFactory.getPhone(phoneId);
408 if (phone != null) {
409 imsi = phone.getSubscriberId();
410 gid1 = phone.getGroupIdLevel1();
Junda Liu73183532015-05-14 13:55:40 -0700411 gid2 = phone.getGroupIdLevel2();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800412 }
413
414 return new CarrierIdentifier(mcc, mnc, spn, imsi, gid1, gid2);
415 }
416
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700417 /** Returns the package name of a priveleged carrier app, or null if there is none. */
418 private String getCarrierPackageForPhoneId(int phoneId) {
419 List<String> carrierPackageNames = TelephonyManager.from(mContext)
420 .getCarrierPackageNamesForIntentAndPhone(
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700421 new Intent(CarrierService.CARRIER_SERVICE_INTERFACE), phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700422 if (carrierPackageNames != null && carrierPackageNames.size() > 0) {
423 return carrierPackageNames.get(0);
424 } else {
425 return null;
426 }
427 }
428
429 private String getIccIdForPhoneId(int phoneId) {
430 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
431 return null;
432 }
433 Phone phone = PhoneFactory.getPhone(phoneId);
434 if (phone == null) {
435 return null;
436 }
437 return phone.getIccSerialNumber();
438 }
439
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700440 /**
441 * Writes a bundle to an XML file.
442 *
443 * The bundle will be written to a file named after the package name and ICCID, so that it can
444 * be restored later with {@link @restoreConfigFromXml}. The XML output will include the bundle
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700445 * and the current version of the specified package.
446 *
447 * In case of errors or invalid input, no file will be written.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700448 *
449 * @param packageName the name of the package from which we fetched this bundle.
450 * @param iccid the ICCID of the subscription for which this bundle was fetched.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700451 * @param config the bundle to be written. Null will be treated as an empty bundle.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700452 */
453 private void saveConfigToXml(String packageName, String iccid, PersistableBundle config) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700454 if (packageName == null || iccid == null) {
455 loge("Cannot save config with null packageName or iccid.");
456 return;
457 }
458 if (config == null) {
459 config = new PersistableBundle();
460 }
461
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700462 final String version = getPackageVersion(packageName);
463 if (version == null) {
464 loge("Failed to get package version for: " + packageName);
465 return;
466 }
467
468 FileOutputStream outFile = null;
469 try {
470 outFile = new FileOutputStream(
471 new File(mContext.getFilesDir(), getFilenameForConfig(packageName, iccid)));
472 FastXmlSerializer out = new FastXmlSerializer();
473 out.setOutput(outFile, "utf-8");
474 out.startDocument("utf-8", true);
475 out.startTag(null, TAG_DOCUMENT);
476 out.startTag(null, TAG_VERSION);
477 out.text(version);
478 out.endTag(null, TAG_VERSION);
479 out.startTag(null, TAG_BUNDLE);
480 config.saveToXml(out);
481 out.endTag(null, TAG_BUNDLE);
482 out.endTag(null, TAG_DOCUMENT);
483 out.endDocument();
484 out.flush();
485 outFile.close();
486 }
487 catch (IOException e) {
488 loge(e.toString());
489 }
490 catch (XmlPullParserException e) {
491 loge(e.toString());
492 }
493 }
494
495 /**
496 * Reads a bundle from an XML file.
497 *
498 * This restores a bundle that was written with {@link #saveConfigToXml}. This returns the saved
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700499 * config bundle for the given package and ICCID.
500 *
501 * In case of errors, or if the saved config is from a different package version than the
502 * current version, then null will be returned.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700503 *
504 * @param packageName the name of the package from which we fetched this bundle.
505 * @param iccid the ICCID of the subscription for which this bundle was fetched.
506 * @return the bundle from the XML file. Returns null if there is no saved config, the saved
507 * version does not match, or reading config fails.
508 */
509 private PersistableBundle restoreConfigFromXml(String packageName, String iccid) {
510 final String version = getPackageVersion(packageName);
511 if (version == null) {
512 loge("Failed to get package version for: " + packageName);
513 return null;
514 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700515 if (packageName == null || iccid == null) {
516 loge("Cannot restore config with null packageName or iccid.");
517 return null;
518 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700519
520 PersistableBundle restoredBundle = null;
521 FileInputStream inFile = null;
522 try {
523 inFile = new FileInputStream(
524 new File(mContext.getFilesDir(), getFilenameForConfig(packageName, iccid)));
525 XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
526 parser.setInput(inFile, "utf-8");
527
528 int event;
529 while (((event = parser.next()) != XmlPullParser.END_DOCUMENT)) {
530
531 if (event == XmlPullParser.START_TAG && TAG_VERSION.equals(parser.getName())) {
532 String savedVersion = parser.nextText();
533 if (!version.equals(savedVersion)) {
534 log("Saved version mismatch: " + version + " vs " + savedVersion);
535 break;
536 }
537 }
538
539 if (event == XmlPullParser.START_TAG && TAG_BUNDLE.equals(parser.getName())) {
540 restoredBundle = PersistableBundle.restoreFromXml(parser);
541 }
542 }
543 inFile.close();
544 }
545 catch (FileNotFoundException e) {
546 loge(e.toString());
547 }
548 catch (XmlPullParserException e) {
549 loge(e.toString());
550 }
551 catch (IOException e) {
552 loge(e.toString());
553 }
554
555 return restoredBundle;
556 }
557
Junda Liu8a8a53a2015-05-15 16:19:57 -0700558 /**
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700559 * Clears cached carrier config.
560 * This deletes all saved XML files associated with the given package name. If packageName is
561 * null, then it deletes all saved XML files.
562 *
563 * @param packageName the name of a carrier package, or null if all cached config should be
564 * cleared.
565 * @return true iff one or more files were deleted.
Junda Liu8a8a53a2015-05-15 16:19:57 -0700566 */
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700567 private boolean clearCachedConfigForPackage(final String packageName) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700568 File dir = mContext.getFilesDir();
569 File[] packageFiles = dir.listFiles(new FilenameFilter() {
570 public boolean accept(File dir, String filename) {
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700571 if (packageName != null) {
572 return filename.startsWith("carrierconfig-" + packageName + "-");
573 } else {
574 return filename.startsWith("carrierconfig-");
575 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700576 }
577 });
Junda Liu8a8a53a2015-05-15 16:19:57 -0700578 if (packageFiles == null || packageFiles.length < 1) return false;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700579 for (File f : packageFiles) {
580 log("deleting " + f.getName());
581 f.delete();
582 }
Junda Liu8a8a53a2015-05-15 16:19:57 -0700583 return true;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700584 }
585
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700586 /** Builds a canonical file name for a config file. */
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700587 private String getFilenameForConfig(@NonNull String packageName, @NonNull String iccid) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700588 return "carrierconfig-" + packageName + "-" + iccid + ".xml";
589 }
590
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700591 /** Return the current version code of a package, or null if the name is not found. */
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700592 private String getPackageVersion(String packageName) {
593 try {
594 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700595 return Integer.toString(info.versionCode);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700596 } catch (PackageManager.NameNotFoundException e) {
597 return null;
598 }
599 }
600
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700601 /** Read up to date config.
602 *
603 * This reads config bundles for the given phoneId. That means getting the latest bundle from
604 * the default app and a privileged carrier app, if present. This will not bind to an app if we
605 * have a saved config file to use instead.
606 */
607 private void updateConfigForPhoneId(int phoneId) {
Junda Liu8a8a53a2015-05-15 16:19:57 -0700608 // Clear in-memory cache for carrier app config, so when carrier app gets uninstalled, no
609 // stale config is left.
610 if (mConfigFromCarrierApp[phoneId] != null &&
611 getCarrierPackageForPhoneId(phoneId) == null) {
612 mConfigFromCarrierApp[phoneId] = null;
613 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700614 mHandler.sendMessage(mHandler.obtainMessage(EVENT_FETCH_DEFAULT, phoneId, -1));
615 }
616
617 @Override public
618 @NonNull
619 PersistableBundle getConfigForSubId(int subId) {
Amit Mahajan40b3fa52015-07-14 10:27:19 -0700620 try {
621 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, null);
622 // SKIP checking run-time READ_PHONE_STATE since using PRIVILEGED
623 } catch (SecurityException e) {
624 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, null);
625 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800626 int phoneId = SubscriptionManager.getPhoneId(subId);
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700627 PersistableBundle retConfig = CarrierConfigManager.getDefaultConfig();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800628 if (SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700629 PersistableBundle config = mConfigFromDefaultApp[phoneId];
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700630 if (config != null)
631 retConfig.putAll(config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800632 config = mConfigFromCarrierApp[phoneId];
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700633 if (config != null)
634 retConfig.putAll(config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800635 }
636 return retConfig;
637 }
638
639 @Override
Jonathan Basseri86030352015-06-08 12:27:56 -0700640 public void notifyConfigChangedForSubId(int subId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800641 int phoneId = SubscriptionManager.getPhoneId(subId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700642 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800643 log("Ignore invalid phoneId: " + phoneId + " for subId: " + subId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700644 return;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800645 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700646 String callingPackageName = mContext.getPackageManager().getNameForUid(
647 Binder.getCallingUid());
648 // TODO: Check that the calling packages is privileged for subId specifically.
649 int privilegeStatus = TelephonyManager.from(mContext).checkCarrierPrivilegesForPackage(
650 callingPackageName);
651 if (privilegeStatus != TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) {
652 throw new SecurityException(
653 "Package is not privileged for subId=" + subId + ": " + callingPackageName);
654 }
655
656 // This method should block until deleting has completed, so that an error which prevents us
657 // from clearing the cache is passed back to the carrier app. With the files successfully
658 // deleted, this can return and we will eventually bind to the carrier app.
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700659 clearCachedConfigForPackage(callingPackageName);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700660 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800661 }
662
663 @Override
664 public void updateConfigForPhoneId(int phoneId, String simState) {
Junda Liu1f2b34d2015-06-18 15:26:56 -0700665 mContext.enforceCallingOrSelfPermission(
666 android.Manifest.permission.MODIFY_PHONE_STATE, null);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800667 log("update config for phoneId: " + phoneId + " simState: " + simState);
668 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
669 return;
670 }
671 // requires Java 7 for switch on string.
672 switch (simState) {
673 case IccCardConstants.INTENT_VALUE_ICC_ABSENT:
674 case IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR:
675 case IccCardConstants.INTENT_VALUE_ICC_UNKNOWN:
Junda Liu9f2d2712015-05-15 14:22:45 -0700676 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CLEAR_CONFIG, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800677 break;
678 case IccCardConstants.INTENT_VALUE_ICC_LOADED:
679 case IccCardConstants.INTENT_VALUE_ICC_LOCKED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700680 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800681 break;
682 }
683 }
684
Junda Liu43d723a2015-05-12 17:23:45 -0700685 @Override
686 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
687 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
688 != PackageManager.PERMISSION_GRANTED) {
689 pw.println("Permission Denial: can't dump carrierconfig from from pid="
690 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
691 return;
692 }
693 pw.println("CarrierConfigLoader: " + this);
694 for (int i = 0; i < TelephonyManager.getDefault().getPhoneCount(); i++) {
695 pw.println(" Phone Id=" + i);
696 pw.println(" mConfigFromDefaultApp=" + mConfigFromDefaultApp[i]);
697 pw.println(" mConfigFromCarrierApp=" + mConfigFromCarrierApp[i]);
698 }
699 }
700
Zach Johnson36d7aab2015-05-22 15:43:00 -0700701 private class CarrierServiceConnection implements ServiceConnection {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800702 int phoneId;
703 int eventId;
704 IBinder service;
705
Zach Johnson36d7aab2015-05-22 15:43:00 -0700706 public CarrierServiceConnection(int phoneId, int eventId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800707 this.phoneId = phoneId;
708 this.eventId = eventId;
709 }
710
711 @Override
712 public void onServiceConnected(ComponentName name, IBinder service) {
713 log("Connected to config app: " + name.flattenToString());
714 this.service = service;
715 mHandler.sendMessage(mHandler.obtainMessage(eventId, phoneId, -1, this));
716 }
717
718 @Override
719 public void onServiceDisconnected(ComponentName name) {
720 this.service = null;
721 }
722 }
723
724 private class ConfigLoaderBroadcastReceiver extends BroadcastReceiver {
725 @Override
726 public void onReceive(Context context, Intent intent) {
727 String action = intent.getAction();
Junda Liu8a8a53a2015-05-15 16:19:57 -0700728 boolean replace = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
729 // If replace is true, only care ACTION_PACKAGE_REPLACED.
730 if (replace && !Intent.ACTION_PACKAGE_REPLACED.equals(action))
731 return;
732
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700733 switch (action) {
734 case Intent.ACTION_PACKAGE_ADDED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700735 case Intent.ACTION_PACKAGE_REMOVED:
Junda Liu8a8a53a2015-05-15 16:19:57 -0700736 case Intent.ACTION_PACKAGE_REPLACED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700737 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
738 String packageName = mContext.getPackageManager().getNameForUid(uid);
Junda Liu8a8a53a2015-05-15 16:19:57 -0700739 if (packageName != null) {
740 // We don't have a phoneId for arg1.
741 mHandler.sendMessage(
742 mHandler.obtainMessage(EVENT_PACKAGE_CHANGED, packageName));
743 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700744 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700745 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800746 }
747 }
748
749 private static void log(String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700750 Log.d(LOG_TAG, msg);
751 }
752
753 private static void loge(String msg) {
754 Log.e(LOG_TAG, msg);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800755 }
756}