summaryrefslogtreecommitdiffstats
path: root/services/core/java/com/android/server/pm/PackageInstallerSession.java
blob: 26019dbecf240651d773588a9beea7c690fbe468 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.server.pm;

import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
import static android.system.OsConstants.O_CREAT;
import static android.system.OsConstants.O_RDONLY;
import static android.system.OsConstants.O_WRONLY;

import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageInstallObserver2;
import android.content.pm.IPackageInstallerSession;
import android.content.pm.InstallSessionInfo;
import android.content.pm.InstallSessionParams;
import android.content.pm.PackageManager;
import android.content.pm.PackageParser;
import android.content.pm.PackageParser.ApkLite;
import android.content.pm.PackageParser.PackageParserException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.os.FileBridge;
import android.os.FileUtils;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.os.UserHandle;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
import android.system.StructStat;
import android.util.ArraySet;
import android.util.ExceptionUtils;
import android.util.MathUtils;
import android.util.Slog;

import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.ArrayUtils;
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.Preconditions;

import libcore.io.Libcore;

import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class PackageInstallerSession extends IPackageInstallerSession.Stub {
    private static final String TAG = "PackageInstaller";
    private static final boolean LOGD = true;

    private static final int MSG_COMMIT = 0;

    // TODO: enforce INSTALL_ALLOW_TEST
    // TODO: enforce INSTALL_ALLOW_DOWNGRADE
    // TODO: handle INSTALL_EXTERNAL, INSTALL_INTERNAL

    // TODO: treat INHERIT_EXISTING as installExistingPackage()

    private final PackageInstallerService.InternalCallback mCallback;
    private final PackageManagerService mPm;
    private final Handler mHandler;

    final int sessionId;
    final int userId;
    final String installerPackageName;
    final InstallSessionParams params;
    final long createdMillis;
    final File sessionStageDir;

    /** Note that UID is not persisted; it's always derived at runtime. */
    final int installerUid;

    AtomicInteger openCount = new AtomicInteger();

    private final Object mLock = new Object();

    @GuardedBy("mLock")
    private float mClientProgress = 0;
    @GuardedBy("mLock")
    private float mProgress = 0;
    @GuardedBy("mLock")
    private float mReportedProgress = -1;

    @GuardedBy("mLock")
    private boolean mSealed = false;
    @GuardedBy("mLock")
    private boolean mPermissionsConfirmed = false;
    @GuardedBy("mLock")
    private boolean mDestroyed = false;

    @GuardedBy("mLock")
    private ArrayList<FileBridge> mBridges = new ArrayList<>();

    @GuardedBy("mLock")
    private IPackageInstallObserver2 mRemoteObserver;

    /** Fields derived from commit parsing */
    private String mPackageName;
    private int mVersionCode;
    private Signature[] mSignatures;

    private final Handler.Callback mHandlerCallback = new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            synchronized (mLock) {
                if (msg.obj != null) {
                    mRemoteObserver = (IPackageInstallObserver2) msg.obj;
                }

                try {
                    commitLocked();
                } catch (PackageManagerException e) {
                    Slog.e(TAG, "Install failed: " + e);
                    destroyInternal();
                    try {
                        mRemoteObserver.packageInstalled(mPackageName, null, e.error,
                                e.getMessage());
                    } catch (RemoteException ignored) {
                    }
                    mCallback.onSessionFinished(PackageInstallerSession.this, false);
                }

                return true;
            }
        }
    };

    public PackageInstallerSession(PackageInstallerService.InternalCallback callback,
            PackageManagerService pm, Looper looper, int sessionId, int userId,
            String installerPackageName, InstallSessionParams params, long createdMillis,
            File sessionStageDir, boolean sealed) {
        mCallback = callback;
        mPm = pm;
        mHandler = new Handler(looper, mHandlerCallback);

        this.sessionId = sessionId;
        this.userId = userId;
        this.installerPackageName = installerPackageName;
        this.params = params;
        this.createdMillis = createdMillis;
        this.sessionStageDir = sessionStageDir;

        mSealed = sealed;

        // Always derived at runtime
        installerUid = mPm.getPackageUid(installerPackageName, userId);

        if (mPm.checkPermission(android.Manifest.permission.INSTALL_PACKAGES,
                installerPackageName) == PackageManager.PERMISSION_GRANTED) {
            mPermissionsConfirmed = true;
        } else {
            mPermissionsConfirmed = false;
        }

        computeProgressLocked();
    }

    public InstallSessionInfo generateInfo() {
        final InstallSessionInfo info = new InstallSessionInfo();

        info.sessionId = sessionId;
        info.installerPackageName = installerPackageName;
        info.progress = mProgress;
        info.open = openCount.get() > 0;

        info.mode = params.mode;
        info.sizeBytes = params.sizeBytes;
        info.appPackageName = params.appPackageName;
        info.appIcon = params.appIcon;
        info.appLabel = params.appLabel;

        return info;
    }

    private void assertNotSealed(String cookie) {
        synchronized (mLock) {
            if (mSealed) {
                throw new SecurityException(cookie + " not allowed after commit");
            }
        }
    }

    @Override
    public void setClientProgress(float progress) {
        synchronized (mLock) {
            mClientProgress = progress;
            computeProgressLocked();
        }
        maybePublishProgress();
    }

    @Override
    public void addClientProgress(float progress) {
        synchronized (mLock) {
            mClientProgress += progress;
            computeProgressLocked();
        }
        maybePublishProgress();
    }

    private void computeProgressLocked() {
        mProgress = MathUtils.constrain(mClientProgress * 0.8f, 0f, 0.8f);
    }

    private void maybePublishProgress() {
        // Only publish when meaningful change
        if (Math.abs(mProgress - mReportedProgress) > 0.01) {
            mReportedProgress = mProgress;
            mCallback.onSessionProgressChanged(this, mProgress);
        }
    }

    @Override
    public String[] list() {
        assertNotSealed("list");
        return sessionStageDir.list();
    }

    @Override
    public ParcelFileDescriptor openWrite(String name, long offsetBytes, long lengthBytes) {
        try {
            return openWriteInternal(name, offsetBytes, lengthBytes);
        } catch (IOException e) {
            throw ExceptionUtils.wrap(e);
        }
    }

    private ParcelFileDescriptor openWriteInternal(String name, long offsetBytes, long lengthBytes)
            throws IOException {
        // TODO: relay over to DCS when installing to ASEC

        // Quick sanity check of state, and allocate a pipe for ourselves. We
        // then do heavy disk allocation outside the lock, but this open pipe
        // will block any attempted install transitions.
        final FileBridge bridge;
        synchronized (mLock) {
            assertNotSealed("openWrite");

            bridge = new FileBridge();
            mBridges.add(bridge);
        }

        try {
            // Use installer provided name for now; we always rename later
            if (!FileUtils.isValidExtFilename(name)) {
                throw new IllegalArgumentException("Invalid name: " + name);
            }
            final File target = new File(sessionStageDir, name);

            final FileDescriptor targetFd = Libcore.os.open(target.getAbsolutePath(),
                    O_CREAT | O_WRONLY, 0644);
            Os.chmod(target.getAbsolutePath(), 0644);

            // If caller specified a total length, allocate it for them. Free up
            // cache space to grow, if needed.
            if (lengthBytes > 0) {
                final StructStat stat = Libcore.os.fstat(targetFd);
                final long deltaBytes = lengthBytes - stat.st_size;
                if (deltaBytes > 0) {
                    mPm.freeStorage(deltaBytes);
                }
                Libcore.os.posix_fallocate(targetFd, 0, lengthBytes);
            }

            if (offsetBytes > 0) {
                Libcore.os.lseek(targetFd, offsetBytes, OsConstants.SEEK_SET);
            }

            bridge.setTargetFile(targetFd);
            bridge.start();
            return new ParcelFileDescriptor(bridge.getClientSocket());

        } catch (ErrnoException e) {
            throw e.rethrowAsIOException();
        }
    }

    @Override
    public ParcelFileDescriptor openRead(String name) {
        try {
            return openReadInternal(name);
        } catch (IOException e) {
            throw ExceptionUtils.wrap(e);
        }
    }

    private ParcelFileDescriptor openReadInternal(String name) throws IOException {
        assertNotSealed("openRead");

        try {
            if (!FileUtils.isValidExtFilename(name)) {
                throw new IllegalArgumentException("Invalid name: " + name);
            }
            final File target = new File(sessionStageDir, name);

            final FileDescriptor targetFd = Libcore.os.open(target.getAbsolutePath(), O_RDONLY, 0);
            return new ParcelFileDescriptor(targetFd);

        } catch (ErrnoException e) {
            throw e.rethrowAsIOException();
        }
    }

    @Override
    public void commit(IPackageInstallObserver2 observer) {
        Preconditions.checkNotNull(observer);
        mHandler.obtainMessage(MSG_COMMIT, observer).sendToTarget();
    }

    private void commitLocked() throws PackageManagerException {
        if (mDestroyed) {
            throw new PackageManagerException(INSTALL_FAILED_ALREADY_EXISTS, "Invalid session");
        }

        // Verify that all writers are hands-off
        if (!mSealed) {
            for (FileBridge bridge : mBridges) {
                if (!bridge.isClosed()) {
                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
                            "Files still open");
                }
            }
            mSealed = true;

            // TODO: persist disabled mutations before going forward, since
            // beyond this point we may have hardlinks to the valid install
        }

        // Verify that stage looks sane with respect to existing application.
        // This currently only ensures packageName, versionCode, and certificate
        // consistency.
        validateInstallLocked();

        Preconditions.checkNotNull(mPackageName);
        Preconditions.checkNotNull(mSignatures);

        if (!mPermissionsConfirmed) {
            // TODO: async confirm permissions with user
            // when they confirm, we'll kick off another install() pass
            throw new SecurityException("Caller must hold INSTALL permission");
        }

        // Inherit any packages and native libraries from existing install that
        // haven't been overridden.
        if (params.mode == InstallSessionParams.MODE_INHERIT_EXISTING) {
            spliceExistingFilesIntoStage();
        }

        // TODO: surface more granular state from dexopt
        mCallback.onSessionProgressChanged(this, 0.9f);

        // TODO: for ASEC based applications, grow and stream in packages

        // We've reached point of no return; call into PMS to install the stage.
        // Regardless of success or failure we always destroy session.
        final IPackageInstallObserver2 remoteObserver = mRemoteObserver;
        final IPackageInstallObserver2 localObserver = new IPackageInstallObserver2.Stub() {
            @Override
            public void packageInstalled(String basePackageName, Bundle extras, int returnCode,
                    String msg) {
                destroyInternal();
                try {
                    remoteObserver.packageInstalled(basePackageName, extras, returnCode, msg);
                } catch (RemoteException ignored) {
                }
                final boolean success = (returnCode == PackageManager.INSTALL_SUCCEEDED);
                mCallback.onSessionFinished(PackageInstallerSession.this, success);
            }
        };

        mPm.installStage(mPackageName, this.sessionStageDir, localObserver, params,
                installerPackageName, installerUid, new UserHandle(userId));
    }

    /**
     * Validate install by confirming that all application packages are have
     * consistent package name, version code, and signing certificates.
     * <p>
     * Renames package files in stage to match split names defined inside.
     */
    private void validateInstallLocked() throws PackageManagerException {
        mPackageName = null;
        mVersionCode = -1;
        mSignatures = null;

        final File[] files = sessionStageDir.listFiles();
        if (ArrayUtils.isEmpty(files)) {
            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, "No packages staged");
        }

        final ArraySet<String> seenSplits = new ArraySet<>();

        // Verify that all staged packages are internally consistent
        for (File file : files) {
            final ApkLite info;
            try {
                info = PackageParser.parseApkLite(file, PackageParser.PARSE_GET_SIGNATURES);
            } catch (PackageParserException e) {
                throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
                        "Failed to parse " + file + ": " + e);
            }

            if (!seenSplits.add(info.splitName)) {
                throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
                        "Split " + info.splitName + " was defined multiple times");
            }

            // Use first package to define unknown values
            if (mPackageName == null) {
                mPackageName = info.packageName;
                mVersionCode = info.versionCode;
            }
            if (mSignatures == null) {
                mSignatures = info.signatures;
            }

            assertPackageConsistent(String.valueOf(file), info.packageName, info.versionCode,
                    info.signatures);

            // Take this opportunity to enforce uniform naming
            final String name;
            if (info.splitName == null) {
                name = "base.apk";
            } else {
                name = "split_" + info.splitName + ".apk";
            }
            if (!FileUtils.isValidExtFilename(name)) {
                throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
                        "Invalid filename: " + name);
            }
            if (!file.getName().equals(name)) {
                file.renameTo(new File(file.getParentFile(), name));
            }
        }

        // TODO: shift package signature verification to installer; we're
        // currently relying on PMS to do this.
        // TODO: teach about compatible upgrade keysets.

        if (params.mode == InstallSessionParams.MODE_FULL_INSTALL) {
            // Full installs must include a base package
            if (!seenSplits.contains(null)) {
                throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
                        "Full install must include a base package");
            }

        } else {
            // Partial installs must be consistent with existing install.
            final ApplicationInfo app = mPm.getApplicationInfo(mPackageName, 0, userId);
            if (app == null) {
                throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
                        "Missing existing base package for " + mPackageName);
            }

            final ApkLite info;
            try {
                info = PackageParser.parseApkLite(new File(app.getBaseCodePath()),
                        PackageParser.PARSE_GET_SIGNATURES);
            } catch (PackageParserException e) {
                throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
                        "Failed to parse existing base " + app.getBaseCodePath() + ": " + e);
            }

            assertPackageConsistent("Existing base", info.packageName, info.versionCode,
                    info.signatures);
        }
    }

    private void assertPackageConsistent(String tag, String packageName, int versionCode,
            Signature[] signatures) throws PackageManagerException {
        if (!mPackageName.equals(packageName)) {
            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, tag + " package "
                    + packageName + " inconsistent with " + mPackageName);
        }
        if (mVersionCode != versionCode) {
            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, tag
                    + " version code " + versionCode + " inconsistent with "
                    + mVersionCode);
        }
        if (!Signature.areExactMatch(mSignatures, signatures)) {
            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
                    tag + " signatures are inconsistent");
        }
    }

    /**
     * Application is already installed; splice existing files that haven't been
     * overridden into our stage.
     */
    private void spliceExistingFilesIntoStage() throws PackageManagerException {
        final ApplicationInfo app = mPm.getApplicationInfo(mPackageName, 0, userId);

        int n = 0;
        final File[] oldFiles = new File(app.getCodePath()).listFiles();
        if (!ArrayUtils.isEmpty(oldFiles)) {
            for (File oldFile : oldFiles) {
                if (!PackageParser.isApkFile(oldFile)) continue;

                final File newFile = new File(sessionStageDir, oldFile.getName());
                try {
                    Os.link(oldFile.getAbsolutePath(), newFile.getAbsolutePath());
                    n++;
                } catch (ErrnoException e) {
                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
                            "Failed to splice into stage", e);
                }
            }
        }

        if (LOGD) Slog.d(TAG, "Spliced " + n + " existing APKs into stage");
    }

    @Override
    public void close() {
        if (openCount.decrementAndGet() == 0) {
            mCallback.onSessionClosed(this);
        }
    }

    @Override
    public void abandon() {
        try {
            destroyInternal();
        } finally {
            mCallback.onSessionFinished(this, false);
        }
    }

    private void destroyInternal() {
        synchronized (mLock) {
            mSealed = true;
            mDestroyed = true;
        }
        FileUtils.deleteContents(sessionStageDir);
        sessionStageDir.delete();
    }

    void dump(IndentingPrintWriter pw) {
        pw.println("Session " + sessionId + ":");
        pw.increaseIndent();

        pw.printPair("userId", userId);
        pw.printPair("installerPackageName", installerPackageName);
        pw.printPair("installerUid", installerUid);
        pw.printPair("createdMillis", createdMillis);
        pw.printPair("sessionStageDir", sessionStageDir);
        pw.println();

        params.dump(pw);

        pw.printPair("mClientProgress", mClientProgress);
        pw.printPair("mProgress", mProgress);
        pw.printPair("mSealed", mSealed);
        pw.printPair("mPermissionsConfirmed", mPermissionsConfirmed);
        pw.printPair("mDestroyed", mDestroyed);
        pw.printPair("mBridges", mBridges.size());
        pw.println();

        pw.decreaseIndent();
    }

    Snapshot snapshot() {
        return new Snapshot(this);
    }

    static class Snapshot {
        final float clientProgress;
        final boolean sealed;

        public Snapshot(PackageInstallerSession session) {
            clientProgress = session.mClientProgress;
            sealed = session.mSealed;
        }
    }
}