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