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