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