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