PackageInstallerSession.java revision 57dcf5b177b56195421535938544f32d8b591b42
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_FAILED_ALREADY_EXISTS;
20import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
21import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
22import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
23import static android.content.pm.PackageManager.INSTALL_SUCCEEDED;
24
25import android.content.pm.ApplicationInfo;
26import android.content.pm.IPackageInstallObserver2;
27import android.content.pm.IPackageInstallerSession;
28import android.content.pm.PackageInstallerParams;
29import android.content.pm.PackageManager;
30import android.content.pm.PackageParser;
31import android.content.pm.PackageParser.ApkLite;
32import android.content.pm.PackageParser.PackageParserException;
33import android.content.pm.Signature;
34import android.os.Build;
35import android.os.Bundle;
36import android.os.FileBridge;
37import android.os.FileUtils;
38import android.os.Handler;
39import android.os.Looper;
40import android.os.Message;
41import android.os.ParcelFileDescriptor;
42import android.os.RemoteException;
43import android.os.SELinux;
44import android.os.UserHandle;
45import android.system.ErrnoException;
46import android.system.OsConstants;
47import android.system.StructStat;
48import android.util.ArraySet;
49import android.util.Slog;
50
51import com.android.internal.content.NativeLibraryHelper;
52import com.android.internal.util.ArrayUtils;
53import com.android.internal.util.Preconditions;
54
55import libcore.io.IoUtils;
56import libcore.io.Libcore;
57
58import java.io.File;
59import java.io.FileDescriptor;
60import java.io.IOException;
61import java.util.ArrayList;
62
63public class PackageInstallerSession extends IPackageInstallerSession.Stub {
64    private static final String TAG = "PackageInstaller";
65
66    private final PackageInstallerService.Callback mCallback;
67    private final PackageManagerService mPm;
68    private final Handler mHandler;
69
70    public final int sessionId;
71    public final int userId;
72    public final String installerPackageName;
73    /** UID not persisted */
74    public final int installerUid;
75    public final PackageInstallerParams params;
76    public final long createdMillis;
77    public final File sessionDir;
78
79    private static final int MSG_INSTALL = 0;
80
81    private Handler.Callback mHandlerCallback = new Handler.Callback() {
82        @Override
83        public boolean handleMessage(Message msg) {
84            synchronized (mLock) {
85                if (msg.obj != null) {
86                    mRemoteObserver = (IPackageInstallObserver2) msg.obj;
87                }
88
89                try {
90                    installLocked();
91                } catch (InstallFailedException e) {
92                    Slog.e(TAG, "Install failed: " + e);
93                    try {
94                        mRemoteObserver.packageInstalled(mPackageName, null, e.error);
95                    } catch (RemoteException ignored) {
96                    }
97                }
98
99                return true;
100            }
101        }
102    };
103
104    private final Object mLock = new Object();
105
106    private int mProgress;
107
108    private String mPackageName;
109    private int mVersionCode;
110    private Signature[] mSignatures;
111
112    private boolean mMutationsAllowed;
113    private boolean mVerifierConfirmed;
114    private boolean mPermissionsConfirmed;
115    private boolean mInvalid;
116
117    private ArrayList<FileBridge> mBridges = new ArrayList<>();
118
119    private IPackageInstallObserver2 mRemoteObserver;
120
121    public PackageInstallerSession(PackageInstallerService.Callback callback,
122            PackageManagerService pm, int sessionId, int userId, String installerPackageName,
123            int installerUid, PackageInstallerParams params, long createdMillis, File sessionDir,
124            Looper looper) {
125        mCallback = callback;
126        mPm = pm;
127        mHandler = new Handler(looper, mHandlerCallback);
128
129        this.sessionId = sessionId;
130        this.userId = userId;
131        this.installerPackageName = installerPackageName;
132        this.installerUid = installerUid;
133        this.params = params;
134        this.createdMillis = createdMillis;
135        this.sessionDir = sessionDir;
136
137        // Check against any explicitly provided signatures
138        mSignatures = params.signatures;
139
140        // TODO: splice in flag when restoring persisted session
141        mMutationsAllowed = true;
142
143        if (pm.checkPermission(android.Manifest.permission.INSTALL_PACKAGES, installerPackageName)
144                == PackageManager.PERMISSION_GRANTED) {
145            mPermissionsConfirmed = true;
146        }
147    }
148
149    @Override
150    public void updateProgress(int progress) {
151        mProgress = progress;
152        mCallback.onProgressChanged(this);
153    }
154
155    @Override
156    public ParcelFileDescriptor openWrite(String name, long offsetBytes, long lengthBytes) {
157        // TODO: relay over to DCS when installing to ASEC
158
159        // Quick sanity check of state, and allocate a pipe for ourselves. We
160        // then do heavy disk allocation outside the lock, but this open pipe
161        // will block any attempted install transitions.
162        final FileBridge bridge;
163        synchronized (mLock) {
164            if (!mMutationsAllowed) {
165                throw new IllegalStateException("Mutations not allowed");
166            }
167
168            bridge = new FileBridge();
169            mBridges.add(bridge);
170        }
171
172        try {
173            // Use installer provided name for now; we always rename later
174            if (!FileUtils.isValidExtFilename(name)) {
175                throw new IllegalArgumentException("Invalid name: " + name);
176            }
177            final File target = new File(sessionDir, name);
178
179            final FileDescriptor targetFd = Libcore.os.open(target.getAbsolutePath(),
180                    OsConstants.O_CREAT | OsConstants.O_WRONLY, 00700);
181
182            // If caller specified a total length, allocate it for them. Free up
183            // cache space to grow, if needed.
184            if (lengthBytes > 0) {
185                final StructStat stat = Libcore.os.fstat(targetFd);
186                final long deltaBytes = lengthBytes - stat.st_size;
187                if (deltaBytes > 0) {
188                    mPm.freeStorage(deltaBytes);
189                }
190                Libcore.os.posix_fallocate(targetFd, 0, lengthBytes);
191            }
192
193            if (offsetBytes > 0) {
194                Libcore.os.lseek(targetFd, offsetBytes, OsConstants.SEEK_SET);
195            }
196
197            bridge.setTargetFile(targetFd);
198            bridge.start();
199            return new ParcelFileDescriptor(bridge.getClientSocket());
200
201        } catch (ErrnoException e) {
202            throw new IllegalStateException("Failed to write", e);
203        } catch (IOException e) {
204            throw new IllegalStateException("Failed to write", e);
205        }
206    }
207
208    @Override
209    public void install(IPackageInstallObserver2 observer) {
210        Preconditions.checkNotNull(observer);
211        mHandler.obtainMessage(MSG_INSTALL, observer).sendToTarget();
212    }
213
214    private void installLocked() throws InstallFailedException {
215        if (mInvalid) {
216            throw new InstallFailedException(INSTALL_FAILED_ALREADY_EXISTS, "Invalid session");
217        }
218
219        // Verify that all writers are hands-off
220        if (mMutationsAllowed) {
221            for (FileBridge bridge : mBridges) {
222                if (!bridge.isClosed()) {
223                    throw new InstallFailedException(INSTALL_FAILED_PACKAGE_CHANGED,
224                            "Files still open");
225                }
226            }
227            mMutationsAllowed = false;
228
229            // TODO: persist disabled mutations before going forward, since
230            // beyond this point we may have hardlinks to the valid install
231        }
232
233        // Verify that stage looks sane with respect to existing application.
234        // This currently only ensures packageName, versionCode, and certificate
235        // consistency.
236        validateInstallLocked();
237
238        Preconditions.checkNotNull(mPackageName);
239        Preconditions.checkNotNull(mSignatures);
240
241        if (!mVerifierConfirmed) {
242            // TODO: async communication with verifier
243            // when they confirm, we'll kick off another install() pass
244            mVerifierConfirmed = true;
245        }
246
247        if (!mPermissionsConfirmed) {
248            // TODO: async confirm permissions with user
249            // when they confirm, we'll kick off another install() pass
250            mPermissionsConfirmed = true;
251        }
252
253        // Unpack any native libraries contained in this session
254        unpackNativeLibraries();
255
256        // Inherit any packages and native libraries from existing install that
257        // haven't been overridden.
258        if (!params.fullInstall) {
259            spliceExistingFilesIntoStage();
260        }
261
262        // TODO: for ASEC based applications, grow and stream in packages
263
264        // We've reached point of no return; call into PMS to install the stage.
265        // Regardless of success or failure we always destroy session.
266        final IPackageInstallObserver2 remoteObserver = mRemoteObserver;
267        final IPackageInstallObserver2 localObserver = new IPackageInstallObserver2.Stub() {
268            @Override
269            public void packageInstalled(String basePackageName, Bundle extras, int returnCode)
270                    throws RemoteException {
271                destroy();
272                remoteObserver.packageInstalled(basePackageName, extras, returnCode);
273            }
274        };
275
276        mPm.installStage(mPackageName, this.sessionDir, localObserver, params, installerPackageName,
277                installerUid, new UserHandle(userId));
278    }
279
280    /**
281     * Validate install by confirming that all application packages are have
282     * consistent package name, version code, and signing certificates.
283     * <p>
284     * Renames package files in stage to match split names defined inside.
285     */
286    private void validateInstallLocked() throws InstallFailedException {
287        mPackageName = null;
288        mVersionCode = -1;
289        mSignatures = null;
290
291        final File[] files = sessionDir.listFiles();
292        if (ArrayUtils.isEmpty(files)) {
293            throw new InstallFailedException(INSTALL_FAILED_INVALID_APK, "No packages staged");
294        }
295
296        final ArraySet<String> seenSplits = new ArraySet<>();
297
298        // Verify that all staged packages are internally consistent
299        for (File file : files) {
300            final ApkLite info;
301            try {
302                info = PackageParser.parseApkLite(file, PackageParser.PARSE_GET_SIGNATURES);
303            } catch (PackageParserException e) {
304                throw new InstallFailedException(INSTALL_FAILED_INVALID_APK,
305                        "Failed to parse " + file + ": " + e);
306            }
307
308            if (!seenSplits.add(info.splitName)) {
309                throw new InstallFailedException(INSTALL_FAILED_INVALID_APK,
310                        "Split " + info.splitName + " was defined multiple times");
311            }
312
313            // Use first package to define unknown values
314            if (mPackageName != null) {
315                mPackageName = info.packageName;
316                mVersionCode = info.versionCode;
317            }
318            if (mSignatures != null) {
319                mSignatures = info.signatures;
320            }
321
322            assertPackageConsistent(String.valueOf(file), info.packageName, info.versionCode,
323                    info.signatures);
324
325            // Take this opportunity to enforce uniform naming
326            final String name;
327            if (info.splitName == null) {
328                name = info.packageName + ".apk";
329            } else {
330                name = info.packageName + "-" + info.splitName + ".apk";
331            }
332            if (!FileUtils.isValidExtFilename(name)) {
333                throw new InstallFailedException(INSTALL_FAILED_INVALID_APK,
334                        "Invalid filename: " + name);
335            }
336            if (!file.getName().equals(name)) {
337                file.renameTo(new File(file.getParentFile(), name));
338            }
339        }
340
341        // TODO: shift package signature verification to installer; we're
342        // currently relying on PMS to do this.
343        // TODO: teach about compatible upgrade keysets.
344
345        if (params.fullInstall) {
346            // Full installs must include a base package
347            if (!seenSplits.contains(null)) {
348                throw new InstallFailedException(INSTALL_FAILED_INVALID_APK,
349                        "Full install must include a base package");
350            }
351
352        } else {
353            // Partial installs must be consistent with existing install.
354            final ApplicationInfo app = mPm.getApplicationInfo(mPackageName, 0, userId);
355            if (app == null) {
356                throw new InstallFailedException(INSTALL_FAILED_INVALID_APK,
357                        "Missing existing base package for " + mPackageName);
358            }
359
360            final ApkLite info;
361            try {
362                info = PackageParser.parseApkLite(new File(app.sourceDir),
363                        PackageParser.PARSE_GET_SIGNATURES);
364            } catch (PackageParserException e) {
365                throw new InstallFailedException(INSTALL_FAILED_INVALID_APK,
366                        "Failed to parse existing base " + app.sourceDir + ": " + e);
367            }
368
369            assertPackageConsistent("Existing base", info.packageName, info.versionCode,
370                    info.signatures);
371        }
372    }
373
374    private void assertPackageConsistent(String tag, String packageName, int versionCode,
375            Signature[] signatures) throws InstallFailedException {
376        if (!mPackageName.equals(packageName)) {
377            throw new InstallFailedException(INSTALL_FAILED_INVALID_APK, tag + " package "
378                    + packageName + " inconsistent with " + mPackageName);
379        }
380        if (mVersionCode != versionCode) {
381            throw new InstallFailedException(INSTALL_FAILED_INVALID_APK, tag
382                    + " version code " + versionCode + " inconsistent with "
383                    + mVersionCode);
384        }
385        if (!Signature.areExactMatch(mSignatures, signatures)) {
386            throw new InstallFailedException(INSTALL_FAILED_INVALID_APK,
387                    tag + " signatures are inconsistent");
388        }
389    }
390
391    /**
392     * Application is already installed; splice existing files that haven't been
393     * overridden into our stage.
394     */
395    private void spliceExistingFilesIntoStage() throws InstallFailedException {
396        final ApplicationInfo app = mPm.getApplicationInfo(mPackageName, 0, userId);
397        final File existingDir = new File(app.sourceDir).getParentFile();
398
399        try {
400            linkTreeIgnoringExisting(existingDir, sessionDir);
401        } catch (ErrnoException e) {
402            throw new InstallFailedException(INSTALL_FAILED_INTERNAL_ERROR,
403                    "Failed to splice into stage");
404        }
405    }
406
407    /**
408     * Recursively hard link all files from source directory tree to target.
409     * When a file already exists in the target tree, it leaves that file
410     * intact.
411     */
412    private void linkTreeIgnoringExisting(File sourceDir, File targetDir) throws ErrnoException {
413        final File[] sourceContents = sourceDir.listFiles();
414        if (ArrayUtils.isEmpty(sourceContents)) return;
415
416        for (File sourceFile : sourceContents) {
417            final File targetFile = new File(targetDir, sourceFile.getName());
418
419            if (sourceFile.isDirectory()) {
420                targetFile.mkdir();
421                linkTreeIgnoringExisting(sourceFile, targetFile);
422            } else {
423                Libcore.os.link(sourceFile.getAbsolutePath(), targetFile.getAbsolutePath());
424            }
425        }
426    }
427
428    private void unpackNativeLibraries() throws InstallFailedException {
429        final File libDir = new File(sessionDir, "lib");
430
431        if (!libDir.mkdir()) {
432            throw new InstallFailedException(INSTALL_FAILED_INTERNAL_ERROR,
433                    "Failed to create " + libDir);
434        }
435
436        try {
437            Libcore.os.chmod(libDir.getAbsolutePath(), 0755);
438        } catch (ErrnoException e) {
439            throw new InstallFailedException(INSTALL_FAILED_INTERNAL_ERROR,
440                    "Failed to prepare " + libDir + ": " + e);
441        }
442
443        if (!SELinux.restorecon(libDir)) {
444            throw new InstallFailedException(INSTALL_FAILED_INTERNAL_ERROR,
445                    "Failed to set context on " + libDir);
446        }
447
448        // Unpack all native libraries under stage
449        final File[] files = sessionDir.listFiles();
450        if (ArrayUtils.isEmpty(files)) {
451            throw new InstallFailedException(INSTALL_FAILED_INVALID_APK, "No packages staged");
452        }
453
454        for (File file : files) {
455            NativeLibraryHelper.ApkHandle handle = null;
456            try {
457                handle = NativeLibraryHelper.ApkHandle.create(file);
458                final int abiIndex = NativeLibraryHelper.findSupportedAbi(handle,
459                        Build.SUPPORTED_ABIS);
460                if (abiIndex >= 0) {
461                    int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, libDir,
462                            Build.SUPPORTED_ABIS[abiIndex]);
463                    if (copyRet != INSTALL_SUCCEEDED) {
464                        throw new InstallFailedException(copyRet,
465                                "Failed to copy native libraries for " + file);
466                    }
467                } else if (abiIndex != PackageManager.NO_NATIVE_LIBRARIES) {
468                    throw new InstallFailedException(abiIndex,
469                            "Failed to copy native libraries for " + file);
470                }
471            } catch (IOException ioe) {
472                throw new InstallFailedException(INSTALL_FAILED_INTERNAL_ERROR,
473                        "Failed to create handle for " + file);
474            } finally {
475                IoUtils.closeQuietly(handle);
476            }
477        }
478    }
479
480    @Override
481    public void destroy() {
482        try {
483            synchronized (mLock) {
484                mInvalid = true;
485            }
486            FileUtils.deleteContents(sessionDir);
487            sessionDir.delete();
488        } finally {
489            mCallback.onSessionInvalid(this);
490        }
491    }
492
493    private class InstallFailedException extends Exception {
494        private final int error;
495
496        public InstallFailedException(int error, String detailMessage) {
497            super(detailMessage);
498            this.error = error;
499        }
500    }
501}
502