blob: f7e3cea0d05a163cbb3b3fba3e84e049fdcb5c89 [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 Amalapurapudaec1722010-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 Amalapurapudaec1722010-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 Amalapurapudaec1722010-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 Hackbornc14b9cc2009-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 Hackbornc14b9cc2009-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 Hackbornc14b9cc2009-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 Hackbornc14b9cc2009-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 Hackbornc14b9cc2009-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 Amalapurapub56ae202010-02-04 22:51:07 -08004962 boolean replace = 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
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08004968 // Retrieve PackageSettings and parse package
4969 int parseFlags = PackageParser.PARSE_CHATTY |
4970 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
4971 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
4972 parseFlags |= mDefParseFlags;
4973 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
4974 pp.setSeparateProcesses(mSeparateProcesses);
4975 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
4976 null, mMetrics, parseFlags);
4977 if (pkg == null) {
4978 res.returnCode = pp.getParseError();
4979 return;
4980 }
4981 String pkgName = res.name = pkg.packageName;
4982 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
4983 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
4984 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
4985 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004986 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08004987 }
4988 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
4989 res.returnCode = pp.getParseError();
4990 return;
4991 }
4992 // Some preinstall checks
4993 if (forwardLocked && onSd) {
4994 // Make sure forward locked apps can only be installed
4995 // on internal storage
4996 Log.w(TAG, "Cannot install protected apps on sdcard");
4997 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4998 return;
4999 }
5000 // Get rid of all references to package scan path via parser.
5001 pp = null;
5002 String oldCodePath = null;
5003 boolean systemApp = false;
5004 synchronized (mPackages) {
5005 // Check if installing already existing package
5006 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
5007 && mPackages.containsKey(pkgName)) {
5008 replace = true;
5009 }
5010 PackageSetting ps = mSettings.mPackages.get(pkgName);
5011 if (ps != null) {
5012 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5013 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5014 systemApp = (ps.pkg.applicationInfo.flags &
5015 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005016 }
5017 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005018 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005019
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005020 if (systemApp && onSd) {
5021 // Disable updates to system apps on sdcard
5022 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5023 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5024 return;
5025 }
5026 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5027 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5028 return;
5029 }
5030 // Set application objects path explicitly after the rename
5031 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
5032 if(replace) {
5033 replacePackageLI(pkg, parseFlags, scanMode,
5034 installerPackageName, res);
5035 } else {
5036 installNewPackageLI(pkg, parseFlags, scanMode,
5037 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 }
5039 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005040
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005041 private int setPermissionsLI(PackageParser.Package newPackage) {
5042 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005043 int retCode = 0;
5044 // TODO Gross hack but fix later. Ideally move this to be a post installation
5045 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005046 if ((newPackage.applicationInfo.flags
5047 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5048 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005049 try {
5050 extractPublicFiles(newPackage, destResourceFile);
5051 } catch (IOException e) {
5052 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5053 " forward-locked app.");
5054 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5055 } finally {
5056 //TODO clean up the extracted public files
5057 }
5058 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005059 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005060 newPackage.applicationInfo.uid);
5061 } else {
5062 final int filePermissions =
5063 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005064 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 newPackage.applicationInfo.uid);
5066 }
5067 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005068 // The permissions on the resource file was set when it was copied for
5069 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005073 Log.e(TAG, "Couldn't set new package file permissions for " +
5074 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005075 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005076 // TODO Define new internal error
5077 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005078 }
5079 return PackageManager.INSTALL_SUCCEEDED;
5080 }
5081
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005082 private boolean isForwardLocked(PackageParser.Package pkg) {
5083 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005084 }
5085
5086 private void extractPublicFiles(PackageParser.Package newPackage,
5087 File publicZipFile) throws IOException {
5088 final ZipOutputStream publicZipOutStream =
5089 new ZipOutputStream(new FileOutputStream(publicZipFile));
5090 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5091
5092 // Copy manifest, resources.arsc and res directory to public zip
5093
5094 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5095 while (privateZipEntries.hasMoreElements()) {
5096 final ZipEntry zipEntry = privateZipEntries.nextElement();
5097 final String zipEntryName = zipEntry.getName();
5098 if ("AndroidManifest.xml".equals(zipEntryName)
5099 || "resources.arsc".equals(zipEntryName)
5100 || zipEntryName.startsWith("res/")) {
5101 try {
5102 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5103 } catch (IOException e) {
5104 try {
5105 publicZipOutStream.close();
5106 throw e;
5107 } finally {
5108 publicZipFile.delete();
5109 }
5110 }
5111 }
5112 }
5113
5114 publicZipOutStream.close();
5115 FileUtils.setPermissions(
5116 publicZipFile.getAbsolutePath(),
5117 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5118 -1, -1);
5119 }
5120
5121 private static void copyZipEntry(ZipEntry zipEntry,
5122 ZipFile inZipFile,
5123 ZipOutputStream outZipStream) throws IOException {
5124 byte[] buffer = new byte[4096];
5125 int num;
5126
5127 ZipEntry newEntry;
5128 if (zipEntry.getMethod() == ZipEntry.STORED) {
5129 // Preserve the STORED method of the input entry.
5130 newEntry = new ZipEntry(zipEntry);
5131 } else {
5132 // Create a new entry so that the compressed len is recomputed.
5133 newEntry = new ZipEntry(zipEntry.getName());
5134 }
5135 outZipStream.putNextEntry(newEntry);
5136
5137 InputStream data = inZipFile.getInputStream(zipEntry);
5138 while ((num = data.read(buffer)) > 0) {
5139 outZipStream.write(buffer, 0, num);
5140 }
5141 outZipStream.flush();
5142 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144 private void deleteTempPackageFiles() {
5145 FilenameFilter filter = new FilenameFilter() {
5146 public boolean accept(File dir, String name) {
5147 return name.startsWith("vmdl") && name.endsWith(".tmp");
5148 }
5149 };
5150 String tmpFilesList[] = mAppInstallDir.list(filter);
5151 if(tmpFilesList == null) {
5152 return;
5153 }
5154 for(int i = 0; i < tmpFilesList.length; i++) {
5155 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5156 tmpFile.delete();
5157 }
5158 }
5159
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005160 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005161 File tmpPackageFile;
5162 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005163 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005164 } catch (IOException e) {
5165 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5166 return null;
5167 }
5168 try {
5169 FileUtils.setPermissions(
5170 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5171 -1, -1);
5172 } catch (IOException e) {
5173 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5174 return null;
5175 }
5176 return tmpPackageFile;
5177 }
5178
5179 public void deletePackage(final String packageName,
5180 final IPackageDeleteObserver observer,
5181 final int flags) {
5182 mContext.enforceCallingOrSelfPermission(
5183 android.Manifest.permission.DELETE_PACKAGES, null);
5184 // Queue up an async operation since the package deletion may take a little while.
5185 mHandler.post(new Runnable() {
5186 public void run() {
5187 mHandler.removeCallbacks(this);
5188 final boolean succeded = deletePackageX(packageName, true, true, flags);
5189 if (observer != null) {
5190 try {
5191 observer.packageDeleted(succeded);
5192 } catch (RemoteException e) {
5193 Log.i(TAG, "Observer no longer exists.");
5194 } //end catch
5195 } //end if
5196 } //end run
5197 });
5198 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 /**
5201 * This method is an internal method that could be get invoked either
5202 * to delete an installed package or to clean up a failed installation.
5203 * After deleting an installed package, a broadcast is sent to notify any
5204 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005205 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005206 * installation wouldn't have sent the initial broadcast either
5207 * The key steps in deleting a package are
5208 * deleting the package information in internal structures like mPackages,
5209 * deleting the packages base directories through installd
5210 * updating mSettings to reflect current status
5211 * persisting settings for later use
5212 * sending a broadcast if necessary
5213 */
5214
5215 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5216 boolean deleteCodeAndResources, int flags) {
5217 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005218 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219
5220 synchronized (mInstallLock) {
5221 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5222 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005225 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5226 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5227
5228 // If the removed package was a system update, the old system packaged
5229 // was re-enabled; we need to broadcast this information
5230 if (systemUpdate) {
5231 Bundle extras = new Bundle(1);
5232 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5233 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5234
5235 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5236 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005238 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005239 // Delete the resources here after sending the broadcast to let
5240 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005241 if (info.args != null) {
5242 synchronized (mInstallLock) {
5243 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005244 }
5245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 return res;
5247 }
5248
5249 static class PackageRemovedInfo {
5250 String removedPackage;
5251 int uid = -1;
5252 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005253 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005254 // Clean up resources deleted packages.
5255 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257 void sendBroadcast(boolean fullRemove, boolean replacing) {
5258 Bundle extras = new Bundle(1);
5259 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5260 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5261 if (replacing) {
5262 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5263 }
5264 if (removedPackage != null) {
5265 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5266 }
5267 if (removedUid >= 0) {
5268 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5269 }
5270 }
5271 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 /*
5274 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5275 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005276 * 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 -08005277 * delete a partially installed application.
5278 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005279 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005280 int flags) {
5281 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005282 if (outInfo != null) {
5283 outInfo.removedPackage = packageName;
5284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005285 removePackageLI(p, true);
5286 // Retrieve object to delete permissions for shared user later on
5287 PackageSetting deletedPs;
5288 synchronized (mPackages) {
5289 deletedPs = mSettings.mPackages.get(packageName);
5290 }
5291 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005292 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005293 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005294 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005295 if (retCode < 0) {
5296 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5297 + packageName + ", retcode=" + retCode);
5298 // we don't consider this to be a failure of the core package deletion
5299 }
5300 } else {
5301 //for emulator
5302 PackageParser.Package pkg = mPackages.get(packageName);
5303 File dataDir = new File(pkg.applicationInfo.dataDir);
5304 dataDir.delete();
5305 }
5306 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005307 if (outInfo != null) {
5308 outInfo.removedUid = mSettings.removePackageLP(packageName);
5309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005310 }
5311 }
5312 synchronized (mPackages) {
5313 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5314 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005315 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005316 }
5317 // Save settings now
5318 mSettings.writeLP ();
5319 }
5320 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005322 /*
5323 * Tries to delete system package.
5324 */
5325 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005326 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 ApplicationInfo applicationInfo = p.applicationInfo;
5328 //applicable for non-partially installed applications only
5329 if (applicationInfo == null) {
5330 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5331 return false;
5332 }
5333 PackageSetting ps = null;
5334 // Confirm if the system package has been updated
5335 // An updated system app can be deleted. This will also have to restore
5336 // the system pkg from system partition
5337 synchronized (mPackages) {
5338 ps = mSettings.getDisabledSystemPkg(p.packageName);
5339 }
5340 if (ps == null) {
5341 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5342 return false;
5343 } else {
5344 Log.i(TAG, "Deleting system pkg from data partition");
5345 }
5346 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005347 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005348 boolean deleteCodeAndResources = false;
5349 if (ps.versionCode < p.mVersionCode) {
5350 // Delete code and resources for downgrades
5351 deleteCodeAndResources = true;
5352 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5353 flags &= ~PackageManager.DONT_DELETE_DATA;
5354 }
5355 } else {
5356 // Preserve data by setting flag
5357 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5358 flags |= PackageManager.DONT_DELETE_DATA;
5359 }
5360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5362 if (!ret) {
5363 return false;
5364 }
5365 synchronized (mPackages) {
5366 // Reinstate the old system package
5367 mSettings.enableSystemPackageLP(p.packageName);
5368 }
5369 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005370 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005371 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005372 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 if (newPkg == null) {
5375 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5376 return false;
5377 }
5378 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005379 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380 mSettings.writeLP();
5381 }
5382 return true;
5383 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005385 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5386 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5387 ApplicationInfo applicationInfo = p.applicationInfo;
5388 if (applicationInfo == null) {
5389 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5390 return false;
5391 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005392 if (outInfo != null) {
5393 outInfo.uid = applicationInfo.uid;
5394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395
5396 // Delete package data from internal structures and also remove data if flag is set
5397 removePackageDataLI(p, outInfo, flags);
5398
5399 // Delete application code and resources
5400 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005401 // TODO can pick up from PackageSettings as well
5402 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
5403 PackageManager.INSTALL_ON_SDCARD : 0;
5404 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5405 PackageManager.INSTALL_FORWARD_LOCK : 0;
5406 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005407 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005408 }
5409 return true;
5410 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005412 /*
5413 * This method handles package deletion in general
5414 */
5415 private boolean deletePackageLI(String packageName,
5416 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5417 if (packageName == null) {
5418 Log.w(TAG, "Attempt to delete null packageName.");
5419 return false;
5420 }
5421 PackageParser.Package p;
5422 boolean dataOnly = false;
5423 synchronized (mPackages) {
5424 p = mPackages.get(packageName);
5425 if (p == null) {
5426 //this retrieves partially installed apps
5427 dataOnly = true;
5428 PackageSetting ps = mSettings.mPackages.get(packageName);
5429 if (ps == null) {
5430 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5431 return false;
5432 }
5433 p = ps.pkg;
5434 }
5435 }
5436 if (p == null) {
5437 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5438 return false;
5439 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 if (dataOnly) {
5442 // Delete application data first
5443 removePackageDataLI(p, outInfo, flags);
5444 return true;
5445 }
5446 // At this point the package should have ApplicationInfo associated with it
5447 if (p.applicationInfo == null) {
5448 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5449 return false;
5450 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005451 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5453 Log.i(TAG, "Removing system package:"+p.packageName);
5454 // When an updated system application is deleted we delete the existing resources as well and
5455 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005456 ret = deleteSystemPackageLI(p, flags, outInfo);
5457 } else {
5458 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005459 // Kill application pre-emptively especially for apps on sd.
5460 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005461 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005462 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005463 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 public void clearApplicationUserData(final String packageName,
5467 final IPackageDataObserver observer) {
5468 mContext.enforceCallingOrSelfPermission(
5469 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5470 // Queue up an async operation since the package deletion may take a little while.
5471 mHandler.post(new Runnable() {
5472 public void run() {
5473 mHandler.removeCallbacks(this);
5474 final boolean succeeded;
5475 synchronized (mInstallLock) {
5476 succeeded = clearApplicationUserDataLI(packageName);
5477 }
5478 if (succeeded) {
5479 // invoke DeviceStorageMonitor's update method to clear any notifications
5480 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5481 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5482 if (dsm != null) {
5483 dsm.updateMemory();
5484 }
5485 }
5486 if(observer != null) {
5487 try {
5488 observer.onRemoveCompleted(packageName, succeeded);
5489 } catch (RemoteException e) {
5490 Log.i(TAG, "Observer no longer exists.");
5491 }
5492 } //end if observer
5493 } //end run
5494 });
5495 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005497 private boolean clearApplicationUserDataLI(String packageName) {
5498 if (packageName == null) {
5499 Log.w(TAG, "Attempt to delete null packageName.");
5500 return false;
5501 }
5502 PackageParser.Package p;
5503 boolean dataOnly = false;
5504 synchronized (mPackages) {
5505 p = mPackages.get(packageName);
5506 if(p == null) {
5507 dataOnly = true;
5508 PackageSetting ps = mSettings.mPackages.get(packageName);
5509 if((ps == null) || (ps.pkg == null)) {
5510 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5511 return false;
5512 }
5513 p = ps.pkg;
5514 }
5515 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005516 boolean useEncryptedFSDir = false;
5517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 if(!dataOnly) {
5519 //need to check this only for fully installed applications
5520 if (p == null) {
5521 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5522 return false;
5523 }
5524 final ApplicationInfo applicationInfo = p.applicationInfo;
5525 if (applicationInfo == null) {
5526 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5527 return false;
5528 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005529 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 }
5531 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005532 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005533 if (retCode < 0) {
5534 Log.w(TAG, "Couldn't remove cache files for package: "
5535 + packageName);
5536 return false;
5537 }
5538 }
5539 return true;
5540 }
5541
5542 public void deleteApplicationCacheFiles(final String packageName,
5543 final IPackageDataObserver observer) {
5544 mContext.enforceCallingOrSelfPermission(
5545 android.Manifest.permission.DELETE_CACHE_FILES, null);
5546 // Queue up an async operation since the package deletion may take a little while.
5547 mHandler.post(new Runnable() {
5548 public void run() {
5549 mHandler.removeCallbacks(this);
5550 final boolean succeded;
5551 synchronized (mInstallLock) {
5552 succeded = deleteApplicationCacheFilesLI(packageName);
5553 }
5554 if(observer != null) {
5555 try {
5556 observer.onRemoveCompleted(packageName, succeded);
5557 } catch (RemoteException e) {
5558 Log.i(TAG, "Observer no longer exists.");
5559 }
5560 } //end if observer
5561 } //end run
5562 });
5563 }
5564
5565 private boolean deleteApplicationCacheFilesLI(String packageName) {
5566 if (packageName == null) {
5567 Log.w(TAG, "Attempt to delete null packageName.");
5568 return false;
5569 }
5570 PackageParser.Package p;
5571 synchronized (mPackages) {
5572 p = mPackages.get(packageName);
5573 }
5574 if (p == null) {
5575 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5576 return false;
5577 }
5578 final ApplicationInfo applicationInfo = p.applicationInfo;
5579 if (applicationInfo == null) {
5580 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5581 return false;
5582 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005583 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005584 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005585 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 if (retCode < 0) {
5587 Log.w(TAG, "Couldn't remove cache files for package: "
5588 + packageName);
5589 return false;
5590 }
5591 }
5592 return true;
5593 }
5594
5595 public void getPackageSizeInfo(final String packageName,
5596 final IPackageStatsObserver observer) {
5597 mContext.enforceCallingOrSelfPermission(
5598 android.Manifest.permission.GET_PACKAGE_SIZE, null);
5599 // Queue up an async operation since the package deletion may take a little while.
5600 mHandler.post(new Runnable() {
5601 public void run() {
5602 mHandler.removeCallbacks(this);
5603 PackageStats lStats = new PackageStats(packageName);
5604 final boolean succeded;
5605 synchronized (mInstallLock) {
5606 succeded = getPackageSizeInfoLI(packageName, lStats);
5607 }
5608 if(observer != null) {
5609 try {
5610 observer.onGetStatsCompleted(lStats, succeded);
5611 } catch (RemoteException e) {
5612 Log.i(TAG, "Observer no longer exists.");
5613 }
5614 } //end if observer
5615 } //end run
5616 });
5617 }
5618
5619 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
5620 if (packageName == null) {
5621 Log.w(TAG, "Attempt to get size of null packageName.");
5622 return false;
5623 }
5624 PackageParser.Package p;
5625 boolean dataOnly = false;
5626 synchronized (mPackages) {
5627 p = mPackages.get(packageName);
5628 if(p == null) {
5629 dataOnly = true;
5630 PackageSetting ps = mSettings.mPackages.get(packageName);
5631 if((ps == null) || (ps.pkg == null)) {
5632 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5633 return false;
5634 }
5635 p = ps.pkg;
5636 }
5637 }
5638 String publicSrcDir = null;
5639 if(!dataOnly) {
5640 final ApplicationInfo applicationInfo = p.applicationInfo;
5641 if (applicationInfo == null) {
5642 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5643 return false;
5644 }
5645 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
5646 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005647 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005648 if (mInstaller != null) {
5649 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08005650 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 if (res < 0) {
5652 return false;
5653 } else {
5654 return true;
5655 }
5656 }
5657 return true;
5658 }
5659
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 public void addPackageToPreferred(String packageName) {
5662 mContext.enforceCallingOrSelfPermission(
5663 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005664 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 }
5666
5667 public void removePackageFromPreferred(String packageName) {
5668 mContext.enforceCallingOrSelfPermission(
5669 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005670 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 }
5672
5673 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005674 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 }
5676
5677 public void addPreferredActivity(IntentFilter filter, int match,
5678 ComponentName[] set, ComponentName activity) {
5679 mContext.enforceCallingOrSelfPermission(
5680 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5681
5682 synchronized (mPackages) {
5683 Log.i(TAG, "Adding preferred activity " + activity + ":");
5684 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5685 mSettings.mPreferredActivities.addFilter(
5686 new PreferredActivity(filter, match, set, activity));
5687 mSettings.writeLP();
5688 }
5689 }
5690
Satish Sampath8dbe6122009-06-02 23:35:54 +01005691 public void replacePreferredActivity(IntentFilter filter, int match,
5692 ComponentName[] set, ComponentName activity) {
5693 mContext.enforceCallingOrSelfPermission(
5694 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5695 if (filter.countActions() != 1) {
5696 throw new IllegalArgumentException(
5697 "replacePreferredActivity expects filter to have only 1 action.");
5698 }
5699 if (filter.countCategories() != 1) {
5700 throw new IllegalArgumentException(
5701 "replacePreferredActivity expects filter to have only 1 category.");
5702 }
5703 if (filter.countDataAuthorities() != 0
5704 || filter.countDataPaths() != 0
5705 || filter.countDataSchemes() != 0
5706 || filter.countDataTypes() != 0) {
5707 throw new IllegalArgumentException(
5708 "replacePreferredActivity expects filter to have no data authorities, " +
5709 "paths, schemes or types.");
5710 }
5711 synchronized (mPackages) {
5712 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5713 String action = filter.getAction(0);
5714 String category = filter.getCategory(0);
5715 while (it.hasNext()) {
5716 PreferredActivity pa = it.next();
5717 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5718 it.remove();
5719 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5720 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5721 }
5722 }
5723 addPreferredActivity(filter, match, set, activity);
5724 }
5725 }
5726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 public void clearPackagePreferredActivities(String packageName) {
5728 mContext.enforceCallingOrSelfPermission(
5729 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5730
5731 synchronized (mPackages) {
5732 if (clearPackagePreferredActivitiesLP(packageName)) {
5733 mSettings.writeLP();
5734 }
5735 }
5736 }
5737
5738 boolean clearPackagePreferredActivitiesLP(String packageName) {
5739 boolean changed = false;
5740 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5741 while (it.hasNext()) {
5742 PreferredActivity pa = it.next();
5743 if (pa.mActivity.getPackageName().equals(packageName)) {
5744 it.remove();
5745 changed = true;
5746 }
5747 }
5748 return changed;
5749 }
5750
5751 public int getPreferredActivities(List<IntentFilter> outFilters,
5752 List<ComponentName> outActivities, String packageName) {
5753
5754 int num = 0;
5755 synchronized (mPackages) {
5756 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5757 while (it.hasNext()) {
5758 PreferredActivity pa = it.next();
5759 if (packageName == null
5760 || pa.mActivity.getPackageName().equals(packageName)) {
5761 if (outFilters != null) {
5762 outFilters.add(new IntentFilter(pa));
5763 }
5764 if (outActivities != null) {
5765 outActivities.add(pa.mActivity);
5766 }
5767 }
5768 }
5769 }
5770
5771 return num;
5772 }
5773
5774 public void setApplicationEnabledSetting(String appPackageName,
5775 int newState, int flags) {
5776 setEnabledSetting(appPackageName, null, newState, flags);
5777 }
5778
5779 public void setComponentEnabledSetting(ComponentName componentName,
5780 int newState, int flags) {
5781 setEnabledSetting(componentName.getPackageName(),
5782 componentName.getClassName(), newState, flags);
5783 }
5784
5785 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005786 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5788 || newState == COMPONENT_ENABLED_STATE_ENABLED
5789 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5790 throw new IllegalArgumentException("Invalid new component state: "
5791 + newState);
5792 }
5793 PackageSetting pkgSetting;
5794 final int uid = Binder.getCallingUid();
5795 final int permission = mContext.checkCallingPermission(
5796 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5797 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005798 boolean sendNow = false;
5799 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005800 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005801 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005802 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005804 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005805 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005806 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005807 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005808 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 }
5810 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005811 "Unknown component: " + packageName
5812 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005813 }
5814 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5815 throw new SecurityException(
5816 "Permission Denial: attempt to change component state from pid="
5817 + Binder.getCallingPid()
5818 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5819 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005820 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 // We're dealing with an application/package level state change
5822 pkgSetting.enabled = newState;
5823 } else {
5824 // We're dealing with a component level state change
5825 switch (newState) {
5826 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005827 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 break;
5829 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005830 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 break;
5832 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005833 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 break;
5835 default:
5836 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005837 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005838 }
5839 }
5840 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005841 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005842 components = mPendingBroadcasts.get(packageName);
5843 boolean newPackage = components == null;
5844 if (newPackage) {
5845 components = new ArrayList<String>();
5846 }
5847 if (!components.contains(componentName)) {
5848 components.add(componentName);
5849 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005850 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5851 sendNow = true;
5852 // Purge entry from pending broadcast list if another one exists already
5853 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005854 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005855 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005856 if (newPackage) {
5857 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005858 }
5859 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5860 // Schedule a message
5861 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5862 }
5863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 long callingId = Binder.clearCallingIdentity();
5867 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005868 if (sendNow) {
5869 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005870 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005872 } finally {
5873 Binder.restoreCallingIdentity(callingId);
5874 }
5875 }
5876
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005877 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005878 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
5879 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
5880 + " components=" + componentNames);
5881 Bundle extras = new Bundle(4);
5882 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
5883 String nameList[] = new String[componentNames.size()];
5884 componentNames.toArray(nameList);
5885 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005886 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5887 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005888 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005889 }
5890
Jacek Surazski65e13172009-04-28 15:26:38 +02005891 public String getInstallerPackageName(String packageName) {
5892 synchronized (mPackages) {
5893 PackageSetting pkg = mSettings.mPackages.get(packageName);
5894 if (pkg == null) {
5895 throw new IllegalArgumentException("Unknown package: " + packageName);
5896 }
5897 return pkg.installerPackageName;
5898 }
5899 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005901 public int getApplicationEnabledSetting(String appPackageName) {
5902 synchronized (mPackages) {
5903 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5904 if (pkg == null) {
5905 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5906 }
5907 return pkg.enabled;
5908 }
5909 }
5910
5911 public int getComponentEnabledSetting(ComponentName componentName) {
5912 synchronized (mPackages) {
5913 final String packageNameStr = componentName.getPackageName();
5914 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5915 if (pkg == null) {
5916 throw new IllegalArgumentException("Unknown component: " + componentName);
5917 }
5918 final String classNameStr = componentName.getClassName();
5919 return pkg.currentEnabledStateLP(classNameStr);
5920 }
5921 }
5922
5923 public void enterSafeMode() {
5924 if (!mSystemReady) {
5925 mSafeMode = true;
5926 }
5927 }
5928
5929 public void systemReady() {
5930 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005931
5932 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005933 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005934 mContext.getContentResolver(),
5935 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005936 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005937 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005938 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 }
5941
5942 public boolean isSafeMode() {
5943 return mSafeMode;
5944 }
5945
5946 public boolean hasSystemUidErrors() {
5947 return mHasSystemUidErrors;
5948 }
5949
5950 static String arrayToString(int[] array) {
5951 StringBuffer buf = new StringBuffer(128);
5952 buf.append('[');
5953 if (array != null) {
5954 for (int i=0; i<array.length; i++) {
5955 if (i > 0) buf.append(", ");
5956 buf.append(array[i]);
5957 }
5958 }
5959 buf.append(']');
5960 return buf.toString();
5961 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 @Override
5964 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5965 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5966 != PackageManager.PERMISSION_GRANTED) {
5967 pw.println("Permission Denial: can't dump ActivityManager from from pid="
5968 + Binder.getCallingPid()
5969 + ", uid=" + Binder.getCallingUid()
5970 + " without permission "
5971 + android.Manifest.permission.DUMP);
5972 return;
5973 }
5974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975 synchronized (mPackages) {
5976 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005977 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 pw.println(" ");
5979 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005980 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 pw.println(" ");
5982 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005983 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 pw.println(" ");
5985 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005986 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 pw.println("Permissions:");
5989 {
5990 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005991 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
5992 pw.print(Integer.toHexString(System.identityHashCode(p)));
5993 pw.println("):");
5994 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
5995 pw.print(" uid="); pw.print(p.uid);
5996 pw.print(" gids="); pw.print(arrayToString(p.gids));
5997 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005998 }
5999 }
6000 pw.println(" ");
6001 pw.println("Packages:");
6002 {
6003 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006004 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
6005 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6006 pw.println("):");
6007 pw.print(" userId="); pw.print(ps.userId);
6008 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6009 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6010 pw.print(" pkg="); pw.println(ps.pkg);
6011 pw.print(" codePath="); pw.println(ps.codePathString);
6012 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006014 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006015 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006016 pw.print(" supportsScreens=[");
6017 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006018 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006019 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006020 if (!first) pw.print(", ");
6021 first = false;
6022 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006023 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006024 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006025 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006026 if (!first) pw.print(", ");
6027 first = false;
6028 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006029 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006030 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006031 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006032 if (!first) pw.print(", ");
6033 first = false;
6034 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006035 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006036 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006037 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006038 if (!first) pw.print(", ");
6039 first = false;
6040 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006041 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006042 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006043 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6044 if (!first) pw.print(", ");
6045 first = false;
6046 pw.print("anyDensity");
6047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006049 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006050 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6051 pw.print(" signatures="); pw.println(ps.signatures);
6052 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6053 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6054 pw.print(" installStatus="); pw.print(ps.installStatus);
6055 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 if (ps.disabledComponents.size() > 0) {
6057 pw.println(" disabledComponents:");
6058 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006059 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060 }
6061 }
6062 if (ps.enabledComponents.size() > 0) {
6063 pw.println(" enabledComponents:");
6064 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006065 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 }
6067 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006068 if (ps.grantedPermissions.size() > 0) {
6069 pw.println(" grantedPermissions:");
6070 for (String s : ps.grantedPermissions) {
6071 pw.print(" "); pw.println(s);
6072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006073 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006074 if (ps.loadedPermissions.size() > 0) {
6075 pw.println(" loadedPermissions:");
6076 for (String s : ps.loadedPermissions) {
6077 pw.print(" "); pw.println(s);
6078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 }
6080 }
6081 }
6082 pw.println(" ");
6083 pw.println("Shared Users:");
6084 {
6085 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006086 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6087 pw.print(Integer.toHexString(System.identityHashCode(su)));
6088 pw.println("):");
6089 pw.print(" userId="); pw.print(su.userId);
6090 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 pw.println(" grantedPermissions:");
6092 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006093 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 }
6095 pw.println(" loadedPermissions:");
6096 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006097 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006098 }
6099 }
6100 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 pw.println(" ");
6103 pw.println("Settings parse messages:");
6104 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006105
6106 pw.println(" ");
6107 pw.println("Package warning messages:");
6108 File fname = getSettingsProblemFile();
6109 FileInputStream in;
6110 try {
6111 in = new FileInputStream(fname);
6112 int avail = in.available();
6113 byte[] data = new byte[avail];
6114 in.read(data);
6115 pw.println(new String(data));
6116 } catch (FileNotFoundException e) {
6117 } catch (IOException e) {
6118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006120
6121 synchronized (mProviders) {
6122 pw.println(" ");
6123 pw.println("Registered ContentProviders:");
6124 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006125 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006126 pw.println(p.toString());
6127 }
6128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 }
6130
6131 static final class BasePermission {
6132 final static int TYPE_NORMAL = 0;
6133 final static int TYPE_BUILTIN = 1;
6134 final static int TYPE_DYNAMIC = 2;
6135
6136 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006137 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 final int type;
6139 PackageParser.Permission perm;
6140 PermissionInfo pendingInfo;
6141 int uid;
6142 int[] gids;
6143
6144 BasePermission(String _name, String _sourcePackage, int _type) {
6145 name = _name;
6146 sourcePackage = _sourcePackage;
6147 type = _type;
6148 }
6149 }
6150
6151 static class PackageSignatures {
6152 private Signature[] mSignatures;
6153
6154 PackageSignatures(Signature[] sigs) {
6155 assignSignatures(sigs);
6156 }
6157
6158 PackageSignatures() {
6159 }
6160
6161 void writeXml(XmlSerializer serializer, String tagName,
6162 ArrayList<Signature> pastSignatures) throws IOException {
6163 if (mSignatures == null) {
6164 return;
6165 }
6166 serializer.startTag(null, tagName);
6167 serializer.attribute(null, "count",
6168 Integer.toString(mSignatures.length));
6169 for (int i=0; i<mSignatures.length; i++) {
6170 serializer.startTag(null, "cert");
6171 final Signature sig = mSignatures[i];
6172 final int sigHash = sig.hashCode();
6173 final int numPast = pastSignatures.size();
6174 int j;
6175 for (j=0; j<numPast; j++) {
6176 Signature pastSig = pastSignatures.get(j);
6177 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6178 serializer.attribute(null, "index", Integer.toString(j));
6179 break;
6180 }
6181 }
6182 if (j >= numPast) {
6183 pastSignatures.add(sig);
6184 serializer.attribute(null, "index", Integer.toString(numPast));
6185 serializer.attribute(null, "key", sig.toCharsString());
6186 }
6187 serializer.endTag(null, "cert");
6188 }
6189 serializer.endTag(null, tagName);
6190 }
6191
6192 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6193 throws IOException, XmlPullParserException {
6194 String countStr = parser.getAttributeValue(null, "count");
6195 if (countStr == null) {
6196 reportSettingsProblem(Log.WARN,
6197 "Error in package manager settings: <signatures> has"
6198 + " no count at " + parser.getPositionDescription());
6199 XmlUtils.skipCurrentTag(parser);
6200 }
6201 final int count = Integer.parseInt(countStr);
6202 mSignatures = new Signature[count];
6203 int pos = 0;
6204
6205 int outerDepth = parser.getDepth();
6206 int type;
6207 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6208 && (type != XmlPullParser.END_TAG
6209 || parser.getDepth() > outerDepth)) {
6210 if (type == XmlPullParser.END_TAG
6211 || type == XmlPullParser.TEXT) {
6212 continue;
6213 }
6214
6215 String tagName = parser.getName();
6216 if (tagName.equals("cert")) {
6217 if (pos < count) {
6218 String index = parser.getAttributeValue(null, "index");
6219 if (index != null) {
6220 try {
6221 int idx = Integer.parseInt(index);
6222 String key = parser.getAttributeValue(null, "key");
6223 if (key == null) {
6224 if (idx >= 0 && idx < pastSignatures.size()) {
6225 Signature sig = pastSignatures.get(idx);
6226 if (sig != null) {
6227 mSignatures[pos] = pastSignatures.get(idx);
6228 pos++;
6229 } else {
6230 reportSettingsProblem(Log.WARN,
6231 "Error in package manager settings: <cert> "
6232 + "index " + index + " is not defined at "
6233 + parser.getPositionDescription());
6234 }
6235 } else {
6236 reportSettingsProblem(Log.WARN,
6237 "Error in package manager settings: <cert> "
6238 + "index " + index + " is out of bounds at "
6239 + parser.getPositionDescription());
6240 }
6241 } else {
6242 while (pastSignatures.size() <= idx) {
6243 pastSignatures.add(null);
6244 }
6245 Signature sig = new Signature(key);
6246 pastSignatures.set(idx, sig);
6247 mSignatures[pos] = sig;
6248 pos++;
6249 }
6250 } catch (NumberFormatException e) {
6251 reportSettingsProblem(Log.WARN,
6252 "Error in package manager settings: <cert> "
6253 + "index " + index + " is not a number at "
6254 + parser.getPositionDescription());
6255 }
6256 } else {
6257 reportSettingsProblem(Log.WARN,
6258 "Error in package manager settings: <cert> has"
6259 + " no index at " + parser.getPositionDescription());
6260 }
6261 } else {
6262 reportSettingsProblem(Log.WARN,
6263 "Error in package manager settings: too "
6264 + "many <cert> tags, expected " + count
6265 + " at " + parser.getPositionDescription());
6266 }
6267 } else {
6268 reportSettingsProblem(Log.WARN,
6269 "Unknown element under <cert>: "
6270 + parser.getName());
6271 }
6272 XmlUtils.skipCurrentTag(parser);
6273 }
6274
6275 if (pos < count) {
6276 // Should never happen -- there is an error in the written
6277 // settings -- but if it does we don't want to generate
6278 // a bad array.
6279 Signature[] newSigs = new Signature[pos];
6280 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6281 mSignatures = newSigs;
6282 }
6283 }
6284
6285 /**
6286 * If any of the given 'sigs' is contained in the existing signatures,
6287 * then completely replace the current signatures with the ones in
6288 * 'sigs'. This is used for updating an existing package to a newly
6289 * installed version.
6290 */
6291 boolean updateSignatures(Signature[] sigs, boolean update) {
6292 if (mSignatures == null) {
6293 if (update) {
6294 assignSignatures(sigs);
6295 }
6296 return true;
6297 }
6298 if (sigs == null) {
6299 return false;
6300 }
6301
6302 for (int i=0; i<sigs.length; i++) {
6303 Signature sig = sigs[i];
6304 for (int j=0; j<mSignatures.length; j++) {
6305 if (mSignatures[j].equals(sig)) {
6306 if (update) {
6307 assignSignatures(sigs);
6308 }
6309 return true;
6310 }
6311 }
6312 }
6313 return false;
6314 }
6315
6316 /**
6317 * If any of the given 'sigs' is contained in the existing signatures,
6318 * then add in any new signatures found in 'sigs'. This is used for
6319 * including a new package into an existing shared user id.
6320 */
6321 boolean mergeSignatures(Signature[] sigs, boolean update) {
6322 if (mSignatures == null) {
6323 if (update) {
6324 assignSignatures(sigs);
6325 }
6326 return true;
6327 }
6328 if (sigs == null) {
6329 return false;
6330 }
6331
6332 Signature[] added = null;
6333 int addedCount = 0;
6334 boolean haveMatch = false;
6335 for (int i=0; i<sigs.length; i++) {
6336 Signature sig = sigs[i];
6337 boolean found = false;
6338 for (int j=0; j<mSignatures.length; j++) {
6339 if (mSignatures[j].equals(sig)) {
6340 found = true;
6341 haveMatch = true;
6342 break;
6343 }
6344 }
6345
6346 if (!found) {
6347 if (added == null) {
6348 added = new Signature[sigs.length];
6349 }
6350 added[i] = sig;
6351 addedCount++;
6352 }
6353 }
6354
6355 if (!haveMatch) {
6356 // Nothing matched -- reject the new signatures.
6357 return false;
6358 }
6359 if (added == null) {
6360 // Completely matched -- nothing else to do.
6361 return true;
6362 }
6363
6364 // Add additional signatures in.
6365 if (update) {
6366 Signature[] total = new Signature[addedCount+mSignatures.length];
6367 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6368 int j = mSignatures.length;
6369 for (int i=0; i<added.length; i++) {
6370 if (added[i] != null) {
6371 total[j] = added[i];
6372 j++;
6373 }
6374 }
6375 mSignatures = total;
6376 }
6377 return true;
6378 }
6379
6380 private void assignSignatures(Signature[] sigs) {
6381 if (sigs == null) {
6382 mSignatures = null;
6383 return;
6384 }
6385 mSignatures = new Signature[sigs.length];
6386 for (int i=0; i<sigs.length; i++) {
6387 mSignatures[i] = sigs[i];
6388 }
6389 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 @Override
6392 public String toString() {
6393 StringBuffer buf = new StringBuffer(128);
6394 buf.append("PackageSignatures{");
6395 buf.append(Integer.toHexString(System.identityHashCode(this)));
6396 buf.append(" [");
6397 if (mSignatures != null) {
6398 for (int i=0; i<mSignatures.length; i++) {
6399 if (i > 0) buf.append(", ");
6400 buf.append(Integer.toHexString(
6401 System.identityHashCode(mSignatures[i])));
6402 }
6403 }
6404 buf.append("]}");
6405 return buf.toString();
6406 }
6407 }
6408
6409 static class PreferredActivity extends IntentFilter {
6410 final int mMatch;
6411 final String[] mSetPackages;
6412 final String[] mSetClasses;
6413 final String[] mSetComponents;
6414 final ComponentName mActivity;
6415 final String mShortActivity;
6416 String mParseError;
6417
6418 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6419 ComponentName activity) {
6420 super(filter);
6421 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6422 mActivity = activity;
6423 mShortActivity = activity.flattenToShortString();
6424 mParseError = null;
6425 if (set != null) {
6426 final int N = set.length;
6427 String[] myPackages = new String[N];
6428 String[] myClasses = new String[N];
6429 String[] myComponents = new String[N];
6430 for (int i=0; i<N; i++) {
6431 ComponentName cn = set[i];
6432 if (cn == null) {
6433 mSetPackages = null;
6434 mSetClasses = null;
6435 mSetComponents = null;
6436 return;
6437 }
6438 myPackages[i] = cn.getPackageName().intern();
6439 myClasses[i] = cn.getClassName().intern();
6440 myComponents[i] = cn.flattenToShortString().intern();
6441 }
6442 mSetPackages = myPackages;
6443 mSetClasses = myClasses;
6444 mSetComponents = myComponents;
6445 } else {
6446 mSetPackages = null;
6447 mSetClasses = null;
6448 mSetComponents = null;
6449 }
6450 }
6451
6452 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6453 IOException {
6454 mShortActivity = parser.getAttributeValue(null, "name");
6455 mActivity = ComponentName.unflattenFromString(mShortActivity);
6456 if (mActivity == null) {
6457 mParseError = "Bad activity name " + mShortActivity;
6458 }
6459 String matchStr = parser.getAttributeValue(null, "match");
6460 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6461 String setCountStr = parser.getAttributeValue(null, "set");
6462 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6463
6464 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6465 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6466 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6467
6468 int setPos = 0;
6469
6470 int outerDepth = parser.getDepth();
6471 int type;
6472 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6473 && (type != XmlPullParser.END_TAG
6474 || parser.getDepth() > outerDepth)) {
6475 if (type == XmlPullParser.END_TAG
6476 || type == XmlPullParser.TEXT) {
6477 continue;
6478 }
6479
6480 String tagName = parser.getName();
6481 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6482 // + parser.getDepth() + " tag=" + tagName);
6483 if (tagName.equals("set")) {
6484 String name = parser.getAttributeValue(null, "name");
6485 if (name == null) {
6486 if (mParseError == null) {
6487 mParseError = "No name in set tag in preferred activity "
6488 + mShortActivity;
6489 }
6490 } else if (setPos >= setCount) {
6491 if (mParseError == null) {
6492 mParseError = "Too many set tags in preferred activity "
6493 + mShortActivity;
6494 }
6495 } else {
6496 ComponentName cn = ComponentName.unflattenFromString(name);
6497 if (cn == null) {
6498 if (mParseError == null) {
6499 mParseError = "Bad set name " + name + " in preferred activity "
6500 + mShortActivity;
6501 }
6502 } else {
6503 myPackages[setPos] = cn.getPackageName();
6504 myClasses[setPos] = cn.getClassName();
6505 myComponents[setPos] = name;
6506 setPos++;
6507 }
6508 }
6509 XmlUtils.skipCurrentTag(parser);
6510 } else if (tagName.equals("filter")) {
6511 //Log.i(TAG, "Starting to parse filter...");
6512 readFromXml(parser);
6513 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6514 // + parser.getDepth() + " tag=" + parser.getName());
6515 } else {
6516 reportSettingsProblem(Log.WARN,
6517 "Unknown element under <preferred-activities>: "
6518 + parser.getName());
6519 XmlUtils.skipCurrentTag(parser);
6520 }
6521 }
6522
6523 if (setPos != setCount) {
6524 if (mParseError == null) {
6525 mParseError = "Not enough set tags (expected " + setCount
6526 + " but found " + setPos + ") in " + mShortActivity;
6527 }
6528 }
6529
6530 mSetPackages = myPackages;
6531 mSetClasses = myClasses;
6532 mSetComponents = myComponents;
6533 }
6534
6535 public void writeToXml(XmlSerializer serializer) throws IOException {
6536 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6537 serializer.attribute(null, "name", mShortActivity);
6538 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6539 serializer.attribute(null, "set", Integer.toString(NS));
6540 for (int s=0; s<NS; s++) {
6541 serializer.startTag(null, "set");
6542 serializer.attribute(null, "name", mSetComponents[s]);
6543 serializer.endTag(null, "set");
6544 }
6545 serializer.startTag(null, "filter");
6546 super.writeToXml(serializer);
6547 serializer.endTag(null, "filter");
6548 }
6549
6550 boolean sameSet(List<ResolveInfo> query, int priority) {
6551 if (mSetPackages == null) return false;
6552 final int NQ = query.size();
6553 final int NS = mSetPackages.length;
6554 int numMatch = 0;
6555 for (int i=0; i<NQ; i++) {
6556 ResolveInfo ri = query.get(i);
6557 if (ri.priority != priority) continue;
6558 ActivityInfo ai = ri.activityInfo;
6559 boolean good = false;
6560 for (int j=0; j<NS; j++) {
6561 if (mSetPackages[j].equals(ai.packageName)
6562 && mSetClasses[j].equals(ai.name)) {
6563 numMatch++;
6564 good = true;
6565 break;
6566 }
6567 }
6568 if (!good) return false;
6569 }
6570 return numMatch == NS;
6571 }
6572 }
6573
6574 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006575 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 HashSet<String> grantedPermissions = new HashSet<String>();
6578 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006582 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08006583 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
6584 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
6585 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 }
6587 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006589 /**
6590 * Settings base class for pending and resolved classes.
6591 */
6592 static class PackageSettingBase extends GrantedPermissions {
6593 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006594 File codePath;
6595 String codePathString;
6596 File resourcePath;
6597 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 private long timeStamp;
6599 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006600 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006601
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006602 boolean uidError;
6603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 PackageSignatures signatures = new PackageSignatures();
6605
6606 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 /* Explicitly disabled components */
6609 HashSet<String> disabledComponents = new HashSet<String>(0);
6610 /* Explicitly enabled components */
6611 HashSet<String> enabledComponents = new HashSet<String>(0);
6612 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6613 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006614
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006615 PackageSettingBase origPackage;
6616
Jacek Surazski65e13172009-04-28 15:26:38 +02006617 /* package name of the app that installed this package */
6618 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006619
6620 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006621 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006622 super(pkgFlags);
6623 this.name = name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006624 init(codePath, resourcePath, pVersionCode);
6625 }
6626
6627 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 this.codePath = codePath;
6629 this.codePathString = codePath.toString();
6630 this.resourcePath = resourcePath;
6631 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006632 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006634
Jacek Surazski65e13172009-04-28 15:26:38 +02006635 public void setInstallerPackageName(String packageName) {
6636 installerPackageName = packageName;
6637 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006638
Jacek Surazski65e13172009-04-28 15:26:38 +02006639 String getInstallerPackageName() {
6640 return installerPackageName;
6641 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006643 public void setInstallStatus(int newStatus) {
6644 installStatus = newStatus;
6645 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006647 public int getInstallStatus() {
6648 return installStatus;
6649 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006651 public void setTimeStamp(long newStamp) {
6652 if (newStamp != timeStamp) {
6653 timeStamp = newStamp;
6654 timeStampString = Long.toString(newStamp);
6655 }
6656 }
6657
6658 public void setTimeStamp(long newStamp, String newStampStr) {
6659 timeStamp = newStamp;
6660 timeStampString = newStampStr;
6661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 public long getTimeStamp() {
6664 return timeStamp;
6665 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 public String getTimeStampStr() {
6668 return timeStampString;
6669 }
6670
6671 public void copyFrom(PackageSettingBase base) {
6672 grantedPermissions = base.grantedPermissions;
6673 gids = base.gids;
6674 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006676 timeStamp = base.timeStamp;
6677 timeStampString = base.timeStampString;
6678 signatures = base.signatures;
6679 permissionsFixed = base.permissionsFixed;
6680 disabledComponents = base.disabledComponents;
6681 enabledComponents = base.enabledComponents;
6682 enabled = base.enabled;
6683 installStatus = base.installStatus;
6684 }
6685
6686 void enableComponentLP(String componentClassName) {
6687 disabledComponents.remove(componentClassName);
6688 enabledComponents.add(componentClassName);
6689 }
6690
6691 void disableComponentLP(String componentClassName) {
6692 enabledComponents.remove(componentClassName);
6693 disabledComponents.add(componentClassName);
6694 }
6695
6696 void restoreComponentLP(String componentClassName) {
6697 enabledComponents.remove(componentClassName);
6698 disabledComponents.remove(componentClassName);
6699 }
6700
6701 int currentEnabledStateLP(String componentName) {
6702 if (enabledComponents.contains(componentName)) {
6703 return COMPONENT_ENABLED_STATE_ENABLED;
6704 } else if (disabledComponents.contains(componentName)) {
6705 return COMPONENT_ENABLED_STATE_DISABLED;
6706 } else {
6707 return COMPONENT_ENABLED_STATE_DEFAULT;
6708 }
6709 }
6710 }
6711
6712 /**
6713 * Settings data for a particular package we know about.
6714 */
6715 static final class PackageSetting extends PackageSettingBase {
6716 int userId;
6717 PackageParser.Package pkg;
6718 SharedUserSetting sharedUser;
6719
6720 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006721 int pVersionCode, int pkgFlags) {
6722 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006723 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006725 @Override
6726 public String toString() {
6727 return "PackageSetting{"
6728 + Integer.toHexString(System.identityHashCode(this))
6729 + " " + name + "/" + userId + "}";
6730 }
6731 }
6732
6733 /**
6734 * Settings data for a particular shared user ID we know about.
6735 */
6736 static final class SharedUserSetting extends GrantedPermissions {
6737 final String name;
6738 int userId;
6739 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6740 final PackageSignatures signatures = new PackageSignatures();
6741
6742 SharedUserSetting(String _name, int _pkgFlags) {
6743 super(_pkgFlags);
6744 name = _name;
6745 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 @Override
6748 public String toString() {
6749 return "SharedUserSetting{"
6750 + Integer.toHexString(System.identityHashCode(this))
6751 + " " + name + "/" + userId + "}";
6752 }
6753 }
6754
6755 /**
6756 * Holds information about dynamic settings.
6757 */
6758 private static final class Settings {
6759 private final File mSettingsFilename;
6760 private final File mBackupSettingsFilename;
6761 private final HashMap<String, PackageSetting> mPackages =
6762 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006763 // List of replaced system applications
6764 final HashMap<String, PackageSetting> mDisabledSysPackages =
6765 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 // The user's preferred activities associated with particular intent
6768 // filters.
6769 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6770 new IntentResolver<PreferredActivity, PreferredActivity>() {
6771 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006772 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006773 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006774 out.print(prefix); out.print(
6775 Integer.toHexString(System.identityHashCode(filter)));
6776 out.print(' ');
6777 out.print(filter.mActivity.flattenToShortString());
6778 out.print(" match=0x");
6779 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006780 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006781 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006782 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006783 out.print(prefix); out.print(" ");
6784 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006785 }
6786 }
6787 }
6788 };
6789 private final HashMap<String, SharedUserSetting> mSharedUsers =
6790 new HashMap<String, SharedUserSetting>();
6791 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6792 private final SparseArray<Object> mOtherUserIds =
6793 new SparseArray<Object>();
6794
6795 // For reading/writing settings file.
6796 private final ArrayList<Signature> mPastSignatures =
6797 new ArrayList<Signature>();
6798
6799 // Mapping from permission names to info about them.
6800 final HashMap<String, BasePermission> mPermissions =
6801 new HashMap<String, BasePermission>();
6802
6803 // Mapping from permission tree names to info about them.
6804 final HashMap<String, BasePermission> mPermissionTrees =
6805 new HashMap<String, BasePermission>();
6806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006807 private final StringBuilder mReadMessages = new StringBuilder();
6808
6809 private static final class PendingPackage extends PackageSettingBase {
6810 final int sharedId;
6811
6812 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006813 int sharedId, int pVersionCode, int pkgFlags) {
6814 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 this.sharedId = sharedId;
6816 }
6817 }
6818 private final ArrayList<PendingPackage> mPendingPackages
6819 = new ArrayList<PendingPackage>();
6820
6821 Settings() {
6822 File dataDir = Environment.getDataDirectory();
6823 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08006824 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
6825 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006826 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08006827 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006828 FileUtils.setPermissions(systemDir.toString(),
6829 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6830 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6831 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08006832 FileUtils.setPermissions(systemSecureDir.toString(),
6833 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6834 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6835 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 mSettingsFilename = new File(systemDir, "packages.xml");
6837 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6838 }
6839
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006840 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006841 SharedUserSetting sharedUser, File codePath, File resourcePath,
6842 int pkgFlags, boolean create, boolean add) {
6843 final String name = pkg.packageName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006844 PackageSetting p = getPackageLP(name, origPackage, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006845 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006846 return p;
6847 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006848
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006849 PackageSetting peekPackageLP(String name) {
6850 return mPackages.get(name);
6851 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006852 PackageSetting p = mPackages.get(name);
6853 if (p != null && p.codePath.getPath().equals(codePath)) {
6854 return p;
6855 }
6856 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006857 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006860 void setInstallStatus(String pkgName, int status) {
6861 PackageSetting p = mPackages.get(pkgName);
6862 if(p != null) {
6863 if(p.getInstallStatus() != status) {
6864 p.setInstallStatus(status);
6865 }
6866 }
6867 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006868
Jacek Surazski65e13172009-04-28 15:26:38 +02006869 void setInstallerPackageName(String pkgName,
6870 String installerPkgName) {
6871 PackageSetting p = mPackages.get(pkgName);
6872 if(p != null) {
6873 p.setInstallerPackageName(installerPkgName);
6874 }
6875 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006876
Jacek Surazski65e13172009-04-28 15:26:38 +02006877 String getInstallerPackageName(String pkgName) {
6878 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006879 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02006880 }
6881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006882 int getInstallStatus(String pkgName) {
6883 PackageSetting p = mPackages.get(pkgName);
6884 if(p != null) {
6885 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006887 return -1;
6888 }
6889
6890 SharedUserSetting getSharedUserLP(String name,
6891 int pkgFlags, boolean create) {
6892 SharedUserSetting s = mSharedUsers.get(name);
6893 if (s == null) {
6894 if (!create) {
6895 return null;
6896 }
6897 s = new SharedUserSetting(name, pkgFlags);
6898 if (MULTIPLE_APPLICATION_UIDS) {
6899 s.userId = newUserIdLP(s);
6900 } else {
6901 s.userId = FIRST_APPLICATION_UID;
6902 }
6903 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6904 // < 0 means we couldn't assign a userid; fall out and return
6905 // s, which is currently null
6906 if (s.userId >= 0) {
6907 mSharedUsers.put(name, s);
6908 }
6909 }
6910
6911 return s;
6912 }
6913
6914 int disableSystemPackageLP(String name) {
6915 PackageSetting p = mPackages.get(name);
6916 if(p == null) {
6917 Log.w(TAG, "Package:"+name+" is not an installed package");
6918 return -1;
6919 }
6920 PackageSetting dp = mDisabledSysPackages.get(name);
6921 // always make sure the system package code and resource paths dont change
6922 if(dp == null) {
6923 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6924 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6925 }
6926 mDisabledSysPackages.put(name, p);
6927 }
6928 return removePackageLP(name);
6929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006931 PackageSetting enableSystemPackageLP(String name) {
6932 PackageSetting p = mDisabledSysPackages.get(name);
6933 if(p == null) {
6934 Log.w(TAG, "Package:"+name+" is not disabled");
6935 return null;
6936 }
6937 // Reset flag in ApplicationInfo object
6938 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6939 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6940 }
6941 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006942 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006943 mDisabledSysPackages.remove(name);
6944 return ret;
6945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006948 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006949 PackageSetting p = mPackages.get(name);
6950 if (p != null) {
6951 if (p.userId == uid) {
6952 return p;
6953 }
6954 reportSettingsProblem(Log.ERROR,
6955 "Adding duplicate package, keeping first: " + name);
6956 return null;
6957 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006958 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006959 p.userId = uid;
6960 if (addUserIdLP(uid, p, name)) {
6961 mPackages.put(name, p);
6962 return p;
6963 }
6964 return null;
6965 }
6966
6967 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
6968 SharedUserSetting s = mSharedUsers.get(name);
6969 if (s != null) {
6970 if (s.userId == uid) {
6971 return s;
6972 }
6973 reportSettingsProblem(Log.ERROR,
6974 "Adding duplicate shared user, keeping first: " + name);
6975 return null;
6976 }
6977 s = new SharedUserSetting(name, pkgFlags);
6978 s.userId = uid;
6979 if (addUserIdLP(uid, s, name)) {
6980 mSharedUsers.put(name, s);
6981 return s;
6982 }
6983 return null;
6984 }
6985
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006986 // Transfer ownership of permissions from one package to another.
6987 private void transferPermissions(String origPkg, String newPkg) {
6988 // Transfer ownership of permissions to the new package.
6989 for (int i=0; i<2; i++) {
6990 HashMap<String, BasePermission> permissions =
6991 i == 0 ? mPermissionTrees : mPermissions;
6992 for (BasePermission bp : permissions.values()) {
6993 if (origPkg.equals(bp.sourcePackage)) {
6994 if (DEBUG_UPGRADE) Log.v(TAG,
6995 "Moving permission " + bp.name
6996 + " from pkg " + bp.sourcePackage
6997 + " to " + newPkg);
6998 bp.sourcePackage = newPkg;
6999 bp.perm = null;
7000 if (bp.pendingInfo != null) {
7001 bp.sourcePackage = newPkg;
7002 }
7003 bp.uid = 0;
7004 bp.gids = null;
7005 }
7006 }
7007 }
7008 }
7009
7010 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007012 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007013 PackageSetting p = mPackages.get(name);
7014 if (p != null) {
7015 if (!p.codePath.equals(codePath)) {
7016 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007017 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007018 // This is an updated system app with versions in both system
7019 // and data partition. Just let the most recent version
7020 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007021 Log.w(TAG, "Trying to update system app code path from " +
7022 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007023 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007024 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07007025 reportSettingsProblem(Log.WARN,
7026 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007027 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007029 }
7030 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007031 reportSettingsProblem(Log.WARN,
7032 "Package " + name + " shared user changed from "
7033 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7034 + " to "
7035 + (sharedUser != null ? sharedUser.name : "<nothing>")
7036 + "; replacing with new");
7037 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007038 } else {
7039 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7040 // If what we are scanning is a system package, then
7041 // make it so, regardless of whether it was previously
7042 // installed only in the data partition.
7043 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007045 }
7046 }
7047 if (p == null) {
7048 // Create a new PackageSettings entry. this can end up here because
7049 // of code path mismatch or user id mismatch of an updated system partition
7050 if (!create) {
7051 return null;
7052 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007053 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007054 if (origPackage != null) {
7055 // We are consuming the data from an existing package.
7056 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7057 + " is adopting original package " + origPackage.name);
7058 p.copyFrom(origPackage);
7059 p.sharedUser = origPackage.sharedUser;
7060 p.userId = origPackage.userId;
7061 p.origPackage = origPackage;
7062 transferPermissions(origPackage.name, name);
7063 // Update new package state.
7064 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007065 } else {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007066 p.setTimeStamp(codePath.lastModified());
7067 p.sharedUser = sharedUser;
7068 if (sharedUser != null) {
7069 p.userId = sharedUser.userId;
7070 } else if (MULTIPLE_APPLICATION_UIDS) {
7071 // Clone the setting here for disabled system packages
7072 PackageSetting dis = mDisabledSysPackages.get(name);
7073 if (dis != null) {
7074 // For disabled packages a new setting is created
7075 // from the existing user id. This still has to be
7076 // added to list of user id's
7077 // Copy signatures from previous setting
7078 if (dis.signatures.mSignatures != null) {
7079 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7080 }
7081 p.userId = dis.userId;
7082 // Clone permissions
7083 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7084 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7085 // Clone component info
7086 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7087 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7088 // Add new setting to list of user ids
7089 addUserIdLP(p.userId, p, name);
7090 } else {
7091 // Assign new user id
7092 p.userId = newUserIdLP(p);
7093 }
7094 } else {
7095 p.userId = FIRST_APPLICATION_UID;
7096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007097 }
7098 if (p.userId < 0) {
7099 reportSettingsProblem(Log.WARN,
7100 "Package " + name + " could not be assigned a valid uid");
7101 return null;
7102 }
7103 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007104 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007105 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007106 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007107 }
7108 }
7109 return p;
7110 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007111
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007112 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007113 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007114 String codePath = pkg.applicationInfo.sourceDir;
7115 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007116 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007117 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007118 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007119 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007120 p.codePath = new File(codePath);
7121 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007122 }
7123 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007124 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007125 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007126 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007127 p.resourcePath = new File(resourcePath);
7128 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007129 }
7130 // Update version code if needed
7131 if (pkg.mVersionCode != p.versionCode) {
7132 p.versionCode = pkg.mVersionCode;
7133 }
7134 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7135 }
7136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007137 // Utility method that adds a PackageSetting to mPackages and
7138 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007139 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007140 SharedUserSetting sharedUser) {
7141 mPackages.put(name, p);
7142 if (sharedUser != null) {
7143 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7144 reportSettingsProblem(Log.ERROR,
7145 "Package " + p.name + " was user "
7146 + p.sharedUser + " but is now " + sharedUser
7147 + "; I am not changing its files so it will probably fail!");
7148 p.sharedUser.packages.remove(p);
7149 } else if (p.userId != sharedUser.userId) {
7150 reportSettingsProblem(Log.ERROR,
7151 "Package " + p.name + " was user id " + p.userId
7152 + " but is now user " + sharedUser
7153 + " with id " + sharedUser.userId
7154 + "; I am not changing its files so it will probably fail!");
7155 }
7156
7157 sharedUser.packages.add(p);
7158 p.sharedUser = sharedUser;
7159 p.userId = sharedUser.userId;
7160 }
7161 }
7162
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007163 /*
7164 * Update the shared user setting when a package using
7165 * specifying the shared user id is removed. The gids
7166 * associated with each permission of the deleted package
7167 * are removed from the shared user's gid list only if its
7168 * not in use by other permissions of packages in the
7169 * shared user setting.
7170 */
7171 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007172 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7173 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7174 return;
7175 }
7176 // No sharedUserId
7177 if (deletedPs.sharedUser == null) {
7178 return;
7179 }
7180 SharedUserSetting sus = deletedPs.sharedUser;
7181 // Update permissions
7182 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7183 boolean used = false;
7184 if (!sus.grantedPermissions.contains (eachPerm)) {
7185 continue;
7186 }
7187 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007188 if (pkg.pkg != null &&
7189 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7190 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007191 used = true;
7192 break;
7193 }
7194 }
7195 if (!used) {
7196 // can safely delete this permission from list
7197 sus.grantedPermissions.remove(eachPerm);
7198 sus.loadedPermissions.remove(eachPerm);
7199 }
7200 }
7201 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007202 int newGids[] = globalGids;
7203 for (String eachPerm : sus.grantedPermissions) {
7204 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007205 if (bp != null) {
7206 newGids = appendInts(newGids, bp.gids);
7207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007208 }
7209 sus.gids = newGids;
7210 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007212 private int removePackageLP(String name) {
7213 PackageSetting p = mPackages.get(name);
7214 if (p != null) {
7215 mPackages.remove(name);
7216 if (p.sharedUser != null) {
7217 p.sharedUser.packages.remove(p);
7218 if (p.sharedUser.packages.size() == 0) {
7219 mSharedUsers.remove(p.sharedUser.name);
7220 removeUserIdLP(p.sharedUser.userId);
7221 return p.sharedUser.userId;
7222 }
7223 } else {
7224 removeUserIdLP(p.userId);
7225 return p.userId;
7226 }
7227 }
7228 return -1;
7229 }
7230
7231 private boolean addUserIdLP(int uid, Object obj, Object name) {
7232 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7233 return false;
7234 }
7235
7236 if (uid >= FIRST_APPLICATION_UID) {
7237 int N = mUserIds.size();
7238 final int index = uid - FIRST_APPLICATION_UID;
7239 while (index >= N) {
7240 mUserIds.add(null);
7241 N++;
7242 }
7243 if (mUserIds.get(index) != null) {
7244 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007245 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007246 + " name=" + name);
7247 return false;
7248 }
7249 mUserIds.set(index, obj);
7250 } else {
7251 if (mOtherUserIds.get(uid) != null) {
7252 reportSettingsProblem(Log.ERROR,
7253 "Adding duplicate shared id: " + uid
7254 + " name=" + name);
7255 return false;
7256 }
7257 mOtherUserIds.put(uid, obj);
7258 }
7259 return true;
7260 }
7261
7262 public Object getUserIdLP(int uid) {
7263 if (uid >= FIRST_APPLICATION_UID) {
7264 int N = mUserIds.size();
7265 final int index = uid - FIRST_APPLICATION_UID;
7266 return index < N ? mUserIds.get(index) : null;
7267 } else {
7268 return mOtherUserIds.get(uid);
7269 }
7270 }
7271
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007272 private Set<String> findPackagesWithFlag(int flag) {
7273 Set<String> ret = new HashSet<String>();
7274 for (PackageSetting ps : mPackages.values()) {
7275 // Has to match atleast all the flag bits set on flag
7276 if ((ps.pkgFlags & flag) == flag) {
7277 ret.add(ps.name);
7278 }
7279 }
7280 return ret;
7281 }
7282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007283 private void removeUserIdLP(int uid) {
7284 if (uid >= FIRST_APPLICATION_UID) {
7285 int N = mUserIds.size();
7286 final int index = uid - FIRST_APPLICATION_UID;
7287 if (index < N) mUserIds.set(index, null);
7288 } else {
7289 mOtherUserIds.remove(uid);
7290 }
7291 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007293 void writeLP() {
7294 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7295
7296 // Keep the old settings around until we know the new ones have
7297 // been successfully written.
7298 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007299 // Presence of backup settings file indicates that we failed
7300 // to persist settings earlier. So preserve the older
7301 // backup for future reference since the current settings
7302 // might have been corrupted.
7303 if (!mBackupSettingsFilename.exists()) {
7304 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7305 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7306 return;
7307 }
7308 } else {
7309 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007311 }
7312
7313 mPastSignatures.clear();
7314
7315 try {
7316 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7317
7318 //XmlSerializer serializer = XmlUtils.serializerInstance();
7319 XmlSerializer serializer = new FastXmlSerializer();
7320 serializer.setOutput(str, "utf-8");
7321 serializer.startDocument(null, true);
7322 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7323
7324 serializer.startTag(null, "packages");
7325
7326 serializer.startTag(null, "permission-trees");
7327 for (BasePermission bp : mPermissionTrees.values()) {
7328 writePermission(serializer, bp);
7329 }
7330 serializer.endTag(null, "permission-trees");
7331
7332 serializer.startTag(null, "permissions");
7333 for (BasePermission bp : mPermissions.values()) {
7334 writePermission(serializer, bp);
7335 }
7336 serializer.endTag(null, "permissions");
7337
7338 for (PackageSetting pkg : mPackages.values()) {
7339 writePackage(serializer, pkg);
7340 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7343 writeDisabledSysPackage(serializer, pkg);
7344 }
7345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007346 serializer.startTag(null, "preferred-activities");
7347 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7348 serializer.startTag(null, "item");
7349 pa.writeToXml(serializer);
7350 serializer.endTag(null, "item");
7351 }
7352 serializer.endTag(null, "preferred-activities");
7353
7354 for (SharedUserSetting usr : mSharedUsers.values()) {
7355 serializer.startTag(null, "shared-user");
7356 serializer.attribute(null, "name", usr.name);
7357 serializer.attribute(null, "userId",
7358 Integer.toString(usr.userId));
7359 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7360 serializer.startTag(null, "perms");
7361 for (String name : usr.grantedPermissions) {
7362 serializer.startTag(null, "item");
7363 serializer.attribute(null, "name", name);
7364 serializer.endTag(null, "item");
7365 }
7366 serializer.endTag(null, "perms");
7367 serializer.endTag(null, "shared-user");
7368 }
7369
7370 serializer.endTag(null, "packages");
7371
7372 serializer.endDocument();
7373
7374 str.flush();
7375 str.close();
7376
7377 // New settings successfully written, old ones are no longer
7378 // needed.
7379 mBackupSettingsFilename.delete();
7380 FileUtils.setPermissions(mSettingsFilename.toString(),
7381 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7382 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7383 |FileUtils.S_IROTH,
7384 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007385 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007386
7387 } catch(XmlPullParserException e) {
7388 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 -08007389 } catch(java.io.IOException e) {
7390 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 -08007391 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007392 // Clean up partially written file
7393 if (mSettingsFilename.exists()) {
7394 if (!mSettingsFilename.delete()) {
7395 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7396 }
7397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007398 //Debug.stopMethodTracing();
7399 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007400
7401 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007402 throws java.io.IOException {
7403 serializer.startTag(null, "updated-package");
7404 serializer.attribute(null, "name", pkg.name);
7405 serializer.attribute(null, "codePath", pkg.codePathString);
7406 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007407 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007408 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7409 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7410 }
7411 if (pkg.sharedUser == null) {
7412 serializer.attribute(null, "userId",
7413 Integer.toString(pkg.userId));
7414 } else {
7415 serializer.attribute(null, "sharedUserId",
7416 Integer.toString(pkg.userId));
7417 }
7418 serializer.startTag(null, "perms");
7419 if (pkg.sharedUser == null) {
7420 // If this is a shared user, the permissions will
7421 // be written there. We still need to write an
7422 // empty permissions list so permissionsFixed will
7423 // be set.
7424 for (final String name : pkg.grantedPermissions) {
7425 BasePermission bp = mPermissions.get(name);
7426 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7427 // We only need to write signature or system permissions but this wont
7428 // match the semantics of grantedPermissions. So write all permissions.
7429 serializer.startTag(null, "item");
7430 serializer.attribute(null, "name", name);
7431 serializer.endTag(null, "item");
7432 }
7433 }
7434 }
7435 serializer.endTag(null, "perms");
7436 serializer.endTag(null, "updated-package");
7437 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007438
7439 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007440 throws java.io.IOException {
7441 serializer.startTag(null, "package");
7442 serializer.attribute(null, "name", pkg.name);
7443 serializer.attribute(null, "codePath", pkg.codePathString);
7444 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7445 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7446 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007447 serializer.attribute(null, "flags",
7448 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007449 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007450 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007451 if (pkg.sharedUser == null) {
7452 serializer.attribute(null, "userId",
7453 Integer.toString(pkg.userId));
7454 } else {
7455 serializer.attribute(null, "sharedUserId",
7456 Integer.toString(pkg.userId));
7457 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007458 if (pkg.uidError) {
7459 serializer.attribute(null, "uidError", "true");
7460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007461 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
7462 serializer.attribute(null, "enabled",
7463 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
7464 ? "true" : "false");
7465 }
7466 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
7467 serializer.attribute(null, "installStatus", "false");
7468 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007469 if (pkg.installerPackageName != null) {
7470 serializer.attribute(null, "installer", pkg.installerPackageName);
7471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007472 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
7473 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7474 serializer.startTag(null, "perms");
7475 if (pkg.sharedUser == null) {
7476 // If this is a shared user, the permissions will
7477 // be written there. We still need to write an
7478 // empty permissions list so permissionsFixed will
7479 // be set.
7480 for (final String name : pkg.grantedPermissions) {
7481 serializer.startTag(null, "item");
7482 serializer.attribute(null, "name", name);
7483 serializer.endTag(null, "item");
7484 }
7485 }
7486 serializer.endTag(null, "perms");
7487 }
7488 if (pkg.disabledComponents.size() > 0) {
7489 serializer.startTag(null, "disabled-components");
7490 for (final String name : pkg.disabledComponents) {
7491 serializer.startTag(null, "item");
7492 serializer.attribute(null, "name", name);
7493 serializer.endTag(null, "item");
7494 }
7495 serializer.endTag(null, "disabled-components");
7496 }
7497 if (pkg.enabledComponents.size() > 0) {
7498 serializer.startTag(null, "enabled-components");
7499 for (final String name : pkg.enabledComponents) {
7500 serializer.startTag(null, "item");
7501 serializer.attribute(null, "name", name);
7502 serializer.endTag(null, "item");
7503 }
7504 serializer.endTag(null, "enabled-components");
7505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507 serializer.endTag(null, "package");
7508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007510 void writePermission(XmlSerializer serializer, BasePermission bp)
7511 throws XmlPullParserException, java.io.IOException {
7512 if (bp.type != BasePermission.TYPE_BUILTIN
7513 && bp.sourcePackage != null) {
7514 serializer.startTag(null, "item");
7515 serializer.attribute(null, "name", bp.name);
7516 serializer.attribute(null, "package", bp.sourcePackage);
7517 if (DEBUG_SETTINGS) Log.v(TAG,
7518 "Writing perm: name=" + bp.name + " type=" + bp.type);
7519 if (bp.type == BasePermission.TYPE_DYNAMIC) {
7520 PermissionInfo pi = bp.perm != null ? bp.perm.info
7521 : bp.pendingInfo;
7522 if (pi != null) {
7523 serializer.attribute(null, "type", "dynamic");
7524 if (pi.icon != 0) {
7525 serializer.attribute(null, "icon",
7526 Integer.toString(pi.icon));
7527 }
7528 if (pi.nonLocalizedLabel != null) {
7529 serializer.attribute(null, "label",
7530 pi.nonLocalizedLabel.toString());
7531 }
7532 if (pi.protectionLevel !=
7533 PermissionInfo.PROTECTION_NORMAL) {
7534 serializer.attribute(null, "protection",
7535 Integer.toString(pi.protectionLevel));
7536 }
7537 }
7538 }
7539 serializer.endTag(null, "item");
7540 }
7541 }
7542
7543 String getReadMessagesLP() {
7544 return mReadMessages.toString();
7545 }
7546
Oscar Montemayora8529f62009-11-18 10:14:20 -08007547 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
7549 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007550 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007551 while(its.hasNext()) {
7552 String key = its.next();
7553 PackageSetting ps = mPackages.get(key);
7554 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08007555 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007556 }
7557 }
7558 return ret;
7559 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007561 boolean readLP() {
7562 FileInputStream str = null;
7563 if (mBackupSettingsFilename.exists()) {
7564 try {
7565 str = new FileInputStream(mBackupSettingsFilename);
7566 mReadMessages.append("Reading from backup settings file\n");
7567 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007568 if (mSettingsFilename.exists()) {
7569 // If both the backup and settings file exist, we
7570 // ignore the settings since it might have been
7571 // corrupted.
7572 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
7573 mSettingsFilename.delete();
7574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007575 } catch (java.io.IOException e) {
7576 // We'll try for the normal settings file.
7577 }
7578 }
7579
7580 mPastSignatures.clear();
7581
7582 try {
7583 if (str == null) {
7584 if (!mSettingsFilename.exists()) {
7585 mReadMessages.append("No settings file found\n");
7586 Log.i(TAG, "No current settings file!");
7587 return false;
7588 }
7589 str = new FileInputStream(mSettingsFilename);
7590 }
7591 XmlPullParser parser = Xml.newPullParser();
7592 parser.setInput(str, null);
7593
7594 int type;
7595 while ((type=parser.next()) != XmlPullParser.START_TAG
7596 && type != XmlPullParser.END_DOCUMENT) {
7597 ;
7598 }
7599
7600 if (type != XmlPullParser.START_TAG) {
7601 mReadMessages.append("No start tag found in settings file\n");
7602 Log.e(TAG, "No start tag found in package manager settings");
7603 return false;
7604 }
7605
7606 int outerDepth = parser.getDepth();
7607 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7608 && (type != XmlPullParser.END_TAG
7609 || parser.getDepth() > outerDepth)) {
7610 if (type == XmlPullParser.END_TAG
7611 || type == XmlPullParser.TEXT) {
7612 continue;
7613 }
7614
7615 String tagName = parser.getName();
7616 if (tagName.equals("package")) {
7617 readPackageLP(parser);
7618 } else if (tagName.equals("permissions")) {
7619 readPermissionsLP(mPermissions, parser);
7620 } else if (tagName.equals("permission-trees")) {
7621 readPermissionsLP(mPermissionTrees, parser);
7622 } else if (tagName.equals("shared-user")) {
7623 readSharedUserLP(parser);
7624 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08007625 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007626 } else if (tagName.equals("preferred-activities")) {
7627 readPreferredActivitiesLP(parser);
7628 } else if(tagName.equals("updated-package")) {
7629 readDisabledSysPackageLP(parser);
7630 } else {
7631 Log.w(TAG, "Unknown element under <packages>: "
7632 + parser.getName());
7633 XmlUtils.skipCurrentTag(parser);
7634 }
7635 }
7636
7637 str.close();
7638
7639 } catch(XmlPullParserException e) {
7640 mReadMessages.append("Error reading: " + e.toString());
7641 Log.e(TAG, "Error reading package manager settings", e);
7642
7643 } catch(java.io.IOException e) {
7644 mReadMessages.append("Error reading: " + e.toString());
7645 Log.e(TAG, "Error reading package manager settings", e);
7646
7647 }
7648
7649 int N = mPendingPackages.size();
7650 for (int i=0; i<N; i++) {
7651 final PendingPackage pp = mPendingPackages.get(i);
7652 Object idObj = getUserIdLP(pp.sharedId);
7653 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007654 PackageSetting p = getPackageLP(pp.name, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007655 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007656 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007657 if (p == null) {
7658 Log.w(TAG, "Unable to create application package for "
7659 + pp.name);
7660 continue;
7661 }
7662 p.copyFrom(pp);
7663 } else if (idObj != null) {
7664 String msg = "Bad package setting: package " + pp.name
7665 + " has shared uid " + pp.sharedId
7666 + " that is not a shared uid\n";
7667 mReadMessages.append(msg);
7668 Log.e(TAG, msg);
7669 } else {
7670 String msg = "Bad package setting: package " + pp.name
7671 + " has shared uid " + pp.sharedId
7672 + " that is not defined\n";
7673 mReadMessages.append(msg);
7674 Log.e(TAG, msg);
7675 }
7676 }
7677 mPendingPackages.clear();
7678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679 mReadMessages.append("Read completed successfully: "
7680 + mPackages.size() + " packages, "
7681 + mSharedUsers.size() + " shared uids\n");
7682
7683 return true;
7684 }
7685
7686 private int readInt(XmlPullParser parser, String ns, String name,
7687 int defValue) {
7688 String v = parser.getAttributeValue(ns, name);
7689 try {
7690 if (v == null) {
7691 return defValue;
7692 }
7693 return Integer.parseInt(v);
7694 } catch (NumberFormatException e) {
7695 reportSettingsProblem(Log.WARN,
7696 "Error in package manager settings: attribute " +
7697 name + " has bad integer value " + v + " at "
7698 + parser.getPositionDescription());
7699 }
7700 return defValue;
7701 }
7702
7703 private void readPermissionsLP(HashMap<String, BasePermission> out,
7704 XmlPullParser parser)
7705 throws IOException, XmlPullParserException {
7706 int outerDepth = parser.getDepth();
7707 int type;
7708 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7709 && (type != XmlPullParser.END_TAG
7710 || parser.getDepth() > outerDepth)) {
7711 if (type == XmlPullParser.END_TAG
7712 || type == XmlPullParser.TEXT) {
7713 continue;
7714 }
7715
7716 String tagName = parser.getName();
7717 if (tagName.equals("item")) {
7718 String name = parser.getAttributeValue(null, "name");
7719 String sourcePackage = parser.getAttributeValue(null, "package");
7720 String ptype = parser.getAttributeValue(null, "type");
7721 if (name != null && sourcePackage != null) {
7722 boolean dynamic = "dynamic".equals(ptype);
7723 BasePermission bp = new BasePermission(name, sourcePackage,
7724 dynamic
7725 ? BasePermission.TYPE_DYNAMIC
7726 : BasePermission.TYPE_NORMAL);
7727 if (dynamic) {
7728 PermissionInfo pi = new PermissionInfo();
7729 pi.packageName = sourcePackage.intern();
7730 pi.name = name.intern();
7731 pi.icon = readInt(parser, null, "icon", 0);
7732 pi.nonLocalizedLabel = parser.getAttributeValue(
7733 null, "label");
7734 pi.protectionLevel = readInt(parser, null, "protection",
7735 PermissionInfo.PROTECTION_NORMAL);
7736 bp.pendingInfo = pi;
7737 }
7738 out.put(bp.name, bp);
7739 } else {
7740 reportSettingsProblem(Log.WARN,
7741 "Error in package manager settings: permissions has"
7742 + " no name at " + parser.getPositionDescription());
7743 }
7744 } else {
7745 reportSettingsProblem(Log.WARN,
7746 "Unknown element reading permissions: "
7747 + parser.getName() + " at "
7748 + parser.getPositionDescription());
7749 }
7750 XmlUtils.skipCurrentTag(parser);
7751 }
7752 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007754 private void readDisabledSysPackageLP(XmlPullParser parser)
7755 throws XmlPullParserException, IOException {
7756 String name = parser.getAttributeValue(null, "name");
7757 String codePathStr = parser.getAttributeValue(null, "codePath");
7758 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
7759 if(resourcePathStr == null) {
7760 resourcePathStr = codePathStr;
7761 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007762 String version = parser.getAttributeValue(null, "version");
7763 int versionCode = 0;
7764 if (version != null) {
7765 try {
7766 versionCode = Integer.parseInt(version);
7767 } catch (NumberFormatException e) {
7768 }
7769 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 int pkgFlags = 0;
7772 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007773 PackageSetting ps = new PackageSetting(name,
7774 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007775 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 String timeStampStr = parser.getAttributeValue(null, "ts");
7777 if (timeStampStr != null) {
7778 try {
7779 long timeStamp = Long.parseLong(timeStampStr);
7780 ps.setTimeStamp(timeStamp, timeStampStr);
7781 } catch (NumberFormatException e) {
7782 }
7783 }
7784 String idStr = parser.getAttributeValue(null, "userId");
7785 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
7786 if(ps.userId <= 0) {
7787 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7788 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
7789 }
7790 int outerDepth = parser.getDepth();
7791 int type;
7792 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7793 && (type != XmlPullParser.END_TAG
7794 || parser.getDepth() > outerDepth)) {
7795 if (type == XmlPullParser.END_TAG
7796 || type == XmlPullParser.TEXT) {
7797 continue;
7798 }
7799
7800 String tagName = parser.getName();
7801 if (tagName.equals("perms")) {
7802 readGrantedPermissionsLP(parser,
7803 ps.grantedPermissions);
7804 } else {
7805 reportSettingsProblem(Log.WARN,
7806 "Unknown element under <updated-package>: "
7807 + parser.getName());
7808 XmlUtils.skipCurrentTag(parser);
7809 }
7810 }
7811 mDisabledSysPackages.put(name, ps);
7812 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007814 private void readPackageLP(XmlPullParser parser)
7815 throws XmlPullParserException, IOException {
7816 String name = null;
7817 String idStr = null;
7818 String sharedIdStr = null;
7819 String codePathStr = null;
7820 String resourcePathStr = null;
7821 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02007822 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007823 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 int pkgFlags = 0;
7825 String timeStampStr;
7826 long timeStamp = 0;
7827 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007828 String version = null;
7829 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007830 try {
7831 name = parser.getAttributeValue(null, "name");
7832 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007833 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007834 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7835 codePathStr = parser.getAttributeValue(null, "codePath");
7836 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007837 version = parser.getAttributeValue(null, "version");
7838 if (version != null) {
7839 try {
7840 versionCode = Integer.parseInt(version);
7841 } catch (NumberFormatException e) {
7842 }
7843 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007844 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007845
7846 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007848 try {
7849 pkgFlags = Integer.parseInt(systemStr);
7850 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 }
7852 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007853 // For backward compatibility
7854 systemStr = parser.getAttributeValue(null, "system");
7855 if (systemStr != null) {
7856 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
7857 } else {
7858 // Old settings that don't specify system... just treat
7859 // them as system, good enough.
7860 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 }
7863 timeStampStr = parser.getAttributeValue(null, "ts");
7864 if (timeStampStr != null) {
7865 try {
7866 timeStamp = Long.parseLong(timeStampStr);
7867 } catch (NumberFormatException e) {
7868 }
7869 }
7870 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7871 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7872 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7873 if (resourcePathStr == null) {
7874 resourcePathStr = codePathStr;
7875 }
7876 if (name == null) {
7877 reportSettingsProblem(Log.WARN,
7878 "Error in package manager settings: <package> has no name at "
7879 + parser.getPositionDescription());
7880 } else if (codePathStr == null) {
7881 reportSettingsProblem(Log.WARN,
7882 "Error in package manager settings: <package> has no codePath at "
7883 + parser.getPositionDescription());
7884 } else if (userId > 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007885 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007886 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7888 + ": userId=" + userId + " pkg=" + packageSetting);
7889 if (packageSetting == null) {
7890 reportSettingsProblem(Log.ERROR,
7891 "Failure adding uid " + userId
7892 + " while parsing settings at "
7893 + parser.getPositionDescription());
7894 } else {
7895 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7896 }
7897 } else if (sharedIdStr != null) {
7898 userId = sharedIdStr != null
7899 ? Integer.parseInt(sharedIdStr) : 0;
7900 if (userId > 0) {
7901 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007902 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7904 mPendingPackages.add((PendingPackage) packageSetting);
7905 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7906 + ": sharedUserId=" + userId + " pkg="
7907 + packageSetting);
7908 } else {
7909 reportSettingsProblem(Log.WARN,
7910 "Error in package manager settings: package "
7911 + name + " has bad sharedId " + sharedIdStr
7912 + " at " + parser.getPositionDescription());
7913 }
7914 } else {
7915 reportSettingsProblem(Log.WARN,
7916 "Error in package manager settings: package "
7917 + name + " has bad userId " + idStr + " at "
7918 + parser.getPositionDescription());
7919 }
7920 } catch (NumberFormatException e) {
7921 reportSettingsProblem(Log.WARN,
7922 "Error in package manager settings: package "
7923 + name + " has bad userId " + idStr + " at "
7924 + parser.getPositionDescription());
7925 }
7926 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007927 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02007928 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007929 final String enabledStr = parser.getAttributeValue(null, "enabled");
7930 if (enabledStr != null) {
7931 if (enabledStr.equalsIgnoreCase("true")) {
7932 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
7933 } else if (enabledStr.equalsIgnoreCase("false")) {
7934 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
7935 } else if (enabledStr.equalsIgnoreCase("default")) {
7936 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7937 } else {
7938 reportSettingsProblem(Log.WARN,
7939 "Error in package manager settings: package "
7940 + name + " has bad enabled value: " + idStr
7941 + " at " + parser.getPositionDescription());
7942 }
7943 } else {
7944 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7945 }
7946 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
7947 if (installStatusStr != null) {
7948 if (installStatusStr.equalsIgnoreCase("false")) {
7949 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
7950 } else {
7951 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
7952 }
7953 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955 int outerDepth = parser.getDepth();
7956 int type;
7957 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7958 && (type != XmlPullParser.END_TAG
7959 || parser.getDepth() > outerDepth)) {
7960 if (type == XmlPullParser.END_TAG
7961 || type == XmlPullParser.TEXT) {
7962 continue;
7963 }
7964
7965 String tagName = parser.getName();
7966 if (tagName.equals("disabled-components")) {
7967 readDisabledComponentsLP(packageSetting, parser);
7968 } else if (tagName.equals("enabled-components")) {
7969 readEnabledComponentsLP(packageSetting, parser);
7970 } else if (tagName.equals("sigs")) {
7971 packageSetting.signatures.readXml(parser, mPastSignatures);
7972 } else if (tagName.equals("perms")) {
7973 readGrantedPermissionsLP(parser,
7974 packageSetting.loadedPermissions);
7975 packageSetting.permissionsFixed = true;
7976 } else {
7977 reportSettingsProblem(Log.WARN,
7978 "Unknown element under <package>: "
7979 + parser.getName());
7980 XmlUtils.skipCurrentTag(parser);
7981 }
7982 }
7983 } else {
7984 XmlUtils.skipCurrentTag(parser);
7985 }
7986 }
7987
7988 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
7989 XmlPullParser parser)
7990 throws IOException, XmlPullParserException {
7991 int outerDepth = parser.getDepth();
7992 int type;
7993 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7994 && (type != XmlPullParser.END_TAG
7995 || parser.getDepth() > outerDepth)) {
7996 if (type == XmlPullParser.END_TAG
7997 || type == XmlPullParser.TEXT) {
7998 continue;
7999 }
8000
8001 String tagName = parser.getName();
8002 if (tagName.equals("item")) {
8003 String name = parser.getAttributeValue(null, "name");
8004 if (name != null) {
8005 packageSetting.disabledComponents.add(name.intern());
8006 } else {
8007 reportSettingsProblem(Log.WARN,
8008 "Error in package manager settings: <disabled-components> has"
8009 + " no name at " + parser.getPositionDescription());
8010 }
8011 } else {
8012 reportSettingsProblem(Log.WARN,
8013 "Unknown element under <disabled-components>: "
8014 + parser.getName());
8015 }
8016 XmlUtils.skipCurrentTag(parser);
8017 }
8018 }
8019
8020 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8021 XmlPullParser parser)
8022 throws IOException, XmlPullParserException {
8023 int outerDepth = parser.getDepth();
8024 int type;
8025 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8026 && (type != XmlPullParser.END_TAG
8027 || parser.getDepth() > outerDepth)) {
8028 if (type == XmlPullParser.END_TAG
8029 || type == XmlPullParser.TEXT) {
8030 continue;
8031 }
8032
8033 String tagName = parser.getName();
8034 if (tagName.equals("item")) {
8035 String name = parser.getAttributeValue(null, "name");
8036 if (name != null) {
8037 packageSetting.enabledComponents.add(name.intern());
8038 } else {
8039 reportSettingsProblem(Log.WARN,
8040 "Error in package manager settings: <enabled-components> has"
8041 + " no name at " + parser.getPositionDescription());
8042 }
8043 } else {
8044 reportSettingsProblem(Log.WARN,
8045 "Unknown element under <enabled-components>: "
8046 + parser.getName());
8047 }
8048 XmlUtils.skipCurrentTag(parser);
8049 }
8050 }
8051
8052 private void readSharedUserLP(XmlPullParser parser)
8053 throws XmlPullParserException, IOException {
8054 String name = null;
8055 String idStr = null;
8056 int pkgFlags = 0;
8057 SharedUserSetting su = null;
8058 try {
8059 name = parser.getAttributeValue(null, "name");
8060 idStr = parser.getAttributeValue(null, "userId");
8061 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8062 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8063 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8064 }
8065 if (name == null) {
8066 reportSettingsProblem(Log.WARN,
8067 "Error in package manager settings: <shared-user> has no name at "
8068 + parser.getPositionDescription());
8069 } else if (userId == 0) {
8070 reportSettingsProblem(Log.WARN,
8071 "Error in package manager settings: shared-user "
8072 + name + " has bad userId " + idStr + " at "
8073 + parser.getPositionDescription());
8074 } else {
8075 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8076 reportSettingsProblem(Log.ERROR,
8077 "Occurred while parsing settings at "
8078 + parser.getPositionDescription());
8079 }
8080 }
8081 } catch (NumberFormatException e) {
8082 reportSettingsProblem(Log.WARN,
8083 "Error in package manager settings: package "
8084 + name + " has bad userId " + idStr + " at "
8085 + parser.getPositionDescription());
8086 };
8087
8088 if (su != null) {
8089 int outerDepth = parser.getDepth();
8090 int type;
8091 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8092 && (type != XmlPullParser.END_TAG
8093 || parser.getDepth() > outerDepth)) {
8094 if (type == XmlPullParser.END_TAG
8095 || type == XmlPullParser.TEXT) {
8096 continue;
8097 }
8098
8099 String tagName = parser.getName();
8100 if (tagName.equals("sigs")) {
8101 su.signatures.readXml(parser, mPastSignatures);
8102 } else if (tagName.equals("perms")) {
8103 readGrantedPermissionsLP(parser, su.loadedPermissions);
8104 } else {
8105 reportSettingsProblem(Log.WARN,
8106 "Unknown element under <shared-user>: "
8107 + parser.getName());
8108 XmlUtils.skipCurrentTag(parser);
8109 }
8110 }
8111
8112 } else {
8113 XmlUtils.skipCurrentTag(parser);
8114 }
8115 }
8116
8117 private void readGrantedPermissionsLP(XmlPullParser parser,
8118 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8119 int outerDepth = parser.getDepth();
8120 int type;
8121 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8122 && (type != XmlPullParser.END_TAG
8123 || parser.getDepth() > outerDepth)) {
8124 if (type == XmlPullParser.END_TAG
8125 || type == XmlPullParser.TEXT) {
8126 continue;
8127 }
8128
8129 String tagName = parser.getName();
8130 if (tagName.equals("item")) {
8131 String name = parser.getAttributeValue(null, "name");
8132 if (name != null) {
8133 outPerms.add(name.intern());
8134 } else {
8135 reportSettingsProblem(Log.WARN,
8136 "Error in package manager settings: <perms> has"
8137 + " no name at " + parser.getPositionDescription());
8138 }
8139 } else {
8140 reportSettingsProblem(Log.WARN,
8141 "Unknown element under <perms>: "
8142 + parser.getName());
8143 }
8144 XmlUtils.skipCurrentTag(parser);
8145 }
8146 }
8147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 private void readPreferredActivitiesLP(XmlPullParser parser)
8149 throws XmlPullParserException, IOException {
8150 int outerDepth = parser.getDepth();
8151 int type;
8152 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8153 && (type != XmlPullParser.END_TAG
8154 || parser.getDepth() > outerDepth)) {
8155 if (type == XmlPullParser.END_TAG
8156 || type == XmlPullParser.TEXT) {
8157 continue;
8158 }
8159
8160 String tagName = parser.getName();
8161 if (tagName.equals("item")) {
8162 PreferredActivity pa = new PreferredActivity(parser);
8163 if (pa.mParseError == null) {
8164 mPreferredActivities.addFilter(pa);
8165 } else {
8166 reportSettingsProblem(Log.WARN,
8167 "Error in package manager settings: <preferred-activity> "
8168 + pa.mParseError + " at "
8169 + parser.getPositionDescription());
8170 }
8171 } else {
8172 reportSettingsProblem(Log.WARN,
8173 "Unknown element under <preferred-activities>: "
8174 + parser.getName());
8175 XmlUtils.skipCurrentTag(parser);
8176 }
8177 }
8178 }
8179
8180 // Returns -1 if we could not find an available UserId to assign
8181 private int newUserIdLP(Object obj) {
8182 // Let's be stupidly inefficient for now...
8183 final int N = mUserIds.size();
8184 for (int i=0; i<N; i++) {
8185 if (mUserIds.get(i) == null) {
8186 mUserIds.set(i, obj);
8187 return FIRST_APPLICATION_UID + i;
8188 }
8189 }
8190
8191 // None left?
8192 if (N >= MAX_APPLICATION_UIDS) {
8193 return -1;
8194 }
8195
8196 mUserIds.add(obj);
8197 return FIRST_APPLICATION_UID + N;
8198 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008200 public PackageSetting getDisabledSystemPkg(String name) {
8201 synchronized(mPackages) {
8202 PackageSetting ps = mDisabledSysPackages.get(name);
8203 return ps;
8204 }
8205 }
8206
8207 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8208 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8209 if (Config.LOGV) {
8210 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8211 + " componentName = " + componentInfo.name);
8212 Log.v(TAG, "enabledComponents: "
8213 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8214 Log.v(TAG, "disabledComponents: "
8215 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8216 }
8217 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8218 || ((componentInfo.enabled
8219 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8220 || (componentInfo.applicationInfo.enabled
8221 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8222 && !packageSettings.disabledComponents.contains(componentInfo.name))
8223 || packageSettings.enabledComponents.contains(componentInfo.name));
8224 }
8225 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008226
8227 // ------- apps on sdcard specific code -------
8228 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008229 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008230 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008231 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008232 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008233
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008234
8235 static MountService getMountService() {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008236 return (MountService) ServiceManager.getService("mount");
8237 }
8238
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008239 private String getEncryptKey() {
8240 try {
8241 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8242 if (sdEncKey == null) {
8243 sdEncKey = SystemKeyStore.getInstance().
8244 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8245 if (sdEncKey == null) {
8246 Log.e(TAG, "Failed to create encryption keys");
8247 return null;
8248 }
8249 }
8250 return sdEncKey;
8251 } catch (NoSuchAlgorithmException nsae) {
8252 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8253 return null;
8254 }
8255 }
8256
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008257 private String createSdDir(File tmpPackageFile, String pkgName) {
8258 // Create mount point via MountService
8259 MountService mountService = getMountService();
8260 long len = tmpPackageFile.length();
8261 int mbLen = (int) (len/(1024*1024));
8262 if ((len - (mbLen * 1024 * 1024)) > 0) {
8263 mbLen++;
8264 }
8265 if (DEBUG_SD_INSTALL) Log.i(TAG, "mbLen="+mbLen);
8266 String cachePath = null;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008267 String sdEncKey;
8268 try {
8269 sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8270 if (sdEncKey == null) {
8271 sdEncKey = SystemKeyStore.getInstance().
8272 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8273 if (sdEncKey == null) {
8274 Log.e(TAG, "Failed to create encryption keys for package: " + pkgName + ".");
8275 return null;
8276 }
8277 }
8278 } catch (NoSuchAlgorithmException nsae) {
8279 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8280 return null;
8281 }
San Mehatbe16cb12010-01-29 05:35:35 -08008282
8283 int rc = mountService.createSecureContainer(
8284 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
8285 if (rc != MountServiceResultCode.OperationSucceeded) {
8286 Log.e(TAG, String.format("Failed to create container (%d)", rc));
8287
8288 rc = mountService.destroySecureContainer(pkgName);
8289 if (rc != MountServiceResultCode.OperationSucceeded) {
8290 Log.e(TAG, String.format("Failed to cleanup container (%d)", rc));
8291 return null;
8292 }
8293 rc = mountService.createSecureContainer(
8294 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
8295 if (rc != MountServiceResultCode.OperationSucceeded) {
8296 Log.e(TAG, String.format("Failed to create container (2nd try) (%d)", rc));
8297 return null;
8298 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008299 }
San Mehatbe16cb12010-01-29 05:35:35 -08008300
8301 cachePath = mountService.getSecureContainerPath(pkgName);
8302 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install " + pkgName + ", cachePath =" + cachePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008303 return cachePath;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008304 }
8305
8306 private String mountSdDir(String pkgName, int ownerUid) {
Oscar Montemayord02546b2010-01-14 16:38:40 -08008307 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8308 if (sdEncKey == null) {
8309 Log.e(TAG, "Failed to retrieve encryption keys to mount package code: " + pkgName + ".");
8310 return null;
8311 }
San Mehatbe16cb12010-01-29 05:35:35 -08008312
8313 int rc = getMountService().mountSecureContainer(pkgName, sdEncKey, ownerUid);
8314
8315 if (rc != MountServiceResultCode.OperationSucceeded) {
8316 Log.i(TAG, "Failed to mount container for pkg : " + pkgName + " rc : " + rc);
8317 return null;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008318 }
San Mehatbe16cb12010-01-29 05:35:35 -08008319
8320 return getMountService().getSecureContainerPath(pkgName);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008321 }
8322
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008323 private boolean unMountSdDir(String pkgName) {
8324 // STOPSHIP unmount directory
San Mehatbe16cb12010-01-29 05:35:35 -08008325 int rc = getMountService().unmountSecureContainer(pkgName);
8326 if (rc != MountServiceResultCode.OperationSucceeded) {
8327 Log.e(TAG, "Failed to unmount : " + pkgName + " with rc " + rc);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008328 return false;
8329 }
San Mehatbe16cb12010-01-29 05:35:35 -08008330 return true;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008331 }
8332
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008333 private boolean renameSdDir(String oldId, String newId) {
8334 try {
8335 getMountService().renameSecureContainer(oldId, newId);
8336 return true;
8337 } catch (IllegalStateException e) {
8338 Log.i(TAG, "Failed ot rename " + oldId + " to " + newId +
8339 " with exception : " + e);
8340 }
8341 return false;
8342 }
8343
8344 private String getSdDir(String pkgName) {
8345 return getMountService().getSecureContainerPath(pkgName);
8346 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008347
San Mehatbe16cb12010-01-29 05:35:35 -08008348 private boolean finalizeSdDir(String pkgName) {
8349 int rc = getMountService().finalizeSecureContainer(pkgName);
8350 if (rc != MountServiceResultCode.OperationSucceeded) {
8351 Log.i(TAG, "Failed to finalize container for pkg : " + pkgName);
8352 return false;
8353 }
8354 return true;
8355 }
8356
8357 private boolean destroySdDir(String pkgName) {
8358 int rc = getMountService().destroySecureContainer(pkgName);
8359 if (rc != MountServiceResultCode.OperationSucceeded) {
8360 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
8361 return false;
8362 }
8363 return true;
8364 }
8365
8366 static String[] getSecureContainerList() {
8367 String[] list = getMountService().getSecureContainerList();
8368 return list.length == 0 ? null : list;
8369 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008370
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008371 static boolean isContainerMounted(String cid) {
8372 // STOPSHIP
8373 // New api from MountService
8374 try {
8375 return (getMountService().getSecureContainerPath(cid) != null);
8376 } catch (IllegalStateException e) {
8377 }
8378 return false;
8379 }
8380
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008381 static String getTempContainerId() {
8382 String prefix = "smdl1tmp";
8383 int tmpIdx = 1;
8384 String list[] = getSecureContainerList();
8385 if (list != null) {
8386 int idx = 0;
8387 int idList[] = new int[MAX_CONTAINERS];
8388 boolean neverFound = true;
8389 for (String name : list) {
8390 // Ignore null entries
8391 if (name == null) {
8392 continue;
8393 }
8394 int sidx = name.indexOf(prefix);
8395 if (sidx == -1) {
8396 // Not a temp file. just ignore
8397 continue;
8398 }
8399 String subStr = name.substring(sidx + prefix.length());
8400 idList[idx] = -1;
8401 if (subStr != null) {
8402 try {
8403 int cid = Integer.parseInt(subStr);
8404 idList[idx++] = cid;
8405 neverFound = false;
8406 } catch (NumberFormatException e) {
8407 }
8408 }
8409 }
8410 if (!neverFound) {
8411 // Sort idList
8412 Arrays.sort(idList);
8413 for (int j = 1; j <= idList.length; j++) {
8414 if (idList[j-1] != j) {
8415 tmpIdx = j;
8416 break;
8417 }
8418 }
8419 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008420 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008421 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008422 }
8423
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008424 public void updateExternalMediaStatus(final boolean mediaStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008425 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8426 mediaStatus+", mMediaMounted=" + mMediaMounted);
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008427 if (mediaStatus == mMediaMounted) {
8428 return;
8429 }
8430 mMediaMounted = mediaStatus;
8431 // Queue up an async operation since the package installation may take a little while.
8432 mHandler.post(new Runnable() {
8433 public void run() {
8434 mHandler.removeCallbacks(this);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008435 updateExternalMediaStatusInner(mediaStatus);
8436 }
8437 });
8438 }
8439
8440 void updateExternalMediaStatusInner(boolean mediaStatus) {
8441 final String list[] = getSecureContainerList();
8442 if (list == null || list.length == 0) {
8443 return;
8444 }
8445 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
8446 int uidList[] = new int[list.length];
8447 int num = 0;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008448 synchronized (mPackages) {
8449 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8450 for (String cid : list) {
8451 SdInstallArgs args = new SdInstallArgs(cid);
8452 String removeEntry = null;
8453 for (String app : appList) {
8454 if (args.matchContainer(app)) {
8455 removeEntry = app;
8456 break;
8457 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008458 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008459 if (removeEntry == null) {
8460 // No matching app on device. Skip entry or may be cleanup?
8461 // Ignore default package
8462 continue;
8463 }
8464 appList.remove(removeEntry);
8465 PackageSetting ps = mSettings.mPackages.get(removeEntry);
8466 processCids.put(args, ps.codePathString);
8467 int uid = ps.userId;
8468 if (uid != -1) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008469 uidList[num++] = uid;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008470 }
8471 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008472 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008473 int uidArr[] = null;
8474 if (num > 0) {
8475 // Sort uid list
8476 Arrays.sort(uidList, 0, num);
8477 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008478 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008479 uidArr[0] = uidList[0];
8480 int di = 0;
8481 for (int i = 1; i < num; i++) {
8482 if (uidList[i-1] != uidList[i]) {
8483 uidArr[di++] = uidList[i];
8484 }
8485 }
8486 if (true) {
8487 for (int j = 0; j < num; j++) {
8488 Log.i(TAG, "uidArr[" + j + "]=" + uidArr[j]);
8489 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008490 }
8491 }
8492 if (mediaStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008493 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008494 loadMediaPackages(processCids, uidArr);
8495 } else {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008496 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008497 unloadMediaPackages(processCids, uidArr);
8498 }
8499 }
8500
8501 private void sendResourcesChangedBroadcast(boolean mediaStatus,
8502 ArrayList<String> pkgList, int uidArr[]) {
8503 int size = pkgList.size();
8504 if (size > 0) {
8505 // Send broadcasts here
8506 Bundle extras = new Bundle();
8507 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
8508 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008509 if (uidArr != null) {
8510 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
8511 }
8512 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
8513 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008514 sendPackageBroadcast(action, null, extras);
8515 }
8516 }
8517
8518 void loadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
8519 ArrayList<String> pkgList = new ArrayList<String>();
8520 Set<SdInstallArgs> keys = processCids.keySet();
8521 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008522 String codePath = processCids.get(args);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008523 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install pkg : "
8524 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008525 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008526 Log.e(TAG, "Failed to install package: " + codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008527 continue;
8528 }
8529 // Parse package
8530 int parseFlags = PackageParser.PARSE_CHATTY |
8531 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8532 PackageParser pp = new PackageParser(codePath);
8533 pp.setSeparateProcesses(mSeparateProcesses);
8534 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
8535 codePath, mMetrics, parseFlags);
8536 if (pkg == null) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008537 Log.e(TAG, "Trying to install pkg : "
8538 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008539 continue;
8540 }
8541 setApplicationInfoPaths(pkg, codePath, codePath);
8542 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8543 synchronized (mInstallLock) {
8544 // Scan the package
8545 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
8546 synchronized (mPackages) {
8547 // Grant permissions
8548 grantPermissionsLP(pkg, false);
8549 // Persist settings
8550 mSettings.writeLP();
8551 retCode = PackageManager.INSTALL_SUCCEEDED;
8552 pkgList.add(pkg.packageName);
8553 }
8554 } else {
8555 Log.i(TAG, "Failed to install package: " + pkg.packageName + " from sdcard");
8556 }
8557 }
8558 args.doPostInstall(retCode);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008559 }
8560 // Send broadcasts first
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008561 if (pkgList.size() > 0) {
8562 sendResourcesChangedBroadcast(true, pkgList, uidArr);
8563 Runtime.getRuntime().gc();
8564 // If something failed do we clean up here or next install?
8565 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008566 }
8567
8568 void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008569 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008570 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008571 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008572 Set<SdInstallArgs> keys = processCids.keySet();
8573 for (SdInstallArgs args : keys) {
8574 String cid = args.cid;
8575 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008576 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008577 // Delete package internally
8578 PackageRemovedInfo outInfo = new PackageRemovedInfo();
8579 synchronized (mInstallLock) {
8580 boolean res = deletePackageLI(pkgName, false,
8581 PackageManager.DONT_DELETE_DATA, outInfo);
8582 if (res) {
8583 pkgList.add(pkgName);
8584 } else {
8585 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008586 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008587 }
8588 }
8589 }
8590 // Send broadcasts
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008591 if (pkgList.size() > 0) {
8592 sendResourcesChangedBroadcast(false, pkgList, uidArr);
8593 Runtime.getRuntime().gc();
8594 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008595 // Do clean up. Just unmount
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008596 for (SdInstallArgs args : failedList) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008597 synchronized (mInstallLock) {
8598 args.doPostDeleteLI(false);
8599 }
8600 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008602}