PackageInstallerService.java revision 941a8ba1a6043cf84a7bf622e44a0b4f7abd0178
1/*
2 * Copyright (C) 2014 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.pm;
18
19import static android.content.pm.PackageManager.INSTALL_ALL_USERS;
20import static android.content.pm.PackageManager.INSTALL_FROM_ADB;
21import static android.content.pm.PackageManager.INSTALL_REPLACE_EXISTING;
22import static com.android.internal.util.XmlUtils.readBitmapAttribute;
23import static com.android.internal.util.XmlUtils.readBooleanAttribute;
24import static com.android.internal.util.XmlUtils.readIntAttribute;
25import static com.android.internal.util.XmlUtils.readLongAttribute;
26import static com.android.internal.util.XmlUtils.readStringAttribute;
27import static com.android.internal.util.XmlUtils.readUriAttribute;
28import static com.android.internal.util.XmlUtils.writeBitmapAttribute;
29import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
30import static com.android.internal.util.XmlUtils.writeIntAttribute;
31import static com.android.internal.util.XmlUtils.writeLongAttribute;
32import static com.android.internal.util.XmlUtils.writeStringAttribute;
33import static com.android.internal.util.XmlUtils.writeUriAttribute;
34import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
35import static org.xmlpull.v1.XmlPullParser.START_TAG;
36
37import android.app.ActivityManager;
38import android.app.AppOpsManager;
39import android.app.PackageDeleteObserver;
40import android.app.PackageInstallObserver;
41import android.content.Context;
42import android.content.Intent;
43import android.content.IntentSender;
44import android.content.IntentSender.SendIntentException;
45import android.content.pm.ApplicationInfo;
46import android.content.pm.IPackageInstaller;
47import android.content.pm.IPackageInstallerCallback;
48import android.content.pm.IPackageInstallerSession;
49import android.content.pm.PackageInstaller;
50import android.content.pm.PackageParser;
51import android.content.pm.PackageInstaller.SessionInfo;
52import android.content.pm.PackageInstaller.SessionParams;
53import android.content.pm.PackageParser.PackageLite;
54import android.content.pm.PackageParser.PackageParserException;
55import android.content.pm.PackageManager;
56import android.graphics.Bitmap;
57import android.net.Uri;
58import android.os.Binder;
59import android.os.Bundle;
60import android.os.Environment;
61import android.os.Environment.UserEnvironment;
62import android.os.FileUtils;
63import android.os.Handler;
64import android.os.HandlerThread;
65import android.os.Looper;
66import android.os.Message;
67import android.os.Process;
68import android.os.RemoteCallbackList;
69import android.os.RemoteException;
70import android.os.SELinux;
71import android.os.UserHandle;
72import android.os.UserManager;
73import android.os.storage.StorageManager;
74import android.system.ErrnoException;
75import android.system.Os;
76import android.text.TextUtils;
77import android.text.format.DateUtils;
78import android.util.ArraySet;
79import android.util.AtomicFile;
80import android.util.ExceptionUtils;
81import android.util.Log;
82import android.util.Slog;
83import android.util.SparseArray;
84import android.util.SparseBooleanArray;
85import android.util.Xml;
86
87import com.android.internal.annotations.GuardedBy;
88import com.android.internal.content.PackageHelper;
89import com.android.internal.util.FastXmlSerializer;
90import com.android.internal.util.IndentingPrintWriter;
91import com.android.server.IoThread;
92import com.google.android.collect.Sets;
93
94import libcore.io.IoUtils;
95
96import org.xmlpull.v1.XmlPullParser;
97import org.xmlpull.v1.XmlPullParserException;
98import org.xmlpull.v1.XmlSerializer;
99
100import java.io.File;
101import java.io.FileInputStream;
102import java.io.FileNotFoundException;
103import java.io.FileOutputStream;
104import java.io.FilenameFilter;
105import java.io.IOException;
106import java.security.SecureRandom;
107import java.util.ArrayList;
108import java.util.List;
109import java.util.Objects;
110import java.util.Random;
111
112public class PackageInstallerService extends IPackageInstaller.Stub {
113    private static final String TAG = "PackageInstaller";
114    private static final boolean LOGD = true;
115
116    // TODO: remove outstanding sessions when installer package goes away
117    // TODO: notify listeners in other users when package has been installed there
118    // TODO: purge expired sessions periodically in addition to at reboot
119
120    /** XML constants used in {@link #mSessionsFile} */
121    private static final String TAG_SESSIONS = "sessions";
122    private static final String TAG_SESSION = "session";
123    private static final String ATTR_SESSION_ID = "sessionId";
124    private static final String ATTR_USER_ID = "userId";
125    private static final String ATTR_INSTALLER_PACKAGE_NAME = "installerPackageName";
126    private static final String ATTR_CREATED_MILLIS = "createdMillis";
127    private static final String ATTR_SESSION_STAGE_DIR = "sessionStageDir";
128    private static final String ATTR_SESSION_STAGE_CID = "sessionStageCid";
129    private static final String ATTR_SEALED = "sealed";
130    private static final String ATTR_MODE = "mode";
131    private static final String ATTR_INSTALL_FLAGS = "installFlags";
132    private static final String ATTR_INSTALL_LOCATION = "installLocation";
133    private static final String ATTR_SIZE_BYTES = "sizeBytes";
134    private static final String ATTR_APP_PACKAGE_NAME = "appPackageName";
135    private static final String ATTR_APP_ICON = "appIcon";
136    private static final String ATTR_APP_LABEL = "appLabel";
137    private static final String ATTR_ORIGINATING_URI = "originatingUri";
138    private static final String ATTR_REFERRER_URI = "referrerUri";
139    private static final String ATTR_ABI_OVERRIDE = "abiOverride";
140
141    /** Automatically destroy sessions older than this */
142    private static final long MAX_AGE_MILLIS = 3 * DateUtils.DAY_IN_MILLIS;
143    /** Upper bound on number of active sessions for a UID */
144    private static final long MAX_ACTIVE_SESSIONS = 1024;
145    /** Upper bound on number of historical sessions for a UID */
146    private static final long MAX_HISTORICAL_SESSIONS = 1048576;
147
148    private final Context mContext;
149    private final PackageManagerService mPm;
150    private final AppOpsManager mAppOps;
151    private final StorageManager mStorage;
152
153    private final File mStagingDir;
154    private final HandlerThread mInstallThread;
155
156    private final Callbacks mCallbacks;
157
158    /**
159     * File storing persisted {@link #mSessions}.
160     */
161    private final AtomicFile mSessionsFile;
162
163    private final InternalCallback mInternalCallback = new InternalCallback();
164
165    /**
166     * Used for generating session IDs. Since this is created at boot time,
167     * normal random might be predictable.
168     */
169    private final Random mRandom = new SecureRandom();
170
171    @GuardedBy("mSessions")
172    private final SparseArray<PackageInstallerSession> mSessions = new SparseArray<>();
173
174    /** Historical sessions kept around for debugging purposes */
175    @GuardedBy("mSessions")
176    private final SparseArray<PackageInstallerSession> mHistoricalSessions = new SparseArray<>();
177
178    /** Sessions allocated to legacy users */
179    @GuardedBy("mSessions")
180    private final SparseBooleanArray mLegacySessions = new SparseBooleanArray();
181
182    private static final FilenameFilter sStageFilter = new FilenameFilter() {
183        @Override
184        public boolean accept(File dir, String name) {
185            return isStageName(name);
186        }
187    };
188
189    public PackageInstallerService(Context context, PackageManagerService pm, File stagingDir) {
190        mContext = context;
191        mPm = pm;
192        mAppOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
193        mStorage = StorageManager.from(mContext);
194
195        mStagingDir = stagingDir;
196
197        mInstallThread = new HandlerThread(TAG);
198        mInstallThread.start();
199
200        mCallbacks = new Callbacks(mInstallThread.getLooper());
201
202        mSessionsFile = new AtomicFile(
203                new File(Environment.getSystemSecureDirectory(), "install_sessions.xml"));
204
205        synchronized (mSessions) {
206            readSessionsLocked();
207
208            final ArraySet<File> unclaimed = Sets.newArraySet(mStagingDir.listFiles(sStageFilter));
209
210            // Ignore stages claimed by active sessions
211            for (int i = 0; i < mSessions.size(); i++) {
212                final PackageInstallerSession session = mSessions.valueAt(i);
213                unclaimed.remove(session.stageDir);
214            }
215
216            // Clean up orphaned staging directories
217            for (File stage : unclaimed) {
218                Slog.w(TAG, "Deleting orphan stage " + stage);
219                if (stage.isDirectory()) {
220                    FileUtils.deleteContents(stage);
221                }
222                stage.delete();
223            }
224        }
225    }
226
227    public void onSecureContainersAvailable() {
228        synchronized (mSessions) {
229            final ArraySet<String> unclaimed = new ArraySet<>();
230            for (String cid : PackageHelper.getSecureContainerList()) {
231                if (isStageName(cid)) {
232                    unclaimed.add(cid);
233                }
234            }
235
236            // Ignore stages claimed by active sessions
237            for (int i = 0; i < mSessions.size(); i++) {
238                final PackageInstallerSession session = mSessions.valueAt(i);
239                final String cid = session.stageCid;
240
241                if (unclaimed.remove(cid)) {
242                    // Claimed by active session, mount it
243                    PackageHelper.mountSdDir(cid, PackageManagerService.getEncryptKey(),
244                            Process.SYSTEM_UID);
245                }
246            }
247
248            // Clean up orphaned staging containers
249            for (String cid : unclaimed) {
250                Slog.w(TAG, "Deleting orphan container " + cid);
251                PackageHelper.destroySdDir(cid);
252            }
253        }
254    }
255
256    public static boolean isStageName(String name) {
257        final boolean isFile = name.startsWith("vmdl") && name.endsWith(".tmp");
258        final boolean isContainer = name.startsWith("smdl") && name.endsWith(".tmp");
259        final boolean isLegacyContainer = name.startsWith("smdl2tmp");
260        return isFile || isContainer || isLegacyContainer;
261    }
262
263    @Deprecated
264    public File allocateInternalStageDirLegacy() throws IOException {
265        synchronized (mSessions) {
266            try {
267                final int sessionId = allocateSessionIdLocked();
268                mLegacySessions.put(sessionId, true);
269                return prepareInternalStageDir(sessionId);
270            } catch (IllegalStateException e) {
271                throw new IOException(e);
272            }
273        }
274    }
275
276    @Deprecated
277    public String allocateExternalStageCidLegacy() {
278        synchronized (mSessions) {
279            final int sessionId = allocateSessionIdLocked();
280            mLegacySessions.put(sessionId, true);
281            return "smdl" + sessionId + ".tmp";
282        }
283    }
284
285    private void readSessionsLocked() {
286        if (LOGD) Slog.v(TAG, "readSessionsLocked()");
287
288        mSessions.clear();
289
290        FileInputStream fis = null;
291        try {
292            fis = mSessionsFile.openRead();
293            final XmlPullParser in = Xml.newPullParser();
294            in.setInput(fis, null);
295
296            int type;
297            while ((type = in.next()) != END_DOCUMENT) {
298                if (type == START_TAG) {
299                    final String tag = in.getName();
300                    if (TAG_SESSION.equals(tag)) {
301                        final PackageInstallerSession session = readSessionLocked(in);
302                        final long age = System.currentTimeMillis() - session.createdMillis;
303
304                        final boolean valid;
305                        if (age >= MAX_AGE_MILLIS) {
306                            Slog.w(TAG, "Abandoning old session first created at "
307                                    + session.createdMillis);
308                            valid = false;
309                        } else if (session.stageDir != null
310                                && !session.stageDir.exists()) {
311                            Slog.w(TAG, "Abandoning internal session with missing stage "
312                                    + session.stageDir);
313                            valid = false;
314                        } else {
315                            valid = true;
316                        }
317
318                        if (valid) {
319                            mSessions.put(session.sessionId, session);
320                        } else {
321                            // Since this is early during boot we don't send
322                            // any observer events about the session, but we
323                            // keep details around for dumpsys.
324                            mHistoricalSessions.put(session.sessionId, session);
325                        }
326                    }
327                }
328            }
329        } catch (FileNotFoundException e) {
330            // Missing sessions are okay, probably first boot
331        } catch (IOException e) {
332            Log.wtf(TAG, "Failed reading install sessions", e);
333        } catch (XmlPullParserException e) {
334            Log.wtf(TAG, "Failed reading install sessions", e);
335        } finally {
336            IoUtils.closeQuietly(fis);
337        }
338    }
339
340    private PackageInstallerSession readSessionLocked(XmlPullParser in) throws IOException {
341        final int sessionId = readIntAttribute(in, ATTR_SESSION_ID);
342        final int userId = readIntAttribute(in, ATTR_USER_ID);
343        final String installerPackageName = readStringAttribute(in, ATTR_INSTALLER_PACKAGE_NAME);
344        final long createdMillis = readLongAttribute(in, ATTR_CREATED_MILLIS);
345        final String stageDirRaw = readStringAttribute(in, ATTR_SESSION_STAGE_DIR);
346        final File stageDir = (stageDirRaw != null) ? new File(stageDirRaw) : null;
347        final String stageCid = readStringAttribute(in, ATTR_SESSION_STAGE_CID);
348        final boolean sealed = readBooleanAttribute(in, ATTR_SEALED);
349
350        final SessionParams params = new SessionParams(
351                SessionParams.MODE_INVALID);
352        params.mode = readIntAttribute(in, ATTR_MODE);
353        params.installFlags = readIntAttribute(in, ATTR_INSTALL_FLAGS);
354        params.installLocation = readIntAttribute(in, ATTR_INSTALL_LOCATION);
355        params.sizeBytes = readLongAttribute(in, ATTR_SIZE_BYTES);
356        params.appPackageName = readStringAttribute(in, ATTR_APP_PACKAGE_NAME);
357        params.appIcon = readBitmapAttribute(in, ATTR_APP_ICON);
358        params.appLabel = readStringAttribute(in, ATTR_APP_LABEL);
359        params.originatingUri = readUriAttribute(in, ATTR_ORIGINATING_URI);
360        params.referrerUri = readUriAttribute(in, ATTR_REFERRER_URI);
361        params.abiOverride = readStringAttribute(in, ATTR_ABI_OVERRIDE);
362
363        return new PackageInstallerSession(mInternalCallback, mContext, mPm,
364                mInstallThread.getLooper(), sessionId, userId, installerPackageName, params,
365                createdMillis, stageDir, stageCid, sealed);
366    }
367
368    private void writeSessionsLocked() {
369        if (LOGD) Slog.v(TAG, "writeSessionsLocked()");
370
371        FileOutputStream fos = null;
372        try {
373            fos = mSessionsFile.startWrite();
374
375            XmlSerializer out = new FastXmlSerializer();
376            out.setOutput(fos, "utf-8");
377            out.startDocument(null, true);
378            out.startTag(null, TAG_SESSIONS);
379            final int size = mSessions.size();
380            for (int i = 0; i < size; i++) {
381                final PackageInstallerSession session = mSessions.valueAt(i);
382                writeSessionLocked(out, session);
383            }
384            out.endTag(null, TAG_SESSIONS);
385            out.endDocument();
386
387            mSessionsFile.finishWrite(fos);
388        } catch (IOException e) {
389            if (fos != null) {
390                mSessionsFile.failWrite(fos);
391            }
392        }
393    }
394
395    private void writeSessionLocked(XmlSerializer out, PackageInstallerSession session)
396            throws IOException {
397        final SessionParams params = session.params;
398
399        out.startTag(null, TAG_SESSION);
400
401        writeIntAttribute(out, ATTR_SESSION_ID, session.sessionId);
402        writeIntAttribute(out, ATTR_USER_ID, session.userId);
403        writeStringAttribute(out, ATTR_INSTALLER_PACKAGE_NAME,
404                session.installerPackageName);
405        writeLongAttribute(out, ATTR_CREATED_MILLIS, session.createdMillis);
406        if (session.stageDir != null) {
407            writeStringAttribute(out, ATTR_SESSION_STAGE_DIR,
408                    session.stageDir.getAbsolutePath());
409        }
410        if (session.stageCid != null) {
411            writeStringAttribute(out, ATTR_SESSION_STAGE_CID, session.stageCid);
412        }
413        writeBooleanAttribute(out, ATTR_SEALED, session.isSealed());
414
415        writeIntAttribute(out, ATTR_MODE, params.mode);
416        writeIntAttribute(out, ATTR_INSTALL_FLAGS, params.installFlags);
417        writeIntAttribute(out, ATTR_INSTALL_LOCATION, params.installLocation);
418        writeLongAttribute(out, ATTR_SIZE_BYTES, params.sizeBytes);
419        writeStringAttribute(out, ATTR_APP_PACKAGE_NAME, params.appPackageName);
420        writeBitmapAttribute(out, ATTR_APP_ICON, params.appIcon);
421        writeStringAttribute(out, ATTR_APP_LABEL, params.appLabel);
422        writeUriAttribute(out, ATTR_ORIGINATING_URI, params.originatingUri);
423        writeUriAttribute(out, ATTR_REFERRER_URI, params.referrerUri);
424        writeStringAttribute(out, ATTR_ABI_OVERRIDE, params.abiOverride);
425
426        out.endTag(null, TAG_SESSION);
427    }
428
429    private void writeSessionsAsync() {
430        IoThread.getHandler().post(new Runnable() {
431            @Override
432            public void run() {
433                synchronized (mSessions) {
434                    writeSessionsLocked();
435                }
436            }
437        });
438    }
439
440    @Override
441    public int createSession(SessionParams params, String installerPackageName, int userId) {
442        try {
443            return createSessionInternal(params, installerPackageName, userId);
444        } catch (IOException e) {
445            throw ExceptionUtils.wrap(e);
446        }
447    }
448
449    private int createSessionInternal(SessionParams params, String installerPackageName, int userId)
450            throws IOException {
451        final int callingUid = Binder.getCallingUid();
452        mPm.enforceCrossUserPermission(callingUid, userId, true, "createSession");
453
454        if (mPm.isUserRestricted(UserHandle.getUserId(callingUid),
455                UserManager.DISALLOW_INSTALL_APPS)) {
456            throw new SecurityException("User restriction prevents installing");
457        }
458
459        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
460            installerPackageName = "com.android.shell";
461
462            params.installFlags |= INSTALL_FROM_ADB;
463
464        } else {
465            mAppOps.checkPackage(callingUid, installerPackageName);
466
467            params.installFlags &= ~INSTALL_FROM_ADB;
468            params.installFlags &= ~INSTALL_ALL_USERS;
469            params.installFlags |= INSTALL_REPLACE_EXISTING;
470        }
471
472        // Defensively resize giant app icons
473        if (params.appIcon != null) {
474            final ActivityManager am = (ActivityManager) mContext.getSystemService(
475                    Context.ACTIVITY_SERVICE);
476            final int iconSize = am.getLauncherLargeIconSize();
477            if ((params.appIcon.getWidth() > iconSize * 2)
478                    || (params.appIcon.getHeight() > iconSize * 2)) {
479                params.appIcon = Bitmap.createScaledBitmap(params.appIcon, iconSize, iconSize,
480                        true);
481            }
482        }
483
484        // TODO: treat INHERIT_EXISTING as install for user
485
486        // Figure out where we're going to be staging session data
487        final boolean stageInternal;
488
489        if (params.mode == SessionParams.MODE_FULL_INSTALL) {
490            // Brand new install, use best resolved location. This also verifies
491            // that target has enough free space for the install.
492            final long ident = Binder.clearCallingIdentity();
493            try {
494                final int resolved = PackageHelper.resolveInstallLocation(mContext,
495                        params.appPackageName, params.installLocation, params.sizeBytes,
496                        params.installFlags);
497
498                if (resolved == PackageHelper.RECOMMEND_INSTALL_INTERNAL) {
499                    stageInternal = true;
500                } else if (resolved == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
501                    stageInternal = false;
502                } else {
503                    throw new IOException("No storage with enough free space; res=" + resolved);
504                }
505            } finally {
506                Binder.restoreCallingIdentity(ident);
507            }
508        } else if (params.mode == SessionParams.MODE_INHERIT_EXISTING) {
509            // Inheriting existing install, so stay on the same storage medium.
510            final ApplicationInfo existingApp = mPm.getApplicationInfo(params.appPackageName, 0,
511                    userId);
512            if (existingApp == null) {
513                throw new IllegalStateException(
514                        "Missing existing app " + params.appPackageName);
515            }
516
517            final long existingSize;
518            try {
519                final PackageLite existingPkg = PackageParser.parsePackageLite(
520                        new File(existingApp.getCodePath()), 0);
521                existingSize = PackageHelper.calculateInstalledSize(existingPkg, false,
522                        params.abiOverride);
523            } catch (PackageParserException e) {
524                throw new IllegalStateException(
525                        "Failed to calculate size of " + params.appPackageName);
526            }
527
528            if ((existingApp.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) == 0) {
529                // Internal we can link existing install into place, so we only
530                // need enough space for the new data.
531                checkInternalStorage(params.sizeBytes);
532                stageInternal = true;
533            } else {
534                // External we're going to copy existing install into our
535                // container, so we need footprint of both.
536                checkExternalStorage(params.sizeBytes + existingSize);
537                stageInternal = false;
538            }
539        } else {
540            throw new IllegalArgumentException("Invalid install mode: " + params.mode);
541        }
542
543        final int sessionId;
544        final PackageInstallerSession session;
545        synchronized (mSessions) {
546            // Sanity check that installer isn't going crazy
547            final int activeCount = getSessionCount(mSessions, callingUid);
548            if (activeCount >= MAX_ACTIVE_SESSIONS) {
549                throw new IllegalStateException(
550                        "Too many active sessions for UID " + callingUid);
551            }
552            final int historicalCount = getSessionCount(mHistoricalSessions, callingUid);
553            if (historicalCount >= MAX_HISTORICAL_SESSIONS) {
554                throw new IllegalStateException(
555                        "Too many historical sessions for UID " + callingUid);
556            }
557
558            final long createdMillis = System.currentTimeMillis();
559            sessionId = allocateSessionIdLocked();
560
561            // We're staging to exactly one location
562            File stageDir = null;
563            String stageCid = null;
564            if (stageInternal) {
565                stageDir = prepareInternalStageDir(sessionId);
566            } else {
567                stageCid = prepareExternalStageCid(sessionId, params.sizeBytes);
568            }
569
570            session = new PackageInstallerSession(mInternalCallback, mContext, mPm,
571                    mInstallThread.getLooper(), sessionId, userId, installerPackageName, params,
572                    createdMillis, stageDir, stageCid, false);
573            mSessions.put(sessionId, session);
574        }
575
576        mCallbacks.notifySessionCreated(session.sessionId, session.userId);
577        writeSessionsAsync();
578        return sessionId;
579    }
580
581    private void checkInternalStorage(long sizeBytes) throws IOException {
582        if (sizeBytes <= 0) return;
583
584        final File target = Environment.getDataDirectory();
585        final long targetBytes = sizeBytes + mStorage.getStorageLowBytes(target);
586
587        mPm.freeStorage(targetBytes);
588        if (target.getUsableSpace() < targetBytes) {
589            throw new IOException("Not enough internal space to write " + sizeBytes + " bytes");
590        }
591    }
592
593    private void checkExternalStorage(long sizeBytes) throws IOException {
594        if (sizeBytes <= 0) return;
595
596        final File target = new UserEnvironment(UserHandle.USER_OWNER)
597                .getExternalStorageDirectory();
598        final long targetBytes = sizeBytes + mStorage.getStorageLowBytes(target);
599
600        if (target.getUsableSpace() < targetBytes) {
601            throw new IOException("Not enough external space to write " + sizeBytes + " bytes");
602        }
603    }
604
605    @Override
606    public IPackageInstallerSession openSession(int sessionId) {
607        synchronized (mSessions) {
608            final PackageInstallerSession session = mSessions.get(sessionId);
609            if (session == null) {
610                throw new IllegalStateException("Missing session " + sessionId);
611            }
612            if (!isCallingUidOwner(session)) {
613                throw new SecurityException("Caller has no access to session " + sessionId);
614            }
615            session.open();
616            return session;
617        }
618    }
619
620    private int allocateSessionIdLocked() {
621        int n = 0;
622        int sessionId;
623        do {
624            sessionId = mRandom.nextInt(Integer.MAX_VALUE - 1) + 1;
625            if (mSessions.get(sessionId) == null && mHistoricalSessions.get(sessionId) == null
626                    && !mLegacySessions.get(sessionId, false)) {
627                return sessionId;
628            }
629        } while (n++ < 32);
630
631        throw new IllegalStateException("Failed to allocate session ID");
632    }
633
634    private File prepareInternalStageDir(int sessionId) throws IOException {
635        final File file = new File(mStagingDir, "vmdl" + sessionId + ".tmp");
636
637        if (file.exists()) {
638            throw new IOException("Session dir already exists: " + file);
639        }
640
641        try {
642            Os.mkdir(file.getAbsolutePath(), 0755);
643            Os.chmod(file.getAbsolutePath(), 0755);
644        } catch (ErrnoException e) {
645            // This purposefully throws if directory already exists
646            throw new IOException("Failed to prepare session dir", e);
647        }
648
649        if (!SELinux.restorecon(file)) {
650            throw new IOException("Failed to restorecon session dir");
651        }
652
653        return file;
654    }
655
656    private String prepareExternalStageCid(int sessionId, long sizeBytes) throws IOException {
657        if (sizeBytes <= 0) {
658            throw new IOException("Session must provide valid size for ASEC");
659        }
660
661        final String cid = "smdl" + sessionId + ".tmp";
662        if (PackageHelper.createSdDir(sizeBytes, cid, PackageManagerService.getEncryptKey(),
663                Process.SYSTEM_UID, true) == null) {
664            throw new IOException("Failed to create ASEC");
665        }
666
667        return cid;
668    }
669
670    @Override
671    public SessionInfo getSessionInfo(int sessionId) {
672        synchronized (mSessions) {
673            final PackageInstallerSession session = mSessions.get(sessionId);
674            if (!isCallingUidOwner(session)) {
675                enforceCallerCanReadSessions();
676            }
677            return session != null ? session.generateInfo() : null;
678        }
679    }
680
681    @Override
682    public List<SessionInfo> getAllSessions(int userId) {
683        mPm.enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "getAllSessions");
684        enforceCallerCanReadSessions();
685
686        final List<SessionInfo> result = new ArrayList<>();
687        synchronized (mSessions) {
688            for (int i = 0; i < mSessions.size(); i++) {
689                final PackageInstallerSession session = mSessions.valueAt(i);
690                if (session.userId == userId) {
691                    result.add(session.generateInfo());
692                }
693            }
694        }
695        return result;
696    }
697
698    @Override
699    public List<SessionInfo> getMySessions(String installerPackageName, int userId) {
700        mPm.enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "getMySessions");
701        mAppOps.checkPackage(Binder.getCallingUid(), installerPackageName);
702
703        final List<SessionInfo> result = new ArrayList<>();
704        synchronized (mSessions) {
705            for (int i = 0; i < mSessions.size(); i++) {
706                final PackageInstallerSession session = mSessions.valueAt(i);
707                if (Objects.equals(session.installerPackageName, installerPackageName)
708                        && session.userId == userId) {
709                    result.add(session.generateInfo());
710                }
711            }
712        }
713        return result;
714    }
715
716    @Override
717    public void uninstall(String packageName, int flags, IntentSender statusReceiver, int userId) {
718        mPm.enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "uninstall");
719
720        final PackageDeleteObserverAdapter adapter = new PackageDeleteObserverAdapter(mContext,
721                statusReceiver, packageName);
722        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DELETE_PACKAGES)
723                == PackageManager.PERMISSION_GRANTED) {
724            // Sweet, call straight through!
725            mPm.deletePackage(packageName, adapter.getBinder(), userId, flags);
726
727        } else {
728            // Take a short detour to confirm with user
729            final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
730            intent.setData(Uri.fromParts("package", packageName, null));
731            intent.putExtra(PackageInstaller.EXTRA_CALLBACK, adapter.getBinder().asBinder());
732            adapter.onUserActionRequired(intent);
733        }
734    }
735
736    @Override
737    public void setPermissionsResult(int sessionId, boolean accepted) {
738        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, TAG);
739
740        synchronized (mSessions) {
741            mSessions.get(sessionId).setPermissionsResult(accepted);
742        }
743    }
744
745    @Override
746    public void registerCallback(IPackageInstallerCallback callback, int userId) {
747        mPm.enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "registerCallback");
748        enforceCallerCanReadSessions();
749
750        mCallbacks.register(callback, userId);
751    }
752
753    @Override
754    public void unregisterCallback(IPackageInstallerCallback callback) {
755        mCallbacks.unregister(callback);
756    }
757
758    private static int getSessionCount(SparseArray<PackageInstallerSession> sessions,
759            int installerUid) {
760        int count = 0;
761        final int size = sessions.size();
762        for (int i = 0; i < size; i++) {
763            final PackageInstallerSession session = sessions.valueAt(i);
764            if (session.installerUid == installerUid) {
765                count++;
766            }
767        }
768        return count;
769    }
770
771    private boolean isCallingUidOwner(PackageInstallerSession session) {
772        final int callingUid = Binder.getCallingUid();
773        if (callingUid == Process.ROOT_UID) {
774            return true;
775        } else {
776            return (session != null) && (callingUid == session.installerUid);
777        }
778    }
779
780    /**
781     * We allow those with permission, or the current home app.
782     */
783    private void enforceCallerCanReadSessions() {
784        final boolean hasPermission = (mContext.checkCallingOrSelfPermission(
785                android.Manifest.permission.READ_INSTALL_SESSIONS)
786                == PackageManager.PERMISSION_GRANTED);
787        final boolean isHomeApp = mPm.checkCallerIsHomeApp();
788        if (hasPermission || isHomeApp) {
789            return;
790        } else {
791            throw new SecurityException("Caller must be current home app to read install sessions");
792        }
793    }
794
795    static class PackageDeleteObserverAdapter extends PackageDeleteObserver {
796        private final Context mContext;
797        private final IntentSender mTarget;
798        private final String mPackageName;
799
800        public PackageDeleteObserverAdapter(Context context, IntentSender target,
801                String packageName) {
802            mContext = context;
803            mTarget = target;
804            mPackageName = packageName;
805        }
806
807        @Override
808        public void onUserActionRequired(Intent intent) {
809            final Intent fillIn = new Intent();
810            fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, mPackageName);
811            fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
812                    PackageInstaller.STATUS_PENDING_USER_ACTION);
813            fillIn.putExtra(Intent.EXTRA_INTENT, intent);
814            try {
815                mTarget.sendIntent(mContext, 0, fillIn, null, null);
816            } catch (SendIntentException ignored) {
817            }
818        }
819
820        @Override
821        public void onPackageDeleted(String basePackageName, int returnCode, String msg) {
822            final Intent fillIn = new Intent();
823            fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, mPackageName);
824            fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
825                    PackageManager.deleteStatusToPublicStatus(returnCode));
826            fillIn.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE,
827                    PackageManager.deleteStatusToString(returnCode, msg));
828            fillIn.putExtra(PackageInstaller.EXTRA_LEGACY_STATUS, returnCode);
829            try {
830                mTarget.sendIntent(mContext, 0, fillIn, null, null);
831            } catch (SendIntentException ignored) {
832            }
833        }
834    }
835
836    static class PackageInstallObserverAdapter extends PackageInstallObserver {
837        private final Context mContext;
838        private final IntentSender mTarget;
839        private final int mSessionId;
840
841        public PackageInstallObserverAdapter(Context context, IntentSender target, int sessionId) {
842            mContext = context;
843            mTarget = target;
844            mSessionId = sessionId;
845        }
846
847        @Override
848        public void onUserActionRequired(Intent intent) {
849            final Intent fillIn = new Intent();
850            fillIn.putExtra(PackageInstaller.EXTRA_SESSION_ID, mSessionId);
851            fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
852                    PackageInstaller.STATUS_PENDING_USER_ACTION);
853            fillIn.putExtra(Intent.EXTRA_INTENT, intent);
854            try {
855                mTarget.sendIntent(mContext, 0, fillIn, null, null);
856            } catch (SendIntentException ignored) {
857            }
858        }
859
860        @Override
861        public void onPackageInstalled(String basePackageName, int returnCode, String msg,
862                Bundle extras) {
863            final Intent fillIn = new Intent();
864            fillIn.putExtra(PackageInstaller.EXTRA_SESSION_ID, mSessionId);
865            fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
866                    PackageManager.installStatusToPublicStatus(returnCode));
867            fillIn.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE,
868                    PackageManager.installStatusToString(returnCode, msg));
869            fillIn.putExtra(PackageInstaller.EXTRA_LEGACY_STATUS, returnCode);
870            if (extras != null) {
871                final String existing = extras.getString(
872                        PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE);
873                if (!TextUtils.isEmpty(existing)) {
874                    fillIn.putExtra(PackageInstaller.EXTRA_OTHER_PACKAGE_NAME, existing);
875                }
876            }
877            try {
878                mTarget.sendIntent(mContext, 0, fillIn, null, null);
879            } catch (SendIntentException ignored) {
880            }
881        }
882    }
883
884    private static class Callbacks extends Handler {
885        private static final int MSG_SESSION_CREATED = 1;
886        private static final int MSG_SESSION_OPENED = 2;
887        private static final int MSG_SESSION_PROGRESS_CHANGED = 3;
888        private static final int MSG_SESSION_CLOSED = 4;
889        private static final int MSG_SESSION_FINISHED = 5;
890
891        private final RemoteCallbackList<IPackageInstallerCallback>
892                mCallbacks = new RemoteCallbackList<>();
893
894        public Callbacks(Looper looper) {
895            super(looper);
896        }
897
898        public void register(IPackageInstallerCallback callback, int userId) {
899            mCallbacks.register(callback, new UserHandle(userId));
900        }
901
902        public void unregister(IPackageInstallerCallback callback) {
903            mCallbacks.unregister(callback);
904        }
905
906        @Override
907        public void handleMessage(Message msg) {
908            final int userId = msg.arg2;
909            final int n = mCallbacks.beginBroadcast();
910            for (int i = 0; i < n; i++) {
911                final IPackageInstallerCallback callback = mCallbacks.getBroadcastItem(i);
912                final UserHandle user = (UserHandle) mCallbacks.getBroadcastCookie(i);
913                // TODO: dispatch notifications for slave profiles
914                if (userId == user.getIdentifier()) {
915                    try {
916                        invokeCallback(callback, msg);
917                    } catch (RemoteException ignored) {
918                    }
919                }
920            }
921            mCallbacks.finishBroadcast();
922        }
923
924        private void invokeCallback(IPackageInstallerCallback callback, Message msg)
925                throws RemoteException {
926            final int sessionId = msg.arg1;
927            switch (msg.what) {
928                case MSG_SESSION_CREATED:
929                    callback.onSessionCreated(sessionId);
930                    break;
931                case MSG_SESSION_OPENED:
932                    callback.onSessionOpened(sessionId);
933                    break;
934                case MSG_SESSION_PROGRESS_CHANGED:
935                    callback.onSessionProgressChanged(sessionId, (float) msg.obj);
936                    break;
937                case MSG_SESSION_CLOSED:
938                    callback.onSessionClosed(sessionId);
939                    break;
940                case MSG_SESSION_FINISHED:
941                    callback.onSessionFinished(sessionId, (boolean) msg.obj);
942                    break;
943            }
944        }
945
946        private void notifySessionCreated(int sessionId, int userId) {
947            obtainMessage(MSG_SESSION_CREATED, sessionId, userId).sendToTarget();
948        }
949
950        private void notifySessionOpened(int sessionId, int userId) {
951            obtainMessage(MSG_SESSION_OPENED, sessionId, userId).sendToTarget();
952        }
953
954        private void notifySessionProgressChanged(int sessionId, int userId, float progress) {
955            obtainMessage(MSG_SESSION_PROGRESS_CHANGED, sessionId, userId, progress).sendToTarget();
956        }
957
958        private void notifySessionClosed(int sessionId, int userId) {
959            obtainMessage(MSG_SESSION_CLOSED, sessionId, userId).sendToTarget();
960        }
961
962        public void notifySessionFinished(int sessionId, int userId, boolean success) {
963            obtainMessage(MSG_SESSION_FINISHED, sessionId, userId, success).sendToTarget();
964        }
965    }
966
967    void dump(IndentingPrintWriter pw) {
968        synchronized (mSessions) {
969            pw.println("Active install sessions:");
970            pw.increaseIndent();
971            int N = mSessions.size();
972            for (int i = 0; i < N; i++) {
973                final PackageInstallerSession session = mSessions.valueAt(i);
974                session.dump(pw);
975                pw.println();
976            }
977            pw.println();
978            pw.decreaseIndent();
979
980            pw.println("Historical install sessions:");
981            pw.increaseIndent();
982            N = mHistoricalSessions.size();
983            for (int i = 0; i < N; i++) {
984                final PackageInstallerSession session = mHistoricalSessions.valueAt(i);
985                session.dump(pw);
986                pw.println();
987            }
988            pw.println();
989            pw.decreaseIndent();
990
991            pw.println("Legacy install sessions:");
992            pw.increaseIndent();
993            pw.println(mLegacySessions.toString());
994            pw.decreaseIndent();
995        }
996    }
997
998    class InternalCallback {
999        public void onSessionProgressChanged(PackageInstallerSession session, float progress) {
1000            mCallbacks.notifySessionProgressChanged(session.sessionId, session.userId, progress);
1001        }
1002
1003        public void onSessionOpened(PackageInstallerSession session) {
1004            mCallbacks.notifySessionOpened(session.sessionId, session.userId);
1005        }
1006
1007        public void onSessionClosed(PackageInstallerSession session) {
1008            mCallbacks.notifySessionClosed(session.sessionId, session.userId);
1009        }
1010
1011        public void onSessionFinished(PackageInstallerSession session, boolean success) {
1012            mCallbacks.notifySessionFinished(session.sessionId, session.userId, success);
1013            synchronized (mSessions) {
1014                mSessions.remove(session.sessionId);
1015                mHistoricalSessions.put(session.sessionId, session);
1016            }
1017            writeSessionsAsync();
1018        }
1019
1020        public void onSessionSealed(PackageInstallerSession session) {
1021            // It's very important that we block until we've recorded the
1022            // session as being sealed, since we never want to allow mutation
1023            // after sealing.
1024            writeSessionsLocked();
1025        }
1026    }
1027}
1028