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