BackupManagerService.java revision fe2368c38cc8ed57dbf7fb2614ca2d7939262818
1/*
2 * Copyright (C) 2009 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.backup;
18
19import static android.app.backup.BackupManagerMonitor.EXTRA_LOG_EVENT_PACKAGE_NAME;
20import static android.app.backup.BackupManagerMonitor.EXTRA_LOG_EVENT_PACKAGE_VERSION;
21import static android.app.backup.BackupManagerMonitor.EXTRA_LOG_OLD_VERSION;
22import static android.app.backup.BackupManagerMonitor.EXTRA_LOG_POLICY_ALLOW_APKS;
23import static android.app.backup.BackupManagerMonitor.EXTRA_LOG_MANIFEST_PACKAGE_NAME;
24import static android.app.backup.BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT;
25import static android.app.backup.BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY;
26import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_VERSION_OF_BACKUP_OLDER;
27import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_FULL_RESTORE_SIGNATURE_MISMATCH;
28import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_SYSTEM_APP_NO_AGENT;
29import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_FULL_RESTORE_ALLOW_BACKUP_FALSE;
30import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_APK_NOT_INSTALLED;
31import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_CANNOT_RESTORE_WITHOUT_APK;
32import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_MISSING_SIGNATURE;
33import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_EXPECTED_DIFFERENT_PACKAGE;
34import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_RESTORE_ANY_VERSION;
35import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_VERSIONS_MATCH;
36import static android.content.pm.ApplicationInfo.PRIVATE_FLAG_BACKUP_IN_FOREGROUND;
37
38import android.app.ActivityManager;
39import android.app.AlarmManager;
40import android.app.AppGlobals;
41import android.app.ApplicationThreadConstants;
42import android.app.IActivityManager;
43import android.app.IBackupAgent;
44import android.app.PackageInstallObserver;
45import android.app.PendingIntent;
46import android.app.backup.BackupAgent;
47import android.app.backup.BackupDataInput;
48import android.app.backup.BackupDataOutput;
49import android.app.backup.BackupManager;
50import android.app.backup.BackupManagerMonitor;
51import android.app.backup.BackupProgress;
52import android.app.backup.BackupTransport;
53import android.app.backup.FullBackup;
54import android.app.backup.FullBackupDataOutput;
55import android.app.backup.IBackupManager;
56import android.app.backup.IBackupManagerMonitor;
57import android.app.backup.IBackupObserver;
58import android.app.backup.IFullBackupRestoreObserver;
59import android.app.backup.IRestoreObserver;
60import android.app.backup.IRestoreSession;
61import android.app.backup.ISelectBackupTransportCallback;
62import android.app.backup.RestoreDescription;
63import android.app.backup.RestoreSet;
64import android.app.backup.SelectBackupTransportCallback;
65import android.content.ActivityNotFoundException;
66import android.content.BroadcastReceiver;
67import android.content.ComponentName;
68import android.content.ContentResolver;
69import android.content.Context;
70import android.content.Intent;
71import android.content.IntentFilter;
72import android.content.ServiceConnection;
73import android.content.pm.ApplicationInfo;
74import android.content.pm.IPackageDataObserver;
75import android.content.pm.IPackageDeleteObserver;
76import android.content.pm.IPackageManager;
77import android.content.pm.PackageInfo;
78import android.content.pm.PackageManager;
79import android.content.pm.PackageManager.NameNotFoundException;
80import android.content.pm.Signature;
81import android.database.ContentObserver;
82import android.net.Uri;
83import android.os.PowerSaveState;
84import android.os.Binder;
85import android.os.Build;
86import android.os.Bundle;
87import android.os.Environment;
88import android.os.Environment.UserEnvironment;
89import android.os.Handler;
90import android.os.HandlerThread;
91import android.os.IBinder;
92import android.os.Looper;
93import android.os.Message;
94import android.os.ParcelFileDescriptor;
95import android.os.PowerManager;
96import android.os.Process;
97import android.os.RemoteException;
98import android.os.SELinux;
99import android.os.ServiceManager;
100import android.os.SystemClock;
101import android.os.UserHandle;
102import android.os.WorkSource;
103import android.os.storage.IStorageManager;
104import android.os.storage.StorageManager;
105import android.provider.Settings;
106import android.system.ErrnoException;
107import android.system.Os;
108import android.text.TextUtils;
109import android.util.AtomicFile;
110import android.util.EventLog;
111import android.util.Log;
112import android.util.Pair;
113import android.util.Slog;
114import android.util.SparseArray;
115import android.util.StringBuilderPrinter;
116
117import com.android.internal.annotations.GuardedBy;
118import com.android.internal.backup.IBackupTransport;
119import com.android.internal.backup.IObbBackupService;
120import com.android.internal.util.DumpUtils;
121import com.android.server.AppWidgetBackupBridge;
122import com.android.server.EventLogTags;
123import com.android.server.SystemConfig;
124import com.android.server.SystemService;
125import com.android.server.backup.PackageManagerBackupAgent.Metadata;
126
127import com.android.server.power.BatterySaverPolicy.ServiceType;
128import libcore.io.IoUtils;
129
130import java.io.BufferedInputStream;
131import java.io.BufferedOutputStream;
132import java.io.ByteArrayInputStream;
133import java.io.ByteArrayOutputStream;
134import java.io.DataInputStream;
135import java.io.DataOutputStream;
136import java.io.EOFException;
137import java.io.File;
138import java.io.FileDescriptor;
139import java.io.FileInputStream;
140import java.io.FileNotFoundException;
141import java.io.FileOutputStream;
142import java.io.IOException;
143import java.io.InputStream;
144import java.io.OutputStream;
145import java.io.PrintWriter;
146import java.io.RandomAccessFile;
147import java.security.InvalidAlgorithmParameterException;
148import java.security.InvalidKeyException;
149import java.security.Key;
150import java.security.MessageDigest;
151import java.security.NoSuchAlgorithmException;
152import java.security.SecureRandom;
153import java.security.spec.InvalidKeySpecException;
154import java.security.spec.KeySpec;
155import java.text.SimpleDateFormat;
156import java.util.ArrayDeque;
157import java.util.ArrayList;
158import java.util.Arrays;
159import java.util.Collections;
160import java.util.Date;
161import java.util.HashMap;
162import java.util.HashSet;
163import java.util.Iterator;
164import java.util.List;
165import java.util.Map.Entry;
166import java.util.Objects;
167import java.util.Queue;
168import java.util.Random;
169import java.util.Set;
170import java.util.TreeMap;
171import java.util.concurrent.CountDownLatch;
172import java.util.concurrent.TimeUnit;
173import java.util.concurrent.atomic.AtomicBoolean;
174import java.util.concurrent.atomic.AtomicInteger;
175import java.util.concurrent.atomic.AtomicLong;
176import java.util.zip.Deflater;
177import java.util.zip.DeflaterOutputStream;
178import java.util.zip.InflaterInputStream;
179
180import javax.crypto.BadPaddingException;
181import javax.crypto.Cipher;
182import javax.crypto.CipherInputStream;
183import javax.crypto.CipherOutputStream;
184import javax.crypto.IllegalBlockSizeException;
185import javax.crypto.NoSuchPaddingException;
186import javax.crypto.SecretKey;
187import javax.crypto.SecretKeyFactory;
188import javax.crypto.spec.IvParameterSpec;
189import javax.crypto.spec.PBEKeySpec;
190import javax.crypto.spec.SecretKeySpec;
191
192public class BackupManagerService implements BackupManagerServiceInterface {
193
194    private static final String TAG = "BackupManagerService";
195    static final boolean DEBUG = true;
196    static final boolean MORE_DEBUG = false;
197    static final boolean DEBUG_SCHEDULING = MORE_DEBUG || true;
198
199    // File containing backup-enabled state.  Contains a single byte;
200    // nonzero == enabled.  File missing or contains a zero byte == disabled.
201    static final String BACKUP_ENABLE_FILE = "backup_enabled";
202
203    // System-private key used for backing up an app's widget state.  Must
204    // begin with U+FFxx by convention (we reserve all keys starting
205    // with U+FF00 or higher for system use).
206    static final String KEY_WIDGET_STATE = "\uffed\uffedwidget";
207
208    // Historical and current algorithm names
209    static final String PBKDF_CURRENT = "PBKDF2WithHmacSHA1";
210    static final String PBKDF_FALLBACK = "PBKDF2WithHmacSHA1And8bit";
211
212    // Name and current contents version of the full-backup manifest file
213    //
214    // Manifest version history:
215    //
216    // 1 : initial release
217    static final String BACKUP_MANIFEST_FILENAME = "_manifest";
218    static final int BACKUP_MANIFEST_VERSION = 1;
219
220    // External archive format version history:
221    //
222    // 1 : initial release
223    // 2 : no format change per se; version bump to facilitate PBKDF2 version skew detection
224    // 3 : introduced "_meta" metadata file; no other format change per se
225    // 4 : added support for new device-encrypted storage locations
226    // 5 : added support for key-value packages
227    static final int BACKUP_FILE_VERSION = 5;
228    static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
229    static final int BACKUP_PW_FILE_VERSION = 2;
230    static final String BACKUP_METADATA_FILENAME = "_meta";
231    static final int BACKUP_METADATA_VERSION = 1;
232    static final int BACKUP_WIDGET_METADATA_TOKEN = 0x01FFED01;
233
234    static final int TAR_HEADER_LONG_RADIX = 8;
235    static final int TAR_HEADER_OFFSET_FILESIZE = 124;
236    static final int TAR_HEADER_LENGTH_FILESIZE = 12;
237    static final int TAR_HEADER_OFFSET_MODTIME = 136;
238    static final int TAR_HEADER_LENGTH_MODTIME = 12;
239    static final int TAR_HEADER_OFFSET_MODE = 100;
240    static final int TAR_HEADER_LENGTH_MODE = 8;
241    static final int TAR_HEADER_OFFSET_PATH_PREFIX = 345;
242    static final int TAR_HEADER_LENGTH_PATH_PREFIX = 155;
243    static final int TAR_HEADER_OFFSET_PATH = 0;
244    static final int TAR_HEADER_LENGTH_PATH = 100;
245    static final int TAR_HEADER_OFFSET_TYPE_CHAR = 156;
246
247    static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
248
249    static final String SETTINGS_PACKAGE = "com.android.providers.settings";
250    static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
251    static final String SERVICE_ACTION_TRANSPORT_HOST = "android.backup.TRANSPORT_HOST";
252
253    // Retry interval for clear/init when the transport is unavailable
254    private static final long TRANSPORT_RETRY_INTERVAL = 1 * AlarmManager.INTERVAL_HOUR;
255
256    private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
257    private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
258    private static final int MSG_RUN_BACKUP = 1;
259    private static final int MSG_RUN_ADB_BACKUP = 2;
260    private static final int MSG_RUN_RESTORE = 3;
261    private static final int MSG_RUN_CLEAR = 4;
262    private static final int MSG_RUN_INITIALIZE = 5;
263    private static final int MSG_RUN_GET_RESTORE_SETS = 6;
264    private static final int MSG_RESTORE_SESSION_TIMEOUT = 8;
265    private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
266    private static final int MSG_RUN_ADB_RESTORE = 10;
267    private static final int MSG_RETRY_INIT = 11;
268    private static final int MSG_RETRY_CLEAR = 12;
269    private static final int MSG_WIDGET_BROADCAST = 13;
270    private static final int MSG_RUN_FULL_TRANSPORT_BACKUP = 14;
271    private static final int MSG_REQUEST_BACKUP = 15;
272    private static final int MSG_SCHEDULE_BACKUP_PACKAGE = 16;
273    private static final int MSG_BACKUP_OPERATION_TIMEOUT = 17;
274    private static final int MSG_RESTORE_OPERATION_TIMEOUT = 18;
275
276    // backup task state machine tick
277    static final int MSG_BACKUP_RESTORE_STEP = 20;
278    static final int MSG_OP_COMPLETE = 21;
279
280    // Timeout interval for deciding that a bind or clear-data has taken too long
281    static final long TIMEOUT_INTERVAL = 10 * 1000;
282
283    // Timeout intervals for agent backup & restore operations
284    static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
285    static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
286    static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
287    static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
288    static final long TIMEOUT_RESTORE_FINISHED_INTERVAL = 30 * 1000;
289
290    // User confirmation timeout for a full backup/restore operation.  It's this long in
291    // order to give them time to enter the backup password.
292    static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
293
294    // How long between attempts to perform a full-data backup of any given app
295    static final long MIN_FULL_BACKUP_INTERVAL = 1000 * 60 * 60 * 24; // one day
296
297    // If an app is busy when we want to do a full-data backup, how long to defer the retry.
298    // This is fuzzed, so there are two parameters; backoff_min + Rand[0, backoff_fuzz)
299    static final long BUSY_BACKOFF_MIN_MILLIS = 1000 * 60 * 60;  // one hour
300    static final int BUSY_BACKOFF_FUZZ = 1000 * 60 * 60 * 2;  // two hours
301
302    Context mContext;
303    private PackageManager mPackageManager;
304    IPackageManager mPackageManagerBinder;
305    private IActivityManager mActivityManager;
306    private PowerManager mPowerManager;
307    private AlarmManager mAlarmManager;
308    private IStorageManager mStorageManager;
309
310    IBackupManager mBackupManagerBinder;
311
312    private final TransportManager mTransportManager;
313
314    boolean mEnabled;   // access to this is synchronized on 'this'
315    boolean mProvisioned;
316    boolean mAutoRestore;
317    PowerManager.WakeLock mWakelock;
318    HandlerThread mHandlerThread;
319    BackupHandler mBackupHandler;
320    PendingIntent mRunBackupIntent, mRunInitIntent;
321    BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
322    // map UIDs to the set of participating packages under that UID
323    final SparseArray<HashSet<String>> mBackupParticipants
324            = new SparseArray<HashSet<String>>();
325    // set of backup services that have pending changes
326    class BackupRequest {
327        public String packageName;
328
329        BackupRequest(String pkgName) {
330            packageName = pkgName;
331        }
332
333        public String toString() {
334            return "BackupRequest{pkg=" + packageName + "}";
335        }
336    }
337    // Backups that we haven't started yet.  Keys are package names.
338    HashMap<String,BackupRequest> mPendingBackups
339            = new HashMap<String,BackupRequest>();
340
341    // Pseudoname that we use for the Package Manager metadata "package"
342    static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
343
344    // locking around the pending-backup management
345    final Object mQueueLock = new Object();
346
347    // The thread performing the sequence of queued backups binds to each app's agent
348    // in succession.  Bind notifications are asynchronously delivered through the
349    // Activity Manager; use this lock object to signal when a requested binding has
350    // completed.
351    final Object mAgentConnectLock = new Object();
352    IBackupAgent mConnectedAgent;
353    volatile boolean mBackupRunning;
354    volatile boolean mConnecting;
355    volatile long mLastBackupPass;
356
357    // For debugging, we maintain a progress trace of operations during backup
358    static final boolean DEBUG_BACKUP_TRACE = true;
359    final List<String> mBackupTrace = new ArrayList<String>();
360
361    // A similar synchronization mechanism around clearing apps' data for restore
362    final Object mClearDataLock = new Object();
363    volatile boolean mClearingData;
364
365    @GuardedBy("mPendingRestores")
366    private boolean mIsRestoreInProgress;
367    @GuardedBy("mPendingRestores")
368    private final Queue<PerformUnifiedRestoreTask> mPendingRestores = new ArrayDeque<>();
369
370    ActiveRestoreSession mActiveRestoreSession;
371
372    // Watch the device provisioning operation during setup
373    ContentObserver mProvisionedObserver;
374
375    // The published binder is actually to a singleton trampoline object that calls
376    // through to the proper code.  This indirection lets us turn down the heavy
377    // implementation object on the fly without disturbing binders that have been
378    // cached elsewhere in the system.
379    static Trampoline sInstance;
380    static Trampoline getInstance() {
381        // Always constructed during system bringup, so no need to lazy-init
382        return sInstance;
383    }
384
385    public static final class Lifecycle extends SystemService {
386
387        public Lifecycle(Context context) {
388            super(context);
389            sInstance = new Trampoline(context);
390        }
391
392        @Override
393        public void onStart() {
394            publishBinderService(Context.BACKUP_SERVICE, sInstance);
395        }
396
397        @Override
398        public void onUnlockUser(int userId) {
399            if (userId == UserHandle.USER_SYSTEM) {
400                sInstance.initialize(userId);
401
402                // Migrate legacy setting
403                if (!backupSettingMigrated(userId)) {
404                    if (DEBUG) {
405                        Slog.i(TAG, "Backup enable apparently not migrated");
406                    }
407                    final ContentResolver r = sInstance.mContext.getContentResolver();
408                    final int enableState = Settings.Secure.getIntForUser(r,
409                            Settings.Secure.BACKUP_ENABLED, -1, userId);
410                    if (enableState >= 0) {
411                        if (DEBUG) {
412                            Slog.i(TAG, "Migrating enable state " + (enableState != 0));
413                        }
414                        writeBackupEnableState(enableState != 0, userId);
415                        Settings.Secure.putStringForUser(r,
416                                Settings.Secure.BACKUP_ENABLED, null, userId);
417                    } else {
418                        if (DEBUG) {
419                            Slog.i(TAG, "Backup not yet configured; retaining null enable state");
420                        }
421                    }
422                }
423
424                try {
425                    sInstance.setBackupEnabled(readBackupEnableState(userId));
426                } catch (RemoteException e) {
427                    // can't happen; it's a local object
428                }
429            }
430        }
431    }
432
433    class ProvisionedObserver extends ContentObserver {
434        public ProvisionedObserver(Handler handler) {
435            super(handler);
436        }
437
438        public void onChange(boolean selfChange) {
439            final boolean wasProvisioned = mProvisioned;
440            final boolean isProvisioned = deviceIsProvisioned();
441            // latch: never unprovision
442            mProvisioned = wasProvisioned || isProvisioned;
443            if (MORE_DEBUG) {
444                Slog.d(TAG, "Provisioning change: was=" + wasProvisioned
445                        + " is=" + isProvisioned + " now=" + mProvisioned);
446            }
447
448            synchronized (mQueueLock) {
449                if (mProvisioned && !wasProvisioned && mEnabled) {
450                    // we're now good to go, so start the backup alarms
451                    if (MORE_DEBUG) Slog.d(TAG, "Now provisioned, so starting backups");
452                    KeyValueBackupJob.schedule(mContext);
453                    scheduleNextFullBackupJob(0);
454                }
455            }
456        }
457    }
458
459    class RestoreGetSetsParams {
460        public IBackupTransport transport;
461        public ActiveRestoreSession session;
462        public IRestoreObserver observer;
463        public IBackupManagerMonitor monitor;
464
465        RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
466                IRestoreObserver _observer, IBackupManagerMonitor _monitor) {
467            transport = _transport;
468            session = _session;
469            observer = _observer;
470            monitor = _monitor;
471        }
472    }
473
474    class RestoreParams {
475        public IBackupTransport transport;
476        public String dirName;
477        public IRestoreObserver observer;
478        public IBackupManagerMonitor monitor;
479        public long token;
480        public PackageInfo pkgInfo;
481        public int pmToken; // in post-install restore, the PM's token for this transaction
482        public boolean isSystemRestore;
483        public String[] filterSet;
484
485        /**
486         * Restore a single package; no kill after restore
487         */
488        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
489                IBackupManagerMonitor _monitor, long _token, PackageInfo _pkg) {
490            transport = _transport;
491            dirName = _dirName;
492            observer = _obs;
493            monitor = _monitor;
494            token = _token;
495            pkgInfo = _pkg;
496            pmToken = 0;
497            isSystemRestore = false;
498            filterSet = null;
499        }
500
501        /**
502         * Restore at install: PM token needed, kill after restore
503         */
504        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
505                IBackupManagerMonitor _monitor, long _token, String _pkgName, int _pmToken) {
506            transport = _transport;
507            dirName = _dirName;
508            observer = _obs;
509            monitor = _monitor;
510            token = _token;
511            pkgInfo = null;
512            pmToken = _pmToken;
513            isSystemRestore = false;
514            filterSet = new String[] { _pkgName };
515        }
516
517        /**
518         * Restore everything possible.  This is the form that Setup Wizard or similar
519         * restore UXes use.
520         */
521        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
522                IBackupManagerMonitor _monitor, long _token) {
523            transport = _transport;
524            dirName = _dirName;
525            observer = _obs;
526            monitor = _monitor;
527            token = _token;
528            pkgInfo = null;
529            pmToken = 0;
530            isSystemRestore = true;
531            filterSet = null;
532        }
533
534        /**
535         * Restore some set of packages.  Leave this one up to the caller to specify
536         * whether it's to be considered a system-level restore.
537         */
538        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
539                IBackupManagerMonitor _monitor, long _token,
540                String[] _filterSet, boolean _isSystemRestore) {
541            transport = _transport;
542            dirName = _dirName;
543            observer = _obs;
544            monitor = _monitor;
545            token = _token;
546            pkgInfo = null;
547            pmToken = 0;
548            isSystemRestore = _isSystemRestore;
549            filterSet = _filterSet;
550        }
551    }
552
553    class ClearParams {
554        public IBackupTransport transport;
555        public PackageInfo packageInfo;
556
557        ClearParams(IBackupTransport _transport, PackageInfo _info) {
558            transport = _transport;
559            packageInfo = _info;
560        }
561    }
562
563    class ClearRetryParams {
564        public String transportName;
565        public String packageName;
566
567        ClearRetryParams(String transport, String pkg) {
568            transportName = transport;
569            packageName = pkg;
570        }
571    }
572
573    // Parameters used by adbBackup() and adbRestore()
574    class AdbParams {
575        public ParcelFileDescriptor fd;
576        public final AtomicBoolean latch;
577        public IFullBackupRestoreObserver observer;
578        public String curPassword;     // filled in by the confirmation step
579        public String encryptPassword;
580
581        AdbParams() {
582            latch = new AtomicBoolean(false);
583        }
584    }
585
586    class AdbBackupParams extends AdbParams {
587        public boolean includeApks;
588        public boolean includeObbs;
589        public boolean includeShared;
590        public boolean doWidgets;
591        public boolean allApps;
592        public boolean includeSystem;
593        public boolean doCompress;
594        public boolean includeKeyValue;
595        public String[] packages;
596
597        AdbBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveObbs,
598                boolean saveShared, boolean alsoWidgets, boolean doAllApps, boolean doSystem,
599                boolean compress, boolean doKeyValue, String[] pkgList) {
600            fd = output;
601            includeApks = saveApks;
602            includeObbs = saveObbs;
603            includeShared = saveShared;
604            doWidgets = alsoWidgets;
605            allApps = doAllApps;
606            includeSystem = doSystem;
607            doCompress = compress;
608            includeKeyValue = doKeyValue;
609            packages = pkgList;
610        }
611    }
612
613    class AdbRestoreParams extends AdbParams {
614        AdbRestoreParams(ParcelFileDescriptor input) {
615            fd = input;
616        }
617    }
618
619    class BackupParams {
620        public IBackupTransport transport;
621        public String dirName;
622        public ArrayList<String> kvPackages;
623        public ArrayList<String> fullPackages;
624        public IBackupObserver observer;
625        public IBackupManagerMonitor monitor;
626        public boolean userInitiated;
627        public boolean nonIncrementalBackup;
628
629        BackupParams(IBackupTransport transport, String dirName, ArrayList<String> kvPackages,
630                ArrayList<String> fullPackages, IBackupObserver observer,
631                IBackupManagerMonitor monitor,boolean userInitiated, boolean nonIncrementalBackup) {
632            this.transport = transport;
633            this.dirName = dirName;
634            this.kvPackages = kvPackages;
635            this.fullPackages = fullPackages;
636            this.observer = observer;
637            this.monitor = monitor;
638            this.userInitiated = userInitiated;
639            this.nonIncrementalBackup = nonIncrementalBackup;
640        }
641    }
642
643    // Bookkeeping of in-flight operations for timeout etc. purposes.  The operation
644    // token is the index of the entry in the pending-operations list.
645    static final int OP_PENDING = 0;
646    static final int OP_ACKNOWLEDGED = 1;
647    static final int OP_TIMEOUT = -1;
648
649    // Waiting for backup agent to respond during backup operation.
650    static final int OP_TYPE_BACKUP_WAIT = 0;
651
652    // Waiting for backup agent to respond during restore operation.
653    static final int OP_TYPE_RESTORE_WAIT = 1;
654
655    // An entire backup operation spanning multiple packages.
656    private static final int OP_TYPE_BACKUP = 2;
657
658    class Operation {
659        int state;
660        final BackupRestoreTask callback;
661        final int type;
662
663        Operation(int initialState, BackupRestoreTask callbackObj, int type) {
664            state = initialState;
665            callback = callbackObj;
666            this.type = type;
667        }
668    }
669
670    /**
671     * mCurrentOperations contains the list of currently active operations.
672     *
673     * If type of operation is OP_TYPE_WAIT, it are waiting for an ack or timeout.
674     * An operation wraps a BackupRestoreTask within it.
675     * It's the responsibility of this task to remove the operation from this array.
676     *
677     * A BackupRestore task gets notified of ack/timeout for the operation via
678     * BackupRestoreTask#handleCancel, BackupRestoreTask#operationComplete and notifyAll called
679     * on the mCurrentOpLock. {@link BackupManagerService#waitUntilOperationComplete(int)} is
680     * used in various places to 'wait' for notifyAll and detect change of pending state of an
681     * operation. So typically, an operation will be removed from this array by:
682     *   - BackupRestoreTask#handleCancel and
683     *   - BackupRestoreTask#operationComplete OR waitUntilOperationComplete. Do not remove at both
684     *     these places because waitUntilOperationComplete relies on the operation being present to
685     *     determine its completion status.
686     *
687     * If type of operation is OP_BACKUP, it is a task running backups. It provides a handle to
688     * cancel backup tasks.
689     */
690    @GuardedBy("mCurrentOpLock")
691    final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
692    final Object mCurrentOpLock = new Object();
693    final Random mTokenGenerator = new Random();
694
695    final SparseArray<AdbParams> mAdbBackupRestoreConfirmations = new SparseArray<AdbParams>();
696
697    // Where we keep our journal files and other bookkeeping
698    File mBaseStateDir;
699    File mDataDir;
700    File mJournalDir;
701    File mJournal;
702
703    // Backup password, if any, and the file where it's saved.  What is stored is not the
704    // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
705    // persisted) salt.  Validation is performed by running the challenge text through the
706    // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
707    // the saved hash string, then the challenge text matches the originally supplied
708    // password text.
709    private final SecureRandom mRng = new SecureRandom();
710    private String mPasswordHash;
711    private File mPasswordHashFile;
712    private int mPasswordVersion;
713    private File mPasswordVersionFile;
714    private byte[] mPasswordSalt;
715
716    // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
717    static final int PBKDF2_HASH_ROUNDS = 10000;
718    static final int PBKDF2_KEY_SIZE = 256;     // bits
719    static final int PBKDF2_SALT_SIZE = 512;    // bits
720    static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
721
722    // Keep a log of all the apps we've ever backed up, and what the
723    // dataset tokens are for both the current backup dataset and
724    // the ancestral dataset.
725    private File mEverStored;
726    HashSet<String> mEverStoredApps = new HashSet<String>();
727
728    static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1;  // increment when the schema changes
729    File mTokenFile;
730    Set<String> mAncestralPackages = null;
731    long mAncestralToken = 0;
732    long mCurrentToken = 0;
733
734    // Persistently track the need to do a full init
735    static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
736    HashSet<String> mPendingInits = new HashSet<String>();  // transport names
737
738    // Round-robin queue for scheduling full backup passes
739    static final int SCHEDULE_FILE_VERSION = 1; // current version of the schedule file
740    class FullBackupEntry implements Comparable<FullBackupEntry> {
741        String packageName;
742        long lastBackup;
743
744        FullBackupEntry(String pkg, long when) {
745            packageName = pkg;
746            lastBackup = when;
747        }
748
749        @Override
750        public int compareTo(FullBackupEntry other) {
751            if (lastBackup < other.lastBackup) return -1;
752            else if (lastBackup > other.lastBackup) return 1;
753            else return 0;
754        }
755    }
756
757    File mFullBackupScheduleFile;
758    // If we're running a schedule-driven full backup, this is the task instance doing it
759
760    @GuardedBy("mQueueLock")
761    PerformFullTransportBackupTask mRunningFullBackupTask;
762
763    @GuardedBy("mQueueLock")
764    ArrayList<FullBackupEntry> mFullBackupQueue;
765
766    // Utility: build a new random integer token
767    @Override
768    public int generateRandomIntegerToken() {
769        int token;
770        do {
771            synchronized (mTokenGenerator) {
772                token = mTokenGenerator.nextInt();
773            }
774        } while (token < 0);
775        return token;
776    }
777
778    // High level policy: apps are generally ineligible for backup if certain conditions apply
779    public static boolean appIsEligibleForBackup(ApplicationInfo app, PackageManager pm) {
780        // 1. their manifest states android:allowBackup="false"
781        if ((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
782            return false;
783        }
784
785        // 2. they run as a system-level uid but do not supply their own backup agent
786        if ((app.uid < Process.FIRST_APPLICATION_UID) && (app.backupAgentName == null)) {
787            return false;
788        }
789
790        // 3. it is the special shared-storage backup package used for 'adb backup'
791        if (app.packageName.equals(BackupManagerService.SHARED_BACKUP_AGENT_PACKAGE)) {
792            return false;
793        }
794
795        // 4. it is an "instant" app
796        if (app.isInstantApp()) {
797            return false;
798        }
799
800        // Everything else checks out; the only remaining roadblock would be if the
801        // package were disabled
802        return !appIsDisabled(app, pm);
803    }
804
805    // Checks if the app is in a stopped state.  This is not part of the general "eligible for
806    // backup?" check because we *do* still need to restore data to apps in this state (e.g.
807    // newly-installing ones)
808    private static boolean appIsStopped(ApplicationInfo app) {
809        return ((app.flags & ApplicationInfo.FLAG_STOPPED) != 0);
810    }
811
812    private static boolean appIsDisabled(ApplicationInfo app, PackageManager pm) {
813        switch (pm.getApplicationEnabledSetting(app.packageName)) {
814            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED:
815            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER:
816            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED:
817                return true;
818
819            default:
820                return false;
821        }
822    }
823
824    /* does *not* check overall backup eligibility policy! */
825    private static boolean appGetsFullBackup(PackageInfo pkg) {
826        if (pkg.applicationInfo.backupAgentName != null) {
827            // If it has an agent, it gets full backups only if it says so
828            return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FULL_BACKUP_ONLY) != 0;
829        }
830
831        // No agent or fullBackupOnly="true" means we do indeed perform full-data backups for it
832        return true;
833    }
834
835    /* adb backup: is this app only capable of doing key/value?  We say otherwise if
836     * the app has a backup agent and does not say fullBackupOnly,
837     */
838    private static boolean appIsKeyValueOnly(PackageInfo pkg) {
839        return !appGetsFullBackup(pkg);
840    }
841
842    /*
843     * Construct a backup agent instance for the metadata pseudopackage.  This is a
844     * process-local non-lifecycle agent instance, so we manually set up the context
845     * topology for it.
846     */
847    PackageManagerBackupAgent makeMetadataAgent() {
848        PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(mPackageManager);
849        pmAgent.attach(mContext);
850        pmAgent.onCreate();
851        return pmAgent;
852    }
853
854    /*
855     * Same as above but with the explicit package-set configuration.
856     */
857    PackageManagerBackupAgent makeMetadataAgent(List<PackageInfo> packages) {
858        PackageManagerBackupAgent pmAgent =
859                new PackageManagerBackupAgent(mPackageManager, packages);
860        pmAgent.attach(mContext);
861        pmAgent.onCreate();
862        return pmAgent;
863    }
864
865    // ----- Asynchronous backup/restore handler thread -----
866
867    private class BackupHandler extends Handler {
868        public BackupHandler(Looper looper) {
869            super(looper);
870        }
871
872        public void handleMessage(Message msg) {
873
874            switch (msg.what) {
875            case MSG_RUN_BACKUP:
876            {
877                mLastBackupPass = System.currentTimeMillis();
878
879                IBackupTransport transport = mTransportManager.getCurrentTransportBinder();
880                if (transport == null) {
881                    Slog.v(TAG, "Backup requested but no transport available");
882                    synchronized (mQueueLock) {
883                        mBackupRunning = false;
884                    }
885                    mWakelock.release();
886                    break;
887                }
888
889                // snapshot the pending-backup set and work on that
890                ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
891                File oldJournal = mJournal;
892                synchronized (mQueueLock) {
893                    // Do we have any work to do?  Construct the work queue
894                    // then release the synchronization lock to actually run
895                    // the backup.
896                    if (mPendingBackups.size() > 0) {
897                        for (BackupRequest b: mPendingBackups.values()) {
898                            queue.add(b);
899                        }
900                        if (DEBUG) Slog.v(TAG, "clearing pending backups");
901                        mPendingBackups.clear();
902
903                        // Start a new backup-queue journal file too
904                        mJournal = null;
905
906                    }
907                }
908
909                // At this point, we have started a new journal file, and the old
910                // file identity is being passed to the backup processing task.
911                // When it completes successfully, that old journal file will be
912                // deleted.  If we crash prior to that, the old journal is parsed
913                // at next boot and the journaled requests fulfilled.
914                boolean staged = true;
915                if (queue.size() > 0) {
916                    // Spin up a backup state sequence and set it running
917                    try {
918                        String dirName = transport.transportDirName();
919                        PerformBackupTask pbt = new PerformBackupTask(transport, dirName, queue,
920                                oldJournal, null, null, Collections.<String>emptyList(), false,
921                                false /* nonIncremental */);
922                        Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
923                        sendMessage(pbtMessage);
924                    } catch (Exception e) {
925                        // unable to ask the transport its dir name -- transient failure, since
926                        // the above check succeeded.  Try again next time.
927                        Slog.e(TAG, "Transport became unavailable attempting backup"
928                                + " or error initializing backup task", e);
929                        staged = false;
930                    }
931                } else {
932                    Slog.v(TAG, "Backup requested but nothing pending");
933                    staged = false;
934                }
935
936                if (!staged) {
937                    // if we didn't actually hand off the wakelock, rewind until next time
938                    synchronized (mQueueLock) {
939                        mBackupRunning = false;
940                    }
941                    mWakelock.release();
942                }
943                break;
944            }
945
946            case MSG_BACKUP_RESTORE_STEP:
947            {
948                try {
949                    BackupRestoreTask task = (BackupRestoreTask) msg.obj;
950                    if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
951                    task.execute();
952                } catch (ClassCastException e) {
953                    Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
954                }
955                break;
956            }
957
958            case MSG_OP_COMPLETE:
959            {
960                try {
961                    Pair<BackupRestoreTask, Long> taskWithResult =
962                            (Pair<BackupRestoreTask, Long>) msg.obj;
963                    taskWithResult.first.operationComplete(taskWithResult.second);
964                } catch (ClassCastException e) {
965                    Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
966                }
967                break;
968            }
969
970            case MSG_RUN_ADB_BACKUP:
971            {
972                // TODO: refactor full backup to be a looper-based state machine
973                // similar to normal backup/restore.
974                AdbBackupParams params = (AdbBackupParams)msg.obj;
975                PerformAdbBackupTask task = new PerformAdbBackupTask(params.fd,
976                        params.observer, params.includeApks, params.includeObbs,
977                        params.includeShared, params.doWidgets, params.curPassword,
978                        params.encryptPassword, params.allApps, params.includeSystem,
979                        params.doCompress, params.includeKeyValue, params.packages, params.latch);
980                (new Thread(task, "adb-backup")).start();
981                break;
982            }
983
984            case MSG_RUN_FULL_TRANSPORT_BACKUP:
985            {
986                PerformFullTransportBackupTask task = (PerformFullTransportBackupTask) msg.obj;
987                (new Thread(task, "transport-backup")).start();
988                break;
989            }
990
991            case MSG_RUN_RESTORE:
992            {
993                RestoreParams params = (RestoreParams)msg.obj;
994                Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
995
996                PerformUnifiedRestoreTask task = new PerformUnifiedRestoreTask(params.transport,
997                        params.observer, params.monitor, params.token, params.pkgInfo,
998                        params.pmToken, params.isSystemRestore, params.filterSet);
999
1000                synchronized (mPendingRestores) {
1001                    if (mIsRestoreInProgress) {
1002                        if (DEBUG) {
1003                            Slog.d(TAG, "Restore in progress, queueing.");
1004                        }
1005                        mPendingRestores.add(task);
1006                        // This task will be picked up and executed when the the currently running
1007                        // restore task finishes.
1008                    } else {
1009                        if (DEBUG) {
1010                            Slog.d(TAG, "Starting restore.");
1011                        }
1012                        mIsRestoreInProgress = true;
1013                        Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
1014                        sendMessage(restoreMsg);
1015                    }
1016                }
1017                break;
1018            }
1019
1020            case MSG_RUN_ADB_RESTORE:
1021            {
1022                // TODO: refactor full restore to be a looper-based state machine
1023                // similar to normal backup/restore.
1024                AdbRestoreParams params = (AdbRestoreParams)msg.obj;
1025                PerformAdbRestoreTask task = new PerformAdbRestoreTask(params.fd,
1026                        params.curPassword, params.encryptPassword,
1027                        params.observer, params.latch);
1028                (new Thread(task, "adb-restore")).start();
1029                break;
1030            }
1031
1032            case MSG_RUN_CLEAR:
1033            {
1034                ClearParams params = (ClearParams)msg.obj;
1035                (new PerformClearTask(params.transport, params.packageInfo)).run();
1036                break;
1037            }
1038
1039            case MSG_RETRY_CLEAR:
1040            {
1041                // reenqueues if the transport remains unavailable
1042                ClearRetryParams params = (ClearRetryParams)msg.obj;
1043                clearBackupData(params.transportName, params.packageName);
1044                break;
1045            }
1046
1047            case MSG_RUN_INITIALIZE:
1048            {
1049                HashSet<String> queue;
1050
1051                // Snapshot the pending-init queue and work on that
1052                synchronized (mQueueLock) {
1053                    queue = new HashSet<String>(mPendingInits);
1054                    mPendingInits.clear();
1055                }
1056
1057                (new PerformInitializeTask(queue)).run();
1058                break;
1059            }
1060
1061            case MSG_RETRY_INIT:
1062            {
1063                synchronized (mQueueLock) {
1064                    recordInitPendingLocked(msg.arg1 != 0, (String)msg.obj);
1065                    mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1066                            mRunInitIntent);
1067                }
1068                break;
1069            }
1070
1071            case MSG_RUN_GET_RESTORE_SETS:
1072            {
1073                // Like other async operations, this is entered with the wakelock held
1074                RestoreSet[] sets = null;
1075                RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
1076                try {
1077                    sets = params.transport.getAvailableRestoreSets();
1078                    // cache the result in the active session
1079                    synchronized (params.session) {
1080                        params.session.mRestoreSets = sets;
1081                    }
1082                    if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
1083                } catch (Exception e) {
1084                    Slog.e(TAG, "Error from transport getting set list: " + e.getMessage());
1085                } finally {
1086                    if (params.observer != null) {
1087                        try {
1088                            params.observer.restoreSetsAvailable(sets);
1089                        } catch (RemoteException re) {
1090                            Slog.e(TAG, "Unable to report listing to observer");
1091                        } catch (Exception e) {
1092                            Slog.e(TAG, "Restore observer threw: " + e.getMessage());
1093                        }
1094                    }
1095
1096                    // Done: reset the session timeout clock
1097                    removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
1098                    sendEmptyMessageDelayed(MSG_RESTORE_SESSION_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
1099
1100                    mWakelock.release();
1101                }
1102                break;
1103            }
1104
1105            case MSG_BACKUP_OPERATION_TIMEOUT:
1106            case MSG_RESTORE_OPERATION_TIMEOUT:
1107            {
1108                Slog.d(TAG, "Timeout message received for token=" + Integer.toHexString(msg.arg1));
1109                handleCancel(msg.arg1, false);
1110                break;
1111            }
1112
1113            case MSG_RESTORE_SESSION_TIMEOUT:
1114            {
1115                synchronized (BackupManagerService.this) {
1116                    if (mActiveRestoreSession != null) {
1117                        // Client app left the restore session dangling.  We know that it
1118                        // can't be in the middle of an actual restore operation because
1119                        // the timeout is suspended while a restore is in progress.  Clean
1120                        // up now.
1121                        Slog.w(TAG, "Restore session timed out; aborting");
1122                        mActiveRestoreSession.markTimedOut();
1123                        post(mActiveRestoreSession.new EndRestoreRunnable(
1124                                BackupManagerService.this, mActiveRestoreSession));
1125                    }
1126                }
1127                break;
1128            }
1129
1130            case MSG_FULL_CONFIRMATION_TIMEOUT:
1131            {
1132                synchronized (mAdbBackupRestoreConfirmations) {
1133                    AdbParams params = mAdbBackupRestoreConfirmations.get(msg.arg1);
1134                    if (params != null) {
1135                        Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
1136
1137                        // Release the waiter; timeout == completion
1138                        signalAdbBackupRestoreCompletion(params);
1139
1140                        // Remove the token from the set
1141                        mAdbBackupRestoreConfirmations.delete(msg.arg1);
1142
1143                        // Report a timeout to the observer, if any
1144                        if (params.observer != null) {
1145                            try {
1146                                params.observer.onTimeout();
1147                            } catch (RemoteException e) {
1148                                /* don't care if the app has gone away */
1149                            }
1150                        }
1151                    } else {
1152                        Slog.d(TAG, "couldn't find params for token " + msg.arg1);
1153                    }
1154                }
1155                break;
1156            }
1157
1158            case MSG_WIDGET_BROADCAST:
1159            {
1160                final Intent intent = (Intent) msg.obj;
1161                mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
1162                break;
1163            }
1164
1165            case MSG_REQUEST_BACKUP:
1166            {
1167                BackupParams params = (BackupParams)msg.obj;
1168                if (MORE_DEBUG) {
1169                    Slog.d(TAG, "MSG_REQUEST_BACKUP observer=" + params.observer);
1170                }
1171                ArrayList<BackupRequest> kvQueue = new ArrayList<>();
1172                for (String packageName : params.kvPackages) {
1173                    kvQueue.add(new BackupRequest(packageName));
1174                }
1175                mBackupRunning = true;
1176                mWakelock.acquire();
1177
1178                PerformBackupTask pbt = new PerformBackupTask(params.transport, params.dirName,
1179                        kvQueue, null, params.observer, params.monitor, params.fullPackages, true,
1180                        params.nonIncrementalBackup);
1181                Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
1182                sendMessage(pbtMessage);
1183                break;
1184            }
1185
1186            case MSG_SCHEDULE_BACKUP_PACKAGE:
1187            {
1188                String pkgName = (String)msg.obj;
1189                if (MORE_DEBUG) {
1190                    Slog.d(TAG, "MSG_SCHEDULE_BACKUP_PACKAGE " + pkgName);
1191                }
1192                dataChangedImpl(pkgName);
1193                break;
1194            }
1195            }
1196        }
1197    }
1198
1199    // ----- Debug-only backup operation trace -----
1200    void addBackupTrace(String s) {
1201        if (DEBUG_BACKUP_TRACE) {
1202            synchronized (mBackupTrace) {
1203                mBackupTrace.add(s);
1204            }
1205        }
1206    }
1207
1208    void clearBackupTrace() {
1209        if (DEBUG_BACKUP_TRACE) {
1210            synchronized (mBackupTrace) {
1211                mBackupTrace.clear();
1212            }
1213        }
1214    }
1215
1216    // ----- Main service implementation -----
1217
1218    public BackupManagerService(Context context, Trampoline parent) {
1219        mContext = context;
1220        mPackageManager = context.getPackageManager();
1221        mPackageManagerBinder = AppGlobals.getPackageManager();
1222        mActivityManager = ActivityManager.getService();
1223
1224        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1225        mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
1226        mStorageManager = IStorageManager.Stub.asInterface(ServiceManager.getService("mount"));
1227
1228        mBackupManagerBinder = Trampoline.asInterface(parent.asBinder());
1229
1230        // spin up the backup/restore handler thread
1231        mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
1232        mHandlerThread.start();
1233        mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
1234
1235        // Set up our bookkeeping
1236        final ContentResolver resolver = context.getContentResolver();
1237        mProvisioned = Settings.Global.getInt(resolver,
1238                Settings.Global.DEVICE_PROVISIONED, 0) != 0;
1239        mAutoRestore = Settings.Secure.getInt(resolver,
1240                Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
1241
1242        mProvisionedObserver = new ProvisionedObserver(mBackupHandler);
1243        resolver.registerContentObserver(
1244                Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
1245                false, mProvisionedObserver);
1246
1247        // If Encrypted file systems is enabled or disabled, this call will return the
1248        // correct directory.
1249        mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
1250        mBaseStateDir.mkdirs();
1251        if (!SELinux.restorecon(mBaseStateDir)) {
1252            Slog.e(TAG, "SELinux restorecon failed on " + mBaseStateDir);
1253        }
1254
1255        // This dir on /cache is managed directly in init.rc
1256        mDataDir = new File(Environment.getDownloadCacheDirectory(), "backup_stage");
1257
1258        mPasswordVersion = 1;       // unless we hear otherwise
1259        mPasswordVersionFile = new File(mBaseStateDir, "pwversion");
1260        if (mPasswordVersionFile.exists()) {
1261            FileInputStream fin = null;
1262            DataInputStream in = null;
1263            try {
1264                fin = new FileInputStream(mPasswordVersionFile);
1265                in = new DataInputStream(fin);
1266                mPasswordVersion = in.readInt();
1267            } catch (IOException e) {
1268                Slog.e(TAG, "Unable to read backup pw version");
1269            } finally {
1270                try {
1271                    if (in != null) in.close();
1272                    if (fin != null) fin.close();
1273                } catch (IOException e) {
1274                    Slog.w(TAG, "Error closing pw version files");
1275                }
1276            }
1277        }
1278
1279        mPasswordHashFile = new File(mBaseStateDir, "pwhash");
1280        if (mPasswordHashFile.exists()) {
1281            FileInputStream fin = null;
1282            DataInputStream in = null;
1283            try {
1284                fin = new FileInputStream(mPasswordHashFile);
1285                in = new DataInputStream(new BufferedInputStream(fin));
1286                // integer length of the salt array, followed by the salt,
1287                // then the hex pw hash string
1288                int saltLen = in.readInt();
1289                byte[] salt = new byte[saltLen];
1290                in.readFully(salt);
1291                mPasswordHash = in.readUTF();
1292                mPasswordSalt = salt;
1293            } catch (IOException e) {
1294                Slog.e(TAG, "Unable to read saved backup pw hash");
1295            } finally {
1296                try {
1297                    if (in != null) in.close();
1298                    if (fin != null) fin.close();
1299                } catch (IOException e) {
1300                    Slog.w(TAG, "Unable to close streams");
1301                }
1302            }
1303        }
1304
1305        // Alarm receivers for scheduled backups & initialization operations
1306        mRunBackupReceiver = new RunBackupReceiver();
1307        IntentFilter filter = new IntentFilter();
1308        filter.addAction(RUN_BACKUP_ACTION);
1309        context.registerReceiver(mRunBackupReceiver, filter,
1310                android.Manifest.permission.BACKUP, null);
1311
1312        mRunInitReceiver = new RunInitializeReceiver();
1313        filter = new IntentFilter();
1314        filter.addAction(RUN_INITIALIZE_ACTION);
1315        context.registerReceiver(mRunInitReceiver, filter,
1316                android.Manifest.permission.BACKUP, null);
1317
1318        Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
1319        backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1320        mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
1321
1322        Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
1323        backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1324        mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
1325
1326        // Set up the backup-request journaling
1327        mJournalDir = new File(mBaseStateDir, "pending");
1328        mJournalDir.mkdirs();   // creates mBaseStateDir along the way
1329        mJournal = null;        // will be created on first use
1330
1331        // Set up the various sorts of package tracking we do
1332        mFullBackupScheduleFile = new File(mBaseStateDir, "fb-schedule");
1333        initPackageTracking();
1334
1335        // Build our mapping of uid to backup client services.  This implicitly
1336        // schedules a backup pass on the Package Manager metadata the first
1337        // time anything needs to be backed up.
1338        synchronized (mBackupParticipants) {
1339            addPackageParticipantsLocked(null);
1340        }
1341
1342        // Set up our transport options and initialize the default transport
1343        // TODO: Don't create transports that we don't need to?
1344        SystemConfig systemConfig = SystemConfig.getInstance();
1345        Set<ComponentName> transportWhitelist = systemConfig.getBackupTransportWhitelist();
1346
1347        String transport = Settings.Secure.getString(context.getContentResolver(),
1348                Settings.Secure.BACKUP_TRANSPORT);
1349        if (TextUtils.isEmpty(transport)) {
1350            transport = null;
1351        }
1352        String currentTransport = transport;
1353        if (DEBUG) Slog.v(TAG, "Starting with transport " + currentTransport);
1354
1355        mTransportManager = new TransportManager(context, transportWhitelist, currentTransport,
1356                mTransportBoundListener, mHandlerThread.getLooper());
1357        mTransportManager.registerAllTransports();
1358
1359        // Now that we know about valid backup participants, parse any
1360        // leftover journal files into the pending backup set
1361        mBackupHandler.post(() -> parseLeftoverJournals());
1362
1363        // Power management
1364        mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
1365    }
1366
1367    private class RunBackupReceiver extends BroadcastReceiver {
1368        public void onReceive(Context context, Intent intent) {
1369            if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
1370                synchronized (mQueueLock) {
1371                    if (mPendingInits.size() > 0) {
1372                        // If there are pending init operations, we process those
1373                        // and then settle into the usual periodic backup schedule.
1374                        if (MORE_DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
1375                        try {
1376                            mAlarmManager.cancel(mRunInitIntent);
1377                            mRunInitIntent.send();
1378                        } catch (PendingIntent.CanceledException ce) {
1379                            Slog.e(TAG, "Run init intent cancelled");
1380                            // can't really do more than bail here
1381                        }
1382                    } else {
1383                        // Don't run backups now if we're disabled or not yet
1384                        // fully set up.
1385                        if (mEnabled && mProvisioned) {
1386                            if (!mBackupRunning) {
1387                                if (DEBUG) Slog.v(TAG, "Running a backup pass");
1388
1389                                // Acquire the wakelock and pass it to the backup thread.  it will
1390                                // be released once backup concludes.
1391                                mBackupRunning = true;
1392                                mWakelock.acquire();
1393
1394                                Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
1395                                mBackupHandler.sendMessage(msg);
1396                            } else {
1397                                Slog.i(TAG, "Backup time but one already running");
1398                            }
1399                        } else {
1400                            Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
1401                        }
1402                    }
1403                }
1404            }
1405        }
1406    }
1407
1408    private class RunInitializeReceiver extends BroadcastReceiver {
1409        public void onReceive(Context context, Intent intent) {
1410            if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
1411                synchronized (mQueueLock) {
1412                    if (DEBUG) Slog.v(TAG, "Running a device init");
1413
1414                    // Acquire the wakelock and pass it to the init thread.  it will
1415                    // be released once init concludes.
1416                    mWakelock.acquire();
1417
1418                    Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
1419                    mBackupHandler.sendMessage(msg);
1420                }
1421            }
1422        }
1423    }
1424
1425    private void initPackageTracking() {
1426        if (MORE_DEBUG) Slog.v(TAG, "` tracking");
1427
1428        // Remember our ancestral dataset
1429        mTokenFile = new File(mBaseStateDir, "ancestral");
1430        try (DataInputStream tokenStream = new DataInputStream(new BufferedInputStream(
1431                new FileInputStream(mTokenFile)))) {
1432            int version = tokenStream.readInt();
1433            if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
1434                mAncestralToken = tokenStream.readLong();
1435                mCurrentToken = tokenStream.readLong();
1436
1437                int numPackages = tokenStream.readInt();
1438                if (numPackages >= 0) {
1439                    mAncestralPackages = new HashSet<>();
1440                    for (int i = 0; i < numPackages; i++) {
1441                        String pkgName = tokenStream.readUTF();
1442                        mAncestralPackages.add(pkgName);
1443                    }
1444                }
1445            }
1446        } catch (FileNotFoundException fnf) {
1447            // Probably innocuous
1448            Slog.v(TAG, "No ancestral data");
1449        } catch (IOException e) {
1450            Slog.w(TAG, "Unable to read token file", e);
1451        }
1452
1453        // Keep a log of what apps we've ever backed up.  Because we might have
1454        // rebooted in the middle of an operation that was removing something from
1455        // this log, we sanity-check its contents here and reconstruct it.
1456        mEverStored = new File(mBaseStateDir, "processed");
1457        File tempProcessedFile = new File(mBaseStateDir, "processed.new");
1458
1459        // If we were in the middle of removing something from the ever-backed-up
1460        // file, there might be a transient "processed.new" file still present.
1461        // Ignore it -- we'll validate "processed" against the current package set.
1462        if (tempProcessedFile.exists()) {
1463            tempProcessedFile.delete();
1464        }
1465
1466        // If there are previous contents, parse them out then start a new
1467        // file to continue the recordkeeping.
1468        if (mEverStored.exists()) {
1469            DataOutputStream temp = null;
1470            DataInputStream in = null;
1471
1472            try {
1473                temp = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(
1474                        tempProcessedFile)));
1475                in = new DataInputStream(new BufferedInputStream(new FileInputStream(mEverStored)));
1476
1477                // Loop until we hit EOF
1478                while (true) {
1479                    String pkg = in.readUTF();
1480                    try {
1481                        // is this package still present?
1482                        mPackageManager.getPackageInfo(pkg, 0);
1483                        // if we get here then yes it is; remember it
1484                        mEverStoredApps.add(pkg);
1485                        temp.writeUTF(pkg);
1486                        if (MORE_DEBUG) Slog.v(TAG, "   + " + pkg);
1487                    } catch (NameNotFoundException e) {
1488                        // nope, this package was uninstalled; don't include it
1489                        if (MORE_DEBUG) Slog.v(TAG, "   - " + pkg);
1490                    }
1491                }
1492            } catch (EOFException e) {
1493                // Once we've rewritten the backup history log, atomically replace the
1494                // old one with the new one then reopen the file for continuing use.
1495                if (!tempProcessedFile.renameTo(mEverStored)) {
1496                    Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
1497                }
1498            } catch (IOException e) {
1499                Slog.e(TAG, "Error in processed file", e);
1500            } finally {
1501                try { if (temp != null) temp.close(); } catch (IOException e) {}
1502                try { if (in != null) in.close(); } catch (IOException e) {}
1503            }
1504        }
1505
1506        synchronized (mQueueLock) {
1507            // Resume the full-data backup queue
1508            mFullBackupQueue = readFullBackupSchedule();
1509        }
1510
1511        // Register for broadcasts about package install, etc., so we can
1512        // update the provider list.
1513        IntentFilter filter = new IntentFilter();
1514        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1515        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1516        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1517        filter.addDataScheme("package");
1518        mContext.registerReceiver(mBroadcastReceiver, filter);
1519        // Register for events related to sdcard installation.
1520        IntentFilter sdFilter = new IntentFilter();
1521        sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1522        sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1523        mContext.registerReceiver(mBroadcastReceiver, sdFilter);
1524    }
1525
1526    private ArrayList<FullBackupEntry> readFullBackupSchedule() {
1527        boolean changed = false;
1528        ArrayList<FullBackupEntry> schedule = null;
1529        List<PackageInfo> apps =
1530                PackageManagerBackupAgent.getStorableApplications(mPackageManager);
1531
1532        if (mFullBackupScheduleFile.exists()) {
1533            FileInputStream fstream = null;
1534            BufferedInputStream bufStream = null;
1535            DataInputStream in = null;
1536            try {
1537                fstream = new FileInputStream(mFullBackupScheduleFile);
1538                bufStream = new BufferedInputStream(fstream);
1539                in = new DataInputStream(bufStream);
1540
1541                int version = in.readInt();
1542                if (version != SCHEDULE_FILE_VERSION) {
1543                    Slog.e(TAG, "Unknown backup schedule version " + version);
1544                    return null;
1545                }
1546
1547                final int N = in.readInt();
1548                schedule = new ArrayList<FullBackupEntry>(N);
1549
1550                // HashSet instead of ArraySet specifically because we want the eventual
1551                // lookups against O(hundreds) of entries to be as fast as possible, and
1552                // we discard the set immediately after the scan so the extra memory
1553                // overhead is transient.
1554                HashSet<String> foundApps = new HashSet<String>(N);
1555
1556                for (int i = 0; i < N; i++) {
1557                    String pkgName = in.readUTF();
1558                    long lastBackup = in.readLong();
1559                    foundApps.add(pkgName); // all apps that we've addressed already
1560                    try {
1561                        PackageInfo pkg = mPackageManager.getPackageInfo(pkgName, 0);
1562                        if (appGetsFullBackup(pkg)
1563                                && appIsEligibleForBackup(pkg.applicationInfo, mPackageManager)) {
1564                            schedule.add(new FullBackupEntry(pkgName, lastBackup));
1565                        } else {
1566                            if (DEBUG) {
1567                                Slog.i(TAG, "Package " + pkgName
1568                                        + " no longer eligible for full backup");
1569                            }
1570                        }
1571                    } catch (NameNotFoundException e) {
1572                        if (DEBUG) {
1573                            Slog.i(TAG, "Package " + pkgName
1574                                    + " not installed; dropping from full backup");
1575                        }
1576                    }
1577                }
1578
1579                // New apps can arrive "out of band" via OTA and similar, so we also need to
1580                // scan to make sure that we're tracking all full-backup candidates properly
1581                for (PackageInfo app : apps) {
1582                    if (appGetsFullBackup(app)
1583                            && appIsEligibleForBackup(app.applicationInfo, mPackageManager)) {
1584                        if (!foundApps.contains(app.packageName)) {
1585                            if (MORE_DEBUG) {
1586                                Slog.i(TAG, "New full backup app " + app.packageName + " found");
1587                            }
1588                            schedule.add(new FullBackupEntry(app.packageName, 0));
1589                            changed = true;
1590                        }
1591                    }
1592                }
1593
1594                Collections.sort(schedule);
1595            } catch (Exception e) {
1596                Slog.e(TAG, "Unable to read backup schedule", e);
1597                mFullBackupScheduleFile.delete();
1598                schedule = null;
1599            } finally {
1600                IoUtils.closeQuietly(in);
1601                IoUtils.closeQuietly(bufStream);
1602                IoUtils.closeQuietly(fstream);
1603            }
1604        }
1605
1606        if (schedule == null) {
1607            // no prior queue record, or unable to read it.  Set up the queue
1608            // from scratch.
1609            changed = true;
1610            schedule = new ArrayList<FullBackupEntry>(apps.size());
1611            for (PackageInfo info : apps) {
1612                if (appGetsFullBackup(info)
1613                        && appIsEligibleForBackup(info.applicationInfo, mPackageManager)) {
1614                    schedule.add(new FullBackupEntry(info.packageName, 0));
1615                }
1616            }
1617        }
1618
1619        if (changed) {
1620            writeFullBackupScheduleAsync();
1621        }
1622        return schedule;
1623    }
1624
1625    Runnable mFullBackupScheduleWriter = new Runnable() {
1626        @Override public void run() {
1627            synchronized (mQueueLock) {
1628                try {
1629                    ByteArrayOutputStream bufStream = new ByteArrayOutputStream(4096);
1630                    DataOutputStream bufOut = new DataOutputStream(bufStream);
1631                    bufOut.writeInt(SCHEDULE_FILE_VERSION);
1632
1633                    // version 1:
1634                    //
1635                    // [int] # of packages in the queue = N
1636                    // N * {
1637                    //     [utf8] package name
1638                    //     [long] last backup time for this package
1639                    //     }
1640                    int N = mFullBackupQueue.size();
1641                    bufOut.writeInt(N);
1642
1643                    for (int i = 0; i < N; i++) {
1644                        FullBackupEntry entry = mFullBackupQueue.get(i);
1645                        bufOut.writeUTF(entry.packageName);
1646                        bufOut.writeLong(entry.lastBackup);
1647                    }
1648                    bufOut.flush();
1649
1650                    AtomicFile af = new AtomicFile(mFullBackupScheduleFile);
1651                    FileOutputStream out = af.startWrite();
1652                    out.write(bufStream.toByteArray());
1653                    af.finishWrite(out);
1654                } catch (Exception e) {
1655                    Slog.e(TAG, "Unable to write backup schedule!", e);
1656                }
1657            }
1658        }
1659    };
1660
1661    private void writeFullBackupScheduleAsync() {
1662        mBackupHandler.removeCallbacks(mFullBackupScheduleWriter);
1663        mBackupHandler.post(mFullBackupScheduleWriter);
1664    }
1665
1666    private void parseLeftoverJournals() {
1667        for (File f : mJournalDir.listFiles()) {
1668            if (mJournal == null || f.compareTo(mJournal) != 0) {
1669                // This isn't the current journal, so it must be a leftover.  Read
1670                // out the package names mentioned there and schedule them for
1671                // backup.
1672                DataInputStream in = null;
1673                try {
1674                    Slog.i(TAG, "Found stale backup journal, scheduling");
1675                    // Journals will tend to be on the order of a few kilobytes(around 4k), hence,
1676                    // setting the buffer size to 8192.
1677                    InputStream bufferedInputStream = new BufferedInputStream(
1678                            new FileInputStream(f), 8192);
1679                    in = new DataInputStream(bufferedInputStream);
1680                    while (true) {
1681                        String packageName = in.readUTF();
1682                        if (MORE_DEBUG) Slog.i(TAG, "  " + packageName);
1683                        dataChangedImpl(packageName);
1684                    }
1685                } catch (EOFException e) {
1686                    // no more data; we're done
1687                } catch (Exception e) {
1688                    Slog.e(TAG, "Can't read " + f, e);
1689                } finally {
1690                    // close/delete the file
1691                    try { if (in != null) in.close(); } catch (IOException e) {}
1692                    f.delete();
1693                }
1694            }
1695        }
1696    }
1697
1698    private SecretKey buildPasswordKey(String algorithm, String pw, byte[] salt, int rounds) {
1699        return buildCharArrayKey(algorithm, pw.toCharArray(), salt, rounds);
1700    }
1701
1702    private SecretKey buildCharArrayKey(String algorithm, char[] pwArray, byte[] salt, int rounds) {
1703        try {
1704            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
1705            KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1706            return keyFactory.generateSecret(ks);
1707        } catch (InvalidKeySpecException e) {
1708            Slog.e(TAG, "Invalid key spec for PBKDF2!");
1709        } catch (NoSuchAlgorithmException e) {
1710            Slog.e(TAG, "PBKDF2 unavailable!");
1711        }
1712        return null;
1713    }
1714
1715    private String buildPasswordHash(String algorithm, String pw, byte[] salt, int rounds) {
1716        SecretKey key = buildPasswordKey(algorithm, pw, salt, rounds);
1717        if (key != null) {
1718            return byteArrayToHex(key.getEncoded());
1719        }
1720        return null;
1721    }
1722
1723    private String byteArrayToHex(byte[] data) {
1724        StringBuilder buf = new StringBuilder(data.length * 2);
1725        for (int i = 0; i < data.length; i++) {
1726            buf.append(Byte.toHexString(data[i], true));
1727        }
1728        return buf.toString();
1729    }
1730
1731    private byte[] hexToByteArray(String digits) {
1732        final int bytes = digits.length() / 2;
1733        if (2*bytes != digits.length()) {
1734            throw new IllegalArgumentException("Hex string must have an even number of digits");
1735        }
1736
1737        byte[] result = new byte[bytes];
1738        for (int i = 0; i < digits.length(); i += 2) {
1739            result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1740        }
1741        return result;
1742    }
1743
1744    private byte[] makeKeyChecksum(String algorithm, byte[] pwBytes, byte[] salt, int rounds) {
1745        char[] mkAsChar = new char[pwBytes.length];
1746        for (int i = 0; i < pwBytes.length; i++) {
1747            mkAsChar[i] = (char) pwBytes[i];
1748        }
1749
1750        Key checksum = buildCharArrayKey(algorithm, mkAsChar, salt, rounds);
1751        return checksum.getEncoded();
1752    }
1753
1754    // Used for generating random salts or passwords
1755    private byte[] randomBytes(int bits) {
1756        byte[] array = new byte[bits / 8];
1757        mRng.nextBytes(array);
1758        return array;
1759    }
1760
1761    boolean passwordMatchesSaved(String algorithm, String candidatePw, int rounds) {
1762        if (mPasswordHash == null) {
1763            // no current password case -- require that 'currentPw' be null or empty
1764            if (candidatePw == null || "".equals(candidatePw)) {
1765                return true;
1766            } // else the non-empty candidate does not match the empty stored pw
1767        } else {
1768            // hash the stated current pw and compare to the stored one
1769            if (candidatePw != null && candidatePw.length() > 0) {
1770                String currentPwHash = buildPasswordHash(algorithm, candidatePw, mPasswordSalt, rounds);
1771                if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1772                    // candidate hash matches the stored hash -- the password matches
1773                    return true;
1774                }
1775            } // else the stored pw is nonempty but the candidate is empty; no match
1776        }
1777        return false;
1778    }
1779
1780    @Override
1781    public boolean setBackupPassword(String currentPw, String newPw) {
1782        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1783                "setBackupPassword");
1784
1785        // When processing v1 passwords we may need to try two different PBKDF2 checksum regimes
1786        final boolean pbkdf2Fallback = (mPasswordVersion < BACKUP_PW_FILE_VERSION);
1787
1788        // If the supplied pw doesn't hash to the the saved one, fail.  The password
1789        // might be caught in the legacy crypto mismatch; verify that too.
1790        if (!passwordMatchesSaved(PBKDF_CURRENT, currentPw, PBKDF2_HASH_ROUNDS)
1791                && !(pbkdf2Fallback && passwordMatchesSaved(PBKDF_FALLBACK,
1792                        currentPw, PBKDF2_HASH_ROUNDS))) {
1793            return false;
1794        }
1795
1796        // Snap up to current on the pw file version
1797        mPasswordVersion = BACKUP_PW_FILE_VERSION;
1798        FileOutputStream pwFout = null;
1799        DataOutputStream pwOut = null;
1800        try {
1801            pwFout = new FileOutputStream(mPasswordVersionFile);
1802            pwOut = new DataOutputStream(pwFout);
1803            pwOut.writeInt(mPasswordVersion);
1804        } catch (IOException e) {
1805            Slog.e(TAG, "Unable to write backup pw version; password not changed");
1806            return false;
1807        } finally {
1808            try {
1809                if (pwOut != null) pwOut.close();
1810                if (pwFout != null) pwFout.close();
1811            } catch (IOException e) {
1812                Slog.w(TAG, "Unable to close pw version record");
1813            }
1814        }
1815
1816        // Clearing the password is okay
1817        if (newPw == null || newPw.isEmpty()) {
1818            if (mPasswordHashFile.exists()) {
1819                if (!mPasswordHashFile.delete()) {
1820                    // Unable to delete the old pw file, so fail
1821                    Slog.e(TAG, "Unable to clear backup password");
1822                    return false;
1823                }
1824            }
1825            mPasswordHash = null;
1826            mPasswordSalt = null;
1827            return true;
1828        }
1829
1830        try {
1831            // Okay, build the hash of the new backup password
1832            byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1833            String newPwHash = buildPasswordHash(PBKDF_CURRENT, newPw, salt, PBKDF2_HASH_ROUNDS);
1834
1835            OutputStream pwf = null, buffer = null;
1836            DataOutputStream out = null;
1837            try {
1838                pwf = new FileOutputStream(mPasswordHashFile);
1839                buffer = new BufferedOutputStream(pwf);
1840                out = new DataOutputStream(buffer);
1841                // integer length of the salt array, followed by the salt,
1842                // then the hex pw hash string
1843                out.writeInt(salt.length);
1844                out.write(salt);
1845                out.writeUTF(newPwHash);
1846                out.flush();
1847                mPasswordHash = newPwHash;
1848                mPasswordSalt = salt;
1849                return true;
1850            } finally {
1851                if (out != null) out.close();
1852                if (buffer != null) buffer.close();
1853                if (pwf != null) pwf.close();
1854            }
1855        } catch (IOException e) {
1856            Slog.e(TAG, "Unable to set backup password");
1857        }
1858        return false;
1859    }
1860
1861    @Override
1862    public boolean hasBackupPassword() {
1863        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1864                "hasBackupPassword");
1865
1866        return mPasswordHash != null && mPasswordHash.length() > 0;
1867    }
1868
1869    private boolean backupPasswordMatches(String currentPw) {
1870        if (hasBackupPassword()) {
1871            final boolean pbkdf2Fallback = (mPasswordVersion < BACKUP_PW_FILE_VERSION);
1872            if (!passwordMatchesSaved(PBKDF_CURRENT, currentPw, PBKDF2_HASH_ROUNDS)
1873                    && !(pbkdf2Fallback && passwordMatchesSaved(PBKDF_FALLBACK,
1874                            currentPw, PBKDF2_HASH_ROUNDS))) {
1875                if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
1876                return false;
1877            }
1878        }
1879        return true;
1880    }
1881
1882    // Maintain persistent state around whether need to do an initialize operation.
1883    // Must be called with the queue lock held.
1884    void recordInitPendingLocked(boolean isPending, String transportName) {
1885        if (MORE_DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
1886                + " on transport " + transportName);
1887        mBackupHandler.removeMessages(MSG_RETRY_INIT);
1888
1889        try {
1890            IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
1891            if (transport != null) {
1892                String transportDirName = transport.transportDirName();
1893                File stateDir = new File(mBaseStateDir, transportDirName);
1894                File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1895
1896                if (isPending) {
1897                    // We need an init before we can proceed with sending backup data.
1898                    // Record that with an entry in our set of pending inits, as well as
1899                    // journaling it via creation of a sentinel file.
1900                    mPendingInits.add(transportName);
1901                    try {
1902                        (new FileOutputStream(initPendingFile)).close();
1903                    } catch (IOException ioe) {
1904                        // Something is badly wrong with our permissions; just try to move on
1905                    }
1906                } else {
1907                    // No more initialization needed; wipe the journal and reset our state.
1908                    initPendingFile.delete();
1909                    mPendingInits.remove(transportName);
1910                }
1911                return; // done; don't fall through to the error case
1912            }
1913        } catch (Exception e) {
1914            // transport threw when asked its name; fall through to the lookup-failed case
1915            Slog.e(TAG, "Transport " + transportName + " failed to report name: "
1916                    + e.getMessage());
1917        }
1918
1919        // The named transport doesn't exist or threw.  This operation is
1920        // important, so we record the need for a an init and post a message
1921        // to retry the init later.
1922        if (isPending) {
1923            mPendingInits.add(transportName);
1924            mBackupHandler.sendMessageDelayed(
1925                    mBackupHandler.obtainMessage(MSG_RETRY_INIT,
1926                            (isPending ? 1 : 0),
1927                            0,
1928                            transportName),
1929                    TRANSPORT_RETRY_INTERVAL);
1930        }
1931    }
1932
1933    // Reset all of our bookkeeping, in response to having been told that
1934    // the backend data has been wiped [due to idle expiry, for example],
1935    // so we must re-upload all saved settings.
1936    void resetBackupState(File stateFileDir) {
1937        synchronized (mQueueLock) {
1938            // Wipe the "what we've ever backed up" tracking
1939            mEverStoredApps.clear();
1940            mEverStored.delete();
1941
1942            mCurrentToken = 0;
1943            writeRestoreTokens();
1944
1945            // Remove all the state files
1946            for (File sf : stateFileDir.listFiles()) {
1947                // ... but don't touch the needs-init sentinel
1948                if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1949                    sf.delete();
1950                }
1951            }
1952        }
1953
1954        // Enqueue a new backup of every participant
1955        synchronized (mBackupParticipants) {
1956            final int N = mBackupParticipants.size();
1957            for (int i=0; i<N; i++) {
1958                HashSet<String> participants = mBackupParticipants.valueAt(i);
1959                if (participants != null) {
1960                    for (String packageName : participants) {
1961                        dataChangedImpl(packageName);
1962                    }
1963                }
1964            }
1965        }
1966    }
1967
1968    private TransportManager.TransportBoundListener mTransportBoundListener =
1969            new TransportManager.TransportBoundListener() {
1970        @Override
1971        public boolean onTransportBound(IBackupTransport transport) {
1972            // If the init sentinel file exists, we need to be sure to perform the init
1973            // as soon as practical.  We also create the state directory at registration
1974            // time to ensure it's present from the outset.
1975            String name = null;
1976            try {
1977                name = transport.name();
1978                String transportDirName = transport.transportDirName();
1979                File stateDir = new File(mBaseStateDir, transportDirName);
1980                stateDir.mkdirs();
1981
1982                File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1983                if (initSentinel.exists()) {
1984                    synchronized (mQueueLock) {
1985                        mPendingInits.add(name);
1986
1987                        // TODO: pick a better starting time than now + 1 minute
1988                        long delay = 1000 * 60; // one minute, in milliseconds
1989                        mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1990                                System.currentTimeMillis() + delay, mRunInitIntent);
1991                    }
1992                }
1993                return true;
1994            } catch (Exception e) {
1995                // the transport threw when asked its file naming prefs; declare it invalid
1996                Slog.w(TAG, "Failed to regiser transport: " + name);
1997                return false;
1998            }
1999        }
2000    };
2001
2002    // ----- Track installation/removal of packages -----
2003    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
2004        public void onReceive(Context context, Intent intent) {
2005            if (MORE_DEBUG) Slog.d(TAG, "Received broadcast " + intent);
2006
2007            String action = intent.getAction();
2008            boolean replacing = false;
2009            boolean added = false;
2010            boolean changed = false;
2011            Bundle extras = intent.getExtras();
2012            String pkgList[] = null;
2013            if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
2014                    Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
2015                    Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
2016                Uri uri = intent.getData();
2017                if (uri == null) {
2018                    return;
2019                }
2020                String pkgName = uri.getSchemeSpecificPart();
2021                if (pkgName != null) {
2022                    pkgList = new String[] { pkgName };
2023                }
2024                changed = Intent.ACTION_PACKAGE_CHANGED.equals(action);
2025
2026                // At package-changed we only care about looking at new transport states
2027                if (changed) {
2028                    String[] components =
2029                            intent.getStringArrayExtra(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
2030
2031                    if (MORE_DEBUG) {
2032                        Slog.i(TAG, "Package " + pkgName + " changed; rechecking");
2033                        for (int i = 0; i < components.length; i++) {
2034                            Slog.i(TAG, "   * " + components[i]);
2035                        }
2036                    }
2037
2038                    mTransportManager.onPackageChanged(pkgName, components);
2039                    return; // nothing more to do in the PACKAGE_CHANGED case
2040                }
2041
2042                added = Intent.ACTION_PACKAGE_ADDED.equals(action);
2043                replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
2044            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
2045                added = true;
2046                pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
2047            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
2048                added = false;
2049                pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
2050            }
2051
2052            if (pkgList == null || pkgList.length == 0) {
2053                return;
2054            }
2055
2056            final int uid = extras.getInt(Intent.EXTRA_UID);
2057            if (added) {
2058                synchronized (mBackupParticipants) {
2059                    if (replacing) {
2060                        // This is the package-replaced case; we just remove the entry
2061                        // under the old uid and fall through to re-add.  If an app
2062                        // just added key/value backup participation, this picks it up
2063                        // as a known participant.
2064                        removePackageParticipantsLocked(pkgList, uid);
2065                    }
2066                    addPackageParticipantsLocked(pkgList);
2067                }
2068                // If they're full-backup candidates, add them there instead
2069                final long now = System.currentTimeMillis();
2070                for (String packageName : pkgList) {
2071                    try {
2072                        PackageInfo app = mPackageManager.getPackageInfo(packageName, 0);
2073                        if (appGetsFullBackup(app)
2074                                && appIsEligibleForBackup(app.applicationInfo, mPackageManager)) {
2075                            enqueueFullBackup(packageName, now);
2076                            scheduleNextFullBackupJob(0);
2077                        } else {
2078                            // The app might have just transitioned out of full-data into
2079                            // doing key/value backups, or might have just disabled backups
2080                            // entirely.  Make sure it is no longer in the full-data queue.
2081                            synchronized (mQueueLock) {
2082                                dequeueFullBackupLocked(packageName);
2083                            }
2084                            writeFullBackupScheduleAsync();
2085                        }
2086
2087                        mTransportManager.onPackageAdded(packageName);
2088
2089                    } catch (NameNotFoundException e) {
2090                        // doesn't really exist; ignore it
2091                        if (DEBUG) {
2092                            Slog.w(TAG, "Can't resolve new app " + packageName);
2093                        }
2094                    }
2095                }
2096
2097                // Whenever a package is added or updated we need to update
2098                // the package metadata bookkeeping.
2099                dataChangedImpl(PACKAGE_MANAGER_SENTINEL);
2100            } else {
2101                if (replacing) {
2102                    // The package is being updated.  We'll receive a PACKAGE_ADDED shortly.
2103                } else {
2104                    // Outright removal.  In the full-data case, the app will be dropped
2105                    // from the queue when its (now obsolete) name comes up again for
2106                    // backup.
2107                    synchronized (mBackupParticipants) {
2108                        removePackageParticipantsLocked(pkgList, uid);
2109                    }
2110                }
2111                for (String pkgName : pkgList) {
2112                    mTransportManager.onPackageRemoved(pkgName);
2113                }
2114            }
2115        }
2116    };
2117
2118    // Add the backup agents in the given packages to our set of known backup participants.
2119    // If 'packageNames' is null, adds all backup agents in the whole system.
2120    void addPackageParticipantsLocked(String[] packageNames) {
2121        // Look for apps that define the android:backupAgent attribute
2122        List<PackageInfo> targetApps = allAgentPackages();
2123        if (packageNames != null) {
2124            if (MORE_DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
2125            for (String packageName : packageNames) {
2126                addPackageParticipantsLockedInner(packageName, targetApps);
2127            }
2128        } else {
2129            if (MORE_DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
2130            addPackageParticipantsLockedInner(null, targetApps);
2131        }
2132    }
2133
2134    private void addPackageParticipantsLockedInner(String packageName,
2135            List<PackageInfo> targetPkgs) {
2136        if (MORE_DEBUG) {
2137            Slog.v(TAG, "Examining " + packageName + " for backup agent");
2138        }
2139
2140        for (PackageInfo pkg : targetPkgs) {
2141            if (packageName == null || pkg.packageName.equals(packageName)) {
2142                int uid = pkg.applicationInfo.uid;
2143                HashSet<String> set = mBackupParticipants.get(uid);
2144                if (set == null) {
2145                    set = new HashSet<>();
2146                    mBackupParticipants.put(uid, set);
2147                }
2148                set.add(pkg.packageName);
2149                if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
2150
2151                // Schedule a backup for it on general principles
2152                if (MORE_DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName);
2153                Message msg = mBackupHandler
2154                        .obtainMessage(MSG_SCHEDULE_BACKUP_PACKAGE, pkg.packageName);
2155                mBackupHandler.sendMessage(msg);
2156            }
2157        }
2158    }
2159
2160    // Remove the given packages' entries from our known active set.
2161    void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
2162        if (packageNames == null) {
2163            Slog.w(TAG, "removePackageParticipants with null list");
2164            return;
2165        }
2166
2167        if (MORE_DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
2168                + " #" + packageNames.length);
2169        for (String pkg : packageNames) {
2170            // Known previous UID, so we know which package set to check
2171            HashSet<String> set = mBackupParticipants.get(oldUid);
2172            if (set != null && set.contains(pkg)) {
2173                removePackageFromSetLocked(set, pkg);
2174                if (set.isEmpty()) {
2175                    if (MORE_DEBUG) Slog.v(TAG, "  last one of this uid; purging set");
2176                    mBackupParticipants.remove(oldUid);
2177                }
2178            }
2179        }
2180    }
2181
2182    private void removePackageFromSetLocked(final HashSet<String> set,
2183            final String packageName) {
2184        if (set.contains(packageName)) {
2185            // Found it.  Remove this one package from the bookkeeping, and
2186            // if it's the last participating app under this uid we drop the
2187            // (now-empty) set as well.
2188            // Note that we deliberately leave it 'known' in the "ever backed up"
2189            // bookkeeping so that its current-dataset data will be retrieved
2190            // if the app is subsequently reinstalled
2191            if (MORE_DEBUG) Slog.v(TAG, "  removing participant " + packageName);
2192            set.remove(packageName);
2193            mPendingBackups.remove(packageName);
2194        }
2195    }
2196
2197    // Returns the set of all applications that define an android:backupAgent attribute
2198    List<PackageInfo> allAgentPackages() {
2199        // !!! TODO: cache this and regenerate only when necessary
2200        int flags = PackageManager.GET_SIGNATURES;
2201        List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
2202        int N = packages.size();
2203        for (int a = N-1; a >= 0; a--) {
2204            PackageInfo pkg = packages.get(a);
2205            try {
2206                ApplicationInfo app = pkg.applicationInfo;
2207                if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
2208                        || app.backupAgentName == null
2209                        || (app.flags&ApplicationInfo.FLAG_FULL_BACKUP_ONLY) != 0) {
2210                    packages.remove(a);
2211                }
2212                else {
2213                    // we will need the shared library path, so look that up and store it here.
2214                    // This is used implicitly when we pass the PackageInfo object off to
2215                    // the Activity Manager to launch the app for backup/restore purposes.
2216                    app = mPackageManager.getApplicationInfo(pkg.packageName,
2217                            PackageManager.GET_SHARED_LIBRARY_FILES);
2218                    pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
2219                }
2220            } catch (NameNotFoundException e) {
2221                packages.remove(a);
2222            }
2223        }
2224        return packages;
2225    }
2226
2227    // Called from the backup tasks: record that the given app has been successfully
2228    // backed up at least once.  This includes both key/value and full-data backups
2229    // through the transport.
2230    void logBackupComplete(String packageName) {
2231        if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
2232
2233        synchronized (mEverStoredApps) {
2234            if (!mEverStoredApps.add(packageName)) return;
2235
2236            RandomAccessFile out = null;
2237            try {
2238                out = new RandomAccessFile(mEverStored, "rws");
2239                out.seek(out.length());
2240                out.writeUTF(packageName);
2241            } catch (IOException e) {
2242                Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
2243            } finally {
2244                try { if (out != null) out.close(); } catch (IOException e) {}
2245            }
2246        }
2247    }
2248
2249    // Remove our awareness of having ever backed up the given package
2250    void removeEverBackedUp(String packageName) {
2251        if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
2252        if (MORE_DEBUG) Slog.v(TAG, "New set:");
2253
2254        synchronized (mEverStoredApps) {
2255            // Rewrite the file and rename to overwrite.  If we reboot in the middle,
2256            // we'll recognize on initialization time that the package no longer
2257            // exists and fix it up then.
2258            File tempKnownFile = new File(mBaseStateDir, "processed.new");
2259            RandomAccessFile known = null;
2260            try {
2261                known = new RandomAccessFile(tempKnownFile, "rws");
2262                mEverStoredApps.remove(packageName);
2263                for (String s : mEverStoredApps) {
2264                    known.writeUTF(s);
2265                    if (MORE_DEBUG) Slog.v(TAG, "    " + s);
2266                }
2267                known.close();
2268                known = null;
2269                if (!tempKnownFile.renameTo(mEverStored)) {
2270                    throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
2271                }
2272            } catch (IOException e) {
2273                // Bad: we couldn't create the new copy.  For safety's sake we
2274                // abandon the whole process and remove all what's-backed-up
2275                // state entirely, meaning we'll force a backup pass for every
2276                // participant on the next boot or [re]install.
2277                Slog.w(TAG, "Error rewriting " + mEverStored, e);
2278                mEverStoredApps.clear();
2279                tempKnownFile.delete();
2280                mEverStored.delete();
2281            } finally {
2282                try { if (known != null) known.close(); } catch (IOException e) {}
2283            }
2284        }
2285    }
2286
2287    // Persistently record the current and ancestral backup tokens as well
2288    // as the set of packages with data [supposedly] available in the
2289    // ancestral dataset.
2290    void writeRestoreTokens() {
2291        try {
2292            RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
2293
2294            // First, the version number of this record, for futureproofing
2295            af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
2296
2297            // Write the ancestral and current tokens
2298            af.writeLong(mAncestralToken);
2299            af.writeLong(mCurrentToken);
2300
2301            // Now write the set of ancestral packages
2302            if (mAncestralPackages == null) {
2303                af.writeInt(-1);
2304            } else {
2305                af.writeInt(mAncestralPackages.size());
2306                if (DEBUG) Slog.v(TAG, "Ancestral packages:  " + mAncestralPackages.size());
2307                for (String pkgName : mAncestralPackages) {
2308                    af.writeUTF(pkgName);
2309                    if (MORE_DEBUG) Slog.v(TAG, "   " + pkgName);
2310                }
2311            }
2312            af.close();
2313        } catch (IOException e) {
2314            Slog.w(TAG, "Unable to write token file:", e);
2315        }
2316    }
2317
2318    // What name is this transport registered under...?
2319    private String getTransportName(IBackupTransport transport) {
2320        if (MORE_DEBUG) {
2321            Slog.v(TAG, "Searching for transport name of " + transport);
2322        }
2323        return mTransportManager.getTransportName(transport);
2324    }
2325
2326    // fire off a backup agent, blocking until it attaches or times out
2327    @Override
2328    public IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
2329        IBackupAgent agent = null;
2330        synchronized(mAgentConnectLock) {
2331            mConnecting = true;
2332            mConnectedAgent = null;
2333            try {
2334                if (mActivityManager.bindBackupAgent(app.packageName, mode,
2335                        UserHandle.USER_OWNER)) {
2336                    Slog.d(TAG, "awaiting agent for " + app);
2337
2338                    // success; wait for the agent to arrive
2339                    // only wait 10 seconds for the bind to happen
2340                    long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
2341                    while (mConnecting && mConnectedAgent == null
2342                            && (System.currentTimeMillis() < timeoutMark)) {
2343                        try {
2344                            mAgentConnectLock.wait(5000);
2345                        } catch (InterruptedException e) {
2346                            // just bail
2347                            Slog.w(TAG, "Interrupted: " + e);
2348                            mConnecting = false;
2349                            mConnectedAgent = null;
2350                        }
2351                    }
2352
2353                    // if we timed out with no connect, abort and move on
2354                    if (mConnecting == true) {
2355                        Slog.w(TAG, "Timeout waiting for agent " + app);
2356                        mConnectedAgent = null;
2357                    }
2358                    if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
2359                    agent = mConnectedAgent;
2360                }
2361            } catch (RemoteException e) {
2362                // can't happen - ActivityManager is local
2363            }
2364        }
2365        if (agent == null) {
2366            try {
2367                mActivityManager.clearPendingBackup();
2368            } catch (RemoteException e) {
2369                // can't happen - ActivityManager is local
2370            }
2371        }
2372        return agent;
2373    }
2374
2375    // clear an application's data, blocking until the operation completes or times out
2376    void clearApplicationDataSynchronous(String packageName) {
2377        // Don't wipe packages marked allowClearUserData=false
2378        try {
2379            PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
2380            if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
2381                if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
2382                        + packageName);
2383                return;
2384            }
2385        } catch (NameNotFoundException e) {
2386            Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
2387            return;
2388        }
2389
2390        ClearDataObserver observer = new ClearDataObserver();
2391
2392        synchronized(mClearDataLock) {
2393            mClearingData = true;
2394            try {
2395                mActivityManager.clearApplicationUserData(packageName, observer, 0);
2396            } catch (RemoteException e) {
2397                // can't happen because the activity manager is in this process
2398            }
2399
2400            // only wait 10 seconds for the clear data to happen
2401            long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
2402            while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
2403                try {
2404                    mClearDataLock.wait(5000);
2405                } catch (InterruptedException e) {
2406                    // won't happen, but still.
2407                    mClearingData = false;
2408                }
2409            }
2410        }
2411    }
2412
2413    class ClearDataObserver extends IPackageDataObserver.Stub {
2414        public void onRemoveCompleted(String packageName, boolean succeeded) {
2415            synchronized(mClearDataLock) {
2416                mClearingData = false;
2417                mClearDataLock.notifyAll();
2418            }
2419        }
2420    }
2421
2422    // Get the restore-set token for the best-available restore set for this package:
2423    // the active set if possible, else the ancestral one.  Returns zero if none available.
2424    @Override
2425    public long getAvailableRestoreToken(String packageName) {
2426        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2427                "getAvailableRestoreToken");
2428
2429        long token = mAncestralToken;
2430        synchronized (mQueueLock) {
2431            if (mCurrentToken != 0 && mEverStoredApps.contains(packageName)) {
2432                if (MORE_DEBUG) {
2433                    Slog.i(TAG, "App in ever-stored, so using current token");
2434                }
2435                token = mCurrentToken;
2436            }
2437        }
2438        if (MORE_DEBUG) Slog.i(TAG, "getAvailableRestoreToken() == " + token);
2439        return token;
2440    }
2441
2442    @Override
2443    public int requestBackup(String[] packages, IBackupObserver observer, int flags) {
2444        return requestBackup(packages, observer, null, flags);
2445    }
2446
2447    @Override
2448    public int requestBackup(String[] packages, IBackupObserver observer,
2449            IBackupManagerMonitor monitor, int flags) {
2450        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "requestBackup");
2451
2452        if (packages == null || packages.length < 1) {
2453            Slog.e(TAG, "No packages named for backup request");
2454            sendBackupFinished(observer, BackupManager.ERROR_TRANSPORT_ABORTED);
2455            monitor = monitorEvent(monitor, BackupManagerMonitor.LOG_EVENT_ID_NO_PACKAGES,
2456                    null, BackupManagerMonitor.LOG_EVENT_CATEGORY_TRANSPORT, null);
2457            throw new IllegalArgumentException("No packages are provided for backup");
2458        }
2459
2460        IBackupTransport transport = mTransportManager.getCurrentTransportBinder();
2461        if (transport == null) {
2462            sendBackupFinished(observer, BackupManager.ERROR_TRANSPORT_ABORTED);
2463            monitor = monitorEvent(monitor, BackupManagerMonitor.LOG_EVENT_ID_TRANSPORT_IS_NULL,
2464                    null, BackupManagerMonitor.LOG_EVENT_CATEGORY_TRANSPORT, null);
2465            return BackupManager.ERROR_TRANSPORT_ABORTED;
2466        }
2467
2468        ArrayList<String> fullBackupList = new ArrayList<>();
2469        ArrayList<String> kvBackupList = new ArrayList<>();
2470        for (String packageName : packages) {
2471            if (PACKAGE_MANAGER_SENTINEL.equals(packageName)) {
2472                kvBackupList.add(packageName);
2473                continue;
2474            }
2475            try {
2476                PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName,
2477                        PackageManager.GET_SIGNATURES);
2478                if (!appIsEligibleForBackup(packageInfo.applicationInfo, mPackageManager)) {
2479                    sendBackupOnPackageResult(observer, packageName,
2480                            BackupManager.ERROR_BACKUP_NOT_ALLOWED);
2481                    continue;
2482                }
2483                if (appGetsFullBackup(packageInfo)) {
2484                    fullBackupList.add(packageInfo.packageName);
2485                } else {
2486                    kvBackupList.add(packageInfo.packageName);
2487                }
2488            } catch (NameNotFoundException e) {
2489                sendBackupOnPackageResult(observer, packageName,
2490                        BackupManager.ERROR_PACKAGE_NOT_FOUND);
2491            }
2492        }
2493        EventLog.writeEvent(EventLogTags.BACKUP_REQUESTED, packages.length, kvBackupList.size(),
2494                fullBackupList.size());
2495        if (MORE_DEBUG) {
2496            Slog.i(TAG, "Backup requested for " + packages.length + " packages, of them: " +
2497                fullBackupList.size() + " full backups, " + kvBackupList.size() + " k/v backups");
2498        }
2499
2500        String dirName;
2501        try {
2502            dirName = transport.transportDirName();
2503        } catch (Exception e) {
2504            Slog.e(TAG, "Transport unavailable while attempting backup: " + e.getMessage());
2505            sendBackupFinished(observer, BackupManager.ERROR_TRANSPORT_ABORTED);
2506            return BackupManager.ERROR_TRANSPORT_ABORTED;
2507        }
2508
2509        boolean nonIncrementalBackup = (flags & BackupManager.FLAG_NON_INCREMENTAL_BACKUP) != 0;
2510
2511        Message msg = mBackupHandler.obtainMessage(MSG_REQUEST_BACKUP);
2512        msg.obj = new BackupParams(transport, dirName, kvBackupList, fullBackupList, observer,
2513                monitor, true, nonIncrementalBackup);
2514        mBackupHandler.sendMessage(msg);
2515        return BackupManager.SUCCESS;
2516    }
2517
2518    // Cancel all running backups.
2519    @Override
2520    public void cancelBackups(){
2521        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "cancelBackups");
2522        if (MORE_DEBUG) {
2523            Slog.i(TAG, "cancelBackups() called.");
2524        }
2525        final long oldToken = Binder.clearCallingIdentity();
2526        try {
2527            List<Integer> operationsToCancel = new ArrayList<>();
2528            synchronized (mCurrentOpLock) {
2529                for (int i = 0; i < mCurrentOperations.size(); i++) {
2530                    Operation op = mCurrentOperations.valueAt(i);
2531                    int token = mCurrentOperations.keyAt(i);
2532                    if (op.type == OP_TYPE_BACKUP) {
2533                        operationsToCancel.add(token);
2534                    }
2535                }
2536            }
2537            for (Integer token : operationsToCancel) {
2538                handleCancel(token, true /* cancelAll */);
2539            }
2540            // We don't want the backup jobs to kick in any time soon.
2541            // Reschedules them to run in the distant future.
2542            KeyValueBackupJob.schedule(mContext, BUSY_BACKOFF_MIN_MILLIS);
2543            FullBackupJob.schedule(mContext, 2 * BUSY_BACKOFF_MIN_MILLIS);
2544        } finally {
2545            Binder.restoreCallingIdentity(oldToken);
2546        }
2547    }
2548
2549    @Override
2550    public void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback,
2551        int operationType) {
2552        if (operationType != OP_TYPE_BACKUP_WAIT && operationType != OP_TYPE_RESTORE_WAIT) {
2553            Slog.wtf(TAG, "prepareOperationTimeout() doesn't support operation " +
2554                    Integer.toHexString(token) + " of type " + operationType);
2555            return;
2556        }
2557        if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
2558                + " interval=" + interval + " callback=" + callback);
2559
2560        synchronized (mCurrentOpLock) {
2561            mCurrentOperations.put(token, new Operation(OP_PENDING, callback, operationType));
2562            Message msg = mBackupHandler.obtainMessage(getMessageIdForOperationType(operationType),
2563                    token, 0, callback);
2564            mBackupHandler.sendMessageDelayed(msg, interval);
2565        }
2566    }
2567
2568    private int getMessageIdForOperationType(int operationType) {
2569        switch (operationType) {
2570            case OP_TYPE_BACKUP_WAIT:
2571                return MSG_BACKUP_OPERATION_TIMEOUT;
2572            case OP_TYPE_RESTORE_WAIT:
2573                return MSG_RESTORE_OPERATION_TIMEOUT;
2574            default:
2575                Slog.wtf(TAG, "getMessageIdForOperationType called on invalid operation type: " +
2576                        operationType);
2577                return -1;
2578        }
2579    }
2580
2581    private void removeOperation(int token) {
2582        if (MORE_DEBUG) {
2583            Slog.d(TAG, "Removing operation token=" + Integer.toHexString(token));
2584        }
2585        synchronized (mCurrentOpLock) {
2586            if (mCurrentOperations.get(token) == null) {
2587                Slog.w(TAG, "Duplicate remove for operation. token=" +
2588                        Integer.toHexString(token));
2589            }
2590            mCurrentOperations.remove(token);
2591        }
2592    }
2593
2594    // synchronous waiter case
2595    @Override
2596    public boolean waitUntilOperationComplete(int token) {
2597        if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
2598                + Integer.toHexString(token));
2599        int finalState = OP_PENDING;
2600        Operation op = null;
2601        synchronized (mCurrentOpLock) {
2602            while (true) {
2603                op = mCurrentOperations.get(token);
2604                if (op == null) {
2605                    // mysterious disappearance: treat as success with no callback
2606                    break;
2607                } else {
2608                    if (op.state == OP_PENDING) {
2609                        try {
2610                            mCurrentOpLock.wait();
2611                        } catch (InterruptedException e) {
2612                        }
2613                        // When the wait is notified we loop around and recheck the current state
2614                    } else {
2615                        if (MORE_DEBUG) {
2616                            Slog.d(TAG, "Unblocked waiting for operation token=" +
2617                                    Integer.toHexString(token));
2618                        }
2619                        // No longer pending; we're done
2620                        finalState = op.state;
2621                        break;
2622                    }
2623                }
2624            }
2625        }
2626
2627        removeOperation(token);
2628        if (op != null) {
2629            mBackupHandler.removeMessages(getMessageIdForOperationType(op.type));
2630        }
2631        if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
2632                + " complete: finalState=" + finalState);
2633        return finalState == OP_ACKNOWLEDGED;
2634    }
2635
2636    void handleCancel(int token, boolean cancelAll) {
2637        // Notify any synchronous waiters
2638        Operation op = null;
2639        synchronized (mCurrentOpLock) {
2640            op = mCurrentOperations.get(token);
2641            if (MORE_DEBUG) {
2642                if (op == null) Slog.w(TAG, "Cancel of token " + Integer.toHexString(token)
2643                        + " but no op found");
2644            }
2645            int state = (op != null) ? op.state : OP_TIMEOUT;
2646            if (state == OP_ACKNOWLEDGED) {
2647                // The operation finished cleanly, so we have nothing more to do.
2648                if (DEBUG) {
2649                    Slog.w(TAG, "Operation already got an ack." +
2650                            "Should have been removed from mCurrentOperations.");
2651                }
2652                op = null;
2653                mCurrentOperations.delete(token);
2654            } else if (state == OP_PENDING) {
2655                if (DEBUG) Slog.v(TAG, "Cancel: token=" + Integer.toHexString(token));
2656                op.state = OP_TIMEOUT;
2657                // Can't delete op from mCurrentOperations here. waitUntilOperationComplete may be
2658                // called after we receive cancel here. We need this op's state there.
2659
2660                // Remove all pending timeout messages of types OP_TYPE_BACKUP_WAIT and
2661                // OP_TYPE_RESTORE_WAIT. On the other hand, OP_TYPE_BACKUP cannot time out and
2662                // doesn't require cancellation.
2663                if (op.type == OP_TYPE_BACKUP_WAIT || op.type == OP_TYPE_RESTORE_WAIT) {
2664                    mBackupHandler.removeMessages(getMessageIdForOperationType(op.type));
2665                }
2666            }
2667            mCurrentOpLock.notifyAll();
2668        }
2669
2670        // If there's a TimeoutHandler for this event, call it
2671        if (op != null && op.callback != null) {
2672            if (MORE_DEBUG) {
2673                Slog.v(TAG, "   Invoking cancel on " + op.callback);
2674            }
2675            op.callback.handleCancel(cancelAll);
2676        }
2677    }
2678
2679    // ----- Back up a set of applications via a worker thread -----
2680
2681    enum BackupState {
2682        INITIAL,
2683        RUNNING_QUEUE,
2684        FINAL
2685    }
2686
2687    /**
2688     * This class handles the process of backing up a given list of key/value backup packages.
2689     * Also takes in a list of pending dolly backups and kicks them off when key/value backups
2690     * are done.
2691     *
2692     * Flow:
2693     * If required, backup @pm@.
2694     * For each pending key/value backup package:
2695     *     - Bind to agent.
2696     *     - Call agent.doBackup()
2697     *     - Wait either for cancel/timeout or operationComplete() callback from the agent.
2698     * Start task to perform dolly backups.
2699     *
2700     * There are three entry points into this class:
2701     *     - execute() [Called from the handler thread]
2702     *     - operationComplete(long result) [Called from the handler thread]
2703     *     - handleCancel(boolean cancelAll) [Can be called from any thread]
2704     * These methods synchronize on mCancelLock.
2705     *
2706     * Interaction with mCurrentOperations:
2707     *     - An entry for this task is put into mCurrentOperations for the entire lifetime of the
2708     *       task. This is useful to cancel the task if required.
2709     *     - An ephemeral entry is put into mCurrentOperations each time we are waiting on for
2710     *       response from a backup agent. This is used to plumb timeouts and completion callbacks.
2711     */
2712    class PerformBackupTask implements BackupRestoreTask {
2713        private static final String TAG = "PerformBackupTask";
2714
2715        private final Object mCancelLock = new Object();
2716
2717        IBackupTransport mTransport;
2718        ArrayList<BackupRequest> mQueue;
2719        ArrayList<BackupRequest> mOriginalQueue;
2720        File mStateDir;
2721        File mJournal;
2722        BackupState mCurrentState;
2723        List<String> mPendingFullBackups;
2724        IBackupObserver mObserver;
2725        IBackupManagerMonitor mMonitor;
2726
2727        private final PerformFullTransportBackupTask mFullBackupTask;
2728        private final int mCurrentOpToken;
2729        private volatile int mEphemeralOpToken;
2730
2731        // carried information about the current in-flight operation
2732        IBackupAgent mAgentBinder;
2733        PackageInfo mCurrentPackage;
2734        File mSavedStateName;
2735        File mBackupDataName;
2736        File mNewStateName;
2737        ParcelFileDescriptor mSavedState;
2738        ParcelFileDescriptor mBackupData;
2739        ParcelFileDescriptor mNewState;
2740        int mStatus;
2741        boolean mFinished;
2742        final boolean mUserInitiated;
2743        final boolean mNonIncremental;
2744
2745        private volatile boolean mCancelAll;
2746
2747        public PerformBackupTask(IBackupTransport transport, String dirName,
2748                ArrayList<BackupRequest> queue, File journal, IBackupObserver observer,
2749                IBackupManagerMonitor monitor, List<String> pendingFullBackups,
2750                boolean userInitiated, boolean nonIncremental) {
2751            mTransport = transport;
2752            mOriginalQueue = queue;
2753            mQueue = new ArrayList<>();
2754            mJournal = journal;
2755            mObserver = observer;
2756            mMonitor = monitor;
2757            mPendingFullBackups = pendingFullBackups;
2758            mUserInitiated = userInitiated;
2759            mNonIncremental = nonIncremental;
2760
2761            mStateDir = new File(mBaseStateDir, dirName);
2762            mCurrentOpToken = generateRandomIntegerToken();
2763
2764            mFinished = false;
2765
2766            synchronized (mCurrentOpLock) {
2767                if (isBackupOperationInProgress()) {
2768                    if (DEBUG) {
2769                        Slog.d(TAG, "Skipping backup since one is already in progress.");
2770                    }
2771                    mCancelAll = true;
2772                    mFullBackupTask = null;
2773                    mCurrentState = BackupState.FINAL;
2774                    addBackupTrace("Skipped. Backup already in progress.");
2775                } else {
2776                    mCurrentState = BackupState.INITIAL;
2777                    CountDownLatch latch = new CountDownLatch(1);
2778                    String[] fullBackups =
2779                            mPendingFullBackups.toArray(new String[mPendingFullBackups.size()]);
2780                    mFullBackupTask =
2781                            new PerformFullTransportBackupTask(/*fullBackupRestoreObserver*/ null,
2782                                    fullBackups, /*updateSchedule*/ false, /*runningJob*/ null,
2783                                    latch,
2784                                    mObserver, mMonitor, mUserInitiated);
2785
2786                    registerTask();
2787                    addBackupTrace("STATE => INITIAL");
2788                }
2789            }
2790        }
2791
2792        /**
2793         * Put this task in the repository of running tasks.
2794         */
2795        private void registerTask() {
2796            synchronized (mCurrentOpLock) {
2797                mCurrentOperations.put(mCurrentOpToken, new Operation(OP_PENDING, this,
2798                        OP_TYPE_BACKUP));
2799            }
2800        }
2801
2802        /**
2803         * Remove this task from repository of running tasks.
2804         */
2805        private void unregisterTask() {
2806            removeOperation(mCurrentOpToken);
2807        }
2808
2809        // Main entry point: perform one chunk of work, updating the state as appropriate
2810        // and reposting the next chunk to the primary backup handler thread.
2811        @Override
2812        @GuardedBy("mCancelLock")
2813        public void execute() {
2814            synchronized (mCancelLock) {
2815                switch (mCurrentState) {
2816                    case INITIAL:
2817                        beginBackup();
2818                        break;
2819
2820                    case RUNNING_QUEUE:
2821                        invokeNextAgent();
2822                        break;
2823
2824                    case FINAL:
2825                        if (!mFinished) finalizeBackup();
2826                        else {
2827                            Slog.e(TAG, "Duplicate finish");
2828                        }
2829                        mFinished = true;
2830                        break;
2831                }
2832            }
2833        }
2834
2835        // We're starting a backup pass.  Initialize the transport and send
2836        // the PM metadata blob if we haven't already.
2837        void beginBackup() {
2838            if (DEBUG_BACKUP_TRACE) {
2839                clearBackupTrace();
2840                StringBuilder b = new StringBuilder(256);
2841                b.append("beginBackup: [");
2842                for (BackupRequest req : mOriginalQueue) {
2843                    b.append(' ');
2844                    b.append(req.packageName);
2845                }
2846                b.append(" ]");
2847                addBackupTrace(b.toString());
2848            }
2849
2850            mAgentBinder = null;
2851            mStatus = BackupTransport.TRANSPORT_OK;
2852
2853            // Sanity check: if the queue is empty we have no work to do.
2854            if (mOriginalQueue.isEmpty() && mPendingFullBackups.isEmpty()) {
2855                Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
2856                addBackupTrace("queue empty at begin");
2857                sendBackupFinished(mObserver, BackupManager.SUCCESS);
2858                executeNextState(BackupState.FINAL);
2859                return;
2860            }
2861
2862            // We need to retain the original queue contents in case of transport
2863            // failure, but we want a working copy that we can manipulate along
2864            // the way.
2865            mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
2866
2867            // When the transport is forcing non-incremental key/value payloads, we send the
2868            // metadata only if it explicitly asks for it.
2869            boolean skipPm = mNonIncremental;
2870
2871            // The app metadata pseudopackage might also be represented in the
2872            // backup queue if apps have been added/removed since the last time
2873            // we performed a backup.  Drop it from the working queue now that
2874            // we're committed to evaluating it for backup regardless.
2875            for (int i = 0; i < mQueue.size(); i++) {
2876                if (PACKAGE_MANAGER_SENTINEL.equals(mQueue.get(i).packageName)) {
2877                    if (MORE_DEBUG) {
2878                        Slog.i(TAG, "Metadata in queue; eliding");
2879                    }
2880                    mQueue.remove(i);
2881                    skipPm = false;
2882                    break;
2883                }
2884            }
2885
2886            if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
2887
2888            File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2889            try {
2890                final String transportName = mTransport.transportDirName();
2891                EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
2892
2893                // If we haven't stored package manager metadata yet, we must init the transport.
2894                if (mStatus == BackupTransport.TRANSPORT_OK && pmState.length() <= 0) {
2895                    Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
2896                    addBackupTrace("initializing transport " + transportName);
2897                    resetBackupState(mStateDir);  // Just to make sure.
2898                    mStatus = mTransport.initializeDevice();
2899
2900                    addBackupTrace("transport.initializeDevice() == " + mStatus);
2901                    if (mStatus == BackupTransport.TRANSPORT_OK) {
2902                        EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
2903                    } else {
2904                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
2905                        Slog.e(TAG, "Transport error in initializeDevice()");
2906                    }
2907                }
2908
2909                if (skipPm) {
2910                    Slog.d(TAG, "Skipping backup of package metadata.");
2911                    executeNextState(BackupState.RUNNING_QUEUE);
2912                } else {
2913                    // The package manager doesn't have a proper <application> etc, but since
2914                    // it's running here in the system process we can just set up its agent
2915                    // directly and use a synthetic BackupRequest.  We always run this pass
2916                    // because it's cheap and this way we guarantee that we don't get out of
2917                    // step even if we're selecting among various transports at run time.
2918                    if (mStatus == BackupTransport.TRANSPORT_OK) {
2919                        PackageManagerBackupAgent pmAgent = makeMetadataAgent();
2920                        mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
2921                                IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
2922                        addBackupTrace("PMBA invoke: " + mStatus);
2923
2924                        // Because the PMBA is a local instance, it has already executed its
2925                        // backup callback and returned.  Blow away the lingering (spurious)
2926                        // pending timeout message for it.
2927                        mBackupHandler.removeMessages(MSG_BACKUP_OPERATION_TIMEOUT);
2928                    }
2929                }
2930
2931                if (mStatus == BackupTransport.TRANSPORT_NOT_INITIALIZED) {
2932                    // The backend reports that our dataset has been wiped.  Note this in
2933                    // the event log; the no-success code below will reset the backup
2934                    // state as well.
2935                    EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
2936                }
2937            } catch (Exception e) {
2938                Slog.e(TAG, "Error in backup thread", e);
2939                addBackupTrace("Exception in backup thread: " + e);
2940                mStatus = BackupTransport.TRANSPORT_ERROR;
2941            } finally {
2942                // If we've succeeded so far, invokeAgentForBackup() will have run the PM
2943                // metadata and its completion/timeout callback will continue the state
2944                // machine chain.  If it failed that won't happen; we handle that now.
2945                addBackupTrace("exiting prelim: " + mStatus);
2946                if (mStatus != BackupTransport.TRANSPORT_OK) {
2947                    // if things went wrong at this point, we need to
2948                    // restage everything and try again later.
2949                    resetBackupState(mStateDir);  // Just to make sure.
2950                    // In case of any other error, it's backup transport error.
2951                    sendBackupFinished(mObserver, BackupManager.ERROR_TRANSPORT_ABORTED);
2952                    executeNextState(BackupState.FINAL);
2953                }
2954            }
2955        }
2956
2957        // Transport has been initialized and the PM metadata submitted successfully
2958        // if that was warranted.  Now we process the single next thing in the queue.
2959        void invokeNextAgent() {
2960            mStatus = BackupTransport.TRANSPORT_OK;
2961            addBackupTrace("invoke q=" + mQueue.size());
2962
2963            // Sanity check that we have work to do.  If not, skip to the end where
2964            // we reestablish the wakelock invariants etc.
2965            if (mQueue.isEmpty()) {
2966                if (MORE_DEBUG) Slog.i(TAG, "queue now empty");
2967                executeNextState(BackupState.FINAL);
2968                return;
2969            }
2970
2971            // pop the entry we're going to process on this step
2972            BackupRequest request = mQueue.get(0);
2973            mQueue.remove(0);
2974
2975            Slog.d(TAG, "starting key/value backup of " + request);
2976            addBackupTrace("launch agent for " + request.packageName);
2977
2978            // Verify that the requested app exists; it might be something that
2979            // requested a backup but was then uninstalled.  The request was
2980            // journalled and rather than tamper with the journal it's safer
2981            // to sanity-check here.  This also gives us the classname of the
2982            // package's backup agent.
2983            try {
2984                mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
2985                        PackageManager.GET_SIGNATURES);
2986                if (!appIsEligibleForBackup(mCurrentPackage.applicationInfo, mPackageManager)) {
2987                    // The manifest has changed but we had a stale backup request pending.
2988                    // This won't happen again because the app won't be requesting further
2989                    // backups.
2990                    Slog.i(TAG, "Package " + request.packageName
2991                            + " no longer supports backup; skipping");
2992                    addBackupTrace("skipping - not eligible, completion is noop");
2993                    // Shouldn't happen in case of requested backup, as pre-check was done in
2994                    // #requestBackup(), except to app update done concurrently
2995                    sendBackupOnPackageResult(mObserver, mCurrentPackage.packageName,
2996                            BackupManager.ERROR_BACKUP_NOT_ALLOWED);
2997                    executeNextState(BackupState.RUNNING_QUEUE);
2998                    return;
2999                }
3000
3001                if (appGetsFullBackup(mCurrentPackage)) {
3002                    // It's possible that this app *formerly* was enqueued for key/value backup,
3003                    // but has since been updated and now only supports the full-data path.
3004                    // Don't proceed with a key/value backup for it in this case.
3005                    Slog.i(TAG, "Package " + request.packageName
3006                            + " requests full-data rather than key/value; skipping");
3007                    addBackupTrace("skipping - fullBackupOnly, completion is noop");
3008                    // Shouldn't happen in case of requested backup, as pre-check was done in
3009                    // #requestBackup()
3010                    sendBackupOnPackageResult(mObserver, mCurrentPackage.packageName,
3011                            BackupManager.ERROR_BACKUP_NOT_ALLOWED);
3012                    executeNextState(BackupState.RUNNING_QUEUE);
3013                    return;
3014                }
3015
3016                if (appIsStopped(mCurrentPackage.applicationInfo)) {
3017                    // The app has been force-stopped or cleared or just installed,
3018                    // and not yet launched out of that state, so just as it won't
3019                    // receive broadcasts, we won't run it for backup.
3020                    addBackupTrace("skipping - stopped");
3021                    sendBackupOnPackageResult(mObserver, mCurrentPackage.packageName,
3022                            BackupManager.ERROR_BACKUP_NOT_ALLOWED);
3023                    executeNextState(BackupState.RUNNING_QUEUE);
3024                    return;
3025                }
3026
3027                IBackupAgent agent = null;
3028                try {
3029                    mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
3030                    agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
3031                            ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL);
3032                    addBackupTrace("agent bound; a? = " + (agent != null));
3033                    if (agent != null) {
3034                        mAgentBinder = agent;
3035                        mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
3036                        // at this point we'll either get a completion callback from the
3037                        // agent, or a timeout message on the main handler.  either way, we're
3038                        // done here as long as we're successful so far.
3039                    } else {
3040                        // Timeout waiting for the agent
3041                        mStatus = BackupTransport.AGENT_ERROR;
3042                    }
3043                } catch (SecurityException ex) {
3044                    // Try for the next one.
3045                    Slog.d(TAG, "error in bind/backup", ex);
3046                    mStatus = BackupTransport.AGENT_ERROR;
3047                            addBackupTrace("agent SE");
3048                }
3049            } catch (NameNotFoundException e) {
3050                Slog.d(TAG, "Package does not exist; skipping");
3051                addBackupTrace("no such package");
3052                mStatus = BackupTransport.AGENT_UNKNOWN;
3053            } finally {
3054                mWakelock.setWorkSource(null);
3055
3056                // If there was an agent error, no timeout/completion handling will occur.
3057                // That means we need to direct to the next state ourselves.
3058                if (mStatus != BackupTransport.TRANSPORT_OK) {
3059                    BackupState nextState = BackupState.RUNNING_QUEUE;
3060                    mAgentBinder = null;
3061
3062                    // An agent-level failure means we reenqueue this one agent for
3063                    // a later retry, but otherwise proceed normally.
3064                    if (mStatus == BackupTransport.AGENT_ERROR) {
3065                        if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
3066                                + " - restaging");
3067                        dataChangedImpl(request.packageName);
3068                        mStatus = BackupTransport.TRANSPORT_OK;
3069                        if (mQueue.isEmpty()) nextState = BackupState.FINAL;
3070                        sendBackupOnPackageResult(mObserver, mCurrentPackage.packageName,
3071                                BackupManager.ERROR_AGENT_FAILURE);
3072                    } else if (mStatus == BackupTransport.AGENT_UNKNOWN) {
3073                        // Failed lookup of the app, so we couldn't bring up an agent, but
3074                        // we're otherwise fine.  Just drop it and go on to the next as usual.
3075                        mStatus = BackupTransport.TRANSPORT_OK;
3076                        sendBackupOnPackageResult(mObserver, mCurrentPackage.packageName,
3077                                BackupManager.ERROR_PACKAGE_NOT_FOUND);
3078                    } else {
3079                        // Transport-level failure means we reenqueue everything
3080                        revertAndEndBackup();
3081                        nextState = BackupState.FINAL;
3082                    }
3083
3084                    executeNextState(nextState);
3085                } else {
3086                    // success case
3087                    addBackupTrace("expecting completion/timeout callback");
3088                }
3089            }
3090        }
3091
3092        void finalizeBackup() {
3093            addBackupTrace("finishing");
3094
3095            // Mark packages that we didn't backup (because backup was cancelled, etc.) as needing
3096            // backup.
3097            for (BackupRequest req : mQueue) {
3098                dataChangedImpl(req.packageName);
3099            }
3100
3101            // Either backup was successful, in which case we of course do not need
3102            // this pass's journal any more; or it failed, in which case we just
3103            // re-enqueued all of these packages in the current active journal.
3104            // Either way, we no longer need this pass's journal.
3105            if (mJournal != null && !mJournal.delete()) {
3106                Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
3107            }
3108
3109            // If everything actually went through and this is the first time we've
3110            // done a backup, we can now record what the current backup dataset token
3111            // is.
3112            if ((mCurrentToken == 0) && (mStatus == BackupTransport.TRANSPORT_OK)) {
3113                addBackupTrace("success; recording token");
3114                try {
3115                    mCurrentToken = mTransport.getCurrentRestoreSet();
3116                    writeRestoreTokens();
3117                } catch (Exception e) {
3118                    // nothing for it at this point, unfortunately, but this will be
3119                    // recorded the next time we fully succeed.
3120                    Slog.e(TAG, "Transport threw reporting restore set: " + e.getMessage());
3121                    addBackupTrace("transport threw returning token");
3122                }
3123            }
3124
3125            // Set up the next backup pass - at this point we can set mBackupRunning
3126            // to false to allow another pass to fire, because we're done with the
3127            // state machine sequence and the wakelock is refcounted.
3128            synchronized (mQueueLock) {
3129                mBackupRunning = false;
3130                if (mStatus == BackupTransport.TRANSPORT_NOT_INITIALIZED) {
3131                    // Make sure we back up everything and perform the one-time init
3132                    if (MORE_DEBUG) Slog.d(TAG, "Server requires init; rerunning");
3133                    addBackupTrace("init required; rerunning");
3134                    try {
3135                        final String name = mTransportManager.getTransportName(mTransport);
3136                        if (name != null) {
3137                            mPendingInits.add(name);
3138                        } else {
3139                            if (DEBUG) {
3140                                Slog.w(TAG, "Couldn't find name of transport " + mTransport
3141                                        + " for init");
3142                            }
3143                        }
3144                    } catch (Exception e) {
3145                        Slog.w(TAG, "Failed to query transport name for init: " + e.getMessage());
3146                        // swallow it and proceed; we don't rely on this
3147                    }
3148                    clearMetadata();
3149                    backupNow();
3150                }
3151            }
3152
3153            clearBackupTrace();
3154
3155            unregisterTask();
3156
3157            if (!mCancelAll && mStatus == BackupTransport.TRANSPORT_OK &&
3158                    mPendingFullBackups != null && !mPendingFullBackups.isEmpty()) {
3159                Slog.d(TAG, "Starting full backups for: " + mPendingFullBackups);
3160                // Acquiring wakelock for PerformFullTransportBackupTask before its start.
3161                mWakelock.acquire();
3162                (new Thread(mFullBackupTask, "full-transport-requested")).start();
3163            } else if (mCancelAll) {
3164                if (mFullBackupTask != null) {
3165                    mFullBackupTask.unregisterTask();
3166                }
3167                sendBackupFinished(mObserver, BackupManager.ERROR_BACKUP_CANCELLED);
3168            } else {
3169                mFullBackupTask.unregisterTask();
3170                switch (mStatus) {
3171                    case BackupTransport.TRANSPORT_OK:
3172                        sendBackupFinished(mObserver, BackupManager.SUCCESS);
3173                        break;
3174                    case BackupTransport.TRANSPORT_NOT_INITIALIZED:
3175                        sendBackupFinished(mObserver, BackupManager.ERROR_TRANSPORT_ABORTED);
3176                        break;
3177                    case BackupTransport.TRANSPORT_ERROR:
3178                    default:
3179                        sendBackupFinished(mObserver, BackupManager.ERROR_TRANSPORT_ABORTED);
3180                        break;
3181                }
3182            }
3183            Slog.i(BackupManagerService.TAG, "K/V backup pass finished.");
3184            // Only once we're entirely finished do we release the wakelock for k/v backup.
3185            mWakelock.release();
3186        }
3187
3188        // Remove the PM metadata state. This will generate an init on the next pass.
3189        void clearMetadata() {
3190            final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
3191            if (pmState.exists()) pmState.delete();
3192        }
3193
3194        // Invoke an agent's doBackup() and start a timeout message spinning on the main
3195        // handler in case it doesn't get back to us.
3196        int invokeAgentForBackup(String packageName, IBackupAgent agent,
3197                IBackupTransport transport) {
3198            if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
3199            addBackupTrace("invoking " + packageName);
3200
3201            File blankStateName = new File(mStateDir, "blank_state");
3202            mSavedStateName = new File(mStateDir, packageName);
3203            mBackupDataName = new File(mDataDir, packageName + ".data");
3204            mNewStateName = new File(mStateDir, packageName + ".new");
3205            if (MORE_DEBUG) Slog.d(TAG, "data file: " + mBackupDataName);
3206
3207            mSavedState = null;
3208            mBackupData = null;
3209            mNewState = null;
3210
3211            boolean callingAgent = false;
3212            mEphemeralOpToken = generateRandomIntegerToken();
3213            try {
3214                // Look up the package info & signatures.  This is first so that if it
3215                // throws an exception, there's no file setup yet that would need to
3216                // be unraveled.
3217                if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
3218                    // The metadata 'package' is synthetic; construct one and make
3219                    // sure our global state is pointed at it
3220                    mCurrentPackage = new PackageInfo();
3221                    mCurrentPackage.packageName = packageName;
3222                }
3223
3224                // In a full backup, we pass a null ParcelFileDescriptor as
3225                // the saved-state "file". For key/value backups we pass the old state if
3226                // an incremental backup is required, and a blank state otherwise.
3227                mSavedState = ParcelFileDescriptor.open(
3228                        mNonIncremental ? blankStateName : mSavedStateName,
3229                        ParcelFileDescriptor.MODE_READ_ONLY |
3230                        ParcelFileDescriptor.MODE_CREATE);  // Make an empty file if necessary
3231
3232                mBackupData = ParcelFileDescriptor.open(mBackupDataName,
3233                        ParcelFileDescriptor.MODE_READ_WRITE |
3234                        ParcelFileDescriptor.MODE_CREATE |
3235                        ParcelFileDescriptor.MODE_TRUNCATE);
3236
3237                if (!SELinux.restorecon(mBackupDataName)) {
3238                    Slog.e(TAG, "SELinux restorecon failed on " + mBackupDataName);
3239                }
3240
3241                mNewState = ParcelFileDescriptor.open(mNewStateName,
3242                        ParcelFileDescriptor.MODE_READ_WRITE |
3243                        ParcelFileDescriptor.MODE_CREATE |
3244                        ParcelFileDescriptor.MODE_TRUNCATE);
3245
3246                final long quota = mTransport.getBackupQuota(packageName, false /* isFullBackup */);
3247                callingAgent = true;
3248
3249                // Initiate the target's backup pass
3250                addBackupTrace("setting timeout");
3251                prepareOperationTimeout(mEphemeralOpToken, TIMEOUT_BACKUP_INTERVAL, this,
3252                        OP_TYPE_BACKUP_WAIT);
3253                addBackupTrace("calling agent doBackup()");
3254
3255                agent.doBackup(mSavedState, mBackupData, mNewState, quota, mEphemeralOpToken,
3256                        mBackupManagerBinder);
3257            } catch (Exception e) {
3258                Slog.e(TAG, "Error invoking for backup on " + packageName + ". " + e);
3259                addBackupTrace("exception: " + e);
3260                EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
3261                        e.toString());
3262                errorCleanup();
3263                return callingAgent ? BackupTransport.AGENT_ERROR
3264                        : BackupTransport.TRANSPORT_ERROR;
3265            } finally {
3266                if (mNonIncremental) {
3267                    blankStateName.delete();
3268                }
3269            }
3270
3271            // At this point the agent is off and running.  The next thing to happen will
3272            // either be a callback from the agent, at which point we'll process its data
3273            // for transport, or a timeout.  Either way the next phase will happen in
3274            // response to the TimeoutHandler interface callbacks.
3275            addBackupTrace("invoke success");
3276            return BackupTransport.TRANSPORT_OK;
3277        }
3278
3279        public void failAgent(IBackupAgent agent, String message) {
3280            try {
3281                agent.fail(message);
3282            } catch (Exception e) {
3283                Slog.w(TAG, "Error conveying failure to " + mCurrentPackage.packageName);
3284            }
3285        }
3286
3287        // SHA-1 a byte array and return the result in hex
3288        private String SHA1Checksum(byte[] input) {
3289            final byte[] checksum;
3290            try {
3291                MessageDigest md = MessageDigest.getInstance("SHA-1");
3292                checksum = md.digest(input);
3293            } catch (NoSuchAlgorithmException e) {
3294                Slog.e(TAG, "Unable to use SHA-1!");
3295                return "00";
3296            }
3297
3298            StringBuffer sb = new StringBuffer(checksum.length * 2);
3299            for (int i = 0; i < checksum.length; i++) {
3300                sb.append(Integer.toHexString(checksum[i]));
3301            }
3302            return sb.toString();
3303        }
3304
3305        private void writeWidgetPayloadIfAppropriate(FileDescriptor fd, String pkgName)
3306                throws IOException {
3307            // TODO: http://b/22388012
3308            byte[] widgetState = AppWidgetBackupBridge.getWidgetState(pkgName,
3309                    UserHandle.USER_SYSTEM);
3310            // has the widget state changed since last time?
3311            final File widgetFile = new File(mStateDir, pkgName + "_widget");
3312            final boolean priorStateExists = widgetFile.exists();
3313
3314            if (MORE_DEBUG) {
3315                if (priorStateExists || widgetState != null) {
3316                    Slog.i(TAG, "Checking widget update: state=" + (widgetState != null)
3317                            + " prior=" + priorStateExists);
3318                }
3319            }
3320
3321            if (!priorStateExists && widgetState == null) {
3322                // no prior state, no new state => nothing to do
3323                return;
3324            }
3325
3326            // if the new state is not null, we might need to compare checksums to
3327            // determine whether to update the widget blob in the archive.  If the
3328            // widget state *is* null, we know a priori at this point that we simply
3329            // need to commit a deletion for it.
3330            String newChecksum = null;
3331            if (widgetState != null) {
3332                newChecksum = SHA1Checksum(widgetState);
3333                if (priorStateExists) {
3334                    final String priorChecksum;
3335                    try (
3336                        FileInputStream fin = new FileInputStream(widgetFile);
3337                        DataInputStream in = new DataInputStream(fin)
3338                    ) {
3339                        priorChecksum = in.readUTF();
3340                    }
3341                    if (Objects.equals(newChecksum, priorChecksum)) {
3342                        // Same checksum => no state change => don't rewrite the widget data
3343                        return;
3344                    }
3345                }
3346            } // else widget state *became* empty, so we need to commit a deletion
3347
3348            BackupDataOutput out = new BackupDataOutput(fd);
3349            if (widgetState != null) {
3350                try (
3351                    FileOutputStream fout = new FileOutputStream(widgetFile);
3352                    DataOutputStream stateOut = new DataOutputStream(fout)
3353                ) {
3354                    stateOut.writeUTF(newChecksum);
3355                }
3356
3357                out.writeEntityHeader(KEY_WIDGET_STATE, widgetState.length);
3358                out.writeEntityData(widgetState, widgetState.length);
3359            } else {
3360                // Widget state for this app has been removed; commit a deletion
3361                out.writeEntityHeader(KEY_WIDGET_STATE, -1);
3362                widgetFile.delete();
3363            }
3364        }
3365
3366        @Override
3367        @GuardedBy("mCancelLock")
3368        public void operationComplete(long unusedResult) {
3369            removeOperation(mEphemeralOpToken);
3370            synchronized (mCancelLock) {
3371                // The agent reported back to us!
3372                if (mFinished) {
3373                    Slog.d(TAG, "operationComplete received after task finished.");
3374                    return;
3375                }
3376
3377                if (mBackupData == null) {
3378                    // This callback was racing with our timeout, so we've cleaned up the
3379                    // agent state already and are on to the next thing.  We have nothing
3380                    // further to do here: agent state having been cleared means that we've
3381                    // initiated the appropriate next operation.
3382                    final String pkg = (mCurrentPackage != null)
3383                            ? mCurrentPackage.packageName : "[none]";
3384                    if (MORE_DEBUG) {
3385                        Slog.i(TAG, "Callback after agent teardown: " + pkg);
3386                    }
3387                    addBackupTrace("late opComplete; curPkg = " + pkg);
3388                    return;
3389                }
3390
3391                final String pkgName = mCurrentPackage.packageName;
3392                final long filepos = mBackupDataName.length();
3393                FileDescriptor fd = mBackupData.getFileDescriptor();
3394                try {
3395                    // If it's a 3rd party app, see whether they wrote any protected keys
3396                    // and complain mightily if they are attempting shenanigans.
3397                    if (mCurrentPackage.applicationInfo != null &&
3398                            (mCurrentPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
3399                                    == 0) {
3400                        ParcelFileDescriptor readFd = ParcelFileDescriptor.open(mBackupDataName,
3401                                ParcelFileDescriptor.MODE_READ_ONLY);
3402                        BackupDataInput in = new BackupDataInput(readFd.getFileDescriptor());
3403                        try {
3404                            while (in.readNextHeader()) {
3405                                final String key = in.getKey();
3406                                if (key != null && key.charAt(0) >= 0xff00) {
3407                                    // Not okay: crash them and bail.
3408                                    failAgent(mAgentBinder, "Illegal backup key: " + key);
3409                                    addBackupTrace("illegal key " + key + " from " + pkgName);
3410                                    EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, pkgName,
3411                                            "bad key");
3412                                    mMonitor = monitorEvent(mMonitor,
3413                                            BackupManagerMonitor.LOG_EVENT_ID_ILLEGAL_KEY,
3414                                            mCurrentPackage,
3415                                            BackupManagerMonitor
3416                                                    .LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
3417                                            putMonitoringExtra(null,
3418                                                    BackupManagerMonitor.EXTRA_LOG_ILLEGAL_KEY,
3419                                                    key));
3420                                    mBackupHandler.removeMessages(MSG_BACKUP_OPERATION_TIMEOUT);
3421                                    sendBackupOnPackageResult(mObserver, pkgName,
3422                                            BackupManager.ERROR_AGENT_FAILURE);
3423                                    errorCleanup();
3424                                    // agentErrorCleanup() implicitly executes next state properly
3425                                    return;
3426                                }
3427                                in.skipEntityData();
3428                            }
3429                        } finally {
3430                            if (readFd != null) {
3431                                readFd.close();
3432                            }
3433                        }
3434                    }
3435
3436                    // Piggyback the widget state payload, if any
3437                    writeWidgetPayloadIfAppropriate(fd, pkgName);
3438                } catch (IOException e) {
3439                    // Hard disk error; recovery/failure policy TBD.  For now roll back,
3440                    // but we may want to consider this a transport-level failure (i.e.
3441                    // we're in such a bad state that we can't contemplate doing backup
3442                    // operations any more during this pass).
3443                    Slog.w(TAG, "Unable to save widget state for " + pkgName);
3444                    try {
3445                        Os.ftruncate(fd, filepos);
3446                    } catch (ErrnoException ee) {
3447                        Slog.w(TAG, "Unable to roll back!");
3448                    }
3449                }
3450
3451                // Spin the data off to the transport and proceed with the next stage.
3452                if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
3453                        + pkgName);
3454                mBackupHandler.removeMessages(MSG_BACKUP_OPERATION_TIMEOUT);
3455                clearAgentState();
3456                addBackupTrace("operation complete");
3457
3458                ParcelFileDescriptor backupData = null;
3459                mStatus = BackupTransport.TRANSPORT_OK;
3460                long size = 0;
3461                try {
3462                    size = mBackupDataName.length();
3463                    if (size > 0) {
3464                        if (mStatus == BackupTransport.TRANSPORT_OK) {
3465                            backupData = ParcelFileDescriptor.open(mBackupDataName,
3466                                    ParcelFileDescriptor.MODE_READ_ONLY);
3467                            addBackupTrace("sending data to transport");
3468                            int flags = mUserInitiated ? BackupTransport.FLAG_USER_INITIATED : 0;
3469                            mStatus = mTransport.performBackup(mCurrentPackage, backupData, flags);
3470                        }
3471
3472                        // TODO - We call finishBackup() for each application backed up, because
3473                        // we need to know now whether it succeeded or failed.  Instead, we should
3474                        // hold off on finishBackup() until the end, which implies holding off on
3475                        // renaming *all* the output state files (see below) until that happens.
3476
3477                        addBackupTrace("data delivered: " + mStatus);
3478                        if (mStatus == BackupTransport.TRANSPORT_OK) {
3479                            addBackupTrace("finishing op on transport");
3480                            mStatus = mTransport.finishBackup();
3481                            addBackupTrace("finished: " + mStatus);
3482                        } else if (mStatus == BackupTransport.TRANSPORT_PACKAGE_REJECTED) {
3483                            addBackupTrace("transport rejected package");
3484                        }
3485                    } else {
3486                        if (MORE_DEBUG) Slog.i(TAG,
3487                                "no backup data written; not calling transport");
3488                        addBackupTrace("no data to send");
3489                        mMonitor = monitorEvent(mMonitor,
3490                                BackupManagerMonitor.LOG_EVENT_ID_NO_DATA_TO_SEND,
3491                                mCurrentPackage,
3492                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
3493                                null);
3494                    }
3495
3496                    if (mStatus == BackupTransport.TRANSPORT_OK) {
3497                        // After successful transport, delete the now-stale data
3498                        // and juggle the files so that next time we supply the agent
3499                        // with the new state file it just created.
3500                        mBackupDataName.delete();
3501                        mNewStateName.renameTo(mSavedStateName);
3502                        sendBackupOnPackageResult(mObserver, pkgName, BackupManager.SUCCESS);
3503                        EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, pkgName, size);
3504                        logBackupComplete(pkgName);
3505                    } else if (mStatus == BackupTransport.TRANSPORT_PACKAGE_REJECTED) {
3506                        // The transport has rejected backup of this specific package.  Roll it
3507                        // back but proceed with running the rest of the queue.
3508                        mBackupDataName.delete();
3509                        mNewStateName.delete();
3510                        sendBackupOnPackageResult(mObserver, pkgName,
3511                                BackupManager.ERROR_TRANSPORT_PACKAGE_REJECTED);
3512                        EventLogTags.writeBackupAgentFailure(pkgName, "Transport rejected");
3513                    } else if (mStatus == BackupTransport.TRANSPORT_QUOTA_EXCEEDED) {
3514                        sendBackupOnPackageResult(mObserver, pkgName,
3515                                BackupManager.ERROR_TRANSPORT_QUOTA_EXCEEDED);
3516                        EventLog.writeEvent(EventLogTags.BACKUP_QUOTA_EXCEEDED, pkgName);
3517                    } else {
3518                        // Actual transport-level failure to communicate the data to the backend
3519                        sendBackupOnPackageResult(mObserver, pkgName,
3520                                BackupManager.ERROR_TRANSPORT_ABORTED);
3521                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, pkgName);
3522                    }
3523                } catch (Exception e) {
3524                    sendBackupOnPackageResult(mObserver, pkgName,
3525                            BackupManager.ERROR_TRANSPORT_ABORTED);
3526                    Slog.e(TAG, "Transport error backing up " + pkgName, e);
3527                    EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, pkgName);
3528                    mStatus = BackupTransport.TRANSPORT_ERROR;
3529                } finally {
3530                    try {
3531                        if (backupData != null) backupData.close();
3532                    } catch (IOException e) {
3533                    }
3534                }
3535
3536                final BackupState nextState;
3537                if (mStatus == BackupTransport.TRANSPORT_OK
3538                        || mStatus == BackupTransport.TRANSPORT_PACKAGE_REJECTED) {
3539                    // Success or single-package rejection.  Proceed with the next app if any,
3540                    // otherwise we're done.
3541                    nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
3542                } else if (mStatus == BackupTransport.TRANSPORT_QUOTA_EXCEEDED) {
3543                    if (MORE_DEBUG) {
3544                        Slog.d(TAG, "Package " + mCurrentPackage.packageName +
3545                                " hit quota limit on k/v backup");
3546                    }
3547                    if (mAgentBinder != null) {
3548                        try {
3549                            long quota = mTransport.getBackupQuota(mCurrentPackage.packageName,
3550                                    false);
3551                            mAgentBinder.doQuotaExceeded(size, quota);
3552                        } catch (Exception e) {
3553                            Slog.e(TAG, "Unable to notify about quota exceeded: " + e.getMessage());
3554                        }
3555                    }
3556                    nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
3557                } else {
3558                    // Any other error here indicates a transport-level failure.  That means
3559                    // we need to halt everything and reschedule everything for next time.
3560                    revertAndEndBackup();
3561                    nextState = BackupState.FINAL;
3562                }
3563
3564                executeNextState(nextState);
3565            }
3566        }
3567
3568
3569        @Override
3570        @GuardedBy("mCancelLock")
3571        public void handleCancel(boolean cancelAll) {
3572            removeOperation(mEphemeralOpToken);
3573            synchronized (mCancelLock) {
3574                if (mFinished) {
3575                    // We have already cancelled this operation.
3576                    if (MORE_DEBUG) {
3577                        Slog.d(TAG, "Ignoring stale cancel. cancelAll=" + cancelAll);
3578                    }
3579                    return;
3580                }
3581                mCancelAll = cancelAll;
3582                final String logPackageName = (mCurrentPackage != null)
3583                        ? mCurrentPackage.packageName
3584                        : "no_package_yet";
3585                Slog.i(TAG, "Cancel backing up " + logPackageName);
3586                EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, logPackageName);
3587                addBackupTrace("cancel of " + logPackageName + ", cancelAll=" + cancelAll);
3588                mMonitor = monitorEvent(mMonitor,
3589                        BackupManagerMonitor.LOG_EVENT_ID_KEY_VALUE_BACKUP_CANCEL,
3590                        mCurrentPackage, BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT,
3591                        putMonitoringExtra(null, BackupManagerMonitor.EXTRA_LOG_CANCEL_ALL,
3592                                mCancelAll));
3593                errorCleanup();
3594                if (!cancelAll) {
3595                    // The current agent either timed out or was cancelled running doBackup().
3596                    // Restage it for the next time we run a backup pass.
3597                    // !!! TODO: keep track of failure counts per agent, and blacklist those which
3598                    // fail repeatedly (i.e. have proved themselves to be buggy).
3599                    executeNextState(
3600                            mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
3601                    dataChangedImpl(mCurrentPackage.packageName);
3602                } else {
3603                    finalizeBackup();
3604                }
3605            }
3606        }
3607
3608        void revertAndEndBackup() {
3609            if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
3610            addBackupTrace("transport error; reverting");
3611
3612            // We want to reset the backup schedule based on whatever the transport suggests
3613            // by way of retry/backoff time.
3614            long delay;
3615            try {
3616                delay = mTransport.requestBackupTime();
3617            } catch (Exception e) {
3618                Slog.w(TAG, "Unable to contact transport for recommended backoff: " + e.getMessage());
3619                delay = 0;  // use the scheduler's default
3620            }
3621            KeyValueBackupJob.schedule(mContext, delay);
3622
3623            for (BackupRequest request : mOriginalQueue) {
3624                dataChangedImpl(request.packageName);
3625            }
3626
3627        }
3628
3629        void errorCleanup() {
3630            mBackupDataName.delete();
3631            mNewStateName.delete();
3632            clearAgentState();
3633        }
3634
3635        // Cleanup common to both success and failure cases
3636        void clearAgentState() {
3637            try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
3638            try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
3639            try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
3640            synchronized (mCurrentOpLock) {
3641                // Current-operation callback handling requires the validity of these various
3642                // bits of internal state as an invariant of the operation still being live.
3643                // This means we make sure to clear all of the state in unison inside the lock.
3644                mCurrentOperations.remove(mEphemeralOpToken);
3645                mSavedState = mBackupData = mNewState = null;
3646            }
3647
3648            // If this was a pseudopackage there's no associated Activity Manager state
3649            if (mCurrentPackage.applicationInfo != null) {
3650                addBackupTrace("unbinding " + mCurrentPackage.packageName);
3651                try {  // unbind even on timeout, just in case
3652                    mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
3653                } catch (RemoteException e) { /* can't happen; activity manager is local */ }
3654            }
3655        }
3656
3657        void executeNextState(BackupState nextState) {
3658            if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
3659                    + this + " nextState=" + nextState);
3660            addBackupTrace("executeNextState => " + nextState);
3661            mCurrentState = nextState;
3662            Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
3663            mBackupHandler.sendMessage(msg);
3664        }
3665    }
3666
3667    private boolean isBackupOperationInProgress() {
3668        synchronized (mCurrentOpLock) {
3669            for (int i = 0; i < mCurrentOperations.size(); i++) {
3670                Operation op = mCurrentOperations.valueAt(i);
3671                if (op.type == OP_TYPE_BACKUP && op.state == OP_PENDING) {
3672                    return true;
3673                }
3674            }
3675        }
3676        return false;
3677    }
3678
3679
3680    // ----- Full backup/restore to a file/socket -----
3681
3682    class FullBackupObbConnection implements ServiceConnection {
3683        volatile IObbBackupService mService;
3684
3685        FullBackupObbConnection() {
3686            mService = null;
3687        }
3688
3689        public void establish() {
3690            if (MORE_DEBUG) Slog.i(TAG, "Initiating bind of OBB service on " + this);
3691            Intent obbIntent = new Intent().setComponent(new ComponentName(
3692                    "com.android.sharedstoragebackup",
3693                    "com.android.sharedstoragebackup.ObbBackupService"));
3694            BackupManagerService.this.mContext.bindServiceAsUser(
3695                    obbIntent, this, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM);
3696        }
3697
3698        public void tearDown() {
3699            BackupManagerService.this.mContext.unbindService(this);
3700        }
3701
3702        public boolean backupObbs(PackageInfo pkg, OutputStream out) {
3703            boolean success = false;
3704            waitForConnection();
3705
3706            ParcelFileDescriptor[] pipes = null;
3707            try {
3708                pipes = ParcelFileDescriptor.createPipe();
3709                int token = generateRandomIntegerToken();
3710                prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL,
3711                        null, OP_TYPE_BACKUP_WAIT);
3712                mService.backupObbs(pkg.packageName, pipes[1], token, mBackupManagerBinder);
3713                routeSocketDataToOutput(pipes[0], out);
3714                success = waitUntilOperationComplete(token);
3715            } catch (Exception e) {
3716                Slog.w(TAG, "Unable to back up OBBs for " + pkg, e);
3717            } finally {
3718                try {
3719                    out.flush();
3720                    if (pipes != null) {
3721                        if (pipes[0] != null) pipes[0].close();
3722                        if (pipes[1] != null) pipes[1].close();
3723                    }
3724                } catch (IOException e) {
3725                    Slog.w(TAG, "I/O error closing down OBB backup", e);
3726                }
3727            }
3728            return success;
3729        }
3730
3731        public void restoreObbFile(String pkgName, ParcelFileDescriptor data,
3732                long fileSize, int type, String path, long mode, long mtime,
3733                int token, IBackupManager callbackBinder) {
3734            waitForConnection();
3735
3736            try {
3737                mService.restoreObbFile(pkgName, data, fileSize, type, path, mode, mtime,
3738                        token, callbackBinder);
3739            } catch (Exception e) {
3740                Slog.w(TAG, "Unable to restore OBBs for " + pkgName, e);
3741            }
3742        }
3743
3744        private void waitForConnection() {
3745            synchronized (this) {
3746                while (mService == null) {
3747                    if (MORE_DEBUG) Slog.i(TAG, "...waiting for OBB service binding...");
3748                    try {
3749                        this.wait();
3750                    } catch (InterruptedException e) { /* never interrupted */ }
3751                }
3752                if (MORE_DEBUG) Slog.i(TAG, "Connected to OBB service; continuing");
3753            }
3754        }
3755
3756        @Override
3757        public void onServiceConnected(ComponentName name, IBinder service) {
3758            synchronized (this) {
3759                mService = IObbBackupService.Stub.asInterface(service);
3760                if (MORE_DEBUG) Slog.i(TAG, "OBB service connection " + mService
3761                        + " connected on " + this);
3762                this.notifyAll();
3763            }
3764        }
3765
3766        @Override
3767        public void onServiceDisconnected(ComponentName name) {
3768            synchronized (this) {
3769                mService = null;
3770                if (MORE_DEBUG) Slog.i(TAG, "OBB service connection disconnected on " + this);
3771                this.notifyAll();
3772            }
3773        }
3774
3775    }
3776
3777    static void routeSocketDataToOutput(ParcelFileDescriptor inPipe, OutputStream out)
3778            throws IOException {
3779        // We do not take close() responsibility for the pipe FD
3780        FileInputStream raw = new FileInputStream(inPipe.getFileDescriptor());
3781        DataInputStream in = new DataInputStream(raw);
3782
3783        byte[] buffer = new byte[32 * 1024];
3784        int chunkTotal;
3785        while ((chunkTotal = in.readInt()) > 0) {
3786            while (chunkTotal > 0) {
3787                int toRead = (chunkTotal > buffer.length) ? buffer.length : chunkTotal;
3788                int nRead = in.read(buffer, 0, toRead);
3789                out.write(buffer, 0, nRead);
3790                chunkTotal -= nRead;
3791            }
3792        }
3793    }
3794
3795    @Override
3796    public void tearDownAgentAndKill(ApplicationInfo app) {
3797        if (app == null) {
3798            // Null means the system package, so just quietly move on.  :)
3799            return;
3800        }
3801
3802        try {
3803            // unbind and tidy up even on timeout or failure, just in case
3804            mActivityManager.unbindBackupAgent(app);
3805
3806            // The agent was running with a stub Application object, so shut it down.
3807            // !!! We hardcode the confirmation UI's package name here rather than use a
3808            //     manifest flag!  TODO something less direct.
3809            if (app.uid >= Process.FIRST_APPLICATION_UID
3810                    && !app.packageName.equals("com.android.backupconfirm")) {
3811                if (MORE_DEBUG) Slog.d(TAG, "Killing agent host process");
3812                mActivityManager.killApplicationProcess(app.processName, app.uid);
3813            } else {
3814                if (MORE_DEBUG) Slog.d(TAG, "Not killing after operation: " + app.processName);
3815            }
3816        } catch (RemoteException e) {
3817            Slog.d(TAG, "Lost app trying to shut down");
3818        }
3819    }
3820
3821    // Core logic for performing one package's full backup, gathering the tarball from the
3822    // application and emitting it to the designated OutputStream.
3823
3824    // Callout from the engine to an interested participant that might need to communicate
3825    // with the agent prior to asking it to move data
3826    interface FullBackupPreflight {
3827        /**
3828         * Perform the preflight operation necessary for the given package.
3829         * @param pkg The name of the package being proposed for full-data backup
3830         * @param agent Live BackupAgent binding to the target app's agent
3831         * @return BackupTransport.TRANSPORT_OK to proceed with the backup operation,
3832         *         or one of the other BackupTransport.* error codes as appropriate
3833         */
3834        int preflightFullBackup(PackageInfo pkg, IBackupAgent agent);
3835
3836        long getExpectedSizeOrErrorCode();
3837    };
3838
3839    class FullBackupEngine {
3840        OutputStream mOutput;
3841        FullBackupPreflight mPreflightHook;
3842        BackupRestoreTask mTimeoutMonitor;
3843        IBackupAgent mAgent;
3844        File mFilesDir;
3845        File mManifestFile;
3846        File mMetadataFile;
3847        boolean mIncludeApks;
3848        PackageInfo mPkg;
3849        private final long mQuota;
3850        private final int mOpToken;
3851
3852        class FullBackupRunner implements Runnable {
3853            PackageInfo mPackage;
3854            byte[] mWidgetData;
3855            IBackupAgent mAgent;
3856            ParcelFileDescriptor mPipe;
3857            int mToken;
3858            boolean mSendApk;
3859            boolean mWriteManifest;
3860
3861            FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
3862                             int token, boolean sendApk, boolean writeManifest, byte[] widgetData)
3863                    throws IOException {
3864                mPackage = pack;
3865                mWidgetData = widgetData;
3866                mAgent = agent;
3867                mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
3868                mToken = token;
3869                mSendApk = sendApk;
3870                mWriteManifest = writeManifest;
3871            }
3872
3873            @Override
3874            public void run() {
3875                try {
3876                    FullBackupDataOutput output = new FullBackupDataOutput(mPipe);
3877
3878                    if (mWriteManifest) {
3879                        final boolean writeWidgetData = mWidgetData != null;
3880                        if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
3881                        writeAppManifest(mPackage, mPackageManager, mManifestFile, mSendApk, writeWidgetData);
3882                        FullBackup.backupToTar(mPackage.packageName, null, null,
3883                                mFilesDir.getAbsolutePath(),
3884                                mManifestFile.getAbsolutePath(),
3885                                output);
3886                        mManifestFile.delete();
3887
3888                        // We only need to write a metadata file if we have widget data to stash
3889                        if (writeWidgetData) {
3890                            writeMetadata(mPackage, mMetadataFile, mWidgetData);
3891                            FullBackup.backupToTar(mPackage.packageName, null, null,
3892                                    mFilesDir.getAbsolutePath(),
3893                                    mMetadataFile.getAbsolutePath(),
3894                                    output);
3895                            mMetadataFile.delete();
3896                        }
3897                    }
3898
3899                    if (mSendApk) {
3900                        writeApkToBackup(mPackage, output);
3901                    }
3902
3903                    final boolean isSharedStorage =
3904                            mPackage.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
3905                    final long timeout = isSharedStorage ?
3906                            TIMEOUT_SHARED_BACKUP_INTERVAL : TIMEOUT_FULL_BACKUP_INTERVAL;
3907
3908                    if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
3909                    prepareOperationTimeout(mToken, timeout, mTimeoutMonitor /* in parent class */,
3910                            OP_TYPE_BACKUP_WAIT);
3911                    mAgent.doFullBackup(mPipe, mQuota, mToken, mBackupManagerBinder);
3912                } catch (IOException e) {
3913                    Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
3914                } catch (RemoteException e) {
3915                    Slog.e(TAG, "Remote agent vanished during full backup of "
3916                            + mPackage.packageName);
3917                } finally {
3918                    try {
3919                        mPipe.close();
3920                    } catch (IOException e) {}
3921                }
3922            }
3923        }
3924
3925        FullBackupEngine(OutputStream output, FullBackupPreflight preflightHook, PackageInfo pkg,
3926                         boolean alsoApks, BackupRestoreTask timeoutMonitor, long quota, int opToken) {
3927            mOutput = output;
3928            mPreflightHook = preflightHook;
3929            mPkg = pkg;
3930            mIncludeApks = alsoApks;
3931            mTimeoutMonitor = timeoutMonitor;
3932            mFilesDir = new File("/data/system");
3933            mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
3934            mMetadataFile = new File(mFilesDir, BACKUP_METADATA_FILENAME);
3935            mQuota = quota;
3936            mOpToken = opToken;
3937        }
3938
3939        public int preflightCheck() throws RemoteException {
3940            if (mPreflightHook == null) {
3941                if (MORE_DEBUG) {
3942                    Slog.v(TAG, "No preflight check");
3943                }
3944                return BackupTransport.TRANSPORT_OK;
3945            }
3946            if (initializeAgent()) {
3947                int result = mPreflightHook.preflightFullBackup(mPkg, mAgent);
3948                if (MORE_DEBUG) {
3949                    Slog.v(TAG, "preflight returned " + result);
3950                }
3951                return result;
3952            } else {
3953                Slog.w(TAG, "Unable to bind to full agent for " + mPkg.packageName);
3954                return BackupTransport.AGENT_ERROR;
3955            }
3956        }
3957
3958        public int backupOnePackage() throws RemoteException {
3959            int result = BackupTransport.AGENT_ERROR;
3960
3961            if (initializeAgent()) {
3962                ParcelFileDescriptor[] pipes = null;
3963                try {
3964                    pipes = ParcelFileDescriptor.createPipe();
3965
3966                    ApplicationInfo app = mPkg.applicationInfo;
3967                    final boolean isSharedStorage =
3968                            mPkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
3969                    final boolean sendApk = mIncludeApks
3970                            && !isSharedStorage
3971                            && ((app.privateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) == 0)
3972                            && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
3973                            (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
3974
3975                    // TODO: http://b/22388012
3976                    byte[] widgetBlob = AppWidgetBackupBridge.getWidgetState(mPkg.packageName,
3977                            UserHandle.USER_SYSTEM);
3978
3979                    FullBackupRunner runner = new FullBackupRunner(mPkg, mAgent, pipes[1],
3980                            mOpToken, sendApk, !isSharedStorage, widgetBlob);
3981                    pipes[1].close();   // the runner has dup'd it
3982                    pipes[1] = null;
3983                    Thread t = new Thread(runner, "app-data-runner");
3984                    t.start();
3985
3986                    // Now pull data from the app and stuff it into the output
3987                    routeSocketDataToOutput(pipes[0], mOutput);
3988
3989                    if (!waitUntilOperationComplete(mOpToken)) {
3990                        Slog.e(TAG, "Full backup failed on package " + mPkg.packageName);
3991                    } else {
3992                        if (MORE_DEBUG) {
3993                            Slog.d(TAG, "Full package backup success: " + mPkg.packageName);
3994                        }
3995                        result = BackupTransport.TRANSPORT_OK;
3996                    }
3997                } catch (IOException e) {
3998                    Slog.e(TAG, "Error backing up " + mPkg.packageName + ": " + e.getMessage());
3999                    result = BackupTransport.AGENT_ERROR;
4000                } finally {
4001                    try {
4002                        // flush after every package
4003                        mOutput.flush();
4004                        if (pipes != null) {
4005                            if (pipes[0] != null) pipes[0].close();
4006                            if (pipes[1] != null) pipes[1].close();
4007                        }
4008                    } catch (IOException e) {
4009                        Slog.w(TAG, "Error bringing down backup stack");
4010                        result = BackupTransport.TRANSPORT_ERROR;
4011                    }
4012                }
4013            } else {
4014                Slog.w(TAG, "Unable to bind to full agent for " + mPkg.packageName);
4015            }
4016            tearDown();
4017            return result;
4018        }
4019
4020        public void sendQuotaExceeded(final long backupDataBytes, final long quotaBytes) {
4021            if (initializeAgent()) {
4022                try {
4023                    mAgent.doQuotaExceeded(backupDataBytes, quotaBytes);
4024                } catch (RemoteException e) {
4025                    Slog.e(TAG, "Remote exception while telling agent about quota exceeded");
4026                }
4027            }
4028        }
4029
4030        private boolean initializeAgent() {
4031            if (mAgent == null) {
4032                if (MORE_DEBUG) {
4033                    Slog.d(TAG, "Binding to full backup agent : " + mPkg.packageName);
4034                }
4035                mAgent = bindToAgentSynchronous(mPkg.applicationInfo,
4036                        ApplicationThreadConstants.BACKUP_MODE_FULL);
4037            }
4038            return mAgent != null;
4039        }
4040
4041        private void writeApkToBackup(PackageInfo pkg, FullBackupDataOutput output) {
4042            // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
4043            // TODO: handle backing up split APKs
4044            final String appSourceDir = pkg.applicationInfo.getBaseCodePath();
4045            final String apkDir = new File(appSourceDir).getParent();
4046            FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
4047                    apkDir, appSourceDir, output);
4048
4049            // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
4050            // doesn't have access to external storage.
4051
4052            // Save associated .obb content if it exists and we did save the apk
4053            // check for .obb and save those too
4054            // TODO: http://b/22388012
4055            final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_SYSTEM);
4056            final File obbDir = userEnv.buildExternalStorageAppObbDirs(pkg.packageName)[0];
4057            if (obbDir != null) {
4058                if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
4059                File[] obbFiles = obbDir.listFiles();
4060                if (obbFiles != null) {
4061                    final String obbDirName = obbDir.getAbsolutePath();
4062                    for (File obb : obbFiles) {
4063                        FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
4064                                obbDirName, obb.getAbsolutePath(), output);
4065                    }
4066                }
4067            }
4068        }
4069
4070        // Widget metadata format. All header entries are strings ending in LF:
4071        //
4072        // Version 1 header:
4073        //     BACKUP_METADATA_VERSION, currently "1"
4074        //     package name
4075        //
4076        // File data (all integers are binary in network byte order)
4077        // *N: 4 : integer token identifying which metadata blob
4078        //     4 : integer size of this blob = N
4079        //     N : raw bytes of this metadata blob
4080        //
4081        // Currently understood blobs (always in network byte order):
4082        //
4083        //     widgets : metadata token = 0x01FFED01 (BACKUP_WIDGET_METADATA_TOKEN)
4084        //
4085        // Unrecognized blobs are *ignored*, not errors.
4086        private void writeMetadata(PackageInfo pkg, File destination, byte[] widgetData)
4087                throws IOException {
4088            StringBuilder b = new StringBuilder(512);
4089            StringBuilderPrinter printer = new StringBuilderPrinter(b);
4090            printer.println(Integer.toString(BACKUP_METADATA_VERSION));
4091            printer.println(pkg.packageName);
4092
4093            FileOutputStream fout = new FileOutputStream(destination);
4094            BufferedOutputStream bout = new BufferedOutputStream(fout);
4095            DataOutputStream out = new DataOutputStream(bout);
4096            bout.write(b.toString().getBytes());    // bypassing DataOutputStream
4097
4098            if (widgetData != null && widgetData.length > 0) {
4099                out.writeInt(BACKUP_WIDGET_METADATA_TOKEN);
4100                out.writeInt(widgetData.length);
4101                out.write(widgetData);
4102            }
4103            bout.flush();
4104            out.close();
4105
4106            // As with the manifest file, guarantee idempotence of the archive metadata
4107            // for the widget block by using a fixed mtime on the transient file.
4108            destination.setLastModified(0);
4109        }
4110
4111        private void tearDown() {
4112            if (mPkg != null) {
4113                tearDownAgentAndKill(mPkg.applicationInfo);
4114            }
4115        }
4116    }
4117
4118    static void writeAppManifest(PackageInfo pkg, PackageManager packageManager, File manifestFile,
4119            boolean withApk, boolean withWidgets) throws IOException {
4120        // Manifest format. All data are strings ending in LF:
4121        //     BACKUP_MANIFEST_VERSION, currently 1
4122        //
4123        // Version 1:
4124        //     package name
4125        //     package's versionCode
4126        //     platform versionCode
4127        //     getInstallerPackageName() for this package (maybe empty)
4128        //     boolean: "1" if archive includes .apk; any other string means not
4129        //     number of signatures == N
4130        // N*:    signature byte array in ascii format per Signature.toCharsString()
4131        StringBuilder builder = new StringBuilder(4096);
4132        StringBuilderPrinter printer = new StringBuilderPrinter(builder);
4133
4134        printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
4135        printer.println(pkg.packageName);
4136        printer.println(Integer.toString(pkg.versionCode));
4137        printer.println(Integer.toString(Build.VERSION.SDK_INT));
4138
4139        String installerName = packageManager.getInstallerPackageName(pkg.packageName);
4140        printer.println((installerName != null) ? installerName : "");
4141
4142        printer.println(withApk ? "1" : "0");
4143        if (pkg.signatures == null) {
4144            printer.println("0");
4145        } else {
4146            printer.println(Integer.toString(pkg.signatures.length));
4147            for (Signature sig : pkg.signatures) {
4148                printer.println(sig.toCharsString());
4149            }
4150        }
4151
4152        FileOutputStream outstream = new FileOutputStream(manifestFile);
4153        outstream.write(builder.toString().getBytes());
4154        outstream.close();
4155
4156        // We want the manifest block in the archive stream to be idempotent:
4157        // each time we generate a backup stream for the app, we want the manifest
4158        // block to be identical.  The underlying tar mechanism sees it as a file,
4159        // though, and will propagate its mtime, causing the tar header to vary.
4160        // Avoid this problem by pinning the mtime to zero.
4161        manifestFile.setLastModified(0);
4162    }
4163
4164    // Generic driver skeleton for full backup operations
4165    abstract class FullBackupTask implements Runnable {
4166        IFullBackupRestoreObserver mObserver;
4167
4168        FullBackupTask(IFullBackupRestoreObserver observer) {
4169            mObserver = observer;
4170        }
4171
4172        // wrappers for observer use
4173        final void sendStartBackup() {
4174            if (mObserver != null) {
4175                try {
4176                    mObserver.onStartBackup();
4177                } catch (RemoteException e) {
4178                    Slog.w(TAG, "full backup observer went away: startBackup");
4179                    mObserver = null;
4180                }
4181            }
4182        }
4183
4184        final void sendOnBackupPackage(String name) {
4185            if (mObserver != null) {
4186                try {
4187                    // TODO: use a more user-friendly name string
4188                    mObserver.onBackupPackage(name);
4189                } catch (RemoteException e) {
4190                    Slog.w(TAG, "full backup observer went away: backupPackage");
4191                    mObserver = null;
4192                }
4193            }
4194        }
4195
4196        final void sendEndBackup() {
4197            if (mObserver != null) {
4198                try {
4199                    mObserver.onEndBackup();
4200                } catch (RemoteException e) {
4201                    Slog.w(TAG, "full backup observer went away: endBackup");
4202                    mObserver = null;
4203                }
4204            }
4205        }
4206    }
4207
4208    boolean deviceIsEncrypted() {
4209        try {
4210            return mStorageManager.getEncryptionState()
4211                     != StorageManager.ENCRYPTION_STATE_NONE
4212                && mStorageManager.getPasswordType()
4213                     != StorageManager.CRYPT_TYPE_DEFAULT;
4214        } catch (Exception e) {
4215            // If we can't talk to the storagemanager service we have a serious problem; fail
4216            // "secure" i.e. assuming that the device is encrypted.
4217            Slog.e(TAG, "Unable to communicate with storagemanager service: " + e.getMessage());
4218            return true;
4219        }
4220    }
4221
4222    // Full backup task variant used for adb backup
4223    class PerformAdbBackupTask extends FullBackupTask implements BackupRestoreTask {
4224        FullBackupEngine mBackupEngine;
4225        final AtomicBoolean mLatch;
4226
4227        ParcelFileDescriptor mOutputFile;
4228        DeflaterOutputStream mDeflater;
4229        boolean mIncludeApks;
4230        boolean mIncludeObbs;
4231        boolean mIncludeShared;
4232        boolean mDoWidgets;
4233        boolean mAllApps;
4234        boolean mIncludeSystem;
4235        boolean mCompress;
4236        boolean mKeyValue;
4237        ArrayList<String> mPackages;
4238        PackageInfo mCurrentTarget;
4239        String mCurrentPassword;
4240        String mEncryptPassword;
4241        private final int mCurrentOpToken;
4242
4243        PerformAdbBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
4244                boolean includeApks, boolean includeObbs, boolean includeShared, boolean doWidgets,
4245                String curPassword, String encryptPassword, boolean doAllApps, boolean doSystem,
4246                boolean doCompress, boolean doKeyValue, String[] packages, AtomicBoolean latch) {
4247            super(observer);
4248            mCurrentOpToken = generateRandomIntegerToken();
4249            mLatch = latch;
4250
4251            mOutputFile = fd;
4252            mIncludeApks = includeApks;
4253            mIncludeObbs = includeObbs;
4254            mIncludeShared = includeShared;
4255            mDoWidgets = doWidgets;
4256            mAllApps = doAllApps;
4257            mIncludeSystem = doSystem;
4258            mPackages = (packages == null)
4259                    ? new ArrayList<String>()
4260                    : new ArrayList<String>(Arrays.asList(packages));
4261            mCurrentPassword = curPassword;
4262            // when backing up, if there is a current backup password, we require that
4263            // the user use a nonempty encryption password as well.  if one is supplied
4264            // in the UI we use that, but if the UI was left empty we fall back to the
4265            // current backup password (which was supplied by the user as well).
4266            if (encryptPassword == null || "".equals(encryptPassword)) {
4267                mEncryptPassword = curPassword;
4268            } else {
4269                mEncryptPassword = encryptPassword;
4270            }
4271            if (MORE_DEBUG) {
4272                Slog.w(TAG, "Encrypting backup with passphrase=" + mEncryptPassword);
4273            }
4274            mCompress = doCompress;
4275            mKeyValue = doKeyValue;
4276        }
4277
4278        void addPackagesToSet(TreeMap<String, PackageInfo> set, List<String> pkgNames) {
4279            for (String pkgName : pkgNames) {
4280                if (!set.containsKey(pkgName)) {
4281                    try {
4282                        PackageInfo info = mPackageManager.getPackageInfo(pkgName,
4283                                PackageManager.GET_SIGNATURES);
4284                        set.put(pkgName, info);
4285                    } catch (NameNotFoundException e) {
4286                        Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
4287                    }
4288                }
4289            }
4290        }
4291
4292        private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
4293                OutputStream ofstream) throws Exception {
4294            // User key will be used to encrypt the master key.
4295            byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
4296            SecretKey userKey = buildPasswordKey(PBKDF_CURRENT, mEncryptPassword, newUserSalt,
4297                    PBKDF2_HASH_ROUNDS);
4298
4299            // the master key is random for each backup
4300            byte[] masterPw = new byte[256 / 8];
4301            mRng.nextBytes(masterPw);
4302            byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
4303
4304            // primary encryption of the datastream with the random key
4305            Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
4306            SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
4307            c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
4308            OutputStream finalOutput = new CipherOutputStream(ofstream, c);
4309
4310            // line 4: name of encryption algorithm
4311            headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
4312            headerbuf.append('\n');
4313            // line 5: user password salt [hex]
4314            headerbuf.append(byteArrayToHex(newUserSalt));
4315            headerbuf.append('\n');
4316            // line 6: master key checksum salt [hex]
4317            headerbuf.append(byteArrayToHex(checksumSalt));
4318            headerbuf.append('\n');
4319            // line 7: number of PBKDF2 rounds used [decimal]
4320            headerbuf.append(PBKDF2_HASH_ROUNDS);
4321            headerbuf.append('\n');
4322
4323            // line 8: IV of the user key [hex]
4324            Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
4325            mkC.init(Cipher.ENCRYPT_MODE, userKey);
4326
4327            byte[] IV = mkC.getIV();
4328            headerbuf.append(byteArrayToHex(IV));
4329            headerbuf.append('\n');
4330
4331            // line 9: master IV + key blob, encrypted by the user key [hex].  Blob format:
4332            //    [byte] IV length = Niv
4333            //    [array of Niv bytes] IV itself
4334            //    [byte] master key length = Nmk
4335            //    [array of Nmk bytes] master key itself
4336            //    [byte] MK checksum hash length = Nck
4337            //    [array of Nck bytes] master key checksum hash
4338            //
4339            // The checksum is the (master key + checksum salt), run through the
4340            // stated number of PBKDF2 rounds
4341            IV = c.getIV();
4342            byte[] mk = masterKeySpec.getEncoded();
4343            byte[] checksum = makeKeyChecksum(PBKDF_CURRENT, masterKeySpec.getEncoded(),
4344                    checksumSalt, PBKDF2_HASH_ROUNDS);
4345
4346            ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
4347                    + checksum.length + 3);
4348            DataOutputStream mkOut = new DataOutputStream(blob);
4349            mkOut.writeByte(IV.length);
4350            mkOut.write(IV);
4351            mkOut.writeByte(mk.length);
4352            mkOut.write(mk);
4353            mkOut.writeByte(checksum.length);
4354            mkOut.write(checksum);
4355            mkOut.flush();
4356            byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
4357            headerbuf.append(byteArrayToHex(encryptedMk));
4358            headerbuf.append('\n');
4359
4360            return finalOutput;
4361        }
4362
4363        private void finalizeBackup(OutputStream out) {
4364            try {
4365                // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
4366                byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
4367                out.write(eof);
4368            } catch (IOException e) {
4369                Slog.w(TAG, "Error attempting to finalize backup stream");
4370            }
4371        }
4372
4373        @Override
4374        public void run() {
4375            String includeKeyValue = mKeyValue ? ", including key-value backups" : "";
4376            Slog.i(TAG, "--- Performing adb backup" + includeKeyValue + " ---");
4377
4378            TreeMap<String, PackageInfo> packagesToBackup = new TreeMap<String, PackageInfo>();
4379            FullBackupObbConnection obbConnection = new FullBackupObbConnection();
4380            obbConnection.establish();  // we'll want this later
4381
4382            sendStartBackup();
4383
4384            // doAllApps supersedes the package set if any
4385            if (mAllApps) {
4386                List<PackageInfo> allPackages = mPackageManager.getInstalledPackages(
4387                        PackageManager.GET_SIGNATURES);
4388                for (int i = 0; i < allPackages.size(); i++) {
4389                    PackageInfo pkg = allPackages.get(i);
4390                    // Exclude system apps if we've been asked to do so
4391                    if (mIncludeSystem == true
4392                            || ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)) {
4393                        packagesToBackup.put(pkg.packageName, pkg);
4394                    }
4395                }
4396            }
4397
4398            // If we're doing widget state as well, ensure that we have all the involved
4399            // host & provider packages in the set
4400            if (mDoWidgets) {
4401                // TODO: http://b/22388012
4402                List<String> pkgs =
4403                        AppWidgetBackupBridge.getWidgetParticipants(UserHandle.USER_SYSTEM);
4404                if (pkgs != null) {
4405                    if (MORE_DEBUG) {
4406                        Slog.i(TAG, "Adding widget participants to backup set:");
4407                        StringBuilder sb = new StringBuilder(128);
4408                        sb.append("   ");
4409                        for (String s : pkgs) {
4410                            sb.append(' ');
4411                            sb.append(s);
4412                        }
4413                        Slog.i(TAG, sb.toString());
4414                    }
4415                    addPackagesToSet(packagesToBackup, pkgs);
4416                }
4417            }
4418
4419            // Now process the command line argument packages, if any. Note that explicitly-
4420            // named system-partition packages will be included even if includeSystem was
4421            // set to false.
4422            if (mPackages != null) {
4423                addPackagesToSet(packagesToBackup, mPackages);
4424            }
4425
4426            // Now we cull any inapplicable / inappropriate packages from the set.  This
4427            // includes the special shared-storage agent package; we handle that one
4428            // explicitly at the end of the backup pass. Packages supporting key-value backup are
4429            // added to their own queue, and handled after packages supporting fullbackup.
4430            ArrayList<PackageInfo> keyValueBackupQueue = new ArrayList<>();
4431            Iterator<Entry<String, PackageInfo>> iter = packagesToBackup.entrySet().iterator();
4432            while (iter.hasNext()) {
4433                PackageInfo pkg = iter.next().getValue();
4434                if (!appIsEligibleForBackup(pkg.applicationInfo, mPackageManager)
4435                        || appIsStopped(pkg.applicationInfo)) {
4436                    iter.remove();
4437                    if (DEBUG) {
4438                        Slog.i(TAG, "Package " + pkg.packageName
4439                                + " is not eligible for backup, removing.");
4440                    }
4441                } else if (appIsKeyValueOnly(pkg)) {
4442                    iter.remove();
4443                    if (DEBUG) {
4444                        Slog.i(TAG, "Package " + pkg.packageName
4445                                + " is key-value.");
4446                    }
4447                    keyValueBackupQueue.add(pkg);
4448                }
4449            }
4450
4451            // flatten the set of packages now so we can explicitly control the ordering
4452            ArrayList<PackageInfo> backupQueue =
4453                    new ArrayList<PackageInfo>(packagesToBackup.values());
4454            FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
4455            OutputStream out = null;
4456
4457            PackageInfo pkg = null;
4458            try {
4459                boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
4460
4461                // Only allow encrypted backups of encrypted devices
4462                if (deviceIsEncrypted() && !encrypting) {
4463                    Slog.e(TAG, "Unencrypted backup of encrypted device; aborting");
4464                    return;
4465                }
4466
4467                OutputStream finalOutput = ofstream;
4468
4469                // Verify that the given password matches the currently-active
4470                // backup password, if any
4471                if (!backupPasswordMatches(mCurrentPassword)) {
4472                    if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
4473                    return;
4474                }
4475
4476                // Write the global file header.  All strings are UTF-8 encoded; lines end
4477                // with a '\n' byte.  Actual backup data begins immediately following the
4478                // final '\n'.
4479                //
4480                // line 1: "ANDROID BACKUP"
4481                // line 2: backup file format version, currently "5"
4482                // line 3: compressed?  "0" if not compressed, "1" if compressed.
4483                // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
4484                //
4485                // When line 4 is not "none", then additional header data follows:
4486                //
4487                // line 5: user password salt [hex]
4488                // line 6: master key checksum salt [hex]
4489                // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
4490                // line 8: IV of the user key [hex]
4491                // line 9: master key blob [hex]
4492                //     IV of the master key, master key itself, master key checksum hash
4493                //
4494                // The master key checksum is the master key plus its checksum salt, run through
4495                // 10k rounds of PBKDF2.  This is used to verify that the user has supplied the
4496                // correct password for decrypting the archive:  the master key decrypted from
4497                // the archive using the user-supplied password is also run through PBKDF2 in
4498                // this way, and if the result does not match the checksum as stored in the
4499                // archive, then we know that the user-supplied password does not match the
4500                // archive's.
4501                StringBuilder headerbuf = new StringBuilder(1024);
4502
4503                headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
4504                headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
4505                headerbuf.append(mCompress ? "\n1\n" : "\n0\n");
4506
4507                try {
4508                    // Set up the encryption stage if appropriate, and emit the correct header
4509                    if (encrypting) {
4510                        finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
4511                    } else {
4512                        headerbuf.append("none\n");
4513                    }
4514
4515                    byte[] header = headerbuf.toString().getBytes("UTF-8");
4516                    ofstream.write(header);
4517
4518                    // Set up the compression stage feeding into the encryption stage (if any)
4519                    if (mCompress) {
4520                        Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
4521                        finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
4522                    }
4523
4524                    out = finalOutput;
4525                } catch (Exception e) {
4526                    // Should never happen!
4527                    Slog.e(TAG, "Unable to emit archive header", e);
4528                    return;
4529                }
4530
4531                // Shared storage if requested
4532                if (mIncludeShared) {
4533                    try {
4534                        pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
4535                        backupQueue.add(pkg);
4536                    } catch (NameNotFoundException e) {
4537                        Slog.e(TAG, "Unable to find shared-storage backup handler");
4538                    }
4539                }
4540
4541                // Now actually run the constructed backup sequence for full backup
4542                int N = backupQueue.size();
4543                for (int i = 0; i < N; i++) {
4544                    pkg = backupQueue.get(i);
4545                    if (DEBUG) {
4546                        Slog.i(TAG,"--- Performing full backup for package " + pkg.packageName
4547                                + " ---");
4548                    }
4549                    final boolean isSharedStorage =
4550                            pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
4551
4552                    mBackupEngine = new FullBackupEngine(out, null, pkg, mIncludeApks, this, Long.MAX_VALUE, mCurrentOpToken);
4553                    sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
4554
4555                    // Don't need to check preflight result as there is no preflight hook.
4556                    mCurrentTarget = pkg;
4557                    mBackupEngine.backupOnePackage();
4558
4559                    // after the app's agent runs to handle its private filesystem
4560                    // contents, back up any OBB content it has on its behalf.
4561                    if (mIncludeObbs) {
4562                        boolean obbOkay = obbConnection.backupObbs(pkg, out);
4563                        if (!obbOkay) {
4564                            throw new RuntimeException("Failure writing OBB stack for " + pkg);
4565                        }
4566                    }
4567                }
4568                // And for key-value backup if enabled
4569                if (mKeyValue) {
4570                    for (PackageInfo keyValuePackage : keyValueBackupQueue) {
4571                        if (DEBUG) {
4572                            Slog.i(TAG, "--- Performing key-value backup for package "
4573                                    + keyValuePackage.packageName + " ---");
4574                        }
4575                        KeyValueAdbBackupEngine kvBackupEngine =
4576                                new KeyValueAdbBackupEngine(out, keyValuePackage,
4577                                        BackupManagerService.this,
4578                                        mPackageManager, mBaseStateDir, mDataDir);
4579                        sendOnBackupPackage(keyValuePackage.packageName);
4580                        kvBackupEngine.backupOnePackage();
4581                    }
4582                }
4583
4584                // Done!
4585                finalizeBackup(out);
4586            } catch (RemoteException e) {
4587                Slog.e(TAG, "App died during full backup");
4588            } catch (Exception e) {
4589                Slog.e(TAG, "Internal exception during full backup", e);
4590            } finally {
4591                try {
4592                    if (out != null) {
4593                        out.flush();
4594                        out.close();
4595                    }
4596                    mOutputFile.close();
4597                } catch (IOException e) {
4598                    /* nothing we can do about this */
4599                }
4600                synchronized (mLatch) {
4601                    mLatch.set(true);
4602                    mLatch.notifyAll();
4603                }
4604                sendEndBackup();
4605                obbConnection.tearDown();
4606                if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
4607                mWakelock.release();
4608            }
4609        }
4610
4611        // BackupRestoreTask methods, used for timeout handling
4612        @Override
4613        public void execute() {
4614            // Unused
4615        }
4616
4617        @Override
4618        public void operationComplete(long result) {
4619            // Unused
4620        }
4621
4622        @Override
4623        public void handleCancel(boolean cancelAll) {
4624            final PackageInfo target = mCurrentTarget;
4625            if (DEBUG) {
4626                Slog.w(TAG, "adb backup cancel of " + target);
4627            }
4628            if (target != null) {
4629                tearDownAgentAndKill(mCurrentTarget.applicationInfo);
4630            }
4631            removeOperation(mCurrentOpToken);
4632        }
4633    }
4634
4635    /**
4636     * Full backup task extension used for transport-oriented operation.
4637     *
4638     * Flow:
4639     * For each requested package:
4640     *     - Spin off a new SinglePackageBackupRunner (mBackupRunner) for the current package.
4641     *     - Wait until preflight is complete. (mBackupRunner.getPreflightResultBlocking())
4642     *     - If preflight data size is within limit, start reading data from agent pipe and writing
4643     *       to transport pipe. While there is data to send, call transport.sendBackupData(int) to
4644     *       tell the transport how many bytes to expect on its pipe.
4645     *     - After sending all data, call transport.finishBackup() if things went well. And
4646     *       transport.cancelFullBackup() otherwise.
4647     *
4648     * Interactions with mCurrentOperations:
4649     *     - An entry for this object is added to mCurrentOperations for the entire lifetime of this
4650     *       object. Used to cancel the operation.
4651     *     - SinglePackageBackupRunner and SinglePackageBackupPreflight will put ephemeral entries
4652     *       to get timeouts or operation complete callbacks.
4653     *
4654     * Handling cancels:
4655     *     - The contract we provide is that the task won't interact with the transport after
4656     *       handleCancel() is done executing.
4657     *     - This task blocks at 3 points: 1. Preflight result check 2. Reading on agent side pipe
4658     *       and 3. Get backup result from mBackupRunner.
4659     *     - Bubbling up handleCancel to mBackupRunner handles all 3: 1. Calls handleCancel on the
4660     *       preflight operation which counts down on the preflight latch. 2. Tears down the agent,
4661     *       so read() returns -1. 3. Notifies mCurrentOpLock which unblocks
4662     *       mBackupRunner.getBackupResultBlocking().
4663     */
4664    class PerformFullTransportBackupTask extends FullBackupTask implements BackupRestoreTask {
4665        static final String TAG = "PFTBT";
4666
4667        private final Object mCancelLock = new Object();
4668
4669        ArrayList<PackageInfo> mPackages;
4670        PackageInfo mCurrentPackage;
4671        boolean mUpdateSchedule;
4672        CountDownLatch mLatch;
4673        FullBackupJob mJob;             // if a scheduled job needs to be finished afterwards
4674        IBackupObserver mBackupObserver;
4675        IBackupManagerMonitor mMonitor;
4676        boolean mUserInitiated;
4677        private volatile IBackupTransport mTransport;
4678        SinglePackageBackupRunner mBackupRunner;
4679        private final int mBackupRunnerOpToken;
4680
4681        // This is true when a backup operation for some package is in progress.
4682        private volatile boolean mIsDoingBackup;
4683        private volatile boolean mCancelAll;
4684        private final int mCurrentOpToken;
4685
4686        PerformFullTransportBackupTask(IFullBackupRestoreObserver observer,
4687                String[] whichPackages, boolean updateSchedule,
4688                FullBackupJob runningJob, CountDownLatch latch, IBackupObserver backupObserver,
4689                IBackupManagerMonitor monitor, boolean userInitiated) {
4690            super(observer);
4691            mUpdateSchedule = updateSchedule;
4692            mLatch = latch;
4693            mJob = runningJob;
4694            mPackages = new ArrayList<PackageInfo>(whichPackages.length);
4695            mBackupObserver = backupObserver;
4696            mMonitor = monitor;
4697            mUserInitiated = userInitiated;
4698            mCurrentOpToken = generateRandomIntegerToken();
4699            mBackupRunnerOpToken = generateRandomIntegerToken();
4700
4701            if (isBackupOperationInProgress()) {
4702                if (DEBUG) {
4703                    Slog.d(TAG, "Skipping full backup. A backup is already in progress.");
4704                }
4705                mCancelAll = true;
4706                return;
4707            }
4708
4709            registerTask();
4710
4711            for (String pkg : whichPackages) {
4712                try {
4713                    PackageInfo info = mPackageManager.getPackageInfo(pkg,
4714                            PackageManager.GET_SIGNATURES);
4715                    mCurrentPackage = info;
4716                    if (!appIsEligibleForBackup(info.applicationInfo, mPackageManager)) {
4717                        // Cull any packages that have indicated that backups are not permitted,
4718                        // that run as system-domain uids but do not define their own backup agents,
4719                        // as well as any explicit mention of the 'special' shared-storage agent
4720                        // package (we handle that one at the end).
4721                        if (MORE_DEBUG) {
4722                            Slog.d(TAG, "Ignoring ineligible package " + pkg);
4723                        }
4724                        mMonitor = monitorEvent(mMonitor,
4725                                BackupManagerMonitor.LOG_EVENT_ID_PACKAGE_INELIGIBLE,
4726                                mCurrentPackage,
4727                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
4728                                null);
4729                        sendBackupOnPackageResult(mBackupObserver, pkg,
4730                            BackupManager.ERROR_BACKUP_NOT_ALLOWED);
4731                        continue;
4732                    } else if (!appGetsFullBackup(info)) {
4733                        // Cull any packages that are found in the queue but now aren't supposed
4734                        // to get full-data backup operations.
4735                        if (MORE_DEBUG) {
4736                            Slog.d(TAG, "Ignoring full-data backup of key/value participant "
4737                                    + pkg);
4738                        }
4739                        mMonitor = monitorEvent(mMonitor,
4740                                BackupManagerMonitor.LOG_EVENT_ID_PACKAGE_KEY_VALUE_PARTICIPANT,
4741                                mCurrentPackage,
4742                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
4743                                null);
4744                        sendBackupOnPackageResult(mBackupObserver, pkg,
4745                                BackupManager.ERROR_BACKUP_NOT_ALLOWED);
4746                        continue;
4747                    } else if (appIsStopped(info.applicationInfo)) {
4748                        // Cull any packages in the 'stopped' state: they've either just been
4749                        // installed or have explicitly been force-stopped by the user.  In both
4750                        // cases we do not want to launch them for backup.
4751                        if (MORE_DEBUG) {
4752                            Slog.d(TAG, "Ignoring stopped package " + pkg);
4753                        }
4754                        mMonitor = monitorEvent(mMonitor,
4755                                BackupManagerMonitor.LOG_EVENT_ID_PACKAGE_STOPPED,
4756                                mCurrentPackage,
4757                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
4758                                null);
4759                        sendBackupOnPackageResult(mBackupObserver, pkg,
4760                                BackupManager.ERROR_BACKUP_NOT_ALLOWED);
4761                        continue;
4762                    }
4763                    mPackages.add(info);
4764                } catch (NameNotFoundException e) {
4765                    Slog.i(TAG, "Requested package " + pkg + " not found; ignoring");
4766                    mMonitor = monitorEvent(mMonitor,
4767                            BackupManagerMonitor.LOG_EVENT_ID_PACKAGE_NOT_FOUND,
4768                            mCurrentPackage,
4769                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
4770                            null);
4771                }
4772            }
4773        }
4774
4775        private void registerTask() {
4776            synchronized (mCurrentOpLock) {
4777                Slog.d(TAG, "backupmanager pftbt token=" + Integer.toHexString(mCurrentOpToken));
4778                mCurrentOperations.put(mCurrentOpToken, new Operation(OP_PENDING, this,
4779                        OP_TYPE_BACKUP));
4780            }
4781        }
4782
4783        private void unregisterTask() {
4784            removeOperation(mCurrentOpToken);
4785        }
4786
4787        @Override
4788        public void execute() {
4789            // Nothing to do.
4790        }
4791
4792        @Override
4793        public void handleCancel(boolean cancelAll) {
4794            synchronized (mCancelLock) {
4795                // We only support 'cancelAll = true' case for this task. Cancelling of a single package
4796
4797                // due to timeout is handled by SinglePackageBackupRunner and SinglePackageBackupPreflight.
4798
4799                if (!cancelAll) {
4800                    Slog.wtf(TAG, "Expected cancelAll to be true.");
4801                }
4802
4803                if (mCancelAll) {
4804                    Slog.d(TAG, "Ignoring duplicate cancel call.");
4805                    return;
4806                }
4807
4808                mCancelAll = true;
4809                if (mIsDoingBackup) {
4810                    BackupManagerService.this.handleCancel(mBackupRunnerOpToken, cancelAll);
4811                    try {
4812                        mTransport.cancelFullBackup();
4813                    } catch (RemoteException e) {
4814                        Slog.w(TAG, "Error calling cancelFullBackup() on transport: " + e);
4815                        // Can't do much.
4816                    }
4817                }
4818            }
4819        }
4820
4821        @Override
4822        public void operationComplete(long result) {
4823            // Nothing to do.
4824        }
4825
4826        @Override
4827        public void run() {
4828
4829            // data from the app, passed to us for bridging to the transport
4830            ParcelFileDescriptor[] enginePipes = null;
4831
4832            // Pipe through which we write data to the transport
4833            ParcelFileDescriptor[] transportPipes = null;
4834
4835            long backoff = 0;
4836            int backupRunStatus = BackupManager.SUCCESS;
4837
4838            try {
4839                if (!mEnabled || !mProvisioned) {
4840                    // Backups are globally disabled, so don't proceed.
4841                    if (DEBUG) {
4842                        Slog.i(TAG, "full backup requested but enabled=" + mEnabled
4843                                + " provisioned=" + mProvisioned + "; ignoring");
4844                    }
4845                    int monitoringEvent;
4846                    if (!mEnabled) {
4847                        monitoringEvent = BackupManagerMonitor.LOG_EVENT_ID_BACKUP_DISABLED;
4848                    } else {
4849                        monitoringEvent = BackupManagerMonitor.LOG_EVENT_ID_DEVICE_NOT_PROVISIONED;
4850                    }
4851                    mMonitor = monitorEvent(mMonitor, monitoringEvent, null,
4852                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
4853                    mUpdateSchedule = false;
4854                    backupRunStatus = BackupManager.ERROR_BACKUP_NOT_ALLOWED;
4855                    return;
4856                }
4857
4858                mTransport = mTransportManager.getCurrentTransportBinder();
4859                if (mTransport == null) {
4860                    Slog.w(TAG, "Transport not present; full data backup not performed");
4861                    backupRunStatus = BackupManager.ERROR_TRANSPORT_ABORTED;
4862                    mMonitor = monitorEvent(mMonitor,
4863                            BackupManagerMonitor.LOG_EVENT_ID_PACKAGE_TRANSPORT_NOT_PRESENT,
4864                            mCurrentPackage, BackupManagerMonitor.LOG_EVENT_CATEGORY_TRANSPORT,
4865                            null);
4866                    return;
4867                }
4868
4869                // Set up to send data to the transport
4870                final int N = mPackages.size();
4871                final byte[] buffer = new byte[8192];
4872                for (int i = 0; i < N; i++) {
4873                    PackageInfo currentPackage = mPackages.get(i);
4874                    String packageName = currentPackage.packageName;
4875                    if (DEBUG) {
4876                        Slog.i(TAG, "Initiating full-data transport backup of " + packageName
4877                                + " token: " + mCurrentOpToken);
4878                    }
4879                    EventLog.writeEvent(EventLogTags.FULL_BACKUP_PACKAGE, packageName);
4880
4881                    transportPipes = ParcelFileDescriptor.createPipe();
4882
4883                    // Tell the transport the data's coming
4884                    int flags = mUserInitiated ? BackupTransport.FLAG_USER_INITIATED : 0;
4885                    int backupPackageStatus;
4886                    long quota = Long.MAX_VALUE;
4887                    synchronized (mCancelLock) {
4888                        if (mCancelAll) {
4889                            break;
4890                        }
4891                        backupPackageStatus = mTransport.performFullBackup(currentPackage,
4892                                transportPipes[0], flags);
4893
4894                        if (backupPackageStatus == BackupTransport.TRANSPORT_OK) {
4895                            quota = mTransport.getBackupQuota(currentPackage.packageName,
4896                                    true /* isFullBackup */);
4897                            // Now set up the backup engine / data source end of things
4898                            enginePipes = ParcelFileDescriptor.createPipe();
4899                            mBackupRunner =
4900                                    new SinglePackageBackupRunner(enginePipes[1], currentPackage,
4901                                            mTransport, quota, mBackupRunnerOpToken);
4902                            // The runner dup'd the pipe half, so we close it here
4903                            enginePipes[1].close();
4904                            enginePipes[1] = null;
4905
4906                            mIsDoingBackup = true;
4907                        }
4908                    }
4909                    if (backupPackageStatus == BackupTransport.TRANSPORT_OK) {
4910
4911                        // The transport has its own copy of the read end of the pipe,
4912                        // so close ours now
4913                        transportPipes[0].close();
4914                        transportPipes[0] = null;
4915
4916                        // Spin off the runner to fetch the app's data and pipe it
4917                        // into the engine pipes
4918                        (new Thread(mBackupRunner, "package-backup-bridge")).start();
4919
4920                        // Read data off the engine pipe and pass it to the transport
4921                        // pipe until we hit EOD on the input stream.  We do not take
4922                        // close() responsibility for these FDs into these stream wrappers.
4923                        FileInputStream in = new FileInputStream(
4924                                enginePipes[0].getFileDescriptor());
4925                        FileOutputStream out = new FileOutputStream(
4926                                transportPipes[1].getFileDescriptor());
4927                        long totalRead = 0;
4928                        final long preflightResult = mBackupRunner.getPreflightResultBlocking();
4929                        // Preflight result is negative if some error happened on preflight.
4930                        if (preflightResult < 0) {
4931                            if (MORE_DEBUG) {
4932                                Slog.d(TAG, "Backup error after preflight of package "
4933                                        + packageName + ": " + preflightResult
4934                                        + ", not running backup.");
4935                            }
4936                            mMonitor = monitorEvent(mMonitor,
4937                                    BackupManagerMonitor.LOG_EVENT_ID_ERROR_PREFLIGHT,
4938                                    mCurrentPackage,
4939                                    BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
4940                                    putMonitoringExtra(null,
4941                                            BackupManagerMonitor.EXTRA_LOG_PREFLIGHT_ERROR,
4942                                            preflightResult));
4943                            backupPackageStatus = (int) preflightResult;
4944                        } else {
4945                            int nRead = 0;
4946                            do {
4947                                nRead = in.read(buffer);
4948                                if (MORE_DEBUG) {
4949                                    Slog.v(TAG, "in.read(buffer) from app: " + nRead);
4950                                }
4951                                if (nRead > 0) {
4952                                    out.write(buffer, 0, nRead);
4953                                    synchronized (mCancelLock) {
4954                                        if (!mCancelAll) {
4955                                            backupPackageStatus = mTransport.sendBackupData(nRead);
4956                                        }
4957                                    }
4958                                    totalRead += nRead;
4959                                    if (mBackupObserver != null && preflightResult > 0) {
4960                                        sendBackupOnUpdate(mBackupObserver, packageName,
4961                                                new BackupProgress(preflightResult, totalRead));
4962                                    }
4963                                }
4964                            } while (nRead > 0
4965                                    && backupPackageStatus == BackupTransport.TRANSPORT_OK);
4966                            // Despite preflight succeeded, package still can hit quota on flight.
4967                            if (backupPackageStatus == BackupTransport.TRANSPORT_QUOTA_EXCEEDED) {
4968                                Slog.w(TAG, "Package hit quota limit in-flight " + packageName
4969                                        + ": " + totalRead + " of " + quota);
4970                                mMonitor = monitorEvent(mMonitor,
4971                                        BackupManagerMonitor.LOG_EVENT_ID_QUOTA_HIT_PREFLIGHT,
4972                                        mCurrentPackage,
4973                                        BackupManagerMonitor.LOG_EVENT_CATEGORY_TRANSPORT,
4974                                        null);
4975                                mBackupRunner.sendQuotaExceeded(totalRead, quota);
4976                            }
4977                        }
4978
4979                        final int backupRunnerResult = mBackupRunner.getBackupResultBlocking();
4980
4981                        synchronized (mCancelLock) {
4982                            mIsDoingBackup = false;
4983                            // If mCancelCurrent is true, we have already called cancelFullBackup().
4984                            if (!mCancelAll) {
4985                                if (backupRunnerResult == BackupTransport.TRANSPORT_OK) {
4986                                    // If we were otherwise in a good state, now interpret the final
4987                                    // result based on what finishBackup() returns.  If we're in a
4988                                    // failure case already, preserve that result and ignore whatever
4989                                    // finishBackup() reports.
4990                                    final int finishResult = mTransport.finishBackup();
4991                                    if (backupPackageStatus == BackupTransport.TRANSPORT_OK) {
4992                                        backupPackageStatus = finishResult;
4993                                    }
4994                                } else {
4995                                    mTransport.cancelFullBackup();
4996                                }
4997                            }
4998                        }
4999
5000                        // A transport-originated error here means that we've hit an error that the
5001                        // runner doesn't know about, so it's still moving data but we're pulling the
5002                        // rug out from under it.  Don't ask for its result:  we already know better
5003                        // and we'll hang if we block waiting for it, since it relies on us to
5004                        // read back the data it's writing into the engine.  Just proceed with
5005                        // a graceful failure.  The runner/engine mechanism will tear itself
5006                        // down cleanly when we close the pipes from this end.  Transport-level
5007                        // errors take precedence over agent/app-specific errors for purposes of
5008                        // determining our course of action.
5009                        if (backupPackageStatus == BackupTransport.TRANSPORT_OK) {
5010                            // We still could fail in backup runner thread.
5011                            if (backupRunnerResult != BackupTransport.TRANSPORT_OK) {
5012                                // If there was an error in runner thread and
5013                                // not TRANSPORT_ERROR here, overwrite it.
5014                                backupPackageStatus = backupRunnerResult;
5015                            }
5016                        } else {
5017                            if (MORE_DEBUG) {
5018                                Slog.i(TAG, "Transport-level failure; cancelling agent work");
5019                            }
5020                        }
5021
5022                        if (MORE_DEBUG) {
5023                            Slog.i(TAG, "Done delivering backup data: result="
5024                                    + backupPackageStatus);
5025                        }
5026
5027                        if (backupPackageStatus != BackupTransport.TRANSPORT_OK) {
5028                            Slog.e(TAG, "Error " + backupPackageStatus + " backing up "
5029                                    + packageName);
5030                        }
5031
5032                        // Also ask the transport how long it wants us to wait before
5033                        // moving on to the next package, if any.
5034                        backoff = mTransport.requestFullBackupTime();
5035                        if (DEBUG_SCHEDULING) {
5036                            Slog.i(TAG, "Transport suggested backoff=" + backoff);
5037                        }
5038
5039                    }
5040
5041                    // Roll this package to the end of the backup queue if we're
5042                    // in a queue-driven mode (regardless of success/failure)
5043                    if (mUpdateSchedule) {
5044                        enqueueFullBackup(packageName, System.currentTimeMillis());
5045                    }
5046
5047                    if (backupPackageStatus == BackupTransport.TRANSPORT_PACKAGE_REJECTED) {
5048                        sendBackupOnPackageResult(mBackupObserver, packageName,
5049                                BackupManager.ERROR_TRANSPORT_PACKAGE_REJECTED);
5050                        if (DEBUG) {
5051                            Slog.i(TAG, "Transport rejected backup of " + packageName
5052                                    + ", skipping");
5053                        }
5054                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_AGENT_FAILURE, packageName,
5055                                "transport rejected");
5056                        // Do nothing, clean up, and continue looping.
5057                    } else if (backupPackageStatus == BackupTransport.TRANSPORT_QUOTA_EXCEEDED) {
5058                        sendBackupOnPackageResult(mBackupObserver, packageName,
5059                                BackupManager.ERROR_TRANSPORT_QUOTA_EXCEEDED);
5060                        if (DEBUG) {
5061                            Slog.i(TAG, "Transport quota exceeded for package: " + packageName);
5062                            EventLog.writeEvent(EventLogTags.FULL_BACKUP_QUOTA_EXCEEDED,
5063                                    packageName);
5064                        }
5065                        // Do nothing, clean up, and continue looping.
5066                    } else if (backupPackageStatus == BackupTransport.AGENT_ERROR) {
5067                        sendBackupOnPackageResult(mBackupObserver, packageName,
5068                                BackupManager.ERROR_AGENT_FAILURE);
5069                        Slog.w(TAG, "Application failure for package: " + packageName);
5070                        EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName);
5071                        tearDownAgentAndKill(currentPackage.applicationInfo);
5072                        // Do nothing, clean up, and continue looping.
5073                    } else if (backupPackageStatus == BackupManager.ERROR_BACKUP_CANCELLED) {
5074                        sendBackupOnPackageResult(mBackupObserver, packageName,
5075                                BackupManager.ERROR_BACKUP_CANCELLED);
5076                        Slog.w(TAG, "Backup cancelled. package=" + packageName +
5077                                ", cancelAll=" + mCancelAll);
5078                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_CANCELLED, packageName);
5079                        tearDownAgentAndKill(currentPackage.applicationInfo);
5080                        // Do nothing, clean up, and continue looping.
5081                    } else if (backupPackageStatus != BackupTransport.TRANSPORT_OK) {
5082                        sendBackupOnPackageResult(mBackupObserver, packageName,
5083                            BackupManager.ERROR_TRANSPORT_ABORTED);
5084                        Slog.w(TAG, "Transport failed; aborting backup: " + backupPackageStatus);
5085                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_TRANSPORT_FAILURE);
5086                        // Abort entire backup pass.
5087                        backupRunStatus = BackupManager.ERROR_TRANSPORT_ABORTED;
5088                        return;
5089                    } else {
5090                        // Success!
5091                        sendBackupOnPackageResult(mBackupObserver, packageName,
5092                                BackupManager.SUCCESS);
5093                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_SUCCESS, packageName);
5094                        logBackupComplete(packageName);
5095                    }
5096                    cleanUpPipes(transportPipes);
5097                    cleanUpPipes(enginePipes);
5098                    if (currentPackage.applicationInfo != null) {
5099                        Slog.i(TAG, "Unbinding agent in " + packageName);
5100                        addBackupTrace("unbinding " + packageName);
5101                        try {
5102                            mActivityManager.unbindBackupAgent(currentPackage.applicationInfo);
5103                        } catch (RemoteException e) { /* can't happen; activity manager is local */ }
5104                    }
5105                }
5106            } catch (Exception e) {
5107                backupRunStatus = BackupManager.ERROR_TRANSPORT_ABORTED;
5108                Slog.w(TAG, "Exception trying full transport backup", e);
5109                mMonitor = monitorEvent(mMonitor,
5110                        BackupManagerMonitor.LOG_EVENT_ID_EXCEPTION_FULL_BACKUP,
5111                        mCurrentPackage,
5112                        BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
5113                        putMonitoringExtra(null,
5114                                BackupManagerMonitor.EXTRA_LOG_EXCEPTION_FULL_BACKUP,
5115                                Log.getStackTraceString(e)));
5116
5117            } finally {
5118
5119                if (mCancelAll) {
5120                    backupRunStatus = BackupManager.ERROR_BACKUP_CANCELLED;
5121                }
5122
5123                if (DEBUG) {
5124                    Slog.i(TAG, "Full backup completed with status: " + backupRunStatus);
5125                }
5126                sendBackupFinished(mBackupObserver, backupRunStatus);
5127
5128                cleanUpPipes(transportPipes);
5129                cleanUpPipes(enginePipes);
5130
5131                unregisterTask();
5132
5133                if (mJob != null) {
5134                    mJob.finishBackupPass();
5135                }
5136
5137                synchronized (mQueueLock) {
5138                    mRunningFullBackupTask = null;
5139                }
5140
5141                mLatch.countDown();
5142
5143                // Now that we're actually done with schedule-driven work, reschedule
5144                // the next pass based on the new queue state.
5145                if (mUpdateSchedule) {
5146                    scheduleNextFullBackupJob(backoff);
5147                }
5148
5149                Slog.i(BackupManagerService.TAG, "Full data backup pass finished.");
5150                mWakelock.release();
5151            }
5152        }
5153
5154        void cleanUpPipes(ParcelFileDescriptor[] pipes) {
5155            if (pipes != null) {
5156                if (pipes[0] != null) {
5157                    ParcelFileDescriptor fd = pipes[0];
5158                    pipes[0] = null;
5159                    try {
5160                        fd.close();
5161                    } catch (IOException e) {
5162                        Slog.w(TAG, "Unable to close pipe!");
5163                    }
5164                }
5165                if (pipes[1] != null) {
5166                    ParcelFileDescriptor fd = pipes[1];
5167                    pipes[1] = null;
5168                    try {
5169                        fd.close();
5170                    } catch (IOException e) {
5171                        Slog.w(TAG, "Unable to close pipe!");
5172                    }
5173                }
5174            }
5175        }
5176
5177        // Run the backup and pipe it back to the given socket -- expects to run on
5178        // a standalone thread.  The  runner owns this half of the pipe, and closes
5179        // it to indicate EOD to the other end.
5180        class SinglePackageBackupPreflight implements BackupRestoreTask, FullBackupPreflight {
5181            final AtomicLong mResult = new AtomicLong(BackupTransport.AGENT_ERROR);
5182            final CountDownLatch mLatch = new CountDownLatch(1);
5183            final IBackupTransport mTransport;
5184            final long mQuota;
5185            private final int mCurrentOpToken;
5186
5187            SinglePackageBackupPreflight(IBackupTransport transport, long quota, int currentOpToken) {
5188                mTransport = transport;
5189                mQuota = quota;
5190                mCurrentOpToken = currentOpToken;
5191            }
5192
5193            @Override
5194            public int preflightFullBackup(PackageInfo pkg, IBackupAgent agent) {
5195                int result;
5196                try {
5197                    prepareOperationTimeout(mCurrentOpToken, TIMEOUT_FULL_BACKUP_INTERVAL,
5198                            this, OP_TYPE_BACKUP_WAIT);
5199                    addBackupTrace("preflighting");
5200                    if (MORE_DEBUG) {
5201                        Slog.d(TAG, "Preflighting full payload of " + pkg.packageName);
5202                    }
5203                    agent.doMeasureFullBackup(mQuota, mCurrentOpToken, mBackupManagerBinder);
5204
5205                    // Now wait to get our result back.  If this backstop timeout is reached without
5206                    // the latch being thrown, flow will continue as though a result or "normal"
5207                    // timeout had been produced.  In case of a real backstop timeout, mResult
5208                    // will still contain the value it was constructed with, AGENT_ERROR, which
5209                    // intentionaly falls into the "just report failure" code.
5210                    mLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
5211
5212                    long totalSize = mResult.get();
5213                    // If preflight timed out, mResult will contain error code as int.
5214                    if (totalSize < 0) {
5215                        return (int) totalSize;
5216                    }
5217                    if (MORE_DEBUG) {
5218                        Slog.v(TAG, "Got preflight response; size=" + totalSize);
5219                    }
5220
5221                    result = mTransport.checkFullBackupSize(totalSize);
5222                    if (result == BackupTransport.TRANSPORT_QUOTA_EXCEEDED) {
5223                        if (MORE_DEBUG) {
5224                            Slog.d(TAG, "Package hit quota limit on preflight " +
5225                                    pkg.packageName + ": " + totalSize + " of " + mQuota);
5226                        }
5227                        agent.doQuotaExceeded(totalSize, mQuota);
5228                    }
5229                } catch (Exception e) {
5230                    Slog.w(TAG, "Exception preflighting " + pkg.packageName + ": " + e.getMessage());
5231                    result = BackupTransport.AGENT_ERROR;
5232                }
5233                return result;
5234            }
5235
5236            @Override
5237            public void execute() {
5238                // Unused.
5239            }
5240
5241            @Override
5242            public void operationComplete(long result) {
5243                // got the callback, and our preflightFullBackup() method is waiting for the result
5244                if (MORE_DEBUG) {
5245                    Slog.i(TAG, "Preflight op complete, result=" + result);
5246                }
5247                mResult.set(result);
5248                mLatch.countDown();
5249                removeOperation(mCurrentOpToken);
5250            }
5251
5252            @Override
5253            public void handleCancel(boolean cancelAll) {
5254                if (MORE_DEBUG) {
5255                    Slog.i(TAG, "Preflight cancelled; failing");
5256                }
5257                mResult.set(BackupTransport.AGENT_ERROR);
5258                mLatch.countDown();
5259                removeOperation(mCurrentOpToken);
5260            }
5261
5262            @Override
5263            public long getExpectedSizeOrErrorCode() {
5264                try {
5265                    mLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
5266                    return mResult.get();
5267                } catch (InterruptedException e) {
5268                    return BackupTransport.NO_MORE_DATA;
5269                }
5270            }
5271        }
5272
5273        class SinglePackageBackupRunner implements Runnable, BackupRestoreTask {
5274            final ParcelFileDescriptor mOutput;
5275            final PackageInfo mTarget;
5276            final SinglePackageBackupPreflight mPreflight;
5277            final CountDownLatch mPreflightLatch;
5278            final CountDownLatch mBackupLatch;
5279            private final int mCurrentOpToken;
5280            private final int mEphemeralToken;
5281            private FullBackupEngine mEngine;
5282            private volatile int mPreflightResult;
5283            private volatile int mBackupResult;
5284            private final long mQuota;
5285            private volatile boolean mIsCancelled;
5286
5287            SinglePackageBackupRunner(ParcelFileDescriptor output, PackageInfo target,
5288                    IBackupTransport transport, long quota, int currentOpToken) throws IOException {
5289                mOutput = ParcelFileDescriptor.dup(output.getFileDescriptor());
5290                mTarget = target;
5291                mCurrentOpToken = currentOpToken;
5292                mEphemeralToken = generateRandomIntegerToken();
5293                mPreflight = new SinglePackageBackupPreflight(transport, quota, mEphemeralToken);
5294                mPreflightLatch = new CountDownLatch(1);
5295                mBackupLatch = new CountDownLatch(1);
5296                mPreflightResult = BackupTransport.AGENT_ERROR;
5297                mBackupResult = BackupTransport.AGENT_ERROR;
5298                mQuota = quota;
5299                registerTask();
5300            }
5301
5302            void registerTask() {
5303                synchronized (mCurrentOpLock) {
5304                    mCurrentOperations.put(mCurrentOpToken, new Operation(OP_PENDING, this,
5305                            OP_TYPE_BACKUP_WAIT));
5306                }
5307            }
5308
5309            void unregisterTask() {
5310                synchronized (mCurrentOpLock) {
5311                    mCurrentOperations.remove(mCurrentOpToken);
5312                }
5313            }
5314
5315            @Override
5316            public void run() {
5317                FileOutputStream out = new FileOutputStream(mOutput.getFileDescriptor());
5318                mEngine = new FullBackupEngine(out, mPreflight, mTarget, false, this, mQuota, mCurrentOpToken);
5319                try {
5320                    try {
5321                        if (!mIsCancelled) {
5322                            mPreflightResult = mEngine.preflightCheck();
5323                        }
5324                    } finally {
5325                        mPreflightLatch.countDown();
5326                    }
5327                    // If there is no error on preflight, continue backup.
5328                    if (mPreflightResult == BackupTransport.TRANSPORT_OK) {
5329                        if (!mIsCancelled) {
5330                            mBackupResult = mEngine.backupOnePackage();
5331                        }
5332                    }
5333                } catch (Exception e) {
5334                    Slog.e(TAG, "Exception during full package backup of " + mTarget.packageName);
5335                } finally {
5336                    unregisterTask();
5337                    mBackupLatch.countDown();
5338                    try {
5339                        mOutput.close();
5340                    } catch (IOException e) {
5341                        Slog.w(TAG, "Error closing transport pipe in runner");
5342                    }
5343                }
5344            }
5345
5346            public void sendQuotaExceeded(final long backupDataBytes, final long quotaBytes) {
5347                mEngine.sendQuotaExceeded(backupDataBytes, quotaBytes);
5348            }
5349
5350            // If preflight succeeded, returns positive number - preflight size,
5351            // otherwise return negative error code.
5352            long getPreflightResultBlocking() {
5353                try {
5354                    mPreflightLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
5355                    if (mIsCancelled) {
5356                        return BackupManager.ERROR_BACKUP_CANCELLED;
5357                    }
5358                    if (mPreflightResult == BackupTransport.TRANSPORT_OK) {
5359                        return mPreflight.getExpectedSizeOrErrorCode();
5360                    } else {
5361                        return mPreflightResult;
5362                    }
5363                } catch (InterruptedException e) {
5364                    return BackupTransport.AGENT_ERROR;
5365                }
5366            }
5367
5368            int getBackupResultBlocking() {
5369                try {
5370                    mBackupLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
5371                    if (mIsCancelled) {
5372                        return BackupManager.ERROR_BACKUP_CANCELLED;
5373                    }
5374                    return mBackupResult;
5375                } catch (InterruptedException e) {
5376                    return BackupTransport.AGENT_ERROR;
5377                }
5378            }
5379
5380
5381            // BackupRestoreTask interface: specifically, timeout detection
5382
5383            @Override
5384            public void execute() { /* intentionally empty */ }
5385
5386            @Override
5387            public void operationComplete(long result) { /* intentionally empty */ }
5388
5389            @Override
5390            public void handleCancel(boolean cancelAll) {
5391                if (DEBUG) {
5392                    Slog.w(TAG, "Full backup cancel of " + mTarget.packageName);
5393                }
5394
5395                mMonitor = monitorEvent(mMonitor,
5396                        BackupManagerMonitor.LOG_EVENT_ID_FULL_BACKUP_CANCEL,
5397                        mCurrentPackage, BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT, null);
5398                mIsCancelled = true;
5399                // Cancel tasks spun off by this task.
5400                BackupManagerService.this.handleCancel(mEphemeralToken, cancelAll);
5401                tearDownAgentAndKill(mTarget.applicationInfo);
5402                // Free up everyone waiting on this task and its children.
5403                mPreflightLatch.countDown();
5404                mBackupLatch.countDown();
5405                // We are done with this operation.
5406                removeOperation(mCurrentOpToken);
5407            }
5408        }
5409    }
5410
5411    // ----- Full-data backup scheduling -----
5412
5413    /**
5414     * Schedule a job to tell us when it's a good time to run a full backup
5415     */
5416    void scheduleNextFullBackupJob(long transportMinLatency) {
5417        synchronized (mQueueLock) {
5418            if (mFullBackupQueue.size() > 0) {
5419                // schedule the next job at the point in the future when the least-recently
5420                // backed up app comes due for backup again; or immediately if it's already
5421                // due.
5422                final long upcomingLastBackup = mFullBackupQueue.get(0).lastBackup;
5423                final long timeSinceLast = System.currentTimeMillis() - upcomingLastBackup;
5424                final long appLatency = (timeSinceLast < MIN_FULL_BACKUP_INTERVAL)
5425                        ? (MIN_FULL_BACKUP_INTERVAL - timeSinceLast) : 0;
5426                final long latency = Math.max(transportMinLatency, appLatency);
5427                Runnable r = new Runnable() {
5428                    @Override public void run() {
5429                        FullBackupJob.schedule(mContext, latency);
5430                    }
5431                };
5432                mBackupHandler.postDelayed(r, 2500);
5433            } else {
5434                if (DEBUG_SCHEDULING) {
5435                    Slog.i(TAG, "Full backup queue empty; not scheduling");
5436                }
5437            }
5438        }
5439    }
5440
5441    /**
5442     * Remove a package from the full-data queue.
5443     */
5444    void dequeueFullBackupLocked(String packageName) {
5445        final int N = mFullBackupQueue.size();
5446        for (int i = N-1; i >= 0; i--) {
5447            final FullBackupEntry e = mFullBackupQueue.get(i);
5448            if (packageName.equals(e.packageName)) {
5449                mFullBackupQueue.remove(i);
5450            }
5451        }
5452    }
5453
5454    /**
5455     * Enqueue full backup for the given app, with a note about when it last ran.
5456     */
5457    void enqueueFullBackup(String packageName, long lastBackedUp) {
5458        FullBackupEntry newEntry = new FullBackupEntry(packageName, lastBackedUp);
5459        synchronized (mQueueLock) {
5460            // First, sanity check that we aren't adding a duplicate.  Slow but
5461            // straightforward; we'll have at most on the order of a few hundred
5462            // items in this list.
5463            dequeueFullBackupLocked(packageName);
5464
5465            // This is also slow but easy for modest numbers of apps: work backwards
5466            // from the end of the queue until we find an item whose last backup
5467            // time was before this one, then insert this new entry after it.  If we're
5468            // adding something new we don't bother scanning, and just prepend.
5469            int which = -1;
5470            if (lastBackedUp > 0) {
5471                for (which = mFullBackupQueue.size() - 1; which >= 0; which--) {
5472                    final FullBackupEntry entry = mFullBackupQueue.get(which);
5473                    if (entry.lastBackup <= lastBackedUp) {
5474                        mFullBackupQueue.add(which + 1, newEntry);
5475                        break;
5476                    }
5477                }
5478            }
5479            if (which < 0) {
5480                // this one is earlier than any existing one, so prepend
5481                mFullBackupQueue.add(0, newEntry);
5482            }
5483        }
5484        writeFullBackupScheduleAsync();
5485    }
5486
5487    private boolean fullBackupAllowable(IBackupTransport transport) {
5488        if (transport == null) {
5489            Slog.w(TAG, "Transport not present; full data backup not performed");
5490            return false;
5491        }
5492
5493        // Don't proceed unless we have already established package metadata
5494        // for the current dataset via a key/value backup pass.
5495        try {
5496            File stateDir = new File(mBaseStateDir, transport.transportDirName());
5497            File pmState = new File(stateDir, PACKAGE_MANAGER_SENTINEL);
5498            if (pmState.length() <= 0) {
5499                if (DEBUG) {
5500                    Slog.i(TAG, "Full backup requested but dataset not yet initialized");
5501                }
5502                return false;
5503            }
5504        } catch (Exception e) {
5505            Slog.w(TAG, "Unable to get transport name: " + e.getMessage());
5506            return false;
5507        }
5508
5509        return true;
5510    }
5511
5512    /**
5513     * Conditions are right for a full backup operation, so run one.  The model we use is
5514     * to perform one app backup per scheduled job execution, and to reschedule the job
5515     * with zero latency as long as conditions remain right and we still have work to do.
5516     *
5517     * <p>This is the "start a full backup operation" entry point called by the scheduled job.
5518     *
5519     * @return Whether ongoing work will continue.  The return value here will be passed
5520     *         along as the return value to the scheduled job's onStartJob() callback.
5521     */
5522    @Override
5523    public boolean beginFullBackup(FullBackupJob scheduledJob) {
5524        long now = System.currentTimeMillis();
5525        FullBackupEntry entry = null;
5526        long latency = MIN_FULL_BACKUP_INTERVAL;
5527
5528        if (!mEnabled || !mProvisioned) {
5529            // Backups are globally disabled, so don't proceed.  We also don't reschedule
5530            // the job driving automatic backups; that job will be scheduled again when
5531            // the user enables backup.
5532            if (MORE_DEBUG) {
5533                Slog.i(TAG, "beginFullBackup but e=" + mEnabled
5534                        + " p=" + mProvisioned + "; ignoring");
5535            }
5536            return false;
5537        }
5538
5539        // Don't run the backup if we're in battery saver mode, but reschedule
5540        // to try again in the not-so-distant future.
5541        final PowerSaveState result =
5542                mPowerManager.getPowerSaveState(ServiceType.FULL_BACKUP);
5543        if (result.batterySaverEnabled) {
5544            if (DEBUG) Slog.i(TAG, "Deferring scheduled full backups in battery saver mode");
5545            FullBackupJob.schedule(mContext, KeyValueBackupJob.BATCH_INTERVAL);
5546            return false;
5547        }
5548
5549        if (DEBUG_SCHEDULING) {
5550            Slog.i(TAG, "Beginning scheduled full backup operation");
5551        }
5552
5553        // Great; we're able to run full backup jobs now.  See if we have any work to do.
5554        synchronized (mQueueLock) {
5555            if (mRunningFullBackupTask != null) {
5556                Slog.e(TAG, "Backup triggered but one already/still running!");
5557                return false;
5558            }
5559
5560            // At this point we think that we have work to do, but possibly not right now.
5561            // Any exit without actually running backups will also require that we
5562            // reschedule the job.
5563            boolean runBackup = true;
5564            boolean headBusy;
5565
5566            do {
5567                // Recheck each time, because culling due to ineligibility may
5568                // have emptied the queue.
5569                if (mFullBackupQueue.size() == 0) {
5570                    // no work to do so just bow out
5571                    if (DEBUG) {
5572                        Slog.i(TAG, "Backup queue empty; doing nothing");
5573                    }
5574                    runBackup = false;
5575                    break;
5576                }
5577
5578                headBusy = false;
5579
5580                if (!fullBackupAllowable(mTransportManager.getCurrentTransportBinder())) {
5581                    if (MORE_DEBUG) {
5582                        Slog.i(TAG, "Preconditions not met; not running full backup");
5583                    }
5584                    runBackup = false;
5585                    // Typically this means we haven't run a key/value backup yet.  Back off
5586                    // full-backup operations by the key/value job's run interval so that
5587                    // next time we run, we are likely to be able to make progress.
5588                    latency = KeyValueBackupJob.BATCH_INTERVAL;
5589                }
5590
5591                if (runBackup) {
5592                    entry = mFullBackupQueue.get(0);
5593                    long timeSinceRun = now - entry.lastBackup;
5594                    runBackup = (timeSinceRun >= MIN_FULL_BACKUP_INTERVAL);
5595                    if (!runBackup) {
5596                        // It's too early to back up the next thing in the queue, so bow out
5597                        if (MORE_DEBUG) {
5598                            Slog.i(TAG, "Device ready but too early to back up next app");
5599                        }
5600                        // Wait until the next app in the queue falls due for a full data backup
5601                        latency = MIN_FULL_BACKUP_INTERVAL - timeSinceRun;
5602                        break;  // we know we aren't doing work yet, so bail.
5603                    }
5604
5605                    try {
5606                        PackageInfo appInfo = mPackageManager.getPackageInfo(entry.packageName, 0);
5607                        if (!appGetsFullBackup(appInfo)) {
5608                            // The head app isn't supposed to get full-data backups [any more];
5609                            // so we cull it and force a loop around to consider the new head
5610                            // app.
5611                            if (MORE_DEBUG) {
5612                                Slog.i(TAG, "Culling package " + entry.packageName
5613                                        + " in full-backup queue but not eligible");
5614                            }
5615                            mFullBackupQueue.remove(0);
5616                            headBusy = true; // force the while() condition
5617                            continue;
5618                        }
5619
5620                        final int privFlags = appInfo.applicationInfo.privateFlags;
5621                        headBusy = (privFlags & PRIVATE_FLAG_BACKUP_IN_FOREGROUND) == 0
5622                                && mActivityManager.isAppForeground(appInfo.applicationInfo.uid);
5623
5624                        if (headBusy) {
5625                            final long nextEligible = System.currentTimeMillis()
5626                                    + BUSY_BACKOFF_MIN_MILLIS
5627                                    + mTokenGenerator.nextInt(BUSY_BACKOFF_FUZZ);
5628                            if (DEBUG_SCHEDULING) {
5629                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
5630                                Slog.i(TAG, "Full backup time but " + entry.packageName
5631                                        + " is busy; deferring to "
5632                                        + sdf.format(new Date(nextEligible)));
5633                            }
5634                            // This relocates the app's entry from the head of the queue to
5635                            // its order-appropriate position further down, so upon looping
5636                            // a new candidate will be considered at the head.
5637                            enqueueFullBackup(entry.packageName,
5638                                    nextEligible - MIN_FULL_BACKUP_INTERVAL);
5639                        }
5640                    } catch (NameNotFoundException nnf) {
5641                        // So, we think we want to back this up, but it turns out the package
5642                        // in question is no longer installed.  We want to drop it from the
5643                        // queue entirely and move on, but if there's nothing else in the queue
5644                        // we should bail entirely.  headBusy cannot have been set to true yet.
5645                        runBackup = (mFullBackupQueue.size() > 1);
5646                    } catch (RemoteException e) {
5647                        // Cannot happen; the Activity Manager is in the same process
5648                    }
5649                }
5650            } while (headBusy);
5651
5652            if (!runBackup) {
5653                if (DEBUG_SCHEDULING) {
5654                    Slog.i(TAG, "Nothing pending full backup; rescheduling +" + latency);
5655                }
5656                final long deferTime = latency;     // pin for the closure
5657                mBackupHandler.post(new Runnable() {
5658                    @Override public void run() {
5659                        FullBackupJob.schedule(mContext, deferTime);
5660                    }
5661                });
5662                return false;
5663            }
5664
5665            // Okay, the top thing is ready for backup now.  Do it.
5666            mFullBackupQueue.remove(0);
5667            CountDownLatch latch = new CountDownLatch(1);
5668            String[] pkg = new String[] {entry.packageName};
5669            mRunningFullBackupTask = new PerformFullTransportBackupTask(null, pkg, true,
5670                    scheduledJob, latch, null, null, false /* userInitiated */);
5671            // Acquiring wakelock for PerformFullTransportBackupTask before its start.
5672            mWakelock.acquire();
5673            (new Thread(mRunningFullBackupTask)).start();
5674        }
5675
5676        return true;
5677    }
5678
5679    // The job scheduler says our constraints don't hold any more,
5680    // so tear down any ongoing backup task right away.
5681    @Override
5682    public void endFullBackup() {
5683        // offload the mRunningFullBackupTask.handleCancel() call to another thread,
5684        // as we might have to wait for mCancelLock
5685        Runnable endFullBackupRunnable = new Runnable() {
5686            @Override
5687            public void run() {
5688                PerformFullTransportBackupTask pftbt = null;
5689                synchronized (mQueueLock) {
5690                    if (mRunningFullBackupTask != null) {
5691                        if (DEBUG_SCHEDULING) {
5692                            Slog.i(TAG, "Telling running backup to stop");
5693                        }
5694                        pftbt = mRunningFullBackupTask;
5695                    }
5696                }
5697                pftbt.handleCancel(true);
5698            }
5699        };
5700        new Thread(endFullBackupRunnable, "end-full-backup").start();
5701    }
5702
5703    // ----- Restore infrastructure -----
5704
5705    abstract class RestoreEngine {
5706        static final String TAG = "RestoreEngine";
5707
5708        public static final int SUCCESS = 0;
5709        public static final int TARGET_FAILURE = -2;
5710        public static final int TRANSPORT_FAILURE = -3;
5711
5712        private AtomicBoolean mRunning = new AtomicBoolean(false);
5713        private AtomicInteger mResult = new AtomicInteger(SUCCESS);
5714
5715        public boolean isRunning() {
5716            return mRunning.get();
5717        }
5718
5719        public void setRunning(boolean stillRunning) {
5720            synchronized (mRunning) {
5721                mRunning.set(stillRunning);
5722                mRunning.notifyAll();
5723            }
5724        }
5725
5726        public int waitForResult() {
5727            synchronized (mRunning) {
5728                while (isRunning()) {
5729                    try {
5730                        mRunning.wait();
5731                    } catch (InterruptedException e) {}
5732                }
5733            }
5734            return getResult();
5735        }
5736
5737        public int getResult() {
5738            return mResult.get();
5739        }
5740
5741        public void setResult(int result) {
5742            mResult.set(result);
5743        }
5744
5745        // TODO: abstract restore state and APIs
5746    }
5747
5748    // ----- Full restore from a file/socket -----
5749
5750    enum RestorePolicy {
5751        IGNORE,
5752        ACCEPT,
5753        ACCEPT_IF_APK
5754    }
5755
5756    // Full restore engine, used by both adb restore and transport-based full restore
5757    class FullRestoreEngine extends RestoreEngine {
5758        // Task in charge of monitoring timeouts
5759        BackupRestoreTask mMonitorTask;
5760
5761        // Dedicated observer, if any
5762        IFullBackupRestoreObserver mObserver;
5763
5764        IBackupManagerMonitor mMonitor;
5765
5766        // Where we're delivering the file data as we go
5767        IBackupAgent mAgent;
5768
5769        // Are we permitted to only deliver a specific package's metadata?
5770        PackageInfo mOnlyPackage;
5771
5772        boolean mAllowApks;
5773        boolean mAllowObbs;
5774
5775        // Which package are we currently handling data for?
5776        String mAgentPackage;
5777
5778        // Info for working with the target app process
5779        ApplicationInfo mTargetApp;
5780
5781        // Machinery for restoring OBBs
5782        FullBackupObbConnection mObbConnection = null;
5783
5784        // possible handling states for a given package in the restore dataset
5785        final HashMap<String, RestorePolicy> mPackagePolicies
5786                = new HashMap<String, RestorePolicy>();
5787
5788        // installer package names for each encountered app, derived from the manifests
5789        final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
5790
5791        // Signatures for a given package found in its manifest file
5792        final HashMap<String, Signature[]> mManifestSignatures
5793                = new HashMap<String, Signature[]>();
5794
5795        // Packages we've already wiped data on when restoring their first file
5796        final HashSet<String> mClearedPackages = new HashSet<String>();
5797
5798        // How much data have we moved?
5799        long mBytes;
5800
5801        // Working buffer
5802        byte[] mBuffer;
5803
5804        // Pipes for moving data
5805        ParcelFileDescriptor[] mPipes = null;
5806
5807        // Widget blob to be restored out-of-band
5808        byte[] mWidgetData = null;
5809
5810        private final int mEphemeralOpToken;
5811
5812        // Runner that can be placed in a separate thread to do in-process
5813        // invocations of the full restore API asynchronously. Used by adb restore.
5814        class RestoreFileRunnable implements Runnable {
5815            IBackupAgent mAgent;
5816            FileMetadata mInfo;
5817            ParcelFileDescriptor mSocket;
5818            int mToken;
5819
5820            RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
5821                    ParcelFileDescriptor socket, int token) throws IOException {
5822                mAgent = agent;
5823                mInfo = info;
5824                mToken = token;
5825
5826                // This class is used strictly for process-local binder invocations.  The
5827                // semantics of ParcelFileDescriptor differ in this case; in particular, we
5828                // do not automatically get a 'dup'ed descriptor that we can can continue
5829                // to use asynchronously from the caller.  So, we make sure to dup it ourselves
5830                // before proceeding to do the restore.
5831                mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
5832            }
5833
5834            @Override
5835            public void run() {
5836                try {
5837                    mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
5838                            mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
5839                            mToken, mBackupManagerBinder);
5840                } catch (RemoteException e) {
5841                    // never happens; this is used strictly for local binder calls
5842                }
5843            }
5844        }
5845
5846        public FullRestoreEngine(BackupRestoreTask monitorTask, IFullBackupRestoreObserver observer,
5847                IBackupManagerMonitor monitor, PackageInfo onlyPackage, boolean allowApks,
5848                boolean allowObbs, int ephemeralOpToken) {
5849            mEphemeralOpToken = ephemeralOpToken;
5850            mMonitorTask = monitorTask;
5851            mObserver = observer;
5852            mMonitor = monitor;
5853            mOnlyPackage = onlyPackage;
5854            mAllowApks = allowApks;
5855            mAllowObbs = allowObbs;
5856            mBuffer = new byte[32 * 1024];
5857            mBytes = 0;
5858        }
5859
5860        public IBackupAgent getAgent() {
5861            return mAgent;
5862        }
5863
5864        public byte[] getWidgetData() {
5865            return mWidgetData;
5866        }
5867
5868        public boolean restoreOneFile(InputStream instream, boolean mustKillAgent) {
5869            if (!isRunning()) {
5870                Slog.w(TAG, "Restore engine used after halting");
5871                return false;
5872            }
5873
5874            FileMetadata info;
5875            try {
5876                if (MORE_DEBUG) {
5877                    Slog.v(TAG, "Reading tar header for restoring file");
5878                }
5879                info = readTarHeaders(instream);
5880                if (info != null) {
5881                    if (MORE_DEBUG) {
5882                        dumpFileMetadata(info);
5883                    }
5884
5885                    final String pkg = info.packageName;
5886                    if (!pkg.equals(mAgentPackage)) {
5887                        // In the single-package case, it's a semantic error to expect
5888                        // one app's data but see a different app's on the wire
5889                        if (mOnlyPackage != null) {
5890                            if (!pkg.equals(mOnlyPackage.packageName)) {
5891                                Slog.w(TAG, "Expected data for " + mOnlyPackage
5892                                        + " but saw " + pkg);
5893                                setResult(RestoreEngine.TRANSPORT_FAILURE);
5894                                setRunning(false);
5895                                return false;
5896                            }
5897                        }
5898
5899                        // okay, change in package; set up our various
5900                        // bookkeeping if we haven't seen it yet
5901                        if (!mPackagePolicies.containsKey(pkg)) {
5902                            mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5903                        }
5904
5905                        // Clean up the previous agent relationship if necessary,
5906                        // and let the observer know we're considering a new app.
5907                        if (mAgent != null) {
5908                            if (DEBUG) Slog.d(TAG, "Saw new package; finalizing old one");
5909                            // Now we're really done
5910                            tearDownPipes();
5911                            tearDownAgent(mTargetApp);
5912                            mTargetApp = null;
5913                            mAgentPackage = null;
5914                        }
5915                    }
5916
5917                    if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
5918                        mPackagePolicies.put(pkg, readAppManifest(info, instream));
5919                        mPackageInstallers.put(pkg, info.installerPackageName);
5920                        // We've read only the manifest content itself at this point,
5921                        // so consume the footer before looping around to the next
5922                        // input file
5923                        skipTarPadding(info.size, instream);
5924                        sendOnRestorePackage(pkg);
5925                    } else if (info.path.equals(BACKUP_METADATA_FILENAME)) {
5926                        // Metadata blobs!
5927                        readMetadata(info, instream);
5928                        skipTarPadding(info.size, instream);
5929                    } else {
5930                        // Non-manifest, so it's actual file data.  Is this a package
5931                        // we're ignoring?
5932                        boolean okay = true;
5933                        RestorePolicy policy = mPackagePolicies.get(pkg);
5934                        switch (policy) {
5935                            case IGNORE:
5936                                okay = false;
5937                                break;
5938
5939                            case ACCEPT_IF_APK:
5940                                // If we're in accept-if-apk state, then the first file we
5941                                // see MUST be the apk.
5942                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
5943                                    if (DEBUG) Slog.d(TAG, "APK file; installing");
5944                                    // Try to install the app.
5945                                    String installerName = mPackageInstallers.get(pkg);
5946                                    okay = installApk(info, installerName, instream);
5947                                    // good to go; promote to ACCEPT
5948                                    mPackagePolicies.put(pkg, (okay)
5949                                            ? RestorePolicy.ACCEPT
5950                                                    : RestorePolicy.IGNORE);
5951                                    // At this point we've consumed this file entry
5952                                    // ourselves, so just strip the tar footer and
5953                                    // go on to the next file in the input stream
5954                                    skipTarPadding(info.size, instream);
5955                                    return true;
5956                                } else {
5957                                    // File data before (or without) the apk.  We can't
5958                                    // handle it coherently in this case so ignore it.
5959                                    mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5960                                    okay = false;
5961                                }
5962                                break;
5963
5964                            case ACCEPT:
5965                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
5966                                    if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
5967                                    // we can take the data without the apk, so we
5968                                    // *want* to do so.  skip the apk by declaring this
5969                                    // one file not-okay without changing the restore
5970                                    // policy for the package.
5971                                    okay = false;
5972                                }
5973                                break;
5974
5975                            default:
5976                                // Something has gone dreadfully wrong when determining
5977                                // the restore policy from the manifest.  Ignore the
5978                                // rest of this package's data.
5979                                Slog.e(TAG, "Invalid policy from manifest");
5980                                okay = false;
5981                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5982                                break;
5983                        }
5984
5985                        // Is it a *file* we need to drop?
5986                        if (!isRestorableFile(info)) {
5987                            okay = false;
5988                        }
5989
5990                        // If the policy is satisfied, go ahead and set up to pipe the
5991                        // data to the agent.
5992                        if (MORE_DEBUG && okay && mAgent != null) {
5993                            Slog.i(TAG, "Reusing existing agent instance");
5994                        }
5995                        if (okay && mAgent == null) {
5996                            if (MORE_DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
5997
5998                            try {
5999                                mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
6000
6001                                // If we haven't sent any data to this app yet, we probably
6002                                // need to clear it first.  Check that.
6003                                if (!mClearedPackages.contains(pkg)) {
6004                                    // apps with their own backup agents are
6005                                    // responsible for coherently managing a full
6006                                    // restore.
6007                                    if (mTargetApp.backupAgentName == null) {
6008                                        if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
6009                                        clearApplicationDataSynchronous(pkg);
6010                                    } else {
6011                                        if (MORE_DEBUG) Slog.d(TAG, "backup agent ("
6012                                                + mTargetApp.backupAgentName + ") => no clear");
6013                                    }
6014                                    mClearedPackages.add(pkg);
6015                                } else {
6016                                    if (MORE_DEBUG) {
6017                                        Slog.d(TAG, "We've initialized this app already; no clear required");
6018                                    }
6019                                }
6020
6021                                // All set; now set up the IPC and launch the agent
6022                                setUpPipes();
6023                                mAgent = bindToAgentSynchronous(mTargetApp,
6024                                        ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL);
6025                                mAgentPackage = pkg;
6026                            } catch (IOException e) {
6027                                // fall through to error handling
6028                            } catch (NameNotFoundException e) {
6029                                // fall through to error handling
6030                            }
6031
6032                            if (mAgent == null) {
6033                                Slog.e(TAG, "Unable to create agent for " + pkg);
6034                                okay = false;
6035                                tearDownPipes();
6036                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
6037                            }
6038                        }
6039
6040                        // Sanity check: make sure we never give data to the wrong app.  This
6041                        // should never happen but a little paranoia here won't go amiss.
6042                        if (okay && !pkg.equals(mAgentPackage)) {
6043                            Slog.e(TAG, "Restoring data for " + pkg
6044                                    + " but agent is for " + mAgentPackage);
6045                            okay = false;
6046                        }
6047
6048                        // At this point we have an agent ready to handle the full
6049                        // restore data as well as a pipe for sending data to
6050                        // that agent.  Tell the agent to start reading from the
6051                        // pipe.
6052                        if (okay) {
6053                            boolean agentSuccess = true;
6054                            long toCopy = info.size;
6055                            try {
6056                                prepareOperationTimeout(mEphemeralOpToken,
6057                                        TIMEOUT_FULL_BACKUP_INTERVAL, mMonitorTask,
6058                                        OP_TYPE_RESTORE_WAIT);
6059
6060                                if (info.domain.equals(FullBackup.OBB_TREE_TOKEN)) {
6061                                    if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
6062                                            + " : " + info.path);
6063                                    mObbConnection.restoreObbFile(pkg, mPipes[0],
6064                                            info.size, info.type, info.path, info.mode,
6065                                            info.mtime, mEphemeralOpToken, mBackupManagerBinder);
6066                                } else {
6067                                    if (MORE_DEBUG) Slog.d(TAG, "Invoking agent to restore file "
6068                                            + info.path);
6069                                    // fire up the app's agent listening on the socket.  If
6070                                    // the agent is running in the system process we can't
6071                                    // just invoke it asynchronously, so we provide a thread
6072                                    // for it here.
6073                                    if (mTargetApp.processName.equals("system")) {
6074                                        Slog.d(TAG, "system process agent - spinning a thread");
6075                                        RestoreFileRunnable runner = new RestoreFileRunnable(
6076                                                mAgent, info, mPipes[0], mEphemeralOpToken);
6077                                        new Thread(runner, "restore-sys-runner").start();
6078                                    } else {
6079                                        mAgent.doRestoreFile(mPipes[0], info.size, info.type,
6080                                                info.domain, info.path, info.mode, info.mtime,
6081                                                mEphemeralOpToken, mBackupManagerBinder);
6082                                    }
6083                                }
6084                            } catch (IOException e) {
6085                                // couldn't dup the socket for a process-local restore
6086                                Slog.d(TAG, "Couldn't establish restore");
6087                                agentSuccess = false;
6088                                okay = false;
6089                            } catch (RemoteException e) {
6090                                // whoops, remote entity went away.  We'll eat the content
6091                                // ourselves, then, and not copy it over.
6092                                Slog.e(TAG, "Agent crashed during full restore");
6093                                agentSuccess = false;
6094                                okay = false;
6095                            }
6096
6097                            // Copy over the data if the agent is still good
6098                            if (okay) {
6099                                if (MORE_DEBUG) {
6100                                    Slog.v(TAG, "  copying to restore agent: "
6101                                            + toCopy + " bytes");
6102                                }
6103                                boolean pipeOkay = true;
6104                                FileOutputStream pipe = new FileOutputStream(
6105                                        mPipes[1].getFileDescriptor());
6106                                while (toCopy > 0) {
6107                                    int toRead = (toCopy > mBuffer.length)
6108                                            ? mBuffer.length : (int)toCopy;
6109                                    int nRead = instream.read(mBuffer, 0, toRead);
6110                                    if (nRead >= 0) mBytes += nRead;
6111                                    if (nRead <= 0) break;
6112                                    toCopy -= nRead;
6113
6114                                    // send it to the output pipe as long as things
6115                                    // are still good
6116                                    if (pipeOkay) {
6117                                        try {
6118                                            pipe.write(mBuffer, 0, nRead);
6119                                        } catch (IOException e) {
6120                                            Slog.e(TAG, "Failed to write to restore pipe: "
6121                                                    + e.getMessage());
6122                                            pipeOkay = false;
6123                                        }
6124                                    }
6125                                }
6126
6127                                // done sending that file!  Now we just need to consume
6128                                // the delta from info.size to the end of block.
6129                                skipTarPadding(info.size, instream);
6130
6131                                // and now that we've sent it all, wait for the remote
6132                                // side to acknowledge receipt
6133                                agentSuccess = waitUntilOperationComplete(mEphemeralOpToken);
6134                            }
6135
6136                            // okay, if the remote end failed at any point, deal with
6137                            // it by ignoring the rest of the restore on it
6138                            if (!agentSuccess) {
6139                                Slog.w(TAG, "Agent failure; ending restore");
6140                                mBackupHandler.removeMessages(MSG_RESTORE_OPERATION_TIMEOUT);
6141                                tearDownPipes();
6142                                tearDownAgent(mTargetApp);
6143                                mAgent = null;
6144                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
6145
6146                                // If this was a single-package restore, we halt immediately
6147                                // with an agent error under these circumstances
6148                                if (mOnlyPackage != null) {
6149                                    setResult(RestoreEngine.TARGET_FAILURE);
6150                                    setRunning(false);
6151                                    return false;
6152                                }
6153                            }
6154                        }
6155
6156                        // Problems setting up the agent communication, an explicitly
6157                        // dropped file, or an already-ignored package: skip to the
6158                        // next stream entry by reading and discarding this file.
6159                        if (!okay) {
6160                            if (MORE_DEBUG) Slog.d(TAG, "[discarding file content]");
6161                            long bytesToConsume = (info.size + 511) & ~511;
6162                            while (bytesToConsume > 0) {
6163                                int toRead = (bytesToConsume > mBuffer.length)
6164                                        ? mBuffer.length : (int)bytesToConsume;
6165                                long nRead = instream.read(mBuffer, 0, toRead);
6166                                if (nRead >= 0) mBytes += nRead;
6167                                if (nRead <= 0) break;
6168                                bytesToConsume -= nRead;
6169                            }
6170                        }
6171                    }
6172                }
6173            } catch (IOException e) {
6174                if (DEBUG) Slog.w(TAG, "io exception on restore socket read: " + e.getMessage());
6175                setResult(RestoreEngine.TRANSPORT_FAILURE);
6176                info = null;
6177            }
6178
6179            // If we got here we're either running smoothly or we've finished
6180            if (info == null) {
6181                if (MORE_DEBUG) {
6182                    Slog.i(TAG, "No [more] data for this package; tearing down");
6183                }
6184                tearDownPipes();
6185                setRunning(false);
6186                if (mustKillAgent) {
6187                    tearDownAgent(mTargetApp);
6188                }
6189            }
6190            return (info != null);
6191        }
6192
6193        void setUpPipes() throws IOException {
6194            mPipes = ParcelFileDescriptor.createPipe();
6195        }
6196
6197        void tearDownPipes() {
6198            // Teardown might arise from the inline restore processing or from the asynchronous
6199            // timeout mechanism, and these might race.  Make sure we don't try to close and
6200            // null out the pipes twice.
6201            synchronized (this) {
6202                if (mPipes != null) {
6203                    try {
6204                        mPipes[0].close();
6205                        mPipes[0] = null;
6206                        mPipes[1].close();
6207                        mPipes[1] = null;
6208                    } catch (IOException e) {
6209                        Slog.w(TAG, "Couldn't close agent pipes", e);
6210                    }
6211                    mPipes = null;
6212                }
6213            }
6214        }
6215
6216        void tearDownAgent(ApplicationInfo app) {
6217            if (mAgent != null) {
6218                tearDownAgentAndKill(app);
6219                mAgent = null;
6220            }
6221        }
6222
6223        void handleTimeout() {
6224            tearDownPipes();
6225            setResult(RestoreEngine.TARGET_FAILURE);
6226            setRunning(false);
6227        }
6228
6229        class RestoreInstallObserver extends PackageInstallObserver {
6230            final AtomicBoolean mDone = new AtomicBoolean();
6231            String mPackageName;
6232            int mResult;
6233
6234            public void reset() {
6235                synchronized (mDone) {
6236                    mDone.set(false);
6237                }
6238            }
6239
6240            public void waitForCompletion() {
6241                synchronized (mDone) {
6242                    while (mDone.get() == false) {
6243                        try {
6244                            mDone.wait();
6245                        } catch (InterruptedException e) { }
6246                    }
6247                }
6248            }
6249
6250            int getResult() {
6251                return mResult;
6252            }
6253
6254            @Override
6255            public void onPackageInstalled(String packageName, int returnCode,
6256                    String msg, Bundle extras) {
6257                synchronized (mDone) {
6258                    mResult = returnCode;
6259                    mPackageName = packageName;
6260                    mDone.set(true);
6261                    mDone.notifyAll();
6262                }
6263            }
6264        }
6265
6266        class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
6267            final AtomicBoolean mDone = new AtomicBoolean();
6268            int mResult;
6269
6270            public void reset() {
6271                synchronized (mDone) {
6272                    mDone.set(false);
6273                }
6274            }
6275
6276            public void waitForCompletion() {
6277                synchronized (mDone) {
6278                    while (mDone.get() == false) {
6279                        try {
6280                            mDone.wait();
6281                        } catch (InterruptedException e) { }
6282                    }
6283                }
6284            }
6285
6286            @Override
6287            public void packageDeleted(String packageName, int returnCode) throws RemoteException {
6288                synchronized (mDone) {
6289                    mResult = returnCode;
6290                    mDone.set(true);
6291                    mDone.notifyAll();
6292                }
6293            }
6294        }
6295
6296        final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
6297        final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
6298
6299        boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
6300            boolean okay = true;
6301
6302            if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
6303
6304            // The file content is an .apk file.  Copy it out to a staging location and
6305            // attempt to install it.
6306            File apkFile = new File(mDataDir, info.packageName);
6307            try {
6308                FileOutputStream apkStream = new FileOutputStream(apkFile);
6309                byte[] buffer = new byte[32 * 1024];
6310                long size = info.size;
6311                while (size > 0) {
6312                    long toRead = (buffer.length < size) ? buffer.length : size;
6313                    int didRead = instream.read(buffer, 0, (int)toRead);
6314                    if (didRead >= 0) mBytes += didRead;
6315                    apkStream.write(buffer, 0, didRead);
6316                    size -= didRead;
6317                }
6318                apkStream.close();
6319
6320                // make sure the installer can read it
6321                apkFile.setReadable(true, false);
6322
6323                // Now install it
6324                Uri packageUri = Uri.fromFile(apkFile);
6325                mInstallObserver.reset();
6326                mPackageManager.installPackage(packageUri, mInstallObserver,
6327                        PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
6328                        installerPackage);
6329                mInstallObserver.waitForCompletion();
6330
6331                if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
6332                    // The only time we continue to accept install of data even if the
6333                    // apk install failed is if we had already determined that we could
6334                    // accept the data regardless.
6335                    if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
6336                        okay = false;
6337                    }
6338                } else {
6339                    // Okay, the install succeeded.  Make sure it was the right app.
6340                    boolean uninstall = false;
6341                    if (!mInstallObserver.mPackageName.equals(info.packageName)) {
6342                        Slog.w(TAG, "Restore stream claimed to include apk for "
6343                                + info.packageName + " but apk was really "
6344                                + mInstallObserver.mPackageName);
6345                        // delete the package we just put in place; it might be fraudulent
6346                        okay = false;
6347                        uninstall = true;
6348                    } else {
6349                        try {
6350                            PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
6351                                    PackageManager.GET_SIGNATURES);
6352                            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
6353                                Slog.w(TAG, "Restore stream contains apk of package "
6354                                        + info.packageName + " but it disallows backup/restore");
6355                                okay = false;
6356                            } else {
6357                                // So far so good -- do the signatures match the manifest?
6358                                Signature[] sigs = mManifestSignatures.get(info.packageName);
6359                                if (signaturesMatch(sigs, pkg)) {
6360                                    // If this is a system-uid app without a declared backup agent,
6361                                    // don't restore any of the file data.
6362                                    if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
6363                                            && (pkg.applicationInfo.backupAgentName == null)) {
6364                                        Slog.w(TAG, "Installed app " + info.packageName
6365                                                + " has restricted uid and no agent");
6366                                        okay = false;
6367                                    }
6368                                } else {
6369                                    Slog.w(TAG, "Installed app " + info.packageName
6370                                            + " signatures do not match restore manifest");
6371                                    okay = false;
6372                                    uninstall = true;
6373                                }
6374                            }
6375                        } catch (NameNotFoundException e) {
6376                            Slog.w(TAG, "Install of package " + info.packageName
6377                                    + " succeeded but now not found");
6378                            okay = false;
6379                        }
6380                    }
6381
6382                    // If we're not okay at this point, we need to delete the package
6383                    // that we just installed.
6384                    if (uninstall) {
6385                        mDeleteObserver.reset();
6386                        mPackageManager.deletePackage(mInstallObserver.mPackageName,
6387                                mDeleteObserver, 0);
6388                        mDeleteObserver.waitForCompletion();
6389                    }
6390                }
6391            } catch (IOException e) {
6392                Slog.e(TAG, "Unable to transcribe restored apk for install");
6393                okay = false;
6394            } finally {
6395                apkFile.delete();
6396            }
6397
6398            return okay;
6399        }
6400
6401        // Given an actual file content size, consume the post-content padding mandated
6402        // by the tar format.
6403        void skipTarPadding(long size, InputStream instream) throws IOException {
6404            long partial = (size + 512) % 512;
6405            if (partial > 0) {
6406                final int needed = 512 - (int)partial;
6407                if (MORE_DEBUG) {
6408                    Slog.i(TAG, "Skipping tar padding: " + needed + " bytes");
6409                }
6410                byte[] buffer = new byte[needed];
6411                if (readExactly(instream, buffer, 0, needed) == needed) {
6412                    mBytes += needed;
6413                } else throw new IOException("Unexpected EOF in padding");
6414            }
6415        }
6416
6417        // Read a widget metadata file, returning the restored blob
6418        void readMetadata(FileMetadata info, InputStream instream) throws IOException {
6419            // Fail on suspiciously large widget dump files
6420            if (info.size > 64 * 1024) {
6421                throw new IOException("Metadata too big; corrupt? size=" + info.size);
6422            }
6423
6424            byte[] buffer = new byte[(int) info.size];
6425            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
6426                mBytes += info.size;
6427            } else throw new IOException("Unexpected EOF in widget data");
6428
6429            String[] str = new String[1];
6430            int offset = extractLine(buffer, 0, str);
6431            int version = Integer.parseInt(str[0]);
6432            if (version == BACKUP_MANIFEST_VERSION) {
6433                offset = extractLine(buffer, offset, str);
6434                final String pkg = str[0];
6435                if (info.packageName.equals(pkg)) {
6436                    // Data checks out -- the rest of the buffer is a concatenation of
6437                    // binary blobs as described in the comment at writeAppWidgetData()
6438                    ByteArrayInputStream bin = new ByteArrayInputStream(buffer,
6439                            offset, buffer.length - offset);
6440                    DataInputStream in = new DataInputStream(bin);
6441                    while (bin.available() > 0) {
6442                        int token = in.readInt();
6443                        int size = in.readInt();
6444                        if (size > 64 * 1024) {
6445                            throw new IOException("Datum "
6446                                    + Integer.toHexString(token)
6447                                    + " too big; corrupt? size=" + info.size);
6448                        }
6449                        switch (token) {
6450                            case BACKUP_WIDGET_METADATA_TOKEN:
6451                            {
6452                                if (MORE_DEBUG) {
6453                                    Slog.i(TAG, "Got widget metadata for " + info.packageName);
6454                                }
6455                                mWidgetData = new byte[size];
6456                                in.read(mWidgetData);
6457                                break;
6458                            }
6459                            default:
6460                            {
6461                                if (DEBUG) {
6462                                    Slog.i(TAG, "Ignoring metadata blob "
6463                                            + Integer.toHexString(token)
6464                                            + " for " + info.packageName);
6465                                }
6466                                in.skipBytes(size);
6467                                break;
6468                            }
6469                        }
6470                    }
6471                } else {
6472                    Slog.w(TAG, "Metadata mismatch: package " + info.packageName
6473                            + " but widget data for " + pkg);
6474
6475                    Bundle monitoringExtras = putMonitoringExtra(null,
6476                            EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName);
6477                    monitoringExtras = putMonitoringExtra(monitoringExtras,
6478                            BackupManagerMonitor.EXTRA_LOG_WIDGET_PACKAGE_NAME, pkg);
6479                    mMonitor = monitorEvent(mMonitor,
6480                            BackupManagerMonitor.LOG_EVENT_ID_WIDGET_METADATA_MISMATCH,
6481                            null,
6482                            LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6483                            monitoringExtras);
6484                }
6485            } else {
6486                Slog.w(TAG, "Unsupported metadata version " + version);
6487
6488                Bundle monitoringExtras = putMonitoringExtra(null, EXTRA_LOG_EVENT_PACKAGE_NAME,
6489                        info.packageName);
6490                monitoringExtras = putMonitoringExtra(monitoringExtras,
6491                        EXTRA_LOG_EVENT_PACKAGE_VERSION, version);
6492                mMonitor = monitorEvent(mMonitor,
6493                        BackupManagerMonitor.LOG_EVENT_ID_WIDGET_UNKNOWN_VERSION,
6494                        null,
6495                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6496                        monitoringExtras);
6497            }
6498        }
6499
6500        // Returns a policy constant
6501        RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
6502                throws IOException {
6503            // Fail on suspiciously large manifest files
6504            if (info.size > 64 * 1024) {
6505                throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
6506            }
6507
6508            byte[] buffer = new byte[(int) info.size];
6509            if (MORE_DEBUG) {
6510                Slog.i(TAG, "   readAppManifest() looking for " + info.size + " bytes, "
6511                        + mBytes + " already consumed");
6512            }
6513            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
6514                mBytes += info.size;
6515            } else throw new IOException("Unexpected EOF in manifest");
6516
6517            RestorePolicy policy = RestorePolicy.IGNORE;
6518            String[] str = new String[1];
6519            int offset = 0;
6520
6521            try {
6522                offset = extractLine(buffer, offset, str);
6523                int version = Integer.parseInt(str[0]);
6524                if (version == BACKUP_MANIFEST_VERSION) {
6525                    offset = extractLine(buffer, offset, str);
6526                    String manifestPackage = str[0];
6527                    // TODO: handle <original-package>
6528                    if (manifestPackage.equals(info.packageName)) {
6529                        offset = extractLine(buffer, offset, str);
6530                        version = Integer.parseInt(str[0]);  // app version
6531                        offset = extractLine(buffer, offset, str);
6532                        // This is the platform version, which we don't use, but we parse it
6533                        // as a safety against corruption in the manifest.
6534                        Integer.parseInt(str[0]);
6535                        offset = extractLine(buffer, offset, str);
6536                        info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
6537                        offset = extractLine(buffer, offset, str);
6538                        boolean hasApk = str[0].equals("1");
6539                        offset = extractLine(buffer, offset, str);
6540                        int numSigs = Integer.parseInt(str[0]);
6541                        if (numSigs > 0) {
6542                            Signature[] sigs = new Signature[numSigs];
6543                            for (int i = 0; i < numSigs; i++) {
6544                                offset = extractLine(buffer, offset, str);
6545                                sigs[i] = new Signature(str[0]);
6546                            }
6547                            mManifestSignatures.put(info.packageName, sigs);
6548
6549                            // Okay, got the manifest info we need...
6550                            try {
6551                                PackageInfo pkgInfo = mPackageManager.getPackageInfo(
6552                                        info.packageName, PackageManager.GET_SIGNATURES);
6553                                // Fall through to IGNORE if the app explicitly disallows backup
6554                                final int flags = pkgInfo.applicationInfo.flags;
6555                                if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
6556                                    // Restore system-uid-space packages only if they have
6557                                    // defined a custom backup agent
6558                                    if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
6559                                            || (pkgInfo.applicationInfo.backupAgentName != null)) {
6560                                        // Verify signatures against any installed version; if they
6561                                        // don't match, then we fall though and ignore the data.  The
6562                                        // signatureMatch() method explicitly ignores the signature
6563                                        // check for packages installed on the system partition, because
6564                                        // such packages are signed with the platform cert instead of
6565                                        // the app developer's cert, so they're different on every
6566                                        // device.
6567                                        if (signaturesMatch(sigs, pkgInfo)) {
6568                                            if ((pkgInfo.applicationInfo.flags
6569                                                    & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) != 0) {
6570                                                Slog.i(TAG, "Package has restoreAnyVersion; taking data");
6571                                                mMonitor = monitorEvent(mMonitor,
6572                                                        LOG_EVENT_ID_RESTORE_ANY_VERSION,
6573                                                        pkgInfo,
6574                                                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6575                                                        null);
6576                                                policy = RestorePolicy.ACCEPT;
6577                                            } else if (pkgInfo.versionCode >= version) {
6578                                                Slog.i(TAG, "Sig + version match; taking data");
6579                                                policy = RestorePolicy.ACCEPT;
6580                                                mMonitor = monitorEvent(mMonitor,
6581                                                        LOG_EVENT_ID_VERSIONS_MATCH,
6582                                                        pkgInfo,
6583                                                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6584                                                        null);
6585                                            } else {
6586                                                // The data is from a newer version of the app than
6587                                                // is presently installed.  That means we can only
6588                                                // use it if the matching apk is also supplied.
6589                                                if (mAllowApks) {
6590                                                    Slog.i(TAG, "Data version " + version
6591                                                            + " is newer than installed version "
6592                                                            + pkgInfo.versionCode
6593                                                            + " - requiring apk");
6594                                                    policy = RestorePolicy.ACCEPT_IF_APK;
6595                                                } else {
6596                                                    Slog.i(TAG, "Data requires newer version "
6597                                                            + version + "; ignoring");
6598                                                    mMonitor = monitorEvent(mMonitor,
6599                                                            LOG_EVENT_ID_VERSION_OF_BACKUP_OLDER,
6600                                                            pkgInfo,
6601                                                            LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6602                                                            putMonitoringExtra(null,
6603                                                                    EXTRA_LOG_OLD_VERSION,
6604                                                                    version));
6605
6606                                                    policy = RestorePolicy.IGNORE;
6607                                                }
6608                                            }
6609                                        } else {
6610                                            Slog.w(TAG, "Restore manifest signatures do not match "
6611                                                    + "installed application for " + info.packageName);
6612                                            mMonitor = monitorEvent(mMonitor,
6613                                                    LOG_EVENT_ID_FULL_RESTORE_SIGNATURE_MISMATCH,
6614                                                    pkgInfo,
6615                                                    LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6616                                                    null);
6617                                        }
6618                                    } else {
6619                                        Slog.w(TAG, "Package " + info.packageName
6620                                                + " is system level with no agent");
6621                                        mMonitor = monitorEvent(mMonitor,
6622                                                LOG_EVENT_ID_SYSTEM_APP_NO_AGENT,
6623                                                pkgInfo,
6624                                                LOG_EVENT_CATEGORY_AGENT,
6625                                                null);
6626                                    }
6627                                } else {
6628                                    if (DEBUG) Slog.i(TAG, "Restore manifest from "
6629                                            + info.packageName + " but allowBackup=false");
6630                                    mMonitor = monitorEvent(mMonitor,
6631                                            LOG_EVENT_ID_FULL_RESTORE_ALLOW_BACKUP_FALSE,
6632                                            pkgInfo,
6633                                            LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6634                                            null);
6635                                }
6636                            } catch (NameNotFoundException e) {
6637                                // Okay, the target app isn't installed.  We can process
6638                                // the restore properly only if the dataset provides the
6639                                // apk file and we can successfully install it.
6640                                if (mAllowApks) {
6641                                    if (DEBUG) Slog.i(TAG, "Package " + info.packageName
6642                                            + " not installed; requiring apk in dataset");
6643                                    policy = RestorePolicy.ACCEPT_IF_APK;
6644                                } else {
6645                                    policy = RestorePolicy.IGNORE;
6646                                }
6647                                Bundle monitoringExtras = putMonitoringExtra(null,
6648                                        EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName);
6649                                monitoringExtras = putMonitoringExtra(monitoringExtras,
6650                                        EXTRA_LOG_POLICY_ALLOW_APKS, mAllowApks);
6651                                mMonitor = monitorEvent(mMonitor,
6652                                        LOG_EVENT_ID_APK_NOT_INSTALLED,
6653                                        null,
6654                                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6655                                        monitoringExtras);
6656                            }
6657
6658                            if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
6659                                Slog.i(TAG, "Cannot restore package " + info.packageName
6660                                        + " without the matching .apk");
6661                                mMonitor = monitorEvent(mMonitor,
6662                                        LOG_EVENT_ID_CANNOT_RESTORE_WITHOUT_APK,
6663                                        null,
6664                                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6665                                        putMonitoringExtra(null,
6666                                                EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName));
6667                            }
6668                        } else {
6669                            Slog.i(TAG, "Missing signature on backed-up package "
6670                                    + info.packageName);
6671                            mMonitor = monitorEvent(mMonitor,
6672                                    LOG_EVENT_ID_MISSING_SIGNATURE,
6673                                    null,
6674                                    LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6675                                    putMonitoringExtra(null,
6676                                            EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName));
6677                        }
6678                    } else {
6679                        Slog.i(TAG, "Expected package " + info.packageName
6680                                + " but restore manifest claims " + manifestPackage);
6681                        Bundle monitoringExtras = putMonitoringExtra(null,
6682                                EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName);
6683                        monitoringExtras = putMonitoringExtra(monitoringExtras,
6684                                EXTRA_LOG_MANIFEST_PACKAGE_NAME, manifestPackage);
6685                        mMonitor = monitorEvent(mMonitor,
6686                                LOG_EVENT_ID_EXPECTED_DIFFERENT_PACKAGE,
6687                                null,
6688                                LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6689                                monitoringExtras);
6690                    }
6691                } else {
6692                    Slog.i(TAG, "Unknown restore manifest version " + version
6693                            + " for package " + info.packageName);
6694                    Bundle monitoringExtras = putMonitoringExtra(null,
6695                            EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName);
6696                    monitoringExtras = putMonitoringExtra(monitoringExtras,
6697                            EXTRA_LOG_EVENT_PACKAGE_VERSION, version);
6698                    mMonitor = monitorEvent(mMonitor,
6699                            BackupManagerMonitor.LOG_EVENT_ID_UNKNOWN_VERSION,
6700                            null,
6701                            LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6702                            monitoringExtras);
6703
6704                }
6705            } catch (NumberFormatException e) {
6706                Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
6707                mMonitor = monitorEvent(mMonitor,
6708                        BackupManagerMonitor.LOG_EVENT_ID_CORRUPT_MANIFEST,
6709                        null,
6710                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6711                        putMonitoringExtra(null, EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName));
6712            } catch (IllegalArgumentException e) {
6713                Slog.w(TAG, e.getMessage());
6714            }
6715
6716            return policy;
6717        }
6718
6719        // Builds a line from a byte buffer starting at 'offset', and returns
6720        // the index of the next unconsumed data in the buffer.
6721        int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
6722            final int end = buffer.length;
6723            if (offset >= end) throw new IOException("Incomplete data");
6724
6725            int pos;
6726            for (pos = offset; pos < end; pos++) {
6727                byte c = buffer[pos];
6728                // at LF we declare end of line, and return the next char as the
6729                // starting point for the next time through
6730                if (c == '\n') {
6731                    break;
6732                }
6733            }
6734            outStr[0] = new String(buffer, offset, pos - offset);
6735            pos++;  // may be pointing an extra byte past the end but that's okay
6736            return pos;
6737        }
6738
6739        void dumpFileMetadata(FileMetadata info) {
6740            if (MORE_DEBUG) {
6741                StringBuilder b = new StringBuilder(128);
6742
6743                // mode string
6744                b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
6745                b.append(((info.mode & 0400) != 0) ? 'r' : '-');
6746                b.append(((info.mode & 0200) != 0) ? 'w' : '-');
6747                b.append(((info.mode & 0100) != 0) ? 'x' : '-');
6748                b.append(((info.mode & 0040) != 0) ? 'r' : '-');
6749                b.append(((info.mode & 0020) != 0) ? 'w' : '-');
6750                b.append(((info.mode & 0010) != 0) ? 'x' : '-');
6751                b.append(((info.mode & 0004) != 0) ? 'r' : '-');
6752                b.append(((info.mode & 0002) != 0) ? 'w' : '-');
6753                b.append(((info.mode & 0001) != 0) ? 'x' : '-');
6754                b.append(String.format(" %9d ", info.size));
6755
6756                Date stamp = new Date(info.mtime);
6757                b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp));
6758
6759                b.append(info.packageName);
6760                b.append(" :: ");
6761                b.append(info.domain);
6762                b.append(" :: ");
6763                b.append(info.path);
6764
6765                Slog.i(TAG, b.toString());
6766            }
6767        }
6768
6769        // Consume a tar file header block [sequence] and accumulate the relevant metadata
6770        FileMetadata readTarHeaders(InputStream instream) throws IOException {
6771            byte[] block = new byte[512];
6772            FileMetadata info = null;
6773
6774            boolean gotHeader = readTarHeader(instream, block);
6775            if (gotHeader) {
6776                try {
6777                    // okay, presume we're okay, and extract the various metadata
6778                    info = new FileMetadata();
6779                    info.size = extractRadix(block, TAR_HEADER_OFFSET_FILESIZE,
6780                            TAR_HEADER_LENGTH_FILESIZE, TAR_HEADER_LONG_RADIX);
6781                    info.mtime = extractRadix(block, TAR_HEADER_OFFSET_MODTIME,
6782                            TAR_HEADER_LENGTH_MODTIME, TAR_HEADER_LONG_RADIX);
6783                    info.mode = extractRadix(block, TAR_HEADER_OFFSET_MODE,
6784                            TAR_HEADER_LENGTH_MODE, TAR_HEADER_LONG_RADIX);
6785
6786                    info.path = extractString(block, TAR_HEADER_OFFSET_PATH_PREFIX,
6787                            TAR_HEADER_LENGTH_PATH_PREFIX);
6788                    String path = extractString(block, TAR_HEADER_OFFSET_PATH,
6789                            TAR_HEADER_LENGTH_PATH);
6790                    if (path.length() > 0) {
6791                        if (info.path.length() > 0) info.path += '/';
6792                        info.path += path;
6793                    }
6794
6795                    // tar link indicator field: 1 byte at offset 156 in the header.
6796                    int typeChar = block[TAR_HEADER_OFFSET_TYPE_CHAR];
6797                    if (typeChar == 'x') {
6798                        // pax extended header, so we need to read that
6799                        gotHeader = readPaxExtendedHeader(instream, info);
6800                        if (gotHeader) {
6801                            // and after a pax extended header comes another real header -- read
6802                            // that to find the real file type
6803                            gotHeader = readTarHeader(instream, block);
6804                        }
6805                        if (!gotHeader) throw new IOException("Bad or missing pax header");
6806
6807                        typeChar = block[TAR_HEADER_OFFSET_TYPE_CHAR];
6808                    }
6809
6810                    switch (typeChar) {
6811                        case '0': info.type = BackupAgent.TYPE_FILE; break;
6812                        case '5': {
6813                            info.type = BackupAgent.TYPE_DIRECTORY;
6814                            if (info.size != 0) {
6815                                Slog.w(TAG, "Directory entry with nonzero size in header");
6816                                info.size = 0;
6817                            }
6818                            break;
6819                        }
6820                        case 0: {
6821                            // presume EOF
6822                            if (MORE_DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
6823                            return null;
6824                        }
6825                        default: {
6826                            Slog.e(TAG, "Unknown tar entity type: " + typeChar);
6827                            throw new IOException("Unknown entity type " + typeChar);
6828                        }
6829                    }
6830
6831                    // Parse out the path
6832                    //
6833                    // first: apps/shared/unrecognized
6834                    if (FullBackup.SHARED_PREFIX.regionMatches(0,
6835                            info.path, 0, FullBackup.SHARED_PREFIX.length())) {
6836                        // File in shared storage.  !!! TODO: implement this.
6837                        info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
6838                        info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
6839                        info.domain = FullBackup.SHARED_STORAGE_TOKEN;
6840                        if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
6841                    } else if (FullBackup.APPS_PREFIX.regionMatches(0,
6842                            info.path, 0, FullBackup.APPS_PREFIX.length())) {
6843                        // App content!  Parse out the package name and domain
6844
6845                        // strip the apps/ prefix
6846                        info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
6847
6848                        // extract the package name
6849                        int slash = info.path.indexOf('/');
6850                        if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
6851                        info.packageName = info.path.substring(0, slash);
6852                        info.path = info.path.substring(slash+1);
6853
6854                        // if it's a manifest or metadata payload we're done, otherwise parse
6855                        // out the domain into which the file will be restored
6856                        if (!info.path.equals(BACKUP_MANIFEST_FILENAME)
6857                                && !info.path.equals(BACKUP_METADATA_FILENAME)) {
6858                            slash = info.path.indexOf('/');
6859                            if (slash < 0) {
6860                                throw new IOException("Illegal semantic path in non-manifest "
6861                                        + info.path);
6862                            }
6863                            info.domain = info.path.substring(0, slash);
6864                            info.path = info.path.substring(slash + 1);
6865                        }
6866                    }
6867                } catch (IOException e) {
6868                    if (DEBUG) {
6869                        Slog.e(TAG, "Parse error in header: " + e.getMessage());
6870                        if (MORE_DEBUG) {
6871                            HEXLOG(block);
6872                        }
6873                    }
6874                    throw e;
6875                }
6876            }
6877            return info;
6878        }
6879
6880        private boolean isRestorableFile(FileMetadata info) {
6881            if (FullBackup.CACHE_TREE_TOKEN.equals(info.domain)) {
6882                if (MORE_DEBUG) {
6883                    Slog.i(TAG, "Dropping cache file path " + info.path);
6884                }
6885                return false;
6886            }
6887
6888            if (FullBackup.ROOT_TREE_TOKEN.equals(info.domain)) {
6889                // It's possible this is "no-backup" dir contents in an archive stream
6890                // produced on a device running a version of the OS that predates that
6891                // API.  Respect the no-backup intention and don't let the data get to
6892                // the app.
6893                if (info.path.startsWith("no_backup/")) {
6894                    if (MORE_DEBUG) {
6895                        Slog.i(TAG, "Dropping no_backup file path " + info.path);
6896                    }
6897                    return false;
6898                }
6899            }
6900
6901            // The path needs to be canonical
6902            if (info.path.contains("..") || info.path.contains("//")) {
6903                if (MORE_DEBUG) {
6904                    Slog.w(TAG, "Dropping invalid path " + info.path);
6905                }
6906                return false;
6907            }
6908
6909            // Otherwise we think this file is good to go
6910            return true;
6911        }
6912
6913        private void HEXLOG(byte[] block) {
6914            int offset = 0;
6915            int todo = block.length;
6916            StringBuilder buf = new StringBuilder(64);
6917            while (todo > 0) {
6918                buf.append(String.format("%04x   ", offset));
6919                int numThisLine = (todo > 16) ? 16 : todo;
6920                for (int i = 0; i < numThisLine; i++) {
6921                    buf.append(String.format("%02x ", block[offset+i]));
6922                }
6923                Slog.i("hexdump", buf.toString());
6924                buf.setLength(0);
6925                todo -= numThisLine;
6926                offset += numThisLine;
6927            }
6928        }
6929
6930        // Read exactly the given number of bytes into a buffer at the stated offset.
6931        // Returns false if EOF is encountered before the requested number of bytes
6932        // could be read.
6933        int readExactly(InputStream in, byte[] buffer, int offset, int size)
6934                throws IOException {
6935            if (size <= 0) throw new IllegalArgumentException("size must be > 0");
6936if (MORE_DEBUG) Slog.i(TAG, "  ... readExactly(" + size + ") called");
6937            int soFar = 0;
6938            while (soFar < size) {
6939                int nRead = in.read(buffer, offset + soFar, size - soFar);
6940                if (nRead <= 0) {
6941                    if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
6942                    break;
6943                }
6944                soFar += nRead;
6945if (MORE_DEBUG) Slog.v(TAG, "   + got " + nRead + "; now wanting " + (size - soFar));
6946            }
6947            return soFar;
6948        }
6949
6950        boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
6951            final int got = readExactly(instream, block, 0, 512);
6952            if (got == 0) return false;     // Clean EOF
6953            if (got < 512) throw new IOException("Unable to read full block header");
6954            mBytes += 512;
6955            return true;
6956        }
6957
6958        // overwrites 'info' fields based on the pax extended header
6959        boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
6960                throws IOException {
6961            // We should never see a pax extended header larger than this
6962            if (info.size > 32*1024) {
6963                Slog.w(TAG, "Suspiciously large pax header size " + info.size
6964                        + " - aborting");
6965                throw new IOException("Sanity failure: pax header size " + info.size);
6966            }
6967
6968            // read whole blocks, not just the content size
6969            int numBlocks = (int)((info.size + 511) >> 9);
6970            byte[] data = new byte[numBlocks * 512];
6971            if (readExactly(instream, data, 0, data.length) < data.length) {
6972                throw new IOException("Unable to read full pax header");
6973            }
6974            mBytes += data.length;
6975
6976            final int contentSize = (int) info.size;
6977            int offset = 0;
6978            do {
6979                // extract the line at 'offset'
6980                int eol = offset+1;
6981                while (eol < contentSize && data[eol] != ' ') eol++;
6982                if (eol >= contentSize) {
6983                    // error: we just hit EOD looking for the end of the size field
6984                    throw new IOException("Invalid pax data");
6985                }
6986                // eol points to the space between the count and the key
6987                int linelen = (int) extractRadix(data, offset, eol - offset, 10);
6988                int key = eol + 1;  // start of key=value
6989                eol = offset + linelen - 1; // trailing LF
6990                int value;
6991                for (value = key+1; data[value] != '=' && value <= eol; value++);
6992                if (value > eol) {
6993                    throw new IOException("Invalid pax declaration");
6994                }
6995
6996                // pax requires that key/value strings be in UTF-8
6997                String keyStr = new String(data, key, value-key, "UTF-8");
6998                // -1 to strip the trailing LF
6999                String valStr = new String(data, value+1, eol-value-1, "UTF-8");
7000
7001                if ("path".equals(keyStr)) {
7002                    info.path = valStr;
7003                } else if ("size".equals(keyStr)) {
7004                    info.size = Long.parseLong(valStr);
7005                } else {
7006                    if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
7007                }
7008
7009                offset += linelen;
7010            } while (offset < contentSize);
7011
7012            return true;
7013        }
7014
7015        long extractRadix(byte[] data, int offset, int maxChars, int radix)
7016                throws IOException {
7017            long value = 0;
7018            final int end = offset + maxChars;
7019            for (int i = offset; i < end; i++) {
7020                final byte b = data[i];
7021                // Numeric fields in tar can terminate with either NUL or SPC
7022                if (b == 0 || b == ' ') break;
7023                if (b < '0' || b > ('0' + radix - 1)) {
7024                    throw new IOException("Invalid number in header: '" + (char)b
7025                            + "' for radix " + radix);
7026                }
7027                value = radix * value + (b - '0');
7028            }
7029            return value;
7030        }
7031
7032        String extractString(byte[] data, int offset, int maxChars) throws IOException {
7033            final int end = offset + maxChars;
7034            int eos = offset;
7035            // tar string fields terminate early with a NUL
7036            while (eos < end && data[eos] != 0) eos++;
7037            return new String(data, offset, eos-offset, "US-ASCII");
7038        }
7039
7040        void sendStartRestore() {
7041            if (mObserver != null) {
7042                try {
7043                    mObserver.onStartRestore();
7044                } catch (RemoteException e) {
7045                    Slog.w(TAG, "full restore observer went away: startRestore");
7046                    mObserver = null;
7047                }
7048            }
7049        }
7050
7051        void sendOnRestorePackage(String name) {
7052            if (mObserver != null) {
7053                try {
7054                    // TODO: use a more user-friendly name string
7055                    mObserver.onRestorePackage(name);
7056                } catch (RemoteException e) {
7057                    Slog.w(TAG, "full restore observer went away: restorePackage");
7058                    mObserver = null;
7059                }
7060            }
7061        }
7062
7063        void sendEndRestore() {
7064            if (mObserver != null) {
7065                try {
7066                    mObserver.onEndRestore();
7067                } catch (RemoteException e) {
7068                    Slog.w(TAG, "full restore observer went away: endRestore");
7069                    mObserver = null;
7070                }
7071            }
7072        }
7073    }
7074
7075    // ***** end new engine class ***
7076
7077    // Used for synchronizing doRestoreFinished during adb restore
7078    class AdbRestoreFinishedLatch implements BackupRestoreTask {
7079        static final String TAG = "AdbRestoreFinishedLatch";
7080        final CountDownLatch mLatch;
7081        private final int mCurrentOpToken;
7082
7083        AdbRestoreFinishedLatch(int currentOpToken) {
7084            mLatch = new CountDownLatch(1);
7085            mCurrentOpToken = currentOpToken;
7086        }
7087
7088        void await() {
7089            boolean latched = false;
7090            try {
7091                latched = mLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
7092            } catch (InterruptedException e) {
7093                Slog.w(TAG, "Interrupted!");
7094            }
7095        }
7096
7097        @Override
7098        public void execute() {
7099            // Unused
7100        }
7101
7102        @Override
7103        public void operationComplete(long result) {
7104            if (MORE_DEBUG) {
7105                Slog.w(TAG, "adb onRestoreFinished() complete");
7106            }
7107            mLatch.countDown();
7108            removeOperation(mCurrentOpToken);
7109        }
7110
7111        @Override
7112        public void handleCancel(boolean cancelAll) {
7113            if (DEBUG) {
7114                Slog.w(TAG, "adb onRestoreFinished() timed out");
7115            }
7116            mLatch.countDown();
7117            removeOperation(mCurrentOpToken);
7118        }
7119    }
7120
7121    class PerformAdbRestoreTask implements Runnable {
7122        ParcelFileDescriptor mInputFile;
7123        String mCurrentPassword;
7124        String mDecryptPassword;
7125        IFullBackupRestoreObserver mObserver;
7126        AtomicBoolean mLatchObject;
7127        IBackupAgent mAgent;
7128        PackageManagerBackupAgent mPackageManagerBackupAgent;
7129        String mAgentPackage;
7130        ApplicationInfo mTargetApp;
7131        FullBackupObbConnection mObbConnection = null;
7132        ParcelFileDescriptor[] mPipes = null;
7133        byte[] mWidgetData = null;
7134
7135        long mBytes;
7136
7137        // Runner that can be placed on a separate thread to do in-process invocation
7138        // of the "restore finished" API asynchronously.  Used by adb restore.
7139        class RestoreFinishedRunnable implements Runnable {
7140            final IBackupAgent mAgent;
7141            final int mToken;
7142
7143            RestoreFinishedRunnable(IBackupAgent agent, int token) {
7144                mAgent = agent;
7145                mToken = token;
7146            }
7147
7148            @Override
7149            public void run() {
7150                try {
7151                    mAgent.doRestoreFinished(mToken, mBackupManagerBinder);
7152                } catch (RemoteException e) {
7153                    // never happens; this is used only for local binder calls
7154                }
7155            }
7156        }
7157
7158        // possible handling states for a given package in the restore dataset
7159        final HashMap<String, RestorePolicy> mPackagePolicies
7160                = new HashMap<String, RestorePolicy>();
7161
7162        // installer package names for each encountered app, derived from the manifests
7163        final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
7164
7165        // Signatures for a given package found in its manifest file
7166        final HashMap<String, Signature[]> mManifestSignatures
7167                = new HashMap<String, Signature[]>();
7168
7169        // Packages we've already wiped data on when restoring their first file
7170        final HashSet<String> mClearedPackages = new HashSet<String>();
7171
7172        PerformAdbRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
7173                IFullBackupRestoreObserver observer, AtomicBoolean latch) {
7174            mInputFile = fd;
7175            mCurrentPassword = curPassword;
7176            mDecryptPassword = decryptPassword;
7177            mObserver = observer;
7178            mLatchObject = latch;
7179            mAgent = null;
7180            mPackageManagerBackupAgent = makeMetadataAgent();
7181            mAgentPackage = null;
7182            mTargetApp = null;
7183            mObbConnection = new FullBackupObbConnection();
7184
7185            // Which packages we've already wiped data on.  We prepopulate this
7186            // with a whitelist of packages known to be unclearable.
7187            mClearedPackages.add("android");
7188            mClearedPackages.add(SETTINGS_PACKAGE);
7189        }
7190
7191        class RestoreFileRunnable implements Runnable {
7192            IBackupAgent mAgent;
7193            FileMetadata mInfo;
7194            ParcelFileDescriptor mSocket;
7195            int mToken;
7196
7197            RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
7198                    ParcelFileDescriptor socket, int token) throws IOException {
7199                mAgent = agent;
7200                mInfo = info;
7201                mToken = token;
7202
7203                // This class is used strictly for process-local binder invocations.  The
7204                // semantics of ParcelFileDescriptor differ in this case; in particular, we
7205                // do not automatically get a 'dup'ed descriptor that we can can continue
7206                // to use asynchronously from the caller.  So, we make sure to dup it ourselves
7207                // before proceeding to do the restore.
7208                mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
7209            }
7210
7211            @Override
7212            public void run() {
7213                try {
7214                    mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
7215                            mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
7216                            mToken, mBackupManagerBinder);
7217                } catch (RemoteException e) {
7218                    // never happens; this is used strictly for local binder calls
7219                }
7220            }
7221        }
7222
7223        @Override
7224        public void run() {
7225            Slog.i(TAG, "--- Performing full-dataset restore ---");
7226            mObbConnection.establish();
7227            sendStartRestore();
7228
7229            // Are we able to restore shared-storage data?
7230            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
7231                mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
7232            }
7233
7234            FileInputStream rawInStream = null;
7235            DataInputStream rawDataIn = null;
7236            try {
7237                if (!backupPasswordMatches(mCurrentPassword)) {
7238                    if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
7239                    return;
7240                }
7241
7242                mBytes = 0;
7243                byte[] buffer = new byte[32 * 1024];
7244                rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
7245                rawDataIn = new DataInputStream(rawInStream);
7246
7247                // First, parse out the unencrypted/uncompressed header
7248                boolean compressed = false;
7249                InputStream preCompressStream = rawInStream;
7250                final InputStream in;
7251
7252                boolean okay = false;
7253                final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
7254                byte[] streamHeader = new byte[headerLen];
7255                rawDataIn.readFully(streamHeader);
7256                byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
7257                if (Arrays.equals(magicBytes, streamHeader)) {
7258                    // okay, header looks good.  now parse out the rest of the fields.
7259                    String s = readHeaderLine(rawInStream);
7260                    final int archiveVersion = Integer.parseInt(s);
7261                    if (archiveVersion <= BACKUP_FILE_VERSION) {
7262                        // okay, it's a version we recognize.  if it's version 1, we may need
7263                        // to try two different PBKDF2 regimes to compare checksums.
7264                        final boolean pbkdf2Fallback = (archiveVersion == 1);
7265
7266                        s = readHeaderLine(rawInStream);
7267                        compressed = (Integer.parseInt(s) != 0);
7268                        s = readHeaderLine(rawInStream);
7269                        if (s.equals("none")) {
7270                            // no more header to parse; we're good to go
7271                            okay = true;
7272                        } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
7273                            preCompressStream = decodeAesHeaderAndInitialize(s, pbkdf2Fallback,
7274                                    rawInStream);
7275                            if (preCompressStream != null) {
7276                                okay = true;
7277                            }
7278                        } else Slog.w(TAG, "Archive is encrypted but no password given");
7279                    } else Slog.w(TAG, "Wrong header version: " + s);
7280                } else Slog.w(TAG, "Didn't read the right header magic");
7281
7282                if (!okay) {
7283                    Slog.w(TAG, "Invalid restore data; aborting.");
7284                    return;
7285                }
7286
7287                // okay, use the right stream layer based on compression
7288                in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
7289
7290                boolean didRestore;
7291                do {
7292                    didRestore = restoreOneFile(in, buffer);
7293                } while (didRestore);
7294
7295                if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
7296            } catch (IOException e) {
7297                Slog.e(TAG, "Unable to read restore input");
7298            } finally {
7299                tearDownPipes();
7300                tearDownAgent(mTargetApp, true);
7301
7302                try {
7303                    if (rawDataIn != null) rawDataIn.close();
7304                    if (rawInStream != null) rawInStream.close();
7305                    mInputFile.close();
7306                } catch (IOException e) {
7307                    Slog.w(TAG, "Close of restore data pipe threw", e);
7308                    /* nothing we can do about this */
7309                }
7310                synchronized (mLatchObject) {
7311                    mLatchObject.set(true);
7312                    mLatchObject.notifyAll();
7313                }
7314                mObbConnection.tearDown();
7315                sendEndRestore();
7316                Slog.d(TAG, "Full restore pass complete.");
7317                mWakelock.release();
7318            }
7319        }
7320
7321        String readHeaderLine(InputStream in) throws IOException {
7322            int c;
7323            StringBuilder buffer = new StringBuilder(80);
7324            while ((c = in.read()) >= 0) {
7325                if (c == '\n') break;   // consume and discard the newlines
7326                buffer.append((char)c);
7327            }
7328            return buffer.toString();
7329        }
7330
7331        InputStream attemptMasterKeyDecryption(String algorithm, byte[] userSalt, byte[] ckSalt,
7332                int rounds, String userIvHex, String masterKeyBlobHex, InputStream rawInStream,
7333                boolean doLog) {
7334            InputStream result = null;
7335
7336            try {
7337                Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
7338                SecretKey userKey = buildPasswordKey(algorithm, mDecryptPassword, userSalt,
7339                        rounds);
7340                byte[] IV = hexToByteArray(userIvHex);
7341                IvParameterSpec ivSpec = new IvParameterSpec(IV);
7342                c.init(Cipher.DECRYPT_MODE,
7343                        new SecretKeySpec(userKey.getEncoded(), "AES"),
7344                        ivSpec);
7345                byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
7346                byte[] mkBlob = c.doFinal(mkCipher);
7347
7348                // first, the master key IV
7349                int offset = 0;
7350                int len = mkBlob[offset++];
7351                IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
7352                offset += len;
7353                // then the master key itself
7354                len = mkBlob[offset++];
7355                byte[] mk = Arrays.copyOfRange(mkBlob,
7356                        offset, offset + len);
7357                offset += len;
7358                // and finally the master key checksum hash
7359                len = mkBlob[offset++];
7360                byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
7361                        offset, offset + len);
7362
7363                // now validate the decrypted master key against the checksum
7364                byte[] calculatedCk = makeKeyChecksum(algorithm, mk, ckSalt, rounds);
7365                if (Arrays.equals(calculatedCk, mkChecksum)) {
7366                    ivSpec = new IvParameterSpec(IV);
7367                    c.init(Cipher.DECRYPT_MODE,
7368                            new SecretKeySpec(mk, "AES"),
7369                            ivSpec);
7370                    // Only if all of the above worked properly will 'result' be assigned
7371                    result = new CipherInputStream(rawInStream, c);
7372                } else if (doLog) Slog.w(TAG, "Incorrect password");
7373            } catch (InvalidAlgorithmParameterException e) {
7374                if (doLog) Slog.e(TAG, "Needed parameter spec unavailable!", e);
7375            } catch (BadPaddingException e) {
7376                // This case frequently occurs when the wrong password is used to decrypt
7377                // the master key.  Use the identical "incorrect password" log text as is
7378                // used in the checksum failure log in order to avoid providing additional
7379                // information to an attacker.
7380                if (doLog) Slog.w(TAG, "Incorrect password");
7381            } catch (IllegalBlockSizeException e) {
7382                if (doLog) Slog.w(TAG, "Invalid block size in master key");
7383            } catch (NoSuchAlgorithmException e) {
7384                if (doLog) Slog.e(TAG, "Needed decryption algorithm unavailable!");
7385            } catch (NoSuchPaddingException e) {
7386                if (doLog) Slog.e(TAG, "Needed padding mechanism unavailable!");
7387            } catch (InvalidKeyException e) {
7388                if (doLog) Slog.w(TAG, "Illegal password; aborting");
7389            }
7390
7391            return result;
7392        }
7393
7394        InputStream decodeAesHeaderAndInitialize(String encryptionName, boolean pbkdf2Fallback,
7395                InputStream rawInStream) {
7396            InputStream result = null;
7397            try {
7398                if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
7399
7400                    String userSaltHex = readHeaderLine(rawInStream); // 5
7401                    byte[] userSalt = hexToByteArray(userSaltHex);
7402
7403                    String ckSaltHex = readHeaderLine(rawInStream); // 6
7404                    byte[] ckSalt = hexToByteArray(ckSaltHex);
7405
7406                    int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
7407                    String userIvHex = readHeaderLine(rawInStream); // 8
7408
7409                    String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
7410
7411                    // decrypt the master key blob
7412                    result = attemptMasterKeyDecryption(PBKDF_CURRENT, userSalt, ckSalt,
7413                            rounds, userIvHex, masterKeyBlobHex, rawInStream, false);
7414                    if (result == null && pbkdf2Fallback) {
7415                        result = attemptMasterKeyDecryption(PBKDF_FALLBACK, userSalt, ckSalt,
7416                                rounds, userIvHex, masterKeyBlobHex, rawInStream, true);
7417                    }
7418                } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
7419            } catch (NumberFormatException e) {
7420                Slog.w(TAG, "Can't parse restore data header");
7421            } catch (IOException e) {
7422                Slog.w(TAG, "Can't read input header");
7423            }
7424
7425            return result;
7426        }
7427
7428        boolean restoreOneFile(InputStream instream, byte[] buffer) {
7429            FileMetadata info;
7430            try {
7431                info = readTarHeaders(instream);
7432                if (info != null) {
7433                    if (MORE_DEBUG) {
7434                        dumpFileMetadata(info);
7435                    }
7436
7437                    final String pkg = info.packageName;
7438                    if (!pkg.equals(mAgentPackage)) {
7439                        // okay, change in package; set up our various
7440                        // bookkeeping if we haven't seen it yet
7441                        if (!mPackagePolicies.containsKey(pkg)) {
7442                            mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7443                        }
7444
7445                        // Clean up the previous agent relationship if necessary,
7446                        // and let the observer know we're considering a new app.
7447                        if (mAgent != null) {
7448                            if (DEBUG) Slog.d(TAG, "Saw new package; finalizing old one");
7449                            // Now we're really done
7450                            tearDownPipes();
7451                            tearDownAgent(mTargetApp, true);
7452                            mTargetApp = null;
7453                            mAgentPackage = null;
7454                        }
7455                    }
7456
7457                    if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
7458                        mPackagePolicies.put(pkg, readAppManifest(info, instream));
7459                        mPackageInstallers.put(pkg, info.installerPackageName);
7460                        // We've read only the manifest content itself at this point,
7461                        // so consume the footer before looping around to the next
7462                        // input file
7463                        skipTarPadding(info.size, instream);
7464                        sendOnRestorePackage(pkg);
7465                    } else if (info.path.equals(BACKUP_METADATA_FILENAME)) {
7466                        // Metadata blobs!
7467                        readMetadata(info, instream);
7468                        skipTarPadding(info.size, instream);
7469                    } else {
7470                        // Non-manifest, so it's actual file data.  Is this a package
7471                        // we're ignoring?
7472                        boolean okay = true;
7473                        RestorePolicy policy = mPackagePolicies.get(pkg);
7474                        switch (policy) {
7475                            case IGNORE:
7476                                okay = false;
7477                                break;
7478
7479                            case ACCEPT_IF_APK:
7480                                // If we're in accept-if-apk state, then the first file we
7481                                // see MUST be the apk.
7482                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
7483                                    if (DEBUG) Slog.d(TAG, "APK file; installing");
7484                                    // Try to install the app.
7485                                    String installerName = mPackageInstallers.get(pkg);
7486                                    okay = installApk(info, installerName, instream);
7487                                    // good to go; promote to ACCEPT
7488                                    mPackagePolicies.put(pkg, (okay)
7489                                            ? RestorePolicy.ACCEPT
7490                                            : RestorePolicy.IGNORE);
7491                                    // At this point we've consumed this file entry
7492                                    // ourselves, so just strip the tar footer and
7493                                    // go on to the next file in the input stream
7494                                    skipTarPadding(info.size, instream);
7495                                    return true;
7496                                } else {
7497                                    // File data before (or without) the apk.  We can't
7498                                    // handle it coherently in this case so ignore it.
7499                                    mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7500                                    okay = false;
7501                                }
7502                                break;
7503
7504                            case ACCEPT:
7505                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
7506                                    if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
7507                                    // we can take the data without the apk, so we
7508                                    // *want* to do so.  skip the apk by declaring this
7509                                    // one file not-okay without changing the restore
7510                                    // policy for the package.
7511                                    okay = false;
7512                                }
7513                                break;
7514
7515                            default:
7516                                // Something has gone dreadfully wrong when determining
7517                                // the restore policy from the manifest.  Ignore the
7518                                // rest of this package's data.
7519                                Slog.e(TAG, "Invalid policy from manifest");
7520                                okay = false;
7521                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7522                                break;
7523                        }
7524
7525                        // The path needs to be canonical
7526                        if (info.path.contains("..") || info.path.contains("//")) {
7527                            if (MORE_DEBUG) {
7528                                Slog.w(TAG, "Dropping invalid path " + info.path);
7529                            }
7530                            okay = false;
7531                        }
7532
7533                        // If the policy is satisfied, go ahead and set up to pipe the
7534                        // data to the agent.
7535                        if (DEBUG && okay && mAgent != null) {
7536                            Slog.i(TAG, "Reusing existing agent instance");
7537                        }
7538                        if (okay && mAgent == null) {
7539                            if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
7540
7541                            try {
7542                                mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
7543
7544                                // If we haven't sent any data to this app yet, we probably
7545                                // need to clear it first.  Check that.
7546                                if (!mClearedPackages.contains(pkg)) {
7547                                    // apps with their own backup agents are
7548                                    // responsible for coherently managing a full
7549                                    // restore.
7550                                    if (mTargetApp.backupAgentName == null) {
7551                                        if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
7552                                        clearApplicationDataSynchronous(pkg);
7553                                    } else {
7554                                        if (DEBUG) Slog.d(TAG, "backup agent ("
7555                                                + mTargetApp.backupAgentName + ") => no clear");
7556                                    }
7557                                    mClearedPackages.add(pkg);
7558                                } else {
7559                                    if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
7560                                }
7561
7562                                // All set; now set up the IPC and launch the agent
7563                                setUpPipes();
7564                                mAgent = bindToAgentSynchronous(mTargetApp,
7565                                        ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL);
7566                                mAgentPackage = pkg;
7567                            } catch (IOException e) {
7568                                // fall through to error handling
7569                            } catch (NameNotFoundException e) {
7570                                // fall through to error handling
7571                            }
7572
7573                            if (mAgent == null) {
7574                                if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
7575                                okay = false;
7576                                tearDownPipes();
7577                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7578                            }
7579                        }
7580
7581                        // Sanity check: make sure we never give data to the wrong app.  This
7582                        // should never happen but a little paranoia here won't go amiss.
7583                        if (okay && !pkg.equals(mAgentPackage)) {
7584                            Slog.e(TAG, "Restoring data for " + pkg
7585                                    + " but agent is for " + mAgentPackage);
7586                            okay = false;
7587                        }
7588
7589                        // At this point we have an agent ready to handle the full
7590                        // restore data as well as a pipe for sending data to
7591                        // that agent.  Tell the agent to start reading from the
7592                        // pipe.
7593                        if (okay) {
7594                            boolean agentSuccess = true;
7595                            long toCopy = info.size;
7596                            final boolean isSharedStorage = pkg.equals(SHARED_BACKUP_AGENT_PACKAGE);
7597                            final long timeout = isSharedStorage ?
7598                                    TIMEOUT_SHARED_BACKUP_INTERVAL : TIMEOUT_RESTORE_INTERVAL;
7599                            final int token = generateRandomIntegerToken();
7600                            try {
7601                                prepareOperationTimeout(token, timeout, null,
7602                                        OP_TYPE_RESTORE_WAIT);
7603                                if (FullBackup.OBB_TREE_TOKEN.equals(info.domain)) {
7604                                    if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
7605                                            + " : " + info.path);
7606                                    mObbConnection.restoreObbFile(pkg, mPipes[0],
7607                                            info.size, info.type, info.path, info.mode,
7608                                            info.mtime, token, mBackupManagerBinder);
7609                                } else if (FullBackup.KEY_VALUE_DATA_TOKEN.equals(info.domain)) {
7610                                    if (DEBUG) Slog.d(TAG, "Restoring key-value file for " + pkg
7611                                            + " : " + info.path);
7612                                    KeyValueAdbRestoreEngine restoreEngine =
7613                                            new KeyValueAdbRestoreEngine(BackupManagerService.this,
7614                                                    mDataDir, info, mPipes[0], mAgent, token);
7615                                    new Thread(restoreEngine, "restore-key-value-runner").start();
7616                                } else {
7617                                    if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
7618                                            + info.path);
7619                                    // fire up the app's agent listening on the socket.  If
7620                                    // the agent is running in the system process we can't
7621                                    // just invoke it asynchronously, so we provide a thread
7622                                    // for it here.
7623                                    if (mTargetApp.processName.equals("system")) {
7624                                        Slog.d(TAG, "system process agent - spinning a thread");
7625                                        RestoreFileRunnable runner = new RestoreFileRunnable(
7626                                                mAgent, info, mPipes[0], token);
7627                                        new Thread(runner, "restore-sys-runner").start();
7628                                    } else {
7629                                        mAgent.doRestoreFile(mPipes[0], info.size, info.type,
7630                                                info.domain, info.path, info.mode, info.mtime,
7631                                                token, mBackupManagerBinder);
7632                                    }
7633                                }
7634                            } catch (IOException e) {
7635                                // couldn't dup the socket for a process-local restore
7636                                Slog.d(TAG, "Couldn't establish restore");
7637                                agentSuccess = false;
7638                                okay = false;
7639                            } catch (RemoteException e) {
7640                                // whoops, remote entity went away.  We'll eat the content
7641                                // ourselves, then, and not copy it over.
7642                                Slog.e(TAG, "Agent crashed during full restore");
7643                                agentSuccess = false;
7644                                okay = false;
7645                            }
7646
7647                            // Copy over the data if the agent is still good
7648                            if (okay) {
7649                                boolean pipeOkay = true;
7650                                FileOutputStream pipe = new FileOutputStream(
7651                                        mPipes[1].getFileDescriptor());
7652                                while (toCopy > 0) {
7653                                    int toRead = (toCopy > buffer.length)
7654                                    ? buffer.length : (int)toCopy;
7655                                    int nRead = instream.read(buffer, 0, toRead);
7656                                    if (nRead >= 0) mBytes += nRead;
7657                                    if (nRead <= 0) break;
7658                                    toCopy -= nRead;
7659
7660                                    // send it to the output pipe as long as things
7661                                    // are still good
7662                                    if (pipeOkay) {
7663                                        try {
7664                                            pipe.write(buffer, 0, nRead);
7665                                        } catch (IOException e) {
7666                                            Slog.e(TAG, "Failed to write to restore pipe", e);
7667                                            pipeOkay = false;
7668                                        }
7669                                    }
7670                                }
7671
7672                                // done sending that file!  Now we just need to consume
7673                                // the delta from info.size to the end of block.
7674                                skipTarPadding(info.size, instream);
7675
7676                                // and now that we've sent it all, wait for the remote
7677                                // side to acknowledge receipt
7678                                agentSuccess = waitUntilOperationComplete(token);
7679                            }
7680
7681                            // okay, if the remote end failed at any point, deal with
7682                            // it by ignoring the rest of the restore on it
7683                            if (!agentSuccess) {
7684                                if (DEBUG) {
7685                                    Slog.d(TAG, "Agent failure restoring " + pkg + "; now ignoring");
7686                                }
7687                                mBackupHandler.removeMessages(MSG_RESTORE_OPERATION_TIMEOUT);
7688                                tearDownPipes();
7689                                tearDownAgent(mTargetApp, false);
7690                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7691                            }
7692                        }
7693
7694                        // Problems setting up the agent communication, or an already-
7695                        // ignored package: skip to the next tar stream entry by
7696                        // reading and discarding this file.
7697                        if (!okay) {
7698                            if (DEBUG) Slog.d(TAG, "[discarding file content]");
7699                            long bytesToConsume = (info.size + 511) & ~511;
7700                            while (bytesToConsume > 0) {
7701                                int toRead = (bytesToConsume > buffer.length)
7702                                ? buffer.length : (int)bytesToConsume;
7703                                long nRead = instream.read(buffer, 0, toRead);
7704                                if (nRead >= 0) mBytes += nRead;
7705                                if (nRead <= 0) break;
7706                                bytesToConsume -= nRead;
7707                            }
7708                        }
7709                    }
7710                }
7711            } catch (IOException e) {
7712                if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
7713                // treat as EOF
7714                info = null;
7715            }
7716
7717            return (info != null);
7718        }
7719
7720        void setUpPipes() throws IOException {
7721            mPipes = ParcelFileDescriptor.createPipe();
7722        }
7723
7724        void tearDownPipes() {
7725            if (mPipes != null) {
7726                try {
7727                    mPipes[0].close();
7728                    mPipes[0] = null;
7729                    mPipes[1].close();
7730                    mPipes[1] = null;
7731                } catch (IOException e) {
7732                    Slog.w(TAG, "Couldn't close agent pipes", e);
7733                }
7734                mPipes = null;
7735            }
7736        }
7737
7738        void tearDownAgent(ApplicationInfo app, boolean doRestoreFinished) {
7739            if (mAgent != null) {
7740                try {
7741                    // In the adb restore case, we do restore-finished here
7742                    if (doRestoreFinished) {
7743                        final int token = generateRandomIntegerToken();
7744                        final AdbRestoreFinishedLatch latch = new AdbRestoreFinishedLatch(token);
7745                        prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, latch,
7746                                OP_TYPE_RESTORE_WAIT);
7747                        if (mTargetApp.processName.equals("system")) {
7748                            if (MORE_DEBUG) {
7749                                Slog.d(TAG, "system agent - restoreFinished on thread");
7750                            }
7751                            Runnable runner = new RestoreFinishedRunnable(mAgent, token);
7752                            new Thread(runner, "restore-sys-finished-runner").start();
7753                        } else {
7754                            mAgent.doRestoreFinished(token, mBackupManagerBinder);
7755                        }
7756
7757                        latch.await();
7758                    }
7759
7760                    // unbind and tidy up even on timeout or failure, just in case
7761                    mActivityManager.unbindBackupAgent(app);
7762
7763                    // The agent was running with a stub Application object, so shut it down.
7764                    // !!! We hardcode the confirmation UI's package name here rather than use a
7765                    //     manifest flag!  TODO something less direct.
7766                    if (app.uid >= Process.FIRST_APPLICATION_UID
7767                            && !app.packageName.equals("com.android.backupconfirm")) {
7768                        if (DEBUG) Slog.d(TAG, "Killing host process");
7769                        mActivityManager.killApplicationProcess(app.processName, app.uid);
7770                    } else {
7771                        if (DEBUG) Slog.d(TAG, "Not killing after full restore");
7772                    }
7773                } catch (RemoteException e) {
7774                    Slog.d(TAG, "Lost app trying to shut down");
7775                }
7776                mAgent = null;
7777            }
7778        }
7779
7780        class RestoreInstallObserver extends PackageInstallObserver {
7781            final AtomicBoolean mDone = new AtomicBoolean();
7782            String mPackageName;
7783            int mResult;
7784
7785            public void reset() {
7786                synchronized (mDone) {
7787                    mDone.set(false);
7788                }
7789            }
7790
7791            public void waitForCompletion() {
7792                synchronized (mDone) {
7793                    while (mDone.get() == false) {
7794                        try {
7795                            mDone.wait();
7796                        } catch (InterruptedException e) { }
7797                    }
7798                }
7799            }
7800
7801            int getResult() {
7802                return mResult;
7803            }
7804
7805            @Override
7806            public void onPackageInstalled(String packageName, int returnCode,
7807                    String msg, Bundle extras) {
7808                synchronized (mDone) {
7809                    mResult = returnCode;
7810                    mPackageName = packageName;
7811                    mDone.set(true);
7812                    mDone.notifyAll();
7813                }
7814            }
7815        }
7816
7817        class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
7818            final AtomicBoolean mDone = new AtomicBoolean();
7819            int mResult;
7820
7821            public void reset() {
7822                synchronized (mDone) {
7823                    mDone.set(false);
7824                }
7825            }
7826
7827            public void waitForCompletion() {
7828                synchronized (mDone) {
7829                    while (mDone.get() == false) {
7830                        try {
7831                            mDone.wait();
7832                        } catch (InterruptedException e) { }
7833                    }
7834                }
7835            }
7836
7837            @Override
7838            public void packageDeleted(String packageName, int returnCode) throws RemoteException {
7839                synchronized (mDone) {
7840                    mResult = returnCode;
7841                    mDone.set(true);
7842                    mDone.notifyAll();
7843                }
7844            }
7845        }
7846
7847        final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
7848        final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
7849
7850        boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
7851            boolean okay = true;
7852
7853            if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
7854
7855            // The file content is an .apk file.  Copy it out to a staging location and
7856            // attempt to install it.
7857            File apkFile = new File(mDataDir, info.packageName);
7858            try {
7859                FileOutputStream apkStream = new FileOutputStream(apkFile);
7860                byte[] buffer = new byte[32 * 1024];
7861                long size = info.size;
7862                while (size > 0) {
7863                    long toRead = (buffer.length < size) ? buffer.length : size;
7864                    int didRead = instream.read(buffer, 0, (int)toRead);
7865                    if (didRead >= 0) mBytes += didRead;
7866                    apkStream.write(buffer, 0, didRead);
7867                    size -= didRead;
7868                }
7869                apkStream.close();
7870
7871                // make sure the installer can read it
7872                apkFile.setReadable(true, false);
7873
7874                // Now install it
7875                Uri packageUri = Uri.fromFile(apkFile);
7876                mInstallObserver.reset();
7877                mPackageManager.installPackage(packageUri, mInstallObserver,
7878                        PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
7879                        installerPackage);
7880                mInstallObserver.waitForCompletion();
7881
7882                if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
7883                    // The only time we continue to accept install of data even if the
7884                    // apk install failed is if we had already determined that we could
7885                    // accept the data regardless.
7886                    if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
7887                        okay = false;
7888                    }
7889                } else {
7890                    // Okay, the install succeeded.  Make sure it was the right app.
7891                    boolean uninstall = false;
7892                    if (!mInstallObserver.mPackageName.equals(info.packageName)) {
7893                        Slog.w(TAG, "Restore stream claimed to include apk for "
7894                                + info.packageName + " but apk was really "
7895                                + mInstallObserver.mPackageName);
7896                        // delete the package we just put in place; it might be fraudulent
7897                        okay = false;
7898                        uninstall = true;
7899                    } else {
7900                        try {
7901                            PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
7902                                    PackageManager.GET_SIGNATURES);
7903                            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
7904                                Slog.w(TAG, "Restore stream contains apk of package "
7905                                        + info.packageName + " but it disallows backup/restore");
7906                                okay = false;
7907                            } else {
7908                                // So far so good -- do the signatures match the manifest?
7909                                Signature[] sigs = mManifestSignatures.get(info.packageName);
7910                                if (signaturesMatch(sigs, pkg)) {
7911                                    // If this is a system-uid app without a declared backup agent,
7912                                    // don't restore any of the file data.
7913                                    if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
7914                                            && (pkg.applicationInfo.backupAgentName == null)) {
7915                                        Slog.w(TAG, "Installed app " + info.packageName
7916                                                + " has restricted uid and no agent");
7917                                        okay = false;
7918                                    }
7919                                } else {
7920                                    Slog.w(TAG, "Installed app " + info.packageName
7921                                            + " signatures do not match restore manifest");
7922                                    okay = false;
7923                                    uninstall = true;
7924                                }
7925                            }
7926                        } catch (NameNotFoundException e) {
7927                            Slog.w(TAG, "Install of package " + info.packageName
7928                                    + " succeeded but now not found");
7929                            okay = false;
7930                        }
7931                    }
7932
7933                    // If we're not okay at this point, we need to delete the package
7934                    // that we just installed.
7935                    if (uninstall) {
7936                        mDeleteObserver.reset();
7937                        mPackageManager.deletePackage(mInstallObserver.mPackageName,
7938                                mDeleteObserver, 0);
7939                        mDeleteObserver.waitForCompletion();
7940                    }
7941                }
7942            } catch (IOException e) {
7943                Slog.e(TAG, "Unable to transcribe restored apk for install");
7944                okay = false;
7945            } finally {
7946                apkFile.delete();
7947            }
7948
7949            return okay;
7950        }
7951
7952        // Given an actual file content size, consume the post-content padding mandated
7953        // by the tar format.
7954        void skipTarPadding(long size, InputStream instream) throws IOException {
7955            long partial = (size + 512) % 512;
7956            if (partial > 0) {
7957                final int needed = 512 - (int)partial;
7958                byte[] buffer = new byte[needed];
7959                if (readExactly(instream, buffer, 0, needed) == needed) {
7960                    mBytes += needed;
7961                } else throw new IOException("Unexpected EOF in padding");
7962            }
7963        }
7964
7965        // Read a widget metadata file, returning the restored blob
7966        void readMetadata(FileMetadata info, InputStream instream) throws IOException {
7967            // Fail on suspiciously large widget dump files
7968            if (info.size > 64 * 1024) {
7969                throw new IOException("Metadata too big; corrupt? size=" + info.size);
7970            }
7971
7972            byte[] buffer = new byte[(int) info.size];
7973            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
7974                mBytes += info.size;
7975            } else throw new IOException("Unexpected EOF in widget data");
7976
7977            String[] str = new String[1];
7978            int offset = extractLine(buffer, 0, str);
7979            int version = Integer.parseInt(str[0]);
7980            if (version == BACKUP_MANIFEST_VERSION) {
7981                offset = extractLine(buffer, offset, str);
7982                final String pkg = str[0];
7983                if (info.packageName.equals(pkg)) {
7984                    // Data checks out -- the rest of the buffer is a concatenation of
7985                    // binary blobs as described in the comment at writeAppWidgetData()
7986                    ByteArrayInputStream bin = new ByteArrayInputStream(buffer,
7987                            offset, buffer.length - offset);
7988                    DataInputStream in = new DataInputStream(bin);
7989                    while (bin.available() > 0) {
7990                        int token = in.readInt();
7991                        int size = in.readInt();
7992                        if (size > 64 * 1024) {
7993                            throw new IOException("Datum "
7994                                    + Integer.toHexString(token)
7995                                    + " too big; corrupt? size=" + info.size);
7996                        }
7997                        switch (token) {
7998                            case BACKUP_WIDGET_METADATA_TOKEN:
7999                            {
8000                                if (MORE_DEBUG) {
8001                                    Slog.i(TAG, "Got widget metadata for " + info.packageName);
8002                                }
8003                                mWidgetData = new byte[size];
8004                                in.read(mWidgetData);
8005                                break;
8006                            }
8007                            default:
8008                            {
8009                                if (DEBUG) {
8010                                    Slog.i(TAG, "Ignoring metadata blob "
8011                                            + Integer.toHexString(token)
8012                                            + " for " + info.packageName);
8013                                }
8014                                in.skipBytes(size);
8015                                break;
8016                            }
8017                        }
8018                    }
8019                } else {
8020                    Slog.w(TAG, "Metadata mismatch: package " + info.packageName
8021                            + " but widget data for " + pkg);
8022                }
8023            } else {
8024                Slog.w(TAG, "Unsupported metadata version " + version);
8025            }
8026        }
8027
8028        // Returns a policy constant; takes a buffer arg to reduce memory churn
8029        RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
8030                throws IOException {
8031            // Fail on suspiciously large manifest files
8032            if (info.size > 64 * 1024) {
8033                throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
8034            }
8035
8036            byte[] buffer = new byte[(int) info.size];
8037            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
8038                mBytes += info.size;
8039            } else throw new IOException("Unexpected EOF in manifest");
8040
8041            RestorePolicy policy = RestorePolicy.IGNORE;
8042            String[] str = new String[1];
8043            int offset = 0;
8044
8045            try {
8046                offset = extractLine(buffer, offset, str);
8047                int version = Integer.parseInt(str[0]);
8048                if (version == BACKUP_MANIFEST_VERSION) {
8049                    offset = extractLine(buffer, offset, str);
8050                    String manifestPackage = str[0];
8051                    // TODO: handle <original-package>
8052                    if (manifestPackage.equals(info.packageName)) {
8053                        offset = extractLine(buffer, offset, str);
8054                        version = Integer.parseInt(str[0]);  // app version
8055                        offset = extractLine(buffer, offset, str);
8056                        // This is the platform version, which we don't use, but we parse it
8057                        // as a safety against corruption in the manifest.
8058                        Integer.parseInt(str[0]);
8059                        offset = extractLine(buffer, offset, str);
8060                        info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
8061                        offset = extractLine(buffer, offset, str);
8062                        boolean hasApk = str[0].equals("1");
8063                        offset = extractLine(buffer, offset, str);
8064                        int numSigs = Integer.parseInt(str[0]);
8065                        if (numSigs > 0) {
8066                            Signature[] sigs = new Signature[numSigs];
8067                            for (int i = 0; i < numSigs; i++) {
8068                                offset = extractLine(buffer, offset, str);
8069                                sigs[i] = new Signature(str[0]);
8070                            }
8071                            mManifestSignatures.put(info.packageName, sigs);
8072
8073                            // Okay, got the manifest info we need...
8074                            try {
8075                                PackageInfo pkgInfo = mPackageManager.getPackageInfo(
8076                                        info.packageName, PackageManager.GET_SIGNATURES);
8077                                // Fall through to IGNORE if the app explicitly disallows backup
8078                                final int flags = pkgInfo.applicationInfo.flags;
8079                                if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
8080                                    // Restore system-uid-space packages only if they have
8081                                    // defined a custom backup agent
8082                                    if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
8083                                            || (pkgInfo.applicationInfo.backupAgentName != null)) {
8084                                        // Verify signatures against any installed version; if they
8085                                        // don't match, then we fall though and ignore the data.  The
8086                                        // signatureMatch() method explicitly ignores the signature
8087                                        // check for packages installed on the system partition, because
8088                                        // such packages are signed with the platform cert instead of
8089                                        // the app developer's cert, so they're different on every
8090                                        // device.
8091                                        if (signaturesMatch(sigs, pkgInfo)) {
8092                                            if ((pkgInfo.applicationInfo.flags
8093                                                    & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) != 0) {
8094                                                Slog.i(TAG, "Package has restoreAnyVersion; taking data");
8095                                                policy = RestorePolicy.ACCEPT;
8096                                            } else if (pkgInfo.versionCode >= version) {
8097                                                Slog.i(TAG, "Sig + version match; taking data");
8098                                                policy = RestorePolicy.ACCEPT;
8099                                            } else {
8100                                                // The data is from a newer version of the app than
8101                                                // is presently installed.  That means we can only
8102                                                // use it if the matching apk is also supplied.
8103                                                Slog.d(TAG, "Data version " + version
8104                                                        + " is newer than installed version "
8105                                                        + pkgInfo.versionCode + " - requiring apk");
8106                                                policy = RestorePolicy.ACCEPT_IF_APK;
8107                                            }
8108                                        } else {
8109                                            Slog.w(TAG, "Restore manifest signatures do not match "
8110                                                    + "installed application for " + info.packageName);
8111                                        }
8112                                    } else {
8113                                        Slog.w(TAG, "Package " + info.packageName
8114                                                + " is system level with no agent");
8115                                    }
8116                                } else {
8117                                    if (DEBUG) Slog.i(TAG, "Restore manifest from "
8118                                            + info.packageName + " but allowBackup=false");
8119                                }
8120                            } catch (NameNotFoundException e) {
8121                                // Okay, the target app isn't installed.  We can process
8122                                // the restore properly only if the dataset provides the
8123                                // apk file and we can successfully install it.
8124                                if (DEBUG) Slog.i(TAG, "Package " + info.packageName
8125                                        + " not installed; requiring apk in dataset");
8126                                policy = RestorePolicy.ACCEPT_IF_APK;
8127                            }
8128
8129                            if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
8130                                Slog.i(TAG, "Cannot restore package " + info.packageName
8131                                        + " without the matching .apk");
8132                            }
8133                        } else {
8134                            Slog.i(TAG, "Missing signature on backed-up package "
8135                                    + info.packageName);
8136                        }
8137                    } else {
8138                        Slog.i(TAG, "Expected package " + info.packageName
8139                                + " but restore manifest claims " + manifestPackage);
8140                    }
8141                } else {
8142                    Slog.i(TAG, "Unknown restore manifest version " + version
8143                            + " for package " + info.packageName);
8144                }
8145            } catch (NumberFormatException e) {
8146                Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
8147            } catch (IllegalArgumentException e) {
8148                Slog.w(TAG, e.getMessage());
8149            }
8150
8151            return policy;
8152        }
8153
8154        // Builds a line from a byte buffer starting at 'offset', and returns
8155        // the index of the next unconsumed data in the buffer.
8156        int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
8157            final int end = buffer.length;
8158            if (offset >= end) throw new IOException("Incomplete data");
8159
8160            int pos;
8161            for (pos = offset; pos < end; pos++) {
8162                byte c = buffer[pos];
8163                // at LF we declare end of line, and return the next char as the
8164                // starting point for the next time through
8165                if (c == '\n') {
8166                    break;
8167                }
8168            }
8169            outStr[0] = new String(buffer, offset, pos - offset);
8170            pos++;  // may be pointing an extra byte past the end but that's okay
8171            return pos;
8172        }
8173
8174        void dumpFileMetadata(FileMetadata info) {
8175            if (DEBUG) {
8176                StringBuilder b = new StringBuilder(128);
8177
8178                // mode string
8179                b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
8180                b.append(((info.mode & 0400) != 0) ? 'r' : '-');
8181                b.append(((info.mode & 0200) != 0) ? 'w' : '-');
8182                b.append(((info.mode & 0100) != 0) ? 'x' : '-');
8183                b.append(((info.mode & 0040) != 0) ? 'r' : '-');
8184                b.append(((info.mode & 0020) != 0) ? 'w' : '-');
8185                b.append(((info.mode & 0010) != 0) ? 'x' : '-');
8186                b.append(((info.mode & 0004) != 0) ? 'r' : '-');
8187                b.append(((info.mode & 0002) != 0) ? 'w' : '-');
8188                b.append(((info.mode & 0001) != 0) ? 'x' : '-');
8189                b.append(String.format(" %9d ", info.size));
8190
8191                Date stamp = new Date(info.mtime);
8192                b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp));
8193
8194                b.append(info.packageName);
8195                b.append(" :: ");
8196                b.append(info.domain);
8197                b.append(" :: ");
8198                b.append(info.path);
8199
8200                Slog.i(TAG, b.toString());
8201            }
8202        }
8203
8204        // Consume a tar file header block [sequence] and accumulate the relevant metadata
8205        FileMetadata readTarHeaders(InputStream instream) throws IOException {
8206            byte[] block = new byte[512];
8207            FileMetadata info = null;
8208
8209            boolean gotHeader = readTarHeader(instream, block);
8210            if (gotHeader) {
8211                try {
8212                    // okay, presume we're okay, and extract the various metadata
8213                    info = new FileMetadata();
8214                    info.size = extractRadix(block, 124, 12, 8);
8215                    info.mtime = extractRadix(block, 136, 12, 8);
8216                    info.mode = extractRadix(block, 100, 8, 8);
8217
8218                    info.path = extractString(block, 345, 155); // prefix
8219                    String path = extractString(block, 0, 100);
8220                    if (path.length() > 0) {
8221                        if (info.path.length() > 0) info.path += '/';
8222                        info.path += path;
8223                    }
8224
8225                    // tar link indicator field: 1 byte at offset 156 in the header.
8226                    int typeChar = block[156];
8227                    if (typeChar == 'x') {
8228                        // pax extended header, so we need to read that
8229                        gotHeader = readPaxExtendedHeader(instream, info);
8230                        if (gotHeader) {
8231                            // and after a pax extended header comes another real header -- read
8232                            // that to find the real file type
8233                            gotHeader = readTarHeader(instream, block);
8234                        }
8235                        if (!gotHeader) throw new IOException("Bad or missing pax header");
8236
8237                        typeChar = block[156];
8238                    }
8239
8240                    switch (typeChar) {
8241                        case '0': info.type = BackupAgent.TYPE_FILE; break;
8242                        case '5': {
8243                            info.type = BackupAgent.TYPE_DIRECTORY;
8244                            if (info.size != 0) {
8245                                Slog.w(TAG, "Directory entry with nonzero size in header");
8246                                info.size = 0;
8247                            }
8248                            break;
8249                        }
8250                        case 0: {
8251                            // presume EOF
8252                            if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
8253                            return null;
8254                        }
8255                        default: {
8256                            Slog.e(TAG, "Unknown tar entity type: " + typeChar);
8257                            throw new IOException("Unknown entity type " + typeChar);
8258                        }
8259                    }
8260
8261                    // Parse out the path
8262                    //
8263                    // first: apps/shared/unrecognized
8264                    if (FullBackup.SHARED_PREFIX.regionMatches(0,
8265                            info.path, 0, FullBackup.SHARED_PREFIX.length())) {
8266                        // File in shared storage.  !!! TODO: implement this.
8267                        info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
8268                        info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
8269                        info.domain = FullBackup.SHARED_STORAGE_TOKEN;
8270                        if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
8271                    } else if (FullBackup.APPS_PREFIX.regionMatches(0,
8272                            info.path, 0, FullBackup.APPS_PREFIX.length())) {
8273                        // App content!  Parse out the package name and domain
8274
8275                        // strip the apps/ prefix
8276                        info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
8277
8278                        // extract the package name
8279                        int slash = info.path.indexOf('/');
8280                        if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
8281                        info.packageName = info.path.substring(0, slash);
8282                        info.path = info.path.substring(slash+1);
8283
8284                        // if it's a manifest or metadata payload we're done, otherwise parse
8285                        // out the domain into which the file will be restored
8286                        if (!info.path.equals(BACKUP_MANIFEST_FILENAME)
8287                                && !info.path.equals(BACKUP_METADATA_FILENAME)) {
8288                            slash = info.path.indexOf('/');
8289                            if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
8290                            info.domain = info.path.substring(0, slash);
8291                            info.path = info.path.substring(slash + 1);
8292                        }
8293                    }
8294                } catch (IOException e) {
8295                    if (DEBUG) {
8296                        Slog.e(TAG, "Parse error in header: " + e.getMessage());
8297                        HEXLOG(block);
8298                    }
8299                    throw e;
8300                }
8301            }
8302            return info;
8303        }
8304
8305        private void HEXLOG(byte[] block) {
8306            int offset = 0;
8307            int todo = block.length;
8308            StringBuilder buf = new StringBuilder(64);
8309            while (todo > 0) {
8310                buf.append(String.format("%04x   ", offset));
8311                int numThisLine = (todo > 16) ? 16 : todo;
8312                for (int i = 0; i < numThisLine; i++) {
8313                    buf.append(String.format("%02x ", block[offset+i]));
8314                }
8315                Slog.i("hexdump", buf.toString());
8316                buf.setLength(0);
8317                todo -= numThisLine;
8318                offset += numThisLine;
8319            }
8320        }
8321
8322        // Read exactly the given number of bytes into a buffer at the stated offset.
8323        // Returns false if EOF is encountered before the requested number of bytes
8324        // could be read.
8325        int readExactly(InputStream in, byte[] buffer, int offset, int size)
8326                throws IOException {
8327            if (size <= 0) throw new IllegalArgumentException("size must be > 0");
8328
8329            int soFar = 0;
8330            while (soFar < size) {
8331                int nRead = in.read(buffer, offset + soFar, size - soFar);
8332                if (nRead <= 0) {
8333                    if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
8334                    break;
8335                }
8336                soFar += nRead;
8337            }
8338            return soFar;
8339        }
8340
8341        boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
8342            final int got = readExactly(instream, block, 0, 512);
8343            if (got == 0) return false;     // Clean EOF
8344            if (got < 512) throw new IOException("Unable to read full block header");
8345            mBytes += 512;
8346            return true;
8347        }
8348
8349        // overwrites 'info' fields based on the pax extended header
8350        boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
8351                throws IOException {
8352            // We should never see a pax extended header larger than this
8353            if (info.size > 32*1024) {
8354                Slog.w(TAG, "Suspiciously large pax header size " + info.size
8355                        + " - aborting");
8356                throw new IOException("Sanity failure: pax header size " + info.size);
8357            }
8358
8359            // read whole blocks, not just the content size
8360            int numBlocks = (int)((info.size + 511) >> 9);
8361            byte[] data = new byte[numBlocks * 512];
8362            if (readExactly(instream, data, 0, data.length) < data.length) {
8363                throw new IOException("Unable to read full pax header");
8364            }
8365            mBytes += data.length;
8366
8367            final int contentSize = (int) info.size;
8368            int offset = 0;
8369            do {
8370                // extract the line at 'offset'
8371                int eol = offset+1;
8372                while (eol < contentSize && data[eol] != ' ') eol++;
8373                if (eol >= contentSize) {
8374                    // error: we just hit EOD looking for the end of the size field
8375                    throw new IOException("Invalid pax data");
8376                }
8377                // eol points to the space between the count and the key
8378                int linelen = (int) extractRadix(data, offset, eol - offset, 10);
8379                int key = eol + 1;  // start of key=value
8380                eol = offset + linelen - 1; // trailing LF
8381                int value;
8382                for (value = key+1; data[value] != '=' && value <= eol; value++);
8383                if (value > eol) {
8384                    throw new IOException("Invalid pax declaration");
8385                }
8386
8387                // pax requires that key/value strings be in UTF-8
8388                String keyStr = new String(data, key, value-key, "UTF-8");
8389                // -1 to strip the trailing LF
8390                String valStr = new String(data, value+1, eol-value-1, "UTF-8");
8391
8392                if ("path".equals(keyStr)) {
8393                    info.path = valStr;
8394                } else if ("size".equals(keyStr)) {
8395                    info.size = Long.parseLong(valStr);
8396                } else {
8397                    if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
8398                }
8399
8400                offset += linelen;
8401            } while (offset < contentSize);
8402
8403            return true;
8404        }
8405
8406        long extractRadix(byte[] data, int offset, int maxChars, int radix)
8407                throws IOException {
8408            long value = 0;
8409            final int end = offset + maxChars;
8410            for (int i = offset; i < end; i++) {
8411                final byte b = data[i];
8412                // Numeric fields in tar can terminate with either NUL or SPC
8413                if (b == 0 || b == ' ') break;
8414                if (b < '0' || b > ('0' + radix - 1)) {
8415                    throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
8416                }
8417                value = radix * value + (b - '0');
8418            }
8419            return value;
8420        }
8421
8422        String extractString(byte[] data, int offset, int maxChars) throws IOException {
8423            final int end = offset + maxChars;
8424            int eos = offset;
8425            // tar string fields terminate early with a NUL
8426            while (eos < end && data[eos] != 0) eos++;
8427            return new String(data, offset, eos-offset, "US-ASCII");
8428        }
8429
8430        void sendStartRestore() {
8431            if (mObserver != null) {
8432                try {
8433                    mObserver.onStartRestore();
8434                } catch (RemoteException e) {
8435                    Slog.w(TAG, "full restore observer went away: startRestore");
8436                    mObserver = null;
8437                }
8438            }
8439        }
8440
8441        void sendOnRestorePackage(String name) {
8442            if (mObserver != null) {
8443                try {
8444                    // TODO: use a more user-friendly name string
8445                    mObserver.onRestorePackage(name);
8446                } catch (RemoteException e) {
8447                    Slog.w(TAG, "full restore observer went away: restorePackage");
8448                    mObserver = null;
8449                }
8450            }
8451        }
8452
8453        void sendEndRestore() {
8454            if (mObserver != null) {
8455                try {
8456                    mObserver.onEndRestore();
8457                } catch (RemoteException e) {
8458                    Slog.w(TAG, "full restore observer went away: endRestore");
8459                    mObserver = null;
8460                }
8461            }
8462        }
8463    }
8464
8465    // ----- Restore handling -----
8466
8467    // Old style: directly match the stored vs on device signature blocks
8468    static boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
8469        if (target == null) {
8470            return false;
8471        }
8472
8473        // If the target resides on the system partition, we allow it to restore
8474        // data from the like-named package in a restore set even if the signatures
8475        // do not match.  (Unlike general applications, those flashed to the system
8476        // partition will be signed with the device's platform certificate, so on
8477        // different phones the same system app will have different signatures.)
8478        if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8479            if (MORE_DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
8480            return true;
8481        }
8482
8483        // Allow unsigned apps, but not signed on one device and unsigned on the other
8484        // !!! TODO: is this the right policy?
8485        Signature[] deviceSigs = target.signatures;
8486        if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
8487                + " device=" + deviceSigs);
8488        if ((storedSigs == null || storedSigs.length == 0)
8489                && (deviceSigs == null || deviceSigs.length == 0)) {
8490            return true;
8491        }
8492        if (storedSigs == null || deviceSigs == null) {
8493            return false;
8494        }
8495
8496        // !!! TODO: this demands that every stored signature match one
8497        // that is present on device, and does not demand the converse.
8498        // Is this this right policy?
8499        int nStored = storedSigs.length;
8500        int nDevice = deviceSigs.length;
8501
8502        for (int i=0; i < nStored; i++) {
8503            boolean match = false;
8504            for (int j=0; j < nDevice; j++) {
8505                if (storedSigs[i].equals(deviceSigs[j])) {
8506                    match = true;
8507                    break;
8508                }
8509            }
8510            if (!match) {
8511                return false;
8512            }
8513        }
8514        return true;
8515    }
8516
8517    // Used by both incremental and full restore
8518    void restoreWidgetData(String packageName, byte[] widgetData) {
8519        // Apply the restored widget state and generate the ID update for the app
8520        // TODO: http://b/22388012
8521        if (MORE_DEBUG) {
8522            Slog.i(TAG, "Incorporating restored widget data");
8523        }
8524        AppWidgetBackupBridge.restoreWidgetState(packageName, widgetData, UserHandle.USER_SYSTEM);
8525    }
8526
8527    // *****************************
8528    // NEW UNIFIED RESTORE IMPLEMENTATION
8529    // *****************************
8530
8531    // states of the unified-restore state machine
8532    enum UnifiedRestoreState {
8533        INITIAL,
8534        RUNNING_QUEUE,
8535        RESTORE_KEYVALUE,
8536        RESTORE_FULL,
8537        RESTORE_FINISHED,
8538        FINAL
8539    }
8540
8541    class PerformUnifiedRestoreTask implements BackupRestoreTask {
8542        // Transport we're working with to do the restore
8543        private IBackupTransport mTransport;
8544
8545        // Where per-transport saved state goes
8546        File mStateDir;
8547
8548        // Restore observer; may be null
8549        private IRestoreObserver mObserver;
8550
8551        // BackuoManagerMonitor; may be null
8552        private IBackupManagerMonitor mMonitor;
8553
8554        // Token identifying the dataset to the transport
8555        private long mToken;
8556
8557        // When this is a restore-during-install, this is the token identifying the
8558        // operation to the Package Manager, and we must ensure that we let it know
8559        // when we're finished.
8560        private int mPmToken;
8561
8562        // When this is restore-during-install, we need to tell the package manager
8563        // whether we actually launched the app, because this affects notifications
8564        // around externally-visible state transitions.
8565        private boolean mDidLaunch;
8566
8567        // Is this a whole-system restore, i.e. are we establishing a new ancestral
8568        // dataset to base future restore-at-install operations from?
8569        private boolean mIsSystemRestore;
8570
8571        // If this is a single-package restore, what package are we interested in?
8572        private PackageInfo mTargetPackage;
8573
8574        // In all cases, the calculated list of packages that we are trying to restore
8575        private List<PackageInfo> mAcceptSet;
8576
8577        // Our bookkeeping about the ancestral dataset
8578        private PackageManagerBackupAgent mPmAgent;
8579
8580        // Currently-bound backup agent for restore + restoreFinished purposes
8581        private IBackupAgent mAgent;
8582
8583        // What sort of restore we're doing now
8584        private RestoreDescription mRestoreDescription;
8585
8586        // The package we're currently restoring
8587        private PackageInfo mCurrentPackage;
8588
8589        // Widget-related data handled as part of this restore operation
8590        private byte[] mWidgetData;
8591
8592        // Number of apps restored in this pass
8593        private int mCount;
8594
8595        // When did we start?
8596        private long mStartRealtime;
8597
8598        // State machine progress
8599        private UnifiedRestoreState mState;
8600
8601        // How are things going?
8602        private int mStatus;
8603
8604        // Done?
8605        private boolean mFinished;
8606
8607        // Key/value: bookkeeping about staged data and files for agent access
8608        private File mBackupDataName;
8609        private File mStageName;
8610        private File mSavedStateName;
8611        private File mNewStateName;
8612        ParcelFileDescriptor mBackupData;
8613        ParcelFileDescriptor mNewState;
8614
8615        private final int mEphemeralOpToken;
8616
8617        // Invariant: mWakelock is already held, and this task is responsible for
8618        // releasing it at the end of the restore operation.
8619        PerformUnifiedRestoreTask(IBackupTransport transport, IRestoreObserver observer,
8620                IBackupManagerMonitor monitor, long restoreSetToken, PackageInfo targetPackage,
8621                int pmToken, boolean isFullSystemRestore, String[] filterSet) {
8622            mEphemeralOpToken = generateRandomIntegerToken();
8623            mState = UnifiedRestoreState.INITIAL;
8624            mStartRealtime = SystemClock.elapsedRealtime();
8625
8626            mTransport = transport;
8627            mObserver = observer;
8628            mMonitor = monitor;
8629            mToken = restoreSetToken;
8630            mPmToken = pmToken;
8631            mTargetPackage = targetPackage;
8632            mIsSystemRestore = isFullSystemRestore;
8633            mFinished = false;
8634            mDidLaunch = false;
8635
8636            if (targetPackage != null) {
8637                // Single package restore
8638                mAcceptSet = new ArrayList<PackageInfo>();
8639                mAcceptSet.add(targetPackage);
8640            } else {
8641                // Everything possible, or a target set
8642                if (filterSet == null) {
8643                    // We want everything and a pony
8644                    List<PackageInfo> apps =
8645                            PackageManagerBackupAgent.getStorableApplications(mPackageManager);
8646                    filterSet = packagesToNames(apps);
8647                    if (DEBUG) {
8648                        Slog.i(TAG, "Full restore; asking about " + filterSet.length + " apps");
8649                    }
8650                }
8651
8652                mAcceptSet = new ArrayList<PackageInfo>(filterSet.length);
8653
8654                // Pro tem, we insist on moving the settings provider package to last place.
8655                // Keep track of whether it's in the list, and bump it down if so.  We also
8656                // want to do the system package itself first if it's called for.
8657                boolean hasSystem = false;
8658                boolean hasSettings = false;
8659                for (int i = 0; i < filterSet.length; i++) {
8660                    try {
8661                        PackageInfo info = mPackageManager.getPackageInfo(filterSet[i], 0);
8662                        if ("android".equals(info.packageName)) {
8663                            hasSystem = true;
8664                            continue;
8665                        }
8666                        if (SETTINGS_PACKAGE.equals(info.packageName)) {
8667                            hasSettings = true;
8668                            continue;
8669                        }
8670
8671                        if (appIsEligibleForBackup(info.applicationInfo, mPackageManager)) {
8672                            mAcceptSet.add(info);
8673                        }
8674                    } catch (NameNotFoundException e) {
8675                        // requested package name doesn't exist; ignore it
8676                    }
8677                }
8678                if (hasSystem) {
8679                    try {
8680                        mAcceptSet.add(0, mPackageManager.getPackageInfo("android", 0));
8681                    } catch (NameNotFoundException e) {
8682                        // won't happen; we know a priori that it's valid
8683                    }
8684                }
8685                if (hasSettings) {
8686                    try {
8687                        mAcceptSet.add(mPackageManager.getPackageInfo(SETTINGS_PACKAGE, 0));
8688                    } catch (NameNotFoundException e) {
8689                        // this one is always valid too
8690                    }
8691                }
8692            }
8693
8694            if (MORE_DEBUG) {
8695                Slog.v(TAG, "Restore; accept set size is " + mAcceptSet.size());
8696                for (PackageInfo info : mAcceptSet) {
8697                    Slog.v(TAG, "   " + info.packageName);
8698                }
8699            }
8700        }
8701
8702        private String[] packagesToNames(List<PackageInfo> apps) {
8703            final int N = apps.size();
8704            String[] names = new String[N];
8705            for (int i = 0; i < N; i++) {
8706                names[i] = apps.get(i).packageName;
8707            }
8708            return names;
8709        }
8710
8711        // Execute one tick of whatever state machine the task implements
8712        @Override
8713        public void execute() {
8714            if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step " + mState);
8715            switch (mState) {
8716                case INITIAL:
8717                    startRestore();
8718                    break;
8719
8720                case RUNNING_QUEUE:
8721                    dispatchNextRestore();
8722                    break;
8723
8724                case RESTORE_KEYVALUE:
8725                    restoreKeyValue();
8726                    break;
8727
8728                case RESTORE_FULL:
8729                    restoreFull();
8730                    break;
8731
8732                case RESTORE_FINISHED:
8733                    restoreFinished();
8734                    break;
8735
8736                case FINAL:
8737                    if (!mFinished) finalizeRestore();
8738                    else {
8739                        Slog.e(TAG, "Duplicate finish");
8740                    }
8741                    mFinished = true;
8742                    break;
8743            }
8744        }
8745
8746        /*
8747         * SKETCH OF OPERATION
8748         *
8749         * create one of these PerformUnifiedRestoreTask objects, telling it which
8750         * dataset & transport to address, and then parameters within the restore
8751         * operation: single target package vs many, etc.
8752         *
8753         * 1. transport.startRestore(token, list-of-packages).  If we need @pm@  it is
8754         * always placed first and the settings provider always placed last [for now].
8755         *
8756         * 1a [if we needed @pm@ then nextRestorePackage() and restore the PMBA inline]
8757         *
8758         *   [ state change => RUNNING_QUEUE ]
8759         *
8760         * NOW ITERATE:
8761         *
8762         * { 3. t.nextRestorePackage()
8763         *   4. does the metadata for this package allow us to restore it?
8764         *      does the on-disk app permit us to restore it? [re-check allowBackup etc]
8765         *   5. is this a key/value dataset?  => key/value agent restore
8766         *       [ state change => RESTORE_KEYVALUE ]
8767         *       5a. spin up agent
8768         *       5b. t.getRestoreData() to stage it properly
8769         *       5c. call into agent to perform restore
8770         *       5d. tear down agent
8771         *       [ state change => RUNNING_QUEUE ]
8772         *
8773         *   6. else it's a stream dataset:
8774         *       [ state change => RESTORE_FULL ]
8775         *       6a. instantiate the engine for a stream restore: engine handles agent lifecycles
8776         *       6b. spin off engine runner on separate thread
8777         *       6c. ITERATE getNextFullRestoreDataChunk() and copy data to engine runner socket
8778         *       [ state change => RUNNING_QUEUE ]
8779         * }
8780         *
8781         *   [ state change => FINAL ]
8782         *
8783         * 7. t.finishRestore(), release wakelock, etc.
8784         *
8785         *
8786         */
8787
8788        // state INITIAL : set up for the restore and read the metadata if necessary
8789        private  void startRestore() {
8790            sendStartRestore(mAcceptSet.size());
8791
8792            // If we're starting a full-system restore, set up to begin widget ID remapping
8793            if (mIsSystemRestore) {
8794                // TODO: http://b/22388012
8795                AppWidgetBackupBridge.restoreStarting(UserHandle.USER_SYSTEM);
8796            }
8797
8798            try {
8799                String transportDir = mTransport.transportDirName();
8800                mStateDir = new File(mBaseStateDir, transportDir);
8801
8802                // Fetch the current metadata from the dataset first
8803                PackageInfo pmPackage = new PackageInfo();
8804                pmPackage.packageName = PACKAGE_MANAGER_SENTINEL;
8805                mAcceptSet.add(0, pmPackage);
8806
8807                PackageInfo[] packages = mAcceptSet.toArray(new PackageInfo[0]);
8808                mStatus = mTransport.startRestore(mToken, packages);
8809                if (mStatus != BackupTransport.TRANSPORT_OK) {
8810                    Slog.e(TAG, "Transport error " + mStatus + "; no restore possible");
8811                    mStatus = BackupTransport.TRANSPORT_ERROR;
8812                    executeNextState(UnifiedRestoreState.FINAL);
8813                    return;
8814                }
8815
8816                RestoreDescription desc = mTransport.nextRestorePackage();
8817                if (desc == null) {
8818                    Slog.e(TAG, "No restore metadata available; halting");
8819                    mMonitor = monitorEvent(mMonitor,
8820                            BackupManagerMonitor.LOG_EVENT_ID_NO_RESTORE_METADATA_AVAILABLE,
8821                            mCurrentPackage,
8822                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
8823                    mStatus = BackupTransport.TRANSPORT_ERROR;
8824                    executeNextState(UnifiedRestoreState.FINAL);
8825                    return;
8826                }
8827                if (!PACKAGE_MANAGER_SENTINEL.equals(desc.getPackageName())) {
8828                    Slog.e(TAG, "Required package metadata but got "
8829                            + desc.getPackageName());
8830                    mMonitor = monitorEvent(mMonitor,
8831                            BackupManagerMonitor.LOG_EVENT_ID_NO_PM_METADATA_RECEIVED,
8832                            mCurrentPackage,
8833                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
8834                    mStatus = BackupTransport.TRANSPORT_ERROR;
8835                    executeNextState(UnifiedRestoreState.FINAL);
8836                    return;
8837                }
8838
8839                // Pull the Package Manager metadata from the restore set first
8840                mCurrentPackage = new PackageInfo();
8841                mCurrentPackage.packageName = PACKAGE_MANAGER_SENTINEL;
8842                mPmAgent = makeMetadataAgent(null);
8843                mAgent = IBackupAgent.Stub.asInterface(mPmAgent.onBind());
8844                if (MORE_DEBUG) {
8845                    Slog.v(TAG, "initiating restore for PMBA");
8846                }
8847                initiateOneRestore(mCurrentPackage, 0);
8848                // The PM agent called operationComplete() already, because our invocation
8849                // of it is process-local and therefore synchronous.  That means that the
8850                // next-state message (RUNNING_QUEUE) is already enqueued.  Only if we're
8851                // unable to proceed with running the queue do we remove that pending
8852                // message and jump straight to the FINAL state.  Because this was
8853                // synchronous we also know that we should cancel the pending timeout
8854                // message.
8855                mBackupHandler.removeMessages(MSG_RESTORE_OPERATION_TIMEOUT);
8856
8857                // Verify that the backup set includes metadata.  If not, we can't do
8858                // signature/version verification etc, so we simply do not proceed with
8859                // the restore operation.
8860                if (!mPmAgent.hasMetadata()) {
8861                    Slog.e(TAG, "PM agent has no metadata, so not restoring");
8862                    mMonitor = monitorEvent(mMonitor,
8863                            BackupManagerMonitor.LOG_EVENT_ID_PM_AGENT_HAS_NO_METADATA,
8864                            mCurrentPackage,
8865                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
8866                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
8867                            PACKAGE_MANAGER_SENTINEL,
8868                            "Package manager restore metadata missing");
8869                    mStatus = BackupTransport.TRANSPORT_ERROR;
8870                    mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
8871                    executeNextState(UnifiedRestoreState.FINAL);
8872                    return;
8873                }
8874
8875                // Success; cache the metadata and continue as expected with the
8876                // next state already enqueued
8877
8878            } catch (Exception e) {
8879                // If we lost the transport at any time, halt
8880                Slog.e(TAG, "Unable to contact transport for restore: " + e.getMessage());
8881                mMonitor = monitorEvent(mMonitor,
8882                        BackupManagerMonitor.LOG_EVENT_ID_LOST_TRANSPORT,
8883                        null,
8884                        BackupManagerMonitor.LOG_EVENT_CATEGORY_TRANSPORT, null);
8885                mStatus = BackupTransport.TRANSPORT_ERROR;
8886                mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
8887                executeNextState(UnifiedRestoreState.FINAL);
8888                return;
8889            }
8890        }
8891
8892        // state RUNNING_QUEUE : figure out what the next thing to be restored is,
8893        // and fire the appropriate next step
8894        private void dispatchNextRestore() {
8895            UnifiedRestoreState nextState = UnifiedRestoreState.FINAL;
8896            try {
8897                mRestoreDescription = mTransport.nextRestorePackage();
8898                final String pkgName = (mRestoreDescription != null)
8899                        ? mRestoreDescription.getPackageName() : null;
8900                if (pkgName == null) {
8901                    Slog.e(TAG, "Failure getting next package name");
8902                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
8903                    nextState = UnifiedRestoreState.FINAL;
8904                    return;
8905                } else if (mRestoreDescription == RestoreDescription.NO_MORE_PACKAGES) {
8906                    // Yay we've reached the end cleanly
8907                    if (DEBUG) {
8908                        Slog.v(TAG, "No more packages; finishing restore");
8909                    }
8910                    int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
8911                    EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
8912                    nextState = UnifiedRestoreState.FINAL;
8913                    return;
8914                }
8915
8916                if (DEBUG) {
8917                    Slog.i(TAG, "Next restore package: " + mRestoreDescription);
8918                }
8919                sendOnRestorePackage(pkgName);
8920
8921                Metadata metaInfo = mPmAgent.getRestoredMetadata(pkgName);
8922                if (metaInfo == null) {
8923                    Slog.e(TAG, "No metadata for " + pkgName);
8924                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, pkgName,
8925                            "Package metadata missing");
8926                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
8927                    return;
8928                }
8929
8930                try {
8931                    mCurrentPackage = mPackageManager.getPackageInfo(
8932                            pkgName, PackageManager.GET_SIGNATURES);
8933                } catch (NameNotFoundException e) {
8934                    // Whoops, we thought we could restore this package but it
8935                    // turns out not to be present.  Skip it.
8936                    Slog.e(TAG, "Package not present: " + pkgName);
8937                    mMonitor = monitorEvent(mMonitor,
8938                            BackupManagerMonitor.LOG_EVENT_ID_PACKAGE_NOT_PRESENT,
8939                            mCurrentPackage,
8940                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
8941                            null);
8942                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, pkgName,
8943                            "Package missing on device");
8944                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
8945                    return;
8946                }
8947
8948                if (metaInfo.versionCode > mCurrentPackage.versionCode) {
8949                    // Data is from a "newer" version of the app than we have currently
8950                    // installed.  If the app has not declared that it is prepared to
8951                    // handle this case, we do not attempt the restore.
8952                    if ((mCurrentPackage.applicationInfo.flags
8953                            & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
8954                        String message = "Source version " + metaInfo.versionCode
8955                                + " > installed version " + mCurrentPackage.versionCode;
8956                        Slog.w(TAG, "Package " + pkgName + ": " + message);
8957                        Bundle monitoringExtras = putMonitoringExtra(null,
8958                                BackupManagerMonitor.EXTRA_LOG_RESTORE_VERSION,
8959                                metaInfo.versionCode);
8960                        monitoringExtras = putMonitoringExtra(monitoringExtras,
8961                                BackupManagerMonitor.EXTRA_LOG_RESTORE_ANYWAY, false);
8962                        mMonitor = monitorEvent(mMonitor,
8963                                BackupManagerMonitor.LOG_EVENT_ID_RESTORE_VERSION_HIGHER,
8964                                mCurrentPackage,
8965                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
8966                                monitoringExtras);
8967                        EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
8968                                pkgName, message);
8969                        nextState = UnifiedRestoreState.RUNNING_QUEUE;
8970                        return;
8971                    } else {
8972                        if (DEBUG) Slog.v(TAG, "Source version " + metaInfo.versionCode
8973                                + " > installed version " + mCurrentPackage.versionCode
8974                                + " but restoreAnyVersion");
8975                        Bundle monitoringExtras = putMonitoringExtra(null,
8976                                BackupManagerMonitor.EXTRA_LOG_RESTORE_VERSION,
8977                                metaInfo.versionCode);
8978                        monitoringExtras = putMonitoringExtra(monitoringExtras,
8979                                BackupManagerMonitor.EXTRA_LOG_RESTORE_ANYWAY, true);
8980                        mMonitor = monitorEvent(mMonitor,
8981                                BackupManagerMonitor.LOG_EVENT_ID_RESTORE_VERSION_HIGHER,
8982                                mCurrentPackage,
8983                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
8984                                monitoringExtras);
8985                    }
8986                }
8987
8988                if (MORE_DEBUG) Slog.v(TAG, "Package " + pkgName
8989                        + " restore version [" + metaInfo.versionCode
8990                        + "] is compatible with installed version ["
8991                        + mCurrentPackage.versionCode + "]");
8992
8993                // Reset per-package preconditions and fire the appropriate next state
8994                mWidgetData = null;
8995                final int type = mRestoreDescription.getDataType();
8996                if (type == RestoreDescription.TYPE_KEY_VALUE) {
8997                    nextState = UnifiedRestoreState.RESTORE_KEYVALUE;
8998                } else if (type == RestoreDescription.TYPE_FULL_STREAM) {
8999                    nextState = UnifiedRestoreState.RESTORE_FULL;
9000                } else {
9001                    // Unknown restore type; ignore this package and move on
9002                    Slog.e(TAG, "Unrecognized restore type " + type);
9003                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
9004                    return;
9005                }
9006            } catch (Exception e) {
9007                Slog.e(TAG, "Can't get next restore target from transport; halting: "
9008                        + e.getMessage());
9009                EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
9010                nextState = UnifiedRestoreState.FINAL;
9011                return;
9012            } finally {
9013                executeNextState(nextState);
9014            }
9015        }
9016
9017        // state RESTORE_KEYVALUE : restore one package via key/value API set
9018        private void restoreKeyValue() {
9019            // Initiating the restore will pass responsibility for the state machine's
9020            // progress to the agent callback, so we do not always execute the
9021            // next state here.
9022            final String packageName = mCurrentPackage.packageName;
9023            // Validate some semantic requirements that apply in this way
9024            // only to the key/value restore API flow
9025            if (mCurrentPackage.applicationInfo.backupAgentName == null
9026                    || "".equals(mCurrentPackage.applicationInfo.backupAgentName)) {
9027                if (MORE_DEBUG) {
9028                    Slog.i(TAG, "Data exists for package " + packageName
9029                            + " but app has no agent; skipping");
9030                }
9031                mMonitor = monitorEvent(mMonitor,
9032                        BackupManagerMonitor.LOG_EVENT_ID_APP_HAS_NO_AGENT, mCurrentPackage,
9033                        BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT, null);
9034                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
9035                        "Package has no agent");
9036                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9037                return;
9038            }
9039
9040            Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
9041            if (!BackupUtils.signaturesMatch(metaInfo.sigHashes, mCurrentPackage)) {
9042                Slog.w(TAG, "Signature mismatch restoring " + packageName);
9043                mMonitor = monitorEvent(mMonitor,
9044                        BackupManagerMonitor.LOG_EVENT_ID_SIGNATURE_MISMATCH, mCurrentPackage,
9045                        BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
9046                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
9047                        "Signature mismatch");
9048                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9049                return;
9050            }
9051
9052            // Good to go!  Set up and bind the agent...
9053            mAgent = bindToAgentSynchronous(
9054                    mCurrentPackage.applicationInfo,
9055                    ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL);
9056            if (mAgent == null) {
9057                Slog.w(TAG, "Can't find backup agent for " + packageName);
9058                mMonitor = monitorEvent(mMonitor,
9059                        BackupManagerMonitor.LOG_EVENT_ID_CANT_FIND_AGENT, mCurrentPackage,
9060                        BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
9061                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
9062                        "Restore agent missing");
9063                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9064                return;
9065            }
9066
9067            // Whatever happens next, we've launched the target app now; remember that.
9068            mDidLaunch = true;
9069
9070            // And then finally start the restore on this agent
9071            try {
9072                initiateOneRestore(mCurrentPackage, metaInfo.versionCode);
9073                ++mCount;
9074            } catch (Exception e) {
9075                Slog.e(TAG, "Error when attempting restore: " + e.toString());
9076                keyValueAgentErrorCleanup();
9077                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9078            }
9079        }
9080
9081        // Guts of a key/value restore operation
9082        void initiateOneRestore(PackageInfo app, int appVersionCode) {
9083            final String packageName = app.packageName;
9084
9085            if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
9086
9087            // !!! TODO: get the dirs from the transport
9088            mBackupDataName = new File(mDataDir, packageName + ".restore");
9089            mStageName = new File(mDataDir, packageName + ".stage");
9090            mNewStateName = new File(mStateDir, packageName + ".new");
9091            mSavedStateName = new File(mStateDir, packageName);
9092
9093            // don't stage the 'android' package where the wallpaper data lives.  this is
9094            // an optimization: we know there's no widget data hosted/published by that
9095            // package, and this way we avoid doing a spurious copy of MB-sized wallpaper
9096            // data following the download.
9097            boolean staging = !packageName.equals("android");
9098            ParcelFileDescriptor stage;
9099            File downloadFile = (staging) ? mStageName : mBackupDataName;
9100
9101            try {
9102                // Run the transport's restore pass
9103                stage = ParcelFileDescriptor.open(downloadFile,
9104                        ParcelFileDescriptor.MODE_READ_WRITE |
9105                        ParcelFileDescriptor.MODE_CREATE |
9106                        ParcelFileDescriptor.MODE_TRUNCATE);
9107
9108                if (mTransport.getRestoreData(stage) != BackupTransport.TRANSPORT_OK) {
9109                    // Transport-level failure, so we wind everything up and
9110                    // terminate the restore operation.
9111                    Slog.e(TAG, "Error getting restore data for " + packageName);
9112                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
9113                    stage.close();
9114                    downloadFile.delete();
9115                    executeNextState(UnifiedRestoreState.FINAL);
9116                    return;
9117                }
9118
9119                // We have the data from the transport. Now we extract and strip
9120                // any per-package metadata (typically widget-related information)
9121                // if appropriate
9122                if (staging) {
9123                    stage.close();
9124                    stage = ParcelFileDescriptor.open(downloadFile,
9125                            ParcelFileDescriptor.MODE_READ_ONLY);
9126
9127                    mBackupData = ParcelFileDescriptor.open(mBackupDataName,
9128                            ParcelFileDescriptor.MODE_READ_WRITE |
9129                            ParcelFileDescriptor.MODE_CREATE |
9130                            ParcelFileDescriptor.MODE_TRUNCATE);
9131
9132                    BackupDataInput in = new BackupDataInput(stage.getFileDescriptor());
9133                    BackupDataOutput out = new BackupDataOutput(mBackupData.getFileDescriptor());
9134                    byte[] buffer = new byte[8192]; // will grow when needed
9135                    while (in.readNextHeader()) {
9136                        final String key = in.getKey();
9137                        final int size = in.getDataSize();
9138
9139                        // is this a special key?
9140                        if (key.equals(KEY_WIDGET_STATE)) {
9141                            if (DEBUG) {
9142                                Slog.i(TAG, "Restoring widget state for " + packageName);
9143                            }
9144                            mWidgetData = new byte[size];
9145                            in.readEntityData(mWidgetData, 0, size);
9146                        } else {
9147                            if (size > buffer.length) {
9148                                buffer = new byte[size];
9149                            }
9150                            in.readEntityData(buffer, 0, size);
9151                            out.writeEntityHeader(key, size);
9152                            out.writeEntityData(buffer, size);
9153                        }
9154                    }
9155
9156                    mBackupData.close();
9157                }
9158
9159                // Okay, we have the data.  Now have the agent do the restore.
9160                stage.close();
9161
9162                mBackupData = ParcelFileDescriptor.open(mBackupDataName,
9163                        ParcelFileDescriptor.MODE_READ_ONLY);
9164
9165                mNewState = ParcelFileDescriptor.open(mNewStateName,
9166                        ParcelFileDescriptor.MODE_READ_WRITE |
9167                        ParcelFileDescriptor.MODE_CREATE |
9168                        ParcelFileDescriptor.MODE_TRUNCATE);
9169
9170                // Kick off the restore, checking for hung agents.  The timeout or
9171                // the operationComplete() callback will schedule the next step,
9172                // so we do not do that here.
9173                prepareOperationTimeout(mEphemeralOpToken, TIMEOUT_RESTORE_INTERVAL,
9174                        this, OP_TYPE_RESTORE_WAIT);
9175                mAgent.doRestore(mBackupData, appVersionCode, mNewState,
9176                        mEphemeralOpToken, mBackupManagerBinder);
9177            } catch (Exception e) {
9178                Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
9179                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
9180                        packageName, e.toString());
9181                keyValueAgentErrorCleanup();    // clears any pending timeout messages as well
9182
9183                // After a restore failure we go back to running the queue.  If there
9184                // are no more packages to be restored that will be handled by the
9185                // next step.
9186                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9187            }
9188        }
9189
9190        // state RESTORE_FULL : restore one package via streaming engine
9191        private void restoreFull() {
9192            // None of this can run on the work looper here, so we spin asynchronous
9193            // work like this:
9194            //
9195            //   StreamFeederThread: read data from mTransport.getNextFullRestoreDataChunk()
9196            //                       write it into the pipe to the engine
9197            //   EngineThread: FullRestoreEngine thread communicating with the target app
9198            //
9199            // When finished, StreamFeederThread executes next state as appropriate on the
9200            // backup looper, and the overall unified restore task resumes
9201            try {
9202                StreamFeederThread feeder = new StreamFeederThread();
9203                if (MORE_DEBUG) {
9204                    Slog.i(TAG, "Spinning threads for stream restore of "
9205                            + mCurrentPackage.packageName);
9206                }
9207                new Thread(feeder, "unified-stream-feeder").start();
9208
9209                // At this point the feeder is responsible for advancing the restore
9210                // state, so we're done here.
9211            } catch (IOException e) {
9212                // Unable to instantiate the feeder thread -- we need to bail on the
9213                // current target.  We haven't asked the transport for data yet, though,
9214                // so we can do that simply by going back to running the restore queue.
9215                Slog.e(TAG, "Unable to construct pipes for stream restore!");
9216                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9217            }
9218        }
9219
9220        // state RESTORE_FINISHED : provide the "no more data" signpost callback at the end
9221        private void restoreFinished() {
9222            if (DEBUG) {
9223                Slog.d(TAG, "restoreFinished packageName=" + mCurrentPackage.packageName);
9224            }
9225            try {
9226                prepareOperationTimeout(mEphemeralOpToken, TIMEOUT_RESTORE_FINISHED_INTERVAL, this,
9227                        OP_TYPE_RESTORE_WAIT);
9228                mAgent.doRestoreFinished(mEphemeralOpToken, mBackupManagerBinder);
9229                // If we get this far, the callback or timeout will schedule the
9230                // next restore state, so we're done
9231            } catch (Exception e) {
9232                final String packageName = mCurrentPackage.packageName;
9233                Slog.e(TAG, "Unable to finalize restore of " + packageName);
9234                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
9235                        packageName, e.toString());
9236                keyValueAgentErrorCleanup();
9237                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9238            }
9239        }
9240
9241        class StreamFeederThread extends RestoreEngine implements Runnable, BackupRestoreTask {
9242            final String TAG = "StreamFeederThread";
9243            FullRestoreEngine mEngine;
9244            EngineThread mEngineThread;
9245
9246            // pipe through which we read data from the transport. [0] read, [1] write
9247            ParcelFileDescriptor[] mTransportPipes;
9248
9249            // pipe through which the engine will read data.  [0] read, [1] write
9250            ParcelFileDescriptor[] mEnginePipes;
9251
9252            private final int mEphemeralOpToken;
9253
9254            public StreamFeederThread() throws IOException {
9255                mEphemeralOpToken = generateRandomIntegerToken();
9256                mTransportPipes = ParcelFileDescriptor.createPipe();
9257                mEnginePipes = ParcelFileDescriptor.createPipe();
9258                setRunning(true);
9259            }
9260
9261            @Override
9262            public void run() {
9263                UnifiedRestoreState nextState = UnifiedRestoreState.RUNNING_QUEUE;
9264                int status = BackupTransport.TRANSPORT_OK;
9265
9266                EventLog.writeEvent(EventLogTags.FULL_RESTORE_PACKAGE,
9267                        mCurrentPackage.packageName);
9268
9269                mEngine = new FullRestoreEngine(this, null, mMonitor, mCurrentPackage, false, false, mEphemeralOpToken);
9270                mEngineThread = new EngineThread(mEngine, mEnginePipes[0]);
9271
9272                ParcelFileDescriptor eWriteEnd = mEnginePipes[1];
9273                ParcelFileDescriptor tReadEnd = mTransportPipes[0];
9274                ParcelFileDescriptor tWriteEnd = mTransportPipes[1];
9275
9276                int bufferSize = 32 * 1024;
9277                byte[] buffer = new byte[bufferSize];
9278                FileOutputStream engineOut = new FileOutputStream(eWriteEnd.getFileDescriptor());
9279                FileInputStream transportIn = new FileInputStream(tReadEnd.getFileDescriptor());
9280
9281                // spin up the engine and start moving data to it
9282                new Thread(mEngineThread, "unified-restore-engine").start();
9283
9284                try {
9285                    while (status == BackupTransport.TRANSPORT_OK) {
9286                        // have the transport write some of the restoring data to us
9287                        int result = mTransport.getNextFullRestoreDataChunk(tWriteEnd);
9288                        if (result > 0) {
9289                            // The transport wrote this many bytes of restore data to the
9290                            // pipe, so pass it along to the engine.
9291                            if (MORE_DEBUG) {
9292                                Slog.v(TAG, "  <- transport provided chunk size " + result);
9293                            }
9294                            if (result > bufferSize) {
9295                                bufferSize = result;
9296                                buffer = new byte[bufferSize];
9297                            }
9298                            int toCopy = result;
9299                            while (toCopy > 0) {
9300                                int n = transportIn.read(buffer, 0, toCopy);
9301                                engineOut.write(buffer, 0, n);
9302                                toCopy -= n;
9303                                if (MORE_DEBUG) {
9304                                    Slog.v(TAG, "  -> wrote " + n + " to engine, left=" + toCopy);
9305                                }
9306                            }
9307                        } else if (result == BackupTransport.NO_MORE_DATA) {
9308                            // Clean finish.  Wind up and we're done!
9309                            if (MORE_DEBUG) {
9310                                Slog.i(TAG, "Got clean full-restore EOF for "
9311                                        + mCurrentPackage.packageName);
9312                            }
9313                            status = BackupTransport.TRANSPORT_OK;
9314                            break;
9315                        } else {
9316                            // Transport reported some sort of failure; the fall-through
9317                            // handling will deal properly with that.
9318                            Slog.e(TAG, "Error " + result + " streaming restore for "
9319                                    + mCurrentPackage.packageName);
9320                            EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
9321                            status = result;
9322                        }
9323                    }
9324                    if (MORE_DEBUG) Slog.v(TAG, "Done copying to engine, falling through");
9325                } catch (IOException e) {
9326                    // We lost our ability to communicate via the pipes.  That's worrying
9327                    // but potentially recoverable; abandon this package's restore but
9328                    // carry on with the next restore target.
9329                    Slog.e(TAG, "Unable to route data for restore");
9330                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
9331                            mCurrentPackage.packageName, "I/O error on pipes");
9332                    status = BackupTransport.AGENT_ERROR;
9333                } catch (Exception e) {
9334                    // The transport threw; terminate the whole operation.  Closing
9335                    // the sockets will wake up the engine and it will then tidy up the
9336                    // remote end.
9337                    Slog.e(TAG, "Transport failed during restore: " + e.getMessage());
9338                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
9339                    status = BackupTransport.TRANSPORT_ERROR;
9340                } finally {
9341                    // Close the transport pipes and *our* end of the engine pipe,
9342                    // but leave the engine thread's end open so that it properly
9343                    // hits EOF and winds up its operations.
9344                    IoUtils.closeQuietly(mEnginePipes[1]);
9345                    IoUtils.closeQuietly(mTransportPipes[0]);
9346                    IoUtils.closeQuietly(mTransportPipes[1]);
9347
9348                    // Don't proceed until the engine has wound up operations
9349                    mEngineThread.waitForResult();
9350
9351                    // Now we're really done with this one too
9352                    IoUtils.closeQuietly(mEnginePipes[0]);
9353
9354                    // In all cases we want to remember whether we launched
9355                    // the target app as part of our work so far.
9356                    mDidLaunch = (mEngine.getAgent() != null);
9357
9358                    // If we hit a transport-level error, we are done with everything;
9359                    // if we hit an agent error we just go back to running the queue.
9360                    if (status == BackupTransport.TRANSPORT_OK) {
9361                        // Clean finish means we issue the restore-finished callback
9362                        nextState = UnifiedRestoreState.RESTORE_FINISHED;
9363
9364                        // the engine bound the target's agent, so recover that binding
9365                        // to use for the callback.
9366                        mAgent = mEngine.getAgent();
9367
9368                        // and the restored widget data, if any
9369                        mWidgetData = mEngine.getWidgetData();
9370                    } else {
9371                        // Something went wrong somewhere.  Whether it was at the transport
9372                        // level is immaterial; we need to tell the transport to bail
9373                        try {
9374                            mTransport.abortFullRestore();
9375                        } catch (Exception e) {
9376                            // transport itself is dead; make sure we handle this as a
9377                            // fatal error
9378                            Slog.e(TAG, "Transport threw from abortFullRestore: " + e.getMessage());
9379                            status = BackupTransport.TRANSPORT_ERROR;
9380                        }
9381
9382                        // We also need to wipe the current target's data, as it's probably
9383                        // in an incoherent state.
9384                        clearApplicationDataSynchronous(mCurrentPackage.packageName);
9385
9386                        // Schedule the next state based on the nature of our failure
9387                        if (status == BackupTransport.TRANSPORT_ERROR) {
9388                            nextState = UnifiedRestoreState.FINAL;
9389                        } else {
9390                            nextState = UnifiedRestoreState.RUNNING_QUEUE;
9391                        }
9392                    }
9393                    executeNextState(nextState);
9394                    setRunning(false);
9395                }
9396            }
9397
9398            // BackupRestoreTask interface, specifically for timeout handling
9399
9400            @Override
9401            public void execute() { /* intentionally empty */ }
9402
9403            @Override
9404            public void operationComplete(long result) { /* intentionally empty */ }
9405
9406            // The app has timed out handling a restoring file
9407            @Override
9408            public void handleCancel(boolean cancelAll) {
9409                removeOperation(mEphemeralOpToken);
9410                if (DEBUG) {
9411                    Slog.w(TAG, "Full-data restore target timed out; shutting down");
9412                }
9413
9414                mMonitor = monitorEvent(mMonitor,
9415                        BackupManagerMonitor.LOG_EVENT_ID_FULL_RESTORE_TIMEOUT,
9416                        mCurrentPackage, BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT, null);
9417                mEngineThread.handleTimeout();
9418
9419                IoUtils.closeQuietly(mEnginePipes[1]);
9420                mEnginePipes[1] = null;
9421                IoUtils.closeQuietly(mEnginePipes[0]);
9422                mEnginePipes[0] = null;
9423            }
9424        }
9425
9426        class EngineThread implements Runnable {
9427            FullRestoreEngine mEngine;
9428            FileInputStream mEngineStream;
9429
9430            EngineThread(FullRestoreEngine engine, ParcelFileDescriptor engineSocket) {
9431                mEngine = engine;
9432                engine.setRunning(true);
9433                // We *do* want this FileInputStream to own the underlying fd, so that
9434                // when we are finished with it, it closes this end of the pipe in a way
9435                // that signals its other end.
9436                mEngineStream = new FileInputStream(engineSocket.getFileDescriptor(), true);
9437            }
9438
9439            public boolean isRunning() {
9440                return mEngine.isRunning();
9441            }
9442
9443            public int waitForResult() {
9444                return mEngine.waitForResult();
9445            }
9446
9447            @Override
9448            public void run() {
9449                try {
9450                    while (mEngine.isRunning()) {
9451                        // Tell it to be sure to leave the agent instance up after finishing
9452                        mEngine.restoreOneFile(mEngineStream, false);
9453                    }
9454                } finally {
9455                    // Because mEngineStream adopted its underlying FD, this also
9456                    // closes this end of the pipe.
9457                    IoUtils.closeQuietly(mEngineStream);
9458                }
9459            }
9460
9461            public void handleTimeout() {
9462                IoUtils.closeQuietly(mEngineStream);
9463                mEngine.handleTimeout();
9464            }
9465        }
9466
9467        // state FINAL : tear everything down and we're done.
9468        private void finalizeRestore() {
9469            if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
9470
9471            try {
9472                mTransport.finishRestore();
9473            } catch (Exception e) {
9474                Slog.e(TAG, "Error finishing restore", e);
9475            }
9476
9477            // Tell the observer we're done
9478            if (mObserver != null) {
9479                try {
9480                    mObserver.restoreFinished(mStatus);
9481                } catch (RemoteException e) {
9482                    Slog.d(TAG, "Restore observer died at restoreFinished");
9483                }
9484            }
9485
9486            // Clear any ongoing session timeout.
9487            mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
9488
9489            // If we have a PM token, we must under all circumstances be sure to
9490            // handshake when we've finished.
9491            if (mPmToken > 0) {
9492                if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
9493                try {
9494                    mPackageManagerBinder.finishPackageInstall(mPmToken, mDidLaunch);
9495                } catch (RemoteException e) { /* can't happen */ }
9496            } else {
9497                // We were invoked via an active restore session, not by the Package
9498                // Manager, so start up the session timeout again.
9499                mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_SESSION_TIMEOUT,
9500                        TIMEOUT_RESTORE_INTERVAL);
9501            }
9502
9503            // Kick off any work that may be needed regarding app widget restores
9504            // TODO: http://b/22388012
9505            AppWidgetBackupBridge.restoreFinished(UserHandle.USER_SYSTEM);
9506
9507            // If this was a full-system restore, record the ancestral
9508            // dataset information
9509            if (mIsSystemRestore && mPmAgent != null) {
9510                mAncestralPackages = mPmAgent.getRestoredPackages();
9511                mAncestralToken = mToken;
9512                writeRestoreTokens();
9513            }
9514
9515            // done; we can finally release the wakelock and be legitimately done.
9516            Slog.i(TAG, "Restore complete.");
9517
9518            synchronized (mPendingRestores) {
9519                if (mPendingRestores.size() > 0) {
9520                    if (DEBUG) {
9521                        Slog.d(TAG, "Starting next pending restore.");
9522                    }
9523                    PerformUnifiedRestoreTask task = mPendingRestores.remove();
9524                    mBackupHandler.sendMessage(
9525                            mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, task));
9526
9527                } else {
9528                    mIsRestoreInProgress = false;
9529                    if (MORE_DEBUG) {
9530                        Slog.d(TAG, "No pending restores.");
9531                    }
9532                }
9533            }
9534
9535            mWakelock.release();
9536        }
9537
9538        void keyValueAgentErrorCleanup() {
9539            // If the agent fails restore, it might have put the app's data
9540            // into an incoherent state.  For consistency we wipe its data
9541            // again in this case before continuing with normal teardown
9542            clearApplicationDataSynchronous(mCurrentPackage.packageName);
9543            keyValueAgentCleanup();
9544        }
9545
9546        // TODO: clean up naming; this is now used at finish by both k/v and stream restores
9547        void keyValueAgentCleanup() {
9548            mBackupDataName.delete();
9549            mStageName.delete();
9550            try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
9551            try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
9552            mBackupData = mNewState = null;
9553
9554            // if everything went okay, remember the recorded state now
9555            //
9556            // !!! TODO: the restored data could be migrated on the server
9557            // side into the current dataset.  In that case the new state file
9558            // we just created would reflect the data already extant in the
9559            // backend, so there'd be nothing more to do.  Until that happens,
9560            // however, we need to make sure that we record the data to the
9561            // current backend dataset.  (Yes, this means shipping the data over
9562            // the wire in both directions.  That's bad, but consistency comes
9563            // first, then efficiency.)  Once we introduce server-side data
9564            // migration to the newly-restored device's dataset, we will change
9565            // the following from a discard of the newly-written state to the
9566            // "correct" operation of renaming into the canonical state blob.
9567            mNewStateName.delete();                      // TODO: remove; see above comment
9568            //mNewStateName.renameTo(mSavedStateName);   // TODO: replace with this
9569
9570            // If this wasn't the PM pseudopackage, tear down the agent side
9571            if (mCurrentPackage.applicationInfo != null) {
9572                // unbind and tidy up even on timeout or failure
9573                try {
9574                    mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
9575
9576                    // The agent was probably running with a stub Application object,
9577                    // which isn't a valid run mode for the main app logic.  Shut
9578                    // down the app so that next time it's launched, it gets the
9579                    // usual full initialization.  Note that this is only done for
9580                    // full-system restores: when a single app has requested a restore,
9581                    // it is explicitly not killed following that operation.
9582                    //
9583                    // We execute this kill when these conditions hold:
9584                    //    1. it's not a system-uid process,
9585                    //    2. the app did not request its own restore (mTargetPackage == null), and either
9586                    //    3a. the app is a full-data target (TYPE_FULL_STREAM) or
9587                    //     b. the app does not state android:killAfterRestore="false" in its manifest
9588                    final int appFlags = mCurrentPackage.applicationInfo.flags;
9589                    final boolean killAfterRestore =
9590                            (mCurrentPackage.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
9591                            && ((mRestoreDescription.getDataType() == RestoreDescription.TYPE_FULL_STREAM)
9592                                    || ((appFlags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0));
9593
9594                    if (mTargetPackage == null && killAfterRestore) {
9595                        if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
9596                                + mCurrentPackage.applicationInfo.processName);
9597                        mActivityManager.killApplicationProcess(
9598                                mCurrentPackage.applicationInfo.processName,
9599                                mCurrentPackage.applicationInfo.uid);
9600                    }
9601                } catch (RemoteException e) {
9602                    // can't happen; we run in the same process as the activity manager
9603                }
9604            }
9605
9606            // The caller is responsible for reestablishing the state machine; our
9607            // responsibility here is to clear the decks for whatever comes next.
9608            mBackupHandler.removeMessages(MSG_RESTORE_OPERATION_TIMEOUT, this);
9609        }
9610
9611        @Override
9612        public void operationComplete(long unusedResult) {
9613            removeOperation(mEphemeralOpToken);
9614            if (MORE_DEBUG) {
9615                Slog.i(TAG, "operationComplete() during restore: target="
9616                        + mCurrentPackage.packageName
9617                        + " state=" + mState);
9618            }
9619
9620            final UnifiedRestoreState nextState;
9621            switch (mState) {
9622                case INITIAL:
9623                    // We've just (manually) restored the PMBA.  It doesn't need the
9624                    // additional restore-finished callback so we bypass that and go
9625                    // directly to running the queue.
9626                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
9627                    break;
9628
9629                case RESTORE_KEYVALUE:
9630                case RESTORE_FULL: {
9631                    // Okay, we've just heard back from the agent that it's done with
9632                    // the restore itself.  We now have to send the same agent its
9633                    // doRestoreFinished() callback, so roll into that state.
9634                    nextState = UnifiedRestoreState.RESTORE_FINISHED;
9635                    break;
9636                }
9637
9638                case RESTORE_FINISHED: {
9639                    // Okay, we're done with this package.  Tidy up and go on to the next
9640                    // app in the queue.
9641                    int size = (int) mBackupDataName.length();
9642                    EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE,
9643                            mCurrentPackage.packageName, size);
9644
9645                    // Just go back to running the restore queue
9646                    keyValueAgentCleanup();
9647
9648                    // If there was widget state associated with this app, get the OS to
9649                    // incorporate it into current bookeeping and then pass that along to
9650                    // the app as part of the restore-time work.
9651                    if (mWidgetData != null) {
9652                        restoreWidgetData(mCurrentPackage.packageName, mWidgetData);
9653                    }
9654
9655                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
9656                    break;
9657                }
9658
9659                default: {
9660                    // Some kind of horrible semantic error; we're in an unexpected state.
9661                    // Back off hard and wind up.
9662                    Slog.e(TAG, "Unexpected restore callback into state " + mState);
9663                    keyValueAgentErrorCleanup();
9664                    nextState = UnifiedRestoreState.FINAL;
9665                    break;
9666                }
9667            }
9668
9669            executeNextState(nextState);
9670        }
9671
9672        // A call to agent.doRestore() or agent.doRestoreFinished() has timed out
9673        @Override
9674        public void handleCancel(boolean cancelAll) {
9675            removeOperation(mEphemeralOpToken);
9676            Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
9677            mMonitor = monitorEvent(mMonitor,
9678                    BackupManagerMonitor.LOG_EVENT_ID_KEY_VALUE_RESTORE_TIMEOUT,
9679                    mCurrentPackage, BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT, null);
9680            EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
9681                    mCurrentPackage.packageName, "restore timeout");
9682            // Handle like an agent that threw on invocation: wipe it and go on to the next
9683            keyValueAgentErrorCleanup();
9684            executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9685        }
9686
9687        void executeNextState(UnifiedRestoreState nextState) {
9688            if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
9689                    + this + " nextState=" + nextState);
9690            mState = nextState;
9691            Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
9692            mBackupHandler.sendMessage(msg);
9693        }
9694
9695        // restore observer support
9696        void sendStartRestore(int numPackages) {
9697            if (mObserver != null) {
9698                try {
9699                    mObserver.restoreStarting(numPackages);
9700                } catch (RemoteException e) {
9701                    Slog.w(TAG, "Restore observer went away: startRestore");
9702                    mObserver = null;
9703                }
9704            }
9705        }
9706
9707        void sendOnRestorePackage(String name) {
9708            if (mObserver != null) {
9709                if (mObserver != null) {
9710                    try {
9711                        mObserver.onUpdate(mCount, name);
9712                    } catch (RemoteException e) {
9713                        Slog.d(TAG, "Restore observer died in onUpdate");
9714                        mObserver = null;
9715                    }
9716                }
9717            }
9718        }
9719
9720        void sendEndRestore() {
9721            if (mObserver != null) {
9722                try {
9723                    mObserver.restoreFinished(mStatus);
9724                } catch (RemoteException e) {
9725                    Slog.w(TAG, "Restore observer went away: endRestore");
9726                    mObserver = null;
9727                }
9728            }
9729        }
9730    }
9731
9732    class PerformClearTask implements Runnable {
9733        IBackupTransport mTransport;
9734        PackageInfo mPackage;
9735
9736        PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
9737            mTransport = transport;
9738            mPackage = packageInfo;
9739        }
9740
9741        public void run() {
9742            try {
9743                // Clear the on-device backup state to ensure a full backup next time
9744                File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
9745                File stateFile = new File(stateDir, mPackage.packageName);
9746                stateFile.delete();
9747
9748                // Tell the transport to remove all the persistent storage for the app
9749                // TODO - need to handle failures
9750                mTransport.clearBackupData(mPackage);
9751            } catch (Exception e) {
9752                Slog.e(TAG, "Transport threw clearing data for " + mPackage + ": " + e.getMessage());
9753            } finally {
9754                try {
9755                    // TODO - need to handle failures
9756                    mTransport.finishBackup();
9757                } catch (Exception e) {
9758                    // Nothing we can do here, alas
9759                    Slog.e(TAG, "Unable to mark clear operation finished: " + e.getMessage());
9760                }
9761
9762                // Last but not least, release the cpu
9763                mWakelock.release();
9764            }
9765        }
9766    }
9767
9768    class PerformInitializeTask implements Runnable {
9769        HashSet<String> mQueue;
9770
9771        PerformInitializeTask(HashSet<String> transportNames) {
9772            mQueue = transportNames;
9773        }
9774
9775        public void run() {
9776            try {
9777                for (String transportName : mQueue) {
9778                    IBackupTransport transport =
9779                            mTransportManager.getTransportBinder(transportName);
9780                    if (transport == null) {
9781                        Slog.e(TAG, "Requested init for " + transportName + " but not found");
9782                        continue;
9783                    }
9784
9785                    Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
9786                    EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
9787                    long startRealtime = SystemClock.elapsedRealtime();
9788                    int status = transport.initializeDevice();
9789
9790                    if (status == BackupTransport.TRANSPORT_OK) {
9791                        status = transport.finishBackup();
9792                    }
9793
9794                    // Okay, the wipe really happened.  Clean up our local bookkeeping.
9795                    if (status == BackupTransport.TRANSPORT_OK) {
9796                        Slog.i(TAG, "Device init successful");
9797                        int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
9798                        EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
9799                        resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
9800                        EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
9801                        synchronized (mQueueLock) {
9802                            recordInitPendingLocked(false, transportName);
9803                        }
9804                    } else {
9805                        // If this didn't work, requeue this one and try again
9806                        // after a suitable interval
9807                        Slog.e(TAG, "Transport error in initializeDevice()");
9808                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
9809                        synchronized (mQueueLock) {
9810                            recordInitPendingLocked(true, transportName);
9811                        }
9812                        // do this via another alarm to make sure of the wakelock states
9813                        long delay = transport.requestBackupTime();
9814                        Slog.w(TAG, "Init failed on " + transportName + " resched in " + delay);
9815                        mAlarmManager.set(AlarmManager.RTC_WAKEUP,
9816                                System.currentTimeMillis() + delay, mRunInitIntent);
9817                    }
9818                }
9819            } catch (Exception e) {
9820                Slog.e(TAG, "Unexpected error performing init", e);
9821            } finally {
9822                // Done; release the wakelock
9823                mWakelock.release();
9824            }
9825        }
9826    }
9827
9828    private void dataChangedImpl(String packageName) {
9829        HashSet<String> targets = dataChangedTargets(packageName);
9830        dataChangedImpl(packageName, targets);
9831    }
9832
9833    private void dataChangedImpl(String packageName, HashSet<String> targets) {
9834        // Record that we need a backup pass for the caller.  Since multiple callers
9835        // may share a uid, we need to note all candidates within that uid and schedule
9836        // a backup pass for each of them.
9837        if (targets == null) {
9838            Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
9839                   + " uid=" + Binder.getCallingUid());
9840            return;
9841        }
9842
9843        synchronized (mQueueLock) {
9844            // Note that this client has made data changes that need to be backed up
9845            if (targets.contains(packageName)) {
9846                // Add the caller to the set of pending backups.  If there is
9847                // one already there, then overwrite it, but no harm done.
9848                BackupRequest req = new BackupRequest(packageName);
9849                if (mPendingBackups.put(packageName, req) == null) {
9850                    if (MORE_DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
9851
9852                    // Journal this request in case of crash.  The put()
9853                    // operation returned null when this package was not already
9854                    // in the set; we want to avoid touching the disk redundantly.
9855                    writeToJournalLocked(packageName);
9856                }
9857            }
9858        }
9859
9860        // ...and schedule a backup pass if necessary
9861        KeyValueBackupJob.schedule(mContext);
9862    }
9863
9864    // Note: packageName is currently unused, but may be in the future
9865    private HashSet<String> dataChangedTargets(String packageName) {
9866        // If the caller does not hold the BACKUP permission, it can only request a
9867        // backup of its own data.
9868        if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
9869                Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
9870            synchronized (mBackupParticipants) {
9871                return mBackupParticipants.get(Binder.getCallingUid());
9872            }
9873        }
9874
9875        // a caller with full permission can ask to back up any participating app
9876        HashSet<String> targets = new HashSet<String>();
9877        if (PACKAGE_MANAGER_SENTINEL.equals(packageName)) {
9878            targets.add(PACKAGE_MANAGER_SENTINEL);
9879        } else {
9880            synchronized (mBackupParticipants) {
9881                int N = mBackupParticipants.size();
9882                for (int i = 0; i < N; i++) {
9883                    HashSet<String> s = mBackupParticipants.valueAt(i);
9884                    if (s != null) {
9885                        targets.addAll(s);
9886                    }
9887                }
9888            }
9889        }
9890        return targets;
9891    }
9892
9893    private void writeToJournalLocked(String str) {
9894        RandomAccessFile out = null;
9895        try {
9896            if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
9897            out = new RandomAccessFile(mJournal, "rws");
9898            out.seek(out.length());
9899            out.writeUTF(str);
9900        } catch (IOException e) {
9901            Slog.e(TAG, "Can't write " + str + " to backup journal", e);
9902            mJournal = null;
9903        } finally {
9904            try { if (out != null) out.close(); } catch (IOException e) {}
9905        }
9906    }
9907
9908    // ----- IBackupManager binder interface -----
9909
9910    @Override
9911    public void dataChanged(final String packageName) {
9912        final int callingUserHandle = UserHandle.getCallingUserId();
9913        if (callingUserHandle != UserHandle.USER_SYSTEM) {
9914            // TODO: http://b/22388012
9915            // App is running under a non-owner user profile.  For now, we do not back
9916            // up data from secondary user profiles.
9917            // TODO: backups for all user profiles although don't add backup for profiles
9918            // without adding admin control in DevicePolicyManager.
9919            if (MORE_DEBUG) {
9920                Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
9921                        + callingUserHandle);
9922            }
9923            return;
9924        }
9925
9926        final HashSet<String> targets = dataChangedTargets(packageName);
9927        if (targets == null) {
9928            Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
9929                   + " uid=" + Binder.getCallingUid());
9930            return;
9931        }
9932
9933        mBackupHandler.post(new Runnable() {
9934                public void run() {
9935                    dataChangedImpl(packageName, targets);
9936                }
9937            });
9938    }
9939
9940    // Clear the given package's backup data from the current transport
9941    @Override
9942    public void clearBackupData(String transportName, String packageName) {
9943        if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName + " on " + transportName);
9944        PackageInfo info;
9945        try {
9946            info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
9947        } catch (NameNotFoundException e) {
9948            Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
9949            return;
9950        }
9951
9952        // If the caller does not hold the BACKUP permission, it can only request a
9953        // wipe of its own backed-up data.
9954        HashSet<String> apps;
9955        if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
9956                Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
9957            apps = mBackupParticipants.get(Binder.getCallingUid());
9958        } else {
9959            // a caller with full permission can ask to back up any participating app
9960            // !!! TODO: allow data-clear of ANY app?
9961            if (MORE_DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
9962            apps = new HashSet<String>();
9963            int N = mBackupParticipants.size();
9964            for (int i = 0; i < N; i++) {
9965                HashSet<String> s = mBackupParticipants.valueAt(i);
9966                if (s != null) {
9967                    apps.addAll(s);
9968                }
9969            }
9970        }
9971
9972        // Is the given app an available participant?
9973        if (apps.contains(packageName)) {
9974            // found it; fire off the clear request
9975            if (MORE_DEBUG) Slog.v(TAG, "Found the app - running clear process");
9976            mBackupHandler.removeMessages(MSG_RETRY_CLEAR);
9977            synchronized (mQueueLock) {
9978                final IBackupTransport transport =
9979                        mTransportManager.getTransportBinder(transportName);
9980                if (transport == null) {
9981                    // transport is currently unavailable -- make sure to retry
9982                    Message msg = mBackupHandler.obtainMessage(MSG_RETRY_CLEAR,
9983                            new ClearRetryParams(transportName, packageName));
9984                    mBackupHandler.sendMessageDelayed(msg, TRANSPORT_RETRY_INTERVAL);
9985                    return;
9986                }
9987                long oldId = Binder.clearCallingIdentity();
9988                mWakelock.acquire();
9989                Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
9990                        new ClearParams(transport, info));
9991                mBackupHandler.sendMessage(msg);
9992                Binder.restoreCallingIdentity(oldId);
9993            }
9994        }
9995    }
9996
9997    // Run a backup pass immediately for any applications that have declared
9998    // that they have pending updates.
9999    @Override
10000    public void backupNow() {
10001        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
10002
10003        final PowerSaveState result =
10004                mPowerManager.getPowerSaveState(ServiceType.KEYVALUE_BACKUP);
10005        if (result.batterySaverEnabled) {
10006            if (DEBUG) Slog.v(TAG, "Not running backup while in battery save mode");
10007            KeyValueBackupJob.schedule(mContext);   // try again in several hours
10008        } else {
10009            if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
10010            synchronized (mQueueLock) {
10011                // Fire the intent that kicks off the whole shebang...
10012                try {
10013                    mRunBackupIntent.send();
10014                } catch (PendingIntent.CanceledException e) {
10015                    // should never happen
10016                    Slog.e(TAG, "run-backup intent cancelled!");
10017                }
10018
10019                // ...and cancel any pending scheduled job, because we've just superseded it
10020                KeyValueBackupJob.cancel(mContext);
10021            }
10022        }
10023    }
10024
10025    boolean deviceIsProvisioned() {
10026        final ContentResolver resolver = mContext.getContentResolver();
10027        return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
10028    }
10029
10030    // Run a backup pass for the given packages, writing the resulting data stream
10031    // to the supplied file descriptor.  This method is synchronous and does not return
10032    // to the caller until the backup has been completed.
10033    //
10034    // This is the variant used by 'adb backup'; it requires on-screen confirmation
10035    // by the user because it can be used to offload data over untrusted USB.
10036    @Override
10037    public void adbBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeObbs,
10038            boolean includeShared, boolean doWidgets, boolean doAllApps, boolean includeSystem,
10039            boolean compress, boolean doKeyValue, String[] pkgList) {
10040        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "adbBackup");
10041
10042        final int callingUserHandle = UserHandle.getCallingUserId();
10043        // TODO: http://b/22388012
10044        if (callingUserHandle != UserHandle.USER_SYSTEM) {
10045            throw new IllegalStateException("Backup supported only for the device owner");
10046        }
10047
10048        // Validate
10049        if (!doAllApps) {
10050            if (!includeShared) {
10051                // If we're backing up shared data (sdcard or equivalent), then we can run
10052                // without any supplied app names.  Otherwise, we'd be doing no work, so
10053                // report the error.
10054                if (pkgList == null || pkgList.length == 0) {
10055                    throw new IllegalArgumentException(
10056                            "Backup requested but neither shared nor any apps named");
10057                }
10058            }
10059        }
10060
10061        long oldId = Binder.clearCallingIdentity();
10062        try {
10063            // Doesn't make sense to do a full backup prior to setup
10064            if (!deviceIsProvisioned()) {
10065                Slog.i(TAG, "Backup not supported before setup");
10066                return;
10067            }
10068
10069            if (DEBUG) Slog.v(TAG, "Requesting backup: apks=" + includeApks + " obb=" + includeObbs
10070                    + " shared=" + includeShared + " all=" + doAllApps + " system="
10071                    + includeSystem + " includekeyvalue=" + doKeyValue + " pkgs=" + pkgList);
10072            Slog.i(TAG, "Beginning adb backup...");
10073
10074            AdbBackupParams params = new AdbBackupParams(fd, includeApks, includeObbs,
10075                    includeShared, doWidgets, doAllApps, includeSystem, compress, doKeyValue,
10076                    pkgList);
10077            final int token = generateRandomIntegerToken();
10078            synchronized (mAdbBackupRestoreConfirmations) {
10079                mAdbBackupRestoreConfirmations.put(token, params);
10080            }
10081
10082            // start up the confirmation UI
10083            if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
10084            if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
10085                Slog.e(TAG, "Unable to launch backup confirmation UI");
10086                mAdbBackupRestoreConfirmations.delete(token);
10087                return;
10088            }
10089
10090            // make sure the screen is lit for the user interaction
10091            mPowerManager.userActivity(SystemClock.uptimeMillis(),
10092                    PowerManager.USER_ACTIVITY_EVENT_OTHER,
10093                    0);
10094
10095            // start the confirmation countdown
10096            startConfirmationTimeout(token, params);
10097
10098            // wait for the backup to be performed
10099            if (DEBUG) Slog.d(TAG, "Waiting for backup completion...");
10100            waitForCompletion(params);
10101        } finally {
10102            try {
10103                fd.close();
10104            } catch (IOException e) {
10105                // just eat it
10106            }
10107            Binder.restoreCallingIdentity(oldId);
10108            Slog.d(TAG, "Adb backup processing complete.");
10109        }
10110    }
10111
10112    @Override
10113    public void fullTransportBackup(String[] pkgNames) {
10114        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
10115                "fullTransportBackup");
10116
10117        final int callingUserHandle = UserHandle.getCallingUserId();
10118        // TODO: http://b/22388012
10119        if (callingUserHandle != UserHandle.USER_SYSTEM) {
10120            throw new IllegalStateException("Restore supported only for the device owner");
10121        }
10122
10123        if (!fullBackupAllowable(mTransportManager.getCurrentTransportBinder())) {
10124            Slog.i(TAG, "Full backup not currently possible -- key/value backup not yet run?");
10125        } else {
10126            if (DEBUG) {
10127                Slog.d(TAG, "fullTransportBackup()");
10128            }
10129
10130            final long oldId = Binder.clearCallingIdentity();
10131            try {
10132                CountDownLatch latch = new CountDownLatch(1);
10133                PerformFullTransportBackupTask task = new PerformFullTransportBackupTask(null,
10134                        pkgNames, false, null, latch, null, null, false /* userInitiated */);
10135                // Acquiring wakelock for PerformFullTransportBackupTask before its start.
10136                mWakelock.acquire();
10137                (new Thread(task, "full-transport-master")).start();
10138                do {
10139                    try {
10140                        latch.await();
10141                        break;
10142                    } catch (InterruptedException e) {
10143                        // Just go back to waiting for the latch to indicate completion
10144                    }
10145                } while (true);
10146
10147                // We just ran a backup on these packages, so kick them to the end of the queue
10148                final long now = System.currentTimeMillis();
10149                for (String pkg : pkgNames) {
10150                    enqueueFullBackup(pkg, now);
10151                }
10152            } finally {
10153                Binder.restoreCallingIdentity(oldId);
10154            }
10155        }
10156
10157        if (DEBUG) {
10158            Slog.d(TAG, "Done with full transport backup.");
10159        }
10160    }
10161
10162    @Override
10163    public void adbRestore(ParcelFileDescriptor fd) {
10164        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "adbRestore");
10165
10166        final int callingUserHandle = UserHandle.getCallingUserId();
10167        // TODO: http://b/22388012
10168        if (callingUserHandle != UserHandle.USER_SYSTEM) {
10169            throw new IllegalStateException("Restore supported only for the device owner");
10170        }
10171
10172        long oldId = Binder.clearCallingIdentity();
10173
10174        try {
10175            // Check whether the device has been provisioned -- we don't handle
10176            // full restores prior to completing the setup process.
10177            if (!deviceIsProvisioned()) {
10178                Slog.i(TAG, "Full restore not permitted before setup");
10179                return;
10180            }
10181
10182            Slog.i(TAG, "Beginning restore...");
10183
10184            AdbRestoreParams params = new AdbRestoreParams(fd);
10185            final int token = generateRandomIntegerToken();
10186            synchronized (mAdbBackupRestoreConfirmations) {
10187                mAdbBackupRestoreConfirmations.put(token, params);
10188            }
10189
10190            // start up the confirmation UI
10191            if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
10192            if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
10193                Slog.e(TAG, "Unable to launch restore confirmation");
10194                mAdbBackupRestoreConfirmations.delete(token);
10195                return;
10196            }
10197
10198            // make sure the screen is lit for the user interaction
10199            mPowerManager.userActivity(SystemClock.uptimeMillis(),
10200                    PowerManager.USER_ACTIVITY_EVENT_OTHER,
10201                    0);
10202
10203            // start the confirmation countdown
10204            startConfirmationTimeout(token, params);
10205
10206            // wait for the restore to be performed
10207            if (DEBUG) Slog.d(TAG, "Waiting for restore completion...");
10208            waitForCompletion(params);
10209        } finally {
10210            try {
10211                fd.close();
10212            } catch (IOException e) {
10213                Slog.w(TAG, "Error trying to close fd after adb restore: " + e);
10214            }
10215            Binder.restoreCallingIdentity(oldId);
10216            Slog.i(TAG, "adb restore processing complete.");
10217        }
10218    }
10219
10220    boolean startConfirmationUi(int token, String action) {
10221        try {
10222            Intent confIntent = new Intent(action);
10223            confIntent.setClassName("com.android.backupconfirm",
10224                    "com.android.backupconfirm.BackupRestoreConfirmation");
10225            confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
10226            confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
10227            mContext.startActivityAsUser(confIntent, UserHandle.SYSTEM);
10228        } catch (ActivityNotFoundException e) {
10229            return false;
10230        }
10231        return true;
10232    }
10233
10234    void startConfirmationTimeout(int token, AdbParams params) {
10235        if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
10236                + TIMEOUT_FULL_CONFIRMATION + " millis");
10237        Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
10238                token, 0, params);
10239        mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
10240    }
10241
10242    void waitForCompletion(AdbParams params) {
10243        synchronized (params.latch) {
10244            while (params.latch.get() == false) {
10245                try {
10246                    params.latch.wait();
10247                } catch (InterruptedException e) { /* never interrupted */ }
10248            }
10249        }
10250    }
10251
10252    void signalAdbBackupRestoreCompletion(AdbParams params) {
10253        synchronized (params.latch) {
10254            params.latch.set(true);
10255            params.latch.notifyAll();
10256        }
10257    }
10258
10259    // Confirm that the previously-requested full backup/restore operation can proceed.  This
10260    // is used to require a user-facing disclosure about the operation.
10261    @Override
10262    public void acknowledgeAdbBackupOrRestore(int token, boolean allow,
10263            String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
10264        if (DEBUG) Slog.d(TAG, "acknowledgeAdbBackupOrRestore : token=" + token
10265                + " allow=" + allow);
10266
10267        // TODO: possibly require not just this signature-only permission, but even
10268        // require that the specific designated confirmation-UI app uid is the caller?
10269        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeAdbBackupOrRestore");
10270
10271        long oldId = Binder.clearCallingIdentity();
10272        try {
10273
10274            AdbParams params;
10275            synchronized (mAdbBackupRestoreConfirmations) {
10276                params = mAdbBackupRestoreConfirmations.get(token);
10277                if (params != null) {
10278                    mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
10279                    mAdbBackupRestoreConfirmations.delete(token);
10280
10281                    if (allow) {
10282                        final int verb = params instanceof AdbBackupParams
10283                                ? MSG_RUN_ADB_BACKUP
10284                                : MSG_RUN_ADB_RESTORE;
10285
10286                        params.observer = observer;
10287                        params.curPassword = curPassword;
10288
10289                        params.encryptPassword = encPpassword;
10290
10291                        if (MORE_DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
10292                        mWakelock.acquire();
10293                        Message msg = mBackupHandler.obtainMessage(verb, params);
10294                        mBackupHandler.sendMessage(msg);
10295                    } else {
10296                        Slog.w(TAG, "User rejected full backup/restore operation");
10297                        // indicate completion without having actually transferred any data
10298                        signalAdbBackupRestoreCompletion(params);
10299                    }
10300                } else {
10301                    Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
10302                }
10303            }
10304        } finally {
10305            Binder.restoreCallingIdentity(oldId);
10306        }
10307    }
10308
10309    private static boolean backupSettingMigrated(int userId) {
10310        File base = new File(Environment.getDataDirectory(), "backup");
10311        File enableFile = new File(base, BACKUP_ENABLE_FILE);
10312        return enableFile.exists();
10313    }
10314
10315    private static boolean readBackupEnableState(int userId) {
10316        File base = new File(Environment.getDataDirectory(), "backup");
10317        File enableFile = new File(base, BACKUP_ENABLE_FILE);
10318        if (enableFile.exists()) {
10319            try (FileInputStream fin = new FileInputStream(enableFile)) {
10320                int state = fin.read();
10321                return state != 0;
10322            } catch (IOException e) {
10323                // can't read the file; fall through to assume disabled
10324                Slog.e(TAG, "Cannot read enable state; assuming disabled");
10325            }
10326        } else {
10327            if (DEBUG) {
10328                Slog.i(TAG, "isBackupEnabled() => false due to absent settings file");
10329            }
10330        }
10331        return false;
10332    }
10333
10334    private static void writeBackupEnableState(boolean enable, int userId) {
10335        File base = new File(Environment.getDataDirectory(), "backup");
10336        File enableFile = new File(base, BACKUP_ENABLE_FILE);
10337        File stage = new File(base, BACKUP_ENABLE_FILE + "-stage");
10338        FileOutputStream fout = null;
10339        try {
10340            fout = new FileOutputStream(stage);
10341            fout.write(enable ? 1 : 0);
10342            fout.close();
10343            stage.renameTo(enableFile);
10344            // will be synced immediately by the try-with-resources call to close()
10345        } catch (IOException|RuntimeException e) {
10346            // Whoops; looks like we're doomed.  Roll everything out, disabled,
10347            // including the legacy state.
10348            Slog.e(TAG, "Unable to record backup enable state; reverting to disabled: "
10349                    + e.getMessage());
10350
10351            final ContentResolver r = sInstance.mContext.getContentResolver();
10352            Settings.Secure.putStringForUser(r,
10353                    Settings.Secure.BACKUP_ENABLED, null, userId);
10354            enableFile.delete();
10355            stage.delete();
10356        } finally {
10357            IoUtils.closeQuietly(fout);
10358        }
10359    }
10360
10361    // Enable/disable backups
10362    @Override
10363    public void setBackupEnabled(boolean enable) {
10364        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10365                "setBackupEnabled");
10366
10367        Slog.i(TAG, "Backup enabled => " + enable);
10368
10369        long oldId = Binder.clearCallingIdentity();
10370        try {
10371            boolean wasEnabled = mEnabled;
10372            synchronized (this) {
10373                writeBackupEnableState(enable, UserHandle.USER_SYSTEM);
10374                mEnabled = enable;
10375            }
10376
10377            synchronized (mQueueLock) {
10378                if (enable && !wasEnabled && mProvisioned) {
10379                    // if we've just been enabled, start scheduling backup passes
10380                    KeyValueBackupJob.schedule(mContext);
10381                    scheduleNextFullBackupJob(0);
10382                } else if (!enable) {
10383                    // No longer enabled, so stop running backups
10384                    if (MORE_DEBUG) Slog.i(TAG, "Opting out of backup");
10385
10386                    KeyValueBackupJob.cancel(mContext);
10387
10388                    // This also constitutes an opt-out, so we wipe any data for
10389                    // this device from the backend.  We start that process with
10390                    // an alarm in order to guarantee wakelock states.
10391                    if (wasEnabled && mProvisioned) {
10392                        // NOTE: we currently flush every registered transport, not just
10393                        // the currently-active one.
10394                        String[] allTransports = mTransportManager.getBoundTransportNames();
10395                        // build the set of transports for which we are posting an init
10396                        for (String transport : allTransports) {
10397                            recordInitPendingLocked(true, transport);
10398                        }
10399                        mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
10400                                mRunInitIntent);
10401                    }
10402                }
10403            }
10404        } finally {
10405            Binder.restoreCallingIdentity(oldId);
10406        }
10407    }
10408
10409    // Enable/disable automatic restore of app data at install time
10410    @Override
10411    public void setAutoRestore(boolean doAutoRestore) {
10412        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10413                "setAutoRestore");
10414
10415        Slog.i(TAG, "Auto restore => " + doAutoRestore);
10416
10417        final long oldId = Binder.clearCallingIdentity();
10418        try {
10419            synchronized (this) {
10420                Settings.Secure.putInt(mContext.getContentResolver(),
10421                        Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
10422                mAutoRestore = doAutoRestore;
10423            }
10424        } finally {
10425            Binder.restoreCallingIdentity(oldId);
10426        }
10427    }
10428
10429    // Mark the backup service as having been provisioned
10430    @Override
10431    public void setBackupProvisioned(boolean available) {
10432        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10433                "setBackupProvisioned");
10434        /*
10435         * This is now a no-op; provisioning is simply the device's own setup state.
10436         */
10437    }
10438
10439    // Report whether the backup mechanism is currently enabled
10440    @Override
10441    public boolean isBackupEnabled() {
10442        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
10443        return mEnabled;    // no need to synchronize just to read it
10444    }
10445
10446    // Report the name of the currently active transport
10447    @Override
10448    public String getCurrentTransport() {
10449        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10450                "getCurrentTransport");
10451        String currentTransport = mTransportManager.getCurrentTransportName();
10452        if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + currentTransport);
10453        return currentTransport;
10454    }
10455
10456    // Report all known, available backup transports
10457    @Override
10458    public String[] listAllTransports() {
10459        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
10460
10461        return mTransportManager.getBoundTransportNames();
10462    }
10463
10464    @Override
10465    public ComponentName[] listAllTransportComponents() {
10466        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10467                "listAllTransportComponents");
10468        return mTransportManager.getAllTransportCompenents();
10469    }
10470
10471    @Override
10472    public String[] getTransportWhitelist() {
10473        // No permission check, intentionally.
10474        Set<ComponentName> whitelistedComponents = mTransportManager.getTransportWhitelist();
10475        String[] whitelistedTransports = new String[whitelistedComponents.size()];
10476        int i = 0;
10477        for (ComponentName component : whitelistedComponents) {
10478            whitelistedTransports[i] = component.flattenToShortString();
10479            i++;
10480        }
10481        return whitelistedTransports;
10482    }
10483
10484    // Select which transport to use for the next backup operation.
10485    @Override
10486    public String selectBackupTransport(String transport) {
10487        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10488                "selectBackupTransport");
10489
10490        final long oldId = Binder.clearCallingIdentity();
10491        try {
10492            String prevTransport = mTransportManager.selectTransport(transport);
10493            updateStateForTransport(transport);
10494            Slog.v(TAG, "selectBackupTransport() set " + mTransportManager.getCurrentTransportName()
10495                    + " returning " + prevTransport);
10496            return prevTransport;
10497        } finally {
10498            Binder.restoreCallingIdentity(oldId);
10499        }
10500    }
10501
10502    @Override
10503    public void selectBackupTransportAsync(final ComponentName transport,
10504            final ISelectBackupTransportCallback listener) {
10505        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10506                "selectBackupTransportAsync");
10507
10508        final long oldId = Binder.clearCallingIdentity();
10509
10510        Slog.v(TAG, "selectBackupTransportAsync() called with transport " +
10511                transport.flattenToShortString());
10512
10513        mTransportManager.ensureTransportReady(transport, new SelectBackupTransportCallback() {
10514            @Override
10515            public void onSuccess(String transportName) {
10516                mTransportManager.selectTransport(transportName);
10517                updateStateForTransport(mTransportManager.getCurrentTransportName());
10518                Slog.v(TAG, "Transport successfully selected: " + transport.flattenToShortString());
10519                try {
10520                    listener.onSuccess(transportName);
10521                } catch (RemoteException e) {
10522                    // Nothing to do here.
10523                }
10524            }
10525
10526            @Override
10527            public void onFailure(int reason) {
10528                Slog.v(TAG, "Failed to select transport: " + transport.flattenToShortString());
10529                try {
10530                    listener.onFailure(reason);
10531                } catch (RemoteException e) {
10532                    // Nothing to do here.
10533                }
10534            }
10535        });
10536
10537        Binder.restoreCallingIdentity(oldId);
10538    }
10539
10540    private void updateStateForTransport(String newTransportName) {
10541        // Publish the name change
10542        Settings.Secure.putString(mContext.getContentResolver(),
10543                Settings.Secure.BACKUP_TRANSPORT, newTransportName);
10544
10545        // And update our current-dataset bookkeeping
10546        IBackupTransport transport = mTransportManager.getTransportBinder(newTransportName);
10547        if (transport != null) {
10548            try {
10549                mCurrentToken = transport.getCurrentRestoreSet();
10550            } catch (Exception e) {
10551                // Oops.  We can't know the current dataset token, so reset and figure it out
10552                // when we do the next k/v backup operation on this transport.
10553                mCurrentToken = 0;
10554            }
10555        } else {
10556            // The named transport isn't bound at this particular moment, so we can't
10557            // know yet what its current dataset token is.  Reset as above.
10558            mCurrentToken = 0;
10559        }
10560    }
10561
10562    // Supply the configuration Intent for the given transport.  If the name is not one
10563    // of the available transports, or if the transport does not supply any configuration
10564    // UI, the method returns null.
10565    @Override
10566    public Intent getConfigurationIntent(String transportName) {
10567        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10568                "getConfigurationIntent");
10569
10570        final IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
10571        if (transport != null) {
10572            try {
10573                final Intent intent = transport.configurationIntent();
10574                if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
10575                        + intent);
10576                return intent;
10577            } catch (Exception e) {
10578                /* fall through to return null */
10579                Slog.e(TAG, "Unable to get configuration intent from transport: " + e.getMessage());
10580            }
10581        }
10582
10583        return null;
10584    }
10585
10586    // Supply the configuration summary string for the given transport.  If the name is
10587    // not one of the available transports, or if the transport does not supply any
10588    // summary / destination string, the method can return null.
10589    //
10590    // This string is used VERBATIM as the summary text of the relevant Settings item!
10591    @Override
10592    public String getDestinationString(String transportName) {
10593        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10594                "getDestinationString");
10595
10596        final IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
10597        if (transport != null) {
10598            try {
10599                final String text = transport.currentDestinationString();
10600                if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
10601                return text;
10602            } catch (Exception e) {
10603                /* fall through to return null */
10604                Slog.e(TAG, "Unable to get string from transport: " + e.getMessage());
10605            }
10606        }
10607
10608        return null;
10609    }
10610
10611    // Supply the manage-data intent for the given transport.
10612    @Override
10613    public Intent getDataManagementIntent(String transportName) {
10614        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10615                "getDataManagementIntent");
10616
10617        final IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
10618        if (transport != null) {
10619            try {
10620                final Intent intent = transport.dataManagementIntent();
10621                if (MORE_DEBUG) Slog.d(TAG, "getDataManagementIntent() returning intent "
10622                        + intent);
10623                return intent;
10624            } catch (Exception e) {
10625                /* fall through to return null */
10626                Slog.e(TAG, "Unable to get management intent from transport: " + e.getMessage());
10627            }
10628        }
10629
10630        return null;
10631    }
10632
10633    // Supply the menu label for affordances that fire the manage-data intent
10634    // for the given transport.
10635    @Override
10636    public String getDataManagementLabel(String transportName) {
10637        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10638                "getDataManagementLabel");
10639
10640        final IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
10641        if (transport != null) {
10642            try {
10643                final String text = transport.dataManagementLabel();
10644                if (MORE_DEBUG) Slog.d(TAG, "getDataManagementLabel() returning " + text);
10645                return text;
10646            } catch (Exception e) {
10647                /* fall through to return null */
10648                Slog.e(TAG, "Unable to get management label from transport: " + e.getMessage());
10649            }
10650        }
10651
10652        return null;
10653    }
10654
10655    // Callback: a requested backup agent has been instantiated.  This should only
10656    // be called from the Activity Manager.
10657    @Override
10658    public void agentConnected(String packageName, IBinder agentBinder) {
10659        synchronized(mAgentConnectLock) {
10660            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
10661                Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
10662                IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
10663                mConnectedAgent = agent;
10664                mConnecting = false;
10665            } else {
10666                Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
10667                        + " claiming agent connected");
10668            }
10669            mAgentConnectLock.notifyAll();
10670        }
10671    }
10672
10673    // Callback: a backup agent has failed to come up, or has unexpectedly quit.
10674    // If the agent failed to come up in the first place, the agentBinder argument
10675    // will be null.  This should only be called from the Activity Manager.
10676    @Override
10677    public void agentDisconnected(String packageName) {
10678        // TODO: handle backup being interrupted
10679        synchronized(mAgentConnectLock) {
10680            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
10681                mConnectedAgent = null;
10682                mConnecting = false;
10683            } else {
10684                Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
10685                        + " claiming agent disconnected");
10686            }
10687            mAgentConnectLock.notifyAll();
10688        }
10689    }
10690
10691    // An application being installed will need a restore pass, then the Package Manager
10692    // will need to be told when the restore is finished.
10693    @Override
10694    public void restoreAtInstall(String packageName, int token) {
10695        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
10696            Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
10697                    + " attemping install-time restore");
10698            return;
10699        }
10700
10701        boolean skip = false;
10702
10703        long restoreSet = getAvailableRestoreToken(packageName);
10704        if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
10705                + " token=" + Integer.toHexString(token)
10706                + " restoreSet=" + Long.toHexString(restoreSet));
10707        if (restoreSet == 0) {
10708            if (MORE_DEBUG) Slog.i(TAG, "No restore set");
10709            skip = true;
10710        }
10711
10712        // Do we have a transport to fetch data for us?
10713        IBackupTransport transport = mTransportManager.getCurrentTransportBinder();
10714        if (transport == null) {
10715            if (DEBUG) Slog.w(TAG, "No transport");
10716            skip = true;
10717        }
10718
10719        if (!mAutoRestore) {
10720            if (DEBUG) {
10721                Slog.w(TAG, "Non-restorable state: auto=" + mAutoRestore);
10722            }
10723            skip = true;
10724        }
10725
10726        if (!skip) {
10727            try {
10728                // okay, we're going to attempt a restore of this package from this restore set.
10729                // The eventual message back into the Package Manager to run the post-install
10730                // steps for 'token' will be issued from the restore handling code.
10731
10732                // This can throw and so *must* happen before the wakelock is acquired
10733                String dirName = transport.transportDirName();
10734
10735                mWakelock.acquire();
10736                if (MORE_DEBUG) {
10737                    Slog.d(TAG, "Restore at install of " + packageName);
10738                }
10739                Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
10740                msg.obj = new RestoreParams(transport, dirName, null, null,
10741                        restoreSet, packageName, token);
10742                mBackupHandler.sendMessage(msg);
10743            } catch (Exception e) {
10744                // Calling into the transport broke; back off and proceed with the installation.
10745                Slog.e(TAG, "Unable to contact transport: " + e.getMessage());
10746                skip = true;
10747            }
10748        }
10749
10750        if (skip) {
10751            // Auto-restore disabled or no way to attempt a restore; just tell the Package
10752            // Manager to proceed with the post-install handling for this package.
10753            if (DEBUG) Slog.v(TAG, "Finishing install immediately");
10754            try {
10755                mPackageManagerBinder.finishPackageInstall(token, false);
10756            } catch (RemoteException e) { /* can't happen */ }
10757        }
10758    }
10759
10760    // Hand off a restore session
10761    @Override
10762    public IRestoreSession beginRestoreSession(String packageName, String transport) {
10763        if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
10764                + " transport=" + transport);
10765
10766        boolean needPermission = true;
10767        if (transport == null) {
10768            transport = mTransportManager.getCurrentTransportName();
10769
10770            if (packageName != null) {
10771                PackageInfo app = null;
10772                try {
10773                    app = mPackageManager.getPackageInfo(packageName, 0);
10774                } catch (NameNotFoundException nnf) {
10775                    Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
10776                    throw new IllegalArgumentException("Package " + packageName + " not found");
10777                }
10778
10779                if (app.applicationInfo.uid == Binder.getCallingUid()) {
10780                    // So: using the current active transport, and the caller has asked
10781                    // that its own package will be restored.  In this narrow use case
10782                    // we do not require the caller to hold the permission.
10783                    needPermission = false;
10784                }
10785            }
10786        }
10787
10788        if (needPermission) {
10789            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10790                    "beginRestoreSession");
10791        } else {
10792            if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
10793        }
10794
10795        synchronized(this) {
10796            if (mActiveRestoreSession != null) {
10797                Slog.i(TAG, "Restore session requested but one already active");
10798                return null;
10799            }
10800            if (mBackupRunning) {
10801                Slog.i(TAG, "Restore session requested but currently running backups");
10802                return null;
10803            }
10804            mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
10805            mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_SESSION_TIMEOUT,
10806                    TIMEOUT_RESTORE_INTERVAL);
10807        }
10808        return mActiveRestoreSession;
10809    }
10810
10811    void clearRestoreSession(ActiveRestoreSession currentSession) {
10812        synchronized(this) {
10813            if (currentSession != mActiveRestoreSession) {
10814                Slog.e(TAG, "ending non-current restore session");
10815            } else {
10816                if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
10817                mActiveRestoreSession = null;
10818                mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
10819            }
10820        }
10821    }
10822
10823    // Note that a currently-active backup agent has notified us that it has
10824    // completed the given outstanding asynchronous backup/restore operation.
10825    @Override
10826    public void opComplete(int token, long result) {
10827        if (MORE_DEBUG) {
10828            Slog.v(TAG, "opComplete: " + Integer.toHexString(token) + " result=" + result);
10829        }
10830        Operation op = null;
10831        synchronized (mCurrentOpLock) {
10832            op = mCurrentOperations.get(token);
10833            if (op != null) {
10834                if (op.state == OP_TIMEOUT) {
10835                    // The operation already timed out, and this is a late response.  Tidy up
10836                    // and ignore it; we've already dealt with the timeout.
10837                    op = null;
10838                    mCurrentOperations.delete(token);
10839                } else if (op.state == OP_ACKNOWLEDGED) {
10840                    if (DEBUG) {
10841                        Slog.w(TAG, "Received duplicate ack for token=" +
10842                                Integer.toHexString(token));
10843                    }
10844                    op = null;
10845                    mCurrentOperations.remove(token);
10846                } else if (op.state == OP_PENDING) {
10847                    // Can't delete op from mCurrentOperations. waitUntilOperationComplete can be
10848                    // called after we we receive this call.
10849                    op.state = OP_ACKNOWLEDGED;
10850                }
10851            }
10852            mCurrentOpLock.notifyAll();
10853        }
10854
10855        // The completion callback, if any, is invoked on the handler
10856        if (op != null && op.callback != null) {
10857            Pair<BackupRestoreTask, Long> callbackAndResult = Pair.create(op.callback, result);
10858            Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, callbackAndResult);
10859            mBackupHandler.sendMessage(msg);
10860        }
10861    }
10862
10863    @Override
10864    public boolean isAppEligibleForBackup(String packageName) {
10865        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10866                "isAppEligibleForBackup");
10867        try {
10868            PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName,
10869                    PackageManager.GET_SIGNATURES);
10870            if (!appIsEligibleForBackup(packageInfo.applicationInfo, mPackageManager) ||
10871                    appIsStopped(packageInfo.applicationInfo)) {
10872                return false;
10873            }
10874            IBackupTransport transport = mTransportManager.getCurrentTransportBinder();
10875            if (transport != null) {
10876                try {
10877                    return transport.isAppEligibleForBackup(packageInfo,
10878                        appGetsFullBackup(packageInfo));
10879                } catch (Exception e) {
10880                    Slog.e(TAG, "Unable to ask about eligibility: " + e.getMessage());
10881                }
10882            }
10883            // If transport is not present we couldn't tell that the package is not eligible.
10884            return true;
10885        } catch (NameNotFoundException e) {
10886            return false;
10887        }
10888    }
10889
10890    // ----- Restore session -----
10891
10892    class ActiveRestoreSession extends IRestoreSession.Stub {
10893        private static final String TAG = "RestoreSession";
10894
10895        private String mPackageName;
10896        private IBackupTransport mRestoreTransport = null;
10897        RestoreSet[] mRestoreSets = null;
10898        boolean mEnded = false;
10899        boolean mTimedOut = false;
10900
10901        ActiveRestoreSession(String packageName, String transport) {
10902            mPackageName = packageName;
10903            mRestoreTransport = mTransportManager.getTransportBinder(transport);
10904        }
10905
10906        public void markTimedOut() {
10907            mTimedOut = true;
10908        }
10909
10910        // --- Binder interface ---
10911        public synchronized int getAvailableRestoreSets(IRestoreObserver observer,
10912                IBackupManagerMonitor monitor) {
10913            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10914                    "getAvailableRestoreSets");
10915            if (observer == null) {
10916                throw new IllegalArgumentException("Observer must not be null");
10917            }
10918
10919            if (mEnded) {
10920                throw new IllegalStateException("Restore session already ended");
10921            }
10922
10923            if (mTimedOut) {
10924                Slog.i(TAG, "Session already timed out");
10925                return -1;
10926            }
10927
10928            long oldId = Binder.clearCallingIdentity();
10929            try {
10930                if (mRestoreTransport == null) {
10931                    Slog.w(TAG, "Null transport getting restore sets");
10932                    return -1;
10933                }
10934
10935                // We know we're doing legit work now, so halt the timeout
10936                // until we're done.  It gets started again when the result
10937                // comes in.
10938                mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
10939
10940                // spin off the transport request to our service thread
10941                mWakelock.acquire();
10942                Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
10943                        new RestoreGetSetsParams(mRestoreTransport, this, observer,
10944                                monitor));
10945                mBackupHandler.sendMessage(msg);
10946                return 0;
10947            } catch (Exception e) {
10948                Slog.e(TAG, "Error in getAvailableRestoreSets", e);
10949                return -1;
10950            } finally {
10951                Binder.restoreCallingIdentity(oldId);
10952            }
10953        }
10954
10955        public synchronized int restoreAll(long token, IRestoreObserver observer,
10956                IBackupManagerMonitor monitor) {
10957            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10958                    "performRestore");
10959
10960            if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
10961                    + " observer=" + observer);
10962
10963            if (mEnded) {
10964                throw new IllegalStateException("Restore session already ended");
10965            }
10966
10967            if (mTimedOut) {
10968                Slog.i(TAG, "Session already timed out");
10969                return -1;
10970            }
10971
10972            if (mRestoreTransport == null || mRestoreSets == null) {
10973                Slog.e(TAG, "Ignoring restoreAll() with no restore set");
10974                return -1;
10975            }
10976
10977            if (mPackageName != null) {
10978                Slog.e(TAG, "Ignoring restoreAll() on single-package session");
10979                return -1;
10980            }
10981
10982            String dirName;
10983            try {
10984                dirName = mRestoreTransport.transportDirName();
10985            } catch (Exception e) {
10986                // Transport went AWOL; fail.
10987                Slog.e(TAG, "Unable to get transport dir for restore: " + e.getMessage());
10988                return -1;
10989            }
10990
10991            synchronized (mQueueLock) {
10992                for (int i = 0; i < mRestoreSets.length; i++) {
10993                    if (token == mRestoreSets[i].token) {
10994                        // Real work, so stop the session timeout until we finalize the restore
10995                        mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
10996
10997                        long oldId = Binder.clearCallingIdentity();
10998                        mWakelock.acquire();
10999                        if (MORE_DEBUG) {
11000                            Slog.d(TAG, "restoreAll() kicking off");
11001                        }
11002                        Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
11003                        msg.obj = new RestoreParams(mRestoreTransport, dirName,
11004                                observer, monitor, token);
11005                        mBackupHandler.sendMessage(msg);
11006                        Binder.restoreCallingIdentity(oldId);
11007                        return 0;
11008                    }
11009                }
11010            }
11011
11012            Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
11013            return -1;
11014        }
11015
11016        // Restores of more than a single package are treated as 'system' restores
11017        public synchronized int restoreSome(long token, IRestoreObserver observer,
11018                IBackupManagerMonitor monitor, String[] packages) {
11019            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
11020                    "performRestore");
11021
11022            if (DEBUG) {
11023                StringBuilder b = new StringBuilder(128);
11024                b.append("restoreSome token=");
11025                b.append(Long.toHexString(token));
11026                b.append(" observer=");
11027                b.append(observer.toString());
11028                b.append(" monitor=");
11029                if (monitor == null) {
11030                    b.append("null");
11031                } else {
11032                    b.append(monitor.toString());
11033                }
11034                b.append(" packages=");
11035                if (packages == null) {
11036                    b.append("null");
11037                } else {
11038                    b.append('{');
11039                    boolean first = true;
11040                    for (String s : packages) {
11041                        if (!first) {
11042                            b.append(", ");
11043                        } else first = false;
11044                        b.append(s);
11045                    }
11046                    b.append('}');
11047                }
11048                Slog.d(TAG, b.toString());
11049            }
11050
11051            if (mEnded) {
11052                throw new IllegalStateException("Restore session already ended");
11053            }
11054
11055            if (mTimedOut) {
11056                Slog.i(TAG, "Session already timed out");
11057                return -1;
11058            }
11059
11060            if (mRestoreTransport == null || mRestoreSets == null) {
11061                Slog.e(TAG, "Ignoring restoreAll() with no restore set");
11062                return -1;
11063            }
11064
11065            if (mPackageName != null) {
11066                Slog.e(TAG, "Ignoring restoreAll() on single-package session");
11067                return -1;
11068            }
11069
11070            String dirName;
11071            try {
11072                dirName = mRestoreTransport.transportDirName();
11073            } catch (Exception e) {
11074                // Transport went AWOL; fail.
11075                Slog.e(TAG, "Unable to get transport name for restoreSome: " + e.getMessage());
11076                return -1;
11077            }
11078
11079            synchronized (mQueueLock) {
11080                for (int i = 0; i < mRestoreSets.length; i++) {
11081                    if (token == mRestoreSets[i].token) {
11082                        // Stop the session timeout until we finalize the restore
11083                        mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
11084
11085                        long oldId = Binder.clearCallingIdentity();
11086                        mWakelock.acquire();
11087                        if (MORE_DEBUG) {
11088                            Slog.d(TAG, "restoreSome() of " + packages.length + " packages");
11089                        }
11090                        Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
11091                        msg.obj = new RestoreParams(mRestoreTransport, dirName, observer, monitor,
11092                                token, packages, packages.length > 1);
11093                        mBackupHandler.sendMessage(msg);
11094                        Binder.restoreCallingIdentity(oldId);
11095                        return 0;
11096                    }
11097                }
11098            }
11099
11100            Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
11101            return -1;
11102        }
11103
11104        public synchronized int restorePackage(String packageName, IRestoreObserver observer,
11105                IBackupManagerMonitor monitor) {
11106            if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer
11107                    + "monitor=" + monitor);
11108
11109            if (mEnded) {
11110                throw new IllegalStateException("Restore session already ended");
11111            }
11112
11113            if (mTimedOut) {
11114                Slog.i(TAG, "Session already timed out");
11115                return -1;
11116            }
11117
11118            if (mPackageName != null) {
11119                if (! mPackageName.equals(packageName)) {
11120                    Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
11121                            + " on session for package " + mPackageName);
11122                    return -1;
11123                }
11124            }
11125
11126            PackageInfo app = null;
11127            try {
11128                app = mPackageManager.getPackageInfo(packageName, 0);
11129            } catch (NameNotFoundException nnf) {
11130                Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
11131                return -1;
11132            }
11133
11134            // If the caller is not privileged and is not coming from the target
11135            // app's uid, throw a permission exception back to the caller.
11136            int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
11137                    Binder.getCallingPid(), Binder.getCallingUid());
11138            if ((perm == PackageManager.PERMISSION_DENIED) &&
11139                    (app.applicationInfo.uid != Binder.getCallingUid())) {
11140                Slog.w(TAG, "restorePackage: bad packageName=" + packageName
11141                        + " or calling uid=" + Binder.getCallingUid());
11142                throw new SecurityException("No permission to restore other packages");
11143            }
11144
11145            // So far so good; we're allowed to try to restore this package.
11146            long oldId = Binder.clearCallingIdentity();
11147            try {
11148                // Check whether there is data for it in the current dataset, falling back
11149                // to the ancestral dataset if not.
11150                long token = getAvailableRestoreToken(packageName);
11151                if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName
11152                        + " token=" + Long.toHexString(token));
11153
11154                // If we didn't come up with a place to look -- no ancestral dataset and
11155                // the app has never been backed up from this device -- there's nothing
11156                // to do but return failure.
11157                if (token == 0) {
11158                    if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
11159                    return -1;
11160                }
11161
11162                String dirName;
11163                try {
11164                    dirName = mRestoreTransport.transportDirName();
11165                } catch (Exception e) {
11166                    // Transport went AWOL; fail.
11167                    Slog.e(TAG, "Unable to get transport dir for restorePackage: " + e.getMessage());
11168                    return -1;
11169                }
11170
11171                // Stop the session timeout until we finalize the restore
11172                mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
11173
11174                // Ready to go:  enqueue the restore request and claim success
11175                mWakelock.acquire();
11176                if (MORE_DEBUG) {
11177                    Slog.d(TAG, "restorePackage() : " + packageName);
11178                }
11179                Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
11180                msg.obj = new RestoreParams(mRestoreTransport, dirName, observer, monitor,
11181                        token, app);
11182                mBackupHandler.sendMessage(msg);
11183            } finally {
11184                Binder.restoreCallingIdentity(oldId);
11185            }
11186            return 0;
11187        }
11188
11189        // Posted to the handler to tear down a restore session in a cleanly synchronized way
11190        class EndRestoreRunnable implements Runnable {
11191            BackupManagerService mBackupManager;
11192            ActiveRestoreSession mSession;
11193
11194            EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
11195                mBackupManager = manager;
11196                mSession = session;
11197            }
11198
11199            public void run() {
11200                // clean up the session's bookkeeping
11201                synchronized (mSession) {
11202                    mSession.mRestoreTransport = null;
11203                    mSession.mEnded = true;
11204                }
11205
11206                // clean up the BackupManagerImpl side of the bookkeeping
11207                // and cancel any pending timeout message
11208                mBackupManager.clearRestoreSession(mSession);
11209            }
11210        }
11211
11212        public synchronized void endRestoreSession() {
11213            if (DEBUG) Slog.d(TAG, "endRestoreSession");
11214
11215            if (mTimedOut) {
11216                Slog.i(TAG, "Session already timed out");
11217                return;
11218            }
11219
11220            if (mEnded) {
11221                throw new IllegalStateException("Restore session already ended");
11222            }
11223
11224            mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
11225        }
11226    }
11227
11228    @Override
11229    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11230        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
11231
11232        long identityToken = Binder.clearCallingIdentity();
11233        try {
11234            if (args != null) {
11235                for (String arg : args) {
11236                    if ("-h".equals(arg)) {
11237                        pw.println("'dumpsys backup' optional arguments:");
11238                        pw.println("  -h       : this help text");
11239                        pw.println("  a[gents] : dump information about defined backup agents");
11240                        return;
11241                    } else if ("agents".startsWith(arg)) {
11242                        dumpAgents(pw);
11243                        return;
11244                    }
11245                }
11246            }
11247            dumpInternal(pw);
11248        } finally {
11249            Binder.restoreCallingIdentity(identityToken);
11250        }
11251    }
11252
11253    private void dumpAgents(PrintWriter pw) {
11254        List<PackageInfo> agentPackages = allAgentPackages();
11255        pw.println("Defined backup agents:");
11256        for (PackageInfo pkg : agentPackages) {
11257            pw.print("  ");
11258            pw.print(pkg.packageName); pw.println(':');
11259            pw.print("      "); pw.println(pkg.applicationInfo.backupAgentName);
11260        }
11261    }
11262
11263    private void dumpInternal(PrintWriter pw) {
11264        synchronized (mQueueLock) {
11265            pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
11266                    + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
11267                    + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
11268            pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
11269            if (mBackupRunning) pw.println("Backup currently running");
11270            pw.println("Last backup pass started: " + mLastBackupPass
11271                    + " (now = " + System.currentTimeMillis() + ')');
11272            pw.println("  next scheduled: " + KeyValueBackupJob.nextScheduled());
11273
11274            pw.println("Transport whitelist:");
11275            for (ComponentName transport : mTransportManager.getTransportWhitelist()) {
11276                pw.print("    ");
11277                pw.println(transport.flattenToShortString());
11278            }
11279
11280            pw.println("Available transports:");
11281            final String[] transports = listAllTransports();
11282            if (transports != null) {
11283                for (String t : listAllTransports()) {
11284                    pw.println((t.equals(mTransportManager.getCurrentTransportName()) ? "  * " : "    ") + t);
11285                    try {
11286                        IBackupTransport transport = mTransportManager.getTransportBinder(t);
11287                        File dir = new File(mBaseStateDir, transport.transportDirName());
11288                        pw.println("       destination: " + transport.currentDestinationString());
11289                        pw.println("       intent: " + transport.configurationIntent());
11290                        for (File f : dir.listFiles()) {
11291                            pw.println("       " + f.getName() + " - " + f.length() + " state bytes");
11292                        }
11293                    } catch (Exception e) {
11294                        Slog.e(TAG, "Error in transport", e);
11295                        pw.println("        Error: " + e);
11296                    }
11297                }
11298            }
11299
11300            pw.println("Pending init: " + mPendingInits.size());
11301            for (String s : mPendingInits) {
11302                pw.println("    " + s);
11303            }
11304
11305            if (DEBUG_BACKUP_TRACE) {
11306                synchronized (mBackupTrace) {
11307                    if (!mBackupTrace.isEmpty()) {
11308                        pw.println("Most recent backup trace:");
11309                        for (String s : mBackupTrace) {
11310                            pw.println("   " + s);
11311                        }
11312                    }
11313                }
11314            }
11315
11316            pw.print("Ancestral: "); pw.println(Long.toHexString(mAncestralToken));
11317            pw.print("Current:   "); pw.println(Long.toHexString(mCurrentToken));
11318
11319            int N = mBackupParticipants.size();
11320            pw.println("Participants:");
11321            for (int i=0; i<N; i++) {
11322                int uid = mBackupParticipants.keyAt(i);
11323                pw.print("  uid: ");
11324                pw.println(uid);
11325                HashSet<String> participants = mBackupParticipants.valueAt(i);
11326                for (String app: participants) {
11327                    pw.println("    " + app);
11328                }
11329            }
11330
11331            pw.println("Ancestral packages: "
11332                    + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
11333            if (mAncestralPackages != null) {
11334                for (String pkg : mAncestralPackages) {
11335                    pw.println("    " + pkg);
11336                }
11337            }
11338
11339            pw.println("Ever backed up: " + mEverStoredApps.size());
11340            for (String pkg : mEverStoredApps) {
11341                pw.println("    " + pkg);
11342            }
11343
11344            pw.println("Pending key/value backup: " + mPendingBackups.size());
11345            for (BackupRequest req : mPendingBackups.values()) {
11346                pw.println("    " + req);
11347            }
11348
11349            pw.println("Full backup queue:" + mFullBackupQueue.size());
11350            for (FullBackupEntry entry : mFullBackupQueue) {
11351                pw.print("    "); pw.print(entry.lastBackup);
11352                pw.print(" : "); pw.println(entry.packageName);
11353            }
11354        }
11355    }
11356
11357    private static void sendBackupOnUpdate(IBackupObserver observer, String packageName,
11358            BackupProgress progress) {
11359        if (observer != null) {
11360            try {
11361                observer.onUpdate(packageName, progress);
11362            } catch (RemoteException e) {
11363                if (DEBUG) {
11364                    Slog.w(TAG, "Backup observer went away: onUpdate");
11365                }
11366            }
11367        }
11368    }
11369
11370    private static void sendBackupOnPackageResult(IBackupObserver observer, String packageName,
11371            int status) {
11372        if (observer != null) {
11373            try {
11374                observer.onResult(packageName, status);
11375            } catch (RemoteException e) {
11376                if (DEBUG) {
11377                    Slog.w(TAG, "Backup observer went away: onResult");
11378                }
11379            }
11380        }
11381    }
11382
11383    private static void sendBackupFinished(IBackupObserver observer, int status) {
11384        if (observer != null) {
11385            try {
11386                observer.backupFinished(status);
11387            } catch (RemoteException e) {
11388                if (DEBUG) {
11389                    Slog.w(TAG, "Backup observer went away: backupFinished");
11390                }
11391            }
11392        }
11393    }
11394
11395    private Bundle putMonitoringExtra(Bundle extras, String key, String value) {
11396        if (extras == null) {
11397            extras = new Bundle();
11398        }
11399        extras.putString(key, value);
11400        return extras;
11401    }
11402
11403    private Bundle putMonitoringExtra(Bundle extras, String key, int value) {
11404        if (extras == null) {
11405            extras = new Bundle();
11406        }
11407        extras.putInt(key, value);
11408        return extras;
11409    }
11410
11411    private Bundle putMonitoringExtra(Bundle extras, String key, long value) {
11412        if (extras == null) {
11413            extras = new Bundle();
11414        }
11415        extras.putLong(key, value);
11416        return extras;
11417    }
11418
11419
11420    private Bundle putMonitoringExtra(Bundle extras, String key, boolean value) {
11421        if (extras == null) {
11422            extras = new Bundle();
11423        }
11424        extras.putBoolean(key, value);
11425        return extras;
11426    }
11427
11428    private static IBackupManagerMonitor monitorEvent(IBackupManagerMonitor monitor, int id,
11429            PackageInfo pkg, int category, Bundle extras) {
11430        if (monitor != null) {
11431            try {
11432                Bundle bundle = new Bundle();
11433                bundle.putInt(BackupManagerMonitor.EXTRA_LOG_EVENT_ID, id);
11434                bundle.putInt(BackupManagerMonitor.EXTRA_LOG_EVENT_CATEGORY, category);
11435                if (pkg != null) {
11436                    bundle.putString(EXTRA_LOG_EVENT_PACKAGE_NAME,
11437                            pkg.packageName);
11438                    bundle.putInt(BackupManagerMonitor.EXTRA_LOG_EVENT_PACKAGE_VERSION,
11439                            pkg.versionCode);
11440                }
11441                if (extras != null) {
11442                    bundle.putAll(extras);
11443                }
11444                monitor.onEvent(bundle);
11445                return monitor;
11446            } catch(RemoteException e) {
11447                if (DEBUG) {
11448                    Slog.w(TAG, "backup manager monitor went away");
11449                }
11450            }
11451        }
11452        return null;
11453    }
11454
11455    @Override
11456    public IBackupManager getBackupManagerBinder() {
11457        return mBackupManagerBinder;
11458    }
11459
11460}
11461