blob: e0834c71728ed4063e2f83b7842d4f992b2ef370 [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;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080020
Jonathan Basseri11f89572015-05-05 11:57:39 -070021import android.annotation.NonNull;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080022import android.app.ActivityManagerNative;
23import android.content.BroadcastReceiver;
24import android.content.ComponentName;
25import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.content.ServiceConnection;
Jonathan Basseri7697cae2015-07-06 15:49:23 -070029import android.content.SharedPreferences;
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 Basseri7697cae2015-07-06 15:49:23 -070036import android.os.Build;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080037import android.os.Handler;
38import android.os.IBinder;
39import android.os.Message;
Jonathan Basseric31f1f32015-05-12 10:13:03 -070040import android.os.PersistableBundle;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080041import android.os.RemoteException;
42import android.os.ServiceManager;
43import android.os.UserHandle;
Jonathan Basseri7697cae2015-07-06 15:49:23 -070044import android.preference.PreferenceManager;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080045import android.service.carrier.CarrierIdentifier;
Zach Johnson36d7aab2015-05-22 15:43:00 -070046import android.service.carrier.CarrierService;
47import android.service.carrier.ICarrierService;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080048import android.telephony.CarrierConfigManager;
49import android.telephony.SubscriptionManager;
50import android.telephony.TelephonyManager;
51import android.util.Log;
52
53import com.android.internal.telephony.ICarrierConfigLoader;
54import com.android.internal.telephony.IccCardConstants;
55import com.android.internal.telephony.Phone;
56import com.android.internal.telephony.PhoneConstants;
57import com.android.internal.telephony.PhoneFactory;
58import com.android.internal.telephony.TelephonyIntents;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070059import com.android.internal.util.FastXmlSerializer;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080060
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070061import org.xmlpull.v1.XmlPullParser;
62import org.xmlpull.v1.XmlPullParserException;
63import org.xmlpull.v1.XmlPullParserFactory;
64
65import java.io.File;
Junda Liu43d723a2015-05-12 17:23:45 -070066import java.io.FileDescriptor;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070067import java.io.FileInputStream;
68import java.io.FileNotFoundException;
69import java.io.FileOutputStream;
Jonathan Basseri1f743c92015-05-15 00:19:46 -070070import java.io.FilenameFilter;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070071import java.io.IOException;
Junda Liu43d723a2015-05-12 17:23:45 -070072import java.io.PrintWriter;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080073import java.util.List;
74
75/**
76 * CarrierConfigLoader binds to privileged carrier apps to fetch carrier config overlays.
Jonathan Basseri6465afd2015-02-25 13:05:57 -080077 */
78
79public class CarrierConfigLoader extends ICarrierConfigLoader.Stub {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070080 private static final String LOG_TAG = "CarrierConfigLoader";
Jonathan Basseri6465afd2015-02-25 13:05:57 -080081 // Package name for default carrier config app, bundled with system image.
82 private static final String DEFAULT_CARRIER_CONFIG_PACKAGE = "com.android.carrierconfig";
83
84 /** The singleton instance. */
85 private static CarrierConfigLoader sInstance;
86 // The context for phone app, passed from PhoneGlobals.
87 private Context mContext;
88 // Carrier configs from default app, indexed by phoneID.
Jonathan Basseric31f1f32015-05-12 10:13:03 -070089 private PersistableBundle[] mConfigFromDefaultApp;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080090 // Carrier configs from privileged carrier config app, indexed by phoneID.
Jonathan Basseric31f1f32015-05-12 10:13:03 -070091 private PersistableBundle[] mConfigFromCarrierApp;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080092 // Service connection for binding to config app.
Zach Johnson36d7aab2015-05-22 15:43:00 -070093 private CarrierServiceConnection[] mServiceConnection;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080094
95 // Broadcast receiver for SIM and pkg intents, register intent filter in constructor.
96 private final BroadcastReceiver mReceiver = new ConfigLoaderBroadcastReceiver();
97
98 // Message codes; see mHandler below.
99 // Request from SubscriptionInfoUpdater when SIM becomes absent or error.
100 private static final int EVENT_CLEAR_CONFIG = 0;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800101 // Has connected to default app.
102 private static final int EVENT_CONNECTED_TO_DEFAULT = 3;
103 // Has connected to carrier app.
104 private static final int EVENT_CONNECTED_TO_CARRIER = 4;
105 // Config has been loaded from default app.
106 private static final int EVENT_LOADED_FROM_DEFAULT = 5;
107 // Config has been loaded from carrier app.
108 private static final int EVENT_LOADED_FROM_CARRIER = 6;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700109 // Attempt to fetch from default app or read from XML.
110 private static final int EVENT_FETCH_DEFAULT = 7;
111 // Attempt to fetch from carrier app or read from XML.
112 private static final int EVENT_FETCH_CARRIER = 8;
113 // A package has been installed, uninstalled, or updated.
114 private static final int EVENT_PACKAGE_CHANGED = 9;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700115 // Bind timed out for the default app.
116 private static final int EVENT_BIND_DEFAULT_TIMEOUT = 10;
117 // Bind timed out for a carrier app.
118 private static final int EVENT_BIND_CARRIER_TIMEOUT = 11;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700119 // Check if the system fingerprint has changed.
120 private static final int EVENT_CHECK_SYSTEM_UPDATE = 12;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700121
122 private static final int BIND_TIMEOUT_MILLIS = 10000;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800123
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700124 // Tags used for saving and restoring XML documents.
125 private static final String TAG_DOCUMENT = "carrier_config";
126 private static final String TAG_VERSION = "package_version";
127 private static final String TAG_BUNDLE = "bundle_data";
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800128
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700129 // SharedPreferences key for last known build fingerprint.
130 private static final String KEY_FINGERPRINT = "build_fingerprint";
131
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800132 // Handler to process various events.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700133 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700134 // For each phoneId, the event sequence should be:
135 // fetch default, connected to default, loaded from default,
136 // fetch carrier, connected to carrier, loaded from carrier.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700137 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700138 // If there is a saved config file for either the default app or the carrier app, we skip
139 // binding to the app and go straight from fetch to loaded.
140 //
141 // At any time, at most one connection is active. If events are not in this order, previous
142 // connection will be unbound, so only latest event takes effect.
143 //
144 // We broadcast ACTION_CARRIER_CONFIG_CHANGED after:
145 // 1. loading from carrier app (even if read from a file)
146 // 2. loading from default app if there is no carrier app (even if read from a file)
147 // 3. clearing config (e.g. due to sim removal)
148 // 4. encountering bind or IPC error
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800149 private Handler mHandler = new Handler() {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700150 @Override
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800151 public void handleMessage(Message msg) {
152 int phoneId = msg.arg1;
153 log("mHandler: " + msg.what + " phoneId: " + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700154 String iccid;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800155 CarrierIdentifier carrierId;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700156 String carrierPackageName;
Zach Johnson36d7aab2015-05-22 15:43:00 -0700157 CarrierServiceConnection conn;
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700158 PersistableBundle config;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800159 switch (msg.what) {
160 case EVENT_CLEAR_CONFIG:
Junda Liu0486bdb2015-05-22 15:01:35 -0700161 if (mConfigFromDefaultApp[phoneId] == null &&
162 mConfigFromCarrierApp[phoneId] == null)
163 break;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800164 mConfigFromDefaultApp[phoneId] = null;
165 mConfigFromCarrierApp[phoneId] = null;
166 mServiceConnection[phoneId] = null;
167 broadcastConfigChangedIntent(phoneId);
168 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700169
170 case EVENT_PACKAGE_CHANGED:
171 carrierPackageName = (String) msg.obj;
Junda Liu8a8a53a2015-05-15 16:19:57 -0700172 // Only update if there are cached config removed to avoid updating config
173 // for unrelated packages.
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700174 if (clearCachedConfigForPackage(carrierPackageName)) {
Junda Liu8a8a53a2015-05-15 16:19:57 -0700175 int numPhones = TelephonyManager.from(mContext).getPhoneCount();
176 for (int i = 0; i < numPhones; ++i) {
177 updateConfigForPhoneId(i);
178 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700179 }
180 break;
181
182 case EVENT_FETCH_DEFAULT:
183 iccid = getIccIdForPhoneId(phoneId);
184 config = restoreConfigFromXml(DEFAULT_CARRIER_CONFIG_PACKAGE, iccid);
185 if (config != null) {
186 log("Loaded config from XML. package=" + DEFAULT_CARRIER_CONFIG_PACKAGE
187 + " phoneId=" + phoneId);
188 mConfigFromDefaultApp[phoneId] = config;
189 Message newMsg = obtainMessage(EVENT_LOADED_FROM_DEFAULT, phoneId, -1);
190 newMsg.getData().putBoolean("loaded_from_xml", true);
191 mHandler.sendMessage(newMsg);
192 } else {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700193 if (bindToConfigPackage(DEFAULT_CARRIER_CONFIG_PACKAGE,
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700194 phoneId, EVENT_CONNECTED_TO_DEFAULT)) {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700195 sendMessageDelayed(obtainMessage(EVENT_BIND_DEFAULT_TIMEOUT, phoneId, -1),
196 BIND_TIMEOUT_MILLIS);
197 } else {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700198 // Send bcast if bind fails
199 broadcastConfigChangedIntent(phoneId);
200 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800201 }
202 break;
203
204 case EVENT_CONNECTED_TO_DEFAULT:
Jonathan Basseri930701e2015-06-11 20:56:43 -0700205 removeMessages(EVENT_BIND_DEFAULT_TIMEOUT);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800206 carrierId = getCarrierIdForPhoneId(phoneId);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700207 conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800208 // If new service connection has been created, unbind.
209 if (mServiceConnection[phoneId] != conn || conn.service == null) {
210 mContext.unbindService(conn);
211 break;
212 }
213 try {
Zach Johnson36d7aab2015-05-22 15:43:00 -0700214 ICarrierService carrierService = ICarrierService.Stub
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700215 .asInterface(conn.service);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700216 config = carrierService.getCarrierConfig(carrierId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700217 iccid = getIccIdForPhoneId(phoneId);
218 saveConfigToXml(DEFAULT_CARRIER_CONFIG_PACKAGE, iccid, config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800219 mConfigFromDefaultApp[phoneId] = config;
Junda Liu9f2d2712015-05-15 14:22:45 -0700220 sendMessage(obtainMessage(EVENT_LOADED_FROM_DEFAULT, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800221 } catch (RemoteException ex) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700222 loge("Failed to get carrier config: " + ex.toString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800223 } finally {
224 mContext.unbindService(mServiceConnection[phoneId]);
225 }
226 break;
227
Jonathan Basseri930701e2015-06-11 20:56:43 -0700228 case EVENT_BIND_DEFAULT_TIMEOUT:
229 mContext.unbindService(mServiceConnection[phoneId]);
230 broadcastConfigChangedIntent(phoneId);
231 break;
232
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800233 case EVENT_LOADED_FROM_DEFAULT:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700234 // If we attempted to bind to the app, but the service connection is null, then
235 // config was cleared while we were waiting and we should not continue.
236 if (!msg.getData().getBoolean("loaded_from_xml", false)
237 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800238 break;
239 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700240 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
241 if (carrierPackageName != null) {
242 log("Found carrier config app: " + carrierPackageName);
243 sendMessage(obtainMessage(EVENT_FETCH_CARRIER, phoneId));
Jonathan Basserib919e932015-05-27 16:53:08 +0000244 } else {
245 broadcastConfigChangedIntent(phoneId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700246 }
247 break;
248
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700249 case EVENT_FETCH_CARRIER:
250 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
251 iccid = getIccIdForPhoneId(phoneId);
252 config = restoreConfigFromXml(carrierPackageName, iccid);
253 if (config != null) {
254 log("Loaded config from XML. package=" + carrierPackageName + " phoneId="
255 + phoneId);
256 mConfigFromCarrierApp[phoneId] = config;
257 Message newMsg = obtainMessage(EVENT_LOADED_FROM_CARRIER, phoneId, -1);
258 newMsg.getData().putBoolean("loaded_from_xml", true);
259 sendMessage(newMsg);
260 } else {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700261 if (bindToConfigPackage(carrierPackageName, phoneId,
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700262 EVENT_CONNECTED_TO_CARRIER)) {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700263 sendMessageDelayed(obtainMessage(EVENT_BIND_CARRIER_TIMEOUT, phoneId, -1),
264 BIND_TIMEOUT_MILLIS);
265 } else {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700266 // Send bcast if bind fails
267 broadcastConfigChangedIntent(phoneId);
268 }
269 }
270 break;
271
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800272 case EVENT_CONNECTED_TO_CARRIER:
Jonathan Basseri930701e2015-06-11 20:56:43 -0700273 removeMessages(EVENT_BIND_CARRIER_TIMEOUT);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800274 carrierId = getCarrierIdForPhoneId(phoneId);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700275 conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800276 // If new service connection has been created, unbind.
277 if (mServiceConnection[phoneId] != conn ||
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700278 conn.service == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800279 mContext.unbindService(conn);
280 break;
281 }
282 try {
Zach Johnson36d7aab2015-05-22 15:43:00 -0700283 ICarrierService carrierService = ICarrierService.Stub
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700284 .asInterface(conn.service);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700285 config = carrierService.getCarrierConfig(carrierId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700286 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
287 iccid = getIccIdForPhoneId(phoneId);
288 saveConfigToXml(carrierPackageName, iccid, config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800289 mConfigFromCarrierApp[phoneId] = config;
Junda Liu9f2d2712015-05-15 14:22:45 -0700290 sendMessage(obtainMessage(EVENT_LOADED_FROM_CARRIER, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800291 } catch (RemoteException ex) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700292 loge("Failed to get carrier config: " + ex.toString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800293 } finally {
294 mContext.unbindService(mServiceConnection[phoneId]);
295 }
296 break;
297
Jonathan Basseri930701e2015-06-11 20:56:43 -0700298 case EVENT_BIND_CARRIER_TIMEOUT:
299 mContext.unbindService(mServiceConnection[phoneId]);
300 broadcastConfigChangedIntent(phoneId);
301 break;
302
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800303 case EVENT_LOADED_FROM_CARRIER:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700304 // If we attempted to bind to the app, but the service connection is null, then
305 // config was cleared while we were waiting and we should not continue.
306 if (!msg.getData().getBoolean("loaded_from_xml", false)
307 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800308 break;
309 }
310 broadcastConfigChangedIntent(phoneId);
311 break;
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700312
313 case EVENT_CHECK_SYSTEM_UPDATE:
314 SharedPreferences sharedPrefs =
315 PreferenceManager.getDefaultSharedPreferences(mContext);
316 final String lastFingerprint = sharedPrefs.getString(KEY_FINGERPRINT, null);
317 if (!Build.FINGERPRINT.equals(lastFingerprint)) {
318 log("Build fingerprint changed. old: "
319 + lastFingerprint + " new: " + Build.FINGERPRINT);
320 clearCachedConfigForPackage(null);
321 sharedPrefs.edit().putString(KEY_FINGERPRINT, Build.FINGERPRINT).apply();
322 }
323 break;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800324 }
325 }
326 };
327
328 /**
329 * Constructs a CarrierConfigLoader, registers it as a service, and registers a broadcast
330 * receiver for relevant events.
331 */
332 private CarrierConfigLoader(Context context) {
333 mContext = context;
334
Junda Liu8a8a53a2015-05-15 16:19:57 -0700335 // Register for package updates. Update app or uninstall app update will have all 3 intents,
336 // in the order or removed, added, replaced, all with extra_replace set to true.
337 IntentFilter pkgFilter = new IntentFilter();
338 pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
339 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
340 pkgFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
341 pkgFilter.addDataScheme("package");
342 context.registerReceiverAsUser(mReceiver, UserHandle.ALL, pkgFilter, null, null);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800343
344 int numPhones = TelephonyManager.from(context).getPhoneCount();
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700345 mConfigFromDefaultApp = new PersistableBundle[numPhones];
346 mConfigFromCarrierApp = new PersistableBundle[numPhones];
Zach Johnson36d7aab2015-05-22 15:43:00 -0700347 mServiceConnection = new CarrierServiceConnection[numPhones];
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800348 // Make this service available through ServiceManager.
349 ServiceManager.addService(Context.CARRIER_CONFIG_SERVICE, this);
350 log("CarrierConfigLoader has started");
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700351 mHandler.sendEmptyMessage(EVENT_CHECK_SYSTEM_UPDATE);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800352 }
353
354 /**
355 * Initialize the singleton CarrierConfigLoader instance.
356 *
357 * This is only done once, at startup, from {@link com.android.phone.PhoneApp#onCreate}.
358 */
359 /* package */
360 static CarrierConfigLoader init(Context context) {
361 synchronized (CarrierConfigLoader.class) {
362 if (sInstance == null) {
363 sInstance = new CarrierConfigLoader(context);
364 } else {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700365 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800366 }
367 return sInstance;
368 }
369 }
370
371 private void broadcastConfigChangedIntent(int phoneId) {
372 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
373 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
374 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, phoneId);
375 ActivityManagerNative.broadcastStickyIntent(intent, READ_PHONE_STATE,
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700376 UserHandle.USER_ALL);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800377 }
378
379 /** Binds to the default or carrier config app. */
380 private boolean bindToConfigPackage(String pkgName, int phoneId, int eventId) {
381 log("Binding to " + pkgName + " for phone " + phoneId);
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700382 Intent carrierService = new Intent(CarrierService.CARRIER_SERVICE_INTERFACE);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700383 carrierService.setPackage(pkgName);
384 mServiceConnection[phoneId] = new CarrierServiceConnection(phoneId, eventId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800385 try {
Zach Johnson36d7aab2015-05-22 15:43:00 -0700386 return mContext.bindService(carrierService, mServiceConnection[phoneId],
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800387 Context.BIND_AUTO_CREATE);
388 } catch (SecurityException ex) {
389 return false;
390 }
391 }
392
393 private CarrierIdentifier getCarrierIdForPhoneId(int phoneId) {
394 String mcc = "";
395 String mnc = "";
396 String imsi = "";
397 String gid1 = "";
398 String gid2 = "";
399 String spn = TelephonyManager.from(mContext).getSimOperatorNameForPhone(phoneId);
400 String simOperator = TelephonyManager.from(mContext).getSimOperatorNumericForPhone(phoneId);
Jonathan Basseri1fa437c2015-04-20 11:08:18 -0700401 // A valid simOperator should be 5 or 6 digits, depending on the length of the MNC.
402 if (simOperator != null && simOperator.length() >= 3) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800403 mcc = simOperator.substring(0, 3);
404 mnc = simOperator.substring(3);
405 }
406 Phone phone = PhoneFactory.getPhone(phoneId);
407 if (phone != null) {
408 imsi = phone.getSubscriberId();
409 gid1 = phone.getGroupIdLevel1();
Junda Liu73183532015-05-14 13:55:40 -0700410 gid2 = phone.getGroupIdLevel2();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800411 }
412
413 return new CarrierIdentifier(mcc, mnc, spn, imsi, gid1, gid2);
414 }
415
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700416 /** Returns the package name of a priveleged carrier app, or null if there is none. */
417 private String getCarrierPackageForPhoneId(int phoneId) {
418 List<String> carrierPackageNames = TelephonyManager.from(mContext)
419 .getCarrierPackageNamesForIntentAndPhone(
Zach Johnsonfca8a8d2015-06-19 18:21:37 -0700420 new Intent(CarrierService.CARRIER_SERVICE_INTERFACE), phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700421 if (carrierPackageNames != null && carrierPackageNames.size() > 0) {
422 return carrierPackageNames.get(0);
423 } else {
424 return null;
425 }
426 }
427
428 private String getIccIdForPhoneId(int phoneId) {
429 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
430 return null;
431 }
432 Phone phone = PhoneFactory.getPhone(phoneId);
433 if (phone == null) {
434 return null;
435 }
436 return phone.getIccSerialNumber();
437 }
438
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700439 /**
440 * Writes a bundle to an XML file.
441 *
442 * The bundle will be written to a file named after the package name and ICCID, so that it can
443 * be restored later with {@link @restoreConfigFromXml}. The XML output will include the bundle
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700444 * and the current version of the specified package.
445 *
446 * In case of errors or invalid input, no file will be written.
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.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700450 * @param config the bundle to be written. Null will be treated as an empty bundle.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700451 */
452 private void saveConfigToXml(String packageName, String iccid, PersistableBundle config) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700453 if (packageName == null || iccid == null) {
454 loge("Cannot save config with null packageName or iccid.");
455 return;
456 }
457 if (config == null) {
458 config = new PersistableBundle();
459 }
460
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700461 final String version = getPackageVersion(packageName);
462 if (version == null) {
463 loge("Failed to get package version for: " + packageName);
464 return;
465 }
466
467 FileOutputStream outFile = null;
468 try {
469 outFile = new FileOutputStream(
470 new File(mContext.getFilesDir(), getFilenameForConfig(packageName, iccid)));
471 FastXmlSerializer out = new FastXmlSerializer();
472 out.setOutput(outFile, "utf-8");
473 out.startDocument("utf-8", true);
474 out.startTag(null, TAG_DOCUMENT);
475 out.startTag(null, TAG_VERSION);
476 out.text(version);
477 out.endTag(null, TAG_VERSION);
478 out.startTag(null, TAG_BUNDLE);
479 config.saveToXml(out);
480 out.endTag(null, TAG_BUNDLE);
481 out.endTag(null, TAG_DOCUMENT);
482 out.endDocument();
483 out.flush();
484 outFile.close();
485 }
486 catch (IOException e) {
487 loge(e.toString());
488 }
489 catch (XmlPullParserException e) {
490 loge(e.toString());
491 }
492 }
493
494 /**
495 * Reads a bundle from an XML file.
496 *
497 * This restores a bundle that was written with {@link #saveConfigToXml}. This returns the saved
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700498 * config bundle for the given package and ICCID.
499 *
500 * In case of errors, or if the saved config is from a different package version than the
501 * current version, then null will be returned.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700502 *
503 * @param packageName the name of the package from which we fetched this bundle.
504 * @param iccid the ICCID of the subscription for which this bundle was fetched.
505 * @return the bundle from the XML file. Returns null if there is no saved config, the saved
506 * version does not match, or reading config fails.
507 */
508 private PersistableBundle restoreConfigFromXml(String packageName, String iccid) {
509 final String version = getPackageVersion(packageName);
510 if (version == null) {
511 loge("Failed to get package version for: " + packageName);
512 return null;
513 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700514 if (packageName == null || iccid == null) {
515 loge("Cannot restore config with null packageName or iccid.");
516 return null;
517 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700518
519 PersistableBundle restoredBundle = null;
520 FileInputStream inFile = null;
521 try {
522 inFile = new FileInputStream(
523 new File(mContext.getFilesDir(), getFilenameForConfig(packageName, iccid)));
524 XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
525 parser.setInput(inFile, "utf-8");
526
527 int event;
528 while (((event = parser.next()) != XmlPullParser.END_DOCUMENT)) {
529
530 if (event == XmlPullParser.START_TAG && TAG_VERSION.equals(parser.getName())) {
531 String savedVersion = parser.nextText();
532 if (!version.equals(savedVersion)) {
533 log("Saved version mismatch: " + version + " vs " + savedVersion);
534 break;
535 }
536 }
537
538 if (event == XmlPullParser.START_TAG && TAG_BUNDLE.equals(parser.getName())) {
539 restoredBundle = PersistableBundle.restoreFromXml(parser);
540 }
541 }
542 inFile.close();
543 }
544 catch (FileNotFoundException e) {
545 loge(e.toString());
546 }
547 catch (XmlPullParserException e) {
548 loge(e.toString());
549 }
550 catch (IOException e) {
551 loge(e.toString());
552 }
553
554 return restoredBundle;
555 }
556
Junda Liu8a8a53a2015-05-15 16:19:57 -0700557 /**
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700558 * Clears cached carrier config.
559 * This deletes all saved XML files associated with the given package name. If packageName is
560 * null, then it deletes all saved XML files.
561 *
562 * @param packageName the name of a carrier package, or null if all cached config should be
563 * cleared.
564 * @return true iff one or more files were deleted.
Junda Liu8a8a53a2015-05-15 16:19:57 -0700565 */
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700566 private boolean clearCachedConfigForPackage(final String packageName) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700567 File dir = mContext.getFilesDir();
568 File[] packageFiles = dir.listFiles(new FilenameFilter() {
569 public boolean accept(File dir, String filename) {
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700570 if (packageName != null) {
571 return filename.startsWith("carrierconfig-" + packageName + "-");
572 } else {
573 return filename.startsWith("carrierconfig-");
574 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700575 }
576 });
Junda Liu8a8a53a2015-05-15 16:19:57 -0700577 if (packageFiles == null || packageFiles.length < 1) return false;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700578 for (File f : packageFiles) {
579 log("deleting " + f.getName());
580 f.delete();
581 }
Junda Liu8a8a53a2015-05-15 16:19:57 -0700582 return true;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700583 }
584
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700585 /** Builds a canonical file name for a config file. */
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700586 private String getFilenameForConfig(@NonNull String packageName, @NonNull String iccid) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700587 return "carrierconfig-" + packageName + "-" + iccid + ".xml";
588 }
589
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700590 /** Return the current version code of a package, or null if the name is not found. */
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700591 private String getPackageVersion(String packageName) {
592 try {
593 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700594 return Integer.toString(info.versionCode);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700595 } catch (PackageManager.NameNotFoundException e) {
596 return null;
597 }
598 }
599
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700600 /** Read up to date config.
601 *
602 * This reads config bundles for the given phoneId. That means getting the latest bundle from
603 * the default app and a privileged carrier app, if present. This will not bind to an app if we
604 * have a saved config file to use instead.
605 */
606 private void updateConfigForPhoneId(int phoneId) {
Junda Liu8a8a53a2015-05-15 16:19:57 -0700607 // Clear in-memory cache for carrier app config, so when carrier app gets uninstalled, no
608 // stale config is left.
609 if (mConfigFromCarrierApp[phoneId] != null &&
610 getCarrierPackageForPhoneId(phoneId) == null) {
611 mConfigFromCarrierApp[phoneId] = null;
612 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700613 mHandler.sendMessage(mHandler.obtainMessage(EVENT_FETCH_DEFAULT, phoneId, -1));
614 }
615
616 @Override public
617 @NonNull
618 PersistableBundle getConfigForSubId(int subId) {
Junda Liu1f2b34d2015-06-18 15:26:56 -0700619 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, null);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800620 int phoneId = SubscriptionManager.getPhoneId(subId);
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700621 PersistableBundle retConfig = CarrierConfigManager.getDefaultConfig();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800622 if (SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700623 PersistableBundle config = mConfigFromDefaultApp[phoneId];
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700624 if (config != null)
625 retConfig.putAll(config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800626 config = mConfigFromCarrierApp[phoneId];
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700627 if (config != null)
628 retConfig.putAll(config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800629 }
630 return retConfig;
631 }
632
633 @Override
Jonathan Basseri86030352015-06-08 12:27:56 -0700634 public void notifyConfigChangedForSubId(int subId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800635 int phoneId = SubscriptionManager.getPhoneId(subId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700636 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800637 log("Ignore invalid phoneId: " + phoneId + " for subId: " + subId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700638 return;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800639 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700640 String callingPackageName = mContext.getPackageManager().getNameForUid(
641 Binder.getCallingUid());
642 // TODO: Check that the calling packages is privileged for subId specifically.
643 int privilegeStatus = TelephonyManager.from(mContext).checkCarrierPrivilegesForPackage(
644 callingPackageName);
645 if (privilegeStatus != TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) {
646 throw new SecurityException(
647 "Package is not privileged for subId=" + subId + ": " + callingPackageName);
648 }
649
650 // This method should block until deleting has completed, so that an error which prevents us
651 // from clearing the cache is passed back to the carrier app. With the files successfully
652 // deleted, this can return and we will eventually bind to the carrier app.
Jonathan Basseri7697cae2015-07-06 15:49:23 -0700653 clearCachedConfigForPackage(callingPackageName);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700654 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800655 }
656
657 @Override
658 public void updateConfigForPhoneId(int phoneId, String simState) {
Junda Liu1f2b34d2015-06-18 15:26:56 -0700659 mContext.enforceCallingOrSelfPermission(
660 android.Manifest.permission.MODIFY_PHONE_STATE, null);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800661 log("update config for phoneId: " + phoneId + " simState: " + simState);
662 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
663 return;
664 }
665 // requires Java 7 for switch on string.
666 switch (simState) {
667 case IccCardConstants.INTENT_VALUE_ICC_ABSENT:
668 case IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR:
669 case IccCardConstants.INTENT_VALUE_ICC_UNKNOWN:
Junda Liu9f2d2712015-05-15 14:22:45 -0700670 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CLEAR_CONFIG, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800671 break;
672 case IccCardConstants.INTENT_VALUE_ICC_LOADED:
673 case IccCardConstants.INTENT_VALUE_ICC_LOCKED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700674 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800675 break;
676 }
677 }
678
Junda Liu43d723a2015-05-12 17:23:45 -0700679 @Override
680 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
681 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
682 != PackageManager.PERMISSION_GRANTED) {
683 pw.println("Permission Denial: can't dump carrierconfig from from pid="
684 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
685 return;
686 }
687 pw.println("CarrierConfigLoader: " + this);
688 for (int i = 0; i < TelephonyManager.getDefault().getPhoneCount(); i++) {
689 pw.println(" Phone Id=" + i);
690 pw.println(" mConfigFromDefaultApp=" + mConfigFromDefaultApp[i]);
691 pw.println(" mConfigFromCarrierApp=" + mConfigFromCarrierApp[i]);
692 }
693 }
694
Zach Johnson36d7aab2015-05-22 15:43:00 -0700695 private class CarrierServiceConnection implements ServiceConnection {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800696 int phoneId;
697 int eventId;
698 IBinder service;
699
Zach Johnson36d7aab2015-05-22 15:43:00 -0700700 public CarrierServiceConnection(int phoneId, int eventId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800701 this.phoneId = phoneId;
702 this.eventId = eventId;
703 }
704
705 @Override
706 public void onServiceConnected(ComponentName name, IBinder service) {
707 log("Connected to config app: " + name.flattenToString());
708 this.service = service;
709 mHandler.sendMessage(mHandler.obtainMessage(eventId, phoneId, -1, this));
710 }
711
712 @Override
713 public void onServiceDisconnected(ComponentName name) {
714 this.service = null;
715 }
716 }
717
718 private class ConfigLoaderBroadcastReceiver extends BroadcastReceiver {
719 @Override
720 public void onReceive(Context context, Intent intent) {
721 String action = intent.getAction();
Junda Liu8a8a53a2015-05-15 16:19:57 -0700722 boolean replace = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
723 // If replace is true, only care ACTION_PACKAGE_REPLACED.
724 if (replace && !Intent.ACTION_PACKAGE_REPLACED.equals(action))
725 return;
726
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700727 switch (action) {
728 case Intent.ACTION_PACKAGE_ADDED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700729 case Intent.ACTION_PACKAGE_REMOVED:
Junda Liu8a8a53a2015-05-15 16:19:57 -0700730 case Intent.ACTION_PACKAGE_REPLACED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700731 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
732 String packageName = mContext.getPackageManager().getNameForUid(uid);
Junda Liu8a8a53a2015-05-15 16:19:57 -0700733 if (packageName != null) {
734 // We don't have a phoneId for arg1.
735 mHandler.sendMessage(
736 mHandler.obtainMessage(EVENT_PACKAGE_CHANGED, packageName));
737 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700738 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700739 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800740 }
741 }
742
743 private static void log(String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700744 Log.d(LOG_TAG, msg);
745 }
746
747 private static void loge(String msg) {
748 Log.e(LOG_TAG, msg);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800749 }
750}