blob: b1621cf33711075e1e33d16551268e048e26cba4 [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 Basseri6b50e9f2015-05-12 20:18:31 -070029import android.content.pm.PackageInfo;
Jonathan Basseric31f1f32015-05-12 10:13:03 -070030import android.content.pm.PackageManager;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080031import android.database.sqlite.SQLiteDatabase;
32import android.database.sqlite.SQLiteOpenHelper;
33import android.os.AsyncResult;
Junda Liu43d723a2015-05-12 17:23:45 -070034import android.os.Binder;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080035import android.os.Handler;
36import android.os.IBinder;
37import android.os.Message;
Jonathan Basseric31f1f32015-05-12 10:13:03 -070038import android.os.PersistableBundle;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080039import android.os.RemoteException;
40import android.os.ServiceManager;
41import android.os.UserHandle;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080042import android.service.carrier.CarrierIdentifier;
Zach Johnson36d7aab2015-05-22 15:43:00 -070043import android.service.carrier.CarrierService;
44import android.service.carrier.ICarrierService;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080045import android.telephony.CarrierConfigManager;
46import android.telephony.SubscriptionManager;
47import android.telephony.TelephonyManager;
48import android.util.Log;
49
50import com.android.internal.telephony.ICarrierConfigLoader;
51import com.android.internal.telephony.IccCardConstants;
52import com.android.internal.telephony.Phone;
53import com.android.internal.telephony.PhoneConstants;
54import com.android.internal.telephony.PhoneFactory;
55import com.android.internal.telephony.TelephonyIntents;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070056import com.android.internal.util.FastXmlSerializer;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080057
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070058import org.xmlpull.v1.XmlPullParser;
59import org.xmlpull.v1.XmlPullParserException;
60import org.xmlpull.v1.XmlPullParserFactory;
61
62import java.io.File;
Junda Liu43d723a2015-05-12 17:23:45 -070063import java.io.FileDescriptor;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070064import java.io.FileInputStream;
65import java.io.FileNotFoundException;
66import java.io.FileOutputStream;
Jonathan Basseri1f743c92015-05-15 00:19:46 -070067import java.io.FilenameFilter;
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070068import java.io.IOException;
Junda Liu43d723a2015-05-12 17:23:45 -070069import java.io.PrintWriter;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080070import java.util.List;
71
72/**
73 * CarrierConfigLoader binds to privileged carrier apps to fetch carrier config overlays.
Jonathan Basseri6465afd2015-02-25 13:05:57 -080074 */
75
76public class CarrierConfigLoader extends ICarrierConfigLoader.Stub {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -070077 private static final String LOG_TAG = "CarrierConfigLoader";
Jonathan Basseri6465afd2015-02-25 13:05:57 -080078 // Package name for default carrier config app, bundled with system image.
79 private static final String DEFAULT_CARRIER_CONFIG_PACKAGE = "com.android.carrierconfig";
80
81 /** The singleton instance. */
82 private static CarrierConfigLoader sInstance;
83 // The context for phone app, passed from PhoneGlobals.
84 private Context mContext;
85 // Carrier configs from default app, indexed by phoneID.
Jonathan Basseric31f1f32015-05-12 10:13:03 -070086 private PersistableBundle[] mConfigFromDefaultApp;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080087 // Carrier configs from privileged carrier config app, indexed by phoneID.
Jonathan Basseric31f1f32015-05-12 10:13:03 -070088 private PersistableBundle[] mConfigFromCarrierApp;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080089 // Service connection for binding to config app.
Zach Johnson36d7aab2015-05-22 15:43:00 -070090 private CarrierServiceConnection[] mServiceConnection;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080091
92 // Broadcast receiver for SIM and pkg intents, register intent filter in constructor.
93 private final BroadcastReceiver mReceiver = new ConfigLoaderBroadcastReceiver();
94
95 // Message codes; see mHandler below.
96 // Request from SubscriptionInfoUpdater when SIM becomes absent or error.
97 private static final int EVENT_CLEAR_CONFIG = 0;
Jonathan Basseri6465afd2015-02-25 13:05:57 -080098 // Has connected to default app.
99 private static final int EVENT_CONNECTED_TO_DEFAULT = 3;
100 // Has connected to carrier app.
101 private static final int EVENT_CONNECTED_TO_CARRIER = 4;
102 // Config has been loaded from default app.
103 private static final int EVENT_LOADED_FROM_DEFAULT = 5;
104 // Config has been loaded from carrier app.
105 private static final int EVENT_LOADED_FROM_CARRIER = 6;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700106 // Attempt to fetch from default app or read from XML.
107 private static final int EVENT_FETCH_DEFAULT = 7;
108 // Attempt to fetch from carrier app or read from XML.
109 private static final int EVENT_FETCH_CARRIER = 8;
110 // A package has been installed, uninstalled, or updated.
111 private static final int EVENT_PACKAGE_CHANGED = 9;
Jonathan Basseri930701e2015-06-11 20:56:43 -0700112 // Bind timed out for the default app.
113 private static final int EVENT_BIND_DEFAULT_TIMEOUT = 10;
114 // Bind timed out for a carrier app.
115 private static final int EVENT_BIND_CARRIER_TIMEOUT = 11;
116
117 private static final int BIND_TIMEOUT_MILLIS = 10000;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800118
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700119 // Tags used for saving and restoring XML documents.
120 private static final String TAG_DOCUMENT = "carrier_config";
121 private static final String TAG_VERSION = "package_version";
122 private static final String TAG_BUNDLE = "bundle_data";
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800123
124 // Handler to process various events.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700125 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700126 // For each phoneId, the event sequence should be:
127 // fetch default, connected to default, loaded from default,
128 // fetch carrier, connected to carrier, loaded from carrier.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700129 //
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700130 // If there is a saved config file for either the default app or the carrier app, we skip
131 // binding to the app and go straight from fetch to loaded.
132 //
133 // At any time, at most one connection is active. If events are not in this order, previous
134 // connection will be unbound, so only latest event takes effect.
135 //
136 // We broadcast ACTION_CARRIER_CONFIG_CHANGED after:
137 // 1. loading from carrier app (even if read from a file)
138 // 2. loading from default app if there is no carrier app (even if read from a file)
139 // 3. clearing config (e.g. due to sim removal)
140 // 4. encountering bind or IPC error
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800141 private Handler mHandler = new Handler() {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700142 @Override
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800143 public void handleMessage(Message msg) {
144 int phoneId = msg.arg1;
145 log("mHandler: " + msg.what + " phoneId: " + phoneId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700146 String iccid;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800147 CarrierIdentifier carrierId;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700148 String carrierPackageName;
Zach Johnson36d7aab2015-05-22 15:43:00 -0700149 CarrierServiceConnection conn;
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700150 PersistableBundle config;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800151 switch (msg.what) {
152 case EVENT_CLEAR_CONFIG:
Junda Liu0486bdb2015-05-22 15:01:35 -0700153 if (mConfigFromDefaultApp[phoneId] == null &&
154 mConfigFromCarrierApp[phoneId] == null)
155 break;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800156 mConfigFromDefaultApp[phoneId] = null;
157 mConfigFromCarrierApp[phoneId] = null;
158 mServiceConnection[phoneId] = null;
159 broadcastConfigChangedIntent(phoneId);
160 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700161
162 case EVENT_PACKAGE_CHANGED:
163 carrierPackageName = (String) msg.obj;
Junda Liu8a8a53a2015-05-15 16:19:57 -0700164 // Only update if there are cached config removed to avoid updating config
165 // for unrelated packages.
166 if (deleteConfigForPackage(carrierPackageName)) {
167 int numPhones = TelephonyManager.from(mContext).getPhoneCount();
168 for (int i = 0; i < numPhones; ++i) {
169 updateConfigForPhoneId(i);
170 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700171 }
172 break;
173
174 case EVENT_FETCH_DEFAULT:
175 iccid = getIccIdForPhoneId(phoneId);
176 config = restoreConfigFromXml(DEFAULT_CARRIER_CONFIG_PACKAGE, iccid);
177 if (config != null) {
178 log("Loaded config from XML. package=" + DEFAULT_CARRIER_CONFIG_PACKAGE
179 + " phoneId=" + phoneId);
180 mConfigFromDefaultApp[phoneId] = config;
181 Message newMsg = obtainMessage(EVENT_LOADED_FROM_DEFAULT, phoneId, -1);
182 newMsg.getData().putBoolean("loaded_from_xml", true);
183 mHandler.sendMessage(newMsg);
184 } else {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700185 if (bindToConfigPackage(DEFAULT_CARRIER_CONFIG_PACKAGE,
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700186 phoneId, EVENT_CONNECTED_TO_DEFAULT)) {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700187 sendMessageDelayed(obtainMessage(EVENT_BIND_DEFAULT_TIMEOUT, phoneId, -1),
188 BIND_TIMEOUT_MILLIS);
189 } else {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700190 // Send bcast if bind fails
191 broadcastConfigChangedIntent(phoneId);
192 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800193 }
194 break;
195
196 case EVENT_CONNECTED_TO_DEFAULT:
Jonathan Basseri930701e2015-06-11 20:56:43 -0700197 removeMessages(EVENT_BIND_DEFAULT_TIMEOUT);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800198 carrierId = getCarrierIdForPhoneId(phoneId);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700199 conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800200 // If new service connection has been created, unbind.
201 if (mServiceConnection[phoneId] != conn || conn.service == null) {
202 mContext.unbindService(conn);
203 break;
204 }
205 try {
Zach Johnson36d7aab2015-05-22 15:43:00 -0700206 ICarrierService carrierService = ICarrierService.Stub
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700207 .asInterface(conn.service);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700208 config = carrierService.getCarrierConfig(carrierId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700209 iccid = getIccIdForPhoneId(phoneId);
210 saveConfigToXml(DEFAULT_CARRIER_CONFIG_PACKAGE, iccid, config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800211 mConfigFromDefaultApp[phoneId] = config;
Junda Liu9f2d2712015-05-15 14:22:45 -0700212 sendMessage(obtainMessage(EVENT_LOADED_FROM_DEFAULT, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800213 } catch (RemoteException ex) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700214 loge("Failed to get carrier config: " + ex.toString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800215 } finally {
216 mContext.unbindService(mServiceConnection[phoneId]);
217 }
218 break;
219
Jonathan Basseri930701e2015-06-11 20:56:43 -0700220 case EVENT_BIND_DEFAULT_TIMEOUT:
221 mContext.unbindService(mServiceConnection[phoneId]);
222 broadcastConfigChangedIntent(phoneId);
223 break;
224
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800225 case EVENT_LOADED_FROM_DEFAULT:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700226 // If we attempted to bind to the app, but the service connection is null, then
227 // config was cleared while we were waiting and we should not continue.
228 if (!msg.getData().getBoolean("loaded_from_xml", false)
229 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800230 break;
231 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700232 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
233 if (carrierPackageName != null) {
234 log("Found carrier config app: " + carrierPackageName);
235 sendMessage(obtainMessage(EVENT_FETCH_CARRIER, phoneId));
Jonathan Basserib919e932015-05-27 16:53:08 +0000236 } else {
237 broadcastConfigChangedIntent(phoneId);
Jonathan Basseri4ae2e7c2015-05-15 00:19:46 -0700238 }
239 break;
240
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700241 case EVENT_FETCH_CARRIER:
242 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
243 iccid = getIccIdForPhoneId(phoneId);
244 config = restoreConfigFromXml(carrierPackageName, iccid);
245 if (config != null) {
246 log("Loaded config from XML. package=" + carrierPackageName + " phoneId="
247 + phoneId);
248 mConfigFromCarrierApp[phoneId] = config;
249 Message newMsg = obtainMessage(EVENT_LOADED_FROM_CARRIER, phoneId, -1);
250 newMsg.getData().putBoolean("loaded_from_xml", true);
251 sendMessage(newMsg);
252 } else {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700253 if (bindToConfigPackage(carrierPackageName, phoneId,
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700254 EVENT_CONNECTED_TO_CARRIER)) {
Jonathan Basseri930701e2015-06-11 20:56:43 -0700255 sendMessageDelayed(obtainMessage(EVENT_BIND_CARRIER_TIMEOUT, phoneId, -1),
256 BIND_TIMEOUT_MILLIS);
257 } else {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700258 // Send bcast if bind fails
259 broadcastConfigChangedIntent(phoneId);
260 }
261 }
262 break;
263
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800264 case EVENT_CONNECTED_TO_CARRIER:
Jonathan Basseri930701e2015-06-11 20:56:43 -0700265 removeMessages(EVENT_BIND_CARRIER_TIMEOUT);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800266 carrierId = getCarrierIdForPhoneId(phoneId);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700267 conn = (CarrierServiceConnection) msg.obj;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800268 // If new service connection has been created, unbind.
269 if (mServiceConnection[phoneId] != conn ||
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700270 conn.service == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800271 mContext.unbindService(conn);
272 break;
273 }
274 try {
Zach Johnson36d7aab2015-05-22 15:43:00 -0700275 ICarrierService carrierService = ICarrierService.Stub
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700276 .asInterface(conn.service);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700277 config = carrierService.getCarrierConfig(carrierId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700278 carrierPackageName = getCarrierPackageForPhoneId(phoneId);
279 iccid = getIccIdForPhoneId(phoneId);
280 saveConfigToXml(carrierPackageName, iccid, config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800281 mConfigFromCarrierApp[phoneId] = config;
Junda Liu9f2d2712015-05-15 14:22:45 -0700282 sendMessage(obtainMessage(EVENT_LOADED_FROM_CARRIER, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800283 } catch (RemoteException ex) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700284 loge("Failed to get carrier config: " + ex.toString());
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800285 } finally {
286 mContext.unbindService(mServiceConnection[phoneId]);
287 }
288 break;
289
Jonathan Basseri930701e2015-06-11 20:56:43 -0700290 case EVENT_BIND_CARRIER_TIMEOUT:
291 mContext.unbindService(mServiceConnection[phoneId]);
292 broadcastConfigChangedIntent(phoneId);
293 break;
294
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800295 case EVENT_LOADED_FROM_CARRIER:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700296 // If we attempted to bind to the app, but the service connection is null, then
297 // config was cleared while we were waiting and we should not continue.
298 if (!msg.getData().getBoolean("loaded_from_xml", false)
299 && mServiceConnection[phoneId] == null) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800300 break;
301 }
302 broadcastConfigChangedIntent(phoneId);
303 break;
304 }
305 }
306 };
307
308 /**
309 * Constructs a CarrierConfigLoader, registers it as a service, and registers a broadcast
310 * receiver for relevant events.
311 */
312 private CarrierConfigLoader(Context context) {
313 mContext = context;
314
Junda Liu8a8a53a2015-05-15 16:19:57 -0700315 // Register for package updates. Update app or uninstall app update will have all 3 intents,
316 // in the order or removed, added, replaced, all with extra_replace set to true.
317 IntentFilter pkgFilter = new IntentFilter();
318 pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
319 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
320 pkgFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
321 pkgFilter.addDataScheme("package");
322 context.registerReceiverAsUser(mReceiver, UserHandle.ALL, pkgFilter, null, null);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800323
324 int numPhones = TelephonyManager.from(context).getPhoneCount();
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700325 mConfigFromDefaultApp = new PersistableBundle[numPhones];
326 mConfigFromCarrierApp = new PersistableBundle[numPhones];
Zach Johnson36d7aab2015-05-22 15:43:00 -0700327 mServiceConnection = new CarrierServiceConnection[numPhones];
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800328 // Make this service available through ServiceManager.
329 ServiceManager.addService(Context.CARRIER_CONFIG_SERVICE, this);
330 log("CarrierConfigLoader has started");
331 }
332
333 /**
334 * Initialize the singleton CarrierConfigLoader instance.
335 *
336 * This is only done once, at startup, from {@link com.android.phone.PhoneApp#onCreate}.
337 */
338 /* package */
339 static CarrierConfigLoader init(Context context) {
340 synchronized (CarrierConfigLoader.class) {
341 if (sInstance == null) {
342 sInstance = new CarrierConfigLoader(context);
343 } else {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700344 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800345 }
346 return sInstance;
347 }
348 }
349
350 private void broadcastConfigChangedIntent(int phoneId) {
351 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
352 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
353 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, phoneId);
354 ActivityManagerNative.broadcastStickyIntent(intent, READ_PHONE_STATE,
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700355 UserHandle.USER_ALL);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800356 }
357
358 /** Binds to the default or carrier config app. */
359 private boolean bindToConfigPackage(String pkgName, int phoneId, int eventId) {
360 log("Binding to " + pkgName + " for phone " + phoneId);
Zach Johnsona9d689f2015-05-27 16:23:22 -0700361 Intent carrierService = new Intent(CarrierService.CONFIG_SERVICE_INTERFACE);
Zach Johnson36d7aab2015-05-22 15:43:00 -0700362 carrierService.setPackage(pkgName);
363 mServiceConnection[phoneId] = new CarrierServiceConnection(phoneId, eventId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800364 try {
Zach Johnson36d7aab2015-05-22 15:43:00 -0700365 return mContext.bindService(carrierService, mServiceConnection[phoneId],
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800366 Context.BIND_AUTO_CREATE);
367 } catch (SecurityException ex) {
368 return false;
369 }
370 }
371
372 private CarrierIdentifier getCarrierIdForPhoneId(int phoneId) {
373 String mcc = "";
374 String mnc = "";
375 String imsi = "";
376 String gid1 = "";
377 String gid2 = "";
378 String spn = TelephonyManager.from(mContext).getSimOperatorNameForPhone(phoneId);
379 String simOperator = TelephonyManager.from(mContext).getSimOperatorNumericForPhone(phoneId);
Jonathan Basseri1fa437c2015-04-20 11:08:18 -0700380 // A valid simOperator should be 5 or 6 digits, depending on the length of the MNC.
381 if (simOperator != null && simOperator.length() >= 3) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800382 mcc = simOperator.substring(0, 3);
383 mnc = simOperator.substring(3);
384 }
385 Phone phone = PhoneFactory.getPhone(phoneId);
386 if (phone != null) {
387 imsi = phone.getSubscriberId();
388 gid1 = phone.getGroupIdLevel1();
Junda Liu73183532015-05-14 13:55:40 -0700389 gid2 = phone.getGroupIdLevel2();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800390 }
391
392 return new CarrierIdentifier(mcc, mnc, spn, imsi, gid1, gid2);
393 }
394
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700395 /** Returns the package name of a priveleged carrier app, or null if there is none. */
396 private String getCarrierPackageForPhoneId(int phoneId) {
397 List<String> carrierPackageNames = TelephonyManager.from(mContext)
398 .getCarrierPackageNamesForIntentAndPhone(
399 new Intent(CarrierService.CONFIG_SERVICE_INTERFACE), phoneId);
400 if (carrierPackageNames != null && carrierPackageNames.size() > 0) {
401 return carrierPackageNames.get(0);
402 } else {
403 return null;
404 }
405 }
406
407 private String getIccIdForPhoneId(int phoneId) {
408 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
409 return null;
410 }
411 Phone phone = PhoneFactory.getPhone(phoneId);
412 if (phone == null) {
413 return null;
414 }
415 return phone.getIccSerialNumber();
416 }
417
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700418 /**
419 * Writes a bundle to an XML file.
420 *
421 * The bundle will be written to a file named after the package name and ICCID, so that it can
422 * be restored later with {@link @restoreConfigFromXml}. The XML output will include the bundle
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700423 * and the current version of the specified package.
424 *
425 * In case of errors or invalid input, no file will be written.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700426 *
427 * @param packageName the name of the package from which we fetched this bundle.
428 * @param iccid the ICCID of the subscription for which this bundle was fetched.
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700429 * @param config the bundle to be written. Null will be treated as an empty bundle.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700430 */
431 private void saveConfigToXml(String packageName, String iccid, PersistableBundle config) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700432 if (packageName == null || iccid == null) {
433 loge("Cannot save config with null packageName or iccid.");
434 return;
435 }
436 if (config == null) {
437 config = new PersistableBundle();
438 }
439
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700440 final String version = getPackageVersion(packageName);
441 if (version == null) {
442 loge("Failed to get package version for: " + packageName);
443 return;
444 }
445
446 FileOutputStream outFile = null;
447 try {
448 outFile = new FileOutputStream(
449 new File(mContext.getFilesDir(), getFilenameForConfig(packageName, iccid)));
450 FastXmlSerializer out = new FastXmlSerializer();
451 out.setOutput(outFile, "utf-8");
452 out.startDocument("utf-8", true);
453 out.startTag(null, TAG_DOCUMENT);
454 out.startTag(null, TAG_VERSION);
455 out.text(version);
456 out.endTag(null, TAG_VERSION);
457 out.startTag(null, TAG_BUNDLE);
458 config.saveToXml(out);
459 out.endTag(null, TAG_BUNDLE);
460 out.endTag(null, TAG_DOCUMENT);
461 out.endDocument();
462 out.flush();
463 outFile.close();
464 }
465 catch (IOException e) {
466 loge(e.toString());
467 }
468 catch (XmlPullParserException e) {
469 loge(e.toString());
470 }
471 }
472
473 /**
474 * Reads a bundle from an XML file.
475 *
476 * This restores a bundle that was written with {@link #saveConfigToXml}. This returns the saved
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700477 * config bundle for the given package and ICCID.
478 *
479 * In case of errors, or if the saved config is from a different package version than the
480 * current version, then null will be returned.
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700481 *
482 * @param packageName the name of the package from which we fetched this bundle.
483 * @param iccid the ICCID of the subscription for which this bundle was fetched.
484 * @return the bundle from the XML file. Returns null if there is no saved config, the saved
485 * version does not match, or reading config fails.
486 */
487 private PersistableBundle restoreConfigFromXml(String packageName, String iccid) {
488 final String version = getPackageVersion(packageName);
489 if (version == null) {
490 loge("Failed to get package version for: " + packageName);
491 return null;
492 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700493 if (packageName == null || iccid == null) {
494 loge("Cannot restore config with null packageName or iccid.");
495 return null;
496 }
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700497
498 PersistableBundle restoredBundle = null;
499 FileInputStream inFile = null;
500 try {
501 inFile = new FileInputStream(
502 new File(mContext.getFilesDir(), getFilenameForConfig(packageName, iccid)));
503 XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
504 parser.setInput(inFile, "utf-8");
505
506 int event;
507 while (((event = parser.next()) != XmlPullParser.END_DOCUMENT)) {
508
509 if (event == XmlPullParser.START_TAG && TAG_VERSION.equals(parser.getName())) {
510 String savedVersion = parser.nextText();
511 if (!version.equals(savedVersion)) {
512 log("Saved version mismatch: " + version + " vs " + savedVersion);
513 break;
514 }
515 }
516
517 if (event == XmlPullParser.START_TAG && TAG_BUNDLE.equals(parser.getName())) {
518 restoredBundle = PersistableBundle.restoreFromXml(parser);
519 }
520 }
521 inFile.close();
522 }
523 catch (FileNotFoundException e) {
524 loge(e.toString());
525 }
526 catch (XmlPullParserException e) {
527 loge(e.toString());
528 }
529 catch (IOException e) {
530 loge(e.toString());
531 }
532
533 return restoredBundle;
534 }
535
Junda Liu8a8a53a2015-05-15 16:19:57 -0700536 /**
537 * Deletes all saved XML files associated with the given package name.
538 * Return false if can't find matching XML files.
539 */
540 private boolean deleteConfigForPackage(final String packageName) {
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700541 File dir = mContext.getFilesDir();
542 File[] packageFiles = dir.listFiles(new FilenameFilter() {
543 public boolean accept(File dir, String filename) {
544 return filename.startsWith("carrierconfig-" + packageName + "-");
545 }
546 });
Junda Liu8a8a53a2015-05-15 16:19:57 -0700547 if (packageFiles == null || packageFiles.length < 1) return false;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700548 for (File f : packageFiles) {
549 log("deleting " + f.getName());
550 f.delete();
551 }
Junda Liu8a8a53a2015-05-15 16:19:57 -0700552 return true;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700553 }
554
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700555 /** Builds a canonical file name for a config file. */
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700556 private String getFilenameForConfig(@NonNull String packageName, @NonNull String iccid) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700557 return "carrierconfig-" + packageName + "-" + iccid + ".xml";
558 }
559
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700560 /** Return the current version code of a package, or null if the name is not found. */
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700561 private String getPackageVersion(String packageName) {
562 try {
563 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700564 return Integer.toString(info.versionCode);
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700565 } catch (PackageManager.NameNotFoundException e) {
566 return null;
567 }
568 }
569
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700570 /** Read up to date config.
571 *
572 * This reads config bundles for the given phoneId. That means getting the latest bundle from
573 * the default app and a privileged carrier app, if present. This will not bind to an app if we
574 * have a saved config file to use instead.
575 */
576 private void updateConfigForPhoneId(int phoneId) {
Junda Liu8a8a53a2015-05-15 16:19:57 -0700577 // Clear in-memory cache for carrier app config, so when carrier app gets uninstalled, no
578 // stale config is left.
579 if (mConfigFromCarrierApp[phoneId] != null &&
580 getCarrierPackageForPhoneId(phoneId) == null) {
581 mConfigFromCarrierApp[phoneId] = null;
582 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700583 mHandler.sendMessage(mHandler.obtainMessage(EVENT_FETCH_DEFAULT, phoneId, -1));
584 }
585
586 @Override public
587 @NonNull
588 PersistableBundle getConfigForSubId(int subId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800589 int phoneId = SubscriptionManager.getPhoneId(subId);
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700590 PersistableBundle retConfig = CarrierConfigManager.getDefaultConfig();
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800591 if (SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseric31f1f32015-05-12 10:13:03 -0700592 PersistableBundle config = mConfigFromDefaultApp[phoneId];
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700593 if (config != null)
594 retConfig.putAll(config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800595 config = mConfigFromCarrierApp[phoneId];
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700596 if (config != null)
597 retConfig.putAll(config);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800598 }
599 return retConfig;
600 }
601
602 @Override
Jonathan Basseri86030352015-06-08 12:27:56 -0700603 public void notifyConfigChangedForSubId(int subId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800604 int phoneId = SubscriptionManager.getPhoneId(subId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700605 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800606 log("Ignore invalid phoneId: " + phoneId + " for subId: " + subId);
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700607 return;
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800608 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700609 String callingPackageName = mContext.getPackageManager().getNameForUid(
610 Binder.getCallingUid());
611 // TODO: Check that the calling packages is privileged for subId specifically.
612 int privilegeStatus = TelephonyManager.from(mContext).checkCarrierPrivilegesForPackage(
613 callingPackageName);
614 if (privilegeStatus != TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) {
615 throw new SecurityException(
616 "Package is not privileged for subId=" + subId + ": " + callingPackageName);
617 }
618
619 // This method should block until deleting has completed, so that an error which prevents us
620 // from clearing the cache is passed back to the carrier app. With the files successfully
621 // deleted, this can return and we will eventually bind to the carrier app.
622 deleteConfigForPackage(callingPackageName);
623 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800624 }
625
626 @Override
627 public void updateConfigForPhoneId(int phoneId, String simState) {
628 log("update config for phoneId: " + phoneId + " simState: " + simState);
629 if (!SubscriptionManager.isValidPhoneId(phoneId)) {
630 return;
631 }
632 // requires Java 7 for switch on string.
633 switch (simState) {
634 case IccCardConstants.INTENT_VALUE_ICC_ABSENT:
635 case IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR:
636 case IccCardConstants.INTENT_VALUE_ICC_UNKNOWN:
Junda Liu9f2d2712015-05-15 14:22:45 -0700637 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CLEAR_CONFIG, phoneId, -1));
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800638 break;
639 case IccCardConstants.INTENT_VALUE_ICC_LOADED:
640 case IccCardConstants.INTENT_VALUE_ICC_LOCKED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700641 updateConfigForPhoneId(phoneId);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800642 break;
643 }
644 }
645
Junda Liu43d723a2015-05-12 17:23:45 -0700646 @Override
647 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
648 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
649 != PackageManager.PERMISSION_GRANTED) {
650 pw.println("Permission Denial: can't dump carrierconfig from from pid="
651 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
652 return;
653 }
654 pw.println("CarrierConfigLoader: " + this);
655 for (int i = 0; i < TelephonyManager.getDefault().getPhoneCount(); i++) {
656 pw.println(" Phone Id=" + i);
657 pw.println(" mConfigFromDefaultApp=" + mConfigFromDefaultApp[i]);
658 pw.println(" mConfigFromCarrierApp=" + mConfigFromCarrierApp[i]);
659 }
660 }
661
Zach Johnson36d7aab2015-05-22 15:43:00 -0700662 private class CarrierServiceConnection implements ServiceConnection {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800663 int phoneId;
664 int eventId;
665 IBinder service;
666
Zach Johnson36d7aab2015-05-22 15:43:00 -0700667 public CarrierServiceConnection(int phoneId, int eventId) {
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800668 this.phoneId = phoneId;
669 this.eventId = eventId;
670 }
671
672 @Override
673 public void onServiceConnected(ComponentName name, IBinder service) {
674 log("Connected to config app: " + name.flattenToString());
675 this.service = service;
676 mHandler.sendMessage(mHandler.obtainMessage(eventId, phoneId, -1, this));
677 }
678
679 @Override
680 public void onServiceDisconnected(ComponentName name) {
681 this.service = null;
682 }
683 }
684
685 private class ConfigLoaderBroadcastReceiver extends BroadcastReceiver {
686 @Override
687 public void onReceive(Context context, Intent intent) {
688 String action = intent.getAction();
Junda Liu8a8a53a2015-05-15 16:19:57 -0700689 boolean replace = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
690 // If replace is true, only care ACTION_PACKAGE_REPLACED.
691 if (replace && !Intent.ACTION_PACKAGE_REPLACED.equals(action))
692 return;
693
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700694 switch (action) {
695 case Intent.ACTION_PACKAGE_ADDED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700696 case Intent.ACTION_PACKAGE_REMOVED:
Junda Liu8a8a53a2015-05-15 16:19:57 -0700697 case Intent.ACTION_PACKAGE_REPLACED:
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700698 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
699 String packageName = mContext.getPackageManager().getNameForUid(uid);
Junda Liu8a8a53a2015-05-15 16:19:57 -0700700 if (packageName != null) {
701 // We don't have a phoneId for arg1.
702 mHandler.sendMessage(
703 mHandler.obtainMessage(EVENT_PACKAGE_CHANGED, packageName));
704 }
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700705 break;
Jonathan Basseri1f743c92015-05-15 00:19:46 -0700706 }
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800707 }
708 }
709
710 private static void log(String msg) {
Jonathan Basseri6b50e9f2015-05-12 20:18:31 -0700711 Log.d(LOG_TAG, msg);
712 }
713
714 private static void loge(String msg) {
715 Log.e(LOG_TAG, msg);
Jonathan Basseri6465afd2015-02-25 13:05:57 -0800716 }
717}