blob: 387f139a51ce5e0508473418993948b834c29199 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 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
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Tom Taylord4a47292009-12-21 13:59:18 -080021import com.android.common.FastXmlSerializer;
22import com.android.common.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023
24import org.xmlpull.v1.XmlPullParser;
25import org.xmlpull.v1.XmlPullParserException;
26import org.xmlpull.v1.XmlSerializer;
27
28import android.app.ActivityManagerNative;
29import android.app.IActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070034import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080035import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070036import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.content.pm.ActivityInfo;
38import android.content.pm.ApplicationInfo;
39import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070040import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.pm.IPackageDataObserver;
42import android.content.pm.IPackageDeleteObserver;
43import android.content.pm.IPackageInstallObserver;
44import android.content.pm.IPackageManager;
45import android.content.pm.IPackageStatsObserver;
46import android.content.pm.InstrumentationInfo;
47import android.content.pm.PackageInfo;
48import android.content.pm.PackageManager;
49import android.content.pm.PackageStats;
50import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
51import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
52import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
53import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
54import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
55import android.content.pm.PackageParser;
56import android.content.pm.PermissionInfo;
57import android.content.pm.PermissionGroupInfo;
58import android.content.pm.ProviderInfo;
59import android.content.pm.ResolveInfo;
60import android.content.pm.ServiceInfo;
61import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.Uri;
63import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070064import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080066import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080068import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070069import android.os.Looper;
70import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Parcel;
72import android.os.RemoteException;
73import android.os.Environment;
74import android.os.FileObserver;
75import android.os.FileUtils;
76import android.os.Handler;
San Mehatbe16cb12010-01-29 05:35:35 -080077import android.os.MountServiceResultCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.os.ParcelFileDescriptor;
79import android.os.Process;
80import android.os.ServiceManager;
81import android.os.SystemClock;
82import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080083import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.util.*;
85import android.view.Display;
86import android.view.WindowManager;
87
88import java.io.File;
89import java.io.FileDescriptor;
90import java.io.FileInputStream;
91import java.io.FileNotFoundException;
92import java.io.FileOutputStream;
93import java.io.FileReader;
94import java.io.FilenameFilter;
95import java.io.IOException;
96import java.io.InputStream;
97import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -080098import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -080099import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import java.util.ArrayList;
101import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700102import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.util.Collections;
104import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800105import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.Enumeration;
107import java.util.HashMap;
108import java.util.HashSet;
109import java.util.Iterator;
110import java.util.List;
111import java.util.Map;
112import java.util.Set;
113import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800114import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import java.util.zip.ZipFile;
116import java.util.zip.ZipOutputStream;
117
118class PackageManagerService extends IPackageManager.Stub {
119 private static final String TAG = "PackageManager";
120 private static final boolean DEBUG_SETTINGS = false;
121 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800122 private static final boolean DEBUG_UPGRADE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
124 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
125 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400126 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 private static final int FIRST_APPLICATION_UID =
128 Process.FIRST_APPLICATION_UID;
129 private static final int MAX_APPLICATION_UIDS = 1000;
130
131 private static final boolean SHOW_INFO = false;
132
133 private static final boolean GET_CERTIFICATES = true;
134
Oscar Montemayora8529f62009-11-18 10:14:20 -0800135 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 private static final int REMOVE_EVENTS =
138 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
139 private static final int ADD_EVENTS =
140 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
141
142 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
143
144 static final int SCAN_MONITOR = 1<<0;
145 static final int SCAN_NO_DEX = 1<<1;
146 static final int SCAN_FORCE_DEX = 1<<2;
147 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800148 static final int SCAN_NEW_INSTALL = 1<<4;
149 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150
151 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
152 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700153 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
Dianne Hackborn851a5412009-05-08 12:06:44 -0700155 final int mSdkVersion = Build.VERSION.SDK_INT;
156 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
157 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 final Context mContext;
160 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700161 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 final DisplayMetrics mMetrics;
163 final int mDefParseFlags;
164 final String[] mSeparateProcesses;
165
166 // This is where all application persistent data goes.
167 final File mAppDataDir;
168
Oscar Montemayora8529f62009-11-18 10:14:20 -0800169 // If Encrypted File System feature is enabled, all application persistent data
170 // should go here instead.
171 final File mSecureAppDataDir;
172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 // This is the object monitoring the framework dir.
174 final FileObserver mFrameworkInstallObserver;
175
176 // This is the object monitoring the system app dir.
177 final FileObserver mSystemInstallObserver;
178
179 // This is the object monitoring mAppInstallDir.
180 final FileObserver mAppInstallObserver;
181
182 // This is the object monitoring mDrmAppPrivateInstallDir.
183 final FileObserver mDrmAppInstallObserver;
184
185 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
186 // LOCK HELD. Can be called with mInstallLock held.
187 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 final File mFrameworkDir;
190 final File mSystemAppDir;
191 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700192 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
194 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
195 // apps.
196 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 // Lock for state used when installing and doing other long running
201 // operations. Methods that must be called with this lock held have
202 // the prefix "LI".
203 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 // These are the directories in the 3rd party applications installed dir
206 // that we have currently loaded packages from. Keys are the application's
207 // installed zip file (absolute codePath), and values are Package.
208 final HashMap<String, PackageParser.Package> mAppDirs =
209 new HashMap<String, PackageParser.Package>();
210
211 // Information for the parser to write more useful error messages.
212 File mScanningPath;
213 int mLastScanError;
214
215 final int[] mOutPermissions = new int[3];
216
217 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 // Keys are String (package name), values are Package. This also serves
220 // as the lock for the global state. Methods that must be called with
221 // this lock held have the prefix "LP".
222 final HashMap<String, PackageParser.Package> mPackages =
223 new HashMap<String, PackageParser.Package>();
224
225 final Settings mSettings;
226 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227
228 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
229 int[] mGlobalGids;
230
231 // These are the built-in uid -> permission mappings that were read from the
232 // etc/permissions.xml file.
233 final SparseArray<HashSet<String>> mSystemPermissions =
234 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 // These are the built-in shared libraries that were read from the
237 // etc/permissions.xml file.
238 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800239
Dianne Hackborn49237342009-08-27 20:08:01 -0700240 // Temporary for building the final shared libraries for an .apk.
241 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800242
Dianne Hackborn49237342009-08-27 20:08:01 -0700243 // These are the features this devices supports that were read from the
244 // etc/permissions.xml file.
245 final HashMap<String, FeatureInfo> mAvailableFeatures =
246 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // All available activities, for your resolving pleasure.
249 final ActivityIntentResolver mActivities =
250 new ActivityIntentResolver();
251
252 // All available receivers, for your resolving pleasure.
253 final ActivityIntentResolver mReceivers =
254 new ActivityIntentResolver();
255
256 // All available services, for your resolving pleasure.
257 final ServiceIntentResolver mServices = new ServiceIntentResolver();
258
259 // Keys are String (provider class name), values are Provider.
260 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
261 new HashMap<ComponentName, PackageParser.Provider>();
262
263 // Mapping from provider base names (first directory in content URI codePath)
264 // to the provider information.
265 final HashMap<String, PackageParser.Provider> mProviders =
266 new HashMap<String, PackageParser.Provider>();
267
268 // Mapping from instrumentation class names to info about them.
269 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
270 new HashMap<ComponentName, PackageParser.Instrumentation>();
271
272 // Mapping from permission names to info about them.
273 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
274 new HashMap<String, PackageParser.PermissionGroup>();
275
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800276 // Packages whose data we have transfered into another package, thus
277 // should no longer exist.
278 final HashSet<String> mTransferedPackages = new HashSet<String>();
279
Dianne Hackborn854060af2009-07-09 18:14:31 -0700280 // Broadcast actions that are only available to the system.
281 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 boolean mSystemReady;
284 boolean mSafeMode;
285 boolean mHasSystemUidErrors;
286
287 ApplicationInfo mAndroidApplication;
288 final ActivityInfo mResolveActivity = new ActivityInfo();
289 final ResolveInfo mResolveInfo = new ResolveInfo();
290 ComponentName mResolveComponentName;
291 PackageParser.Package mPlatformPackage;
292
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700293 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800294 final HashMap<String, ArrayList<String>> mPendingBroadcasts
295 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700296 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800297 static final int MCS_BOUND = 3;
298 static final int END_COPY = 4;
299 static final int INIT_COPY = 5;
300 static final int MCS_UNBIND = 6;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700301 // Delay time in millisecs
302 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800303 private ServiceConnection mDefContainerConn = new ServiceConnection() {
304 public void onServiceConnected(ComponentName name, IBinder service) {
305 IMediaContainerService imcs =
306 IMediaContainerService.Stub.asInterface(service);
307 Message msg = mHandler.obtainMessage(MCS_BOUND, imcs);
308 mHandler.sendMessage(msg);
309 }
310
311 public void onServiceDisconnected(ComponentName name) {
312 }
313 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700314
315 class PackageHandler extends Handler {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800316 final ArrayList<InstallArgs> mPendingInstalls =
317 new ArrayList<InstallArgs>();
318 // Service Connection to remote media container service to copy
319 // package uri's from external media onto secure containers
320 // or internal storage.
321 private IMediaContainerService mContainerService = null;
322
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700323 PackageHandler(Looper looper) {
324 super(looper);
325 }
326 public void handleMessage(Message msg) {
327 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800328 case INIT_COPY: {
329 InstallArgs args = (InstallArgs) msg.obj;
330 args.createCopyFile();
331 Intent service = new Intent().setComponent(new ComponentName(
332 "com.android.defcontainer",
333 "com.android.defcontainer.DefaultContainerService"));
334 if (mContainerService != null) {
335 // No need to add to pending list. Use remote stub directly
336 handleStartCopy(args);
337 } else {
338 if (mContext.bindService(service, mDefContainerConn,
339 Context.BIND_AUTO_CREATE)) {
340 mPendingInstalls.add(args);
341 } else {
342 Log.e(TAG, "Failed to bind to media container service");
343 // Indicate install failure TODO add new error code
344 processPendingInstall(args,
345 PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800346 }
347 }
348 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800349 }
350 case MCS_BOUND: {
351 // Initialize mContainerService if needed.
352 if (msg.obj != null) {
353 mContainerService = (IMediaContainerService) msg.obj;
354 }
355 if (mPendingInstalls.size() > 0) {
356 InstallArgs args = mPendingInstalls.remove(0);
357 if (args != null) {
358 handleStartCopy(args);
359 }
360 }
361 break;
362 }
363 case MCS_UNBIND : {
364 if (mPendingInstalls.size() == 0) {
365 mContext.unbindService(mDefContainerConn);
366 mContainerService = null;
367 }
368 break;
369 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700370 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800371 String packages[];
372 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700373 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700374 int uids[];
375 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800376 if (mPendingBroadcasts == null) {
377 return;
378 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700379 size = mPendingBroadcasts.size();
380 if (size <= 0) {
381 // Nothing to be done. Just return
382 return;
383 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800384 packages = new String[size];
385 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700386 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800387 Iterator<HashMap.Entry<String, ArrayList<String>>>
388 it = mPendingBroadcasts.entrySet().iterator();
389 int i = 0;
390 while (it.hasNext() && i < size) {
391 HashMap.Entry<String, ArrayList<String>> ent = it.next();
392 packages[i] = ent.getKey();
393 components[i] = ent.getValue();
394 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700395 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800396 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700397 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800398 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700399 mPendingBroadcasts.clear();
400 }
401 // Send broadcasts
402 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800403 sendPackageChangedBroadcast(packages[i], true,
404 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700405 }
406 break;
407 }
408 }
409 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800410
411 // Utility method to initiate copying apk via media
412 // container service.
413 private void handleStartCopy(InstallArgs args) {
414 int ret = PackageManager.INSTALL_SUCCEEDED;
415 if (mContainerService == null) {
416 // Install error
417 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
418 } else {
419 ret = args.copyApk(mContainerService);
420 }
421 mHandler.sendEmptyMessage(MCS_UNBIND);
422 processPendingInstall(args, ret);
423 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700424 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800425
426 static boolean installOnSd(int flags) {
427 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
428 ((flags & PackageManager.INSTALL_ON_SDCARD) == 0)) {
429 return false;
430 }
431 return true;
432 }
433
434 static boolean isFwdLocked(int flags) {
435 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
436 return true;
437 }
438 return false;
439 }
440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 public static final IPackageManager main(Context context, boolean factoryTest) {
442 PackageManagerService m = new PackageManagerService(context, factoryTest);
443 ServiceManager.addService("package", m);
444 return m;
445 }
446
447 static String[] splitString(String str, char sep) {
448 int count = 1;
449 int i = 0;
450 while ((i=str.indexOf(sep, i)) >= 0) {
451 count++;
452 i++;
453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 String[] res = new String[count];
456 i=0;
457 count = 0;
458 int lastI=0;
459 while ((i=str.indexOf(sep, i)) >= 0) {
460 res[count] = str.substring(lastI, i);
461 count++;
462 i++;
463 lastI = i;
464 }
465 res[count] = str.substring(lastI, str.length());
466 return res;
467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800470 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 if (mSdkVersion <= 0) {
474 Log.w(TAG, "**** ro.build.version.sdk not set!");
475 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 mContext = context;
478 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700479 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 mMetrics = new DisplayMetrics();
481 mSettings = new Settings();
482 mSettings.addSharedUserLP("android.uid.system",
483 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
484 mSettings.addSharedUserLP("android.uid.phone",
485 MULTIPLE_APPLICATION_UIDS
486 ? RADIO_UID : FIRST_APPLICATION_UID,
487 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400488 mSettings.addSharedUserLP("android.uid.log",
489 MULTIPLE_APPLICATION_UIDS
490 ? LOG_UID : FIRST_APPLICATION_UID,
491 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492
493 String separateProcesses = SystemProperties.get("debug.separate_processes");
494 if (separateProcesses != null && separateProcesses.length() > 0) {
495 if ("*".equals(separateProcesses)) {
496 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
497 mSeparateProcesses = null;
498 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
499 } else {
500 mDefParseFlags = 0;
501 mSeparateProcesses = separateProcesses.split(",");
502 Log.w(TAG, "Running with debug.separate_processes: "
503 + separateProcesses);
504 }
505 } else {
506 mDefParseFlags = 0;
507 mSeparateProcesses = null;
508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 Installer installer = new Installer();
511 // Little hacky thing to check if installd is here, to determine
512 // whether we are running on the simulator and thus need to take
513 // care of building the /data file structure ourself.
514 // (apparently the sim now has a working installer)
515 if (installer.ping() && Process.supportsProcesses()) {
516 mInstaller = installer;
517 } else {
518 mInstaller = null;
519 }
520
521 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
522 Display d = wm.getDefaultDisplay();
523 d.getMetrics(mMetrics);
524
525 synchronized (mInstallLock) {
526 synchronized (mPackages) {
527 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700528 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 File dataDir = Environment.getDataDirectory();
531 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800532 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
534
535 if (mInstaller == null) {
536 // Make sure these dirs exist, when we are running in
537 // the simulator.
538 // Make a wide-open directory for random misc stuff.
539 File miscDir = new File(dataDir, "misc");
540 miscDir.mkdirs();
541 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800542 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 mDrmAppPrivateInstallDir.mkdirs();
544 }
545
546 readPermissions();
547
548 mRestoredSettings = mSettings.readLP();
549 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800550
551 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800553
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800554 // Set flag to monitor and not change apk file paths when
555 // scanning install directories.
556 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700557 if (mNoDexOpt) {
558 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800559 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700560 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700565 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700568 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 /**
571 * Out of paranoia, ensure that everything in the boot class
572 * path has been dexed.
573 */
574 String bootClassPath = System.getProperty("java.boot.class.path");
575 if (bootClassPath != null) {
576 String[] paths = splitString(bootClassPath, ':');
577 for (int i=0; i<paths.length; i++) {
578 try {
579 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
580 libFiles.add(paths[i]);
581 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700582 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 }
584 } catch (FileNotFoundException e) {
585 Log.w(TAG, "Boot class path not found: " + paths[i]);
586 } catch (IOException e) {
587 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
588 }
589 }
590 } else {
591 Log.w(TAG, "No BOOTCLASSPATH found!");
592 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 /**
595 * Also ensure all external libraries have had dexopt run on them.
596 */
597 if (mSharedLibraries.size() > 0) {
598 Iterator<String> libs = mSharedLibraries.values().iterator();
599 while (libs.hasNext()) {
600 String lib = libs.next();
601 try {
602 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
603 libFiles.add(lib);
604 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700605 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 }
607 } catch (FileNotFoundException e) {
608 Log.w(TAG, "Library not found: " + lib);
609 } catch (IOException e) {
610 Log.w(TAG, "Exception reading library: " + lib, e);
611 }
612 }
613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 // Gross hack for now: we know this file doesn't contain any
616 // code, so don't dexopt it to avoid the resulting log spew.
617 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 /**
620 * And there are a number of commands implemented in Java, which
621 * we currently need to do the dexopt on so that they can be
622 * run from a non-root shell.
623 */
624 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700625 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 for (int i=0; i<frameworkFiles.length; i++) {
627 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
628 String path = libPath.getPath();
629 // Skip the file if we alrady did it.
630 if (libFiles.contains(path)) {
631 continue;
632 }
633 // Skip the file if it is not a type we want to dexopt.
634 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
635 continue;
636 }
637 try {
638 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
639 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700640 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 }
642 } catch (FileNotFoundException e) {
643 Log.w(TAG, "Jar not found: " + path);
644 } catch (IOException e) {
645 Log.w(TAG, "Exception reading jar: " + path, e);
646 }
647 }
648 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800649
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700650 if (didDexOpt) {
651 // If we had to do a dexopt of one of the previous
652 // things, then something on the system has changed.
653 // Consider this significant, and wipe away all other
654 // existing dexopt files to ensure we don't leave any
655 // dangling around.
656 String[] files = mDalvikCacheDir.list();
657 if (files != null) {
658 for (int i=0; i<files.length; i++) {
659 String fn = files[i];
660 if (fn.startsWith("data@app@")
661 || fn.startsWith("data@app-private@")) {
662 Log.i(TAG, "Pruning dalvik file: " + fn);
663 (new File(mDalvikCacheDir, fn)).delete();
664 }
665 }
666 }
667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800669
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800670 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 mFrameworkInstallObserver = new AppDirObserver(
672 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
673 mFrameworkInstallObserver.startWatching();
674 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800675 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800676
677 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
679 mSystemInstallObserver = new AppDirObserver(
680 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
681 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800682 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800683
684 if (mInstaller != null) {
685 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
686 mInstaller.moveFiles();
687 }
688
689 // Prune any system packages that no longer exist.
690 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
691 while (psit.hasNext()) {
692 PackageSetting ps = psit.next();
693 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
694 && !mPackages.containsKey(ps.name)) {
695 psit.remove();
696 String msg = "System package " + ps.name
697 + " no longer exists; wiping its data";
698 reportSettingsProblem(Log.WARN, msg);
699 if (mInstaller != null) {
700 // XXX how to set useEncryptedFSDir for packages that
701 // are not encrypted?
702 mInstaller.remove(ps.name, true);
703 }
704 }
705 }
706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 mAppInstallDir = new File(dataDir, "app");
708 if (mInstaller == null) {
709 // Make sure these dirs exist, when we are running in
710 // the simulator.
711 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
712 }
713 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800714 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 //clean up list
716 for(int i = 0; i < deletePkgsList.size(); i++) {
717 //clean up here
718 cleanupInstallFailedPackage(deletePkgsList.get(i));
719 }
720 //delete tmp files
721 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800722
723 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 SystemClock.uptimeMillis());
725 mAppInstallObserver = new AppDirObserver(
726 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
727 mAppInstallObserver.startWatching();
728 scanDirLI(mAppInstallDir, 0, scanMode);
729
730 mDrmAppInstallObserver = new AppDirObserver(
731 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
732 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800733 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800735 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 SystemClock.uptimeMillis());
737 Log.i(TAG, "Time to scan packages: "
738 + ((SystemClock.uptimeMillis()-startTime)/1000f)
739 + " seconds");
740
741 updatePermissionsLP();
742
743 mSettings.writeLP();
744
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800745 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 // Now after opening every single application zip, make sure they
749 // are all flushed. Not really needed, but keeps things nice and
750 // tidy.
751 Runtime.getRuntime().gc();
752 } // synchronized (mPackages)
753 } // synchronized (mInstallLock)
754 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 @Override
757 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
758 throws RemoteException {
759 try {
760 return super.onTransact(code, data, reply, flags);
761 } catch (RuntimeException e) {
762 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
763 Log.e(TAG, "Package Manager Crash", e);
764 }
765 throw e;
766 }
767 }
768
Dianne Hackborne6620b22010-01-22 14:46:21 -0800769 void cleanupInstallFailedPackage(PackageSetting ps) {
770 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800772 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
773 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 if (retCode < 0) {
775 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800776 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 }
778 } else {
779 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800780 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 File dataDir = new File(pkg.applicationInfo.dataDir);
782 dataDir.delete();
783 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800784 if (ps.codePath != null) {
785 if (!ps.codePath.delete()) {
786 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
787 }
788 }
789 if (ps.resourcePath != null) {
790 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
791 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
792 }
793 }
794 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 }
796
797 void readPermissions() {
798 // Read permissions from .../etc/permission directory.
799 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
800 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
801 Log.w(TAG, "No directory " + libraryDir + ", skipping");
802 return;
803 }
804 if (!libraryDir.canRead()) {
805 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
806 return;
807 }
808
809 // Iterate over the files in the directory and scan .xml files
810 for (File f : libraryDir.listFiles()) {
811 // We'll read platform.xml last
812 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
813 continue;
814 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 if (!f.getPath().endsWith(".xml")) {
817 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
818 continue;
819 }
820 if (!f.canRead()) {
821 Log.w(TAG, "Permissions library file " + f + " cannot be read");
822 continue;
823 }
824
825 readPermissionsFromXml(f);
826 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
829 final File permFile = new File(Environment.getRootDirectory(),
830 "etc/permissions/platform.xml");
831 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800832
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700833 StringBuilder sb = new StringBuilder(128);
834 sb.append("Libs:");
835 Iterator<String> it = mSharedLibraries.keySet().iterator();
836 while (it.hasNext()) {
837 sb.append(' ');
838 String name = it.next();
839 sb.append(name);
840 sb.append(':');
841 sb.append(mSharedLibraries.get(name));
842 }
843 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800844
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700845 sb.setLength(0);
846 sb.append("Features:");
847 it = mAvailableFeatures.keySet().iterator();
848 while (it.hasNext()) {
849 sb.append(' ');
850 sb.append(it.next());
851 }
852 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800854
855 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 FileReader permReader = null;
857 try {
858 permReader = new FileReader(permFile);
859 } catch (FileNotFoundException e) {
860 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
861 return;
862 }
863
864 try {
865 XmlPullParser parser = Xml.newPullParser();
866 parser.setInput(permReader);
867
868 XmlUtils.beginDocument(parser, "permissions");
869
870 while (true) {
871 XmlUtils.nextElement(parser);
872 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
873 break;
874 }
875
876 String name = parser.getName();
877 if ("group".equals(name)) {
878 String gidStr = parser.getAttributeValue(null, "gid");
879 if (gidStr != null) {
880 int gid = Integer.parseInt(gidStr);
881 mGlobalGids = appendInt(mGlobalGids, gid);
882 } else {
883 Log.w(TAG, "<group> without gid at "
884 + parser.getPositionDescription());
885 }
886
887 XmlUtils.skipCurrentTag(parser);
888 continue;
889 } else if ("permission".equals(name)) {
890 String perm = parser.getAttributeValue(null, "name");
891 if (perm == null) {
892 Log.w(TAG, "<permission> without name at "
893 + parser.getPositionDescription());
894 XmlUtils.skipCurrentTag(parser);
895 continue;
896 }
897 perm = perm.intern();
898 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 } else if ("assign-permission".equals(name)) {
901 String perm = parser.getAttributeValue(null, "name");
902 if (perm == null) {
903 Log.w(TAG, "<assign-permission> without name at "
904 + parser.getPositionDescription());
905 XmlUtils.skipCurrentTag(parser);
906 continue;
907 }
908 String uidStr = parser.getAttributeValue(null, "uid");
909 if (uidStr == null) {
910 Log.w(TAG, "<assign-permission> without uid at "
911 + parser.getPositionDescription());
912 XmlUtils.skipCurrentTag(parser);
913 continue;
914 }
915 int uid = Process.getUidForName(uidStr);
916 if (uid < 0) {
917 Log.w(TAG, "<assign-permission> with unknown uid \""
918 + uidStr + "\" at "
919 + parser.getPositionDescription());
920 XmlUtils.skipCurrentTag(parser);
921 continue;
922 }
923 perm = perm.intern();
924 HashSet<String> perms = mSystemPermissions.get(uid);
925 if (perms == null) {
926 perms = new HashSet<String>();
927 mSystemPermissions.put(uid, perms);
928 }
929 perms.add(perm);
930 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 } else if ("library".equals(name)) {
933 String lname = parser.getAttributeValue(null, "name");
934 String lfile = parser.getAttributeValue(null, "file");
935 if (lname == null) {
936 Log.w(TAG, "<library> without name at "
937 + parser.getPositionDescription());
938 } else if (lfile == null) {
939 Log.w(TAG, "<library> without file at "
940 + parser.getPositionDescription());
941 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700942 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700943 mSharedLibraries.put(lname, lfile);
944 }
945 XmlUtils.skipCurrentTag(parser);
946 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800947
Dianne Hackborn49237342009-08-27 20:08:01 -0700948 } else if ("feature".equals(name)) {
949 String fname = parser.getAttributeValue(null, "name");
950 if (fname == null) {
951 Log.w(TAG, "<feature> without name at "
952 + parser.getPositionDescription());
953 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700954 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -0700955 FeatureInfo fi = new FeatureInfo();
956 fi.name = fname;
957 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 }
959 XmlUtils.skipCurrentTag(parser);
960 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 } else {
963 XmlUtils.skipCurrentTag(parser);
964 continue;
965 }
966
967 }
968 } catch (XmlPullParserException e) {
969 Log.w(TAG, "Got execption parsing permissions.", e);
970 } catch (IOException e) {
971 Log.w(TAG, "Got execption parsing permissions.", e);
972 }
973 }
974
975 void readPermission(XmlPullParser parser, String name)
976 throws IOException, XmlPullParserException {
977
978 name = name.intern();
979
980 BasePermission bp = mSettings.mPermissions.get(name);
981 if (bp == null) {
982 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
983 mSettings.mPermissions.put(name, bp);
984 }
985 int outerDepth = parser.getDepth();
986 int type;
987 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
988 && (type != XmlPullParser.END_TAG
989 || parser.getDepth() > outerDepth)) {
990 if (type == XmlPullParser.END_TAG
991 || type == XmlPullParser.TEXT) {
992 continue;
993 }
994
995 String tagName = parser.getName();
996 if ("group".equals(tagName)) {
997 String gidStr = parser.getAttributeValue(null, "gid");
998 if (gidStr != null) {
999 int gid = Process.getGidForName(gidStr);
1000 bp.gids = appendInt(bp.gids, gid);
1001 } else {
1002 Log.w(TAG, "<group> without gid at "
1003 + parser.getPositionDescription());
1004 }
1005 }
1006 XmlUtils.skipCurrentTag(parser);
1007 }
1008 }
1009
1010 static int[] appendInt(int[] cur, int val) {
1011 if (cur == null) {
1012 return new int[] { val };
1013 }
1014 final int N = cur.length;
1015 for (int i=0; i<N; i++) {
1016 if (cur[i] == val) {
1017 return cur;
1018 }
1019 }
1020 int[] ret = new int[N+1];
1021 System.arraycopy(cur, 0, ret, 0, N);
1022 ret[N] = val;
1023 return ret;
1024 }
1025
1026 static int[] appendInts(int[] cur, int[] add) {
1027 if (add == null) return cur;
1028 if (cur == null) return add;
1029 final int N = add.length;
1030 for (int i=0; i<N; i++) {
1031 cur = appendInt(cur, add[i]);
1032 }
1033 return cur;
1034 }
1035
1036 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001037 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1038 // The package has been uninstalled but has retained data and resources.
1039 return PackageParser.generatePackageInfo(p, null, flags);
1040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 final PackageSetting ps = (PackageSetting)p.mExtras;
1042 if (ps == null) {
1043 return null;
1044 }
1045 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1046 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1047 }
1048
1049 public PackageInfo getPackageInfo(String packageName, int flags) {
1050 synchronized (mPackages) {
1051 PackageParser.Package p = mPackages.get(packageName);
1052 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001053 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 + ": " + p);
1055 if (p != null) {
1056 return generatePackageInfo(p, flags);
1057 }
1058 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1059 return generatePackageInfoFromSettingsLP(packageName, flags);
1060 }
1061 }
1062 return null;
1063 }
1064
1065 public int getPackageUid(String packageName) {
1066 synchronized (mPackages) {
1067 PackageParser.Package p = mPackages.get(packageName);
1068 if(p != null) {
1069 return p.applicationInfo.uid;
1070 }
1071 PackageSetting ps = mSettings.mPackages.get(packageName);
1072 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1073 return -1;
1074 }
1075 p = ps.pkg;
1076 return p != null ? p.applicationInfo.uid : -1;
1077 }
1078 }
1079
1080 public int[] getPackageGids(String packageName) {
1081 synchronized (mPackages) {
1082 PackageParser.Package p = mPackages.get(packageName);
1083 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001084 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 + ": " + p);
1086 if (p != null) {
1087 final PackageSetting ps = (PackageSetting)p.mExtras;
1088 final SharedUserSetting suid = ps.sharedUser;
1089 return suid != null ? suid.gids : ps.gids;
1090 }
1091 }
1092 // stupid thing to indicate an error.
1093 return new int[0];
1094 }
1095
1096 public PermissionInfo getPermissionInfo(String name, int flags) {
1097 synchronized (mPackages) {
1098 final BasePermission p = mSettings.mPermissions.get(name);
1099 if (p != null && p.perm != null) {
1100 return PackageParser.generatePermissionInfo(p.perm, flags);
1101 }
1102 return null;
1103 }
1104 }
1105
1106 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1107 synchronized (mPackages) {
1108 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1109 for (BasePermission p : mSettings.mPermissions.values()) {
1110 if (group == null) {
1111 if (p.perm.info.group == null) {
1112 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1113 }
1114 } else {
1115 if (group.equals(p.perm.info.group)) {
1116 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1117 }
1118 }
1119 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 if (out.size() > 0) {
1122 return out;
1123 }
1124 return mPermissionGroups.containsKey(group) ? out : null;
1125 }
1126 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1129 synchronized (mPackages) {
1130 return PackageParser.generatePermissionGroupInfo(
1131 mPermissionGroups.get(name), flags);
1132 }
1133 }
1134
1135 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1136 synchronized (mPackages) {
1137 final int N = mPermissionGroups.size();
1138 ArrayList<PermissionGroupInfo> out
1139 = new ArrayList<PermissionGroupInfo>(N);
1140 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1141 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1142 }
1143 return out;
1144 }
1145 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1148 PackageSetting ps = mSettings.mPackages.get(packageName);
1149 if(ps != null) {
1150 if(ps.pkg == null) {
1151 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1152 if(pInfo != null) {
1153 return pInfo.applicationInfo;
1154 }
1155 return null;
1156 }
1157 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1158 }
1159 return null;
1160 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1163 PackageSetting ps = mSettings.mPackages.get(packageName);
1164 if(ps != null) {
1165 if(ps.pkg == null) {
1166 ps.pkg = new PackageParser.Package(packageName);
1167 ps.pkg.applicationInfo.packageName = packageName;
1168 }
1169 return generatePackageInfo(ps.pkg, flags);
1170 }
1171 return null;
1172 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1175 synchronized (mPackages) {
1176 PackageParser.Package p = mPackages.get(packageName);
1177 if (Config.LOGV) Log.v(
1178 TAG, "getApplicationInfo " + packageName
1179 + ": " + p);
1180 if (p != null) {
1181 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001182 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 }
1184 if ("android".equals(packageName)||"system".equals(packageName)) {
1185 return mAndroidApplication;
1186 }
1187 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1188 return generateApplicationInfoFromSettingsLP(packageName, flags);
1189 }
1190 }
1191 return null;
1192 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001193
1194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1196 mContext.enforceCallingOrSelfPermission(
1197 android.Manifest.permission.CLEAR_APP_CACHE, null);
1198 // Queue up an async operation since clearing cache may take a little while.
1199 mHandler.post(new Runnable() {
1200 public void run() {
1201 mHandler.removeCallbacks(this);
1202 int retCode = -1;
1203 if (mInstaller != null) {
1204 retCode = mInstaller.freeCache(freeStorageSize);
1205 if (retCode < 0) {
1206 Log.w(TAG, "Couldn't clear application caches");
1207 }
1208 } //end if mInstaller
1209 if (observer != null) {
1210 try {
1211 observer.onRemoveCompleted(null, (retCode >= 0));
1212 } catch (RemoteException e) {
1213 Log.w(TAG, "RemoveException when invoking call back");
1214 }
1215 }
1216 }
1217 });
1218 }
1219
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001220 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001221 mContext.enforceCallingOrSelfPermission(
1222 android.Manifest.permission.CLEAR_APP_CACHE, null);
1223 // Queue up an async operation since clearing cache may take a little while.
1224 mHandler.post(new Runnable() {
1225 public void run() {
1226 mHandler.removeCallbacks(this);
1227 int retCode = -1;
1228 if (mInstaller != null) {
1229 retCode = mInstaller.freeCache(freeStorageSize);
1230 if (retCode < 0) {
1231 Log.w(TAG, "Couldn't clear application caches");
1232 }
1233 }
1234 if(pi != null) {
1235 try {
1236 // Callback via pending intent
1237 int code = (retCode >= 0) ? 1 : 0;
1238 pi.sendIntent(null, code, null,
1239 null, null);
1240 } catch (SendIntentException e1) {
1241 Log.i(TAG, "Failed to send pending intent");
1242 }
1243 }
1244 }
1245 });
1246 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1249 synchronized (mPackages) {
1250 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001251
1252 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001254 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 }
1256 if (mResolveComponentName.equals(component)) {
1257 return mResolveActivity;
1258 }
1259 }
1260 return null;
1261 }
1262
1263 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1264 synchronized (mPackages) {
1265 PackageParser.Activity a = mReceivers.mActivities.get(component);
1266 if (Config.LOGV) Log.v(
1267 TAG, "getReceiverInfo " + component + ": " + a);
1268 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1269 return PackageParser.generateActivityInfo(a, flags);
1270 }
1271 }
1272 return null;
1273 }
1274
1275 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1276 synchronized (mPackages) {
1277 PackageParser.Service s = mServices.mServices.get(component);
1278 if (Config.LOGV) Log.v(
1279 TAG, "getServiceInfo " + component + ": " + s);
1280 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1281 return PackageParser.generateServiceInfo(s, flags);
1282 }
1283 }
1284 return null;
1285 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 public String[] getSystemSharedLibraryNames() {
1288 Set<String> libSet;
1289 synchronized (mPackages) {
1290 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001291 int size = libSet.size();
1292 if (size > 0) {
1293 String[] libs = new String[size];
1294 libSet.toArray(libs);
1295 return libs;
1296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001298 return null;
1299 }
1300
1301 public FeatureInfo[] getSystemAvailableFeatures() {
1302 Collection<FeatureInfo> featSet;
1303 synchronized (mPackages) {
1304 featSet = mAvailableFeatures.values();
1305 int size = featSet.size();
1306 if (size > 0) {
1307 FeatureInfo[] features = new FeatureInfo[size+1];
1308 featSet.toArray(features);
1309 FeatureInfo fi = new FeatureInfo();
1310 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1311 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1312 features[size] = fi;
1313 return features;
1314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
1316 return null;
1317 }
1318
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001319 public boolean hasSystemFeature(String name) {
1320 synchronized (mPackages) {
1321 return mAvailableFeatures.containsKey(name);
1322 }
1323 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 public int checkPermission(String permName, String pkgName) {
1326 synchronized (mPackages) {
1327 PackageParser.Package p = mPackages.get(pkgName);
1328 if (p != null && p.mExtras != null) {
1329 PackageSetting ps = (PackageSetting)p.mExtras;
1330 if (ps.sharedUser != null) {
1331 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1332 return PackageManager.PERMISSION_GRANTED;
1333 }
1334 } else if (ps.grantedPermissions.contains(permName)) {
1335 return PackageManager.PERMISSION_GRANTED;
1336 }
1337 }
1338 }
1339 return PackageManager.PERMISSION_DENIED;
1340 }
1341
1342 public int checkUidPermission(String permName, int uid) {
1343 synchronized (mPackages) {
1344 Object obj = mSettings.getUserIdLP(uid);
1345 if (obj != null) {
1346 if (obj instanceof SharedUserSetting) {
1347 SharedUserSetting sus = (SharedUserSetting)obj;
1348 if (sus.grantedPermissions.contains(permName)) {
1349 return PackageManager.PERMISSION_GRANTED;
1350 }
1351 } else if (obj instanceof PackageSetting) {
1352 PackageSetting ps = (PackageSetting)obj;
1353 if (ps.grantedPermissions.contains(permName)) {
1354 return PackageManager.PERMISSION_GRANTED;
1355 }
1356 }
1357 } else {
1358 HashSet<String> perms = mSystemPermissions.get(uid);
1359 if (perms != null && perms.contains(permName)) {
1360 return PackageManager.PERMISSION_GRANTED;
1361 }
1362 }
1363 }
1364 return PackageManager.PERMISSION_DENIED;
1365 }
1366
1367 private BasePermission findPermissionTreeLP(String permName) {
1368 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1369 if (permName.startsWith(bp.name) &&
1370 permName.length() > bp.name.length() &&
1371 permName.charAt(bp.name.length()) == '.') {
1372 return bp;
1373 }
1374 }
1375 return null;
1376 }
1377
1378 private BasePermission checkPermissionTreeLP(String permName) {
1379 if (permName != null) {
1380 BasePermission bp = findPermissionTreeLP(permName);
1381 if (bp != null) {
1382 if (bp.uid == Binder.getCallingUid()) {
1383 return bp;
1384 }
1385 throw new SecurityException("Calling uid "
1386 + Binder.getCallingUid()
1387 + " is not allowed to add to permission tree "
1388 + bp.name + " owned by uid " + bp.uid);
1389 }
1390 }
1391 throw new SecurityException("No permission tree found for " + permName);
1392 }
1393
1394 public boolean addPermission(PermissionInfo info) {
1395 synchronized (mPackages) {
1396 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1397 throw new SecurityException("Label must be specified in permission");
1398 }
1399 BasePermission tree = checkPermissionTreeLP(info.name);
1400 BasePermission bp = mSettings.mPermissions.get(info.name);
1401 boolean added = bp == null;
1402 if (added) {
1403 bp = new BasePermission(info.name, tree.sourcePackage,
1404 BasePermission.TYPE_DYNAMIC);
1405 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1406 throw new SecurityException(
1407 "Not allowed to modify non-dynamic permission "
1408 + info.name);
1409 }
1410 bp.perm = new PackageParser.Permission(tree.perm.owner,
1411 new PermissionInfo(info));
1412 bp.perm.info.packageName = tree.perm.info.packageName;
1413 bp.uid = tree.uid;
1414 if (added) {
1415 mSettings.mPermissions.put(info.name, bp);
1416 }
1417 mSettings.writeLP();
1418 return added;
1419 }
1420 }
1421
1422 public void removePermission(String name) {
1423 synchronized (mPackages) {
1424 checkPermissionTreeLP(name);
1425 BasePermission bp = mSettings.mPermissions.get(name);
1426 if (bp != null) {
1427 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1428 throw new SecurityException(
1429 "Not allowed to modify non-dynamic permission "
1430 + name);
1431 }
1432 mSettings.mPermissions.remove(name);
1433 mSettings.writeLP();
1434 }
1435 }
1436 }
1437
Dianne Hackborn854060af2009-07-09 18:14:31 -07001438 public boolean isProtectedBroadcast(String actionName) {
1439 synchronized (mPackages) {
1440 return mProtectedBroadcasts.contains(actionName);
1441 }
1442 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 public int checkSignatures(String pkg1, String pkg2) {
1445 synchronized (mPackages) {
1446 PackageParser.Package p1 = mPackages.get(pkg1);
1447 PackageParser.Package p2 = mPackages.get(pkg2);
1448 if (p1 == null || p1.mExtras == null
1449 || p2 == null || p2.mExtras == null) {
1450 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1451 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001452 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 }
1454 }
1455
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001456 public int checkUidSignatures(int uid1, int uid2) {
1457 synchronized (mPackages) {
1458 Signature[] s1;
1459 Signature[] s2;
1460 Object obj = mSettings.getUserIdLP(uid1);
1461 if (obj != null) {
1462 if (obj instanceof SharedUserSetting) {
1463 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1464 } else if (obj instanceof PackageSetting) {
1465 s1 = ((PackageSetting)obj).signatures.mSignatures;
1466 } else {
1467 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1468 }
1469 } else {
1470 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1471 }
1472 obj = mSettings.getUserIdLP(uid2);
1473 if (obj != null) {
1474 if (obj instanceof SharedUserSetting) {
1475 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1476 } else if (obj instanceof PackageSetting) {
1477 s2 = ((PackageSetting)obj).signatures.mSignatures;
1478 } else {
1479 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1480 }
1481 } else {
1482 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1483 }
1484 return checkSignaturesLP(s1, s2);
1485 }
1486 }
1487
1488 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1489 if (s1 == null) {
1490 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1492 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1493 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001494 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1496 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001497 final int N1 = s1.length;
1498 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 for (int i=0; i<N1; i++) {
1500 boolean match = false;
1501 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001502 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 match = true;
1504 break;
1505 }
1506 }
1507 if (!match) {
1508 return PackageManager.SIGNATURE_NO_MATCH;
1509 }
1510 }
1511 return PackageManager.SIGNATURE_MATCH;
1512 }
1513
1514 public String[] getPackagesForUid(int uid) {
1515 synchronized (mPackages) {
1516 Object obj = mSettings.getUserIdLP(uid);
1517 if (obj instanceof SharedUserSetting) {
1518 SharedUserSetting sus = (SharedUserSetting)obj;
1519 final int N = sus.packages.size();
1520 String[] res = new String[N];
1521 Iterator<PackageSetting> it = sus.packages.iterator();
1522 int i=0;
1523 while (it.hasNext()) {
1524 res[i++] = it.next().name;
1525 }
1526 return res;
1527 } else if (obj instanceof PackageSetting) {
1528 PackageSetting ps = (PackageSetting)obj;
1529 return new String[] { ps.name };
1530 }
1531 }
1532 return null;
1533 }
1534
1535 public String getNameForUid(int uid) {
1536 synchronized (mPackages) {
1537 Object obj = mSettings.getUserIdLP(uid);
1538 if (obj instanceof SharedUserSetting) {
1539 SharedUserSetting sus = (SharedUserSetting)obj;
1540 return sus.name + ":" + sus.userId;
1541 } else if (obj instanceof PackageSetting) {
1542 PackageSetting ps = (PackageSetting)obj;
1543 return ps.name;
1544 }
1545 }
1546 return null;
1547 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 public int getUidForSharedUser(String sharedUserName) {
1550 if(sharedUserName == null) {
1551 return -1;
1552 }
1553 synchronized (mPackages) {
1554 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1555 if(suid == null) {
1556 return -1;
1557 }
1558 return suid.userId;
1559 }
1560 }
1561
1562 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1563 int flags) {
1564 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001565 return chooseBestActivity(intent, resolvedType, flags, query);
1566 }
1567
Mihai Predaeae850c2009-05-13 10:13:48 +02001568 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1569 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 if (query != null) {
1571 final int N = query.size();
1572 if (N == 1) {
1573 return query.get(0);
1574 } else if (N > 1) {
1575 // If there is more than one activity with the same priority,
1576 // then let the user decide between them.
1577 ResolveInfo r0 = query.get(0);
1578 ResolveInfo r1 = query.get(1);
1579 if (false) {
1580 System.out.println(r0.activityInfo.name +
1581 "=" + r0.priority + " vs " +
1582 r1.activityInfo.name +
1583 "=" + r1.priority);
1584 }
1585 // If the first activity has a higher priority, or a different
1586 // default, then it is always desireable to pick it.
1587 if (r0.priority != r1.priority
1588 || r0.preferredOrder != r1.preferredOrder
1589 || r0.isDefault != r1.isDefault) {
1590 return query.get(0);
1591 }
1592 // If we have saved a preference for a preferred activity for
1593 // this Intent, use that.
1594 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1595 flags, query, r0.priority);
1596 if (ri != null) {
1597 return ri;
1598 }
1599 return mResolveInfo;
1600 }
1601 }
1602 return null;
1603 }
1604
1605 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1606 int flags, List<ResolveInfo> query, int priority) {
1607 synchronized (mPackages) {
1608 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1609 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001610 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1612 if (prefs != null && prefs.size() > 0) {
1613 // First figure out how good the original match set is.
1614 // We will only allow preferred activities that came
1615 // from the same match quality.
1616 int match = 0;
1617 final int N = query.size();
1618 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1619 for (int j=0; j<N; j++) {
1620 ResolveInfo ri = query.get(j);
1621 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1622 + ": 0x" + Integer.toHexString(match));
1623 if (ri.match > match) match = ri.match;
1624 }
1625 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1626 + Integer.toHexString(match));
1627 match &= IntentFilter.MATCH_CATEGORY_MASK;
1628 final int M = prefs.size();
1629 for (int i=0; i<M; i++) {
1630 PreferredActivity pa = prefs.get(i);
1631 if (pa.mMatch != match) {
1632 continue;
1633 }
1634 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1635 if (DEBUG_PREFERRED) {
1636 Log.v(TAG, "Got preferred activity:");
1637 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1638 }
1639 if (ai != null) {
1640 for (int j=0; j<N; j++) {
1641 ResolveInfo ri = query.get(j);
1642 if (!ri.activityInfo.applicationInfo.packageName
1643 .equals(ai.applicationInfo.packageName)) {
1644 continue;
1645 }
1646 if (!ri.activityInfo.name.equals(ai.name)) {
1647 continue;
1648 }
1649
1650 // Okay we found a previously set preferred app.
1651 // If the result set is different from when this
1652 // was created, we need to clear it and re-ask the
1653 // user their preference.
1654 if (!pa.sameSet(query, priority)) {
1655 Log.i(TAG, "Result set changed, dropping preferred activity for "
1656 + intent + " type " + resolvedType);
1657 mSettings.mPreferredActivities.removeFilter(pa);
1658 return null;
1659 }
1660
1661 // Yay!
1662 return ri;
1663 }
1664 }
1665 }
1666 }
1667 }
1668 return null;
1669 }
1670
1671 public List<ResolveInfo> queryIntentActivities(Intent intent,
1672 String resolvedType, int flags) {
1673 ComponentName comp = intent.getComponent();
1674 if (comp != null) {
1675 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1676 ActivityInfo ai = getActivityInfo(comp, flags);
1677 if (ai != null) {
1678 ResolveInfo ri = new ResolveInfo();
1679 ri.activityInfo = ai;
1680 list.add(ri);
1681 }
1682 return list;
1683 }
1684
1685 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001686 String pkgName = intent.getPackage();
1687 if (pkgName == null) {
1688 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1689 resolvedType, flags);
1690 }
1691 PackageParser.Package pkg = mPackages.get(pkgName);
1692 if (pkg != null) {
1693 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1694 resolvedType, flags, pkg.activities);
1695 }
1696 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 }
1698 }
1699
1700 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1701 Intent[] specifics, String[] specificTypes, Intent intent,
1702 String resolvedType, int flags) {
1703 final String resultsAction = intent.getAction();
1704
1705 List<ResolveInfo> results = queryIntentActivities(
1706 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1707 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1708
1709 int specificsPos = 0;
1710 int N;
1711
1712 // todo: note that the algorithm used here is O(N^2). This
1713 // isn't a problem in our current environment, but if we start running
1714 // into situations where we have more than 5 or 10 matches then this
1715 // should probably be changed to something smarter...
1716
1717 // First we go through and resolve each of the specific items
1718 // that were supplied, taking care of removing any corresponding
1719 // duplicate items in the generic resolve list.
1720 if (specifics != null) {
1721 for (int i=0; i<specifics.length; i++) {
1722 final Intent sintent = specifics[i];
1723 if (sintent == null) {
1724 continue;
1725 }
1726
1727 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1728 String action = sintent.getAction();
1729 if (resultsAction != null && resultsAction.equals(action)) {
1730 // If this action was explicitly requested, then don't
1731 // remove things that have it.
1732 action = null;
1733 }
1734 ComponentName comp = sintent.getComponent();
1735 ResolveInfo ri = null;
1736 ActivityInfo ai = null;
1737 if (comp == null) {
1738 ri = resolveIntent(
1739 sintent,
1740 specificTypes != null ? specificTypes[i] : null,
1741 flags);
1742 if (ri == null) {
1743 continue;
1744 }
1745 if (ri == mResolveInfo) {
1746 // ACK! Must do something better with this.
1747 }
1748 ai = ri.activityInfo;
1749 comp = new ComponentName(ai.applicationInfo.packageName,
1750 ai.name);
1751 } else {
1752 ai = getActivityInfo(comp, flags);
1753 if (ai == null) {
1754 continue;
1755 }
1756 }
1757
1758 // Look for any generic query activities that are duplicates
1759 // of this specific one, and remove them from the results.
1760 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1761 N = results.size();
1762 int j;
1763 for (j=specificsPos; j<N; j++) {
1764 ResolveInfo sri = results.get(j);
1765 if ((sri.activityInfo.name.equals(comp.getClassName())
1766 && sri.activityInfo.applicationInfo.packageName.equals(
1767 comp.getPackageName()))
1768 || (action != null && sri.filter.matchAction(action))) {
1769 results.remove(j);
1770 if (Config.LOGV) Log.v(
1771 TAG, "Removing duplicate item from " + j
1772 + " due to specific " + specificsPos);
1773 if (ri == null) {
1774 ri = sri;
1775 }
1776 j--;
1777 N--;
1778 }
1779 }
1780
1781 // Add this specific item to its proper place.
1782 if (ri == null) {
1783 ri = new ResolveInfo();
1784 ri.activityInfo = ai;
1785 }
1786 results.add(specificsPos, ri);
1787 ri.specificIndex = i;
1788 specificsPos++;
1789 }
1790 }
1791
1792 // Now we go through the remaining generic results and remove any
1793 // duplicate actions that are found here.
1794 N = results.size();
1795 for (int i=specificsPos; i<N-1; i++) {
1796 final ResolveInfo rii = results.get(i);
1797 if (rii.filter == null) {
1798 continue;
1799 }
1800
1801 // Iterate over all of the actions of this result's intent
1802 // filter... typically this should be just one.
1803 final Iterator<String> it = rii.filter.actionsIterator();
1804 if (it == null) {
1805 continue;
1806 }
1807 while (it.hasNext()) {
1808 final String action = it.next();
1809 if (resultsAction != null && resultsAction.equals(action)) {
1810 // If this action was explicitly requested, then don't
1811 // remove things that have it.
1812 continue;
1813 }
1814 for (int j=i+1; j<N; j++) {
1815 final ResolveInfo rij = results.get(j);
1816 if (rij.filter != null && rij.filter.hasAction(action)) {
1817 results.remove(j);
1818 if (Config.LOGV) Log.v(
1819 TAG, "Removing duplicate item from " + j
1820 + " due to action " + action + " at " + i);
1821 j--;
1822 N--;
1823 }
1824 }
1825 }
1826
1827 // If the caller didn't request filter information, drop it now
1828 // so we don't have to marshall/unmarshall it.
1829 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1830 rii.filter = null;
1831 }
1832 }
1833
1834 // Filter out the caller activity if so requested.
1835 if (caller != null) {
1836 N = results.size();
1837 for (int i=0; i<N; i++) {
1838 ActivityInfo ainfo = results.get(i).activityInfo;
1839 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1840 && caller.getClassName().equals(ainfo.name)) {
1841 results.remove(i);
1842 break;
1843 }
1844 }
1845 }
1846
1847 // If the caller didn't request filter information,
1848 // drop them now so we don't have to
1849 // marshall/unmarshall it.
1850 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1851 N = results.size();
1852 for (int i=0; i<N; i++) {
1853 results.get(i).filter = null;
1854 }
1855 }
1856
1857 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1858 return results;
1859 }
1860
1861 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1862 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001863 ComponentName comp = intent.getComponent();
1864 if (comp != null) {
1865 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1866 ActivityInfo ai = getReceiverInfo(comp, flags);
1867 if (ai != null) {
1868 ResolveInfo ri = new ResolveInfo();
1869 ri.activityInfo = ai;
1870 list.add(ri);
1871 }
1872 return list;
1873 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001876 String pkgName = intent.getPackage();
1877 if (pkgName == null) {
1878 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1879 resolvedType, flags);
1880 }
1881 PackageParser.Package pkg = mPackages.get(pkgName);
1882 if (pkg != null) {
1883 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1884 resolvedType, flags, pkg.receivers);
1885 }
1886 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 }
1888 }
1889
1890 public ResolveInfo resolveService(Intent intent, String resolvedType,
1891 int flags) {
1892 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1893 flags);
1894 if (query != null) {
1895 if (query.size() >= 1) {
1896 // If there is more than one service with the same priority,
1897 // just arbitrarily pick the first one.
1898 return query.get(0);
1899 }
1900 }
1901 return null;
1902 }
1903
1904 public List<ResolveInfo> queryIntentServices(Intent intent,
1905 String resolvedType, int flags) {
1906 ComponentName comp = intent.getComponent();
1907 if (comp != null) {
1908 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1909 ServiceInfo si = getServiceInfo(comp, flags);
1910 if (si != null) {
1911 ResolveInfo ri = new ResolveInfo();
1912 ri.serviceInfo = si;
1913 list.add(ri);
1914 }
1915 return list;
1916 }
1917
1918 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001919 String pkgName = intent.getPackage();
1920 if (pkgName == null) {
1921 return (List<ResolveInfo>)mServices.queryIntent(intent,
1922 resolvedType, flags);
1923 }
1924 PackageParser.Package pkg = mPackages.get(pkgName);
1925 if (pkg != null) {
1926 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1927 resolvedType, flags, pkg.services);
1928 }
1929 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 }
1931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 public List<PackageInfo> getInstalledPackages(int flags) {
1934 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1935
1936 synchronized (mPackages) {
1937 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1938 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1939 while (i.hasNext()) {
1940 final PackageSetting ps = i.next();
1941 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1942 if(psPkg != null) {
1943 finalList.add(psPkg);
1944 }
1945 }
1946 }
1947 else {
1948 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1949 while (i.hasNext()) {
1950 final PackageParser.Package p = i.next();
1951 if (p.applicationInfo != null) {
1952 PackageInfo pi = generatePackageInfo(p, flags);
1953 if(pi != null) {
1954 finalList.add(pi);
1955 }
1956 }
1957 }
1958 }
1959 }
1960 return finalList;
1961 }
1962
1963 public List<ApplicationInfo> getInstalledApplications(int flags) {
1964 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1965 synchronized(mPackages) {
1966 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1967 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1968 while (i.hasNext()) {
1969 final PackageSetting ps = i.next();
1970 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1971 if(ai != null) {
1972 finalList.add(ai);
1973 }
1974 }
1975 }
1976 else {
1977 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1978 while (i.hasNext()) {
1979 final PackageParser.Package p = i.next();
1980 if (p.applicationInfo != null) {
1981 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1982 if(ai != null) {
1983 finalList.add(ai);
1984 }
1985 }
1986 }
1987 }
1988 }
1989 return finalList;
1990 }
1991
1992 public List<ApplicationInfo> getPersistentApplications(int flags) {
1993 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1994
1995 synchronized (mPackages) {
1996 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1997 while (i.hasNext()) {
1998 PackageParser.Package p = i.next();
1999 if (p.applicationInfo != null
2000 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2001 && (!mSafeMode || (p.applicationInfo.flags
2002 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2003 finalList.add(p.applicationInfo);
2004 }
2005 }
2006 }
2007
2008 return finalList;
2009 }
2010
2011 public ProviderInfo resolveContentProvider(String name, int flags) {
2012 synchronized (mPackages) {
2013 final PackageParser.Provider provider = mProviders.get(name);
2014 return provider != null
2015 && mSettings.isEnabledLP(provider.info, flags)
2016 && (!mSafeMode || (provider.info.applicationInfo.flags
2017 &ApplicationInfo.FLAG_SYSTEM) != 0)
2018 ? PackageParser.generateProviderInfo(provider, flags)
2019 : null;
2020 }
2021 }
2022
Fred Quintana718d8a22009-04-29 17:53:20 -07002023 /**
2024 * @deprecated
2025 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 public void querySyncProviders(List outNames, List outInfo) {
2027 synchronized (mPackages) {
2028 Iterator<Map.Entry<String, PackageParser.Provider>> i
2029 = mProviders.entrySet().iterator();
2030
2031 while (i.hasNext()) {
2032 Map.Entry<String, PackageParser.Provider> entry = i.next();
2033 PackageParser.Provider p = entry.getValue();
2034
2035 if (p.syncable
2036 && (!mSafeMode || (p.info.applicationInfo.flags
2037 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2038 outNames.add(entry.getKey());
2039 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2040 }
2041 }
2042 }
2043 }
2044
2045 public List<ProviderInfo> queryContentProviders(String processName,
2046 int uid, int flags) {
2047 ArrayList<ProviderInfo> finalList = null;
2048
2049 synchronized (mPackages) {
2050 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2051 while (i.hasNext()) {
2052 PackageParser.Provider p = i.next();
2053 if (p.info.authority != null
2054 && (processName == null ||
2055 (p.info.processName.equals(processName)
2056 && p.info.applicationInfo.uid == uid))
2057 && mSettings.isEnabledLP(p.info, flags)
2058 && (!mSafeMode || (p.info.applicationInfo.flags
2059 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2060 if (finalList == null) {
2061 finalList = new ArrayList<ProviderInfo>(3);
2062 }
2063 finalList.add(PackageParser.generateProviderInfo(p,
2064 flags));
2065 }
2066 }
2067 }
2068
2069 if (finalList != null) {
2070 Collections.sort(finalList, mProviderInitOrderSorter);
2071 }
2072
2073 return finalList;
2074 }
2075
2076 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2077 int flags) {
2078 synchronized (mPackages) {
2079 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2080 return PackageParser.generateInstrumentationInfo(i, flags);
2081 }
2082 }
2083
2084 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2085 int flags) {
2086 ArrayList<InstrumentationInfo> finalList =
2087 new ArrayList<InstrumentationInfo>();
2088
2089 synchronized (mPackages) {
2090 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2091 while (i.hasNext()) {
2092 PackageParser.Instrumentation p = i.next();
2093 if (targetPackage == null
2094 || targetPackage.equals(p.info.targetPackage)) {
2095 finalList.add(PackageParser.generateInstrumentationInfo(p,
2096 flags));
2097 }
2098 }
2099 }
2100
2101 return finalList;
2102 }
2103
2104 private void scanDirLI(File dir, int flags, int scanMode) {
2105 Log.d(TAG, "Scanning app dir " + dir);
2106
2107 String[] files = dir.list();
2108
2109 int i;
2110 for (i=0; i<files.length; i++) {
2111 File file = new File(dir, files[i]);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002112 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
2114 }
2115 }
2116
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002117 private static File getSettingsProblemFile() {
2118 File dataDir = Environment.getDataDirectory();
2119 File systemDir = new File(dataDir, "system");
2120 File fname = new File(systemDir, "uiderrors.txt");
2121 return fname;
2122 }
2123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 private static void reportSettingsProblem(int priority, String msg) {
2125 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002126 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 FileOutputStream out = new FileOutputStream(fname, true);
2128 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002129 SimpleDateFormat formatter = new SimpleDateFormat();
2130 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2131 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 pw.close();
2133 FileUtils.setPermissions(
2134 fname.toString(),
2135 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2136 -1, -1);
2137 } catch (java.io.IOException e) {
2138 }
2139 Log.println(priority, TAG, msg);
2140 }
2141
2142 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2143 PackageParser.Package pkg, File srcFile, int parseFlags) {
2144 if (GET_CERTIFICATES) {
2145 if (ps == null || !ps.codePath.equals(srcFile)
2146 || ps.getTimeStamp() != srcFile.lastModified()) {
2147 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2148 if (!pp.collectCertificates(pkg, parseFlags)) {
2149 mLastScanError = pp.getParseError();
2150 return false;
2151 }
2152 }
2153 }
2154 return true;
2155 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 /*
2158 * Scan a package and return the newly parsed package.
2159 * Returns null in case of errors and the error code is stored in mLastScanError
2160 */
2161 private PackageParser.Package scanPackageLI(File scanFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002162 int parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 int scanMode) {
2164 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002165 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002167 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002170 scanPath,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002171 mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172 if (pkg == null) {
2173 mLastScanError = pp.getParseError();
2174 return null;
2175 }
2176 PackageSetting ps;
2177 PackageSetting updatedPkg;
2178 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002179 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
2181 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002182 // Verify certificates first
2183 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2184 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2185 return null;
2186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 if (updatedPkg != null) {
2188 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2189 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2190 }
2191 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2192 // Check for updated system applications here
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002193 if ((ps != null) && (!ps.codePath.equals(scanFile))) {
2194 if (pkg.mVersionCode < ps.versionCode) {
2195 // The system package has been updated and the code path does not match
2196 // Ignore entry. Just return
2197 Log.w(TAG, "Package:" + pkg.packageName +
2198 " has been updated. Ignoring the one from path:"+scanFile);
2199 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2200 return null;
2201 } else {
2202 // Delete the older apk pointed to by ps
2203 // At this point, its safely assumed that package installation for
2204 // apps in system partition will go through. If not there won't be a working
2205 // version of the app
2206 synchronized (mPackages) {
2207 // Just remove the loaded entries from package lists.
2208 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002209 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002210 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2211 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002212 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 }
2215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 // The apk is forward locked (not public) if its code and resources
2217 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002218 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002220 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002221 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002222
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002223 String codePath = null;
2224 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002225 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2226 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002227 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002228 } else {
2229 // Should not happen at all. Just log an error.
2230 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2231 }
2232 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002233 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002234 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002235 codePath = pkg.mScanPath;
2236 // Set application objects path explicitly.
2237 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002239 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 }
2241
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002242 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2243 String destCodePath, String destResPath) {
2244 pkg.mPath = pkg.mScanPath = destCodePath;
2245 pkg.applicationInfo.sourceDir = destCodePath;
2246 pkg.applicationInfo.publicSourceDir = destResPath;
2247 }
2248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 private static String fixProcessName(String defProcessName,
2250 String processName, int uid) {
2251 if (processName == null) {
2252 return defProcessName;
2253 }
2254 return processName;
2255 }
2256
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002257 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2259 if (pkg.mSignatures != null) {
2260 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2261 updateSignature)) {
2262 Log.e(TAG, "Package " + pkg.packageName
2263 + " signatures do not match the previously installed version; ignoring!");
2264 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2265 return false;
2266 }
2267
2268 if (pkgSetting.sharedUser != null) {
2269 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2270 pkg.mSignatures, updateSignature)) {
2271 Log.e(TAG, "Package " + pkg.packageName
2272 + " has no signatures that match those in shared user "
2273 + pkgSetting.sharedUser.name + "; ignoring!");
2274 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2275 return false;
2276 }
2277 }
2278 } else {
2279 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2280 }
2281 return true;
2282 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002283
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002284 public boolean performDexOpt(String packageName) {
2285 if (!mNoDexOpt) {
2286 return false;
2287 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002288
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002289 PackageParser.Package p;
2290 synchronized (mPackages) {
2291 p = mPackages.get(packageName);
2292 if (p == null || p.mDidDexOpt) {
2293 return false;
2294 }
2295 }
2296 synchronized (mInstallLock) {
2297 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2298 }
2299 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002300
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002301 static final int DEX_OPT_SKIPPED = 0;
2302 static final int DEX_OPT_PERFORMED = 1;
2303 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002304
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002305 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2306 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002307 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002308 String path = pkg.mScanPath;
2309 int ret = 0;
2310 try {
2311 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002312 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002313 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002314 pkg.mDidDexOpt = true;
2315 performed = true;
2316 }
2317 } catch (FileNotFoundException e) {
2318 Log.w(TAG, "Apk not found for dexopt: " + path);
2319 ret = -1;
2320 } catch (IOException e) {
2321 Log.w(TAG, "Exception reading apk: " + path, e);
2322 ret = -1;
2323 }
2324 if (ret < 0) {
2325 //error from installer
2326 return DEX_OPT_FAILED;
2327 }
2328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002329
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002330 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2331 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002332
2333 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2334 return Environment.isEncryptedFilesystemEnabled() &&
2335 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2336 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002337
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002338 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2339 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2340 Log.w(TAG, "Unable to update from " + oldPkg.name
2341 + " to " + newPkg.packageName
2342 + ": old package not in system partition");
2343 return false;
2344 } else if (mPackages.get(oldPkg.name) != null) {
2345 Log.w(TAG, "Unable to update from " + oldPkg.name
2346 + " to " + newPkg.packageName
2347 + ": old package still exists");
2348 return false;
2349 }
2350 return true;
2351 }
2352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 private PackageParser.Package scanPackageLI(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 PackageParser.Package pkg, int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002355 File scanFile = new File(pkg.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 mScanningPath = scanFile;
2357 if (pkg == null) {
2358 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2359 return null;
2360 }
2361
2362 final String pkgName = pkg.applicationInfo.packageName;
2363 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2364 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2365 }
2366
2367 if (pkgName.equals("android")) {
2368 synchronized (mPackages) {
2369 if (mAndroidApplication != null) {
2370 Log.w(TAG, "*************************************************");
2371 Log.w(TAG, "Core android package being redefined. Skipping.");
2372 Log.w(TAG, " file=" + mScanningPath);
2373 Log.w(TAG, "*************************************************");
2374 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2375 return null;
2376 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 // Set up information for our fall-back user intent resolution
2379 // activity.
2380 mPlatformPackage = pkg;
2381 pkg.mVersionCode = mSdkVersion;
2382 mAndroidApplication = pkg.applicationInfo;
2383 mResolveActivity.applicationInfo = mAndroidApplication;
2384 mResolveActivity.name = ResolverActivity.class.getName();
2385 mResolveActivity.packageName = mAndroidApplication.packageName;
2386 mResolveActivity.processName = mAndroidApplication.processName;
2387 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2388 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2389 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2390 mResolveActivity.exported = true;
2391 mResolveActivity.enabled = true;
2392 mResolveInfo.activityInfo = mResolveActivity;
2393 mResolveInfo.priority = 0;
2394 mResolveInfo.preferredOrder = 0;
2395 mResolveInfo.match = 0;
2396 mResolveComponentName = new ComponentName(
2397 mAndroidApplication.packageName, mResolveActivity.name);
2398 }
2399 }
2400
2401 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
2402 TAG, "Scanning package " + pkgName);
2403 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
2404 Log.w(TAG, "*************************************************");
2405 Log.w(TAG, "Application package " + pkgName
2406 + " already installed. Skipping duplicate.");
2407 Log.w(TAG, "*************************************************");
2408 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2409 return null;
2410 }
2411
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002412 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002413 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2414 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 SharedUserSetting suid = null;
2417 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 synchronized (mPackages) {
2422 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002423 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2424 if (mTmpSharedLibraries == null ||
2425 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2426 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2427 }
2428 int num = 0;
2429 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2430 for (int i=0; i<N; i++) {
2431 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 if (file == null) {
2433 Log.e(TAG, "Package " + pkg.packageName
2434 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002435 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2437 return null;
2438 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002439 mTmpSharedLibraries[num] = file;
2440 num++;
2441 }
2442 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2443 for (int i=0; i<N; i++) {
2444 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2445 if (file == null) {
2446 Log.w(TAG, "Package " + pkg.packageName
2447 + " desires unavailable shared library "
2448 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2449 } else {
2450 mTmpSharedLibraries[num] = file;
2451 num++;
2452 }
2453 }
2454 if (num > 0) {
2455 pkg.usesLibraryFiles = new String[num];
2456 System.arraycopy(mTmpSharedLibraries, 0,
2457 pkg.usesLibraryFiles, 0, num);
2458 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002459
Dianne Hackborn49237342009-08-27 20:08:01 -07002460 if (pkg.reqFeatures != null) {
2461 N = pkg.reqFeatures.size();
2462 for (int i=0; i<N; i++) {
2463 FeatureInfo fi = pkg.reqFeatures.get(i);
2464 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2465 // Don't care.
2466 continue;
2467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002468
Dianne Hackborn49237342009-08-27 20:08:01 -07002469 if (fi.name != null) {
2470 if (mAvailableFeatures.get(fi.name) == null) {
2471 Log.e(TAG, "Package " + pkg.packageName
2472 + " requires unavailable feature "
2473 + fi.name + "; failing!");
2474 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2475 return null;
2476 }
2477 }
2478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 }
2480 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 if (pkg.mSharedUserId != null) {
2483 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2484 pkg.applicationInfo.flags, true);
2485 if (suid == null) {
2486 Log.w(TAG, "Creating application package " + pkgName
2487 + " for shared user failed");
2488 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2489 return null;
2490 }
2491 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2492 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2493 + suid.userId + "): packages=" + suid.packages);
2494 }
2495 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002496
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002497 // Check if we are renaming from an original package name.
2498 PackageSetting origPackage = null;
2499 if (pkg.mOriginalPackage != null) {
2500 // We will only retrieve the setting for it if it already
2501 // exists; otherwise we need to make a new one later.
2502 origPackage = mSettings.peekPackageLP(pkg.mOriginalPackage);
2503 if (origPackage != null) {
2504 if (!verifyPackageUpdate(origPackage, pkg)) {
2505 origPackage = null;
2506 } else if (origPackage.sharedUser != null) {
2507 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2508 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2509 + " to " + pkg.packageName + ": old uid "
2510 + origPackage.sharedUser.name
2511 + " differs from " + pkg.mSharedUserId);
2512 origPackage = null;
2513 }
2514 } else {
2515 if (DEBUG_UPGRADE) Log.v(TAG, "Migrating data from "
2516 + origPackage.name + " to " + pkg.packageName);
2517 }
2518 }
2519 }
2520
2521 if (mTransferedPackages.contains(pkg.packageName)) {
2522 Log.w(TAG, "Package " + pkg.packageName
2523 + " was transferred to another, but its .apk remains");
2524 }
2525
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002526 // Just create the setting, don't add it yet. For already existing packages
2527 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002528 pkgSetting = mSettings.getPackageLP(pkg, origPackage, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 destResourceFile, pkg.applicationInfo.flags, true, false);
2530 if (pkgSetting == null) {
2531 Log.w(TAG, "Creating application package " + pkgName + " failed");
2532 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2533 return null;
2534 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002535 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2537 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 pkg.applicationInfo.uid = pkgSetting.userId;
2540 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002541
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002542 if (pkg.mAdoptPermissions != null) {
2543 // This package wants to adopt ownership of permissions from
2544 // another package.
2545 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2546 String origName = pkg.mAdoptPermissions.get(i);
2547 PackageSetting orig = mSettings.peekPackageLP(origName);
2548 if (orig != null) {
2549 if (verifyPackageUpdate(orig, pkg)) {
2550 if (DEBUG_UPGRADE) Log.v(TAG, "Adopting permissions from "
2551 + origName + " to " + pkg.packageName);
2552 mSettings.transferPermissions(origName, pkg.packageName);
2553 }
2554 }
2555 }
2556 }
2557
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002558 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2560 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2561 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2562 return null;
2563 }
2564 // The signature has changed, but this package is in the system
2565 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002566 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 // However... if this package is part of a shared user, but it
2568 // doesn't match the signature of the shared user, let's fail.
2569 // What this means is that you can't change the signatures
2570 // associated with an overall shared user, which doesn't seem all
2571 // that unreasonable.
2572 if (pkgSetting.sharedUser != null) {
2573 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2574 pkg.mSignatures, false)) {
2575 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2576 return null;
2577 }
2578 }
2579 removeExisting = true;
2580 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002581
The Android Open Source Project10592532009-03-18 17:39:46 -07002582 // Verify that this new package doesn't have any content providers
2583 // that conflict with existing packages. Only do this if the
2584 // package isn't already installed, since we don't want to break
2585 // things that are installed.
2586 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2587 int N = pkg.providers.size();
2588 int i;
2589 for (i=0; i<N; i++) {
2590 PackageParser.Provider p = pkg.providers.get(i);
2591 String names[] = p.info.authority.split(";");
2592 for (int j = 0; j < names.length; j++) {
2593 if (mProviders.containsKey(names[j])) {
2594 PackageParser.Provider other = mProviders.get(names[j]);
2595 Log.w(TAG, "Can't install because provider name " + names[j] +
2596 " (in package " + pkg.applicationInfo.packageName +
2597 ") is already used by "
2598 + ((other != null && other.component != null)
2599 ? other.component.getPackageName() : "?"));
2600 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2601 return null;
2602 }
2603 }
2604 }
2605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 }
2607
2608 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002609 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002611 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 if (ret != 0) {
2613 String msg = "System package " + pkg.packageName
2614 + " could not have data directory erased after signature change.";
2615 reportSettingsProblem(Log.WARN, msg);
2616 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2617 return null;
2618 }
2619 }
2620 Log.w(TAG, "System package " + pkg.packageName
2621 + " signature changed: existing data removed.");
2622 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 long scanFileTime = scanFile.lastModified();
2626 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2627 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2628 pkg.applicationInfo.processName = fixProcessName(
2629 pkg.applicationInfo.packageName,
2630 pkg.applicationInfo.processName,
2631 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632
2633 File dataPath;
2634 if (mPlatformPackage == pkg) {
2635 // The system package is special.
2636 dataPath = new File (Environment.getDataDirectory(), "system");
2637 pkg.applicationInfo.dataDir = dataPath.getPath();
2638 } else {
2639 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002640 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2641 if (useEncryptedFSDir) {
2642 dataPath = new File(mSecureAppDataDir, pkgName);
2643 } else {
2644 dataPath = new File(mAppDataDir, pkgName);
2645 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002646
2647 boolean uidError = false;
2648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 if (dataPath.exists()) {
2650 mOutPermissions[1] = 0;
2651 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2652 if (mOutPermissions[1] == pkg.applicationInfo.uid
2653 || !Process.supportsProcesses()) {
2654 pkg.applicationInfo.dataDir = dataPath.getPath();
2655 } else {
2656 boolean recovered = false;
2657 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2658 // If this is a system app, we can at least delete its
2659 // current data so the application will still work.
2660 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002661 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002662 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 // Old data gone!
2664 String msg = "System package " + pkg.packageName
2665 + " has changed from uid: "
2666 + mOutPermissions[1] + " to "
2667 + pkg.applicationInfo.uid + "; old data erased";
2668 reportSettingsProblem(Log.WARN, msg);
2669 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002672 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 pkg.applicationInfo.uid);
2674 if (ret == -1) {
2675 // Ack should not happen!
2676 msg = "System package " + pkg.packageName
2677 + " could not have data directory re-created after delete.";
2678 reportSettingsProblem(Log.WARN, msg);
2679 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2680 return null;
2681 }
2682 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 if (!recovered) {
2685 mHasSystemUidErrors = true;
2686 }
2687 }
2688 if (!recovered) {
2689 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2690 + pkg.applicationInfo.uid + "/fs_"
2691 + mOutPermissions[1];
2692 String msg = "Package " + pkg.packageName
2693 + " has mismatched uid: "
2694 + mOutPermissions[1] + " on disk, "
2695 + pkg.applicationInfo.uid + " in settings";
2696 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002697 mSettings.mReadMessages.append(msg);
2698 mSettings.mReadMessages.append('\n');
2699 uidError = true;
2700 if (!pkgSetting.uidError) {
2701 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 }
2704 }
2705 }
2706 pkg.applicationInfo.dataDir = dataPath.getPath();
2707 } else {
2708 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2709 Log.v(TAG, "Want this data dir: " + dataPath);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002710 if (pkgSetting.origPackage != null) {
2711 synchronized (mPackages) {
2712 // This package is being update from another; rename the
2713 // old one's data dir.
2714 String msg = "Transfering data from old package "
2715 + pkgSetting.origPackage.name + " to new package "
2716 + pkgSetting.name;
2717 reportSettingsProblem(Log.WARN, msg);
2718 if (mInstaller != null) {
2719 int ret = mInstaller.rename(pkgSetting.origPackage.name,
2720 pkgName, useEncryptedFSDir);
2721 if(ret < 0) {
2722 msg = "Error transfering data from old package "
2723 + pkgSetting.origPackage.name + " to new package "
2724 + pkgSetting.name;
2725 reportSettingsProblem(Log.WARN, msg);
2726 }
2727 }
2728 // And now uninstall the old package.
2729 mInstaller.remove(pkgSetting.origPackage.name, useEncryptedFSDir);
2730 mSettings.removePackageLP(pkgSetting.origPackage.name);
2731 }
2732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 //invoke installer to do the actual installation
2734 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002735 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 pkg.applicationInfo.uid);
2737 if(ret < 0) {
2738 // Error from installer
2739 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2740 return null;
2741 }
2742 } else {
2743 dataPath.mkdirs();
2744 if (dataPath.exists()) {
2745 FileUtils.setPermissions(
2746 dataPath.toString(),
2747 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2748 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2749 }
2750 }
2751 if (dataPath.exists()) {
2752 pkg.applicationInfo.dataDir = dataPath.getPath();
2753 } else {
2754 Log.w(TAG, "Unable to create data directory: " + dataPath);
2755 pkg.applicationInfo.dataDir = null;
2756 }
2757 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002758
2759 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 }
2761
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002762 // No longer need to retain this.
2763 if (pkgSetting.origPackage != null) {
2764 mTransferedPackages.add(pkgSetting.origPackage.name);
2765 pkgSetting.origPackage = null;
2766 }
2767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 // Perform shared library installation and dex validation and
2769 // optimization, if this is not a system app.
2770 if (mInstaller != null) {
2771 String path = scanFile.getPath();
2772 if (scanFileNewer) {
2773 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002774 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2775 if (err != PackageManager.INSTALL_SUCCEEDED) {
2776 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 return null;
2778 }
2779 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002780 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002781
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002782 if ((scanMode&SCAN_NO_DEX) == 0) {
2783 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2785 return null;
2786 }
2787 }
2788 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 if (mFactoryTest && pkg.requestedPermissions.contains(
2791 android.Manifest.permission.FACTORY_TEST)) {
2792 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2793 }
2794
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002795 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 if ((scanMode&SCAN_MONITOR) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 mAppDirs.put(pkg.mPath, pkg);
2798 }
2799
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002800 // Request the ActivityManager to kill the process(only for existing packages)
2801 // so that we do not end up in a confused state while the user is still using the older
2802 // version of the application while the new one gets installed.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002803 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING ) != 0) {
2804 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002805 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002806 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002810 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002812 mPackages.put(pkg.applicationInfo.packageName, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 int N = pkg.providers.size();
2814 StringBuilder r = null;
2815 int i;
2816 for (i=0; i<N; i++) {
2817 PackageParser.Provider p = pkg.providers.get(i);
2818 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2819 p.info.processName, pkg.applicationInfo.uid);
2820 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2821 p.info.name), p);
2822 p.syncable = p.info.isSyncable;
2823 String names[] = p.info.authority.split(";");
2824 p.info.authority = null;
2825 for (int j = 0; j < names.length; j++) {
2826 if (j == 1 && p.syncable) {
2827 // We only want the first authority for a provider to possibly be
2828 // syncable, so if we already added this provider using a different
2829 // authority clear the syncable flag. We copy the provider before
2830 // changing it because the mProviders object contains a reference
2831 // to a provider that we don't want to change.
2832 // Only do this for the second authority since the resulting provider
2833 // object can be the same for all future authorities for this provider.
2834 p = new PackageParser.Provider(p);
2835 p.syncable = false;
2836 }
2837 if (!mProviders.containsKey(names[j])) {
2838 mProviders.put(names[j], p);
2839 if (p.info.authority == null) {
2840 p.info.authority = names[j];
2841 } else {
2842 p.info.authority = p.info.authority + ";" + names[j];
2843 }
2844 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2845 Log.d(TAG, "Registered content provider: " + names[j] +
2846 ", className = " + p.info.name +
2847 ", isSyncable = " + p.info.isSyncable);
2848 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002849 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 Log.w(TAG, "Skipping provider name " + names[j] +
2851 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002852 "): name already used by "
2853 + ((other != null && other.component != null)
2854 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 }
2856 }
2857 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2858 if (r == null) {
2859 r = new StringBuilder(256);
2860 } else {
2861 r.append(' ');
2862 }
2863 r.append(p.info.name);
2864 }
2865 }
2866 if (r != null) {
2867 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2868 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 N = pkg.services.size();
2871 r = null;
2872 for (i=0; i<N; i++) {
2873 PackageParser.Service s = pkg.services.get(i);
2874 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2875 s.info.processName, pkg.applicationInfo.uid);
2876 mServices.addService(s);
2877 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2878 if (r == null) {
2879 r = new StringBuilder(256);
2880 } else {
2881 r.append(' ');
2882 }
2883 r.append(s.info.name);
2884 }
2885 }
2886 if (r != null) {
2887 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 N = pkg.receivers.size();
2891 r = null;
2892 for (i=0; i<N; i++) {
2893 PackageParser.Activity a = pkg.receivers.get(i);
2894 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2895 a.info.processName, pkg.applicationInfo.uid);
2896 mReceivers.addActivity(a, "receiver");
2897 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2898 if (r == null) {
2899 r = new StringBuilder(256);
2900 } else {
2901 r.append(' ');
2902 }
2903 r.append(a.info.name);
2904 }
2905 }
2906 if (r != null) {
2907 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 N = pkg.activities.size();
2911 r = null;
2912 for (i=0; i<N; i++) {
2913 PackageParser.Activity a = pkg.activities.get(i);
2914 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2915 a.info.processName, pkg.applicationInfo.uid);
2916 mActivities.addActivity(a, "activity");
2917 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2918 if (r == null) {
2919 r = new StringBuilder(256);
2920 } else {
2921 r.append(' ');
2922 }
2923 r.append(a.info.name);
2924 }
2925 }
2926 if (r != null) {
2927 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 N = pkg.permissionGroups.size();
2931 r = null;
2932 for (i=0; i<N; i++) {
2933 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2934 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2935 if (cur == null) {
2936 mPermissionGroups.put(pg.info.name, pg);
2937 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2938 if (r == null) {
2939 r = new StringBuilder(256);
2940 } else {
2941 r.append(' ');
2942 }
2943 r.append(pg.info.name);
2944 }
2945 } else {
2946 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2947 + pg.info.packageName + " ignored: original from "
2948 + cur.info.packageName);
2949 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2950 if (r == null) {
2951 r = new StringBuilder(256);
2952 } else {
2953 r.append(' ');
2954 }
2955 r.append("DUP:");
2956 r.append(pg.info.name);
2957 }
2958 }
2959 }
2960 if (r != null) {
2961 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2962 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 N = pkg.permissions.size();
2965 r = null;
2966 for (i=0; i<N; i++) {
2967 PackageParser.Permission p = pkg.permissions.get(i);
2968 HashMap<String, BasePermission> permissionMap =
2969 p.tree ? mSettings.mPermissionTrees
2970 : mSettings.mPermissions;
2971 p.group = mPermissionGroups.get(p.info.group);
2972 if (p.info.group == null || p.group != null) {
2973 BasePermission bp = permissionMap.get(p.info.name);
2974 if (bp == null) {
2975 bp = new BasePermission(p.info.name, p.info.packageName,
2976 BasePermission.TYPE_NORMAL);
2977 permissionMap.put(p.info.name, bp);
2978 }
2979 if (bp.perm == null) {
2980 if (bp.sourcePackage == null
2981 || bp.sourcePackage.equals(p.info.packageName)) {
2982 BasePermission tree = findPermissionTreeLP(p.info.name);
2983 if (tree == null
2984 || tree.sourcePackage.equals(p.info.packageName)) {
2985 bp.perm = p;
2986 bp.uid = pkg.applicationInfo.uid;
2987 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2988 if (r == null) {
2989 r = new StringBuilder(256);
2990 } else {
2991 r.append(' ');
2992 }
2993 r.append(p.info.name);
2994 }
2995 } else {
2996 Log.w(TAG, "Permission " + p.info.name + " from package "
2997 + p.info.packageName + " ignored: base tree "
2998 + tree.name + " is from package "
2999 + tree.sourcePackage);
3000 }
3001 } else {
3002 Log.w(TAG, "Permission " + p.info.name + " from package "
3003 + p.info.packageName + " ignored: original from "
3004 + bp.sourcePackage);
3005 }
3006 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3007 if (r == null) {
3008 r = new StringBuilder(256);
3009 } else {
3010 r.append(' ');
3011 }
3012 r.append("DUP:");
3013 r.append(p.info.name);
3014 }
3015 } else {
3016 Log.w(TAG, "Permission " + p.info.name + " from package "
3017 + p.info.packageName + " ignored: no group "
3018 + p.group);
3019 }
3020 }
3021 if (r != null) {
3022 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3023 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 N = pkg.instrumentation.size();
3026 r = null;
3027 for (i=0; i<N; i++) {
3028 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3029 a.info.packageName = pkg.applicationInfo.packageName;
3030 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3031 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3032 a.info.dataDir = pkg.applicationInfo.dataDir;
3033 mInstrumentation.put(a.component, a);
3034 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3035 if (r == null) {
3036 r = new StringBuilder(256);
3037 } else {
3038 r.append(' ');
3039 }
3040 r.append(a.info.name);
3041 }
3042 }
3043 if (r != null) {
3044 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3045 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003046
Dianne Hackborn854060af2009-07-09 18:14:31 -07003047 if (pkg.protectedBroadcasts != null) {
3048 N = pkg.protectedBroadcasts.size();
3049 for (i=0; i<N; i++) {
3050 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3051 }
3052 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 pkgSetting.setTimeStamp(scanFileTime);
3055 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 return pkg;
3058 }
3059
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003060 private void killApplication(String pkgName, int uid) {
3061 // Request the ActivityManager to kill the process(only for existing packages)
3062 // so that we do not end up in a confused state while the user is still using the older
3063 // version of the application while the new one gets installed.
3064 IActivityManager am = ActivityManagerNative.getDefault();
3065 if (am != null) {
3066 try {
3067 am.killApplicationWithUid(pkgName, uid);
3068 } catch (RemoteException e) {
3069 }
3070 }
3071 }
3072
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003073 // The following constants are returned by cachePackageSharedLibsForAbiLI
3074 // to indicate if native shared libraries were found in the package.
3075 // Values are:
3076 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3077 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3078 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3079 // in package (and not installed)
3080 //
3081 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3082 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3083 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003085 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3086 // and automatically copy them to /data/data/<appname>/lib if present.
3087 //
3088 // NOTE: this method may throw an IOException if the library cannot
3089 // be copied to its final destination, e.g. if there isn't enough
3090 // room left on the data partition, or a ZipException if the package
3091 // file is malformed.
3092 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003093 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3094 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003095 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3096 final String apkLib = "lib/";
3097 final int apkLibLen = apkLib.length();
3098 final int cpuAbiLen = cpuAbi.length();
3099 final String libPrefix = "lib";
3100 final int libPrefixLen = libPrefix.length();
3101 final String libSuffix = ".so";
3102 final int libSuffixLen = libSuffix.length();
3103 boolean hasNativeLibraries = false;
3104 boolean installedNativeLibraries = false;
3105
3106 // the minimum length of a valid native shared library of the form
3107 // lib/<something>/lib<name>.so.
3108 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3109
3110 ZipFile zipFile = new ZipFile(scanFile);
3111 Enumeration<ZipEntry> entries =
3112 (Enumeration<ZipEntry>) zipFile.entries();
3113
3114 while (entries.hasMoreElements()) {
3115 ZipEntry entry = entries.nextElement();
3116 // skip directories
3117 if (entry.isDirectory()) {
3118 continue;
3119 }
3120 String entryName = entry.getName();
3121
3122 // check that the entry looks like lib/<something>/lib<name>.so
3123 // here, but don't check the ABI just yet.
3124 //
3125 // - must be sufficiently long
3126 // - must end with libSuffix, i.e. ".so"
3127 // - must start with apkLib, i.e. "lib/"
3128 if (entryName.length() < minEntryLen ||
3129 !entryName.endsWith(libSuffix) ||
3130 !entryName.startsWith(apkLib) ) {
3131 continue;
3132 }
3133
3134 // file name must start with libPrefix, i.e. "lib"
3135 int lastSlash = entryName.lastIndexOf('/');
3136
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003137 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003138 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3139 continue;
3140 }
3141
3142 hasNativeLibraries = true;
3143
3144 // check the cpuAbi now, between lib/ and /lib<name>.so
3145 //
3146 if (lastSlash != apkLibLen + cpuAbiLen ||
3147 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3148 continue;
3149
3150 // extract the library file name, ensure it doesn't contain
3151 // weird characters. we're guaranteed here that it doesn't contain
3152 // a directory separator though.
3153 String libFileName = entryName.substring(lastSlash+1);
3154 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3155 continue;
3156 }
3157
3158 installedNativeLibraries = true;
3159
3160 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3161 File.separator + libFileName;
3162 File sharedLibraryFile = new File(sharedLibraryFilePath);
3163 if (! sharedLibraryFile.exists() ||
3164 sharedLibraryFile.length() != entry.getSize() ||
3165 sharedLibraryFile.lastModified() != entry.getTime()) {
3166 if (Config.LOGD) {
3167 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003169 if (mInstaller == null) {
3170 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003171 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003172 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003173 sharedLibraryFile);
3174 }
3175 }
3176 if (!hasNativeLibraries)
3177 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3178
3179 if (!installedNativeLibraries)
3180 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3181
3182 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3183 }
3184
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003185 // Find the gdbserver executable program in a package at
3186 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3187 //
3188 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3189 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3190 //
3191 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3192 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3193 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3194 final String GDBSERVER = "gdbserver";
3195 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3196
3197 ZipFile zipFile = new ZipFile(scanFile);
3198 Enumeration<ZipEntry> entries =
3199 (Enumeration<ZipEntry>) zipFile.entries();
3200
3201 while (entries.hasMoreElements()) {
3202 ZipEntry entry = entries.nextElement();
3203 // skip directories
3204 if (entry.isDirectory()) {
3205 continue;
3206 }
3207 String entryName = entry.getName();
3208
3209 if (!entryName.equals(apkGdbServerPath)) {
3210 continue;
3211 }
3212
3213 String installGdbServerPath = installGdbServerDir.getPath() +
3214 "/" + GDBSERVER;
3215 File installGdbServerFile = new File(installGdbServerPath);
3216 if (! installGdbServerFile.exists() ||
3217 installGdbServerFile.length() != entry.getSize() ||
3218 installGdbServerFile.lastModified() != entry.getTime()) {
3219 if (Config.LOGD) {
3220 Log.d(TAG, "Caching gdbserver " + entry.getName());
3221 }
3222 if (mInstaller == null) {
3223 installGdbServerDir.mkdir();
3224 }
3225 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3226 installGdbServerFile);
3227 }
3228 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3229 }
3230 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3231 }
3232
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003233 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3234 // and copy them to /data/data/<appname>/lib.
3235 //
3236 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3237 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3238 // one if ro.product.cpu.abi2 is defined.
3239 //
3240 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3241 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003242 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003243 try {
3244 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3245
3246 // some architectures are capable of supporting several CPU ABIs
3247 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3248 // this is indicated by the definition of the ro.product.cpu.abi2
3249 // system property.
3250 //
3251 // only scan the package twice in case of ABI mismatch
3252 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003253 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003254 if (cpuAbi2 != null) {
3255 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003257
3258 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3259 Log.w(TAG,"Native ABI mismatch from package file");
3260 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003262
3263 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3264 cpuAbi = cpuAbi2;
3265 }
3266 }
3267
3268 // for debuggable packages, also extract gdbserver from lib/<abi>
3269 // into /data/data/<appname>/lib too.
3270 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3271 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3272 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3273 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3274 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003277 } catch (ZipException e) {
3278 Log.w(TAG, "Failed to extract data from package file", e);
3279 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003281 Log.w(TAG, "Failed to cache package shared libs", e);
3282 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003284 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 }
3286
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003287 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003289 File binaryDir,
3290 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 InputStream inputStream = zipFile.getInputStream(entry);
3292 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003293 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003295 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 // now need to be left as world readable and owned by the system.
3297 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3298 ! tempFile.setLastModified(entry.getTime()) ||
3299 FileUtils.setPermissions(tempFilePath,
3300 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003301 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003302 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003303 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 // Failed to properly write file.
3305 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003306 throw new IOException("Couldn't create cached binary "
3307 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 }
3309 } finally {
3310 inputStream.close();
3311 }
3312 }
3313
3314 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3315 if (chatty && Config.LOGD) Log.d(
3316 TAG, "Removing package " + pkg.applicationInfo.packageName );
3317
3318 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 mPackages.remove(pkg.applicationInfo.packageName);
3322 if (pkg.mPath != null) {
3323 mAppDirs.remove(pkg.mPath);
3324 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 PackageSetting ps = (PackageSetting)pkg.mExtras;
3327 if (ps != null && ps.sharedUser != null) {
3328 // XXX don't do this until the data is removed.
3329 if (false) {
3330 ps.sharedUser.packages.remove(ps);
3331 if (ps.sharedUser.packages.size() == 0) {
3332 // Remove.
3333 }
3334 }
3335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 int N = pkg.providers.size();
3338 StringBuilder r = null;
3339 int i;
3340 for (i=0; i<N; i++) {
3341 PackageParser.Provider p = pkg.providers.get(i);
3342 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3343 p.info.name));
3344 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 /* The is another ContentProvider with this authority when
3347 * this app was installed so this authority is null,
3348 * Ignore it as we don't have to unregister the provider.
3349 */
3350 continue;
3351 }
3352 String names[] = p.info.authority.split(";");
3353 for (int j = 0; j < names.length; j++) {
3354 if (mProviders.get(names[j]) == p) {
3355 mProviders.remove(names[j]);
3356 if (chatty && Config.LOGD) Log.d(
3357 TAG, "Unregistered content provider: " + names[j] +
3358 ", className = " + p.info.name +
3359 ", isSyncable = " + p.info.isSyncable);
3360 }
3361 }
3362 if (chatty) {
3363 if (r == null) {
3364 r = new StringBuilder(256);
3365 } else {
3366 r.append(' ');
3367 }
3368 r.append(p.info.name);
3369 }
3370 }
3371 if (r != null) {
3372 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3373 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 N = pkg.services.size();
3376 r = null;
3377 for (i=0; i<N; i++) {
3378 PackageParser.Service s = pkg.services.get(i);
3379 mServices.removeService(s);
3380 if (chatty) {
3381 if (r == null) {
3382 r = new StringBuilder(256);
3383 } else {
3384 r.append(' ');
3385 }
3386 r.append(s.info.name);
3387 }
3388 }
3389 if (r != null) {
3390 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3391 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 N = pkg.receivers.size();
3394 r = null;
3395 for (i=0; i<N; i++) {
3396 PackageParser.Activity a = pkg.receivers.get(i);
3397 mReceivers.removeActivity(a, "receiver");
3398 if (chatty) {
3399 if (r == null) {
3400 r = new StringBuilder(256);
3401 } else {
3402 r.append(' ');
3403 }
3404 r.append(a.info.name);
3405 }
3406 }
3407 if (r != null) {
3408 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3409 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 N = pkg.activities.size();
3412 r = null;
3413 for (i=0; i<N; i++) {
3414 PackageParser.Activity a = pkg.activities.get(i);
3415 mActivities.removeActivity(a, "activity");
3416 if (chatty) {
3417 if (r == null) {
3418 r = new StringBuilder(256);
3419 } else {
3420 r.append(' ');
3421 }
3422 r.append(a.info.name);
3423 }
3424 }
3425 if (r != null) {
3426 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3427 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 N = pkg.permissions.size();
3430 r = null;
3431 for (i=0; i<N; i++) {
3432 PackageParser.Permission p = pkg.permissions.get(i);
3433 boolean tree = false;
3434 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3435 if (bp == null) {
3436 tree = true;
3437 bp = mSettings.mPermissionTrees.get(p.info.name);
3438 }
3439 if (bp != null && bp.perm == p) {
3440 if (bp.type != BasePermission.TYPE_BUILTIN) {
3441 if (tree) {
3442 mSettings.mPermissionTrees.remove(p.info.name);
3443 } else {
3444 mSettings.mPermissions.remove(p.info.name);
3445 }
3446 } else {
3447 bp.perm = null;
3448 }
3449 if (chatty) {
3450 if (r == null) {
3451 r = new StringBuilder(256);
3452 } else {
3453 r.append(' ');
3454 }
3455 r.append(p.info.name);
3456 }
3457 }
3458 }
3459 if (r != null) {
3460 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3461 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 N = pkg.instrumentation.size();
3464 r = null;
3465 for (i=0; i<N; i++) {
3466 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3467 mInstrumentation.remove(a.component);
3468 if (chatty) {
3469 if (r == null) {
3470 r = new StringBuilder(256);
3471 } else {
3472 r.append(' ');
3473 }
3474 r.append(a.info.name);
3475 }
3476 }
3477 if (r != null) {
3478 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3479 }
3480 }
3481 }
3482
3483 private static final boolean isPackageFilename(String name) {
3484 return name != null && name.endsWith(".apk");
3485 }
3486
3487 private void updatePermissionsLP() {
3488 // Make sure there are no dangling permission trees.
3489 Iterator<BasePermission> it = mSettings.mPermissionTrees
3490 .values().iterator();
3491 while (it.hasNext()) {
3492 BasePermission bp = it.next();
3493 if (bp.perm == null) {
3494 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3495 + " from package " + bp.sourcePackage);
3496 it.remove();
3497 }
3498 }
3499
3500 // Make sure all dynamic permissions have been assigned to a package,
3501 // and make sure there are no dangling permissions.
3502 it = mSettings.mPermissions.values().iterator();
3503 while (it.hasNext()) {
3504 BasePermission bp = it.next();
3505 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3506 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3507 + bp.name + " pkg=" + bp.sourcePackage
3508 + " info=" + bp.pendingInfo);
3509 if (bp.perm == null && bp.pendingInfo != null) {
3510 BasePermission tree = findPermissionTreeLP(bp.name);
3511 if (tree != null) {
3512 bp.perm = new PackageParser.Permission(tree.perm.owner,
3513 new PermissionInfo(bp.pendingInfo));
3514 bp.perm.info.packageName = tree.perm.info.packageName;
3515 bp.perm.info.name = bp.name;
3516 bp.uid = tree.uid;
3517 }
3518 }
3519 }
3520 if (bp.perm == null) {
3521 Log.w(TAG, "Removing dangling permission: " + bp.name
3522 + " from package " + bp.sourcePackage);
3523 it.remove();
3524 }
3525 }
3526
3527 // Now update the permissions for all packages, in particular
3528 // replace the granted permissions of the system packages.
3529 for (PackageParser.Package pkg : mPackages.values()) {
3530 grantPermissionsLP(pkg, false);
3531 }
3532 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3535 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3536 if (ps == null) {
3537 return;
3538 }
3539 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3540 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 if (replace) {
3543 ps.permissionsFixed = false;
3544 if (gp == ps) {
3545 gp.grantedPermissions.clear();
3546 gp.gids = mGlobalGids;
3547 }
3548 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 if (gp.gids == null) {
3551 gp.gids = mGlobalGids;
3552 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554 final int N = pkg.requestedPermissions.size();
3555 for (int i=0; i<N; i++) {
3556 String name = pkg.requestedPermissions.get(i);
3557 BasePermission bp = mSettings.mPermissions.get(name);
3558 PackageParser.Permission p = bp != null ? bp.perm : null;
3559 if (false) {
3560 if (gp != ps) {
3561 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3562 + ": " + p);
3563 }
3564 }
3565 if (p != null) {
3566 final String perm = p.info.name;
3567 boolean allowed;
3568 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3569 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3570 allowed = true;
3571 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3572 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003573 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003575 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 == PackageManager.SIGNATURE_MATCH);
3577 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3578 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3579 // For updated system applications, the signatureOrSystem permission
3580 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003581 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3583 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3584 if(sysPs.grantedPermissions.contains(perm)) {
3585 allowed = true;
3586 } else {
3587 allowed = false;
3588 }
3589 } else {
3590 allowed = true;
3591 }
3592 }
3593 }
3594 } else {
3595 allowed = false;
3596 }
3597 if (false) {
3598 if (gp != ps) {
3599 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3600 }
3601 }
3602 if (allowed) {
3603 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3604 && ps.permissionsFixed) {
3605 // If this is an existing, non-system package, then
3606 // we can't add any new permissions to it.
3607 if (!gp.loadedPermissions.contains(perm)) {
3608 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003609 // Except... if this is a permission that was added
3610 // to the platform (note: need to only do this when
3611 // updating the platform).
3612 final int NP = PackageParser.NEW_PERMISSIONS.length;
3613 for (int ip=0; ip<NP; ip++) {
3614 final PackageParser.NewPermissionInfo npi
3615 = PackageParser.NEW_PERMISSIONS[ip];
3616 if (npi.name.equals(perm)
3617 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3618 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003619 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003620 + pkg.packageName);
3621 break;
3622 }
3623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 }
3625 }
3626 if (allowed) {
3627 if (!gp.grantedPermissions.contains(perm)) {
3628 addedPermission = true;
3629 gp.grantedPermissions.add(perm);
3630 gp.gids = appendInts(gp.gids, bp.gids);
3631 }
3632 } else {
3633 Log.w(TAG, "Not granting permission " + perm
3634 + " to package " + pkg.packageName
3635 + " because it was previously installed without");
3636 }
3637 } else {
3638 Log.w(TAG, "Not granting permission " + perm
3639 + " to package " + pkg.packageName
3640 + " (protectionLevel=" + p.info.protectionLevel
3641 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3642 + ")");
3643 }
3644 } else {
3645 Log.w(TAG, "Unknown permission " + name
3646 + " in package " + pkg.packageName);
3647 }
3648 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003651 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3652 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 // This is the first that we have heard about this package, so the
3654 // permissions we have now selected are fixed until explicitly
3655 // changed.
3656 ps.permissionsFixed = true;
3657 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3658 }
3659 }
3660
3661 private final class ActivityIntentResolver
3662 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003663 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003665 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 }
3667
Mihai Preda074edef2009-05-18 17:13:31 +02003668 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003670 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3672 }
3673
Mihai Predaeae850c2009-05-13 10:13:48 +02003674 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3675 ArrayList<PackageParser.Activity> packageActivities) {
3676 if (packageActivities == null) {
3677 return null;
3678 }
3679 mFlags = flags;
3680 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3681 int N = packageActivities.size();
3682 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3683 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003684
3685 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003686 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003687 intentFilters = packageActivities.get(i).intents;
3688 if (intentFilters != null && intentFilters.size() > 0) {
3689 listCut.add(intentFilters);
3690 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003691 }
3692 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3693 }
3694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695 public final void addActivity(PackageParser.Activity a, String type) {
3696 mActivities.put(a.component, a);
3697 if (SHOW_INFO || Config.LOGV) Log.v(
3698 TAG, " " + type + " " +
3699 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3700 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3701 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003702 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3704 if (SHOW_INFO || Config.LOGV) {
3705 Log.v(TAG, " IntentFilter:");
3706 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3707 }
3708 if (!intent.debugCheck()) {
3709 Log.w(TAG, "==> For Activity " + a.info.name);
3710 }
3711 addFilter(intent);
3712 }
3713 }
3714
3715 public final void removeActivity(PackageParser.Activity a, String type) {
3716 mActivities.remove(a.component);
3717 if (SHOW_INFO || Config.LOGV) Log.v(
3718 TAG, " " + type + " " +
3719 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3720 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3721 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003722 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3724 if (SHOW_INFO || Config.LOGV) {
3725 Log.v(TAG, " IntentFilter:");
3726 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3727 }
3728 removeFilter(intent);
3729 }
3730 }
3731
3732 @Override
3733 protected boolean allowFilterResult(
3734 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3735 ActivityInfo filterAi = filter.activity.info;
3736 for (int i=dest.size()-1; i>=0; i--) {
3737 ActivityInfo destAi = dest.get(i).activityInfo;
3738 if (destAi.name == filterAi.name
3739 && destAi.packageName == filterAi.packageName) {
3740 return false;
3741 }
3742 }
3743 return true;
3744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 @Override
3747 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3748 int match) {
3749 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3750 return null;
3751 }
3752 final PackageParser.Activity activity = info.activity;
3753 if (mSafeMode && (activity.info.applicationInfo.flags
3754 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3755 return null;
3756 }
3757 final ResolveInfo res = new ResolveInfo();
3758 res.activityInfo = PackageParser.generateActivityInfo(activity,
3759 mFlags);
3760 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3761 res.filter = info;
3762 }
3763 res.priority = info.getPriority();
3764 res.preferredOrder = activity.owner.mPreferredOrder;
3765 //System.out.println("Result: " + res.activityInfo.className +
3766 // " = " + res.priority);
3767 res.match = match;
3768 res.isDefault = info.hasDefault;
3769 res.labelRes = info.labelRes;
3770 res.nonLocalizedLabel = info.nonLocalizedLabel;
3771 res.icon = info.icon;
3772 return res;
3773 }
3774
3775 @Override
3776 protected void sortResults(List<ResolveInfo> results) {
3777 Collections.sort(results, mResolvePrioritySorter);
3778 }
3779
3780 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003781 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003783 out.print(prefix); out.print(
3784 Integer.toHexString(System.identityHashCode(filter.activity)));
3785 out.print(' ');
3786 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003787 }
3788
3789// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3790// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3791// final List<ResolveInfo> retList = Lists.newArrayList();
3792// while (i.hasNext()) {
3793// final ResolveInfo resolveInfo = i.next();
3794// if (isEnabledLP(resolveInfo.activityInfo)) {
3795// retList.add(resolveInfo);
3796// }
3797// }
3798// return retList;
3799// }
3800
3801 // Keys are String (activity class name), values are Activity.
3802 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3803 = new HashMap<ComponentName, PackageParser.Activity>();
3804 private int mFlags;
3805 }
3806
3807 private final class ServiceIntentResolver
3808 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003809 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003811 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 }
3813
Mihai Preda074edef2009-05-18 17:13:31 +02003814 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003816 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3818 }
3819
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003820 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3821 ArrayList<PackageParser.Service> packageServices) {
3822 if (packageServices == null) {
3823 return null;
3824 }
3825 mFlags = flags;
3826 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3827 int N = packageServices.size();
3828 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3829 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3830
3831 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3832 for (int i = 0; i < N; ++i) {
3833 intentFilters = packageServices.get(i).intents;
3834 if (intentFilters != null && intentFilters.size() > 0) {
3835 listCut.add(intentFilters);
3836 }
3837 }
3838 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3839 }
3840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003841 public final void addService(PackageParser.Service s) {
3842 mServices.put(s.component, s);
3843 if (SHOW_INFO || Config.LOGV) Log.v(
3844 TAG, " " + (s.info.nonLocalizedLabel != null
3845 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3846 if (SHOW_INFO || Config.LOGV) Log.v(
3847 TAG, " Class=" + s.info.name);
3848 int NI = s.intents.size();
3849 int j;
3850 for (j=0; j<NI; j++) {
3851 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3852 if (SHOW_INFO || Config.LOGV) {
3853 Log.v(TAG, " IntentFilter:");
3854 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3855 }
3856 if (!intent.debugCheck()) {
3857 Log.w(TAG, "==> For Service " + s.info.name);
3858 }
3859 addFilter(intent);
3860 }
3861 }
3862
3863 public final void removeService(PackageParser.Service s) {
3864 mServices.remove(s.component);
3865 if (SHOW_INFO || Config.LOGV) Log.v(
3866 TAG, " " + (s.info.nonLocalizedLabel != null
3867 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3868 if (SHOW_INFO || Config.LOGV) Log.v(
3869 TAG, " Class=" + s.info.name);
3870 int NI = s.intents.size();
3871 int j;
3872 for (j=0; j<NI; j++) {
3873 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3874 if (SHOW_INFO || Config.LOGV) {
3875 Log.v(TAG, " IntentFilter:");
3876 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3877 }
3878 removeFilter(intent);
3879 }
3880 }
3881
3882 @Override
3883 protected boolean allowFilterResult(
3884 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3885 ServiceInfo filterSi = filter.service.info;
3886 for (int i=dest.size()-1; i>=0; i--) {
3887 ServiceInfo destAi = dest.get(i).serviceInfo;
3888 if (destAi.name == filterSi.name
3889 && destAi.packageName == filterSi.packageName) {
3890 return false;
3891 }
3892 }
3893 return true;
3894 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 @Override
3897 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3898 int match) {
3899 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3900 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3901 return null;
3902 }
3903 final PackageParser.Service service = info.service;
3904 if (mSafeMode && (service.info.applicationInfo.flags
3905 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3906 return null;
3907 }
3908 final ResolveInfo res = new ResolveInfo();
3909 res.serviceInfo = PackageParser.generateServiceInfo(service,
3910 mFlags);
3911 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3912 res.filter = filter;
3913 }
3914 res.priority = info.getPriority();
3915 res.preferredOrder = service.owner.mPreferredOrder;
3916 //System.out.println("Result: " + res.activityInfo.className +
3917 // " = " + res.priority);
3918 res.match = match;
3919 res.isDefault = info.hasDefault;
3920 res.labelRes = info.labelRes;
3921 res.nonLocalizedLabel = info.nonLocalizedLabel;
3922 res.icon = info.icon;
3923 return res;
3924 }
3925
3926 @Override
3927 protected void sortResults(List<ResolveInfo> results) {
3928 Collections.sort(results, mResolvePrioritySorter);
3929 }
3930
3931 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003932 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003934 out.print(prefix); out.print(
3935 Integer.toHexString(System.identityHashCode(filter.service)));
3936 out.print(' ');
3937 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 }
3939
3940// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3941// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3942// final List<ResolveInfo> retList = Lists.newArrayList();
3943// while (i.hasNext()) {
3944// final ResolveInfo resolveInfo = (ResolveInfo) i;
3945// if (isEnabledLP(resolveInfo.serviceInfo)) {
3946// retList.add(resolveInfo);
3947// }
3948// }
3949// return retList;
3950// }
3951
3952 // Keys are String (activity class name), values are Activity.
3953 private final HashMap<ComponentName, PackageParser.Service> mServices
3954 = new HashMap<ComponentName, PackageParser.Service>();
3955 private int mFlags;
3956 };
3957
3958 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3959 new Comparator<ResolveInfo>() {
3960 public int compare(ResolveInfo r1, ResolveInfo r2) {
3961 int v1 = r1.priority;
3962 int v2 = r2.priority;
3963 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3964 if (v1 != v2) {
3965 return (v1 > v2) ? -1 : 1;
3966 }
3967 v1 = r1.preferredOrder;
3968 v2 = r2.preferredOrder;
3969 if (v1 != v2) {
3970 return (v1 > v2) ? -1 : 1;
3971 }
3972 if (r1.isDefault != r2.isDefault) {
3973 return r1.isDefault ? -1 : 1;
3974 }
3975 v1 = r1.match;
3976 v2 = r2.match;
3977 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3978 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3979 }
3980 };
3981
3982 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3983 new Comparator<ProviderInfo>() {
3984 public int compare(ProviderInfo p1, ProviderInfo p2) {
3985 final int v1 = p1.initOrder;
3986 final int v2 = p2.initOrder;
3987 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3988 }
3989 };
3990
3991 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3992 IActivityManager am = ActivityManagerNative.getDefault();
3993 if (am != null) {
3994 try {
3995 final Intent intent = new Intent(action,
3996 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3997 if (extras != null) {
3998 intent.putExtras(extras);
3999 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004000 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 am.broadcastIntent(
4002 null, intent,
4003 null, null, 0, null, null, null, false, false);
4004 } catch (RemoteException ex) {
4005 }
4006 }
4007 }
4008
4009 private final class AppDirObserver extends FileObserver {
4010 public AppDirObserver(String path, int mask, boolean isrom) {
4011 super(path, mask);
4012 mRootDir = path;
4013 mIsRom = isrom;
4014 }
4015
4016 public void onEvent(int event, String path) {
4017 String removedPackage = null;
4018 int removedUid = -1;
4019 String addedPackage = null;
4020 int addedUid = -1;
4021
4022 synchronized (mInstallLock) {
4023 String fullPathStr = null;
4024 File fullPath = null;
4025 if (path != null) {
4026 fullPath = new File(mRootDir, path);
4027 fullPathStr = fullPath.getPath();
4028 }
4029
4030 if (Config.LOGV) Log.v(
4031 TAG, "File " + fullPathStr + " changed: "
4032 + Integer.toHexString(event));
4033
4034 if (!isPackageFilename(path)) {
4035 if (Config.LOGV) Log.v(
4036 TAG, "Ignoring change of non-package file: " + fullPathStr);
4037 return;
4038 }
4039
4040 if ((event&REMOVE_EVENTS) != 0) {
4041 synchronized (mInstallLock) {
4042 PackageParser.Package p = mAppDirs.get(fullPathStr);
4043 if (p != null) {
4044 removePackageLI(p, true);
4045 removedPackage = p.applicationInfo.packageName;
4046 removedUid = p.applicationInfo.uid;
4047 }
4048 }
4049 }
4050
4051 if ((event&ADD_EVENTS) != 0) {
4052 PackageParser.Package p = mAppDirs.get(fullPathStr);
4053 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004054 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004055 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4056 PackageParser.PARSE_CHATTY |
4057 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004058 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 if (p != null) {
4060 synchronized (mPackages) {
4061 grantPermissionsLP(p, false);
4062 }
4063 addedPackage = p.applicationInfo.packageName;
4064 addedUid = p.applicationInfo.uid;
4065 }
4066 }
4067 }
4068
4069 synchronized (mPackages) {
4070 mSettings.writeLP();
4071 }
4072 }
4073
4074 if (removedPackage != null) {
4075 Bundle extras = new Bundle(1);
4076 extras.putInt(Intent.EXTRA_UID, removedUid);
4077 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4078 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4079 }
4080 if (addedPackage != null) {
4081 Bundle extras = new Bundle(1);
4082 extras.putInt(Intent.EXTRA_UID, addedUid);
4083 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4084 }
4085 }
4086
4087 private final String mRootDir;
4088 private final boolean mIsRom;
4089 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 /* Called when a downloaded package installation has been confirmed by the user */
4092 public void installPackage(
4093 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004094 installPackage(packageURI, observer, flags, null);
4095 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004096
Jacek Surazski65e13172009-04-28 15:26:38 +02004097 /* Called when a downloaded package installation has been confirmed by the user */
4098 public void installPackage(
4099 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4100 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 mContext.enforceCallingOrSelfPermission(
4102 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004103
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004104 Message msg = mHandler.obtainMessage(INIT_COPY);
4105 msg.obj = createInstallArgs(packageURI, observer, flags, installerPackageName);
4106 mHandler.sendMessage(msg);
4107 }
4108
4109 private InstallArgs createInstallArgs(Uri packageURI, IPackageInstallObserver observer,
4110 int flags, String installerPackageName) {
4111 if (installOnSd(flags)) {
4112 return new SdInstallArgs(packageURI, observer, flags,
4113 installerPackageName);
4114 } else {
4115 return new FileInstallArgs(packageURI, observer, flags,
4116 installerPackageName);
4117 }
4118 }
4119
4120 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4121 if (installOnSd(flags)) {
4122 return new SdInstallArgs(fullCodePath, fullResourcePath);
4123 } else {
4124 return new FileInstallArgs(fullCodePath, fullResourcePath);
4125 }
4126 }
4127
4128 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 // Queue up an async operation since the package installation may take a little while.
4130 mHandler.post(new Runnable() {
4131 public void run() {
4132 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004133 // Result object to be returned
4134 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004135 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004136 res.uid = -1;
4137 res.pkg = null;
4138 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004139 args.doPreInstall(res.returnCode);
4140 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004141 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004142 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004143 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004144 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004146 if (args.observer != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004147 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004148 args.observer.packageInstalled(res.name, res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004149 } catch (RemoteException e) {
4150 Log.i(TAG, "Observer no longer exists.");
4151 }
4152 }
4153 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
4154 // call appears in the synchronized block above.
4155 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4156 res.removedInfo.sendBroadcast(false, true);
4157 Bundle extras = new Bundle(1);
4158 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004159 final boolean update = res.removedInfo.removedPackage != null;
4160 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004161 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4162 }
4163 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
4164 res.pkg.applicationInfo.packageName,
4165 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004166 if (update) {
4167 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
4168 res.pkg.applicationInfo.packageName,
4169 extras);
4170 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004171 if (res.removedInfo.args != null) {
4172 // Remove the replaced package's older resources safely now
4173 synchronized (mInstallLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004174 res.removedInfo.args.doPostDeleteLI(true);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004175 }
4176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177 }
4178 Runtime.getRuntime().gc();
4179 }
4180 });
4181 }
4182
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004183 static abstract class InstallArgs {
4184 final IPackageInstallObserver observer;
4185 final int flags;
4186 final Uri packageURI;
4187 final String installerPackageName;
4188
4189 InstallArgs(Uri packageURI,
4190 IPackageInstallObserver observer, int flags,
4191 String installerPackageName) {
4192 this.packageURI = packageURI;
4193 this.flags = flags;
4194 this.observer = observer;
4195 this.installerPackageName = installerPackageName;
4196 }
4197
4198 abstract void createCopyFile();
4199 abstract int copyApk(IMediaContainerService imcs);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004200 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004201 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004202 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004203 abstract String getCodePath();
4204 abstract String getResourcePath();
4205 // Need installer lock especially for dex file removal.
4206 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004207 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004208 }
4209
4210 class FileInstallArgs extends InstallArgs {
4211 File installDir;
4212 String codeFileName;
4213 String resourceFileName;
4214
4215 FileInstallArgs(Uri packageURI,
4216 IPackageInstallObserver observer, int flags,
4217 String installerPackageName) {
4218 super(packageURI, observer, flags, installerPackageName);
4219 }
4220
4221 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4222 super(null, null, 0, null);
4223 File codeFile = new File(fullCodePath);
4224 installDir = codeFile.getParentFile();
4225 codeFileName = fullCodePath;
4226 resourceFileName = fullResourcePath;
4227 }
4228
4229 void createCopyFile() {
4230 boolean fwdLocked = isFwdLocked(flags);
4231 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4232 codeFileName = createTempPackageFile(installDir).getPath();
4233 resourceFileName = getResourcePathFromCodePath();
4234 }
4235
4236 String getCodePath() {
4237 return codeFileName;
4238 }
4239
4240 int copyApk(IMediaContainerService imcs) {
4241 // Get a ParcelFileDescriptor to write to the output file
4242 File codeFile = new File(codeFileName);
4243 ParcelFileDescriptor out = null;
4244 try {
4245 out = ParcelFileDescriptor.open(codeFile,
4246 ParcelFileDescriptor.MODE_READ_WRITE);
4247 } catch (FileNotFoundException e) {
4248 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4249 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4250 }
4251 // Copy the resource now
4252 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4253 try {
4254 if (imcs.copyResource(packageURI, out)) {
4255 ret = PackageManager.INSTALL_SUCCEEDED;
4256 }
4257 } catch (RemoteException e) {
4258 } finally {
4259 try { if (out != null) out.close(); } catch (IOException e) {}
4260 }
4261 return ret;
4262 }
4263
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004264 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004265 if (status != PackageManager.INSTALL_SUCCEEDED) {
4266 cleanUp();
4267 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004268 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004269 }
4270
4271 boolean doRename(int status, final String pkgName, String oldCodePath) {
4272 if (status != PackageManager.INSTALL_SUCCEEDED) {
4273 cleanUp();
4274 return false;
4275 } else {
4276 // Rename based on packageName
4277 File codeFile = new File(getCodePath());
4278 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4279 File desFile = new File(installDir, apkName + ".apk");
4280 if (!codeFile.renameTo(desFile)) {
4281 return false;
4282 }
4283 // Reset paths since the file has been renamed.
4284 codeFileName = desFile.getPath();
4285 resourceFileName = getResourcePathFromCodePath();
4286 // Set permissions
4287 if (!setPermissions(pkgName)) {
4288 // Failed setting permissions.
4289 return false;
4290 }
4291 return true;
4292 }
4293 }
4294
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004295 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004296 if (status != PackageManager.INSTALL_SUCCEEDED) {
4297 cleanUp();
4298 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004299 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004300 }
4301
4302 String getResourcePath() {
4303 return resourceFileName;
4304 }
4305
4306 String getResourcePathFromCodePath() {
4307 String codePath = getCodePath();
4308 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4309 String apkNameOnly = getApkName(codePath);
4310 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4311 } else {
4312 return codePath;
4313 }
4314 }
4315
4316 private boolean cleanUp() {
4317 boolean ret = true;
4318 String sourceDir = getCodePath();
4319 String publicSourceDir = getResourcePath();
4320 if (sourceDir != null) {
4321 File sourceFile = new File(sourceDir);
4322 if (!sourceFile.exists()) {
4323 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4324 ret = false;
4325 }
4326 // Delete application's code and resources
4327 sourceFile.delete();
4328 }
4329 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4330 final File publicSourceFile = new File(publicSourceDir);
4331 if (!publicSourceFile.exists()) {
4332 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4333 }
4334 if (publicSourceFile.exists()) {
4335 publicSourceFile.delete();
4336 }
4337 }
4338 return ret;
4339 }
4340
4341 void cleanUpResourcesLI() {
4342 String sourceDir = getCodePath();
4343 if (cleanUp() && mInstaller != null) {
4344 int retCode = mInstaller.rmdex(sourceDir);
4345 if (retCode < 0) {
4346 Log.w(TAG, "Couldn't remove dex file for package: "
4347 + " at location "
4348 + sourceDir + ", retcode=" + retCode);
4349 // we don't consider this to be a failure of the core package deletion
4350 }
4351 }
4352 }
4353
4354 private boolean setPermissions(String pkgName) {
4355 // TODO Do this in a more elegant way later on. for now just a hack
4356 if (!isFwdLocked(flags)) {
4357 final int filePermissions =
4358 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4359 |FileUtils.S_IROTH;
4360 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4361 if (retCode != 0) {
4362 Log.e(TAG, "Couldn't set new package file permissions for " +
4363 getCodePath()
4364 + ". The return code was: " + retCode);
4365 // TODO Define new internal error
4366 return false;
4367 }
4368 return true;
4369 }
4370 return true;
4371 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004372
4373 boolean doPostDeleteLI(boolean delete) {
4374 cleanUpResourcesLI();
4375 return true;
4376 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004377 }
4378
4379 class SdInstallArgs extends InstallArgs {
4380 String cid;
4381 String cachePath;
4382 static final String RES_FILE_NAME = "pkg.apk";
4383
4384 SdInstallArgs(Uri packageURI,
4385 IPackageInstallObserver observer, int flags,
4386 String installerPackageName) {
4387 super(packageURI, observer, flags, installerPackageName);
4388 }
4389
4390 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004391 super(null, null, ApplicationInfo.FLAG_ON_SDCARD, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004392 // Extract cid from fullCodePath
4393 int eidx = fullCodePath.lastIndexOf("/");
4394 String subStr1 = fullCodePath.substring(0, eidx);
4395 int sidx = subStr1.lastIndexOf("/");
4396 cid = subStr1.substring(sidx+1, eidx);
4397 cachePath = subStr1;
4398 }
4399
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004400 SdInstallArgs(String cid) {
4401 super(null, null, ApplicationInfo.FLAG_ON_SDCARD, null);
4402 this.cid = cid;
4403 }
4404
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004405 void createCopyFile() {
4406 cid = getTempContainerId();
4407 }
4408
4409 int copyApk(IMediaContainerService imcs) {
4410 try {
4411 cachePath = imcs.copyResourceToContainer(
4412 packageURI, cid,
4413 getEncryptKey(), RES_FILE_NAME);
4414 } catch (RemoteException e) {
4415 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004416 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
4417 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004418 }
4419
4420 @Override
4421 String getCodePath() {
4422 return cachePath + "/" + RES_FILE_NAME;
4423 }
4424
4425 @Override
4426 String getResourcePath() {
4427 return cachePath + "/" + RES_FILE_NAME;
4428 }
4429
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004430 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004431 if (status != PackageManager.INSTALL_SUCCEEDED) {
4432 // Destroy container
4433 destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004434 } else {
4435 // STOPSHIP Remove once new api is added in MountService
4436 //boolean mounted = isContainerMounted(cid);
4437 boolean mounted = false;
4438 if (!mounted) {
4439 cachePath = mountSdDir(cid, Process.SYSTEM_UID);
4440 if (cachePath == null) {
4441 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4442 }
4443 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004444 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004445 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004446 }
4447
4448 boolean doRename(int status, final String pkgName,
4449 String oldCodePath) {
4450 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004451 String newCachePath = null;
4452 /*final int RENAME_FAILED = 1;
4453 final int MOUNT_FAILED = 2;
4454 final int DESTROY_FAILED = 3;
4455 final int PASS = 4;
4456 int errCode = RENAME_FAILED;
4457 if (mounted) {
4458 // Unmount the container
4459 if (!unMountSdDir(cid)) {
4460 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
4461 return false;
4462 }
4463 mounted = false;
4464 }
4465 if (renameSdDir(cid, newCacheId)) {
4466 errCode = MOUNT_FAILED;
4467 if ((newCachePath = mountSdDir(newCacheId, Process.SYSTEM_UID)) != null) {
4468 errCode = PASS;
4469 }
4470 }
4471 String errMsg = "";
4472 switch (errCode) {
4473 case RENAME_FAILED:
4474 errMsg = "RENAME_FAILED";
4475 break;
4476 case MOUNT_FAILED:
4477 errMsg = "MOUNT_FAILED";
4478 break;
4479 case DESTROY_FAILED:
4480 errMsg = "DESTROY_FAILED";
4481 break;
4482 default:
4483 errMsg = "PASS";
4484 break;
4485 }
4486 Log.i(TAG, "Status: " + errMsg);
4487 if (errCode != PASS) {
4488 return false;
4489 }
4490 Log.i(TAG, "Succesfully renamed " + cid + " to " +newCacheId +
4491 " at path: " + cachePath + " to new path: " + newCachePath);
4492 cid = newCacheId;
4493 cachePath = newCachePath;
4494 return true;
4495 */
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004496 // STOPSHIP TEMPORARY HACK FOR RENAME
4497 // Create new container at newCachePath
4498 String codePath = getCodePath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004499 final int CREATE_FAILED = 1;
4500 final int COPY_FAILED = 3;
4501 final int FINALIZE_FAILED = 5;
4502 final int PASS = 7;
4503 int errCode = CREATE_FAILED;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004504
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004505 if ((newCachePath = createSdDir(new File(codePath), newCacheId)) != null) {
4506 errCode = COPY_FAILED;
4507 // Copy file from codePath
4508 if (FileUtils.copyFile(new File(codePath), new File(newCachePath, RES_FILE_NAME))) {
4509 errCode = FINALIZE_FAILED;
4510 if (finalizeSdDir(newCacheId)) {
4511 errCode = PASS;
4512 }
4513 }
4514 }
4515 // Print error based on errCode
4516 String errMsg = "";
4517 switch (errCode) {
4518 case CREATE_FAILED:
4519 errMsg = "CREATE_FAILED";
4520 break;
4521 case COPY_FAILED:
4522 errMsg = "COPY_FAILED";
4523 destroySdDir(newCacheId);
4524 break;
4525 case FINALIZE_FAILED:
4526 errMsg = "FINALIZE_FAILED";
4527 destroySdDir(newCacheId);
4528 break;
4529 default:
4530 errMsg = "PASS";
4531 break;
4532 }
4533 // Destroy the temporary container
4534 destroySdDir(cid);
4535 Log.i(TAG, "Status: " + errMsg);
4536 if (errCode != PASS) {
4537 return false;
4538 }
4539 cid = newCacheId;
4540 cachePath = newCachePath;
4541
4542 return true;
4543 }
4544
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004545 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004546 if (status != PackageManager.INSTALL_SUCCEEDED) {
4547 cleanUp();
4548 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004549 // STOP SHIP Change this once new api is added.
4550 //boolean mounted = isContainerMounted(cid);
4551 boolean mounted = false;
4552 if (!mounted) {
4553 mountSdDir(cid, Process.SYSTEM_UID);
4554 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004555 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004556 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004557 }
4558
4559 private void cleanUp() {
4560 // Destroy secure container
4561 destroySdDir(cid);
4562 }
4563
4564 void cleanUpResourcesLI() {
4565 String sourceFile = getCodePath();
4566 // Remove dex file
4567 if (mInstaller != null) {
4568 int retCode = mInstaller.rmdex(sourceFile.toString());
4569 if (retCode < 0) {
4570 Log.w(TAG, "Couldn't remove dex file for package: "
4571 + " at location "
4572 + sourceFile.toString() + ", retcode=" + retCode);
4573 // we don't consider this to be a failure of the core package deletion
4574 }
4575 }
4576 cleanUp();
4577 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004578
4579 boolean matchContainer(String app) {
4580 if (cid.startsWith(app)) {
4581 return true;
4582 }
4583 return false;
4584 }
4585
4586 String getPackageName() {
4587 int idx = cid.lastIndexOf("-");
4588 if (idx == -1) {
4589 return cid;
4590 }
4591 return cid.substring(0, idx);
4592 }
4593
4594 boolean doPostDeleteLI(boolean delete) {
4595 boolean ret = false;
4596 boolean mounted = isContainerMounted(cid);
4597 if (mounted) {
4598 // Unmount first
4599 ret = unMountSdDir(cid);
4600 }
4601 if (ret && delete) {
4602 cleanUpResourcesLI();
4603 }
4604 return ret;
4605 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004606 };
4607
4608 // Utility method used to create code paths based on package name and available index.
4609 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
4610 String idxStr = "";
4611 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004612 // Fall back to default value of idx=1 if prefix is not
4613 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004614 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004615 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004616 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004617 if (subStr.endsWith(suffix)) {
4618 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004619 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004620 // If oldCodePath already contains prefix find out the
4621 // ending index to either increment or decrement.
4622 int sidx = subStr.lastIndexOf(prefix);
4623 if (sidx != -1) {
4624 subStr = subStr.substring(sidx + prefix.length());
4625 if (subStr != null) {
4626 if (subStr.startsWith("-")) {
4627 subStr = subStr.substring(1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004628 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004629 try {
4630 idx = Integer.parseInt(subStr);
4631 if (idx <= 1) {
4632 idx++;
4633 } else {
4634 idx--;
4635 }
4636 } catch(NumberFormatException e) {
4637 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004638 }
4639 }
4640 }
4641 idxStr = "-" + Integer.toString(idx);
4642 return prefix + idxStr;
4643 }
4644
4645 // Utility method that returns the relative package path with respect
4646 // to the installation directory. Like say for /data/data/com.test-1.apk
4647 // string com.test-1 is returned.
4648 static String getApkName(String codePath) {
4649 if (codePath == null) {
4650 return null;
4651 }
4652 int sidx = codePath.lastIndexOf("/");
4653 int eidx = codePath.lastIndexOf(".");
4654 if (eidx == -1) {
4655 eidx = codePath.length();
4656 } else if (eidx == 0) {
4657 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
4658 return null;
4659 }
4660 return codePath.substring(sidx+1, eidx);
4661 }
4662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004663 class PackageInstalledInfo {
4664 String name;
4665 int uid;
4666 PackageParser.Package pkg;
4667 int returnCode;
4668 PackageRemovedInfo removedInfo;
4669 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004671 /*
4672 * Install a non-existing package.
4673 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004674 private void installNewPackageLI(PackageParser.Package pkg,
4675 int parseFlags,
4676 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004677 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004678 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08004679 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004680 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08004681
4682 if (useEncryptedFilesystemForPackage(pkg)) {
4683 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
4684 } else {
4685 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
4686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 res.name = pkgName;
4688 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004689 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004690 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004691 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004692 + " without first uninstalling.");
4693 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4694 return;
4695 }
4696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004697 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004698 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004699 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004700 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004701 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4702 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4703 }
4704 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004705 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004706 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 res);
4708 // delete the partially installed application. the data directory will have to be
4709 // restored if it was already existing
4710 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4711 // remove package from internal structures. Note that we want deletePackageX to
4712 // delete the package data and cache directories that it created in
4713 // scanPackageLocked, unless those directories existed before we even tried to
4714 // install.
4715 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004716 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004717 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
4718 res.removedInfo);
4719 }
4720 }
4721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004722
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004723 private void replacePackageLI(PackageParser.Package pkg,
4724 int parseFlags,
4725 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004726 String installerPackageName, PackageInstalledInfo res) {
4727
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004728 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004729 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004730 // First find the old package info and check signatures
4731 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004732 oldPackage = mPackages.get(pkgName);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004733 if(checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
4734 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4736 return;
4737 }
4738 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004739 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004740 if(sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004741 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004743 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004744 }
4745 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004747 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004748 PackageParser.Package pkg,
4749 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004750 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004751 PackageParser.Package newPackage = null;
4752 String pkgName = deletedPackage.packageName;
4753 boolean deletedPkg = true;
4754 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004755
Jacek Surazski65e13172009-04-28 15:26:38 +02004756 String oldInstallerPackageName = null;
4757 synchronized (mPackages) {
4758 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
4759 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004760
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004761 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004762 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004763 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004764 res.removedInfo)) {
4765 // If the existing package was'nt successfully deleted
4766 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4767 deletedPkg = false;
4768 } else {
4769 // Successfully deleted the old package. Now proceed with re-installation
4770 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004771 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004772 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004773 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004774 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4775 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08004776 }
4777 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004778 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004779 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004780 res);
4781 updatedSettings = true;
4782 }
4783 }
4784
4785 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4786 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004787 // were keeping around in case we needed them (see below) can now be deleted.
4788 // This info will be set on the res.removedInfo to clean up later on as post
4789 // install action.
4790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004791 //update signature on the new package setting
4792 //this should always succeed, since we checked the
4793 //signature earlier.
4794 synchronized(mPackages) {
4795 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
4796 parseFlags, true);
4797 }
4798 } else {
4799 // remove package from internal structures. Note that we want deletePackageX to
4800 // delete the package data and cache directories that it created in
4801 // scanPackageLocked, unless those directories existed before we even tried to
4802 // install.
4803 if(updatedSettings) {
4804 deletePackageLI(
4805 pkgName, true,
4806 PackageManager.DONT_DELETE_DATA,
4807 res.removedInfo);
4808 }
4809 // Since we failed to install the new package we need to restore the old
4810 // package that we deleted.
4811 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004812 File restoreFile = new File(deletedPackage.mPath);
4813 if (restoreFile == null) {
4814 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
4815 return;
4816 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004817 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
4818 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004819 // Parse old package
4820 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
4821 scanPackageLI(restoreFile, parseFlags, scanMode);
4822 synchronized (mPackages) {
4823 grantPermissionsLP(deletedPackage, false);
4824 mSettings.writeLP();
4825 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004826 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4827 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
4828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004829 }
4830 }
4831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004833 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004834 PackageParser.Package pkg,
4835 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004836 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 PackageParser.Package newPackage = null;
4838 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004839 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004840 PackageParser.PARSE_IS_SYSTEM;
4841 String packageName = deletedPackage.packageName;
4842 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4843 if (packageName == null) {
4844 Log.w(TAG, "Attempt to delete null packageName.");
4845 return;
4846 }
4847 PackageParser.Package oldPkg;
4848 PackageSetting oldPkgSetting;
4849 synchronized (mPackages) {
4850 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004851 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004852 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
4853 (oldPkgSetting == null)) {
4854 Log.w(TAG, "Could'nt find package:"+packageName+" information");
4855 return;
4856 }
4857 }
4858 res.removedInfo.uid = oldPkg.applicationInfo.uid;
4859 res.removedInfo.removedPackage = packageName;
4860 // Remove existing system package
4861 removePackageLI(oldPkg, true);
4862 synchronized (mPackages) {
4863 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
4864 }
4865
4866 // Successfully disabled the old package. Now proceed with re-installation
4867 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4868 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004869 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004870 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004871 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004872 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4873 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4874 }
4875 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004876 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004877 updatedSettings = true;
4878 }
4879
4880 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4881 //update signature on the new package setting
4882 //this should always succeed, since we checked the
4883 //signature earlier.
4884 synchronized(mPackages) {
4885 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
4886 parseFlags, true);
4887 }
4888 } else {
4889 // Re installation failed. Restore old information
4890 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07004891 if (newPackage != null) {
4892 removePackageLI(newPackage, true);
4893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004894 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004895 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004896 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07004897 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004898 // Restore the old system information in Settings
4899 synchronized(mPackages) {
4900 if(updatedSettings) {
4901 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02004902 mSettings.setInstallerPackageName(packageName,
4903 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004904 }
4905 mSettings.writeLP();
4906 }
4907 }
4908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004909
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004910 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004911 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004912 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004913 synchronized (mPackages) {
4914 //write settings. the installStatus will be incomplete at this stage.
4915 //note that the new package setting would have already been
4916 //added to mPackages. It hasn't been persisted yet.
4917 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
4918 mSettings.writeLP();
4919 }
4920
4921 int retCode = 0;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004922 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4923 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004924 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004925 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004926 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4927 return;
4928 }
4929 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004930 res.returnCode = setPermissionsLI(newPackage);
4931 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4932 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004933 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004934 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004935 }
4936 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4937 if (mInstaller != null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004938 mInstaller.rmdex(newPackage.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939 }
4940 }
4941
4942 synchronized (mPackages) {
4943 grantPermissionsLP(newPackage, true);
4944 res.name = pkgName;
4945 res.uid = newPackage.applicationInfo.uid;
4946 res.pkg = newPackage;
4947 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02004948 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004949 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4950 //to update install status
4951 mSettings.writeLP();
4952 }
4953 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004954
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004955 private void installPackageLI(InstallArgs args,
4956 boolean newInstall, PackageInstalledInfo res) {
4957 int pFlags = args.flags;
4958 String installerPackageName = args.installerPackageName;
4959 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004960 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
4961 boolean onSd = ((pFlags & PackageManager.INSTALL_ON_SDCARD) != 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004962 boolean replacingExistingPackage = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004963 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
4964 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004965 // Result object to be returned
4966 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4967
4968 main_flow: try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004969 // Retrieve PackageSettings and parse package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004970 int parseFlags = PackageParser.PARSE_CHATTY |
4971 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
4972 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004973 parseFlags |= mDefParseFlags;
4974 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
4975 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004977 null, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004978 if (pkg == null) {
4979 res.returnCode = pp.getParseError();
4980 break main_flow;
4981 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004982 String pkgName = res.name = pkg.packageName;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004983 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
4984 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
4985 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
4986 break main_flow;
4987 }
4988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004989 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
4990 res.returnCode = pp.getParseError();
4991 break main_flow;
4992 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004993
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004994 // Get rid of all references to package scan path via parser.
4995 pp = null;
4996 String oldCodePath = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004997 synchronized (mPackages) {
4998 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004999 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 && mPackages.containsKey(pkgName)) {
5001 replacingExistingPackage = true;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005002 }
5003 PackageSetting ps = mSettings.mPackages.get(pkgName);
5004 if (ps != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005005 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005006 }
5007 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005008
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005009 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5010 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5011 break main_flow;
5012 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005013 // Set application objects path explicitly after the rename
5014 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005015 if(replacingExistingPackage) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005016 replacePackageLI(pkg, parseFlags, scanMode,
5017 installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005018 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005019 installNewPackageLI(pkg, parseFlags, scanMode,
5020 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005021 }
5022 } finally {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005023 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005025 }
5026 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005027
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005028 private int setPermissionsLI(PackageParser.Package newPackage) {
5029 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005030 int retCode = 0;
5031 // TODO Gross hack but fix later. Ideally move this to be a post installation
5032 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005033 if ((newPackage.applicationInfo.flags
5034 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5035 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005036 try {
5037 extractPublicFiles(newPackage, destResourceFile);
5038 } catch (IOException e) {
5039 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5040 " forward-locked app.");
5041 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5042 } finally {
5043 //TODO clean up the extracted public files
5044 }
5045 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005046 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005047 newPackage.applicationInfo.uid);
5048 } else {
5049 final int filePermissions =
5050 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005051 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005052 newPackage.applicationInfo.uid);
5053 }
5054 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005055 // The permissions on the resource file was set when it was copied for
5056 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005057 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005060 Log.e(TAG, "Couldn't set new package file permissions for " +
5061 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005063 // TODO Define new internal error
5064 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 }
5066 return PackageManager.INSTALL_SUCCEEDED;
5067 }
5068
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005069 private boolean isForwardLocked(PackageParser.Package pkg) {
5070 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005071 }
5072
5073 private void extractPublicFiles(PackageParser.Package newPackage,
5074 File publicZipFile) throws IOException {
5075 final ZipOutputStream publicZipOutStream =
5076 new ZipOutputStream(new FileOutputStream(publicZipFile));
5077 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5078
5079 // Copy manifest, resources.arsc and res directory to public zip
5080
5081 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5082 while (privateZipEntries.hasMoreElements()) {
5083 final ZipEntry zipEntry = privateZipEntries.nextElement();
5084 final String zipEntryName = zipEntry.getName();
5085 if ("AndroidManifest.xml".equals(zipEntryName)
5086 || "resources.arsc".equals(zipEntryName)
5087 || zipEntryName.startsWith("res/")) {
5088 try {
5089 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5090 } catch (IOException e) {
5091 try {
5092 publicZipOutStream.close();
5093 throw e;
5094 } finally {
5095 publicZipFile.delete();
5096 }
5097 }
5098 }
5099 }
5100
5101 publicZipOutStream.close();
5102 FileUtils.setPermissions(
5103 publicZipFile.getAbsolutePath(),
5104 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5105 -1, -1);
5106 }
5107
5108 private static void copyZipEntry(ZipEntry zipEntry,
5109 ZipFile inZipFile,
5110 ZipOutputStream outZipStream) throws IOException {
5111 byte[] buffer = new byte[4096];
5112 int num;
5113
5114 ZipEntry newEntry;
5115 if (zipEntry.getMethod() == ZipEntry.STORED) {
5116 // Preserve the STORED method of the input entry.
5117 newEntry = new ZipEntry(zipEntry);
5118 } else {
5119 // Create a new entry so that the compressed len is recomputed.
5120 newEntry = new ZipEntry(zipEntry.getName());
5121 }
5122 outZipStream.putNextEntry(newEntry);
5123
5124 InputStream data = inZipFile.getInputStream(zipEntry);
5125 while ((num = data.read(buffer)) > 0) {
5126 outZipStream.write(buffer, 0, num);
5127 }
5128 outZipStream.flush();
5129 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005131 private void deleteTempPackageFiles() {
5132 FilenameFilter filter = new FilenameFilter() {
5133 public boolean accept(File dir, String name) {
5134 return name.startsWith("vmdl") && name.endsWith(".tmp");
5135 }
5136 };
5137 String tmpFilesList[] = mAppInstallDir.list(filter);
5138 if(tmpFilesList == null) {
5139 return;
5140 }
5141 for(int i = 0; i < tmpFilesList.length; i++) {
5142 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5143 tmpFile.delete();
5144 }
5145 }
5146
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005147 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 File tmpPackageFile;
5149 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005150 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005151 } catch (IOException e) {
5152 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5153 return null;
5154 }
5155 try {
5156 FileUtils.setPermissions(
5157 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5158 -1, -1);
5159 } catch (IOException e) {
5160 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5161 return null;
5162 }
5163 return tmpPackageFile;
5164 }
5165
5166 public void deletePackage(final String packageName,
5167 final IPackageDeleteObserver observer,
5168 final int flags) {
5169 mContext.enforceCallingOrSelfPermission(
5170 android.Manifest.permission.DELETE_PACKAGES, null);
5171 // Queue up an async operation since the package deletion may take a little while.
5172 mHandler.post(new Runnable() {
5173 public void run() {
5174 mHandler.removeCallbacks(this);
5175 final boolean succeded = deletePackageX(packageName, true, true, flags);
5176 if (observer != null) {
5177 try {
5178 observer.packageDeleted(succeded);
5179 } catch (RemoteException e) {
5180 Log.i(TAG, "Observer no longer exists.");
5181 } //end catch
5182 } //end if
5183 } //end run
5184 });
5185 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005187 /**
5188 * This method is an internal method that could be get invoked either
5189 * to delete an installed package or to clean up a failed installation.
5190 * After deleting an installed package, a broadcast is sent to notify any
5191 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005192 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005193 * installation wouldn't have sent the initial broadcast either
5194 * The key steps in deleting a package are
5195 * deleting the package information in internal structures like mPackages,
5196 * deleting the packages base directories through installd
5197 * updating mSettings to reflect current status
5198 * persisting settings for later use
5199 * sending a broadcast if necessary
5200 */
5201
5202 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5203 boolean deleteCodeAndResources, int flags) {
5204 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005205 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005206
5207 synchronized (mInstallLock) {
5208 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5209 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005211 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005212 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5213 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5214
5215 // If the removed package was a system update, the old system packaged
5216 // was re-enabled; we need to broadcast this information
5217 if (systemUpdate) {
5218 Bundle extras = new Bundle(1);
5219 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5220 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5221
5222 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5223 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005226 // Delete the resources here after sending the broadcast to let
5227 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005228 if (info.args != null) {
5229 synchronized (mInstallLock) {
5230 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005231 }
5232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005233 return res;
5234 }
5235
5236 static class PackageRemovedInfo {
5237 String removedPackage;
5238 int uid = -1;
5239 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005240 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005241 // Clean up resources deleted packages.
5242 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 void sendBroadcast(boolean fullRemove, boolean replacing) {
5245 Bundle extras = new Bundle(1);
5246 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5247 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5248 if (replacing) {
5249 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5250 }
5251 if (removedPackage != null) {
5252 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5253 }
5254 if (removedUid >= 0) {
5255 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5256 }
5257 }
5258 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 /*
5261 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5262 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005263 * make sure this flag is set for partially installed apps. If not its meaningless to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005264 * delete a partially installed application.
5265 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005266 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005267 int flags) {
5268 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005269 if (outInfo != null) {
5270 outInfo.removedPackage = packageName;
5271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005272 removePackageLI(p, true);
5273 // Retrieve object to delete permissions for shared user later on
5274 PackageSetting deletedPs;
5275 synchronized (mPackages) {
5276 deletedPs = mSettings.mPackages.get(packageName);
5277 }
5278 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005279 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005280 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005281 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005282 if (retCode < 0) {
5283 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5284 + packageName + ", retcode=" + retCode);
5285 // we don't consider this to be a failure of the core package deletion
5286 }
5287 } else {
5288 //for emulator
5289 PackageParser.Package pkg = mPackages.get(packageName);
5290 File dataDir = new File(pkg.applicationInfo.dataDir);
5291 dataDir.delete();
5292 }
5293 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005294 if (outInfo != null) {
5295 outInfo.removedUid = mSettings.removePackageLP(packageName);
5296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005297 }
5298 }
5299 synchronized (mPackages) {
5300 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5301 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005302 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 }
5304 // Save settings now
5305 mSettings.writeLP ();
5306 }
5307 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005309 /*
5310 * Tries to delete system package.
5311 */
5312 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005313 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 ApplicationInfo applicationInfo = p.applicationInfo;
5315 //applicable for non-partially installed applications only
5316 if (applicationInfo == null) {
5317 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5318 return false;
5319 }
5320 PackageSetting ps = null;
5321 // Confirm if the system package has been updated
5322 // An updated system app can be deleted. This will also have to restore
5323 // the system pkg from system partition
5324 synchronized (mPackages) {
5325 ps = mSettings.getDisabledSystemPkg(p.packageName);
5326 }
5327 if (ps == null) {
5328 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5329 return false;
5330 } else {
5331 Log.i(TAG, "Deleting system pkg from data partition");
5332 }
5333 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005334 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005335 boolean deleteCodeAndResources = false;
5336 if (ps.versionCode < p.mVersionCode) {
5337 // Delete code and resources for downgrades
5338 deleteCodeAndResources = true;
5339 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5340 flags &= ~PackageManager.DONT_DELETE_DATA;
5341 }
5342 } else {
5343 // Preserve data by setting flag
5344 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5345 flags |= PackageManager.DONT_DELETE_DATA;
5346 }
5347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005348 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5349 if (!ret) {
5350 return false;
5351 }
5352 synchronized (mPackages) {
5353 // Reinstate the old system package
5354 mSettings.enableSystemPackageLP(p.packageName);
5355 }
5356 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005357 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005358 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005359 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 if (newPkg == null) {
5362 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5363 return false;
5364 }
5365 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005366 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005367 mSettings.writeLP();
5368 }
5369 return true;
5370 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5373 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5374 ApplicationInfo applicationInfo = p.applicationInfo;
5375 if (applicationInfo == null) {
5376 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5377 return false;
5378 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005379 if (outInfo != null) {
5380 outInfo.uid = applicationInfo.uid;
5381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005382
5383 // Delete package data from internal structures and also remove data if flag is set
5384 removePackageDataLI(p, outInfo, flags);
5385
5386 // Delete application code and resources
5387 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005388 // TODO can pick up from PackageSettings as well
5389 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
5390 PackageManager.INSTALL_ON_SDCARD : 0;
5391 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5392 PackageManager.INSTALL_FORWARD_LOCK : 0;
5393 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005394 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 }
5396 return true;
5397 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005399 /*
5400 * This method handles package deletion in general
5401 */
5402 private boolean deletePackageLI(String packageName,
5403 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5404 if (packageName == null) {
5405 Log.w(TAG, "Attempt to delete null packageName.");
5406 return false;
5407 }
5408 PackageParser.Package p;
5409 boolean dataOnly = false;
5410 synchronized (mPackages) {
5411 p = mPackages.get(packageName);
5412 if (p == null) {
5413 //this retrieves partially installed apps
5414 dataOnly = true;
5415 PackageSetting ps = mSettings.mPackages.get(packageName);
5416 if (ps == null) {
5417 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5418 return false;
5419 }
5420 p = ps.pkg;
5421 }
5422 }
5423 if (p == null) {
5424 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5425 return false;
5426 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005428 if (dataOnly) {
5429 // Delete application data first
5430 removePackageDataLI(p, outInfo, flags);
5431 return true;
5432 }
5433 // At this point the package should have ApplicationInfo associated with it
5434 if (p.applicationInfo == null) {
5435 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5436 return false;
5437 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005438 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5440 Log.i(TAG, "Removing system package:"+p.packageName);
5441 // When an updated system application is deleted we delete the existing resources as well and
5442 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005443 ret = deleteSystemPackageLI(p, flags, outInfo);
5444 } else {
5445 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005446 // Kill application pre-emptively especially for apps on sd.
5447 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005448 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005449 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005450 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005453 public void clearApplicationUserData(final String packageName,
5454 final IPackageDataObserver observer) {
5455 mContext.enforceCallingOrSelfPermission(
5456 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5457 // Queue up an async operation since the package deletion may take a little while.
5458 mHandler.post(new Runnable() {
5459 public void run() {
5460 mHandler.removeCallbacks(this);
5461 final boolean succeeded;
5462 synchronized (mInstallLock) {
5463 succeeded = clearApplicationUserDataLI(packageName);
5464 }
5465 if (succeeded) {
5466 // invoke DeviceStorageMonitor's update method to clear any notifications
5467 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5468 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5469 if (dsm != null) {
5470 dsm.updateMemory();
5471 }
5472 }
5473 if(observer != null) {
5474 try {
5475 observer.onRemoveCompleted(packageName, succeeded);
5476 } catch (RemoteException e) {
5477 Log.i(TAG, "Observer no longer exists.");
5478 }
5479 } //end if observer
5480 } //end run
5481 });
5482 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 private boolean clearApplicationUserDataLI(String packageName) {
5485 if (packageName == null) {
5486 Log.w(TAG, "Attempt to delete null packageName.");
5487 return false;
5488 }
5489 PackageParser.Package p;
5490 boolean dataOnly = false;
5491 synchronized (mPackages) {
5492 p = mPackages.get(packageName);
5493 if(p == null) {
5494 dataOnly = true;
5495 PackageSetting ps = mSettings.mPackages.get(packageName);
5496 if((ps == null) || (ps.pkg == null)) {
5497 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5498 return false;
5499 }
5500 p = ps.pkg;
5501 }
5502 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005503 boolean useEncryptedFSDir = false;
5504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005505 if(!dataOnly) {
5506 //need to check this only for fully installed applications
5507 if (p == null) {
5508 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5509 return false;
5510 }
5511 final ApplicationInfo applicationInfo = p.applicationInfo;
5512 if (applicationInfo == null) {
5513 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5514 return false;
5515 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005516 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 }
5518 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005519 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520 if (retCode < 0) {
5521 Log.w(TAG, "Couldn't remove cache files for package: "
5522 + packageName);
5523 return false;
5524 }
5525 }
5526 return true;
5527 }
5528
5529 public void deleteApplicationCacheFiles(final String packageName,
5530 final IPackageDataObserver observer) {
5531 mContext.enforceCallingOrSelfPermission(
5532 android.Manifest.permission.DELETE_CACHE_FILES, null);
5533 // Queue up an async operation since the package deletion may take a little while.
5534 mHandler.post(new Runnable() {
5535 public void run() {
5536 mHandler.removeCallbacks(this);
5537 final boolean succeded;
5538 synchronized (mInstallLock) {
5539 succeded = deleteApplicationCacheFilesLI(packageName);
5540 }
5541 if(observer != null) {
5542 try {
5543 observer.onRemoveCompleted(packageName, succeded);
5544 } catch (RemoteException e) {
5545 Log.i(TAG, "Observer no longer exists.");
5546 }
5547 } //end if observer
5548 } //end run
5549 });
5550 }
5551
5552 private boolean deleteApplicationCacheFilesLI(String packageName) {
5553 if (packageName == null) {
5554 Log.w(TAG, "Attempt to delete null packageName.");
5555 return false;
5556 }
5557 PackageParser.Package p;
5558 synchronized (mPackages) {
5559 p = mPackages.get(packageName);
5560 }
5561 if (p == null) {
5562 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5563 return false;
5564 }
5565 final ApplicationInfo applicationInfo = p.applicationInfo;
5566 if (applicationInfo == null) {
5567 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5568 return false;
5569 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005570 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005572 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 if (retCode < 0) {
5574 Log.w(TAG, "Couldn't remove cache files for package: "
5575 + packageName);
5576 return false;
5577 }
5578 }
5579 return true;
5580 }
5581
5582 public void getPackageSizeInfo(final String packageName,
5583 final IPackageStatsObserver observer) {
5584 mContext.enforceCallingOrSelfPermission(
5585 android.Manifest.permission.GET_PACKAGE_SIZE, null);
5586 // Queue up an async operation since the package deletion may take a little while.
5587 mHandler.post(new Runnable() {
5588 public void run() {
5589 mHandler.removeCallbacks(this);
5590 PackageStats lStats = new PackageStats(packageName);
5591 final boolean succeded;
5592 synchronized (mInstallLock) {
5593 succeded = getPackageSizeInfoLI(packageName, lStats);
5594 }
5595 if(observer != null) {
5596 try {
5597 observer.onGetStatsCompleted(lStats, succeded);
5598 } catch (RemoteException e) {
5599 Log.i(TAG, "Observer no longer exists.");
5600 }
5601 } //end if observer
5602 } //end run
5603 });
5604 }
5605
5606 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
5607 if (packageName == null) {
5608 Log.w(TAG, "Attempt to get size of null packageName.");
5609 return false;
5610 }
5611 PackageParser.Package p;
5612 boolean dataOnly = false;
5613 synchronized (mPackages) {
5614 p = mPackages.get(packageName);
5615 if(p == null) {
5616 dataOnly = true;
5617 PackageSetting ps = mSettings.mPackages.get(packageName);
5618 if((ps == null) || (ps.pkg == null)) {
5619 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5620 return false;
5621 }
5622 p = ps.pkg;
5623 }
5624 }
5625 String publicSrcDir = null;
5626 if(!dataOnly) {
5627 final ApplicationInfo applicationInfo = p.applicationInfo;
5628 if (applicationInfo == null) {
5629 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5630 return false;
5631 }
5632 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
5633 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005634 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 if (mInstaller != null) {
5636 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08005637 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638 if (res < 0) {
5639 return false;
5640 } else {
5641 return true;
5642 }
5643 }
5644 return true;
5645 }
5646
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005648 public void addPackageToPreferred(String packageName) {
5649 mContext.enforceCallingOrSelfPermission(
5650 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005651 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005652 }
5653
5654 public void removePackageFromPreferred(String packageName) {
5655 mContext.enforceCallingOrSelfPermission(
5656 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005657 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 }
5659
5660 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005661 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 }
5663
5664 public void addPreferredActivity(IntentFilter filter, int match,
5665 ComponentName[] set, ComponentName activity) {
5666 mContext.enforceCallingOrSelfPermission(
5667 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5668
5669 synchronized (mPackages) {
5670 Log.i(TAG, "Adding preferred activity " + activity + ":");
5671 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5672 mSettings.mPreferredActivities.addFilter(
5673 new PreferredActivity(filter, match, set, activity));
5674 mSettings.writeLP();
5675 }
5676 }
5677
Satish Sampath8dbe6122009-06-02 23:35:54 +01005678 public void replacePreferredActivity(IntentFilter filter, int match,
5679 ComponentName[] set, ComponentName activity) {
5680 mContext.enforceCallingOrSelfPermission(
5681 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5682 if (filter.countActions() != 1) {
5683 throw new IllegalArgumentException(
5684 "replacePreferredActivity expects filter to have only 1 action.");
5685 }
5686 if (filter.countCategories() != 1) {
5687 throw new IllegalArgumentException(
5688 "replacePreferredActivity expects filter to have only 1 category.");
5689 }
5690 if (filter.countDataAuthorities() != 0
5691 || filter.countDataPaths() != 0
5692 || filter.countDataSchemes() != 0
5693 || filter.countDataTypes() != 0) {
5694 throw new IllegalArgumentException(
5695 "replacePreferredActivity expects filter to have no data authorities, " +
5696 "paths, schemes or types.");
5697 }
5698 synchronized (mPackages) {
5699 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5700 String action = filter.getAction(0);
5701 String category = filter.getCategory(0);
5702 while (it.hasNext()) {
5703 PreferredActivity pa = it.next();
5704 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5705 it.remove();
5706 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5707 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5708 }
5709 }
5710 addPreferredActivity(filter, match, set, activity);
5711 }
5712 }
5713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005714 public void clearPackagePreferredActivities(String packageName) {
5715 mContext.enforceCallingOrSelfPermission(
5716 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5717
5718 synchronized (mPackages) {
5719 if (clearPackagePreferredActivitiesLP(packageName)) {
5720 mSettings.writeLP();
5721 }
5722 }
5723 }
5724
5725 boolean clearPackagePreferredActivitiesLP(String packageName) {
5726 boolean changed = false;
5727 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5728 while (it.hasNext()) {
5729 PreferredActivity pa = it.next();
5730 if (pa.mActivity.getPackageName().equals(packageName)) {
5731 it.remove();
5732 changed = true;
5733 }
5734 }
5735 return changed;
5736 }
5737
5738 public int getPreferredActivities(List<IntentFilter> outFilters,
5739 List<ComponentName> outActivities, String packageName) {
5740
5741 int num = 0;
5742 synchronized (mPackages) {
5743 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5744 while (it.hasNext()) {
5745 PreferredActivity pa = it.next();
5746 if (packageName == null
5747 || pa.mActivity.getPackageName().equals(packageName)) {
5748 if (outFilters != null) {
5749 outFilters.add(new IntentFilter(pa));
5750 }
5751 if (outActivities != null) {
5752 outActivities.add(pa.mActivity);
5753 }
5754 }
5755 }
5756 }
5757
5758 return num;
5759 }
5760
5761 public void setApplicationEnabledSetting(String appPackageName,
5762 int newState, int flags) {
5763 setEnabledSetting(appPackageName, null, newState, flags);
5764 }
5765
5766 public void setComponentEnabledSetting(ComponentName componentName,
5767 int newState, int flags) {
5768 setEnabledSetting(componentName.getPackageName(),
5769 componentName.getClassName(), newState, flags);
5770 }
5771
5772 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005773 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005774 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5775 || newState == COMPONENT_ENABLED_STATE_ENABLED
5776 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5777 throw new IllegalArgumentException("Invalid new component state: "
5778 + newState);
5779 }
5780 PackageSetting pkgSetting;
5781 final int uid = Binder.getCallingUid();
5782 final int permission = mContext.checkCallingPermission(
5783 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5784 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005785 boolean sendNow = false;
5786 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005787 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005788 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005789 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005791 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005793 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005795 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005796 }
5797 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005798 "Unknown component: " + packageName
5799 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 }
5801 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5802 throw new SecurityException(
5803 "Permission Denial: attempt to change component state from pid="
5804 + Binder.getCallingPid()
5805 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5806 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005807 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 // We're dealing with an application/package level state change
5809 pkgSetting.enabled = newState;
5810 } else {
5811 // We're dealing with a component level state change
5812 switch (newState) {
5813 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005814 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005815 break;
5816 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005817 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 break;
5819 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005820 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 break;
5822 default:
5823 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005824 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005825 }
5826 }
5827 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005828 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005829 components = mPendingBroadcasts.get(packageName);
5830 boolean newPackage = components == null;
5831 if (newPackage) {
5832 components = new ArrayList<String>();
5833 }
5834 if (!components.contains(componentName)) {
5835 components.add(componentName);
5836 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005837 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5838 sendNow = true;
5839 // Purge entry from pending broadcast list if another one exists already
5840 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005841 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005842 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005843 if (newPackage) {
5844 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005845 }
5846 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5847 // Schedule a message
5848 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5849 }
5850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 long callingId = Binder.clearCallingIdentity();
5854 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005855 if (sendNow) {
5856 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005857 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005859 } finally {
5860 Binder.restoreCallingIdentity(callingId);
5861 }
5862 }
5863
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005864 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005865 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
5866 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
5867 + " components=" + componentNames);
5868 Bundle extras = new Bundle(4);
5869 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
5870 String nameList[] = new String[componentNames.size()];
5871 componentNames.toArray(nameList);
5872 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005873 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5874 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005875 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005876 }
5877
Jacek Surazski65e13172009-04-28 15:26:38 +02005878 public String getInstallerPackageName(String packageName) {
5879 synchronized (mPackages) {
5880 PackageSetting pkg = mSettings.mPackages.get(packageName);
5881 if (pkg == null) {
5882 throw new IllegalArgumentException("Unknown package: " + packageName);
5883 }
5884 return pkg.installerPackageName;
5885 }
5886 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 public int getApplicationEnabledSetting(String appPackageName) {
5889 synchronized (mPackages) {
5890 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5891 if (pkg == null) {
5892 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5893 }
5894 return pkg.enabled;
5895 }
5896 }
5897
5898 public int getComponentEnabledSetting(ComponentName componentName) {
5899 synchronized (mPackages) {
5900 final String packageNameStr = componentName.getPackageName();
5901 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5902 if (pkg == null) {
5903 throw new IllegalArgumentException("Unknown component: " + componentName);
5904 }
5905 final String classNameStr = componentName.getClassName();
5906 return pkg.currentEnabledStateLP(classNameStr);
5907 }
5908 }
5909
5910 public void enterSafeMode() {
5911 if (!mSystemReady) {
5912 mSafeMode = true;
5913 }
5914 }
5915
5916 public void systemReady() {
5917 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005918
5919 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005920 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005921 mContext.getContentResolver(),
5922 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005923 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005924 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005925 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005927 }
5928
5929 public boolean isSafeMode() {
5930 return mSafeMode;
5931 }
5932
5933 public boolean hasSystemUidErrors() {
5934 return mHasSystemUidErrors;
5935 }
5936
5937 static String arrayToString(int[] array) {
5938 StringBuffer buf = new StringBuffer(128);
5939 buf.append('[');
5940 if (array != null) {
5941 for (int i=0; i<array.length; i++) {
5942 if (i > 0) buf.append(", ");
5943 buf.append(array[i]);
5944 }
5945 }
5946 buf.append(']');
5947 return buf.toString();
5948 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005950 @Override
5951 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5952 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5953 != PackageManager.PERMISSION_GRANTED) {
5954 pw.println("Permission Denial: can't dump ActivityManager from from pid="
5955 + Binder.getCallingPid()
5956 + ", uid=" + Binder.getCallingUid()
5957 + " without permission "
5958 + android.Manifest.permission.DUMP);
5959 return;
5960 }
5961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005962 synchronized (mPackages) {
5963 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005964 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005965 pw.println(" ");
5966 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005967 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005968 pw.println(" ");
5969 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005970 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005971 pw.println(" ");
5972 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005973 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975 pw.println("Permissions:");
5976 {
5977 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005978 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
5979 pw.print(Integer.toHexString(System.identityHashCode(p)));
5980 pw.println("):");
5981 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
5982 pw.print(" uid="); pw.print(p.uid);
5983 pw.print(" gids="); pw.print(arrayToString(p.gids));
5984 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 }
5986 }
5987 pw.println(" ");
5988 pw.println("Packages:");
5989 {
5990 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005991 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
5992 pw.print(Integer.toHexString(System.identityHashCode(ps)));
5993 pw.println("):");
5994 pw.print(" userId="); pw.print(ps.userId);
5995 pw.print(" gids="); pw.println(arrayToString(ps.gids));
5996 pw.print(" sharedUser="); pw.println(ps.sharedUser);
5997 pw.print(" pkg="); pw.println(ps.pkg);
5998 pw.print(" codePath="); pw.println(ps.codePathString);
5999 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006000 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006001 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006002 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006003 pw.print(" supportsScreens=[");
6004 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006005 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006006 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006007 if (!first) pw.print(", ");
6008 first = false;
6009 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006011 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006012 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006013 if (!first) pw.print(", ");
6014 first = false;
6015 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006016 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006017 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006018 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006019 if (!first) pw.print(", ");
6020 first = false;
6021 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006022 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006023 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006024 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006025 if (!first) pw.print(", ");
6026 first = false;
6027 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006028 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006029 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006030 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6031 if (!first) pw.print(", ");
6032 first = false;
6033 pw.print("anyDensity");
6034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006036 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006037 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6038 pw.print(" signatures="); pw.println(ps.signatures);
6039 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6040 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6041 pw.print(" installStatus="); pw.print(ps.installStatus);
6042 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 if (ps.disabledComponents.size() > 0) {
6044 pw.println(" disabledComponents:");
6045 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006046 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006047 }
6048 }
6049 if (ps.enabledComponents.size() > 0) {
6050 pw.println(" enabledComponents:");
6051 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006052 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006053 }
6054 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006055 if (ps.grantedPermissions.size() > 0) {
6056 pw.println(" grantedPermissions:");
6057 for (String s : ps.grantedPermissions) {
6058 pw.print(" "); pw.println(s);
6059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006061 if (ps.loadedPermissions.size() > 0) {
6062 pw.println(" loadedPermissions:");
6063 for (String s : ps.loadedPermissions) {
6064 pw.print(" "); pw.println(s);
6065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 }
6067 }
6068 }
6069 pw.println(" ");
6070 pw.println("Shared Users:");
6071 {
6072 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006073 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6074 pw.print(Integer.toHexString(System.identityHashCode(su)));
6075 pw.println("):");
6076 pw.print(" userId="); pw.print(su.userId);
6077 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 pw.println(" grantedPermissions:");
6079 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006080 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 }
6082 pw.println(" loadedPermissions:");
6083 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006084 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 }
6086 }
6087 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 pw.println(" ");
6090 pw.println("Settings parse messages:");
6091 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006092
6093 pw.println(" ");
6094 pw.println("Package warning messages:");
6095 File fname = getSettingsProblemFile();
6096 FileInputStream in;
6097 try {
6098 in = new FileInputStream(fname);
6099 int avail = in.available();
6100 byte[] data = new byte[avail];
6101 in.read(data);
6102 pw.println(new String(data));
6103 } catch (FileNotFoundException e) {
6104 } catch (IOException e) {
6105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006106 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006107
6108 synchronized (mProviders) {
6109 pw.println(" ");
6110 pw.println("Registered ContentProviders:");
6111 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006112 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006113 pw.println(p.toString());
6114 }
6115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 }
6117
6118 static final class BasePermission {
6119 final static int TYPE_NORMAL = 0;
6120 final static int TYPE_BUILTIN = 1;
6121 final static int TYPE_DYNAMIC = 2;
6122
6123 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006124 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 final int type;
6126 PackageParser.Permission perm;
6127 PermissionInfo pendingInfo;
6128 int uid;
6129 int[] gids;
6130
6131 BasePermission(String _name, String _sourcePackage, int _type) {
6132 name = _name;
6133 sourcePackage = _sourcePackage;
6134 type = _type;
6135 }
6136 }
6137
6138 static class PackageSignatures {
6139 private Signature[] mSignatures;
6140
6141 PackageSignatures(Signature[] sigs) {
6142 assignSignatures(sigs);
6143 }
6144
6145 PackageSignatures() {
6146 }
6147
6148 void writeXml(XmlSerializer serializer, String tagName,
6149 ArrayList<Signature> pastSignatures) throws IOException {
6150 if (mSignatures == null) {
6151 return;
6152 }
6153 serializer.startTag(null, tagName);
6154 serializer.attribute(null, "count",
6155 Integer.toString(mSignatures.length));
6156 for (int i=0; i<mSignatures.length; i++) {
6157 serializer.startTag(null, "cert");
6158 final Signature sig = mSignatures[i];
6159 final int sigHash = sig.hashCode();
6160 final int numPast = pastSignatures.size();
6161 int j;
6162 for (j=0; j<numPast; j++) {
6163 Signature pastSig = pastSignatures.get(j);
6164 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6165 serializer.attribute(null, "index", Integer.toString(j));
6166 break;
6167 }
6168 }
6169 if (j >= numPast) {
6170 pastSignatures.add(sig);
6171 serializer.attribute(null, "index", Integer.toString(numPast));
6172 serializer.attribute(null, "key", sig.toCharsString());
6173 }
6174 serializer.endTag(null, "cert");
6175 }
6176 serializer.endTag(null, tagName);
6177 }
6178
6179 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6180 throws IOException, XmlPullParserException {
6181 String countStr = parser.getAttributeValue(null, "count");
6182 if (countStr == null) {
6183 reportSettingsProblem(Log.WARN,
6184 "Error in package manager settings: <signatures> has"
6185 + " no count at " + parser.getPositionDescription());
6186 XmlUtils.skipCurrentTag(parser);
6187 }
6188 final int count = Integer.parseInt(countStr);
6189 mSignatures = new Signature[count];
6190 int pos = 0;
6191
6192 int outerDepth = parser.getDepth();
6193 int type;
6194 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6195 && (type != XmlPullParser.END_TAG
6196 || parser.getDepth() > outerDepth)) {
6197 if (type == XmlPullParser.END_TAG
6198 || type == XmlPullParser.TEXT) {
6199 continue;
6200 }
6201
6202 String tagName = parser.getName();
6203 if (tagName.equals("cert")) {
6204 if (pos < count) {
6205 String index = parser.getAttributeValue(null, "index");
6206 if (index != null) {
6207 try {
6208 int idx = Integer.parseInt(index);
6209 String key = parser.getAttributeValue(null, "key");
6210 if (key == null) {
6211 if (idx >= 0 && idx < pastSignatures.size()) {
6212 Signature sig = pastSignatures.get(idx);
6213 if (sig != null) {
6214 mSignatures[pos] = pastSignatures.get(idx);
6215 pos++;
6216 } else {
6217 reportSettingsProblem(Log.WARN,
6218 "Error in package manager settings: <cert> "
6219 + "index " + index + " is not defined at "
6220 + parser.getPositionDescription());
6221 }
6222 } else {
6223 reportSettingsProblem(Log.WARN,
6224 "Error in package manager settings: <cert> "
6225 + "index " + index + " is out of bounds at "
6226 + parser.getPositionDescription());
6227 }
6228 } else {
6229 while (pastSignatures.size() <= idx) {
6230 pastSignatures.add(null);
6231 }
6232 Signature sig = new Signature(key);
6233 pastSignatures.set(idx, sig);
6234 mSignatures[pos] = sig;
6235 pos++;
6236 }
6237 } catch (NumberFormatException e) {
6238 reportSettingsProblem(Log.WARN,
6239 "Error in package manager settings: <cert> "
6240 + "index " + index + " is not a number at "
6241 + parser.getPositionDescription());
6242 }
6243 } else {
6244 reportSettingsProblem(Log.WARN,
6245 "Error in package manager settings: <cert> has"
6246 + " no index at " + parser.getPositionDescription());
6247 }
6248 } else {
6249 reportSettingsProblem(Log.WARN,
6250 "Error in package manager settings: too "
6251 + "many <cert> tags, expected " + count
6252 + " at " + parser.getPositionDescription());
6253 }
6254 } else {
6255 reportSettingsProblem(Log.WARN,
6256 "Unknown element under <cert>: "
6257 + parser.getName());
6258 }
6259 XmlUtils.skipCurrentTag(parser);
6260 }
6261
6262 if (pos < count) {
6263 // Should never happen -- there is an error in the written
6264 // settings -- but if it does we don't want to generate
6265 // a bad array.
6266 Signature[] newSigs = new Signature[pos];
6267 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6268 mSignatures = newSigs;
6269 }
6270 }
6271
6272 /**
6273 * If any of the given 'sigs' is contained in the existing signatures,
6274 * then completely replace the current signatures with the ones in
6275 * 'sigs'. This is used for updating an existing package to a newly
6276 * installed version.
6277 */
6278 boolean updateSignatures(Signature[] sigs, boolean update) {
6279 if (mSignatures == null) {
6280 if (update) {
6281 assignSignatures(sigs);
6282 }
6283 return true;
6284 }
6285 if (sigs == null) {
6286 return false;
6287 }
6288
6289 for (int i=0; i<sigs.length; i++) {
6290 Signature sig = sigs[i];
6291 for (int j=0; j<mSignatures.length; j++) {
6292 if (mSignatures[j].equals(sig)) {
6293 if (update) {
6294 assignSignatures(sigs);
6295 }
6296 return true;
6297 }
6298 }
6299 }
6300 return false;
6301 }
6302
6303 /**
6304 * If any of the given 'sigs' is contained in the existing signatures,
6305 * then add in any new signatures found in 'sigs'. This is used for
6306 * including a new package into an existing shared user id.
6307 */
6308 boolean mergeSignatures(Signature[] sigs, boolean update) {
6309 if (mSignatures == null) {
6310 if (update) {
6311 assignSignatures(sigs);
6312 }
6313 return true;
6314 }
6315 if (sigs == null) {
6316 return false;
6317 }
6318
6319 Signature[] added = null;
6320 int addedCount = 0;
6321 boolean haveMatch = false;
6322 for (int i=0; i<sigs.length; i++) {
6323 Signature sig = sigs[i];
6324 boolean found = false;
6325 for (int j=0; j<mSignatures.length; j++) {
6326 if (mSignatures[j].equals(sig)) {
6327 found = true;
6328 haveMatch = true;
6329 break;
6330 }
6331 }
6332
6333 if (!found) {
6334 if (added == null) {
6335 added = new Signature[sigs.length];
6336 }
6337 added[i] = sig;
6338 addedCount++;
6339 }
6340 }
6341
6342 if (!haveMatch) {
6343 // Nothing matched -- reject the new signatures.
6344 return false;
6345 }
6346 if (added == null) {
6347 // Completely matched -- nothing else to do.
6348 return true;
6349 }
6350
6351 // Add additional signatures in.
6352 if (update) {
6353 Signature[] total = new Signature[addedCount+mSignatures.length];
6354 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6355 int j = mSignatures.length;
6356 for (int i=0; i<added.length; i++) {
6357 if (added[i] != null) {
6358 total[j] = added[i];
6359 j++;
6360 }
6361 }
6362 mSignatures = total;
6363 }
6364 return true;
6365 }
6366
6367 private void assignSignatures(Signature[] sigs) {
6368 if (sigs == null) {
6369 mSignatures = null;
6370 return;
6371 }
6372 mSignatures = new Signature[sigs.length];
6373 for (int i=0; i<sigs.length; i++) {
6374 mSignatures[i] = sigs[i];
6375 }
6376 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 @Override
6379 public String toString() {
6380 StringBuffer buf = new StringBuffer(128);
6381 buf.append("PackageSignatures{");
6382 buf.append(Integer.toHexString(System.identityHashCode(this)));
6383 buf.append(" [");
6384 if (mSignatures != null) {
6385 for (int i=0; i<mSignatures.length; i++) {
6386 if (i > 0) buf.append(", ");
6387 buf.append(Integer.toHexString(
6388 System.identityHashCode(mSignatures[i])));
6389 }
6390 }
6391 buf.append("]}");
6392 return buf.toString();
6393 }
6394 }
6395
6396 static class PreferredActivity extends IntentFilter {
6397 final int mMatch;
6398 final String[] mSetPackages;
6399 final String[] mSetClasses;
6400 final String[] mSetComponents;
6401 final ComponentName mActivity;
6402 final String mShortActivity;
6403 String mParseError;
6404
6405 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6406 ComponentName activity) {
6407 super(filter);
6408 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6409 mActivity = activity;
6410 mShortActivity = activity.flattenToShortString();
6411 mParseError = null;
6412 if (set != null) {
6413 final int N = set.length;
6414 String[] myPackages = new String[N];
6415 String[] myClasses = new String[N];
6416 String[] myComponents = new String[N];
6417 for (int i=0; i<N; i++) {
6418 ComponentName cn = set[i];
6419 if (cn == null) {
6420 mSetPackages = null;
6421 mSetClasses = null;
6422 mSetComponents = null;
6423 return;
6424 }
6425 myPackages[i] = cn.getPackageName().intern();
6426 myClasses[i] = cn.getClassName().intern();
6427 myComponents[i] = cn.flattenToShortString().intern();
6428 }
6429 mSetPackages = myPackages;
6430 mSetClasses = myClasses;
6431 mSetComponents = myComponents;
6432 } else {
6433 mSetPackages = null;
6434 mSetClasses = null;
6435 mSetComponents = null;
6436 }
6437 }
6438
6439 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6440 IOException {
6441 mShortActivity = parser.getAttributeValue(null, "name");
6442 mActivity = ComponentName.unflattenFromString(mShortActivity);
6443 if (mActivity == null) {
6444 mParseError = "Bad activity name " + mShortActivity;
6445 }
6446 String matchStr = parser.getAttributeValue(null, "match");
6447 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6448 String setCountStr = parser.getAttributeValue(null, "set");
6449 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6450
6451 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6452 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6453 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6454
6455 int setPos = 0;
6456
6457 int outerDepth = parser.getDepth();
6458 int type;
6459 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6460 && (type != XmlPullParser.END_TAG
6461 || parser.getDepth() > outerDepth)) {
6462 if (type == XmlPullParser.END_TAG
6463 || type == XmlPullParser.TEXT) {
6464 continue;
6465 }
6466
6467 String tagName = parser.getName();
6468 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6469 // + parser.getDepth() + " tag=" + tagName);
6470 if (tagName.equals("set")) {
6471 String name = parser.getAttributeValue(null, "name");
6472 if (name == null) {
6473 if (mParseError == null) {
6474 mParseError = "No name in set tag in preferred activity "
6475 + mShortActivity;
6476 }
6477 } else if (setPos >= setCount) {
6478 if (mParseError == null) {
6479 mParseError = "Too many set tags in preferred activity "
6480 + mShortActivity;
6481 }
6482 } else {
6483 ComponentName cn = ComponentName.unflattenFromString(name);
6484 if (cn == null) {
6485 if (mParseError == null) {
6486 mParseError = "Bad set name " + name + " in preferred activity "
6487 + mShortActivity;
6488 }
6489 } else {
6490 myPackages[setPos] = cn.getPackageName();
6491 myClasses[setPos] = cn.getClassName();
6492 myComponents[setPos] = name;
6493 setPos++;
6494 }
6495 }
6496 XmlUtils.skipCurrentTag(parser);
6497 } else if (tagName.equals("filter")) {
6498 //Log.i(TAG, "Starting to parse filter...");
6499 readFromXml(parser);
6500 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6501 // + parser.getDepth() + " tag=" + parser.getName());
6502 } else {
6503 reportSettingsProblem(Log.WARN,
6504 "Unknown element under <preferred-activities>: "
6505 + parser.getName());
6506 XmlUtils.skipCurrentTag(parser);
6507 }
6508 }
6509
6510 if (setPos != setCount) {
6511 if (mParseError == null) {
6512 mParseError = "Not enough set tags (expected " + setCount
6513 + " but found " + setPos + ") in " + mShortActivity;
6514 }
6515 }
6516
6517 mSetPackages = myPackages;
6518 mSetClasses = myClasses;
6519 mSetComponents = myComponents;
6520 }
6521
6522 public void writeToXml(XmlSerializer serializer) throws IOException {
6523 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6524 serializer.attribute(null, "name", mShortActivity);
6525 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6526 serializer.attribute(null, "set", Integer.toString(NS));
6527 for (int s=0; s<NS; s++) {
6528 serializer.startTag(null, "set");
6529 serializer.attribute(null, "name", mSetComponents[s]);
6530 serializer.endTag(null, "set");
6531 }
6532 serializer.startTag(null, "filter");
6533 super.writeToXml(serializer);
6534 serializer.endTag(null, "filter");
6535 }
6536
6537 boolean sameSet(List<ResolveInfo> query, int priority) {
6538 if (mSetPackages == null) return false;
6539 final int NQ = query.size();
6540 final int NS = mSetPackages.length;
6541 int numMatch = 0;
6542 for (int i=0; i<NQ; i++) {
6543 ResolveInfo ri = query.get(i);
6544 if (ri.priority != priority) continue;
6545 ActivityInfo ai = ri.activityInfo;
6546 boolean good = false;
6547 for (int j=0; j<NS; j++) {
6548 if (mSetPackages[j].equals(ai.packageName)
6549 && mSetClasses[j].equals(ai.name)) {
6550 numMatch++;
6551 good = true;
6552 break;
6553 }
6554 }
6555 if (!good) return false;
6556 }
6557 return numMatch == NS;
6558 }
6559 }
6560
6561 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006562 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006564 HashSet<String> grantedPermissions = new HashSet<String>();
6565 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006567 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006569 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08006570 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
6571 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
6572 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006573 }
6574 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006576 /**
6577 * Settings base class for pending and resolved classes.
6578 */
6579 static class PackageSettingBase extends GrantedPermissions {
6580 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006581 File codePath;
6582 String codePathString;
6583 File resourcePath;
6584 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 private long timeStamp;
6586 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006587 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006589 boolean uidError;
6590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006591 PackageSignatures signatures = new PackageSignatures();
6592
6593 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 /* Explicitly disabled components */
6596 HashSet<String> disabledComponents = new HashSet<String>(0);
6597 /* Explicitly enabled components */
6598 HashSet<String> enabledComponents = new HashSet<String>(0);
6599 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6600 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006601
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006602 PackageSettingBase origPackage;
6603
Jacek Surazski65e13172009-04-28 15:26:38 +02006604 /* package name of the app that installed this package */
6605 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606
6607 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006608 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 super(pkgFlags);
6610 this.name = name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006611 init(codePath, resourcePath, pVersionCode);
6612 }
6613
6614 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006615 this.codePath = codePath;
6616 this.codePathString = codePath.toString();
6617 this.resourcePath = resourcePath;
6618 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006619 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006621
Jacek Surazski65e13172009-04-28 15:26:38 +02006622 public void setInstallerPackageName(String packageName) {
6623 installerPackageName = packageName;
6624 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006625
Jacek Surazski65e13172009-04-28 15:26:38 +02006626 String getInstallerPackageName() {
6627 return installerPackageName;
6628 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006630 public void setInstallStatus(int newStatus) {
6631 installStatus = newStatus;
6632 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006634 public int getInstallStatus() {
6635 return installStatus;
6636 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006638 public void setTimeStamp(long newStamp) {
6639 if (newStamp != timeStamp) {
6640 timeStamp = newStamp;
6641 timeStampString = Long.toString(newStamp);
6642 }
6643 }
6644
6645 public void setTimeStamp(long newStamp, String newStampStr) {
6646 timeStamp = newStamp;
6647 timeStampString = newStampStr;
6648 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 public long getTimeStamp() {
6651 return timeStamp;
6652 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006654 public String getTimeStampStr() {
6655 return timeStampString;
6656 }
6657
6658 public void copyFrom(PackageSettingBase base) {
6659 grantedPermissions = base.grantedPermissions;
6660 gids = base.gids;
6661 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 timeStamp = base.timeStamp;
6664 timeStampString = base.timeStampString;
6665 signatures = base.signatures;
6666 permissionsFixed = base.permissionsFixed;
6667 disabledComponents = base.disabledComponents;
6668 enabledComponents = base.enabledComponents;
6669 enabled = base.enabled;
6670 installStatus = base.installStatus;
6671 }
6672
6673 void enableComponentLP(String componentClassName) {
6674 disabledComponents.remove(componentClassName);
6675 enabledComponents.add(componentClassName);
6676 }
6677
6678 void disableComponentLP(String componentClassName) {
6679 enabledComponents.remove(componentClassName);
6680 disabledComponents.add(componentClassName);
6681 }
6682
6683 void restoreComponentLP(String componentClassName) {
6684 enabledComponents.remove(componentClassName);
6685 disabledComponents.remove(componentClassName);
6686 }
6687
6688 int currentEnabledStateLP(String componentName) {
6689 if (enabledComponents.contains(componentName)) {
6690 return COMPONENT_ENABLED_STATE_ENABLED;
6691 } else if (disabledComponents.contains(componentName)) {
6692 return COMPONENT_ENABLED_STATE_DISABLED;
6693 } else {
6694 return COMPONENT_ENABLED_STATE_DEFAULT;
6695 }
6696 }
6697 }
6698
6699 /**
6700 * Settings data for a particular package we know about.
6701 */
6702 static final class PackageSetting extends PackageSettingBase {
6703 int userId;
6704 PackageParser.Package pkg;
6705 SharedUserSetting sharedUser;
6706
6707 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006708 int pVersionCode, int pkgFlags) {
6709 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 @Override
6713 public String toString() {
6714 return "PackageSetting{"
6715 + Integer.toHexString(System.identityHashCode(this))
6716 + " " + name + "/" + userId + "}";
6717 }
6718 }
6719
6720 /**
6721 * Settings data for a particular shared user ID we know about.
6722 */
6723 static final class SharedUserSetting extends GrantedPermissions {
6724 final String name;
6725 int userId;
6726 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6727 final PackageSignatures signatures = new PackageSignatures();
6728
6729 SharedUserSetting(String _name, int _pkgFlags) {
6730 super(_pkgFlags);
6731 name = _name;
6732 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 @Override
6735 public String toString() {
6736 return "SharedUserSetting{"
6737 + Integer.toHexString(System.identityHashCode(this))
6738 + " " + name + "/" + userId + "}";
6739 }
6740 }
6741
6742 /**
6743 * Holds information about dynamic settings.
6744 */
6745 private static final class Settings {
6746 private final File mSettingsFilename;
6747 private final File mBackupSettingsFilename;
6748 private final HashMap<String, PackageSetting> mPackages =
6749 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 // List of replaced system applications
6751 final HashMap<String, PackageSetting> mDisabledSysPackages =
6752 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 // The user's preferred activities associated with particular intent
6755 // filters.
6756 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6757 new IntentResolver<PreferredActivity, PreferredActivity>() {
6758 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006759 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006761 out.print(prefix); out.print(
6762 Integer.toHexString(System.identityHashCode(filter)));
6763 out.print(' ');
6764 out.print(filter.mActivity.flattenToShortString());
6765 out.print(" match=0x");
6766 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006768 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006770 out.print(prefix); out.print(" ");
6771 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 }
6773 }
6774 }
6775 };
6776 private final HashMap<String, SharedUserSetting> mSharedUsers =
6777 new HashMap<String, SharedUserSetting>();
6778 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6779 private final SparseArray<Object> mOtherUserIds =
6780 new SparseArray<Object>();
6781
6782 // For reading/writing settings file.
6783 private final ArrayList<Signature> mPastSignatures =
6784 new ArrayList<Signature>();
6785
6786 // Mapping from permission names to info about them.
6787 final HashMap<String, BasePermission> mPermissions =
6788 new HashMap<String, BasePermission>();
6789
6790 // Mapping from permission tree names to info about them.
6791 final HashMap<String, BasePermission> mPermissionTrees =
6792 new HashMap<String, BasePermission>();
6793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006794 private final StringBuilder mReadMessages = new StringBuilder();
6795
6796 private static final class PendingPackage extends PackageSettingBase {
6797 final int sharedId;
6798
6799 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006800 int sharedId, int pVersionCode, int pkgFlags) {
6801 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 this.sharedId = sharedId;
6803 }
6804 }
6805 private final ArrayList<PendingPackage> mPendingPackages
6806 = new ArrayList<PendingPackage>();
6807
6808 Settings() {
6809 File dataDir = Environment.getDataDirectory();
6810 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08006811 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
6812 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08006814 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 FileUtils.setPermissions(systemDir.toString(),
6816 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6817 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6818 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08006819 FileUtils.setPermissions(systemSecureDir.toString(),
6820 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6821 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6822 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006823 mSettingsFilename = new File(systemDir, "packages.xml");
6824 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6825 }
6826
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006827 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006828 SharedUserSetting sharedUser, File codePath, File resourcePath,
6829 int pkgFlags, boolean create, boolean add) {
6830 final String name = pkg.packageName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006831 PackageSetting p = getPackageLP(name, origPackage, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006832 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006833 return p;
6834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006835
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006836 PackageSetting peekPackageLP(String name) {
6837 return mPackages.get(name);
6838 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 PackageSetting p = mPackages.get(name);
6840 if (p != null && p.codePath.getPath().equals(codePath)) {
6841 return p;
6842 }
6843 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006844 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 void setInstallStatus(String pkgName, int status) {
6848 PackageSetting p = mPackages.get(pkgName);
6849 if(p != null) {
6850 if(p.getInstallStatus() != status) {
6851 p.setInstallStatus(status);
6852 }
6853 }
6854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006855
Jacek Surazski65e13172009-04-28 15:26:38 +02006856 void setInstallerPackageName(String pkgName,
6857 String installerPkgName) {
6858 PackageSetting p = mPackages.get(pkgName);
6859 if(p != null) {
6860 p.setInstallerPackageName(installerPkgName);
6861 }
6862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006863
Jacek Surazski65e13172009-04-28 15:26:38 +02006864 String getInstallerPackageName(String pkgName) {
6865 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006866 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02006867 }
6868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006869 int getInstallStatus(String pkgName) {
6870 PackageSetting p = mPackages.get(pkgName);
6871 if(p != null) {
6872 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 return -1;
6875 }
6876
6877 SharedUserSetting getSharedUserLP(String name,
6878 int pkgFlags, boolean create) {
6879 SharedUserSetting s = mSharedUsers.get(name);
6880 if (s == null) {
6881 if (!create) {
6882 return null;
6883 }
6884 s = new SharedUserSetting(name, pkgFlags);
6885 if (MULTIPLE_APPLICATION_UIDS) {
6886 s.userId = newUserIdLP(s);
6887 } else {
6888 s.userId = FIRST_APPLICATION_UID;
6889 }
6890 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6891 // < 0 means we couldn't assign a userid; fall out and return
6892 // s, which is currently null
6893 if (s.userId >= 0) {
6894 mSharedUsers.put(name, s);
6895 }
6896 }
6897
6898 return s;
6899 }
6900
6901 int disableSystemPackageLP(String name) {
6902 PackageSetting p = mPackages.get(name);
6903 if(p == null) {
6904 Log.w(TAG, "Package:"+name+" is not an installed package");
6905 return -1;
6906 }
6907 PackageSetting dp = mDisabledSysPackages.get(name);
6908 // always make sure the system package code and resource paths dont change
6909 if(dp == null) {
6910 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6911 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6912 }
6913 mDisabledSysPackages.put(name, p);
6914 }
6915 return removePackageLP(name);
6916 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006918 PackageSetting enableSystemPackageLP(String name) {
6919 PackageSetting p = mDisabledSysPackages.get(name);
6920 if(p == null) {
6921 Log.w(TAG, "Package:"+name+" is not disabled");
6922 return null;
6923 }
6924 // Reset flag in ApplicationInfo object
6925 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6926 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6927 }
6928 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006929 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006930 mDisabledSysPackages.remove(name);
6931 return ret;
6932 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006934 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006935 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006936 PackageSetting p = mPackages.get(name);
6937 if (p != null) {
6938 if (p.userId == uid) {
6939 return p;
6940 }
6941 reportSettingsProblem(Log.ERROR,
6942 "Adding duplicate package, keeping first: " + name);
6943 return null;
6944 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006945 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 p.userId = uid;
6947 if (addUserIdLP(uid, p, name)) {
6948 mPackages.put(name, p);
6949 return p;
6950 }
6951 return null;
6952 }
6953
6954 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
6955 SharedUserSetting s = mSharedUsers.get(name);
6956 if (s != null) {
6957 if (s.userId == uid) {
6958 return s;
6959 }
6960 reportSettingsProblem(Log.ERROR,
6961 "Adding duplicate shared user, keeping first: " + name);
6962 return null;
6963 }
6964 s = new SharedUserSetting(name, pkgFlags);
6965 s.userId = uid;
6966 if (addUserIdLP(uid, s, name)) {
6967 mSharedUsers.put(name, s);
6968 return s;
6969 }
6970 return null;
6971 }
6972
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006973 // Transfer ownership of permissions from one package to another.
6974 private void transferPermissions(String origPkg, String newPkg) {
6975 // Transfer ownership of permissions to the new package.
6976 for (int i=0; i<2; i++) {
6977 HashMap<String, BasePermission> permissions =
6978 i == 0 ? mPermissionTrees : mPermissions;
6979 for (BasePermission bp : permissions.values()) {
6980 if (origPkg.equals(bp.sourcePackage)) {
6981 if (DEBUG_UPGRADE) Log.v(TAG,
6982 "Moving permission " + bp.name
6983 + " from pkg " + bp.sourcePackage
6984 + " to " + newPkg);
6985 bp.sourcePackage = newPkg;
6986 bp.perm = null;
6987 if (bp.pendingInfo != null) {
6988 bp.sourcePackage = newPkg;
6989 }
6990 bp.uid = 0;
6991 bp.gids = null;
6992 }
6993 }
6994 }
6995 }
6996
6997 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006999 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007000 PackageSetting p = mPackages.get(name);
7001 if (p != null) {
7002 if (!p.codePath.equals(codePath)) {
7003 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007004 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007005 // This is an updated system app with versions in both system
7006 // and data partition. Just let the most recent version
7007 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007008 Log.w(TAG, "Trying to update system app code path from " +
7009 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007010 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007011 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07007012 reportSettingsProblem(Log.WARN,
7013 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007014 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007016 }
7017 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007018 reportSettingsProblem(Log.WARN,
7019 "Package " + name + " shared user changed from "
7020 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7021 + " to "
7022 + (sharedUser != null ? sharedUser.name : "<nothing>")
7023 + "; replacing with new");
7024 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007025 } else {
7026 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7027 // If what we are scanning is a system package, then
7028 // make it so, regardless of whether it was previously
7029 // installed only in the data partition.
7030 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007032 }
7033 }
7034 if (p == null) {
7035 // Create a new PackageSettings entry. this can end up here because
7036 // of code path mismatch or user id mismatch of an updated system partition
7037 if (!create) {
7038 return null;
7039 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007040 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007041 if (origPackage != null) {
7042 // We are consuming the data from an existing package.
7043 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7044 + " is adopting original package " + origPackage.name);
7045 p.copyFrom(origPackage);
7046 p.sharedUser = origPackage.sharedUser;
7047 p.userId = origPackage.userId;
7048 p.origPackage = origPackage;
7049 transferPermissions(origPackage.name, name);
7050 // Update new package state.
7051 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007052 } else {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007053 p.setTimeStamp(codePath.lastModified());
7054 p.sharedUser = sharedUser;
7055 if (sharedUser != null) {
7056 p.userId = sharedUser.userId;
7057 } else if (MULTIPLE_APPLICATION_UIDS) {
7058 // Clone the setting here for disabled system packages
7059 PackageSetting dis = mDisabledSysPackages.get(name);
7060 if (dis != null) {
7061 // For disabled packages a new setting is created
7062 // from the existing user id. This still has to be
7063 // added to list of user id's
7064 // Copy signatures from previous setting
7065 if (dis.signatures.mSignatures != null) {
7066 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7067 }
7068 p.userId = dis.userId;
7069 // Clone permissions
7070 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7071 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7072 // Clone component info
7073 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7074 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7075 // Add new setting to list of user ids
7076 addUserIdLP(p.userId, p, name);
7077 } else {
7078 // Assign new user id
7079 p.userId = newUserIdLP(p);
7080 }
7081 } else {
7082 p.userId = FIRST_APPLICATION_UID;
7083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007084 }
7085 if (p.userId < 0) {
7086 reportSettingsProblem(Log.WARN,
7087 "Package " + name + " could not be assigned a valid uid");
7088 return null;
7089 }
7090 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007091 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007093 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 }
7095 }
7096 return p;
7097 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007098
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007099 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007100 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007101 String codePath = pkg.applicationInfo.sourceDir;
7102 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007103 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007104 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007105 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007106 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007107 p.codePath = new File(codePath);
7108 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007109 }
7110 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007111 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007112 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007113 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007114 p.resourcePath = new File(resourcePath);
7115 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007116 }
7117 // Update version code if needed
7118 if (pkg.mVersionCode != p.versionCode) {
7119 p.versionCode = pkg.mVersionCode;
7120 }
7121 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7122 }
7123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007124 // Utility method that adds a PackageSetting to mPackages and
7125 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007126 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007127 SharedUserSetting sharedUser) {
7128 mPackages.put(name, p);
7129 if (sharedUser != null) {
7130 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7131 reportSettingsProblem(Log.ERROR,
7132 "Package " + p.name + " was user "
7133 + p.sharedUser + " but is now " + sharedUser
7134 + "; I am not changing its files so it will probably fail!");
7135 p.sharedUser.packages.remove(p);
7136 } else if (p.userId != sharedUser.userId) {
7137 reportSettingsProblem(Log.ERROR,
7138 "Package " + p.name + " was user id " + p.userId
7139 + " but is now user " + sharedUser
7140 + " with id " + sharedUser.userId
7141 + "; I am not changing its files so it will probably fail!");
7142 }
7143
7144 sharedUser.packages.add(p);
7145 p.sharedUser = sharedUser;
7146 p.userId = sharedUser.userId;
7147 }
7148 }
7149
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007150 /*
7151 * Update the shared user setting when a package using
7152 * specifying the shared user id is removed. The gids
7153 * associated with each permission of the deleted package
7154 * are removed from the shared user's gid list only if its
7155 * not in use by other permissions of packages in the
7156 * shared user setting.
7157 */
7158 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007159 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7160 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7161 return;
7162 }
7163 // No sharedUserId
7164 if (deletedPs.sharedUser == null) {
7165 return;
7166 }
7167 SharedUserSetting sus = deletedPs.sharedUser;
7168 // Update permissions
7169 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7170 boolean used = false;
7171 if (!sus.grantedPermissions.contains (eachPerm)) {
7172 continue;
7173 }
7174 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007175 if (pkg.pkg != null &&
7176 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7177 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 used = true;
7179 break;
7180 }
7181 }
7182 if (!used) {
7183 // can safely delete this permission from list
7184 sus.grantedPermissions.remove(eachPerm);
7185 sus.loadedPermissions.remove(eachPerm);
7186 }
7187 }
7188 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007189 int newGids[] = globalGids;
7190 for (String eachPerm : sus.grantedPermissions) {
7191 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007192 if (bp != null) {
7193 newGids = appendInts(newGids, bp.gids);
7194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007195 }
7196 sus.gids = newGids;
7197 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007199 private int removePackageLP(String name) {
7200 PackageSetting p = mPackages.get(name);
7201 if (p != null) {
7202 mPackages.remove(name);
7203 if (p.sharedUser != null) {
7204 p.sharedUser.packages.remove(p);
7205 if (p.sharedUser.packages.size() == 0) {
7206 mSharedUsers.remove(p.sharedUser.name);
7207 removeUserIdLP(p.sharedUser.userId);
7208 return p.sharedUser.userId;
7209 }
7210 } else {
7211 removeUserIdLP(p.userId);
7212 return p.userId;
7213 }
7214 }
7215 return -1;
7216 }
7217
7218 private boolean addUserIdLP(int uid, Object obj, Object name) {
7219 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7220 return false;
7221 }
7222
7223 if (uid >= FIRST_APPLICATION_UID) {
7224 int N = mUserIds.size();
7225 final int index = uid - FIRST_APPLICATION_UID;
7226 while (index >= N) {
7227 mUserIds.add(null);
7228 N++;
7229 }
7230 if (mUserIds.get(index) != null) {
7231 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007232 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007233 + " name=" + name);
7234 return false;
7235 }
7236 mUserIds.set(index, obj);
7237 } else {
7238 if (mOtherUserIds.get(uid) != null) {
7239 reportSettingsProblem(Log.ERROR,
7240 "Adding duplicate shared id: " + uid
7241 + " name=" + name);
7242 return false;
7243 }
7244 mOtherUserIds.put(uid, obj);
7245 }
7246 return true;
7247 }
7248
7249 public Object getUserIdLP(int uid) {
7250 if (uid >= FIRST_APPLICATION_UID) {
7251 int N = mUserIds.size();
7252 final int index = uid - FIRST_APPLICATION_UID;
7253 return index < N ? mUserIds.get(index) : null;
7254 } else {
7255 return mOtherUserIds.get(uid);
7256 }
7257 }
7258
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007259 private Set<String> findPackagesWithFlag(int flag) {
7260 Set<String> ret = new HashSet<String>();
7261 for (PackageSetting ps : mPackages.values()) {
7262 // Has to match atleast all the flag bits set on flag
7263 if ((ps.pkgFlags & flag) == flag) {
7264 ret.add(ps.name);
7265 }
7266 }
7267 return ret;
7268 }
7269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007270 private void removeUserIdLP(int uid) {
7271 if (uid >= FIRST_APPLICATION_UID) {
7272 int N = mUserIds.size();
7273 final int index = uid - FIRST_APPLICATION_UID;
7274 if (index < N) mUserIds.set(index, null);
7275 } else {
7276 mOtherUserIds.remove(uid);
7277 }
7278 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007280 void writeLP() {
7281 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7282
7283 // Keep the old settings around until we know the new ones have
7284 // been successfully written.
7285 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007286 // Presence of backup settings file indicates that we failed
7287 // to persist settings earlier. So preserve the older
7288 // backup for future reference since the current settings
7289 // might have been corrupted.
7290 if (!mBackupSettingsFilename.exists()) {
7291 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7292 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7293 return;
7294 }
7295 } else {
7296 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007298 }
7299
7300 mPastSignatures.clear();
7301
7302 try {
7303 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7304
7305 //XmlSerializer serializer = XmlUtils.serializerInstance();
7306 XmlSerializer serializer = new FastXmlSerializer();
7307 serializer.setOutput(str, "utf-8");
7308 serializer.startDocument(null, true);
7309 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7310
7311 serializer.startTag(null, "packages");
7312
7313 serializer.startTag(null, "permission-trees");
7314 for (BasePermission bp : mPermissionTrees.values()) {
7315 writePermission(serializer, bp);
7316 }
7317 serializer.endTag(null, "permission-trees");
7318
7319 serializer.startTag(null, "permissions");
7320 for (BasePermission bp : mPermissions.values()) {
7321 writePermission(serializer, bp);
7322 }
7323 serializer.endTag(null, "permissions");
7324
7325 for (PackageSetting pkg : mPackages.values()) {
7326 writePackage(serializer, pkg);
7327 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007329 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7330 writeDisabledSysPackage(serializer, pkg);
7331 }
7332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007333 serializer.startTag(null, "preferred-activities");
7334 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7335 serializer.startTag(null, "item");
7336 pa.writeToXml(serializer);
7337 serializer.endTag(null, "item");
7338 }
7339 serializer.endTag(null, "preferred-activities");
7340
7341 for (SharedUserSetting usr : mSharedUsers.values()) {
7342 serializer.startTag(null, "shared-user");
7343 serializer.attribute(null, "name", usr.name);
7344 serializer.attribute(null, "userId",
7345 Integer.toString(usr.userId));
7346 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7347 serializer.startTag(null, "perms");
7348 for (String name : usr.grantedPermissions) {
7349 serializer.startTag(null, "item");
7350 serializer.attribute(null, "name", name);
7351 serializer.endTag(null, "item");
7352 }
7353 serializer.endTag(null, "perms");
7354 serializer.endTag(null, "shared-user");
7355 }
7356
7357 serializer.endTag(null, "packages");
7358
7359 serializer.endDocument();
7360
7361 str.flush();
7362 str.close();
7363
7364 // New settings successfully written, old ones are no longer
7365 // needed.
7366 mBackupSettingsFilename.delete();
7367 FileUtils.setPermissions(mSettingsFilename.toString(),
7368 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7369 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7370 |FileUtils.S_IROTH,
7371 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007372 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007373
7374 } catch(XmlPullParserException e) {
7375 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007376 } catch(java.io.IOException e) {
7377 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007378 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007379 // Clean up partially written file
7380 if (mSettingsFilename.exists()) {
7381 if (!mSettingsFilename.delete()) {
7382 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7383 }
7384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007385 //Debug.stopMethodTracing();
7386 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007387
7388 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007389 throws java.io.IOException {
7390 serializer.startTag(null, "updated-package");
7391 serializer.attribute(null, "name", pkg.name);
7392 serializer.attribute(null, "codePath", pkg.codePathString);
7393 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007394 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7396 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7397 }
7398 if (pkg.sharedUser == null) {
7399 serializer.attribute(null, "userId",
7400 Integer.toString(pkg.userId));
7401 } else {
7402 serializer.attribute(null, "sharedUserId",
7403 Integer.toString(pkg.userId));
7404 }
7405 serializer.startTag(null, "perms");
7406 if (pkg.sharedUser == null) {
7407 // If this is a shared user, the permissions will
7408 // be written there. We still need to write an
7409 // empty permissions list so permissionsFixed will
7410 // be set.
7411 for (final String name : pkg.grantedPermissions) {
7412 BasePermission bp = mPermissions.get(name);
7413 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7414 // We only need to write signature or system permissions but this wont
7415 // match the semantics of grantedPermissions. So write all permissions.
7416 serializer.startTag(null, "item");
7417 serializer.attribute(null, "name", name);
7418 serializer.endTag(null, "item");
7419 }
7420 }
7421 }
7422 serializer.endTag(null, "perms");
7423 serializer.endTag(null, "updated-package");
7424 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007425
7426 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007427 throws java.io.IOException {
7428 serializer.startTag(null, "package");
7429 serializer.attribute(null, "name", pkg.name);
7430 serializer.attribute(null, "codePath", pkg.codePathString);
7431 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7432 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7433 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007434 serializer.attribute(null, "flags",
7435 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007436 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007437 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007438 if (pkg.sharedUser == null) {
7439 serializer.attribute(null, "userId",
7440 Integer.toString(pkg.userId));
7441 } else {
7442 serializer.attribute(null, "sharedUserId",
7443 Integer.toString(pkg.userId));
7444 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007445 if (pkg.uidError) {
7446 serializer.attribute(null, "uidError", "true");
7447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007448 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
7449 serializer.attribute(null, "enabled",
7450 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
7451 ? "true" : "false");
7452 }
7453 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
7454 serializer.attribute(null, "installStatus", "false");
7455 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007456 if (pkg.installerPackageName != null) {
7457 serializer.attribute(null, "installer", pkg.installerPackageName);
7458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007459 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
7460 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7461 serializer.startTag(null, "perms");
7462 if (pkg.sharedUser == null) {
7463 // If this is a shared user, the permissions will
7464 // be written there. We still need to write an
7465 // empty permissions list so permissionsFixed will
7466 // be set.
7467 for (final String name : pkg.grantedPermissions) {
7468 serializer.startTag(null, "item");
7469 serializer.attribute(null, "name", name);
7470 serializer.endTag(null, "item");
7471 }
7472 }
7473 serializer.endTag(null, "perms");
7474 }
7475 if (pkg.disabledComponents.size() > 0) {
7476 serializer.startTag(null, "disabled-components");
7477 for (final String name : pkg.disabledComponents) {
7478 serializer.startTag(null, "item");
7479 serializer.attribute(null, "name", name);
7480 serializer.endTag(null, "item");
7481 }
7482 serializer.endTag(null, "disabled-components");
7483 }
7484 if (pkg.enabledComponents.size() > 0) {
7485 serializer.startTag(null, "enabled-components");
7486 for (final String name : pkg.enabledComponents) {
7487 serializer.startTag(null, "item");
7488 serializer.attribute(null, "name", name);
7489 serializer.endTag(null, "item");
7490 }
7491 serializer.endTag(null, "enabled-components");
7492 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007494 serializer.endTag(null, "package");
7495 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007497 void writePermission(XmlSerializer serializer, BasePermission bp)
7498 throws XmlPullParserException, java.io.IOException {
7499 if (bp.type != BasePermission.TYPE_BUILTIN
7500 && bp.sourcePackage != null) {
7501 serializer.startTag(null, "item");
7502 serializer.attribute(null, "name", bp.name);
7503 serializer.attribute(null, "package", bp.sourcePackage);
7504 if (DEBUG_SETTINGS) Log.v(TAG,
7505 "Writing perm: name=" + bp.name + " type=" + bp.type);
7506 if (bp.type == BasePermission.TYPE_DYNAMIC) {
7507 PermissionInfo pi = bp.perm != null ? bp.perm.info
7508 : bp.pendingInfo;
7509 if (pi != null) {
7510 serializer.attribute(null, "type", "dynamic");
7511 if (pi.icon != 0) {
7512 serializer.attribute(null, "icon",
7513 Integer.toString(pi.icon));
7514 }
7515 if (pi.nonLocalizedLabel != null) {
7516 serializer.attribute(null, "label",
7517 pi.nonLocalizedLabel.toString());
7518 }
7519 if (pi.protectionLevel !=
7520 PermissionInfo.PROTECTION_NORMAL) {
7521 serializer.attribute(null, "protection",
7522 Integer.toString(pi.protectionLevel));
7523 }
7524 }
7525 }
7526 serializer.endTag(null, "item");
7527 }
7528 }
7529
7530 String getReadMessagesLP() {
7531 return mReadMessages.toString();
7532 }
7533
Oscar Montemayora8529f62009-11-18 10:14:20 -08007534 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007535 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
7536 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007537 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 while(its.hasNext()) {
7539 String key = its.next();
7540 PackageSetting ps = mPackages.get(key);
7541 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08007542 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007543 }
7544 }
7545 return ret;
7546 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548 boolean readLP() {
7549 FileInputStream str = null;
7550 if (mBackupSettingsFilename.exists()) {
7551 try {
7552 str = new FileInputStream(mBackupSettingsFilename);
7553 mReadMessages.append("Reading from backup settings file\n");
7554 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007555 if (mSettingsFilename.exists()) {
7556 // If both the backup and settings file exist, we
7557 // ignore the settings since it might have been
7558 // corrupted.
7559 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
7560 mSettingsFilename.delete();
7561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 } catch (java.io.IOException e) {
7563 // We'll try for the normal settings file.
7564 }
7565 }
7566
7567 mPastSignatures.clear();
7568
7569 try {
7570 if (str == null) {
7571 if (!mSettingsFilename.exists()) {
7572 mReadMessages.append("No settings file found\n");
7573 Log.i(TAG, "No current settings file!");
7574 return false;
7575 }
7576 str = new FileInputStream(mSettingsFilename);
7577 }
7578 XmlPullParser parser = Xml.newPullParser();
7579 parser.setInput(str, null);
7580
7581 int type;
7582 while ((type=parser.next()) != XmlPullParser.START_TAG
7583 && type != XmlPullParser.END_DOCUMENT) {
7584 ;
7585 }
7586
7587 if (type != XmlPullParser.START_TAG) {
7588 mReadMessages.append("No start tag found in settings file\n");
7589 Log.e(TAG, "No start tag found in package manager settings");
7590 return false;
7591 }
7592
7593 int outerDepth = parser.getDepth();
7594 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7595 && (type != XmlPullParser.END_TAG
7596 || parser.getDepth() > outerDepth)) {
7597 if (type == XmlPullParser.END_TAG
7598 || type == XmlPullParser.TEXT) {
7599 continue;
7600 }
7601
7602 String tagName = parser.getName();
7603 if (tagName.equals("package")) {
7604 readPackageLP(parser);
7605 } else if (tagName.equals("permissions")) {
7606 readPermissionsLP(mPermissions, parser);
7607 } else if (tagName.equals("permission-trees")) {
7608 readPermissionsLP(mPermissionTrees, parser);
7609 } else if (tagName.equals("shared-user")) {
7610 readSharedUserLP(parser);
7611 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08007612 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613 } else if (tagName.equals("preferred-activities")) {
7614 readPreferredActivitiesLP(parser);
7615 } else if(tagName.equals("updated-package")) {
7616 readDisabledSysPackageLP(parser);
7617 } else {
7618 Log.w(TAG, "Unknown element under <packages>: "
7619 + parser.getName());
7620 XmlUtils.skipCurrentTag(parser);
7621 }
7622 }
7623
7624 str.close();
7625
7626 } catch(XmlPullParserException e) {
7627 mReadMessages.append("Error reading: " + e.toString());
7628 Log.e(TAG, "Error reading package manager settings", e);
7629
7630 } catch(java.io.IOException e) {
7631 mReadMessages.append("Error reading: " + e.toString());
7632 Log.e(TAG, "Error reading package manager settings", e);
7633
7634 }
7635
7636 int N = mPendingPackages.size();
7637 for (int i=0; i<N; i++) {
7638 final PendingPackage pp = mPendingPackages.get(i);
7639 Object idObj = getUserIdLP(pp.sharedId);
7640 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007641 PackageSetting p = getPackageLP(pp.name, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007642 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007643 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007644 if (p == null) {
7645 Log.w(TAG, "Unable to create application package for "
7646 + pp.name);
7647 continue;
7648 }
7649 p.copyFrom(pp);
7650 } else if (idObj != null) {
7651 String msg = "Bad package setting: package " + pp.name
7652 + " has shared uid " + pp.sharedId
7653 + " that is not a shared uid\n";
7654 mReadMessages.append(msg);
7655 Log.e(TAG, msg);
7656 } else {
7657 String msg = "Bad package setting: package " + pp.name
7658 + " has shared uid " + pp.sharedId
7659 + " that is not defined\n";
7660 mReadMessages.append(msg);
7661 Log.e(TAG, msg);
7662 }
7663 }
7664 mPendingPackages.clear();
7665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007666 mReadMessages.append("Read completed successfully: "
7667 + mPackages.size() + " packages, "
7668 + mSharedUsers.size() + " shared uids\n");
7669
7670 return true;
7671 }
7672
7673 private int readInt(XmlPullParser parser, String ns, String name,
7674 int defValue) {
7675 String v = parser.getAttributeValue(ns, name);
7676 try {
7677 if (v == null) {
7678 return defValue;
7679 }
7680 return Integer.parseInt(v);
7681 } catch (NumberFormatException e) {
7682 reportSettingsProblem(Log.WARN,
7683 "Error in package manager settings: attribute " +
7684 name + " has bad integer value " + v + " at "
7685 + parser.getPositionDescription());
7686 }
7687 return defValue;
7688 }
7689
7690 private void readPermissionsLP(HashMap<String, BasePermission> out,
7691 XmlPullParser parser)
7692 throws IOException, XmlPullParserException {
7693 int outerDepth = parser.getDepth();
7694 int type;
7695 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7696 && (type != XmlPullParser.END_TAG
7697 || parser.getDepth() > outerDepth)) {
7698 if (type == XmlPullParser.END_TAG
7699 || type == XmlPullParser.TEXT) {
7700 continue;
7701 }
7702
7703 String tagName = parser.getName();
7704 if (tagName.equals("item")) {
7705 String name = parser.getAttributeValue(null, "name");
7706 String sourcePackage = parser.getAttributeValue(null, "package");
7707 String ptype = parser.getAttributeValue(null, "type");
7708 if (name != null && sourcePackage != null) {
7709 boolean dynamic = "dynamic".equals(ptype);
7710 BasePermission bp = new BasePermission(name, sourcePackage,
7711 dynamic
7712 ? BasePermission.TYPE_DYNAMIC
7713 : BasePermission.TYPE_NORMAL);
7714 if (dynamic) {
7715 PermissionInfo pi = new PermissionInfo();
7716 pi.packageName = sourcePackage.intern();
7717 pi.name = name.intern();
7718 pi.icon = readInt(parser, null, "icon", 0);
7719 pi.nonLocalizedLabel = parser.getAttributeValue(
7720 null, "label");
7721 pi.protectionLevel = readInt(parser, null, "protection",
7722 PermissionInfo.PROTECTION_NORMAL);
7723 bp.pendingInfo = pi;
7724 }
7725 out.put(bp.name, bp);
7726 } else {
7727 reportSettingsProblem(Log.WARN,
7728 "Error in package manager settings: permissions has"
7729 + " no name at " + parser.getPositionDescription());
7730 }
7731 } else {
7732 reportSettingsProblem(Log.WARN,
7733 "Unknown element reading permissions: "
7734 + parser.getName() + " at "
7735 + parser.getPositionDescription());
7736 }
7737 XmlUtils.skipCurrentTag(parser);
7738 }
7739 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007741 private void readDisabledSysPackageLP(XmlPullParser parser)
7742 throws XmlPullParserException, IOException {
7743 String name = parser.getAttributeValue(null, "name");
7744 String codePathStr = parser.getAttributeValue(null, "codePath");
7745 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
7746 if(resourcePathStr == null) {
7747 resourcePathStr = codePathStr;
7748 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007749 String version = parser.getAttributeValue(null, "version");
7750 int versionCode = 0;
7751 if (version != null) {
7752 try {
7753 versionCode = Integer.parseInt(version);
7754 } catch (NumberFormatException e) {
7755 }
7756 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007758 int pkgFlags = 0;
7759 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007760 PackageSetting ps = new PackageSetting(name,
7761 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007762 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 String timeStampStr = parser.getAttributeValue(null, "ts");
7764 if (timeStampStr != null) {
7765 try {
7766 long timeStamp = Long.parseLong(timeStampStr);
7767 ps.setTimeStamp(timeStamp, timeStampStr);
7768 } catch (NumberFormatException e) {
7769 }
7770 }
7771 String idStr = parser.getAttributeValue(null, "userId");
7772 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
7773 if(ps.userId <= 0) {
7774 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7775 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
7776 }
7777 int outerDepth = parser.getDepth();
7778 int type;
7779 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7780 && (type != XmlPullParser.END_TAG
7781 || parser.getDepth() > outerDepth)) {
7782 if (type == XmlPullParser.END_TAG
7783 || type == XmlPullParser.TEXT) {
7784 continue;
7785 }
7786
7787 String tagName = parser.getName();
7788 if (tagName.equals("perms")) {
7789 readGrantedPermissionsLP(parser,
7790 ps.grantedPermissions);
7791 } else {
7792 reportSettingsProblem(Log.WARN,
7793 "Unknown element under <updated-package>: "
7794 + parser.getName());
7795 XmlUtils.skipCurrentTag(parser);
7796 }
7797 }
7798 mDisabledSysPackages.put(name, ps);
7799 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 private void readPackageLP(XmlPullParser parser)
7802 throws XmlPullParserException, IOException {
7803 String name = null;
7804 String idStr = null;
7805 String sharedIdStr = null;
7806 String codePathStr = null;
7807 String resourcePathStr = null;
7808 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02007809 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007810 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007811 int pkgFlags = 0;
7812 String timeStampStr;
7813 long timeStamp = 0;
7814 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007815 String version = null;
7816 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 try {
7818 name = parser.getAttributeValue(null, "name");
7819 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007820 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007821 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7822 codePathStr = parser.getAttributeValue(null, "codePath");
7823 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007824 version = parser.getAttributeValue(null, "version");
7825 if (version != null) {
7826 try {
7827 versionCode = Integer.parseInt(version);
7828 } catch (NumberFormatException e) {
7829 }
7830 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007831 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007832
7833 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007834 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007835 try {
7836 pkgFlags = Integer.parseInt(systemStr);
7837 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007838 }
7839 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007840 // For backward compatibility
7841 systemStr = parser.getAttributeValue(null, "system");
7842 if (systemStr != null) {
7843 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
7844 } else {
7845 // Old settings that don't specify system... just treat
7846 // them as system, good enough.
7847 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007849 }
7850 timeStampStr = parser.getAttributeValue(null, "ts");
7851 if (timeStampStr != null) {
7852 try {
7853 timeStamp = Long.parseLong(timeStampStr);
7854 } catch (NumberFormatException e) {
7855 }
7856 }
7857 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7858 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7859 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7860 if (resourcePathStr == null) {
7861 resourcePathStr = codePathStr;
7862 }
7863 if (name == null) {
7864 reportSettingsProblem(Log.WARN,
7865 "Error in package manager settings: <package> has no name at "
7866 + parser.getPositionDescription());
7867 } else if (codePathStr == null) {
7868 reportSettingsProblem(Log.WARN,
7869 "Error in package manager settings: <package> has no codePath at "
7870 + parser.getPositionDescription());
7871 } else if (userId > 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007872 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007873 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7875 + ": userId=" + userId + " pkg=" + packageSetting);
7876 if (packageSetting == null) {
7877 reportSettingsProblem(Log.ERROR,
7878 "Failure adding uid " + userId
7879 + " while parsing settings at "
7880 + parser.getPositionDescription());
7881 } else {
7882 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7883 }
7884 } else if (sharedIdStr != null) {
7885 userId = sharedIdStr != null
7886 ? Integer.parseInt(sharedIdStr) : 0;
7887 if (userId > 0) {
7888 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007889 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007890 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7891 mPendingPackages.add((PendingPackage) packageSetting);
7892 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7893 + ": sharedUserId=" + userId + " pkg="
7894 + packageSetting);
7895 } else {
7896 reportSettingsProblem(Log.WARN,
7897 "Error in package manager settings: package "
7898 + name + " has bad sharedId " + sharedIdStr
7899 + " at " + parser.getPositionDescription());
7900 }
7901 } else {
7902 reportSettingsProblem(Log.WARN,
7903 "Error in package manager settings: package "
7904 + name + " has bad userId " + idStr + " at "
7905 + parser.getPositionDescription());
7906 }
7907 } catch (NumberFormatException e) {
7908 reportSettingsProblem(Log.WARN,
7909 "Error in package manager settings: package "
7910 + name + " has bad userId " + idStr + " at "
7911 + parser.getPositionDescription());
7912 }
7913 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007914 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02007915 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 final String enabledStr = parser.getAttributeValue(null, "enabled");
7917 if (enabledStr != null) {
7918 if (enabledStr.equalsIgnoreCase("true")) {
7919 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
7920 } else if (enabledStr.equalsIgnoreCase("false")) {
7921 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
7922 } else if (enabledStr.equalsIgnoreCase("default")) {
7923 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7924 } else {
7925 reportSettingsProblem(Log.WARN,
7926 "Error in package manager settings: package "
7927 + name + " has bad enabled value: " + idStr
7928 + " at " + parser.getPositionDescription());
7929 }
7930 } else {
7931 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7932 }
7933 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
7934 if (installStatusStr != null) {
7935 if (installStatusStr.equalsIgnoreCase("false")) {
7936 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
7937 } else {
7938 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
7939 }
7940 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007942 int outerDepth = parser.getDepth();
7943 int type;
7944 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7945 && (type != XmlPullParser.END_TAG
7946 || parser.getDepth() > outerDepth)) {
7947 if (type == XmlPullParser.END_TAG
7948 || type == XmlPullParser.TEXT) {
7949 continue;
7950 }
7951
7952 String tagName = parser.getName();
7953 if (tagName.equals("disabled-components")) {
7954 readDisabledComponentsLP(packageSetting, parser);
7955 } else if (tagName.equals("enabled-components")) {
7956 readEnabledComponentsLP(packageSetting, parser);
7957 } else if (tagName.equals("sigs")) {
7958 packageSetting.signatures.readXml(parser, mPastSignatures);
7959 } else if (tagName.equals("perms")) {
7960 readGrantedPermissionsLP(parser,
7961 packageSetting.loadedPermissions);
7962 packageSetting.permissionsFixed = true;
7963 } else {
7964 reportSettingsProblem(Log.WARN,
7965 "Unknown element under <package>: "
7966 + parser.getName());
7967 XmlUtils.skipCurrentTag(parser);
7968 }
7969 }
7970 } else {
7971 XmlUtils.skipCurrentTag(parser);
7972 }
7973 }
7974
7975 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
7976 XmlPullParser parser)
7977 throws IOException, XmlPullParserException {
7978 int outerDepth = parser.getDepth();
7979 int type;
7980 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7981 && (type != XmlPullParser.END_TAG
7982 || parser.getDepth() > outerDepth)) {
7983 if (type == XmlPullParser.END_TAG
7984 || type == XmlPullParser.TEXT) {
7985 continue;
7986 }
7987
7988 String tagName = parser.getName();
7989 if (tagName.equals("item")) {
7990 String name = parser.getAttributeValue(null, "name");
7991 if (name != null) {
7992 packageSetting.disabledComponents.add(name.intern());
7993 } else {
7994 reportSettingsProblem(Log.WARN,
7995 "Error in package manager settings: <disabled-components> has"
7996 + " no name at " + parser.getPositionDescription());
7997 }
7998 } else {
7999 reportSettingsProblem(Log.WARN,
8000 "Unknown element under <disabled-components>: "
8001 + parser.getName());
8002 }
8003 XmlUtils.skipCurrentTag(parser);
8004 }
8005 }
8006
8007 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8008 XmlPullParser parser)
8009 throws IOException, XmlPullParserException {
8010 int outerDepth = parser.getDepth();
8011 int type;
8012 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8013 && (type != XmlPullParser.END_TAG
8014 || parser.getDepth() > outerDepth)) {
8015 if (type == XmlPullParser.END_TAG
8016 || type == XmlPullParser.TEXT) {
8017 continue;
8018 }
8019
8020 String tagName = parser.getName();
8021 if (tagName.equals("item")) {
8022 String name = parser.getAttributeValue(null, "name");
8023 if (name != null) {
8024 packageSetting.enabledComponents.add(name.intern());
8025 } else {
8026 reportSettingsProblem(Log.WARN,
8027 "Error in package manager settings: <enabled-components> has"
8028 + " no name at " + parser.getPositionDescription());
8029 }
8030 } else {
8031 reportSettingsProblem(Log.WARN,
8032 "Unknown element under <enabled-components>: "
8033 + parser.getName());
8034 }
8035 XmlUtils.skipCurrentTag(parser);
8036 }
8037 }
8038
8039 private void readSharedUserLP(XmlPullParser parser)
8040 throws XmlPullParserException, IOException {
8041 String name = null;
8042 String idStr = null;
8043 int pkgFlags = 0;
8044 SharedUserSetting su = null;
8045 try {
8046 name = parser.getAttributeValue(null, "name");
8047 idStr = parser.getAttributeValue(null, "userId");
8048 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8049 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8050 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8051 }
8052 if (name == null) {
8053 reportSettingsProblem(Log.WARN,
8054 "Error in package manager settings: <shared-user> has no name at "
8055 + parser.getPositionDescription());
8056 } else if (userId == 0) {
8057 reportSettingsProblem(Log.WARN,
8058 "Error in package manager settings: shared-user "
8059 + name + " has bad userId " + idStr + " at "
8060 + parser.getPositionDescription());
8061 } else {
8062 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8063 reportSettingsProblem(Log.ERROR,
8064 "Occurred while parsing settings at "
8065 + parser.getPositionDescription());
8066 }
8067 }
8068 } catch (NumberFormatException e) {
8069 reportSettingsProblem(Log.WARN,
8070 "Error in package manager settings: package "
8071 + name + " has bad userId " + idStr + " at "
8072 + parser.getPositionDescription());
8073 };
8074
8075 if (su != null) {
8076 int outerDepth = parser.getDepth();
8077 int type;
8078 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8079 && (type != XmlPullParser.END_TAG
8080 || parser.getDepth() > outerDepth)) {
8081 if (type == XmlPullParser.END_TAG
8082 || type == XmlPullParser.TEXT) {
8083 continue;
8084 }
8085
8086 String tagName = parser.getName();
8087 if (tagName.equals("sigs")) {
8088 su.signatures.readXml(parser, mPastSignatures);
8089 } else if (tagName.equals("perms")) {
8090 readGrantedPermissionsLP(parser, su.loadedPermissions);
8091 } else {
8092 reportSettingsProblem(Log.WARN,
8093 "Unknown element under <shared-user>: "
8094 + parser.getName());
8095 XmlUtils.skipCurrentTag(parser);
8096 }
8097 }
8098
8099 } else {
8100 XmlUtils.skipCurrentTag(parser);
8101 }
8102 }
8103
8104 private void readGrantedPermissionsLP(XmlPullParser parser,
8105 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8106 int outerDepth = parser.getDepth();
8107 int type;
8108 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8109 && (type != XmlPullParser.END_TAG
8110 || parser.getDepth() > outerDepth)) {
8111 if (type == XmlPullParser.END_TAG
8112 || type == XmlPullParser.TEXT) {
8113 continue;
8114 }
8115
8116 String tagName = parser.getName();
8117 if (tagName.equals("item")) {
8118 String name = parser.getAttributeValue(null, "name");
8119 if (name != null) {
8120 outPerms.add(name.intern());
8121 } else {
8122 reportSettingsProblem(Log.WARN,
8123 "Error in package manager settings: <perms> has"
8124 + " no name at " + parser.getPositionDescription());
8125 }
8126 } else {
8127 reportSettingsProblem(Log.WARN,
8128 "Unknown element under <perms>: "
8129 + parser.getName());
8130 }
8131 XmlUtils.skipCurrentTag(parser);
8132 }
8133 }
8134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 private void readPreferredActivitiesLP(XmlPullParser parser)
8136 throws XmlPullParserException, IOException {
8137 int outerDepth = parser.getDepth();
8138 int type;
8139 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8140 && (type != XmlPullParser.END_TAG
8141 || parser.getDepth() > outerDepth)) {
8142 if (type == XmlPullParser.END_TAG
8143 || type == XmlPullParser.TEXT) {
8144 continue;
8145 }
8146
8147 String tagName = parser.getName();
8148 if (tagName.equals("item")) {
8149 PreferredActivity pa = new PreferredActivity(parser);
8150 if (pa.mParseError == null) {
8151 mPreferredActivities.addFilter(pa);
8152 } else {
8153 reportSettingsProblem(Log.WARN,
8154 "Error in package manager settings: <preferred-activity> "
8155 + pa.mParseError + " at "
8156 + parser.getPositionDescription());
8157 }
8158 } else {
8159 reportSettingsProblem(Log.WARN,
8160 "Unknown element under <preferred-activities>: "
8161 + parser.getName());
8162 XmlUtils.skipCurrentTag(parser);
8163 }
8164 }
8165 }
8166
8167 // Returns -1 if we could not find an available UserId to assign
8168 private int newUserIdLP(Object obj) {
8169 // Let's be stupidly inefficient for now...
8170 final int N = mUserIds.size();
8171 for (int i=0; i<N; i++) {
8172 if (mUserIds.get(i) == null) {
8173 mUserIds.set(i, obj);
8174 return FIRST_APPLICATION_UID + i;
8175 }
8176 }
8177
8178 // None left?
8179 if (N >= MAX_APPLICATION_UIDS) {
8180 return -1;
8181 }
8182
8183 mUserIds.add(obj);
8184 return FIRST_APPLICATION_UID + N;
8185 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008187 public PackageSetting getDisabledSystemPkg(String name) {
8188 synchronized(mPackages) {
8189 PackageSetting ps = mDisabledSysPackages.get(name);
8190 return ps;
8191 }
8192 }
8193
8194 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8195 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8196 if (Config.LOGV) {
8197 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8198 + " componentName = " + componentInfo.name);
8199 Log.v(TAG, "enabledComponents: "
8200 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8201 Log.v(TAG, "disabledComponents: "
8202 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8203 }
8204 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8205 || ((componentInfo.enabled
8206 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8207 || (componentInfo.applicationInfo.enabled
8208 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8209 && !packageSettings.disabledComponents.contains(componentInfo.name))
8210 || packageSettings.enabledComponents.contains(componentInfo.name));
8211 }
8212 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008213
8214 // ------- apps on sdcard specific code -------
8215 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008216 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008217 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008218 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008219 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008220
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008221
8222 static MountService getMountService() {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008223 return (MountService) ServiceManager.getService("mount");
8224 }
8225
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008226 private String getEncryptKey() {
8227 try {
8228 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8229 if (sdEncKey == null) {
8230 sdEncKey = SystemKeyStore.getInstance().
8231 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8232 if (sdEncKey == null) {
8233 Log.e(TAG, "Failed to create encryption keys");
8234 return null;
8235 }
8236 }
8237 return sdEncKey;
8238 } catch (NoSuchAlgorithmException nsae) {
8239 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8240 return null;
8241 }
8242 }
8243
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008244 private String createSdDir(File tmpPackageFile, String pkgName) {
8245 // Create mount point via MountService
8246 MountService mountService = getMountService();
8247 long len = tmpPackageFile.length();
8248 int mbLen = (int) (len/(1024*1024));
8249 if ((len - (mbLen * 1024 * 1024)) > 0) {
8250 mbLen++;
8251 }
8252 if (DEBUG_SD_INSTALL) Log.i(TAG, "mbLen="+mbLen);
8253 String cachePath = null;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008254 String sdEncKey;
8255 try {
8256 sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8257 if (sdEncKey == null) {
8258 sdEncKey = SystemKeyStore.getInstance().
8259 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8260 if (sdEncKey == null) {
8261 Log.e(TAG, "Failed to create encryption keys for package: " + pkgName + ".");
8262 return null;
8263 }
8264 }
8265 } catch (NoSuchAlgorithmException nsae) {
8266 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8267 return null;
8268 }
San Mehatbe16cb12010-01-29 05:35:35 -08008269
8270 int rc = mountService.createSecureContainer(
8271 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
8272 if (rc != MountServiceResultCode.OperationSucceeded) {
8273 Log.e(TAG, String.format("Failed to create container (%d)", rc));
8274
8275 rc = mountService.destroySecureContainer(pkgName);
8276 if (rc != MountServiceResultCode.OperationSucceeded) {
8277 Log.e(TAG, String.format("Failed to cleanup container (%d)", rc));
8278 return null;
8279 }
8280 rc = mountService.createSecureContainer(
8281 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
8282 if (rc != MountServiceResultCode.OperationSucceeded) {
8283 Log.e(TAG, String.format("Failed to create container (2nd try) (%d)", rc));
8284 return null;
8285 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008286 }
San Mehatbe16cb12010-01-29 05:35:35 -08008287
8288 cachePath = mountService.getSecureContainerPath(pkgName);
8289 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install " + pkgName + ", cachePath =" + cachePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008290 return cachePath;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008291 }
8292
8293 private String mountSdDir(String pkgName, int ownerUid) {
Oscar Montemayord02546b2010-01-14 16:38:40 -08008294 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8295 if (sdEncKey == null) {
8296 Log.e(TAG, "Failed to retrieve encryption keys to mount package code: " + pkgName + ".");
8297 return null;
8298 }
San Mehatbe16cb12010-01-29 05:35:35 -08008299
8300 int rc = getMountService().mountSecureContainer(pkgName, sdEncKey, ownerUid);
8301
8302 if (rc != MountServiceResultCode.OperationSucceeded) {
8303 Log.i(TAG, "Failed to mount container for pkg : " + pkgName + " rc : " + rc);
8304 return null;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008305 }
San Mehatbe16cb12010-01-29 05:35:35 -08008306
8307 return getMountService().getSecureContainerPath(pkgName);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008308 }
8309
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008310 private boolean unMountSdDir(String pkgName) {
8311 // STOPSHIP unmount directory
San Mehatbe16cb12010-01-29 05:35:35 -08008312 int rc = getMountService().unmountSecureContainer(pkgName);
8313 if (rc != MountServiceResultCode.OperationSucceeded) {
8314 Log.e(TAG, "Failed to unmount : " + pkgName + " with rc " + rc);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008315 return false;
8316 }
San Mehatbe16cb12010-01-29 05:35:35 -08008317 return true;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008318 }
8319
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008320 private boolean renameSdDir(String oldId, String newId) {
8321 try {
8322 getMountService().renameSecureContainer(oldId, newId);
8323 return true;
8324 } catch (IllegalStateException e) {
8325 Log.i(TAG, "Failed ot rename " + oldId + " to " + newId +
8326 " with exception : " + e);
8327 }
8328 return false;
8329 }
8330
8331 private String getSdDir(String pkgName) {
8332 return getMountService().getSecureContainerPath(pkgName);
8333 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008334
San Mehatbe16cb12010-01-29 05:35:35 -08008335 private boolean finalizeSdDir(String pkgName) {
8336 int rc = getMountService().finalizeSecureContainer(pkgName);
8337 if (rc != MountServiceResultCode.OperationSucceeded) {
8338 Log.i(TAG, "Failed to finalize container for pkg : " + pkgName);
8339 return false;
8340 }
8341 return true;
8342 }
8343
8344 private boolean destroySdDir(String pkgName) {
8345 int rc = getMountService().destroySecureContainer(pkgName);
8346 if (rc != MountServiceResultCode.OperationSucceeded) {
8347 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
8348 return false;
8349 }
8350 return true;
8351 }
8352
8353 static String[] getSecureContainerList() {
8354 String[] list = getMountService().getSecureContainerList();
8355 return list.length == 0 ? null : list;
8356 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008357
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008358 static boolean isContainerMounted(String cid) {
8359 // STOPSHIP
8360 // New api from MountService
8361 try {
8362 return (getMountService().getSecureContainerPath(cid) != null);
8363 } catch (IllegalStateException e) {
8364 }
8365 return false;
8366 }
8367
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008368 static String getTempContainerId() {
8369 String prefix = "smdl1tmp";
8370 int tmpIdx = 1;
8371 String list[] = getSecureContainerList();
8372 if (list != null) {
8373 int idx = 0;
8374 int idList[] = new int[MAX_CONTAINERS];
8375 boolean neverFound = true;
8376 for (String name : list) {
8377 // Ignore null entries
8378 if (name == null) {
8379 continue;
8380 }
8381 int sidx = name.indexOf(prefix);
8382 if (sidx == -1) {
8383 // Not a temp file. just ignore
8384 continue;
8385 }
8386 String subStr = name.substring(sidx + prefix.length());
8387 idList[idx] = -1;
8388 if (subStr != null) {
8389 try {
8390 int cid = Integer.parseInt(subStr);
8391 idList[idx++] = cid;
8392 neverFound = false;
8393 } catch (NumberFormatException e) {
8394 }
8395 }
8396 }
8397 if (!neverFound) {
8398 // Sort idList
8399 Arrays.sort(idList);
8400 for (int j = 1; j <= idList.length; j++) {
8401 if (idList[j-1] != j) {
8402 tmpIdx = j;
8403 break;
8404 }
8405 }
8406 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008407 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008408 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008409 }
8410
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008411 public void updateExternalMediaStatus(final boolean mediaStatus) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008412 final boolean DEBUG = true;
8413 if (DEBUG) Log.i(TAG, "updateExterMediaStatus::");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008414 if (mediaStatus == mMediaMounted) {
8415 return;
8416 }
8417 mMediaMounted = mediaStatus;
8418 // Queue up an async operation since the package installation may take a little while.
8419 mHandler.post(new Runnable() {
8420 public void run() {
8421 mHandler.removeCallbacks(this);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008422 updateExternalMediaStatusInner(mediaStatus);
8423 }
8424 });
8425 }
8426
8427 void updateExternalMediaStatusInner(boolean mediaStatus) {
8428 final String list[] = getSecureContainerList();
8429 if (list == null || list.length == 0) {
8430 return;
8431 }
8432 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
8433 int uidList[] = new int[list.length];
8434 int num = 0;
8435 for (int i = 0; i < uidList.length; i++) {
8436 uidList[i] = Process.LAST_APPLICATION_UID;
8437 }
8438 synchronized (mPackages) {
8439 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8440 for (String cid : list) {
8441 SdInstallArgs args = new SdInstallArgs(cid);
8442 String removeEntry = null;
8443 for (String app : appList) {
8444 if (args.matchContainer(app)) {
8445 removeEntry = app;
8446 break;
8447 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008448 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008449 if (removeEntry == null) {
8450 // No matching app on device. Skip entry or may be cleanup?
8451 // Ignore default package
8452 continue;
8453 }
8454 appList.remove(removeEntry);
8455 PackageSetting ps = mSettings.mPackages.get(removeEntry);
8456 processCids.put(args, ps.codePathString);
8457 int uid = ps.userId;
8458 if (uid != -1) {
8459 int idx = Arrays.binarySearch(uidList, uid);
8460 if (idx < 0) {
8461 uidList[-idx] = uid;
8462 num++;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008463 }
8464 }
8465 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008466 }
8467 int uidArr[] = uidList;
8468 if ((num > 0) && (num < uidList.length)) {
8469 uidArr = new int[num];
8470 for (int i = 0; i < num; i++) {
8471 uidArr[i] = uidList[i];
8472 }
8473 }
8474 if (mediaStatus) {
8475 loadMediaPackages(processCids, uidArr);
8476 } else {
8477 unloadMediaPackages(processCids, uidArr);
8478 }
8479 }
8480
8481 private void sendResourcesChangedBroadcast(boolean mediaStatus,
8482 ArrayList<String> pkgList, int uidArr[]) {
8483 int size = pkgList.size();
8484 if (size > 0) {
8485 // Send broadcasts here
8486 Bundle extras = new Bundle();
8487 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
8488 pkgList.toArray(new String[size]));
8489 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
8490 String action = mediaStatus ? Intent.ACTION_MEDIA_RESOURCES_AVAILABLE
8491 : Intent.ACTION_MEDIA_RESOURCES_UNAVAILABLE;
8492 sendPackageBroadcast(action, null, extras);
8493 }
8494 }
8495
8496 void loadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
8497 ArrayList<String> pkgList = new ArrayList<String>();
8498 Set<SdInstallArgs> keys = processCids.keySet();
8499 for (SdInstallArgs args : keys) {
8500 String cid = args.cid;
8501 String codePath = processCids.get(args);
8502 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
8503 Log.i(TAG, "Failed to install package: " + codePath + " from sdcard");
8504 continue;
8505 }
8506 // Parse package
8507 int parseFlags = PackageParser.PARSE_CHATTY |
8508 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8509 PackageParser pp = new PackageParser(codePath);
8510 pp.setSeparateProcesses(mSeparateProcesses);
8511 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
8512 codePath, mMetrics, parseFlags);
8513 if (pkg == null) {
8514 Log.w(TAG, "Failed to install package : " + cid + " from sd card");
8515 continue;
8516 }
8517 setApplicationInfoPaths(pkg, codePath, codePath);
8518 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8519 synchronized (mInstallLock) {
8520 // Scan the package
8521 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
8522 synchronized (mPackages) {
8523 // Grant permissions
8524 grantPermissionsLP(pkg, false);
8525 // Persist settings
8526 mSettings.writeLP();
8527 retCode = PackageManager.INSTALL_SUCCEEDED;
8528 pkgList.add(pkg.packageName);
8529 }
8530 } else {
8531 Log.i(TAG, "Failed to install package: " + pkg.packageName + " from sdcard");
8532 }
8533 }
8534 args.doPostInstall(retCode);
8535 pkgList.add(pkg.packageName);
8536 }
8537 // Send broadcasts first
8538 sendResourcesChangedBroadcast(true, pkgList, uidArr);
8539 Runtime.getRuntime().gc();
8540 // If something failed do we clean up here or next install?
8541 }
8542
8543 void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
8544 ArrayList<String> pkgList = new ArrayList<String>();
8545 Set<SdInstallArgs> keys = processCids.keySet();
8546 for (SdInstallArgs args : keys) {
8547 String cid = args.cid;
8548 String pkgName = args.getPackageName();
8549 // STOPSHIP Send broadcast to apps to remove references
8550 // STOPSHIP Unmount package
8551 // Delete package internally
8552 PackageRemovedInfo outInfo = new PackageRemovedInfo();
8553 synchronized (mInstallLock) {
8554 boolean res = deletePackageLI(pkgName, false,
8555 PackageManager.DONT_DELETE_DATA, outInfo);
8556 if (res) {
8557 pkgList.add(pkgName);
8558 } else {
8559 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
8560 }
8561 }
8562 }
8563 // Send broadcasts
8564 sendResourcesChangedBroadcast(false, pkgList, uidArr);
8565 Runtime.getRuntime().gc();
8566 // Do clean up. Just unmount
8567 for (SdInstallArgs args : keys) {
8568 synchronized (mInstallLock) {
8569 args.doPostDeleteLI(false);
8570 }
8571 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008573}