BackupManagerService.java revision 1a7d868804af59cfc6456bb156358505a572443d
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                    PackageInfo currentPackage = mPackages.get(i);
4879                    String packageName = currentPackage.packageName;
4880                    if (DEBUG) {
4881                        Slog.i(TAG, "Initiating full-data transport backup of " + packageName
4882                                + " token: " + mCurrentOpToken);
4883                    }
4884                    EventLog.writeEvent(EventLogTags.FULL_BACKUP_PACKAGE, packageName);
4885
4886                    transportPipes = ParcelFileDescriptor.createPipe();
4887
4888                    // Tell the transport the data's coming
4889                    int flags = mUserInitiated ? BackupTransport.FLAG_USER_INITIATED : 0;
4890                    int backupPackageStatus;
4891                    long quota = Long.MAX_VALUE;
4892                    synchronized (mCancelLock) {
4893                        if (mCancelAll) {
4894                            break;
4895                        }
4896                        backupPackageStatus = mTransport.performFullBackup(currentPackage,
4897                                transportPipes[0], flags);
4898
4899                        if (backupPackageStatus == BackupTransport.TRANSPORT_OK) {
4900                            quota = mTransport.getBackupQuota(currentPackage.packageName,
4901                                    true /* isFullBackup */);
4902                            // Now set up the backup engine / data source end of things
4903                            enginePipes = ParcelFileDescriptor.createPipe();
4904                            mBackupRunner =
4905                                    new SinglePackageBackupRunner(enginePipes[1], currentPackage,
4906                                            mTransport, quota, mBackupRunnerOpToken);
4907                            // The runner dup'd the pipe half, so we close it here
4908                            enginePipes[1].close();
4909                            enginePipes[1] = null;
4910
4911                            mIsDoingBackup = true;
4912                        }
4913                    }
4914                    if (backupPackageStatus == BackupTransport.TRANSPORT_OK) {
4915
4916                        // The transport has its own copy of the read end of the pipe,
4917                        // so close ours now
4918                        transportPipes[0].close();
4919                        transportPipes[0] = null;
4920
4921                        // Spin off the runner to fetch the app's data and pipe it
4922                        // into the engine pipes
4923                        (new Thread(mBackupRunner, "package-backup-bridge")).start();
4924
4925                        // Read data off the engine pipe and pass it to the transport
4926                        // pipe until we hit EOD on the input stream.  We do not take
4927                        // close() responsibility for these FDs into these stream wrappers.
4928                        FileInputStream in = new FileInputStream(
4929                                enginePipes[0].getFileDescriptor());
4930                        FileOutputStream out = new FileOutputStream(
4931                                transportPipes[1].getFileDescriptor());
4932                        long totalRead = 0;
4933                        final long preflightResult = mBackupRunner.getPreflightResultBlocking();
4934                        // Preflight result is negative if some error happened on preflight.
4935                        if (preflightResult < 0) {
4936                            if (MORE_DEBUG) {
4937                                Slog.d(TAG, "Backup error after preflight of package "
4938                                        + packageName + ": " + preflightResult
4939                                        + ", not running backup.");
4940                            }
4941                            mMonitor = monitorEvent(mMonitor,
4942                                    BackupManagerMonitor.LOG_EVENT_ID_ERROR_PREFLIGHT,
4943                                    mCurrentPackage,
4944                                    BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
4945                                    putMonitoringExtra(null,
4946                                            BackupManagerMonitor.EXTRA_LOG_PREFLIGHT_ERROR,
4947                                            preflightResult));
4948                            backupPackageStatus = (int) preflightResult;
4949                        } else {
4950                            int nRead = 0;
4951                            do {
4952                                nRead = in.read(buffer);
4953                                if (MORE_DEBUG) {
4954                                    Slog.v(TAG, "in.read(buffer) from app: " + nRead);
4955                                }
4956                                if (nRead > 0) {
4957                                    out.write(buffer, 0, nRead);
4958                                    synchronized (mCancelLock) {
4959                                        if (!mCancelAll) {
4960                                            backupPackageStatus = mTransport.sendBackupData(nRead);
4961                                        }
4962                                    }
4963                                    totalRead += nRead;
4964                                    if (mBackupObserver != null && preflightResult > 0) {
4965                                        sendBackupOnUpdate(mBackupObserver, packageName,
4966                                                new BackupProgress(preflightResult, totalRead));
4967                                    }
4968                                }
4969                            } while (nRead > 0
4970                                    && backupPackageStatus == BackupTransport.TRANSPORT_OK);
4971                            // Despite preflight succeeded, package still can hit quota on flight.
4972                            if (backupPackageStatus == BackupTransport.TRANSPORT_QUOTA_EXCEEDED) {
4973                                Slog.w(TAG, "Package hit quota limit in-flight " + packageName
4974                                        + ": " + totalRead + " of " + quota);
4975                                mMonitor = monitorEvent(mMonitor,
4976                                        BackupManagerMonitor.LOG_EVENT_ID_QUOTA_HIT_PREFLIGHT,
4977                                        mCurrentPackage,
4978                                        BackupManagerMonitor.LOG_EVENT_CATEGORY_TRANSPORT,
4979                                        null);
4980                                mBackupRunner.sendQuotaExceeded(totalRead, quota);
4981                            }
4982                        }
4983
4984                        final int backupRunnerResult = mBackupRunner.getBackupResultBlocking();
4985
4986                        synchronized (mCancelLock) {
4987                            mIsDoingBackup = false;
4988                            // If mCancelCurrent is true, we have already called cancelFullBackup().
4989                            if (!mCancelAll) {
4990                                if (backupRunnerResult == BackupTransport.TRANSPORT_OK) {
4991                                    // If we were otherwise in a good state, now interpret the final
4992                                    // result based on what finishBackup() returns.  If we're in a
4993                                    // failure case already, preserve that result and ignore whatever
4994                                    // finishBackup() reports.
4995                                    final int finishResult = mTransport.finishBackup();
4996                                    if (backupPackageStatus == BackupTransport.TRANSPORT_OK) {
4997                                        backupPackageStatus = finishResult;
4998                                    }
4999                                } else {
5000                                    mTransport.cancelFullBackup();
5001                                }
5002                            }
5003                        }
5004
5005                        // A transport-originated error here means that we've hit an error that the
5006                        // runner doesn't know about, so it's still moving data but we're pulling the
5007                        // rug out from under it.  Don't ask for its result:  we already know better
5008                        // and we'll hang if we block waiting for it, since it relies on us to
5009                        // read back the data it's writing into the engine.  Just proceed with
5010                        // a graceful failure.  The runner/engine mechanism will tear itself
5011                        // down cleanly when we close the pipes from this end.  Transport-level
5012                        // errors take precedence over agent/app-specific errors for purposes of
5013                        // determining our course of action.
5014                        if (backupPackageStatus == BackupTransport.TRANSPORT_OK) {
5015                            // We still could fail in backup runner thread.
5016                            if (backupRunnerResult != BackupTransport.TRANSPORT_OK) {
5017                                // If there was an error in runner thread and
5018                                // not TRANSPORT_ERROR here, overwrite it.
5019                                backupPackageStatus = backupRunnerResult;
5020                            }
5021                        } else {
5022                            if (MORE_DEBUG) {
5023                                Slog.i(TAG, "Transport-level failure; cancelling agent work");
5024                            }
5025                        }
5026
5027                        if (MORE_DEBUG) {
5028                            Slog.i(TAG, "Done delivering backup data: result="
5029                                    + backupPackageStatus);
5030                        }
5031
5032                        if (backupPackageStatus != BackupTransport.TRANSPORT_OK) {
5033                            Slog.e(TAG, "Error " + backupPackageStatus + " backing up "
5034                                    + packageName);
5035                        }
5036
5037                        // Also ask the transport how long it wants us to wait before
5038                        // moving on to the next package, if any.
5039                        backoff = mTransport.requestFullBackupTime();
5040                        if (DEBUG_SCHEDULING) {
5041                            Slog.i(TAG, "Transport suggested backoff=" + backoff);
5042                        }
5043
5044                    }
5045
5046                    // Roll this package to the end of the backup queue if we're
5047                    // in a queue-driven mode (regardless of success/failure)
5048                    if (mUpdateSchedule) {
5049                        enqueueFullBackup(packageName, System.currentTimeMillis());
5050                    }
5051
5052                    if (backupPackageStatus == BackupTransport.TRANSPORT_PACKAGE_REJECTED) {
5053                        sendBackupOnPackageResult(mBackupObserver, packageName,
5054                                BackupManager.ERROR_TRANSPORT_PACKAGE_REJECTED);
5055                        if (DEBUG) {
5056                            Slog.i(TAG, "Transport rejected backup of " + packageName
5057                                    + ", skipping");
5058                        }
5059                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_AGENT_FAILURE, packageName,
5060                                "transport rejected");
5061                        // Do nothing, clean up, and continue looping.
5062                    } else if (backupPackageStatus == BackupTransport.TRANSPORT_QUOTA_EXCEEDED) {
5063                        sendBackupOnPackageResult(mBackupObserver, packageName,
5064                                BackupManager.ERROR_TRANSPORT_QUOTA_EXCEEDED);
5065                        if (DEBUG) {
5066                            Slog.i(TAG, "Transport quota exceeded for package: " + packageName);
5067                            EventLog.writeEvent(EventLogTags.FULL_BACKUP_QUOTA_EXCEEDED,
5068                                    packageName);
5069                        }
5070                        // Do nothing, clean up, and continue looping.
5071                    } else if (backupPackageStatus == BackupTransport.AGENT_ERROR) {
5072                        sendBackupOnPackageResult(mBackupObserver, packageName,
5073                                BackupManager.ERROR_AGENT_FAILURE);
5074                        Slog.w(TAG, "Application failure for package: " + packageName);
5075                        EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName);
5076                        tearDownAgentAndKill(currentPackage.applicationInfo);
5077                        // Do nothing, clean up, and continue looping.
5078                    } else if (backupPackageStatus == BackupManager.ERROR_BACKUP_CANCELLED) {
5079                        sendBackupOnPackageResult(mBackupObserver, packageName,
5080                                BackupManager.ERROR_BACKUP_CANCELLED);
5081                        Slog.w(TAG, "Backup cancelled. package=" + packageName +
5082                                ", cancelAll=" + mCancelAll);
5083                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_CANCELLED, packageName);
5084                        tearDownAgentAndKill(currentPackage.applicationInfo);
5085                        // Do nothing, clean up, and continue looping.
5086                    } else if (backupPackageStatus != BackupTransport.TRANSPORT_OK) {
5087                        sendBackupOnPackageResult(mBackupObserver, packageName,
5088                            BackupManager.ERROR_TRANSPORT_ABORTED);
5089                        Slog.w(TAG, "Transport failed; aborting backup: " + backupPackageStatus);
5090                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_TRANSPORT_FAILURE);
5091                        // Abort entire backup pass.
5092                        backupRunStatus = BackupManager.ERROR_TRANSPORT_ABORTED;
5093                        return;
5094                    } else {
5095                        // Success!
5096                        sendBackupOnPackageResult(mBackupObserver, packageName,
5097                                BackupManager.SUCCESS);
5098                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_SUCCESS, packageName);
5099                        logBackupComplete(packageName);
5100                    }
5101                    cleanUpPipes(transportPipes);
5102                    cleanUpPipes(enginePipes);
5103                    if (currentPackage.applicationInfo != null) {
5104                        Slog.i(TAG, "Unbinding agent in " + packageName);
5105                        addBackupTrace("unbinding " + packageName);
5106                        try {
5107                            mActivityManager.unbindBackupAgent(currentPackage.applicationInfo);
5108                        } catch (RemoteException e) { /* can't happen; activity manager is local */ }
5109                    }
5110                }
5111            } catch (Exception e) {
5112                backupRunStatus = BackupManager.ERROR_TRANSPORT_ABORTED;
5113                Slog.w(TAG, "Exception trying full transport backup", e);
5114                mMonitor = monitorEvent(mMonitor,
5115                        BackupManagerMonitor.LOG_EVENT_ID_EXCEPTION_FULL_BACKUP,
5116                        mCurrentPackage,
5117                        BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
5118                        putMonitoringExtra(null,
5119                                BackupManagerMonitor.EXTRA_LOG_EXCEPTION_FULL_BACKUP,
5120                                Log.getStackTraceString(e)));
5121
5122            } finally {
5123
5124                if (mCancelAll) {
5125                    backupRunStatus = BackupManager.ERROR_BACKUP_CANCELLED;
5126                }
5127
5128                if (DEBUG) {
5129                    Slog.i(TAG, "Full backup completed with status: " + backupRunStatus);
5130                }
5131                sendBackupFinished(mBackupObserver, backupRunStatus);
5132
5133                cleanUpPipes(transportPipes);
5134                cleanUpPipes(enginePipes);
5135
5136                unregisterTask();
5137
5138                if (mJob != null) {
5139                    mJob.finishBackupPass();
5140                }
5141
5142                synchronized (mQueueLock) {
5143                    mRunningFullBackupTask = null;
5144                }
5145
5146                mLatch.countDown();
5147
5148                // Now that we're actually done with schedule-driven work, reschedule
5149                // the next pass based on the new queue state.
5150                if (mUpdateSchedule) {
5151                    scheduleNextFullBackupJob(backoff);
5152                }
5153
5154                Slog.i(BackupManagerService.TAG, "Full data backup pass finished.");
5155                mWakelock.release();
5156            }
5157        }
5158
5159        void cleanUpPipes(ParcelFileDescriptor[] pipes) {
5160            if (pipes != null) {
5161                if (pipes[0] != null) {
5162                    ParcelFileDescriptor fd = pipes[0];
5163                    pipes[0] = null;
5164                    try {
5165                        fd.close();
5166                    } catch (IOException e) {
5167                        Slog.w(TAG, "Unable to close pipe!");
5168                    }
5169                }
5170                if (pipes[1] != null) {
5171                    ParcelFileDescriptor fd = pipes[1];
5172                    pipes[1] = null;
5173                    try {
5174                        fd.close();
5175                    } catch (IOException e) {
5176                        Slog.w(TAG, "Unable to close pipe!");
5177                    }
5178                }
5179            }
5180        }
5181
5182        // Run the backup and pipe it back to the given socket -- expects to run on
5183        // a standalone thread.  The  runner owns this half of the pipe, and closes
5184        // it to indicate EOD to the other end.
5185        class SinglePackageBackupPreflight implements BackupRestoreTask, FullBackupPreflight {
5186            final AtomicLong mResult = new AtomicLong(BackupTransport.AGENT_ERROR);
5187            final CountDownLatch mLatch = new CountDownLatch(1);
5188            final IBackupTransport mTransport;
5189            final long mQuota;
5190            private final int mCurrentOpToken;
5191
5192            SinglePackageBackupPreflight(IBackupTransport transport, long quota, int currentOpToken) {
5193                mTransport = transport;
5194                mQuota = quota;
5195                mCurrentOpToken = currentOpToken;
5196            }
5197
5198            @Override
5199            public int preflightFullBackup(PackageInfo pkg, IBackupAgent agent) {
5200                int result;
5201                try {
5202                    prepareOperationTimeout(mCurrentOpToken, TIMEOUT_FULL_BACKUP_INTERVAL,
5203                            this, OP_TYPE_BACKUP_WAIT);
5204                    addBackupTrace("preflighting");
5205                    if (MORE_DEBUG) {
5206                        Slog.d(TAG, "Preflighting full payload of " + pkg.packageName);
5207                    }
5208                    agent.doMeasureFullBackup(mQuota, mCurrentOpToken, mBackupManagerBinder);
5209
5210                    // Now wait to get our result back.  If this backstop timeout is reached without
5211                    // the latch being thrown, flow will continue as though a result or "normal"
5212                    // timeout had been produced.  In case of a real backstop timeout, mResult
5213                    // will still contain the value it was constructed with, AGENT_ERROR, which
5214                    // intentionaly falls into the "just report failure" code.
5215                    mLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
5216
5217                    long totalSize = mResult.get();
5218                    // If preflight timed out, mResult will contain error code as int.
5219                    if (totalSize < 0) {
5220                        return (int) totalSize;
5221                    }
5222                    if (MORE_DEBUG) {
5223                        Slog.v(TAG, "Got preflight response; size=" + totalSize);
5224                    }
5225
5226                    result = mTransport.checkFullBackupSize(totalSize);
5227                    if (result == BackupTransport.TRANSPORT_QUOTA_EXCEEDED) {
5228                        if (MORE_DEBUG) {
5229                            Slog.d(TAG, "Package hit quota limit on preflight " +
5230                                    pkg.packageName + ": " + totalSize + " of " + mQuota);
5231                        }
5232                        agent.doQuotaExceeded(totalSize, mQuota);
5233                    }
5234                } catch (Exception e) {
5235                    Slog.w(TAG, "Exception preflighting " + pkg.packageName + ": " + e.getMessage());
5236                    result = BackupTransport.AGENT_ERROR;
5237                }
5238                return result;
5239            }
5240
5241            @Override
5242            public void execute() {
5243                // Unused.
5244            }
5245
5246            @Override
5247            public void operationComplete(long result) {
5248                // got the callback, and our preflightFullBackup() method is waiting for the result
5249                if (MORE_DEBUG) {
5250                    Slog.i(TAG, "Preflight op complete, result=" + result);
5251                }
5252                mResult.set(result);
5253                mLatch.countDown();
5254                removeOperation(mCurrentOpToken);
5255            }
5256
5257            @Override
5258            public void handleCancel(boolean cancelAll) {
5259                if (MORE_DEBUG) {
5260                    Slog.i(TAG, "Preflight cancelled; failing");
5261                }
5262                mResult.set(BackupTransport.AGENT_ERROR);
5263                mLatch.countDown();
5264                removeOperation(mCurrentOpToken);
5265            }
5266
5267            @Override
5268            public long getExpectedSizeOrErrorCode() {
5269                try {
5270                    mLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
5271                    return mResult.get();
5272                } catch (InterruptedException e) {
5273                    return BackupTransport.NO_MORE_DATA;
5274                }
5275            }
5276        }
5277
5278        class SinglePackageBackupRunner implements Runnable, BackupRestoreTask {
5279            final ParcelFileDescriptor mOutput;
5280            final PackageInfo mTarget;
5281            final SinglePackageBackupPreflight mPreflight;
5282            final CountDownLatch mPreflightLatch;
5283            final CountDownLatch mBackupLatch;
5284            private final int mCurrentOpToken;
5285            private final int mEphemeralToken;
5286            private FullBackupEngine mEngine;
5287            private volatile int mPreflightResult;
5288            private volatile int mBackupResult;
5289            private final long mQuota;
5290            private volatile boolean mIsCancelled;
5291
5292            SinglePackageBackupRunner(ParcelFileDescriptor output, PackageInfo target,
5293                    IBackupTransport transport, long quota, int currentOpToken) throws IOException {
5294                mOutput = ParcelFileDescriptor.dup(output.getFileDescriptor());
5295                mTarget = target;
5296                mCurrentOpToken = currentOpToken;
5297                mEphemeralToken = generateRandomIntegerToken();
5298                mPreflight = new SinglePackageBackupPreflight(transport, quota, mEphemeralToken);
5299                mPreflightLatch = new CountDownLatch(1);
5300                mBackupLatch = new CountDownLatch(1);
5301                mPreflightResult = BackupTransport.AGENT_ERROR;
5302                mBackupResult = BackupTransport.AGENT_ERROR;
5303                mQuota = quota;
5304                registerTask();
5305            }
5306
5307            void registerTask() {
5308                synchronized (mCurrentOpLock) {
5309                    mCurrentOperations.put(mCurrentOpToken, new Operation(OP_PENDING, this,
5310                            OP_TYPE_BACKUP_WAIT));
5311                }
5312            }
5313
5314            void unregisterTask() {
5315                synchronized (mCurrentOpLock) {
5316                    mCurrentOperations.remove(mCurrentOpToken);
5317                }
5318            }
5319
5320            @Override
5321            public void run() {
5322                FileOutputStream out = new FileOutputStream(mOutput.getFileDescriptor());
5323                mEngine = new FullBackupEngine(out, mPreflight, mTarget, false, this, mQuota, mCurrentOpToken);
5324                try {
5325                    try {
5326                        if (!mIsCancelled) {
5327                            mPreflightResult = mEngine.preflightCheck();
5328                        }
5329                    } finally {
5330                        mPreflightLatch.countDown();
5331                    }
5332                    // If there is no error on preflight, continue backup.
5333                    if (mPreflightResult == BackupTransport.TRANSPORT_OK) {
5334                        if (!mIsCancelled) {
5335                            mBackupResult = mEngine.backupOnePackage();
5336                        }
5337                    }
5338                } catch (Exception e) {
5339                    Slog.e(TAG, "Exception during full package backup of " + mTarget.packageName);
5340                } finally {
5341                    unregisterTask();
5342                    mBackupLatch.countDown();
5343                    try {
5344                        mOutput.close();
5345                    } catch (IOException e) {
5346                        Slog.w(TAG, "Error closing transport pipe in runner");
5347                    }
5348                }
5349            }
5350
5351            public void sendQuotaExceeded(final long backupDataBytes, final long quotaBytes) {
5352                mEngine.sendQuotaExceeded(backupDataBytes, quotaBytes);
5353            }
5354
5355            // If preflight succeeded, returns positive number - preflight size,
5356            // otherwise return negative error code.
5357            long getPreflightResultBlocking() {
5358                try {
5359                    mPreflightLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
5360                    if (mIsCancelled) {
5361                        return BackupManager.ERROR_BACKUP_CANCELLED;
5362                    }
5363                    if (mPreflightResult == BackupTransport.TRANSPORT_OK) {
5364                        return mPreflight.getExpectedSizeOrErrorCode();
5365                    } else {
5366                        return mPreflightResult;
5367                    }
5368                } catch (InterruptedException e) {
5369                    return BackupTransport.AGENT_ERROR;
5370                }
5371            }
5372
5373            int getBackupResultBlocking() {
5374                try {
5375                    mBackupLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
5376                    if (mIsCancelled) {
5377                        return BackupManager.ERROR_BACKUP_CANCELLED;
5378                    }
5379                    return mBackupResult;
5380                } catch (InterruptedException e) {
5381                    return BackupTransport.AGENT_ERROR;
5382                }
5383            }
5384
5385
5386            // BackupRestoreTask interface: specifically, timeout detection
5387
5388            @Override
5389            public void execute() { /* intentionally empty */ }
5390
5391            @Override
5392            public void operationComplete(long result) { /* intentionally empty */ }
5393
5394            @Override
5395            public void handleCancel(boolean cancelAll) {
5396                if (DEBUG) {
5397                    Slog.w(TAG, "Full backup cancel of " + mTarget.packageName);
5398                }
5399
5400                mMonitor = monitorEvent(mMonitor,
5401                        BackupManagerMonitor.LOG_EVENT_ID_FULL_BACKUP_CANCEL,
5402                        mCurrentPackage, BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT, null);
5403                mIsCancelled = true;
5404                // Cancel tasks spun off by this task.
5405                BackupManagerService.this.handleCancel(mEphemeralToken, cancelAll);
5406                tearDownAgentAndKill(mTarget.applicationInfo);
5407                // Free up everyone waiting on this task and its children.
5408                mPreflightLatch.countDown();
5409                mBackupLatch.countDown();
5410                // We are done with this operation.
5411                removeOperation(mCurrentOpToken);
5412            }
5413        }
5414    }
5415
5416    // ----- Full-data backup scheduling -----
5417
5418    /**
5419     * Schedule a job to tell us when it's a good time to run a full backup
5420     */
5421    void scheduleNextFullBackupJob(long transportMinLatency) {
5422        synchronized (mQueueLock) {
5423            if (mFullBackupQueue.size() > 0) {
5424                // schedule the next job at the point in the future when the least-recently
5425                // backed up app comes due for backup again; or immediately if it's already
5426                // due.
5427                final long upcomingLastBackup = mFullBackupQueue.get(0).lastBackup;
5428                final long timeSinceLast = System.currentTimeMillis() - upcomingLastBackup;
5429                final long appLatency = (timeSinceLast < MIN_FULL_BACKUP_INTERVAL)
5430                        ? (MIN_FULL_BACKUP_INTERVAL - timeSinceLast) : 0;
5431                final long latency = Math.max(transportMinLatency, appLatency);
5432                Runnable r = new Runnable() {
5433                    @Override public void run() {
5434                        FullBackupJob.schedule(mContext, latency);
5435                    }
5436                };
5437                mBackupHandler.postDelayed(r, 2500);
5438            } else {
5439                if (DEBUG_SCHEDULING) {
5440                    Slog.i(TAG, "Full backup queue empty; not scheduling");
5441                }
5442            }
5443        }
5444    }
5445
5446    /**
5447     * Remove a package from the full-data queue.
5448     */
5449    void dequeueFullBackupLocked(String packageName) {
5450        final int N = mFullBackupQueue.size();
5451        for (int i = N-1; i >= 0; i--) {
5452            final FullBackupEntry e = mFullBackupQueue.get(i);
5453            if (packageName.equals(e.packageName)) {
5454                mFullBackupQueue.remove(i);
5455            }
5456        }
5457    }
5458
5459    /**
5460     * Enqueue full backup for the given app, with a note about when it last ran.
5461     */
5462    void enqueueFullBackup(String packageName, long lastBackedUp) {
5463        FullBackupEntry newEntry = new FullBackupEntry(packageName, lastBackedUp);
5464        synchronized (mQueueLock) {
5465            // First, sanity check that we aren't adding a duplicate.  Slow but
5466            // straightforward; we'll have at most on the order of a few hundred
5467            // items in this list.
5468            dequeueFullBackupLocked(packageName);
5469
5470            // This is also slow but easy for modest numbers of apps: work backwards
5471            // from the end of the queue until we find an item whose last backup
5472            // time was before this one, then insert this new entry after it.  If we're
5473            // adding something new we don't bother scanning, and just prepend.
5474            int which = -1;
5475            if (lastBackedUp > 0) {
5476                for (which = mFullBackupQueue.size() - 1; which >= 0; which--) {
5477                    final FullBackupEntry entry = mFullBackupQueue.get(which);
5478                    if (entry.lastBackup <= lastBackedUp) {
5479                        mFullBackupQueue.add(which + 1, newEntry);
5480                        break;
5481                    }
5482                }
5483            }
5484            if (which < 0) {
5485                // this one is earlier than any existing one, so prepend
5486                mFullBackupQueue.add(0, newEntry);
5487            }
5488        }
5489        writeFullBackupScheduleAsync();
5490    }
5491
5492    private boolean fullBackupAllowable(IBackupTransport transport) {
5493        if (transport == null) {
5494            Slog.w(TAG, "Transport not present; full data backup not performed");
5495            return false;
5496        }
5497
5498        // Don't proceed unless we have already established package metadata
5499        // for the current dataset via a key/value backup pass.
5500        try {
5501            File stateDir = new File(mBaseStateDir, transport.transportDirName());
5502            File pmState = new File(stateDir, PACKAGE_MANAGER_SENTINEL);
5503            if (pmState.length() <= 0) {
5504                if (DEBUG) {
5505                    Slog.i(TAG, "Full backup requested but dataset not yet initialized");
5506                }
5507                return false;
5508            }
5509        } catch (Exception e) {
5510            Slog.w(TAG, "Unable to get transport name: " + e.getMessage());
5511            return false;
5512        }
5513
5514        return true;
5515    }
5516
5517    /**
5518     * Conditions are right for a full backup operation, so run one.  The model we use is
5519     * to perform one app backup per scheduled job execution, and to reschedule the job
5520     * with zero latency as long as conditions remain right and we still have work to do.
5521     *
5522     * <p>This is the "start a full backup operation" entry point called by the scheduled job.
5523     *
5524     * @return Whether ongoing work will continue.  The return value here will be passed
5525     *         along as the return value to the scheduled job's onStartJob() callback.
5526     */
5527    @Override
5528    public boolean beginFullBackup(FullBackupJob scheduledJob) {
5529        long now = System.currentTimeMillis();
5530        FullBackupEntry entry = null;
5531        long latency = MIN_FULL_BACKUP_INTERVAL;
5532
5533        if (!mEnabled || !mProvisioned) {
5534            // Backups are globally disabled, so don't proceed.  We also don't reschedule
5535            // the job driving automatic backups; that job will be scheduled again when
5536            // the user enables backup.
5537            if (MORE_DEBUG) {
5538                Slog.i(TAG, "beginFullBackup but e=" + mEnabled
5539                        + " p=" + mProvisioned + "; ignoring");
5540            }
5541            return false;
5542        }
5543
5544        // Don't run the backup if we're in battery saver mode, but reschedule
5545        // to try again in the not-so-distant future.
5546        final PowerSaveState result =
5547                mPowerManager.getPowerSaveState(ServiceType.FULL_BACKUP);
5548        if (result.batterySaverEnabled) {
5549            if (DEBUG) Slog.i(TAG, "Deferring scheduled full backups in battery saver mode");
5550            FullBackupJob.schedule(mContext, KeyValueBackupJob.BATCH_INTERVAL);
5551            return false;
5552        }
5553
5554        if (DEBUG_SCHEDULING) {
5555            Slog.i(TAG, "Beginning scheduled full backup operation");
5556        }
5557
5558        // Great; we're able to run full backup jobs now.  See if we have any work to do.
5559        synchronized (mQueueLock) {
5560            if (mRunningFullBackupTask != null) {
5561                Slog.e(TAG, "Backup triggered but one already/still running!");
5562                return false;
5563            }
5564
5565            // At this point we think that we have work to do, but possibly not right now.
5566            // Any exit without actually running backups will also require that we
5567            // reschedule the job.
5568            boolean runBackup = true;
5569            boolean headBusy;
5570
5571            do {
5572                // Recheck each time, because culling due to ineligibility may
5573                // have emptied the queue.
5574                if (mFullBackupQueue.size() == 0) {
5575                    // no work to do so just bow out
5576                    if (DEBUG) {
5577                        Slog.i(TAG, "Backup queue empty; doing nothing");
5578                    }
5579                    runBackup = false;
5580                    break;
5581                }
5582
5583                headBusy = false;
5584
5585                if (!fullBackupAllowable(mTransportManager.getCurrentTransportBinder())) {
5586                    if (MORE_DEBUG) {
5587                        Slog.i(TAG, "Preconditions not met; not running full backup");
5588                    }
5589                    runBackup = false;
5590                    // Typically this means we haven't run a key/value backup yet.  Back off
5591                    // full-backup operations by the key/value job's run interval so that
5592                    // next time we run, we are likely to be able to make progress.
5593                    latency = KeyValueBackupJob.BATCH_INTERVAL;
5594                }
5595
5596                if (runBackup) {
5597                    entry = mFullBackupQueue.get(0);
5598                    long timeSinceRun = now - entry.lastBackup;
5599                    runBackup = (timeSinceRun >= MIN_FULL_BACKUP_INTERVAL);
5600                    if (!runBackup) {
5601                        // It's too early to back up the next thing in the queue, so bow out
5602                        if (MORE_DEBUG) {
5603                            Slog.i(TAG, "Device ready but too early to back up next app");
5604                        }
5605                        // Wait until the next app in the queue falls due for a full data backup
5606                        latency = MIN_FULL_BACKUP_INTERVAL - timeSinceRun;
5607                        break;  // we know we aren't doing work yet, so bail.
5608                    }
5609
5610                    try {
5611                        PackageInfo appInfo = mPackageManager.getPackageInfo(entry.packageName, 0);
5612                        if (!appGetsFullBackup(appInfo)) {
5613                            // The head app isn't supposed to get full-data backups [any more];
5614                            // so we cull it and force a loop around to consider the new head
5615                            // app.
5616                            if (MORE_DEBUG) {
5617                                Slog.i(TAG, "Culling package " + entry.packageName
5618                                        + " in full-backup queue but not eligible");
5619                            }
5620                            mFullBackupQueue.remove(0);
5621                            headBusy = true; // force the while() condition
5622                            continue;
5623                        }
5624
5625                        final int privFlags = appInfo.applicationInfo.privateFlags;
5626                        headBusy = (privFlags & PRIVATE_FLAG_BACKUP_IN_FOREGROUND) == 0
5627                                && mActivityManager.isAppForeground(appInfo.applicationInfo.uid);
5628
5629                        if (headBusy) {
5630                            final long nextEligible = System.currentTimeMillis()
5631                                    + BUSY_BACKOFF_MIN_MILLIS
5632                                    + mTokenGenerator.nextInt(BUSY_BACKOFF_FUZZ);
5633                            if (DEBUG_SCHEDULING) {
5634                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
5635                                Slog.i(TAG, "Full backup time but " + entry.packageName
5636                                        + " is busy; deferring to "
5637                                        + sdf.format(new Date(nextEligible)));
5638                            }
5639                            // This relocates the app's entry from the head of the queue to
5640                            // its order-appropriate position further down, so upon looping
5641                            // a new candidate will be considered at the head.
5642                            enqueueFullBackup(entry.packageName,
5643                                    nextEligible - MIN_FULL_BACKUP_INTERVAL);
5644                        }
5645                    } catch (NameNotFoundException nnf) {
5646                        // So, we think we want to back this up, but it turns out the package
5647                        // in question is no longer installed.  We want to drop it from the
5648                        // queue entirely and move on, but if there's nothing else in the queue
5649                        // we should bail entirely.  headBusy cannot have been set to true yet.
5650                        runBackup = (mFullBackupQueue.size() > 1);
5651                    } catch (RemoteException e) {
5652                        // Cannot happen; the Activity Manager is in the same process
5653                    }
5654                }
5655            } while (headBusy);
5656
5657            if (!runBackup) {
5658                if (DEBUG_SCHEDULING) {
5659                    Slog.i(TAG, "Nothing pending full backup; rescheduling +" + latency);
5660                }
5661                final long deferTime = latency;     // pin for the closure
5662                mBackupHandler.post(new Runnable() {
5663                    @Override public void run() {
5664                        FullBackupJob.schedule(mContext, deferTime);
5665                    }
5666                });
5667                return false;
5668            }
5669
5670            // Okay, the top thing is ready for backup now.  Do it.
5671            mFullBackupQueue.remove(0);
5672            CountDownLatch latch = new CountDownLatch(1);
5673            String[] pkg = new String[] {entry.packageName};
5674            mRunningFullBackupTask = new PerformFullTransportBackupTask(null, pkg, true,
5675                    scheduledJob, latch, null, null, false /* userInitiated */);
5676            // Acquiring wakelock for PerformFullTransportBackupTask before its start.
5677            mWakelock.acquire();
5678            (new Thread(mRunningFullBackupTask)).start();
5679        }
5680
5681        return true;
5682    }
5683
5684    // The job scheduler says our constraints don't hold any more,
5685    // so tear down any ongoing backup task right away.
5686    @Override
5687    public void endFullBackup() {
5688        // offload the mRunningFullBackupTask.handleCancel() call to another thread,
5689        // as we might have to wait for mCancelLock
5690        Runnable endFullBackupRunnable = new Runnable() {
5691            @Override
5692            public void run() {
5693                PerformFullTransportBackupTask pftbt = null;
5694                synchronized (mQueueLock) {
5695                    if (mRunningFullBackupTask != null) {
5696                        pftbt = mRunningFullBackupTask;
5697                    }
5698                }
5699                if (pftbt != null) {
5700                    if (DEBUG_SCHEDULING) {
5701                        Slog.i(TAG, "Telling running backup to stop");
5702                    }
5703                    pftbt.handleCancel(true);
5704                }
5705            }
5706        };
5707        new Thread(endFullBackupRunnable, "end-full-backup").start();
5708    }
5709
5710    // ----- Restore infrastructure -----
5711
5712    abstract class RestoreEngine {
5713        static final String TAG = "RestoreEngine";
5714
5715        public static final int SUCCESS = 0;
5716        public static final int TARGET_FAILURE = -2;
5717        public static final int TRANSPORT_FAILURE = -3;
5718
5719        private AtomicBoolean mRunning = new AtomicBoolean(false);
5720        private AtomicInteger mResult = new AtomicInteger(SUCCESS);
5721
5722        public boolean isRunning() {
5723            return mRunning.get();
5724        }
5725
5726        public void setRunning(boolean stillRunning) {
5727            synchronized (mRunning) {
5728                mRunning.set(stillRunning);
5729                mRunning.notifyAll();
5730            }
5731        }
5732
5733        public int waitForResult() {
5734            synchronized (mRunning) {
5735                while (isRunning()) {
5736                    try {
5737                        mRunning.wait();
5738                    } catch (InterruptedException e) {}
5739                }
5740            }
5741            return getResult();
5742        }
5743
5744        public int getResult() {
5745            return mResult.get();
5746        }
5747
5748        public void setResult(int result) {
5749            mResult.set(result);
5750        }
5751
5752        // TODO: abstract restore state and APIs
5753    }
5754
5755    // ----- Full restore from a file/socket -----
5756
5757    enum RestorePolicy {
5758        IGNORE,
5759        ACCEPT,
5760        ACCEPT_IF_APK
5761    }
5762
5763    // Full restore engine, used by both adb restore and transport-based full restore
5764    class FullRestoreEngine extends RestoreEngine {
5765        // Task in charge of monitoring timeouts
5766        BackupRestoreTask mMonitorTask;
5767
5768        // Dedicated observer, if any
5769        IFullBackupRestoreObserver mObserver;
5770
5771        IBackupManagerMonitor mMonitor;
5772
5773        // Where we're delivering the file data as we go
5774        IBackupAgent mAgent;
5775
5776        // Are we permitted to only deliver a specific package's metadata?
5777        PackageInfo mOnlyPackage;
5778
5779        boolean mAllowApks;
5780        boolean mAllowObbs;
5781
5782        // Which package are we currently handling data for?
5783        String mAgentPackage;
5784
5785        // Info for working with the target app process
5786        ApplicationInfo mTargetApp;
5787
5788        // Machinery for restoring OBBs
5789        FullBackupObbConnection mObbConnection = null;
5790
5791        // possible handling states for a given package in the restore dataset
5792        final HashMap<String, RestorePolicy> mPackagePolicies
5793                = new HashMap<String, RestorePolicy>();
5794
5795        // installer package names for each encountered app, derived from the manifests
5796        final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
5797
5798        // Signatures for a given package found in its manifest file
5799        final HashMap<String, Signature[]> mManifestSignatures
5800                = new HashMap<String, Signature[]>();
5801
5802        // Packages we've already wiped data on when restoring their first file
5803        final HashSet<String> mClearedPackages = new HashSet<String>();
5804
5805        // How much data have we moved?
5806        long mBytes;
5807
5808        // Working buffer
5809        byte[] mBuffer;
5810
5811        // Pipes for moving data
5812        ParcelFileDescriptor[] mPipes = null;
5813
5814        // Widget blob to be restored out-of-band
5815        byte[] mWidgetData = null;
5816
5817        private final int mEphemeralOpToken;
5818
5819        // Runner that can be placed in a separate thread to do in-process
5820        // invocations of the full restore API asynchronously. Used by adb restore.
5821        class RestoreFileRunnable implements Runnable {
5822            IBackupAgent mAgent;
5823            FileMetadata mInfo;
5824            ParcelFileDescriptor mSocket;
5825            int mToken;
5826
5827            RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
5828                    ParcelFileDescriptor socket, int token) throws IOException {
5829                mAgent = agent;
5830                mInfo = info;
5831                mToken = token;
5832
5833                // This class is used strictly for process-local binder invocations.  The
5834                // semantics of ParcelFileDescriptor differ in this case; in particular, we
5835                // do not automatically get a 'dup'ed descriptor that we can can continue
5836                // to use asynchronously from the caller.  So, we make sure to dup it ourselves
5837                // before proceeding to do the restore.
5838                mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
5839            }
5840
5841            @Override
5842            public void run() {
5843                try {
5844                    mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
5845                            mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
5846                            mToken, mBackupManagerBinder);
5847                } catch (RemoteException e) {
5848                    // never happens; this is used strictly for local binder calls
5849                }
5850            }
5851        }
5852
5853        public FullRestoreEngine(BackupRestoreTask monitorTask, IFullBackupRestoreObserver observer,
5854                IBackupManagerMonitor monitor, PackageInfo onlyPackage, boolean allowApks,
5855                boolean allowObbs, int ephemeralOpToken) {
5856            mEphemeralOpToken = ephemeralOpToken;
5857            mMonitorTask = monitorTask;
5858            mObserver = observer;
5859            mMonitor = monitor;
5860            mOnlyPackage = onlyPackage;
5861            mAllowApks = allowApks;
5862            mAllowObbs = allowObbs;
5863            mBuffer = new byte[32 * 1024];
5864            mBytes = 0;
5865        }
5866
5867        public IBackupAgent getAgent() {
5868            return mAgent;
5869        }
5870
5871        public byte[] getWidgetData() {
5872            return mWidgetData;
5873        }
5874
5875        public boolean restoreOneFile(InputStream instream, boolean mustKillAgent) {
5876            if (!isRunning()) {
5877                Slog.w(TAG, "Restore engine used after halting");
5878                return false;
5879            }
5880
5881            FileMetadata info;
5882            try {
5883                if (MORE_DEBUG) {
5884                    Slog.v(TAG, "Reading tar header for restoring file");
5885                }
5886                info = readTarHeaders(instream);
5887                if (info != null) {
5888                    if (MORE_DEBUG) {
5889                        dumpFileMetadata(info);
5890                    }
5891
5892                    final String pkg = info.packageName;
5893                    if (!pkg.equals(mAgentPackage)) {
5894                        // In the single-package case, it's a semantic error to expect
5895                        // one app's data but see a different app's on the wire
5896                        if (mOnlyPackage != null) {
5897                            if (!pkg.equals(mOnlyPackage.packageName)) {
5898                                Slog.w(TAG, "Expected data for " + mOnlyPackage
5899                                        + " but saw " + pkg);
5900                                setResult(RestoreEngine.TRANSPORT_FAILURE);
5901                                setRunning(false);
5902                                return false;
5903                            }
5904                        }
5905
5906                        // okay, change in package; set up our various
5907                        // bookkeeping if we haven't seen it yet
5908                        if (!mPackagePolicies.containsKey(pkg)) {
5909                            mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5910                        }
5911
5912                        // Clean up the previous agent relationship if necessary,
5913                        // and let the observer know we're considering a new app.
5914                        if (mAgent != null) {
5915                            if (DEBUG) Slog.d(TAG, "Saw new package; finalizing old one");
5916                            // Now we're really done
5917                            tearDownPipes();
5918                            tearDownAgent(mTargetApp);
5919                            mTargetApp = null;
5920                            mAgentPackage = null;
5921                        }
5922                    }
5923
5924                    if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
5925                        mPackagePolicies.put(pkg, readAppManifest(info, instream));
5926                        mPackageInstallers.put(pkg, info.installerPackageName);
5927                        // We've read only the manifest content itself at this point,
5928                        // so consume the footer before looping around to the next
5929                        // input file
5930                        skipTarPadding(info.size, instream);
5931                        sendOnRestorePackage(pkg);
5932                    } else if (info.path.equals(BACKUP_METADATA_FILENAME)) {
5933                        // Metadata blobs!
5934                        readMetadata(info, instream);
5935                        skipTarPadding(info.size, instream);
5936                    } else {
5937                        // Non-manifest, so it's actual file data.  Is this a package
5938                        // we're ignoring?
5939                        boolean okay = true;
5940                        RestorePolicy policy = mPackagePolicies.get(pkg);
5941                        switch (policy) {
5942                            case IGNORE:
5943                                okay = false;
5944                                break;
5945
5946                            case ACCEPT_IF_APK:
5947                                // If we're in accept-if-apk state, then the first file we
5948                                // see MUST be the apk.
5949                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
5950                                    if (DEBUG) Slog.d(TAG, "APK file; installing");
5951                                    // Try to install the app.
5952                                    String installerName = mPackageInstallers.get(pkg);
5953                                    okay = installApk(info, installerName, instream);
5954                                    // good to go; promote to ACCEPT
5955                                    mPackagePolicies.put(pkg, (okay)
5956                                            ? RestorePolicy.ACCEPT
5957                                                    : RestorePolicy.IGNORE);
5958                                    // At this point we've consumed this file entry
5959                                    // ourselves, so just strip the tar footer and
5960                                    // go on to the next file in the input stream
5961                                    skipTarPadding(info.size, instream);
5962                                    return true;
5963                                } else {
5964                                    // File data before (or without) the apk.  We can't
5965                                    // handle it coherently in this case so ignore it.
5966                                    mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5967                                    okay = false;
5968                                }
5969                                break;
5970
5971                            case ACCEPT:
5972                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
5973                                    if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
5974                                    // we can take the data without the apk, so we
5975                                    // *want* to do so.  skip the apk by declaring this
5976                                    // one file not-okay without changing the restore
5977                                    // policy for the package.
5978                                    okay = false;
5979                                }
5980                                break;
5981
5982                            default:
5983                                // Something has gone dreadfully wrong when determining
5984                                // the restore policy from the manifest.  Ignore the
5985                                // rest of this package's data.
5986                                Slog.e(TAG, "Invalid policy from manifest");
5987                                okay = false;
5988                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5989                                break;
5990                        }
5991
5992                        // Is it a *file* we need to drop?
5993                        if (!isRestorableFile(info)) {
5994                            okay = false;
5995                        }
5996
5997                        // If the policy is satisfied, go ahead and set up to pipe the
5998                        // data to the agent.
5999                        if (MORE_DEBUG && okay && mAgent != null) {
6000                            Slog.i(TAG, "Reusing existing agent instance");
6001                        }
6002                        if (okay && mAgent == null) {
6003                            if (MORE_DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
6004
6005                            try {
6006                                mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
6007
6008                                // If we haven't sent any data to this app yet, we probably
6009                                // need to clear it first.  Check that.
6010                                if (!mClearedPackages.contains(pkg)) {
6011                                    // apps with their own backup agents are
6012                                    // responsible for coherently managing a full
6013                                    // restore.
6014                                    if (mTargetApp.backupAgentName == null) {
6015                                        if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
6016                                        clearApplicationDataSynchronous(pkg);
6017                                    } else {
6018                                        if (MORE_DEBUG) Slog.d(TAG, "backup agent ("
6019                                                + mTargetApp.backupAgentName + ") => no clear");
6020                                    }
6021                                    mClearedPackages.add(pkg);
6022                                } else {
6023                                    if (MORE_DEBUG) {
6024                                        Slog.d(TAG, "We've initialized this app already; no clear required");
6025                                    }
6026                                }
6027
6028                                // All set; now set up the IPC and launch the agent
6029                                setUpPipes();
6030                                mAgent = bindToAgentSynchronous(mTargetApp,
6031                                        ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL);
6032                                mAgentPackage = pkg;
6033                            } catch (IOException e) {
6034                                // fall through to error handling
6035                            } catch (NameNotFoundException e) {
6036                                // fall through to error handling
6037                            }
6038
6039                            if (mAgent == null) {
6040                                Slog.e(TAG, "Unable to create agent for " + pkg);
6041                                okay = false;
6042                                tearDownPipes();
6043                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
6044                            }
6045                        }
6046
6047                        // Sanity check: make sure we never give data to the wrong app.  This
6048                        // should never happen but a little paranoia here won't go amiss.
6049                        if (okay && !pkg.equals(mAgentPackage)) {
6050                            Slog.e(TAG, "Restoring data for " + pkg
6051                                    + " but agent is for " + mAgentPackage);
6052                            okay = false;
6053                        }
6054
6055                        // At this point we have an agent ready to handle the full
6056                        // restore data as well as a pipe for sending data to
6057                        // that agent.  Tell the agent to start reading from the
6058                        // pipe.
6059                        if (okay) {
6060                            boolean agentSuccess = true;
6061                            long toCopy = info.size;
6062                            try {
6063                                prepareOperationTimeout(mEphemeralOpToken,
6064                                        TIMEOUT_FULL_BACKUP_INTERVAL, mMonitorTask,
6065                                        OP_TYPE_RESTORE_WAIT);
6066
6067                                if (info.domain.equals(FullBackup.OBB_TREE_TOKEN)) {
6068                                    if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
6069                                            + " : " + info.path);
6070                                    mObbConnection.restoreObbFile(pkg, mPipes[0],
6071                                            info.size, info.type, info.path, info.mode,
6072                                            info.mtime, mEphemeralOpToken, mBackupManagerBinder);
6073                                } else {
6074                                    if (MORE_DEBUG) Slog.d(TAG, "Invoking agent to restore file "
6075                                            + info.path);
6076                                    // fire up the app's agent listening on the socket.  If
6077                                    // the agent is running in the system process we can't
6078                                    // just invoke it asynchronously, so we provide a thread
6079                                    // for it here.
6080                                    if (mTargetApp.processName.equals("system")) {
6081                                        Slog.d(TAG, "system process agent - spinning a thread");
6082                                        RestoreFileRunnable runner = new RestoreFileRunnable(
6083                                                mAgent, info, mPipes[0], mEphemeralOpToken);
6084                                        new Thread(runner, "restore-sys-runner").start();
6085                                    } else {
6086                                        mAgent.doRestoreFile(mPipes[0], info.size, info.type,
6087                                                info.domain, info.path, info.mode, info.mtime,
6088                                                mEphemeralOpToken, mBackupManagerBinder);
6089                                    }
6090                                }
6091                            } catch (IOException e) {
6092                                // couldn't dup the socket for a process-local restore
6093                                Slog.d(TAG, "Couldn't establish restore");
6094                                agentSuccess = false;
6095                                okay = false;
6096                            } catch (RemoteException e) {
6097                                // whoops, remote entity went away.  We'll eat the content
6098                                // ourselves, then, and not copy it over.
6099                                Slog.e(TAG, "Agent crashed during full restore");
6100                                agentSuccess = false;
6101                                okay = false;
6102                            }
6103
6104                            // Copy over the data if the agent is still good
6105                            if (okay) {
6106                                if (MORE_DEBUG) {
6107                                    Slog.v(TAG, "  copying to restore agent: "
6108                                            + toCopy + " bytes");
6109                                }
6110                                boolean pipeOkay = true;
6111                                FileOutputStream pipe = new FileOutputStream(
6112                                        mPipes[1].getFileDescriptor());
6113                                while (toCopy > 0) {
6114                                    int toRead = (toCopy > mBuffer.length)
6115                                            ? mBuffer.length : (int)toCopy;
6116                                    int nRead = instream.read(mBuffer, 0, toRead);
6117                                    if (nRead >= 0) mBytes += nRead;
6118                                    if (nRead <= 0) break;
6119                                    toCopy -= nRead;
6120
6121                                    // send it to the output pipe as long as things
6122                                    // are still good
6123                                    if (pipeOkay) {
6124                                        try {
6125                                            pipe.write(mBuffer, 0, nRead);
6126                                        } catch (IOException e) {
6127                                            Slog.e(TAG, "Failed to write to restore pipe: "
6128                                                    + e.getMessage());
6129                                            pipeOkay = false;
6130                                        }
6131                                    }
6132                                }
6133
6134                                // done sending that file!  Now we just need to consume
6135                                // the delta from info.size to the end of block.
6136                                skipTarPadding(info.size, instream);
6137
6138                                // and now that we've sent it all, wait for the remote
6139                                // side to acknowledge receipt
6140                                agentSuccess = waitUntilOperationComplete(mEphemeralOpToken);
6141                            }
6142
6143                            // okay, if the remote end failed at any point, deal with
6144                            // it by ignoring the rest of the restore on it
6145                            if (!agentSuccess) {
6146                                Slog.w(TAG, "Agent failure; ending restore");
6147                                mBackupHandler.removeMessages(MSG_RESTORE_OPERATION_TIMEOUT);
6148                                tearDownPipes();
6149                                tearDownAgent(mTargetApp);
6150                                mAgent = null;
6151                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
6152
6153                                // If this was a single-package restore, we halt immediately
6154                                // with an agent error under these circumstances
6155                                if (mOnlyPackage != null) {
6156                                    setResult(RestoreEngine.TARGET_FAILURE);
6157                                    setRunning(false);
6158                                    return false;
6159                                }
6160                            }
6161                        }
6162
6163                        // Problems setting up the agent communication, an explicitly
6164                        // dropped file, or an already-ignored package: skip to the
6165                        // next stream entry by reading and discarding this file.
6166                        if (!okay) {
6167                            if (MORE_DEBUG) Slog.d(TAG, "[discarding file content]");
6168                            long bytesToConsume = (info.size + 511) & ~511;
6169                            while (bytesToConsume > 0) {
6170                                int toRead = (bytesToConsume > mBuffer.length)
6171                                        ? mBuffer.length : (int)bytesToConsume;
6172                                long nRead = instream.read(mBuffer, 0, toRead);
6173                                if (nRead >= 0) mBytes += nRead;
6174                                if (nRead <= 0) break;
6175                                bytesToConsume -= nRead;
6176                            }
6177                        }
6178                    }
6179                }
6180            } catch (IOException e) {
6181                if (DEBUG) Slog.w(TAG, "io exception on restore socket read: " + e.getMessage());
6182                setResult(RestoreEngine.TRANSPORT_FAILURE);
6183                info = null;
6184            }
6185
6186            // If we got here we're either running smoothly or we've finished
6187            if (info == null) {
6188                if (MORE_DEBUG) {
6189                    Slog.i(TAG, "No [more] data for this package; tearing down");
6190                }
6191                tearDownPipes();
6192                setRunning(false);
6193                if (mustKillAgent) {
6194                    tearDownAgent(mTargetApp);
6195                }
6196            }
6197            return (info != null);
6198        }
6199
6200        void setUpPipes() throws IOException {
6201            mPipes = ParcelFileDescriptor.createPipe();
6202        }
6203
6204        void tearDownPipes() {
6205            // Teardown might arise from the inline restore processing or from the asynchronous
6206            // timeout mechanism, and these might race.  Make sure we don't try to close and
6207            // null out the pipes twice.
6208            synchronized (this) {
6209                if (mPipes != null) {
6210                    try {
6211                        mPipes[0].close();
6212                        mPipes[0] = null;
6213                        mPipes[1].close();
6214                        mPipes[1] = null;
6215                    } catch (IOException e) {
6216                        Slog.w(TAG, "Couldn't close agent pipes", e);
6217                    }
6218                    mPipes = null;
6219                }
6220            }
6221        }
6222
6223        void tearDownAgent(ApplicationInfo app) {
6224            if (mAgent != null) {
6225                tearDownAgentAndKill(app);
6226                mAgent = null;
6227            }
6228        }
6229
6230        void handleTimeout() {
6231            tearDownPipes();
6232            setResult(RestoreEngine.TARGET_FAILURE);
6233            setRunning(false);
6234        }
6235
6236        class RestoreInstallObserver extends PackageInstallObserver {
6237            final AtomicBoolean mDone = new AtomicBoolean();
6238            String mPackageName;
6239            int mResult;
6240
6241            public void reset() {
6242                synchronized (mDone) {
6243                    mDone.set(false);
6244                }
6245            }
6246
6247            public void waitForCompletion() {
6248                synchronized (mDone) {
6249                    while (mDone.get() == false) {
6250                        try {
6251                            mDone.wait();
6252                        } catch (InterruptedException e) { }
6253                    }
6254                }
6255            }
6256
6257            int getResult() {
6258                return mResult;
6259            }
6260
6261            @Override
6262            public void onPackageInstalled(String packageName, int returnCode,
6263                    String msg, Bundle extras) {
6264                synchronized (mDone) {
6265                    mResult = returnCode;
6266                    mPackageName = packageName;
6267                    mDone.set(true);
6268                    mDone.notifyAll();
6269                }
6270            }
6271        }
6272
6273        class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
6274            final AtomicBoolean mDone = new AtomicBoolean();
6275            int mResult;
6276
6277            public void reset() {
6278                synchronized (mDone) {
6279                    mDone.set(false);
6280                }
6281            }
6282
6283            public void waitForCompletion() {
6284                synchronized (mDone) {
6285                    while (mDone.get() == false) {
6286                        try {
6287                            mDone.wait();
6288                        } catch (InterruptedException e) { }
6289                    }
6290                }
6291            }
6292
6293            @Override
6294            public void packageDeleted(String packageName, int returnCode) throws RemoteException {
6295                synchronized (mDone) {
6296                    mResult = returnCode;
6297                    mDone.set(true);
6298                    mDone.notifyAll();
6299                }
6300            }
6301        }
6302
6303        final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
6304        final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
6305
6306        boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
6307            boolean okay = true;
6308
6309            if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
6310
6311            // The file content is an .apk file.  Copy it out to a staging location and
6312            // attempt to install it.
6313            File apkFile = new File(mDataDir, info.packageName);
6314            try {
6315                FileOutputStream apkStream = new FileOutputStream(apkFile);
6316                byte[] buffer = new byte[32 * 1024];
6317                long size = info.size;
6318                while (size > 0) {
6319                    long toRead = (buffer.length < size) ? buffer.length : size;
6320                    int didRead = instream.read(buffer, 0, (int)toRead);
6321                    if (didRead >= 0) mBytes += didRead;
6322                    apkStream.write(buffer, 0, didRead);
6323                    size -= didRead;
6324                }
6325                apkStream.close();
6326
6327                // make sure the installer can read it
6328                apkFile.setReadable(true, false);
6329
6330                // Now install it
6331                Uri packageUri = Uri.fromFile(apkFile);
6332                mInstallObserver.reset();
6333                mPackageManager.installPackage(packageUri, mInstallObserver,
6334                        PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
6335                        installerPackage);
6336                mInstallObserver.waitForCompletion();
6337
6338                if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
6339                    // The only time we continue to accept install of data even if the
6340                    // apk install failed is if we had already determined that we could
6341                    // accept the data regardless.
6342                    if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
6343                        okay = false;
6344                    }
6345                } else {
6346                    // Okay, the install succeeded.  Make sure it was the right app.
6347                    boolean uninstall = false;
6348                    if (!mInstallObserver.mPackageName.equals(info.packageName)) {
6349                        Slog.w(TAG, "Restore stream claimed to include apk for "
6350                                + info.packageName + " but apk was really "
6351                                + mInstallObserver.mPackageName);
6352                        // delete the package we just put in place; it might be fraudulent
6353                        okay = false;
6354                        uninstall = true;
6355                    } else {
6356                        try {
6357                            PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
6358                                    PackageManager.GET_SIGNATURES);
6359                            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
6360                                Slog.w(TAG, "Restore stream contains apk of package "
6361                                        + info.packageName + " but it disallows backup/restore");
6362                                okay = false;
6363                            } else {
6364                                // So far so good -- do the signatures match the manifest?
6365                                Signature[] sigs = mManifestSignatures.get(info.packageName);
6366                                if (signaturesMatch(sigs, pkg)) {
6367                                    // If this is a system-uid app without a declared backup agent,
6368                                    // don't restore any of the file data.
6369                                    if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
6370                                            && (pkg.applicationInfo.backupAgentName == null)) {
6371                                        Slog.w(TAG, "Installed app " + info.packageName
6372                                                + " has restricted uid and no agent");
6373                                        okay = false;
6374                                    }
6375                                } else {
6376                                    Slog.w(TAG, "Installed app " + info.packageName
6377                                            + " signatures do not match restore manifest");
6378                                    okay = false;
6379                                    uninstall = true;
6380                                }
6381                            }
6382                        } catch (NameNotFoundException e) {
6383                            Slog.w(TAG, "Install of package " + info.packageName
6384                                    + " succeeded but now not found");
6385                            okay = false;
6386                        }
6387                    }
6388
6389                    // If we're not okay at this point, we need to delete the package
6390                    // that we just installed.
6391                    if (uninstall) {
6392                        mDeleteObserver.reset();
6393                        mPackageManager.deletePackage(mInstallObserver.mPackageName,
6394                                mDeleteObserver, 0);
6395                        mDeleteObserver.waitForCompletion();
6396                    }
6397                }
6398            } catch (IOException e) {
6399                Slog.e(TAG, "Unable to transcribe restored apk for install");
6400                okay = false;
6401            } finally {
6402                apkFile.delete();
6403            }
6404
6405            return okay;
6406        }
6407
6408        // Given an actual file content size, consume the post-content padding mandated
6409        // by the tar format.
6410        void skipTarPadding(long size, InputStream instream) throws IOException {
6411            long partial = (size + 512) % 512;
6412            if (partial > 0) {
6413                final int needed = 512 - (int)partial;
6414                if (MORE_DEBUG) {
6415                    Slog.i(TAG, "Skipping tar padding: " + needed + " bytes");
6416                }
6417                byte[] buffer = new byte[needed];
6418                if (readExactly(instream, buffer, 0, needed) == needed) {
6419                    mBytes += needed;
6420                } else throw new IOException("Unexpected EOF in padding");
6421            }
6422        }
6423
6424        // Read a widget metadata file, returning the restored blob
6425        void readMetadata(FileMetadata info, InputStream instream) throws IOException {
6426            // Fail on suspiciously large widget dump files
6427            if (info.size > 64 * 1024) {
6428                throw new IOException("Metadata too big; corrupt? size=" + info.size);
6429            }
6430
6431            byte[] buffer = new byte[(int) info.size];
6432            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
6433                mBytes += info.size;
6434            } else throw new IOException("Unexpected EOF in widget data");
6435
6436            String[] str = new String[1];
6437            int offset = extractLine(buffer, 0, str);
6438            int version = Integer.parseInt(str[0]);
6439            if (version == BACKUP_MANIFEST_VERSION) {
6440                offset = extractLine(buffer, offset, str);
6441                final String pkg = str[0];
6442                if (info.packageName.equals(pkg)) {
6443                    // Data checks out -- the rest of the buffer is a concatenation of
6444                    // binary blobs as described in the comment at writeAppWidgetData()
6445                    ByteArrayInputStream bin = new ByteArrayInputStream(buffer,
6446                            offset, buffer.length - offset);
6447                    DataInputStream in = new DataInputStream(bin);
6448                    while (bin.available() > 0) {
6449                        int token = in.readInt();
6450                        int size = in.readInt();
6451                        if (size > 64 * 1024) {
6452                            throw new IOException("Datum "
6453                                    + Integer.toHexString(token)
6454                                    + " too big; corrupt? size=" + info.size);
6455                        }
6456                        switch (token) {
6457                            case BACKUP_WIDGET_METADATA_TOKEN:
6458                            {
6459                                if (MORE_DEBUG) {
6460                                    Slog.i(TAG, "Got widget metadata for " + info.packageName);
6461                                }
6462                                mWidgetData = new byte[size];
6463                                in.read(mWidgetData);
6464                                break;
6465                            }
6466                            default:
6467                            {
6468                                if (DEBUG) {
6469                                    Slog.i(TAG, "Ignoring metadata blob "
6470                                            + Integer.toHexString(token)
6471                                            + " for " + info.packageName);
6472                                }
6473                                in.skipBytes(size);
6474                                break;
6475                            }
6476                        }
6477                    }
6478                } else {
6479                    Slog.w(TAG, "Metadata mismatch: package " + info.packageName
6480                            + " but widget data for " + pkg);
6481
6482                    Bundle monitoringExtras = putMonitoringExtra(null,
6483                            EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName);
6484                    monitoringExtras = putMonitoringExtra(monitoringExtras,
6485                            BackupManagerMonitor.EXTRA_LOG_WIDGET_PACKAGE_NAME, pkg);
6486                    mMonitor = monitorEvent(mMonitor,
6487                            BackupManagerMonitor.LOG_EVENT_ID_WIDGET_METADATA_MISMATCH,
6488                            null,
6489                            LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6490                            monitoringExtras);
6491                }
6492            } else {
6493                Slog.w(TAG, "Unsupported metadata version " + version);
6494
6495                Bundle monitoringExtras = putMonitoringExtra(null, EXTRA_LOG_EVENT_PACKAGE_NAME,
6496                        info.packageName);
6497                monitoringExtras = putMonitoringExtra(monitoringExtras,
6498                        EXTRA_LOG_EVENT_PACKAGE_VERSION, version);
6499                mMonitor = monitorEvent(mMonitor,
6500                        BackupManagerMonitor.LOG_EVENT_ID_WIDGET_UNKNOWN_VERSION,
6501                        null,
6502                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6503                        monitoringExtras);
6504            }
6505        }
6506
6507        // Returns a policy constant
6508        RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
6509                throws IOException {
6510            // Fail on suspiciously large manifest files
6511            if (info.size > 64 * 1024) {
6512                throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
6513            }
6514
6515            byte[] buffer = new byte[(int) info.size];
6516            if (MORE_DEBUG) {
6517                Slog.i(TAG, "   readAppManifest() looking for " + info.size + " bytes, "
6518                        + mBytes + " already consumed");
6519            }
6520            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
6521                mBytes += info.size;
6522            } else throw new IOException("Unexpected EOF in manifest");
6523
6524            RestorePolicy policy = RestorePolicy.IGNORE;
6525            String[] str = new String[1];
6526            int offset = 0;
6527
6528            try {
6529                offset = extractLine(buffer, offset, str);
6530                int version = Integer.parseInt(str[0]);
6531                if (version == BACKUP_MANIFEST_VERSION) {
6532                    offset = extractLine(buffer, offset, str);
6533                    String manifestPackage = str[0];
6534                    // TODO: handle <original-package>
6535                    if (manifestPackage.equals(info.packageName)) {
6536                        offset = extractLine(buffer, offset, str);
6537                        version = Integer.parseInt(str[0]);  // app version
6538                        offset = extractLine(buffer, offset, str);
6539                        // This is the platform version, which we don't use, but we parse it
6540                        // as a safety against corruption in the manifest.
6541                        Integer.parseInt(str[0]);
6542                        offset = extractLine(buffer, offset, str);
6543                        info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
6544                        offset = extractLine(buffer, offset, str);
6545                        boolean hasApk = str[0].equals("1");
6546                        offset = extractLine(buffer, offset, str);
6547                        int numSigs = Integer.parseInt(str[0]);
6548                        if (numSigs > 0) {
6549                            Signature[] sigs = new Signature[numSigs];
6550                            for (int i = 0; i < numSigs; i++) {
6551                                offset = extractLine(buffer, offset, str);
6552                                sigs[i] = new Signature(str[0]);
6553                            }
6554                            mManifestSignatures.put(info.packageName, sigs);
6555
6556                            // Okay, got the manifest info we need...
6557                            try {
6558                                PackageInfo pkgInfo = mPackageManager.getPackageInfo(
6559                                        info.packageName, PackageManager.GET_SIGNATURES);
6560                                // Fall through to IGNORE if the app explicitly disallows backup
6561                                final int flags = pkgInfo.applicationInfo.flags;
6562                                if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
6563                                    // Restore system-uid-space packages only if they have
6564                                    // defined a custom backup agent
6565                                    if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
6566                                            || (pkgInfo.applicationInfo.backupAgentName != null)) {
6567                                        // Verify signatures against any installed version; if they
6568                                        // don't match, then we fall though and ignore the data.  The
6569                                        // signatureMatch() method explicitly ignores the signature
6570                                        // check for packages installed on the system partition, because
6571                                        // such packages are signed with the platform cert instead of
6572                                        // the app developer's cert, so they're different on every
6573                                        // device.
6574                                        if (signaturesMatch(sigs, pkgInfo)) {
6575                                            if ((pkgInfo.applicationInfo.flags
6576                                                    & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) != 0) {
6577                                                Slog.i(TAG, "Package has restoreAnyVersion; taking data");
6578                                                mMonitor = monitorEvent(mMonitor,
6579                                                        LOG_EVENT_ID_RESTORE_ANY_VERSION,
6580                                                        pkgInfo,
6581                                                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6582                                                        null);
6583                                                policy = RestorePolicy.ACCEPT;
6584                                            } else if (pkgInfo.versionCode >= version) {
6585                                                Slog.i(TAG, "Sig + version match; taking data");
6586                                                policy = RestorePolicy.ACCEPT;
6587                                                mMonitor = monitorEvent(mMonitor,
6588                                                        LOG_EVENT_ID_VERSIONS_MATCH,
6589                                                        pkgInfo,
6590                                                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6591                                                        null);
6592                                            } else {
6593                                                // The data is from a newer version of the app than
6594                                                // is presently installed.  That means we can only
6595                                                // use it if the matching apk is also supplied.
6596                                                if (mAllowApks) {
6597                                                    Slog.i(TAG, "Data version " + version
6598                                                            + " is newer than installed version "
6599                                                            + pkgInfo.versionCode
6600                                                            + " - requiring apk");
6601                                                    policy = RestorePolicy.ACCEPT_IF_APK;
6602                                                } else {
6603                                                    Slog.i(TAG, "Data requires newer version "
6604                                                            + version + "; ignoring");
6605                                                    mMonitor = monitorEvent(mMonitor,
6606                                                            LOG_EVENT_ID_VERSION_OF_BACKUP_OLDER,
6607                                                            pkgInfo,
6608                                                            LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6609                                                            putMonitoringExtra(null,
6610                                                                    EXTRA_LOG_OLD_VERSION,
6611                                                                    version));
6612
6613                                                    policy = RestorePolicy.IGNORE;
6614                                                }
6615                                            }
6616                                        } else {
6617                                            Slog.w(TAG, "Restore manifest signatures do not match "
6618                                                    + "installed application for " + info.packageName);
6619                                            mMonitor = monitorEvent(mMonitor,
6620                                                    LOG_EVENT_ID_FULL_RESTORE_SIGNATURE_MISMATCH,
6621                                                    pkgInfo,
6622                                                    LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6623                                                    null);
6624                                        }
6625                                    } else {
6626                                        Slog.w(TAG, "Package " + info.packageName
6627                                                + " is system level with no agent");
6628                                        mMonitor = monitorEvent(mMonitor,
6629                                                LOG_EVENT_ID_SYSTEM_APP_NO_AGENT,
6630                                                pkgInfo,
6631                                                LOG_EVENT_CATEGORY_AGENT,
6632                                                null);
6633                                    }
6634                                } else {
6635                                    if (DEBUG) Slog.i(TAG, "Restore manifest from "
6636                                            + info.packageName + " but allowBackup=false");
6637                                    mMonitor = monitorEvent(mMonitor,
6638                                            LOG_EVENT_ID_FULL_RESTORE_ALLOW_BACKUP_FALSE,
6639                                            pkgInfo,
6640                                            LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6641                                            null);
6642                                }
6643                            } catch (NameNotFoundException e) {
6644                                // Okay, the target app isn't installed.  We can process
6645                                // the restore properly only if the dataset provides the
6646                                // apk file and we can successfully install it.
6647                                if (mAllowApks) {
6648                                    if (DEBUG) Slog.i(TAG, "Package " + info.packageName
6649                                            + " not installed; requiring apk in dataset");
6650                                    policy = RestorePolicy.ACCEPT_IF_APK;
6651                                } else {
6652                                    policy = RestorePolicy.IGNORE;
6653                                }
6654                                Bundle monitoringExtras = putMonitoringExtra(null,
6655                                        EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName);
6656                                monitoringExtras = putMonitoringExtra(monitoringExtras,
6657                                        EXTRA_LOG_POLICY_ALLOW_APKS, mAllowApks);
6658                                mMonitor = monitorEvent(mMonitor,
6659                                        LOG_EVENT_ID_APK_NOT_INSTALLED,
6660                                        null,
6661                                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6662                                        monitoringExtras);
6663                            }
6664
6665                            if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
6666                                Slog.i(TAG, "Cannot restore package " + info.packageName
6667                                        + " without the matching .apk");
6668                                mMonitor = monitorEvent(mMonitor,
6669                                        LOG_EVENT_ID_CANNOT_RESTORE_WITHOUT_APK,
6670                                        null,
6671                                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6672                                        putMonitoringExtra(null,
6673                                                EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName));
6674                            }
6675                        } else {
6676                            Slog.i(TAG, "Missing signature on backed-up package "
6677                                    + info.packageName);
6678                            mMonitor = monitorEvent(mMonitor,
6679                                    LOG_EVENT_ID_MISSING_SIGNATURE,
6680                                    null,
6681                                    LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6682                                    putMonitoringExtra(null,
6683                                            EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName));
6684                        }
6685                    } else {
6686                        Slog.i(TAG, "Expected package " + info.packageName
6687                                + " but restore manifest claims " + manifestPackage);
6688                        Bundle monitoringExtras = putMonitoringExtra(null,
6689                                EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName);
6690                        monitoringExtras = putMonitoringExtra(monitoringExtras,
6691                                EXTRA_LOG_MANIFEST_PACKAGE_NAME, manifestPackage);
6692                        mMonitor = monitorEvent(mMonitor,
6693                                LOG_EVENT_ID_EXPECTED_DIFFERENT_PACKAGE,
6694                                null,
6695                                LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6696                                monitoringExtras);
6697                    }
6698                } else {
6699                    Slog.i(TAG, "Unknown restore manifest version " + version
6700                            + " for package " + info.packageName);
6701                    Bundle monitoringExtras = putMonitoringExtra(null,
6702                            EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName);
6703                    monitoringExtras = putMonitoringExtra(monitoringExtras,
6704                            EXTRA_LOG_EVENT_PACKAGE_VERSION, version);
6705                    mMonitor = monitorEvent(mMonitor,
6706                            BackupManagerMonitor.LOG_EVENT_ID_UNKNOWN_VERSION,
6707                            null,
6708                            LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6709                            monitoringExtras);
6710
6711                }
6712            } catch (NumberFormatException e) {
6713                Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
6714                mMonitor = monitorEvent(mMonitor,
6715                        BackupManagerMonitor.LOG_EVENT_ID_CORRUPT_MANIFEST,
6716                        null,
6717                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6718                        putMonitoringExtra(null, EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName));
6719            } catch (IllegalArgumentException e) {
6720                Slog.w(TAG, e.getMessage());
6721            }
6722
6723            return policy;
6724        }
6725
6726        // Builds a line from a byte buffer starting at 'offset', and returns
6727        // the index of the next unconsumed data in the buffer.
6728        int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
6729            final int end = buffer.length;
6730            if (offset >= end) throw new IOException("Incomplete data");
6731
6732            int pos;
6733            for (pos = offset; pos < end; pos++) {
6734                byte c = buffer[pos];
6735                // at LF we declare end of line, and return the next char as the
6736                // starting point for the next time through
6737                if (c == '\n') {
6738                    break;
6739                }
6740            }
6741            outStr[0] = new String(buffer, offset, pos - offset);
6742            pos++;  // may be pointing an extra byte past the end but that's okay
6743            return pos;
6744        }
6745
6746        void dumpFileMetadata(FileMetadata info) {
6747            if (MORE_DEBUG) {
6748                StringBuilder b = new StringBuilder(128);
6749
6750                // mode string
6751                b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
6752                b.append(((info.mode & 0400) != 0) ? 'r' : '-');
6753                b.append(((info.mode & 0200) != 0) ? 'w' : '-');
6754                b.append(((info.mode & 0100) != 0) ? 'x' : '-');
6755                b.append(((info.mode & 0040) != 0) ? 'r' : '-');
6756                b.append(((info.mode & 0020) != 0) ? 'w' : '-');
6757                b.append(((info.mode & 0010) != 0) ? 'x' : '-');
6758                b.append(((info.mode & 0004) != 0) ? 'r' : '-');
6759                b.append(((info.mode & 0002) != 0) ? 'w' : '-');
6760                b.append(((info.mode & 0001) != 0) ? 'x' : '-');
6761                b.append(String.format(" %9d ", info.size));
6762
6763                Date stamp = new Date(info.mtime);
6764                b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp));
6765
6766                b.append(info.packageName);
6767                b.append(" :: ");
6768                b.append(info.domain);
6769                b.append(" :: ");
6770                b.append(info.path);
6771
6772                Slog.i(TAG, b.toString());
6773            }
6774        }
6775
6776        // Consume a tar file header block [sequence] and accumulate the relevant metadata
6777        FileMetadata readTarHeaders(InputStream instream) throws IOException {
6778            byte[] block = new byte[512];
6779            FileMetadata info = null;
6780
6781            boolean gotHeader = readTarHeader(instream, block);
6782            if (gotHeader) {
6783                try {
6784                    // okay, presume we're okay, and extract the various metadata
6785                    info = new FileMetadata();
6786                    info.size = extractRadix(block, TAR_HEADER_OFFSET_FILESIZE,
6787                            TAR_HEADER_LENGTH_FILESIZE, TAR_HEADER_LONG_RADIX);
6788                    info.mtime = extractRadix(block, TAR_HEADER_OFFSET_MODTIME,
6789                            TAR_HEADER_LENGTH_MODTIME, TAR_HEADER_LONG_RADIX);
6790                    info.mode = extractRadix(block, TAR_HEADER_OFFSET_MODE,
6791                            TAR_HEADER_LENGTH_MODE, TAR_HEADER_LONG_RADIX);
6792
6793                    info.path = extractString(block, TAR_HEADER_OFFSET_PATH_PREFIX,
6794                            TAR_HEADER_LENGTH_PATH_PREFIX);
6795                    String path = extractString(block, TAR_HEADER_OFFSET_PATH,
6796                            TAR_HEADER_LENGTH_PATH);
6797                    if (path.length() > 0) {
6798                        if (info.path.length() > 0) info.path += '/';
6799                        info.path += path;
6800                    }
6801
6802                    // tar link indicator field: 1 byte at offset 156 in the header.
6803                    int typeChar = block[TAR_HEADER_OFFSET_TYPE_CHAR];
6804                    if (typeChar == 'x') {
6805                        // pax extended header, so we need to read that
6806                        gotHeader = readPaxExtendedHeader(instream, info);
6807                        if (gotHeader) {
6808                            // and after a pax extended header comes another real header -- read
6809                            // that to find the real file type
6810                            gotHeader = readTarHeader(instream, block);
6811                        }
6812                        if (!gotHeader) throw new IOException("Bad or missing pax header");
6813
6814                        typeChar = block[TAR_HEADER_OFFSET_TYPE_CHAR];
6815                    }
6816
6817                    switch (typeChar) {
6818                        case '0': info.type = BackupAgent.TYPE_FILE; break;
6819                        case '5': {
6820                            info.type = BackupAgent.TYPE_DIRECTORY;
6821                            if (info.size != 0) {
6822                                Slog.w(TAG, "Directory entry with nonzero size in header");
6823                                info.size = 0;
6824                            }
6825                            break;
6826                        }
6827                        case 0: {
6828                            // presume EOF
6829                            if (MORE_DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
6830                            return null;
6831                        }
6832                        default: {
6833                            Slog.e(TAG, "Unknown tar entity type: " + typeChar);
6834                            throw new IOException("Unknown entity type " + typeChar);
6835                        }
6836                    }
6837
6838                    // Parse out the path
6839                    //
6840                    // first: apps/shared/unrecognized
6841                    if (FullBackup.SHARED_PREFIX.regionMatches(0,
6842                            info.path, 0, FullBackup.SHARED_PREFIX.length())) {
6843                        // File in shared storage.  !!! TODO: implement this.
6844                        info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
6845                        info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
6846                        info.domain = FullBackup.SHARED_STORAGE_TOKEN;
6847                        if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
6848                    } else if (FullBackup.APPS_PREFIX.regionMatches(0,
6849                            info.path, 0, FullBackup.APPS_PREFIX.length())) {
6850                        // App content!  Parse out the package name and domain
6851
6852                        // strip the apps/ prefix
6853                        info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
6854
6855                        // extract the package name
6856                        int slash = info.path.indexOf('/');
6857                        if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
6858                        info.packageName = info.path.substring(0, slash);
6859                        info.path = info.path.substring(slash+1);
6860
6861                        // if it's a manifest or metadata payload we're done, otherwise parse
6862                        // out the domain into which the file will be restored
6863                        if (!info.path.equals(BACKUP_MANIFEST_FILENAME)
6864                                && !info.path.equals(BACKUP_METADATA_FILENAME)) {
6865                            slash = info.path.indexOf('/');
6866                            if (slash < 0) {
6867                                throw new IOException("Illegal semantic path in non-manifest "
6868                                        + info.path);
6869                            }
6870                            info.domain = info.path.substring(0, slash);
6871                            info.path = info.path.substring(slash + 1);
6872                        }
6873                    }
6874                } catch (IOException e) {
6875                    if (DEBUG) {
6876                        Slog.e(TAG, "Parse error in header: " + e.getMessage());
6877                        if (MORE_DEBUG) {
6878                            HEXLOG(block);
6879                        }
6880                    }
6881                    throw e;
6882                }
6883            }
6884            return info;
6885        }
6886
6887        private boolean isRestorableFile(FileMetadata info) {
6888            if (FullBackup.CACHE_TREE_TOKEN.equals(info.domain)) {
6889                if (MORE_DEBUG) {
6890                    Slog.i(TAG, "Dropping cache file path " + info.path);
6891                }
6892                return false;
6893            }
6894
6895            if (FullBackup.ROOT_TREE_TOKEN.equals(info.domain)) {
6896                // It's possible this is "no-backup" dir contents in an archive stream
6897                // produced on a device running a version of the OS that predates that
6898                // API.  Respect the no-backup intention and don't let the data get to
6899                // the app.
6900                if (info.path.startsWith("no_backup/")) {
6901                    if (MORE_DEBUG) {
6902                        Slog.i(TAG, "Dropping no_backup file path " + info.path);
6903                    }
6904                    return false;
6905                }
6906            }
6907
6908            // The path needs to be canonical
6909            if (info.path.contains("..") || info.path.contains("//")) {
6910                if (MORE_DEBUG) {
6911                    Slog.w(TAG, "Dropping invalid path " + info.path);
6912                }
6913                return false;
6914            }
6915
6916            // Otherwise we think this file is good to go
6917            return true;
6918        }
6919
6920        private void HEXLOG(byte[] block) {
6921            int offset = 0;
6922            int todo = block.length;
6923            StringBuilder buf = new StringBuilder(64);
6924            while (todo > 0) {
6925                buf.append(String.format("%04x   ", offset));
6926                int numThisLine = (todo > 16) ? 16 : todo;
6927                for (int i = 0; i < numThisLine; i++) {
6928                    buf.append(String.format("%02x ", block[offset+i]));
6929                }
6930                Slog.i("hexdump", buf.toString());
6931                buf.setLength(0);
6932                todo -= numThisLine;
6933                offset += numThisLine;
6934            }
6935        }
6936
6937        // Read exactly the given number of bytes into a buffer at the stated offset.
6938        // Returns false if EOF is encountered before the requested number of bytes
6939        // could be read.
6940        int readExactly(InputStream in, byte[] buffer, int offset, int size)
6941                throws IOException {
6942            if (size <= 0) throw new IllegalArgumentException("size must be > 0");
6943if (MORE_DEBUG) Slog.i(TAG, "  ... readExactly(" + size + ") called");
6944            int soFar = 0;
6945            while (soFar < size) {
6946                int nRead = in.read(buffer, offset + soFar, size - soFar);
6947                if (nRead <= 0) {
6948                    if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
6949                    break;
6950                }
6951                soFar += nRead;
6952if (MORE_DEBUG) Slog.v(TAG, "   + got " + nRead + "; now wanting " + (size - soFar));
6953            }
6954            return soFar;
6955        }
6956
6957        boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
6958            final int got = readExactly(instream, block, 0, 512);
6959            if (got == 0) return false;     // Clean EOF
6960            if (got < 512) throw new IOException("Unable to read full block header");
6961            mBytes += 512;
6962            return true;
6963        }
6964
6965        // overwrites 'info' fields based on the pax extended header
6966        boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
6967                throws IOException {
6968            // We should never see a pax extended header larger than this
6969            if (info.size > 32*1024) {
6970                Slog.w(TAG, "Suspiciously large pax header size " + info.size
6971                        + " - aborting");
6972                throw new IOException("Sanity failure: pax header size " + info.size);
6973            }
6974
6975            // read whole blocks, not just the content size
6976            int numBlocks = (int)((info.size + 511) >> 9);
6977            byte[] data = new byte[numBlocks * 512];
6978            if (readExactly(instream, data, 0, data.length) < data.length) {
6979                throw new IOException("Unable to read full pax header");
6980            }
6981            mBytes += data.length;
6982
6983            final int contentSize = (int) info.size;
6984            int offset = 0;
6985            do {
6986                // extract the line at 'offset'
6987                int eol = offset+1;
6988                while (eol < contentSize && data[eol] != ' ') eol++;
6989                if (eol >= contentSize) {
6990                    // error: we just hit EOD looking for the end of the size field
6991                    throw new IOException("Invalid pax data");
6992                }
6993                // eol points to the space between the count and the key
6994                int linelen = (int) extractRadix(data, offset, eol - offset, 10);
6995                int key = eol + 1;  // start of key=value
6996                eol = offset + linelen - 1; // trailing LF
6997                int value;
6998                for (value = key+1; data[value] != '=' && value <= eol; value++);
6999                if (value > eol) {
7000                    throw new IOException("Invalid pax declaration");
7001                }
7002
7003                // pax requires that key/value strings be in UTF-8
7004                String keyStr = new String(data, key, value-key, "UTF-8");
7005                // -1 to strip the trailing LF
7006                String valStr = new String(data, value+1, eol-value-1, "UTF-8");
7007
7008                if ("path".equals(keyStr)) {
7009                    info.path = valStr;
7010                } else if ("size".equals(keyStr)) {
7011                    info.size = Long.parseLong(valStr);
7012                } else {
7013                    if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
7014                }
7015
7016                offset += linelen;
7017            } while (offset < contentSize);
7018
7019            return true;
7020        }
7021
7022        long extractRadix(byte[] data, int offset, int maxChars, int radix)
7023                throws IOException {
7024            long value = 0;
7025            final int end = offset + maxChars;
7026            for (int i = offset; i < end; i++) {
7027                final byte b = data[i];
7028                // Numeric fields in tar can terminate with either NUL or SPC
7029                if (b == 0 || b == ' ') break;
7030                if (b < '0' || b > ('0' + radix - 1)) {
7031                    throw new IOException("Invalid number in header: '" + (char)b
7032                            + "' for radix " + radix);
7033                }
7034                value = radix * value + (b - '0');
7035            }
7036            return value;
7037        }
7038
7039        String extractString(byte[] data, int offset, int maxChars) throws IOException {
7040            final int end = offset + maxChars;
7041            int eos = offset;
7042            // tar string fields terminate early with a NUL
7043            while (eos < end && data[eos] != 0) eos++;
7044            return new String(data, offset, eos-offset, "US-ASCII");
7045        }
7046
7047        void sendStartRestore() {
7048            if (mObserver != null) {
7049                try {
7050                    mObserver.onStartRestore();
7051                } catch (RemoteException e) {
7052                    Slog.w(TAG, "full restore observer went away: startRestore");
7053                    mObserver = null;
7054                }
7055            }
7056        }
7057
7058        void sendOnRestorePackage(String name) {
7059            if (mObserver != null) {
7060                try {
7061                    // TODO: use a more user-friendly name string
7062                    mObserver.onRestorePackage(name);
7063                } catch (RemoteException e) {
7064                    Slog.w(TAG, "full restore observer went away: restorePackage");
7065                    mObserver = null;
7066                }
7067            }
7068        }
7069
7070        void sendEndRestore() {
7071            if (mObserver != null) {
7072                try {
7073                    mObserver.onEndRestore();
7074                } catch (RemoteException e) {
7075                    Slog.w(TAG, "full restore observer went away: endRestore");
7076                    mObserver = null;
7077                }
7078            }
7079        }
7080    }
7081
7082    // ***** end new engine class ***
7083
7084    // Used for synchronizing doRestoreFinished during adb restore
7085    class AdbRestoreFinishedLatch implements BackupRestoreTask {
7086        static final String TAG = "AdbRestoreFinishedLatch";
7087        final CountDownLatch mLatch;
7088        private final int mCurrentOpToken;
7089
7090        AdbRestoreFinishedLatch(int currentOpToken) {
7091            mLatch = new CountDownLatch(1);
7092            mCurrentOpToken = currentOpToken;
7093        }
7094
7095        void await() {
7096            boolean latched = false;
7097            try {
7098                latched = mLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
7099            } catch (InterruptedException e) {
7100                Slog.w(TAG, "Interrupted!");
7101            }
7102        }
7103
7104        @Override
7105        public void execute() {
7106            // Unused
7107        }
7108
7109        @Override
7110        public void operationComplete(long result) {
7111            if (MORE_DEBUG) {
7112                Slog.w(TAG, "adb onRestoreFinished() complete");
7113            }
7114            mLatch.countDown();
7115            removeOperation(mCurrentOpToken);
7116        }
7117
7118        @Override
7119        public void handleCancel(boolean cancelAll) {
7120            if (DEBUG) {
7121                Slog.w(TAG, "adb onRestoreFinished() timed out");
7122            }
7123            mLatch.countDown();
7124            removeOperation(mCurrentOpToken);
7125        }
7126    }
7127
7128    class PerformAdbRestoreTask implements Runnable {
7129        ParcelFileDescriptor mInputFile;
7130        String mCurrentPassword;
7131        String mDecryptPassword;
7132        IFullBackupRestoreObserver mObserver;
7133        AtomicBoolean mLatchObject;
7134        IBackupAgent mAgent;
7135        PackageManagerBackupAgent mPackageManagerBackupAgent;
7136        String mAgentPackage;
7137        ApplicationInfo mTargetApp;
7138        FullBackupObbConnection mObbConnection = null;
7139        ParcelFileDescriptor[] mPipes = null;
7140        byte[] mWidgetData = null;
7141
7142        long mBytes;
7143
7144        // Runner that can be placed on a separate thread to do in-process invocation
7145        // of the "restore finished" API asynchronously.  Used by adb restore.
7146        class RestoreFinishedRunnable implements Runnable {
7147            final IBackupAgent mAgent;
7148            final int mToken;
7149
7150            RestoreFinishedRunnable(IBackupAgent agent, int token) {
7151                mAgent = agent;
7152                mToken = token;
7153            }
7154
7155            @Override
7156            public void run() {
7157                try {
7158                    mAgent.doRestoreFinished(mToken, mBackupManagerBinder);
7159                } catch (RemoteException e) {
7160                    // never happens; this is used only for local binder calls
7161                }
7162            }
7163        }
7164
7165        // possible handling states for a given package in the restore dataset
7166        final HashMap<String, RestorePolicy> mPackagePolicies
7167                = new HashMap<String, RestorePolicy>();
7168
7169        // installer package names for each encountered app, derived from the manifests
7170        final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
7171
7172        // Signatures for a given package found in its manifest file
7173        final HashMap<String, Signature[]> mManifestSignatures
7174                = new HashMap<String, Signature[]>();
7175
7176        // Packages we've already wiped data on when restoring their first file
7177        final HashSet<String> mClearedPackages = new HashSet<String>();
7178
7179        PerformAdbRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
7180                IFullBackupRestoreObserver observer, AtomicBoolean latch) {
7181            mInputFile = fd;
7182            mCurrentPassword = curPassword;
7183            mDecryptPassword = decryptPassword;
7184            mObserver = observer;
7185            mLatchObject = latch;
7186            mAgent = null;
7187            mPackageManagerBackupAgent = makeMetadataAgent();
7188            mAgentPackage = null;
7189            mTargetApp = null;
7190            mObbConnection = new FullBackupObbConnection();
7191
7192            // Which packages we've already wiped data on.  We prepopulate this
7193            // with a whitelist of packages known to be unclearable.
7194            mClearedPackages.add("android");
7195            mClearedPackages.add(SETTINGS_PACKAGE);
7196        }
7197
7198        class RestoreFileRunnable implements Runnable {
7199            IBackupAgent mAgent;
7200            FileMetadata mInfo;
7201            ParcelFileDescriptor mSocket;
7202            int mToken;
7203
7204            RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
7205                    ParcelFileDescriptor socket, int token) throws IOException {
7206                mAgent = agent;
7207                mInfo = info;
7208                mToken = token;
7209
7210                // This class is used strictly for process-local binder invocations.  The
7211                // semantics of ParcelFileDescriptor differ in this case; in particular, we
7212                // do not automatically get a 'dup'ed descriptor that we can can continue
7213                // to use asynchronously from the caller.  So, we make sure to dup it ourselves
7214                // before proceeding to do the restore.
7215                mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
7216            }
7217
7218            @Override
7219            public void run() {
7220                try {
7221                    mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
7222                            mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
7223                            mToken, mBackupManagerBinder);
7224                } catch (RemoteException e) {
7225                    // never happens; this is used strictly for local binder calls
7226                }
7227            }
7228        }
7229
7230        @Override
7231        public void run() {
7232            Slog.i(TAG, "--- Performing full-dataset restore ---");
7233            mObbConnection.establish();
7234            sendStartRestore();
7235
7236            // Are we able to restore shared-storage data?
7237            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
7238                mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
7239            }
7240
7241            FileInputStream rawInStream = null;
7242            DataInputStream rawDataIn = null;
7243            try {
7244                if (!backupPasswordMatches(mCurrentPassword)) {
7245                    if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
7246                    return;
7247                }
7248
7249                mBytes = 0;
7250                byte[] buffer = new byte[32 * 1024];
7251                rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
7252                rawDataIn = new DataInputStream(rawInStream);
7253
7254                // First, parse out the unencrypted/uncompressed header
7255                boolean compressed = false;
7256                InputStream preCompressStream = rawInStream;
7257                final InputStream in;
7258
7259                boolean okay = false;
7260                final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
7261                byte[] streamHeader = new byte[headerLen];
7262                rawDataIn.readFully(streamHeader);
7263                byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
7264                if (Arrays.equals(magicBytes, streamHeader)) {
7265                    // okay, header looks good.  now parse out the rest of the fields.
7266                    String s = readHeaderLine(rawInStream);
7267                    final int archiveVersion = Integer.parseInt(s);
7268                    if (archiveVersion <= BACKUP_FILE_VERSION) {
7269                        // okay, it's a version we recognize.  if it's version 1, we may need
7270                        // to try two different PBKDF2 regimes to compare checksums.
7271                        final boolean pbkdf2Fallback = (archiveVersion == 1);
7272
7273                        s = readHeaderLine(rawInStream);
7274                        compressed = (Integer.parseInt(s) != 0);
7275                        s = readHeaderLine(rawInStream);
7276                        if (s.equals("none")) {
7277                            // no more header to parse; we're good to go
7278                            okay = true;
7279                        } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
7280                            preCompressStream = decodeAesHeaderAndInitialize(s, pbkdf2Fallback,
7281                                    rawInStream);
7282                            if (preCompressStream != null) {
7283                                okay = true;
7284                            }
7285                        } else Slog.w(TAG, "Archive is encrypted but no password given");
7286                    } else Slog.w(TAG, "Wrong header version: " + s);
7287                } else Slog.w(TAG, "Didn't read the right header magic");
7288
7289                if (!okay) {
7290                    Slog.w(TAG, "Invalid restore data; aborting.");
7291                    return;
7292                }
7293
7294                // okay, use the right stream layer based on compression
7295                in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
7296
7297                boolean didRestore;
7298                do {
7299                    didRestore = restoreOneFile(in, buffer);
7300                } while (didRestore);
7301
7302                if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
7303            } catch (IOException e) {
7304                Slog.e(TAG, "Unable to read restore input");
7305            } finally {
7306                tearDownPipes();
7307                tearDownAgent(mTargetApp, true);
7308
7309                try {
7310                    if (rawDataIn != null) rawDataIn.close();
7311                    if (rawInStream != null) rawInStream.close();
7312                    mInputFile.close();
7313                } catch (IOException e) {
7314                    Slog.w(TAG, "Close of restore data pipe threw", e);
7315                    /* nothing we can do about this */
7316                }
7317                synchronized (mLatchObject) {
7318                    mLatchObject.set(true);
7319                    mLatchObject.notifyAll();
7320                }
7321                mObbConnection.tearDown();
7322                sendEndRestore();
7323                Slog.d(TAG, "Full restore pass complete.");
7324                mWakelock.release();
7325            }
7326        }
7327
7328        String readHeaderLine(InputStream in) throws IOException {
7329            int c;
7330            StringBuilder buffer = new StringBuilder(80);
7331            while ((c = in.read()) >= 0) {
7332                if (c == '\n') break;   // consume and discard the newlines
7333                buffer.append((char)c);
7334            }
7335            return buffer.toString();
7336        }
7337
7338        InputStream attemptMasterKeyDecryption(String algorithm, byte[] userSalt, byte[] ckSalt,
7339                int rounds, String userIvHex, String masterKeyBlobHex, InputStream rawInStream,
7340                boolean doLog) {
7341            InputStream result = null;
7342
7343            try {
7344                Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
7345                SecretKey userKey = buildPasswordKey(algorithm, mDecryptPassword, userSalt,
7346                        rounds);
7347                byte[] IV = hexToByteArray(userIvHex);
7348                IvParameterSpec ivSpec = new IvParameterSpec(IV);
7349                c.init(Cipher.DECRYPT_MODE,
7350                        new SecretKeySpec(userKey.getEncoded(), "AES"),
7351                        ivSpec);
7352                byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
7353                byte[] mkBlob = c.doFinal(mkCipher);
7354
7355                // first, the master key IV
7356                int offset = 0;
7357                int len = mkBlob[offset++];
7358                IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
7359                offset += len;
7360                // then the master key itself
7361                len = mkBlob[offset++];
7362                byte[] mk = Arrays.copyOfRange(mkBlob,
7363                        offset, offset + len);
7364                offset += len;
7365                // and finally the master key checksum hash
7366                len = mkBlob[offset++];
7367                byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
7368                        offset, offset + len);
7369
7370                // now validate the decrypted master key against the checksum
7371                byte[] calculatedCk = makeKeyChecksum(algorithm, mk, ckSalt, rounds);
7372                if (Arrays.equals(calculatedCk, mkChecksum)) {
7373                    ivSpec = new IvParameterSpec(IV);
7374                    c.init(Cipher.DECRYPT_MODE,
7375                            new SecretKeySpec(mk, "AES"),
7376                            ivSpec);
7377                    // Only if all of the above worked properly will 'result' be assigned
7378                    result = new CipherInputStream(rawInStream, c);
7379                } else if (doLog) Slog.w(TAG, "Incorrect password");
7380            } catch (InvalidAlgorithmParameterException e) {
7381                if (doLog) Slog.e(TAG, "Needed parameter spec unavailable!", e);
7382            } catch (BadPaddingException e) {
7383                // This case frequently occurs when the wrong password is used to decrypt
7384                // the master key.  Use the identical "incorrect password" log text as is
7385                // used in the checksum failure log in order to avoid providing additional
7386                // information to an attacker.
7387                if (doLog) Slog.w(TAG, "Incorrect password");
7388            } catch (IllegalBlockSizeException e) {
7389                if (doLog) Slog.w(TAG, "Invalid block size in master key");
7390            } catch (NoSuchAlgorithmException e) {
7391                if (doLog) Slog.e(TAG, "Needed decryption algorithm unavailable!");
7392            } catch (NoSuchPaddingException e) {
7393                if (doLog) Slog.e(TAG, "Needed padding mechanism unavailable!");
7394            } catch (InvalidKeyException e) {
7395                if (doLog) Slog.w(TAG, "Illegal password; aborting");
7396            }
7397
7398            return result;
7399        }
7400
7401        InputStream decodeAesHeaderAndInitialize(String encryptionName, boolean pbkdf2Fallback,
7402                InputStream rawInStream) {
7403            InputStream result = null;
7404            try {
7405                if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
7406
7407                    String userSaltHex = readHeaderLine(rawInStream); // 5
7408                    byte[] userSalt = hexToByteArray(userSaltHex);
7409
7410                    String ckSaltHex = readHeaderLine(rawInStream); // 6
7411                    byte[] ckSalt = hexToByteArray(ckSaltHex);
7412
7413                    int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
7414                    String userIvHex = readHeaderLine(rawInStream); // 8
7415
7416                    String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
7417
7418                    // decrypt the master key blob
7419                    result = attemptMasterKeyDecryption(PBKDF_CURRENT, userSalt, ckSalt,
7420                            rounds, userIvHex, masterKeyBlobHex, rawInStream, false);
7421                    if (result == null && pbkdf2Fallback) {
7422                        result = attemptMasterKeyDecryption(PBKDF_FALLBACK, userSalt, ckSalt,
7423                                rounds, userIvHex, masterKeyBlobHex, rawInStream, true);
7424                    }
7425                } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
7426            } catch (NumberFormatException e) {
7427                Slog.w(TAG, "Can't parse restore data header");
7428            } catch (IOException e) {
7429                Slog.w(TAG, "Can't read input header");
7430            }
7431
7432            return result;
7433        }
7434
7435        boolean restoreOneFile(InputStream instream, byte[] buffer) {
7436            FileMetadata info;
7437            try {
7438                info = readTarHeaders(instream);
7439                if (info != null) {
7440                    if (MORE_DEBUG) {
7441                        dumpFileMetadata(info);
7442                    }
7443
7444                    final String pkg = info.packageName;
7445                    if (!pkg.equals(mAgentPackage)) {
7446                        // okay, change in package; set up our various
7447                        // bookkeeping if we haven't seen it yet
7448                        if (!mPackagePolicies.containsKey(pkg)) {
7449                            mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7450                        }
7451
7452                        // Clean up the previous agent relationship if necessary,
7453                        // and let the observer know we're considering a new app.
7454                        if (mAgent != null) {
7455                            if (DEBUG) Slog.d(TAG, "Saw new package; finalizing old one");
7456                            // Now we're really done
7457                            tearDownPipes();
7458                            tearDownAgent(mTargetApp, true);
7459                            mTargetApp = null;
7460                            mAgentPackage = null;
7461                        }
7462                    }
7463
7464                    if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
7465                        mPackagePolicies.put(pkg, readAppManifest(info, instream));
7466                        mPackageInstallers.put(pkg, info.installerPackageName);
7467                        // We've read only the manifest content itself at this point,
7468                        // so consume the footer before looping around to the next
7469                        // input file
7470                        skipTarPadding(info.size, instream);
7471                        sendOnRestorePackage(pkg);
7472                    } else if (info.path.equals(BACKUP_METADATA_FILENAME)) {
7473                        // Metadata blobs!
7474                        readMetadata(info, instream);
7475                        skipTarPadding(info.size, instream);
7476                    } else {
7477                        // Non-manifest, so it's actual file data.  Is this a package
7478                        // we're ignoring?
7479                        boolean okay = true;
7480                        RestorePolicy policy = mPackagePolicies.get(pkg);
7481                        switch (policy) {
7482                            case IGNORE:
7483                                okay = false;
7484                                break;
7485
7486                            case ACCEPT_IF_APK:
7487                                // If we're in accept-if-apk state, then the first file we
7488                                // see MUST be the apk.
7489                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
7490                                    if (DEBUG) Slog.d(TAG, "APK file; installing");
7491                                    // Try to install the app.
7492                                    String installerName = mPackageInstallers.get(pkg);
7493                                    okay = installApk(info, installerName, instream);
7494                                    // good to go; promote to ACCEPT
7495                                    mPackagePolicies.put(pkg, (okay)
7496                                            ? RestorePolicy.ACCEPT
7497                                            : RestorePolicy.IGNORE);
7498                                    // At this point we've consumed this file entry
7499                                    // ourselves, so just strip the tar footer and
7500                                    // go on to the next file in the input stream
7501                                    skipTarPadding(info.size, instream);
7502                                    return true;
7503                                } else {
7504                                    // File data before (or without) the apk.  We can't
7505                                    // handle it coherently in this case so ignore it.
7506                                    mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7507                                    okay = false;
7508                                }
7509                                break;
7510
7511                            case ACCEPT:
7512                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
7513                                    if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
7514                                    // we can take the data without the apk, so we
7515                                    // *want* to do so.  skip the apk by declaring this
7516                                    // one file not-okay without changing the restore
7517                                    // policy for the package.
7518                                    okay = false;
7519                                }
7520                                break;
7521
7522                            default:
7523                                // Something has gone dreadfully wrong when determining
7524                                // the restore policy from the manifest.  Ignore the
7525                                // rest of this package's data.
7526                                Slog.e(TAG, "Invalid policy from manifest");
7527                                okay = false;
7528                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7529                                break;
7530                        }
7531
7532                        // The path needs to be canonical
7533                        if (info.path.contains("..") || info.path.contains("//")) {
7534                            if (MORE_DEBUG) {
7535                                Slog.w(TAG, "Dropping invalid path " + info.path);
7536                            }
7537                            okay = false;
7538                        }
7539
7540                        // If the policy is satisfied, go ahead and set up to pipe the
7541                        // data to the agent.
7542                        if (DEBUG && okay && mAgent != null) {
7543                            Slog.i(TAG, "Reusing existing agent instance");
7544                        }
7545                        if (okay && mAgent == null) {
7546                            if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
7547
7548                            try {
7549                                mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
7550
7551                                // If we haven't sent any data to this app yet, we probably
7552                                // need to clear it first.  Check that.
7553                                if (!mClearedPackages.contains(pkg)) {
7554                                    // apps with their own backup agents are
7555                                    // responsible for coherently managing a full
7556                                    // restore.
7557                                    if (mTargetApp.backupAgentName == null) {
7558                                        if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
7559                                        clearApplicationDataSynchronous(pkg);
7560                                    } else {
7561                                        if (DEBUG) Slog.d(TAG, "backup agent ("
7562                                                + mTargetApp.backupAgentName + ") => no clear");
7563                                    }
7564                                    mClearedPackages.add(pkg);
7565                                } else {
7566                                    if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
7567                                }
7568
7569                                // All set; now set up the IPC and launch the agent
7570                                setUpPipes();
7571                                mAgent = bindToAgentSynchronous(mTargetApp,
7572                                        FullBackup.KEY_VALUE_DATA_TOKEN.equals(info.domain)
7573                                                ? ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL
7574                                                : ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL);
7575                                mAgentPackage = pkg;
7576                            } catch (IOException e) {
7577                                // fall through to error handling
7578                            } catch (NameNotFoundException e) {
7579                                // fall through to error handling
7580                            }
7581
7582                            if (mAgent == null) {
7583                                if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
7584                                okay = false;
7585                                tearDownPipes();
7586                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7587                            }
7588                        }
7589
7590                        // Sanity check: make sure we never give data to the wrong app.  This
7591                        // should never happen but a little paranoia here won't go amiss.
7592                        if (okay && !pkg.equals(mAgentPackage)) {
7593                            Slog.e(TAG, "Restoring data for " + pkg
7594                                    + " but agent is for " + mAgentPackage);
7595                            okay = false;
7596                        }
7597
7598                        // At this point we have an agent ready to handle the full
7599                        // restore data as well as a pipe for sending data to
7600                        // that agent.  Tell the agent to start reading from the
7601                        // pipe.
7602                        if (okay) {
7603                            boolean agentSuccess = true;
7604                            long toCopy = info.size;
7605                            final boolean isSharedStorage = pkg.equals(SHARED_BACKUP_AGENT_PACKAGE);
7606                            final long timeout = isSharedStorage ?
7607                                    TIMEOUT_SHARED_BACKUP_INTERVAL : TIMEOUT_RESTORE_INTERVAL;
7608                            final int token = generateRandomIntegerToken();
7609                            try {
7610                                prepareOperationTimeout(token, timeout, null,
7611                                        OP_TYPE_RESTORE_WAIT);
7612                                if (FullBackup.OBB_TREE_TOKEN.equals(info.domain)) {
7613                                    if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
7614                                            + " : " + info.path);
7615                                    mObbConnection.restoreObbFile(pkg, mPipes[0],
7616                                            info.size, info.type, info.path, info.mode,
7617                                            info.mtime, token, mBackupManagerBinder);
7618                                } else if (FullBackup.KEY_VALUE_DATA_TOKEN.equals(info.domain)) {
7619                                    if (DEBUG) Slog.d(TAG, "Restoring key-value file for " + pkg
7620                                            + " : " + info.path);
7621                                    KeyValueAdbRestoreEngine restoreEngine =
7622                                            new KeyValueAdbRestoreEngine(BackupManagerService.this,
7623                                                    mDataDir, info, mPipes[0], mAgent, token);
7624                                    new Thread(restoreEngine, "restore-key-value-runner").start();
7625                                } else {
7626                                    if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
7627                                            + info.path);
7628                                    // fire up the app's agent listening on the socket.  If
7629                                    // the agent is running in the system process we can't
7630                                    // just invoke it asynchronously, so we provide a thread
7631                                    // for it here.
7632                                    if (mTargetApp.processName.equals("system")) {
7633                                        Slog.d(TAG, "system process agent - spinning a thread");
7634                                        RestoreFileRunnable runner = new RestoreFileRunnable(
7635                                                mAgent, info, mPipes[0], token);
7636                                        new Thread(runner, "restore-sys-runner").start();
7637                                    } else {
7638                                        mAgent.doRestoreFile(mPipes[0], info.size, info.type,
7639                                                info.domain, info.path, info.mode, info.mtime,
7640                                                token, mBackupManagerBinder);
7641                                    }
7642                                }
7643                            } catch (IOException e) {
7644                                // couldn't dup the socket for a process-local restore
7645                                Slog.d(TAG, "Couldn't establish restore");
7646                                agentSuccess = false;
7647                                okay = false;
7648                            } catch (RemoteException e) {
7649                                // whoops, remote entity went away.  We'll eat the content
7650                                // ourselves, then, and not copy it over.
7651                                Slog.e(TAG, "Agent crashed during full restore");
7652                                agentSuccess = false;
7653                                okay = false;
7654                            }
7655
7656                            // Copy over the data if the agent is still good
7657                            if (okay) {
7658                                boolean pipeOkay = true;
7659                                FileOutputStream pipe = new FileOutputStream(
7660                                        mPipes[1].getFileDescriptor());
7661                                while (toCopy > 0) {
7662                                    int toRead = (toCopy > buffer.length)
7663                                    ? buffer.length : (int)toCopy;
7664                                    int nRead = instream.read(buffer, 0, toRead);
7665                                    if (nRead >= 0) mBytes += nRead;
7666                                    if (nRead <= 0) break;
7667                                    toCopy -= nRead;
7668
7669                                    // send it to the output pipe as long as things
7670                                    // are still good
7671                                    if (pipeOkay) {
7672                                        try {
7673                                            pipe.write(buffer, 0, nRead);
7674                                        } catch (IOException e) {
7675                                            Slog.e(TAG, "Failed to write to restore pipe", e);
7676                                            pipeOkay = false;
7677                                        }
7678                                    }
7679                                }
7680
7681                                // done sending that file!  Now we just need to consume
7682                                // the delta from info.size to the end of block.
7683                                skipTarPadding(info.size, instream);
7684
7685                                // and now that we've sent it all, wait for the remote
7686                                // side to acknowledge receipt
7687                                agentSuccess = waitUntilOperationComplete(token);
7688                            }
7689
7690                            // okay, if the remote end failed at any point, deal with
7691                            // it by ignoring the rest of the restore on it
7692                            if (!agentSuccess) {
7693                                if (DEBUG) {
7694                                    Slog.d(TAG, "Agent failure restoring " + pkg + "; now ignoring");
7695                                }
7696                                mBackupHandler.removeMessages(MSG_RESTORE_OPERATION_TIMEOUT);
7697                                tearDownPipes();
7698                                tearDownAgent(mTargetApp, false);
7699                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7700                            }
7701                        }
7702
7703                        // Problems setting up the agent communication, or an already-
7704                        // ignored package: skip to the next tar stream entry by
7705                        // reading and discarding this file.
7706                        if (!okay) {
7707                            if (DEBUG) Slog.d(TAG, "[discarding file content]");
7708                            long bytesToConsume = (info.size + 511) & ~511;
7709                            while (bytesToConsume > 0) {
7710                                int toRead = (bytesToConsume > buffer.length)
7711                                ? buffer.length : (int)bytesToConsume;
7712                                long nRead = instream.read(buffer, 0, toRead);
7713                                if (nRead >= 0) mBytes += nRead;
7714                                if (nRead <= 0) break;
7715                                bytesToConsume -= nRead;
7716                            }
7717                        }
7718                    }
7719                }
7720            } catch (IOException e) {
7721                if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
7722                // treat as EOF
7723                info = null;
7724            }
7725
7726            return (info != null);
7727        }
7728
7729        void setUpPipes() throws IOException {
7730            mPipes = ParcelFileDescriptor.createPipe();
7731        }
7732
7733        void tearDownPipes() {
7734            if (mPipes != null) {
7735                try {
7736                    mPipes[0].close();
7737                    mPipes[0] = null;
7738                    mPipes[1].close();
7739                    mPipes[1] = null;
7740                } catch (IOException e) {
7741                    Slog.w(TAG, "Couldn't close agent pipes", e);
7742                }
7743                mPipes = null;
7744            }
7745        }
7746
7747        void tearDownAgent(ApplicationInfo app, boolean doRestoreFinished) {
7748            if (mAgent != null) {
7749                try {
7750                    // In the adb restore case, we do restore-finished here
7751                    if (doRestoreFinished) {
7752                        final int token = generateRandomIntegerToken();
7753                        final AdbRestoreFinishedLatch latch = new AdbRestoreFinishedLatch(token);
7754                        prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, latch,
7755                                OP_TYPE_RESTORE_WAIT);
7756                        if (mTargetApp.processName.equals("system")) {
7757                            if (MORE_DEBUG) {
7758                                Slog.d(TAG, "system agent - restoreFinished on thread");
7759                            }
7760                            Runnable runner = new RestoreFinishedRunnable(mAgent, token);
7761                            new Thread(runner, "restore-sys-finished-runner").start();
7762                        } else {
7763                            mAgent.doRestoreFinished(token, mBackupManagerBinder);
7764                        }
7765
7766                        latch.await();
7767                    }
7768
7769                    // unbind and tidy up even on timeout or failure, just in case
7770                    mActivityManager.unbindBackupAgent(app);
7771
7772                    // The agent was running with a stub Application object, so shut it down.
7773                    // !!! We hardcode the confirmation UI's package name here rather than use a
7774                    //     manifest flag!  TODO something less direct.
7775                    if (app.uid >= Process.FIRST_APPLICATION_UID
7776                            && !app.packageName.equals("com.android.backupconfirm")) {
7777                        if (DEBUG) Slog.d(TAG, "Killing host process");
7778                        mActivityManager.killApplicationProcess(app.processName, app.uid);
7779                    } else {
7780                        if (DEBUG) Slog.d(TAG, "Not killing after full restore");
7781                    }
7782                } catch (RemoteException e) {
7783                    Slog.d(TAG, "Lost app trying to shut down");
7784                }
7785                mAgent = null;
7786            }
7787        }
7788
7789        class RestoreInstallObserver extends PackageInstallObserver {
7790            final AtomicBoolean mDone = new AtomicBoolean();
7791            String mPackageName;
7792            int mResult;
7793
7794            public void reset() {
7795                synchronized (mDone) {
7796                    mDone.set(false);
7797                }
7798            }
7799
7800            public void waitForCompletion() {
7801                synchronized (mDone) {
7802                    while (mDone.get() == false) {
7803                        try {
7804                            mDone.wait();
7805                        } catch (InterruptedException e) { }
7806                    }
7807                }
7808            }
7809
7810            int getResult() {
7811                return mResult;
7812            }
7813
7814            @Override
7815            public void onPackageInstalled(String packageName, int returnCode,
7816                    String msg, Bundle extras) {
7817                synchronized (mDone) {
7818                    mResult = returnCode;
7819                    mPackageName = packageName;
7820                    mDone.set(true);
7821                    mDone.notifyAll();
7822                }
7823            }
7824        }
7825
7826        class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
7827            final AtomicBoolean mDone = new AtomicBoolean();
7828            int mResult;
7829
7830            public void reset() {
7831                synchronized (mDone) {
7832                    mDone.set(false);
7833                }
7834            }
7835
7836            public void waitForCompletion() {
7837                synchronized (mDone) {
7838                    while (mDone.get() == false) {
7839                        try {
7840                            mDone.wait();
7841                        } catch (InterruptedException e) { }
7842                    }
7843                }
7844            }
7845
7846            @Override
7847            public void packageDeleted(String packageName, int returnCode) throws RemoteException {
7848                synchronized (mDone) {
7849                    mResult = returnCode;
7850                    mDone.set(true);
7851                    mDone.notifyAll();
7852                }
7853            }
7854        }
7855
7856        final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
7857        final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
7858
7859        boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
7860            boolean okay = true;
7861
7862            if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
7863
7864            // The file content is an .apk file.  Copy it out to a staging location and
7865            // attempt to install it.
7866            File apkFile = new File(mDataDir, info.packageName);
7867            try {
7868                FileOutputStream apkStream = new FileOutputStream(apkFile);
7869                byte[] buffer = new byte[32 * 1024];
7870                long size = info.size;
7871                while (size > 0) {
7872                    long toRead = (buffer.length < size) ? buffer.length : size;
7873                    int didRead = instream.read(buffer, 0, (int)toRead);
7874                    if (didRead >= 0) mBytes += didRead;
7875                    apkStream.write(buffer, 0, didRead);
7876                    size -= didRead;
7877                }
7878                apkStream.close();
7879
7880                // make sure the installer can read it
7881                apkFile.setReadable(true, false);
7882
7883                // Now install it
7884                Uri packageUri = Uri.fromFile(apkFile);
7885                mInstallObserver.reset();
7886                mPackageManager.installPackage(packageUri, mInstallObserver,
7887                        PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
7888                        installerPackage);
7889                mInstallObserver.waitForCompletion();
7890
7891                if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
7892                    // The only time we continue to accept install of data even if the
7893                    // apk install failed is if we had already determined that we could
7894                    // accept the data regardless.
7895                    if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
7896                        okay = false;
7897                    }
7898                } else {
7899                    // Okay, the install succeeded.  Make sure it was the right app.
7900                    boolean uninstall = false;
7901                    if (!mInstallObserver.mPackageName.equals(info.packageName)) {
7902                        Slog.w(TAG, "Restore stream claimed to include apk for "
7903                                + info.packageName + " but apk was really "
7904                                + mInstallObserver.mPackageName);
7905                        // delete the package we just put in place; it might be fraudulent
7906                        okay = false;
7907                        uninstall = true;
7908                    } else {
7909                        try {
7910                            PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
7911                                    PackageManager.GET_SIGNATURES);
7912                            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
7913                                Slog.w(TAG, "Restore stream contains apk of package "
7914                                        + info.packageName + " but it disallows backup/restore");
7915                                okay = false;
7916                            } else {
7917                                // So far so good -- do the signatures match the manifest?
7918                                Signature[] sigs = mManifestSignatures.get(info.packageName);
7919                                if (signaturesMatch(sigs, pkg)) {
7920                                    // If this is a system-uid app without a declared backup agent,
7921                                    // don't restore any of the file data.
7922                                    if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
7923                                            && (pkg.applicationInfo.backupAgentName == null)) {
7924                                        Slog.w(TAG, "Installed app " + info.packageName
7925                                                + " has restricted uid and no agent");
7926                                        okay = false;
7927                                    }
7928                                } else {
7929                                    Slog.w(TAG, "Installed app " + info.packageName
7930                                            + " signatures do not match restore manifest");
7931                                    okay = false;
7932                                    uninstall = true;
7933                                }
7934                            }
7935                        } catch (NameNotFoundException e) {
7936                            Slog.w(TAG, "Install of package " + info.packageName
7937                                    + " succeeded but now not found");
7938                            okay = false;
7939                        }
7940                    }
7941
7942                    // If we're not okay at this point, we need to delete the package
7943                    // that we just installed.
7944                    if (uninstall) {
7945                        mDeleteObserver.reset();
7946                        mPackageManager.deletePackage(mInstallObserver.mPackageName,
7947                                mDeleteObserver, 0);
7948                        mDeleteObserver.waitForCompletion();
7949                    }
7950                }
7951            } catch (IOException e) {
7952                Slog.e(TAG, "Unable to transcribe restored apk for install");
7953                okay = false;
7954            } finally {
7955                apkFile.delete();
7956            }
7957
7958            return okay;
7959        }
7960
7961        // Given an actual file content size, consume the post-content padding mandated
7962        // by the tar format.
7963        void skipTarPadding(long size, InputStream instream) throws IOException {
7964            long partial = (size + 512) % 512;
7965            if (partial > 0) {
7966                final int needed = 512 - (int)partial;
7967                byte[] buffer = new byte[needed];
7968                if (readExactly(instream, buffer, 0, needed) == needed) {
7969                    mBytes += needed;
7970                } else throw new IOException("Unexpected EOF in padding");
7971            }
7972        }
7973
7974        // Read a widget metadata file, returning the restored blob
7975        void readMetadata(FileMetadata info, InputStream instream) throws IOException {
7976            // Fail on suspiciously large widget dump files
7977            if (info.size > 64 * 1024) {
7978                throw new IOException("Metadata too big; corrupt? size=" + info.size);
7979            }
7980
7981            byte[] buffer = new byte[(int) info.size];
7982            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
7983                mBytes += info.size;
7984            } else throw new IOException("Unexpected EOF in widget data");
7985
7986            String[] str = new String[1];
7987            int offset = extractLine(buffer, 0, str);
7988            int version = Integer.parseInt(str[0]);
7989            if (version == BACKUP_MANIFEST_VERSION) {
7990                offset = extractLine(buffer, offset, str);
7991                final String pkg = str[0];
7992                if (info.packageName.equals(pkg)) {
7993                    // Data checks out -- the rest of the buffer is a concatenation of
7994                    // binary blobs as described in the comment at writeAppWidgetData()
7995                    ByteArrayInputStream bin = new ByteArrayInputStream(buffer,
7996                            offset, buffer.length - offset);
7997                    DataInputStream in = new DataInputStream(bin);
7998                    while (bin.available() > 0) {
7999                        int token = in.readInt();
8000                        int size = in.readInt();
8001                        if (size > 64 * 1024) {
8002                            throw new IOException("Datum "
8003                                    + Integer.toHexString(token)
8004                                    + " too big; corrupt? size=" + info.size);
8005                        }
8006                        switch (token) {
8007                            case BACKUP_WIDGET_METADATA_TOKEN:
8008                            {
8009                                if (MORE_DEBUG) {
8010                                    Slog.i(TAG, "Got widget metadata for " + info.packageName);
8011                                }
8012                                mWidgetData = new byte[size];
8013                                in.read(mWidgetData);
8014                                break;
8015                            }
8016                            default:
8017                            {
8018                                if (DEBUG) {
8019                                    Slog.i(TAG, "Ignoring metadata blob "
8020                                            + Integer.toHexString(token)
8021                                            + " for " + info.packageName);
8022                                }
8023                                in.skipBytes(size);
8024                                break;
8025                            }
8026                        }
8027                    }
8028                } else {
8029                    Slog.w(TAG, "Metadata mismatch: package " + info.packageName
8030                            + " but widget data for " + pkg);
8031                }
8032            } else {
8033                Slog.w(TAG, "Unsupported metadata version " + version);
8034            }
8035        }
8036
8037        // Returns a policy constant; takes a buffer arg to reduce memory churn
8038        RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
8039                throws IOException {
8040            // Fail on suspiciously large manifest files
8041            if (info.size > 64 * 1024) {
8042                throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
8043            }
8044
8045            byte[] buffer = new byte[(int) info.size];
8046            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
8047                mBytes += info.size;
8048            } else throw new IOException("Unexpected EOF in manifest");
8049
8050            RestorePolicy policy = RestorePolicy.IGNORE;
8051            String[] str = new String[1];
8052            int offset = 0;
8053
8054            try {
8055                offset = extractLine(buffer, offset, str);
8056                int version = Integer.parseInt(str[0]);
8057                if (version == BACKUP_MANIFEST_VERSION) {
8058                    offset = extractLine(buffer, offset, str);
8059                    String manifestPackage = str[0];
8060                    // TODO: handle <original-package>
8061                    if (manifestPackage.equals(info.packageName)) {
8062                        offset = extractLine(buffer, offset, str);
8063                        version = Integer.parseInt(str[0]);  // app version
8064                        offset = extractLine(buffer, offset, str);
8065                        // This is the platform version, which we don't use, but we parse it
8066                        // as a safety against corruption in the manifest.
8067                        Integer.parseInt(str[0]);
8068                        offset = extractLine(buffer, offset, str);
8069                        info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
8070                        offset = extractLine(buffer, offset, str);
8071                        boolean hasApk = str[0].equals("1");
8072                        offset = extractLine(buffer, offset, str);
8073                        int numSigs = Integer.parseInt(str[0]);
8074                        if (numSigs > 0) {
8075                            Signature[] sigs = new Signature[numSigs];
8076                            for (int i = 0; i < numSigs; i++) {
8077                                offset = extractLine(buffer, offset, str);
8078                                sigs[i] = new Signature(str[0]);
8079                            }
8080                            mManifestSignatures.put(info.packageName, sigs);
8081
8082                            // Okay, got the manifest info we need...
8083                            try {
8084                                PackageInfo pkgInfo = mPackageManager.getPackageInfo(
8085                                        info.packageName, PackageManager.GET_SIGNATURES);
8086                                // Fall through to IGNORE if the app explicitly disallows backup
8087                                final int flags = pkgInfo.applicationInfo.flags;
8088                                if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
8089                                    // Restore system-uid-space packages only if they have
8090                                    // defined a custom backup agent
8091                                    if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
8092                                            || (pkgInfo.applicationInfo.backupAgentName != null)) {
8093                                        // Verify signatures against any installed version; if they
8094                                        // don't match, then we fall though and ignore the data.  The
8095                                        // signatureMatch() method explicitly ignores the signature
8096                                        // check for packages installed on the system partition, because
8097                                        // such packages are signed with the platform cert instead of
8098                                        // the app developer's cert, so they're different on every
8099                                        // device.
8100                                        if (signaturesMatch(sigs, pkgInfo)) {
8101                                            if ((pkgInfo.applicationInfo.flags
8102                                                    & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) != 0) {
8103                                                Slog.i(TAG, "Package has restoreAnyVersion; taking data");
8104                                                policy = RestorePolicy.ACCEPT;
8105                                            } else if (pkgInfo.versionCode >= version) {
8106                                                Slog.i(TAG, "Sig + version match; taking data");
8107                                                policy = RestorePolicy.ACCEPT;
8108                                            } else {
8109                                                // The data is from a newer version of the app than
8110                                                // is presently installed.  That means we can only
8111                                                // use it if the matching apk is also supplied.
8112                                                Slog.d(TAG, "Data version " + version
8113                                                        + " is newer than installed version "
8114                                                        + pkgInfo.versionCode + " - requiring apk");
8115                                                policy = RestorePolicy.ACCEPT_IF_APK;
8116                                            }
8117                                        } else {
8118                                            Slog.w(TAG, "Restore manifest signatures do not match "
8119                                                    + "installed application for " + info.packageName);
8120                                        }
8121                                    } else {
8122                                        Slog.w(TAG, "Package " + info.packageName
8123                                                + " is system level with no agent");
8124                                    }
8125                                } else {
8126                                    if (DEBUG) Slog.i(TAG, "Restore manifest from "
8127                                            + info.packageName + " but allowBackup=false");
8128                                }
8129                            } catch (NameNotFoundException e) {
8130                                // Okay, the target app isn't installed.  We can process
8131                                // the restore properly only if the dataset provides the
8132                                // apk file and we can successfully install it.
8133                                if (DEBUG) Slog.i(TAG, "Package " + info.packageName
8134                                        + " not installed; requiring apk in dataset");
8135                                policy = RestorePolicy.ACCEPT_IF_APK;
8136                            }
8137
8138                            if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
8139                                Slog.i(TAG, "Cannot restore package " + info.packageName
8140                                        + " without the matching .apk");
8141                            }
8142                        } else {
8143                            Slog.i(TAG, "Missing signature on backed-up package "
8144                                    + info.packageName);
8145                        }
8146                    } else {
8147                        Slog.i(TAG, "Expected package " + info.packageName
8148                                + " but restore manifest claims " + manifestPackage);
8149                    }
8150                } else {
8151                    Slog.i(TAG, "Unknown restore manifest version " + version
8152                            + " for package " + info.packageName);
8153                }
8154            } catch (NumberFormatException e) {
8155                Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
8156            } catch (IllegalArgumentException e) {
8157                Slog.w(TAG, e.getMessage());
8158            }
8159
8160            return policy;
8161        }
8162
8163        // Builds a line from a byte buffer starting at 'offset', and returns
8164        // the index of the next unconsumed data in the buffer.
8165        int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
8166            final int end = buffer.length;
8167            if (offset >= end) throw new IOException("Incomplete data");
8168
8169            int pos;
8170            for (pos = offset; pos < end; pos++) {
8171                byte c = buffer[pos];
8172                // at LF we declare end of line, and return the next char as the
8173                // starting point for the next time through
8174                if (c == '\n') {
8175                    break;
8176                }
8177            }
8178            outStr[0] = new String(buffer, offset, pos - offset);
8179            pos++;  // may be pointing an extra byte past the end but that's okay
8180            return pos;
8181        }
8182
8183        void dumpFileMetadata(FileMetadata info) {
8184            if (DEBUG) {
8185                StringBuilder b = new StringBuilder(128);
8186
8187                // mode string
8188                b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
8189                b.append(((info.mode & 0400) != 0) ? 'r' : '-');
8190                b.append(((info.mode & 0200) != 0) ? 'w' : '-');
8191                b.append(((info.mode & 0100) != 0) ? 'x' : '-');
8192                b.append(((info.mode & 0040) != 0) ? 'r' : '-');
8193                b.append(((info.mode & 0020) != 0) ? 'w' : '-');
8194                b.append(((info.mode & 0010) != 0) ? 'x' : '-');
8195                b.append(((info.mode & 0004) != 0) ? 'r' : '-');
8196                b.append(((info.mode & 0002) != 0) ? 'w' : '-');
8197                b.append(((info.mode & 0001) != 0) ? 'x' : '-');
8198                b.append(String.format(" %9d ", info.size));
8199
8200                Date stamp = new Date(info.mtime);
8201                b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp));
8202
8203                b.append(info.packageName);
8204                b.append(" :: ");
8205                b.append(info.domain);
8206                b.append(" :: ");
8207                b.append(info.path);
8208
8209                Slog.i(TAG, b.toString());
8210            }
8211        }
8212
8213        // Consume a tar file header block [sequence] and accumulate the relevant metadata
8214        FileMetadata readTarHeaders(InputStream instream) throws IOException {
8215            byte[] block = new byte[512];
8216            FileMetadata info = null;
8217
8218            boolean gotHeader = readTarHeader(instream, block);
8219            if (gotHeader) {
8220                try {
8221                    // okay, presume we're okay, and extract the various metadata
8222                    info = new FileMetadata();
8223                    info.size = extractRadix(block, 124, 12, 8);
8224                    info.mtime = extractRadix(block, 136, 12, 8);
8225                    info.mode = extractRadix(block, 100, 8, 8);
8226
8227                    info.path = extractString(block, 345, 155); // prefix
8228                    String path = extractString(block, 0, 100);
8229                    if (path.length() > 0) {
8230                        if (info.path.length() > 0) info.path += '/';
8231                        info.path += path;
8232                    }
8233
8234                    // tar link indicator field: 1 byte at offset 156 in the header.
8235                    int typeChar = block[156];
8236                    if (typeChar == 'x') {
8237                        // pax extended header, so we need to read that
8238                        gotHeader = readPaxExtendedHeader(instream, info);
8239                        if (gotHeader) {
8240                            // and after a pax extended header comes another real header -- read
8241                            // that to find the real file type
8242                            gotHeader = readTarHeader(instream, block);
8243                        }
8244                        if (!gotHeader) throw new IOException("Bad or missing pax header");
8245
8246                        typeChar = block[156];
8247                    }
8248
8249                    switch (typeChar) {
8250                        case '0': info.type = BackupAgent.TYPE_FILE; break;
8251                        case '5': {
8252                            info.type = BackupAgent.TYPE_DIRECTORY;
8253                            if (info.size != 0) {
8254                                Slog.w(TAG, "Directory entry with nonzero size in header");
8255                                info.size = 0;
8256                            }
8257                            break;
8258                        }
8259                        case 0: {
8260                            // presume EOF
8261                            if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
8262                            return null;
8263                        }
8264                        default: {
8265                            Slog.e(TAG, "Unknown tar entity type: " + typeChar);
8266                            throw new IOException("Unknown entity type " + typeChar);
8267                        }
8268                    }
8269
8270                    // Parse out the path
8271                    //
8272                    // first: apps/shared/unrecognized
8273                    if (FullBackup.SHARED_PREFIX.regionMatches(0,
8274                            info.path, 0, FullBackup.SHARED_PREFIX.length())) {
8275                        // File in shared storage.  !!! TODO: implement this.
8276                        info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
8277                        info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
8278                        info.domain = FullBackup.SHARED_STORAGE_TOKEN;
8279                        if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
8280                    } else if (FullBackup.APPS_PREFIX.regionMatches(0,
8281                            info.path, 0, FullBackup.APPS_PREFIX.length())) {
8282                        // App content!  Parse out the package name and domain
8283
8284                        // strip the apps/ prefix
8285                        info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
8286
8287                        // extract the package name
8288                        int slash = info.path.indexOf('/');
8289                        if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
8290                        info.packageName = info.path.substring(0, slash);
8291                        info.path = info.path.substring(slash+1);
8292
8293                        // if it's a manifest or metadata payload we're done, otherwise parse
8294                        // out the domain into which the file will be restored
8295                        if (!info.path.equals(BACKUP_MANIFEST_FILENAME)
8296                                && !info.path.equals(BACKUP_METADATA_FILENAME)) {
8297                            slash = info.path.indexOf('/');
8298                            if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
8299                            info.domain = info.path.substring(0, slash);
8300                            info.path = info.path.substring(slash + 1);
8301                        }
8302                    }
8303                } catch (IOException e) {
8304                    if (DEBUG) {
8305                        Slog.e(TAG, "Parse error in header: " + e.getMessage());
8306                        HEXLOG(block);
8307                    }
8308                    throw e;
8309                }
8310            }
8311            return info;
8312        }
8313
8314        private void HEXLOG(byte[] block) {
8315            int offset = 0;
8316            int todo = block.length;
8317            StringBuilder buf = new StringBuilder(64);
8318            while (todo > 0) {
8319                buf.append(String.format("%04x   ", offset));
8320                int numThisLine = (todo > 16) ? 16 : todo;
8321                for (int i = 0; i < numThisLine; i++) {
8322                    buf.append(String.format("%02x ", block[offset+i]));
8323                }
8324                Slog.i("hexdump", buf.toString());
8325                buf.setLength(0);
8326                todo -= numThisLine;
8327                offset += numThisLine;
8328            }
8329        }
8330
8331        // Read exactly the given number of bytes into a buffer at the stated offset.
8332        // Returns false if EOF is encountered before the requested number of bytes
8333        // could be read.
8334        int readExactly(InputStream in, byte[] buffer, int offset, int size)
8335                throws IOException {
8336            if (size <= 0) throw new IllegalArgumentException("size must be > 0");
8337
8338            int soFar = 0;
8339            while (soFar < size) {
8340                int nRead = in.read(buffer, offset + soFar, size - soFar);
8341                if (nRead <= 0) {
8342                    if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
8343                    break;
8344                }
8345                soFar += nRead;
8346            }
8347            return soFar;
8348        }
8349
8350        boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
8351            final int got = readExactly(instream, block, 0, 512);
8352            if (got == 0) return false;     // Clean EOF
8353            if (got < 512) throw new IOException("Unable to read full block header");
8354            mBytes += 512;
8355            return true;
8356        }
8357
8358        // overwrites 'info' fields based on the pax extended header
8359        boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
8360                throws IOException {
8361            // We should never see a pax extended header larger than this
8362            if (info.size > 32*1024) {
8363                Slog.w(TAG, "Suspiciously large pax header size " + info.size
8364                        + " - aborting");
8365                throw new IOException("Sanity failure: pax header size " + info.size);
8366            }
8367
8368            // read whole blocks, not just the content size
8369            int numBlocks = (int)((info.size + 511) >> 9);
8370            byte[] data = new byte[numBlocks * 512];
8371            if (readExactly(instream, data, 0, data.length) < data.length) {
8372                throw new IOException("Unable to read full pax header");
8373            }
8374            mBytes += data.length;
8375
8376            final int contentSize = (int) info.size;
8377            int offset = 0;
8378            do {
8379                // extract the line at 'offset'
8380                int eol = offset+1;
8381                while (eol < contentSize && data[eol] != ' ') eol++;
8382                if (eol >= contentSize) {
8383                    // error: we just hit EOD looking for the end of the size field
8384                    throw new IOException("Invalid pax data");
8385                }
8386                // eol points to the space between the count and the key
8387                int linelen = (int) extractRadix(data, offset, eol - offset, 10);
8388                int key = eol + 1;  // start of key=value
8389                eol = offset + linelen - 1; // trailing LF
8390                int value;
8391                for (value = key+1; data[value] != '=' && value <= eol; value++);
8392                if (value > eol) {
8393                    throw new IOException("Invalid pax declaration");
8394                }
8395
8396                // pax requires that key/value strings be in UTF-8
8397                String keyStr = new String(data, key, value-key, "UTF-8");
8398                // -1 to strip the trailing LF
8399                String valStr = new String(data, value+1, eol-value-1, "UTF-8");
8400
8401                if ("path".equals(keyStr)) {
8402                    info.path = valStr;
8403                } else if ("size".equals(keyStr)) {
8404                    info.size = Long.parseLong(valStr);
8405                } else {
8406                    if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
8407                }
8408
8409                offset += linelen;
8410            } while (offset < contentSize);
8411
8412            return true;
8413        }
8414
8415        long extractRadix(byte[] data, int offset, int maxChars, int radix)
8416                throws IOException {
8417            long value = 0;
8418            final int end = offset + maxChars;
8419            for (int i = offset; i < end; i++) {
8420                final byte b = data[i];
8421                // Numeric fields in tar can terminate with either NUL or SPC
8422                if (b == 0 || b == ' ') break;
8423                if (b < '0' || b > ('0' + radix - 1)) {
8424                    throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
8425                }
8426                value = radix * value + (b - '0');
8427            }
8428            return value;
8429        }
8430
8431        String extractString(byte[] data, int offset, int maxChars) throws IOException {
8432            final int end = offset + maxChars;
8433            int eos = offset;
8434            // tar string fields terminate early with a NUL
8435            while (eos < end && data[eos] != 0) eos++;
8436            return new String(data, offset, eos-offset, "US-ASCII");
8437        }
8438
8439        void sendStartRestore() {
8440            if (mObserver != null) {
8441                try {
8442                    mObserver.onStartRestore();
8443                } catch (RemoteException e) {
8444                    Slog.w(TAG, "full restore observer went away: startRestore");
8445                    mObserver = null;
8446                }
8447            }
8448        }
8449
8450        void sendOnRestorePackage(String name) {
8451            if (mObserver != null) {
8452                try {
8453                    // TODO: use a more user-friendly name string
8454                    mObserver.onRestorePackage(name);
8455                } catch (RemoteException e) {
8456                    Slog.w(TAG, "full restore observer went away: restorePackage");
8457                    mObserver = null;
8458                }
8459            }
8460        }
8461
8462        void sendEndRestore() {
8463            if (mObserver != null) {
8464                try {
8465                    mObserver.onEndRestore();
8466                } catch (RemoteException e) {
8467                    Slog.w(TAG, "full restore observer went away: endRestore");
8468                    mObserver = null;
8469                }
8470            }
8471        }
8472    }
8473
8474    // ----- Restore handling -----
8475
8476    // Old style: directly match the stored vs on device signature blocks
8477    static boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
8478        if (target == null) {
8479            return false;
8480        }
8481
8482        // If the target resides on the system partition, we allow it to restore
8483        // data from the like-named package in a restore set even if the signatures
8484        // do not match.  (Unlike general applications, those flashed to the system
8485        // partition will be signed with the device's platform certificate, so on
8486        // different phones the same system app will have different signatures.)
8487        if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8488            if (MORE_DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
8489            return true;
8490        }
8491
8492        // Allow unsigned apps, but not signed on one device and unsigned on the other
8493        // !!! TODO: is this the right policy?
8494        Signature[] deviceSigs = target.signatures;
8495        if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
8496                + " device=" + deviceSigs);
8497        if ((storedSigs == null || storedSigs.length == 0)
8498                && (deviceSigs == null || deviceSigs.length == 0)) {
8499            return true;
8500        }
8501        if (storedSigs == null || deviceSigs == null) {
8502            return false;
8503        }
8504
8505        // !!! TODO: this demands that every stored signature match one
8506        // that is present on device, and does not demand the converse.
8507        // Is this this right policy?
8508        int nStored = storedSigs.length;
8509        int nDevice = deviceSigs.length;
8510
8511        for (int i=0; i < nStored; i++) {
8512            boolean match = false;
8513            for (int j=0; j < nDevice; j++) {
8514                if (storedSigs[i].equals(deviceSigs[j])) {
8515                    match = true;
8516                    break;
8517                }
8518            }
8519            if (!match) {
8520                return false;
8521            }
8522        }
8523        return true;
8524    }
8525
8526    // Used by both incremental and full restore
8527    void restoreWidgetData(String packageName, byte[] widgetData) {
8528        // Apply the restored widget state and generate the ID update for the app
8529        // TODO: http://b/22388012
8530        if (MORE_DEBUG) {
8531            Slog.i(TAG, "Incorporating restored widget data");
8532        }
8533        AppWidgetBackupBridge.restoreWidgetState(packageName, widgetData, UserHandle.USER_SYSTEM);
8534    }
8535
8536    // *****************************
8537    // NEW UNIFIED RESTORE IMPLEMENTATION
8538    // *****************************
8539
8540    // states of the unified-restore state machine
8541    enum UnifiedRestoreState {
8542        INITIAL,
8543        RUNNING_QUEUE,
8544        RESTORE_KEYVALUE,
8545        RESTORE_FULL,
8546        RESTORE_FINISHED,
8547        FINAL
8548    }
8549
8550    class PerformUnifiedRestoreTask implements BackupRestoreTask {
8551        // Transport we're working with to do the restore
8552        private IBackupTransport mTransport;
8553
8554        // Where per-transport saved state goes
8555        File mStateDir;
8556
8557        // Restore observer; may be null
8558        private IRestoreObserver mObserver;
8559
8560        // BackuoManagerMonitor; may be null
8561        private IBackupManagerMonitor mMonitor;
8562
8563        // Token identifying the dataset to the transport
8564        private long mToken;
8565
8566        // When this is a restore-during-install, this is the token identifying the
8567        // operation to the Package Manager, and we must ensure that we let it know
8568        // when we're finished.
8569        private int mPmToken;
8570
8571        // When this is restore-during-install, we need to tell the package manager
8572        // whether we actually launched the app, because this affects notifications
8573        // around externally-visible state transitions.
8574        private boolean mDidLaunch;
8575
8576        // Is this a whole-system restore, i.e. are we establishing a new ancestral
8577        // dataset to base future restore-at-install operations from?
8578        private boolean mIsSystemRestore;
8579
8580        // If this is a single-package restore, what package are we interested in?
8581        private PackageInfo mTargetPackage;
8582
8583        // In all cases, the calculated list of packages that we are trying to restore
8584        private List<PackageInfo> mAcceptSet;
8585
8586        // Our bookkeeping about the ancestral dataset
8587        private PackageManagerBackupAgent mPmAgent;
8588
8589        // Currently-bound backup agent for restore + restoreFinished purposes
8590        private IBackupAgent mAgent;
8591
8592        // What sort of restore we're doing now
8593        private RestoreDescription mRestoreDescription;
8594
8595        // The package we're currently restoring
8596        private PackageInfo mCurrentPackage;
8597
8598        // Widget-related data handled as part of this restore operation
8599        private byte[] mWidgetData;
8600
8601        // Number of apps restored in this pass
8602        private int mCount;
8603
8604        // When did we start?
8605        private long mStartRealtime;
8606
8607        // State machine progress
8608        private UnifiedRestoreState mState;
8609
8610        // How are things going?
8611        private int mStatus;
8612
8613        // Done?
8614        private boolean mFinished;
8615
8616        // Key/value: bookkeeping about staged data and files for agent access
8617        private File mBackupDataName;
8618        private File mStageName;
8619        private File mSavedStateName;
8620        private File mNewStateName;
8621        ParcelFileDescriptor mBackupData;
8622        ParcelFileDescriptor mNewState;
8623
8624        private final int mEphemeralOpToken;
8625
8626        // Invariant: mWakelock is already held, and this task is responsible for
8627        // releasing it at the end of the restore operation.
8628        PerformUnifiedRestoreTask(IBackupTransport transport, IRestoreObserver observer,
8629                IBackupManagerMonitor monitor, long restoreSetToken, PackageInfo targetPackage,
8630                int pmToken, boolean isFullSystemRestore, String[] filterSet) {
8631            mEphemeralOpToken = generateRandomIntegerToken();
8632            mState = UnifiedRestoreState.INITIAL;
8633            mStartRealtime = SystemClock.elapsedRealtime();
8634
8635            mTransport = transport;
8636            mObserver = observer;
8637            mMonitor = monitor;
8638            mToken = restoreSetToken;
8639            mPmToken = pmToken;
8640            mTargetPackage = targetPackage;
8641            mIsSystemRestore = isFullSystemRestore;
8642            mFinished = false;
8643            mDidLaunch = false;
8644
8645            if (targetPackage != null) {
8646                // Single package restore
8647                mAcceptSet = new ArrayList<PackageInfo>();
8648                mAcceptSet.add(targetPackage);
8649            } else {
8650                // Everything possible, or a target set
8651                if (filterSet == null) {
8652                    // We want everything and a pony
8653                    List<PackageInfo> apps =
8654                            PackageManagerBackupAgent.getStorableApplications(mPackageManager);
8655                    filterSet = packagesToNames(apps);
8656                    if (DEBUG) {
8657                        Slog.i(TAG, "Full restore; asking about " + filterSet.length + " apps");
8658                    }
8659                }
8660
8661                mAcceptSet = new ArrayList<PackageInfo>(filterSet.length);
8662
8663                // Pro tem, we insist on moving the settings provider package to last place.
8664                // Keep track of whether it's in the list, and bump it down if so.  We also
8665                // want to do the system package itself first if it's called for.
8666                boolean hasSystem = false;
8667                boolean hasSettings = false;
8668                for (int i = 0; i < filterSet.length; i++) {
8669                    try {
8670                        PackageInfo info = mPackageManager.getPackageInfo(filterSet[i], 0);
8671                        if ("android".equals(info.packageName)) {
8672                            hasSystem = true;
8673                            continue;
8674                        }
8675                        if (SETTINGS_PACKAGE.equals(info.packageName)) {
8676                            hasSettings = true;
8677                            continue;
8678                        }
8679
8680                        if (appIsEligibleForBackup(info.applicationInfo, mPackageManager)) {
8681                            mAcceptSet.add(info);
8682                        }
8683                    } catch (NameNotFoundException e) {
8684                        // requested package name doesn't exist; ignore it
8685                    }
8686                }
8687                if (hasSystem) {
8688                    try {
8689                        mAcceptSet.add(0, mPackageManager.getPackageInfo("android", 0));
8690                    } catch (NameNotFoundException e) {
8691                        // won't happen; we know a priori that it's valid
8692                    }
8693                }
8694                if (hasSettings) {
8695                    try {
8696                        mAcceptSet.add(mPackageManager.getPackageInfo(SETTINGS_PACKAGE, 0));
8697                    } catch (NameNotFoundException e) {
8698                        // this one is always valid too
8699                    }
8700                }
8701            }
8702
8703            if (MORE_DEBUG) {
8704                Slog.v(TAG, "Restore; accept set size is " + mAcceptSet.size());
8705                for (PackageInfo info : mAcceptSet) {
8706                    Slog.v(TAG, "   " + info.packageName);
8707                }
8708            }
8709        }
8710
8711        private String[] packagesToNames(List<PackageInfo> apps) {
8712            final int N = apps.size();
8713            String[] names = new String[N];
8714            for (int i = 0; i < N; i++) {
8715                names[i] = apps.get(i).packageName;
8716            }
8717            return names;
8718        }
8719
8720        // Execute one tick of whatever state machine the task implements
8721        @Override
8722        public void execute() {
8723            if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step " + mState);
8724            switch (mState) {
8725                case INITIAL:
8726                    startRestore();
8727                    break;
8728
8729                case RUNNING_QUEUE:
8730                    dispatchNextRestore();
8731                    break;
8732
8733                case RESTORE_KEYVALUE:
8734                    restoreKeyValue();
8735                    break;
8736
8737                case RESTORE_FULL:
8738                    restoreFull();
8739                    break;
8740
8741                case RESTORE_FINISHED:
8742                    restoreFinished();
8743                    break;
8744
8745                case FINAL:
8746                    if (!mFinished) finalizeRestore();
8747                    else {
8748                        Slog.e(TAG, "Duplicate finish");
8749                    }
8750                    mFinished = true;
8751                    break;
8752            }
8753        }
8754
8755        /*
8756         * SKETCH OF OPERATION
8757         *
8758         * create one of these PerformUnifiedRestoreTask objects, telling it which
8759         * dataset & transport to address, and then parameters within the restore
8760         * operation: single target package vs many, etc.
8761         *
8762         * 1. transport.startRestore(token, list-of-packages).  If we need @pm@  it is
8763         * always placed first and the settings provider always placed last [for now].
8764         *
8765         * 1a [if we needed @pm@ then nextRestorePackage() and restore the PMBA inline]
8766         *
8767         *   [ state change => RUNNING_QUEUE ]
8768         *
8769         * NOW ITERATE:
8770         *
8771         * { 3. t.nextRestorePackage()
8772         *   4. does the metadata for this package allow us to restore it?
8773         *      does the on-disk app permit us to restore it? [re-check allowBackup etc]
8774         *   5. is this a key/value dataset?  => key/value agent restore
8775         *       [ state change => RESTORE_KEYVALUE ]
8776         *       5a. spin up agent
8777         *       5b. t.getRestoreData() to stage it properly
8778         *       5c. call into agent to perform restore
8779         *       5d. tear down agent
8780         *       [ state change => RUNNING_QUEUE ]
8781         *
8782         *   6. else it's a stream dataset:
8783         *       [ state change => RESTORE_FULL ]
8784         *       6a. instantiate the engine for a stream restore: engine handles agent lifecycles
8785         *       6b. spin off engine runner on separate thread
8786         *       6c. ITERATE getNextFullRestoreDataChunk() and copy data to engine runner socket
8787         *       [ state change => RUNNING_QUEUE ]
8788         * }
8789         *
8790         *   [ state change => FINAL ]
8791         *
8792         * 7. t.finishRestore(), release wakelock, etc.
8793         *
8794         *
8795         */
8796
8797        // state INITIAL : set up for the restore and read the metadata if necessary
8798        private  void startRestore() {
8799            sendStartRestore(mAcceptSet.size());
8800
8801            // If we're starting a full-system restore, set up to begin widget ID remapping
8802            if (mIsSystemRestore) {
8803                // TODO: http://b/22388012
8804                AppWidgetBackupBridge.restoreStarting(UserHandle.USER_SYSTEM);
8805            }
8806
8807            try {
8808                String transportDir = mTransport.transportDirName();
8809                mStateDir = new File(mBaseStateDir, transportDir);
8810
8811                // Fetch the current metadata from the dataset first
8812                PackageInfo pmPackage = new PackageInfo();
8813                pmPackage.packageName = PACKAGE_MANAGER_SENTINEL;
8814                mAcceptSet.add(0, pmPackage);
8815
8816                PackageInfo[] packages = mAcceptSet.toArray(new PackageInfo[0]);
8817                mStatus = mTransport.startRestore(mToken, packages);
8818                if (mStatus != BackupTransport.TRANSPORT_OK) {
8819                    Slog.e(TAG, "Transport error " + mStatus + "; no restore possible");
8820                    mStatus = BackupTransport.TRANSPORT_ERROR;
8821                    executeNextState(UnifiedRestoreState.FINAL);
8822                    return;
8823                }
8824
8825                RestoreDescription desc = mTransport.nextRestorePackage();
8826                if (desc == null) {
8827                    Slog.e(TAG, "No restore metadata available; halting");
8828                    mMonitor = monitorEvent(mMonitor,
8829                            BackupManagerMonitor.LOG_EVENT_ID_NO_RESTORE_METADATA_AVAILABLE,
8830                            mCurrentPackage,
8831                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
8832                    mStatus = BackupTransport.TRANSPORT_ERROR;
8833                    executeNextState(UnifiedRestoreState.FINAL);
8834                    return;
8835                }
8836                if (!PACKAGE_MANAGER_SENTINEL.equals(desc.getPackageName())) {
8837                    Slog.e(TAG, "Required package metadata but got "
8838                            + desc.getPackageName());
8839                    mMonitor = monitorEvent(mMonitor,
8840                            BackupManagerMonitor.LOG_EVENT_ID_NO_PM_METADATA_RECEIVED,
8841                            mCurrentPackage,
8842                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
8843                    mStatus = BackupTransport.TRANSPORT_ERROR;
8844                    executeNextState(UnifiedRestoreState.FINAL);
8845                    return;
8846                }
8847
8848                // Pull the Package Manager metadata from the restore set first
8849                mCurrentPackage = new PackageInfo();
8850                mCurrentPackage.packageName = PACKAGE_MANAGER_SENTINEL;
8851                mPmAgent = makeMetadataAgent(null);
8852                mAgent = IBackupAgent.Stub.asInterface(mPmAgent.onBind());
8853                if (MORE_DEBUG) {
8854                    Slog.v(TAG, "initiating restore for PMBA");
8855                }
8856                initiateOneRestore(mCurrentPackage, 0);
8857                // The PM agent called operationComplete() already, because our invocation
8858                // of it is process-local and therefore synchronous.  That means that the
8859                // next-state message (RUNNING_QUEUE) is already enqueued.  Only if we're
8860                // unable to proceed with running the queue do we remove that pending
8861                // message and jump straight to the FINAL state.  Because this was
8862                // synchronous we also know that we should cancel the pending timeout
8863                // message.
8864                mBackupHandler.removeMessages(MSG_RESTORE_OPERATION_TIMEOUT);
8865
8866                // Verify that the backup set includes metadata.  If not, we can't do
8867                // signature/version verification etc, so we simply do not proceed with
8868                // the restore operation.
8869                if (!mPmAgent.hasMetadata()) {
8870                    Slog.e(TAG, "PM agent has no metadata, so not restoring");
8871                    mMonitor = monitorEvent(mMonitor,
8872                            BackupManagerMonitor.LOG_EVENT_ID_PM_AGENT_HAS_NO_METADATA,
8873                            mCurrentPackage,
8874                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
8875                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
8876                            PACKAGE_MANAGER_SENTINEL,
8877                            "Package manager restore metadata missing");
8878                    mStatus = BackupTransport.TRANSPORT_ERROR;
8879                    mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
8880                    executeNextState(UnifiedRestoreState.FINAL);
8881                    return;
8882                }
8883
8884                // Success; cache the metadata and continue as expected with the
8885                // next state already enqueued
8886
8887            } catch (Exception e) {
8888                // If we lost the transport at any time, halt
8889                Slog.e(TAG, "Unable to contact transport for restore: " + e.getMessage());
8890                mMonitor = monitorEvent(mMonitor,
8891                        BackupManagerMonitor.LOG_EVENT_ID_LOST_TRANSPORT,
8892                        null,
8893                        BackupManagerMonitor.LOG_EVENT_CATEGORY_TRANSPORT, null);
8894                mStatus = BackupTransport.TRANSPORT_ERROR;
8895                mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
8896                executeNextState(UnifiedRestoreState.FINAL);
8897                return;
8898            }
8899        }
8900
8901        // state RUNNING_QUEUE : figure out what the next thing to be restored is,
8902        // and fire the appropriate next step
8903        private void dispatchNextRestore() {
8904            UnifiedRestoreState nextState = UnifiedRestoreState.FINAL;
8905            try {
8906                mRestoreDescription = mTransport.nextRestorePackage();
8907                final String pkgName = (mRestoreDescription != null)
8908                        ? mRestoreDescription.getPackageName() : null;
8909                if (pkgName == null) {
8910                    Slog.e(TAG, "Failure getting next package name");
8911                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
8912                    nextState = UnifiedRestoreState.FINAL;
8913                    return;
8914                } else if (mRestoreDescription == RestoreDescription.NO_MORE_PACKAGES) {
8915                    // Yay we've reached the end cleanly
8916                    if (DEBUG) {
8917                        Slog.v(TAG, "No more packages; finishing restore");
8918                    }
8919                    int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
8920                    EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
8921                    nextState = UnifiedRestoreState.FINAL;
8922                    return;
8923                }
8924
8925                if (DEBUG) {
8926                    Slog.i(TAG, "Next restore package: " + mRestoreDescription);
8927                }
8928                sendOnRestorePackage(pkgName);
8929
8930                Metadata metaInfo = mPmAgent.getRestoredMetadata(pkgName);
8931                if (metaInfo == null) {
8932                    Slog.e(TAG, "No metadata for " + pkgName);
8933                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, pkgName,
8934                            "Package metadata missing");
8935                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
8936                    return;
8937                }
8938
8939                try {
8940                    mCurrentPackage = mPackageManager.getPackageInfo(
8941                            pkgName, PackageManager.GET_SIGNATURES);
8942                } catch (NameNotFoundException e) {
8943                    // Whoops, we thought we could restore this package but it
8944                    // turns out not to be present.  Skip it.
8945                    Slog.e(TAG, "Package not present: " + pkgName);
8946                    mMonitor = monitorEvent(mMonitor,
8947                            BackupManagerMonitor.LOG_EVENT_ID_PACKAGE_NOT_PRESENT,
8948                            mCurrentPackage,
8949                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
8950                            null);
8951                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, pkgName,
8952                            "Package missing on device");
8953                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
8954                    return;
8955                }
8956
8957                if (metaInfo.versionCode > mCurrentPackage.versionCode) {
8958                    // Data is from a "newer" version of the app than we have currently
8959                    // installed.  If the app has not declared that it is prepared to
8960                    // handle this case, we do not attempt the restore.
8961                    if ((mCurrentPackage.applicationInfo.flags
8962                            & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
8963                        String message = "Source version " + metaInfo.versionCode
8964                                + " > installed version " + mCurrentPackage.versionCode;
8965                        Slog.w(TAG, "Package " + pkgName + ": " + message);
8966                        Bundle monitoringExtras = putMonitoringExtra(null,
8967                                BackupManagerMonitor.EXTRA_LOG_RESTORE_VERSION,
8968                                metaInfo.versionCode);
8969                        monitoringExtras = putMonitoringExtra(monitoringExtras,
8970                                BackupManagerMonitor.EXTRA_LOG_RESTORE_ANYWAY, false);
8971                        mMonitor = monitorEvent(mMonitor,
8972                                BackupManagerMonitor.LOG_EVENT_ID_RESTORE_VERSION_HIGHER,
8973                                mCurrentPackage,
8974                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
8975                                monitoringExtras);
8976                        EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
8977                                pkgName, message);
8978                        nextState = UnifiedRestoreState.RUNNING_QUEUE;
8979                        return;
8980                    } else {
8981                        if (DEBUG) Slog.v(TAG, "Source version " + metaInfo.versionCode
8982                                + " > installed version " + mCurrentPackage.versionCode
8983                                + " but restoreAnyVersion");
8984                        Bundle monitoringExtras = putMonitoringExtra(null,
8985                                BackupManagerMonitor.EXTRA_LOG_RESTORE_VERSION,
8986                                metaInfo.versionCode);
8987                        monitoringExtras = putMonitoringExtra(monitoringExtras,
8988                                BackupManagerMonitor.EXTRA_LOG_RESTORE_ANYWAY, true);
8989                        mMonitor = monitorEvent(mMonitor,
8990                                BackupManagerMonitor.LOG_EVENT_ID_RESTORE_VERSION_HIGHER,
8991                                mCurrentPackage,
8992                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
8993                                monitoringExtras);
8994                    }
8995                }
8996
8997                if (MORE_DEBUG) Slog.v(TAG, "Package " + pkgName
8998                        + " restore version [" + metaInfo.versionCode
8999                        + "] is compatible with installed version ["
9000                        + mCurrentPackage.versionCode + "]");
9001
9002                // Reset per-package preconditions and fire the appropriate next state
9003                mWidgetData = null;
9004                final int type = mRestoreDescription.getDataType();
9005                if (type == RestoreDescription.TYPE_KEY_VALUE) {
9006                    nextState = UnifiedRestoreState.RESTORE_KEYVALUE;
9007                } else if (type == RestoreDescription.TYPE_FULL_STREAM) {
9008                    nextState = UnifiedRestoreState.RESTORE_FULL;
9009                } else {
9010                    // Unknown restore type; ignore this package and move on
9011                    Slog.e(TAG, "Unrecognized restore type " + type);
9012                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
9013                    return;
9014                }
9015            } catch (Exception e) {
9016                Slog.e(TAG, "Can't get next restore target from transport; halting: "
9017                        + e.getMessage());
9018                EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
9019                nextState = UnifiedRestoreState.FINAL;
9020                return;
9021            } finally {
9022                executeNextState(nextState);
9023            }
9024        }
9025
9026        // state RESTORE_KEYVALUE : restore one package via key/value API set
9027        private void restoreKeyValue() {
9028            // Initiating the restore will pass responsibility for the state machine's
9029            // progress to the agent callback, so we do not always execute the
9030            // next state here.
9031            final String packageName = mCurrentPackage.packageName;
9032            // Validate some semantic requirements that apply in this way
9033            // only to the key/value restore API flow
9034            if (mCurrentPackage.applicationInfo.backupAgentName == null
9035                    || "".equals(mCurrentPackage.applicationInfo.backupAgentName)) {
9036                if (MORE_DEBUG) {
9037                    Slog.i(TAG, "Data exists for package " + packageName
9038                            + " but app has no agent; skipping");
9039                }
9040                mMonitor = monitorEvent(mMonitor,
9041                        BackupManagerMonitor.LOG_EVENT_ID_APP_HAS_NO_AGENT, mCurrentPackage,
9042                        BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT, null);
9043                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
9044                        "Package has no agent");
9045                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9046                return;
9047            }
9048
9049            Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
9050            if (!BackupUtils.signaturesMatch(metaInfo.sigHashes, mCurrentPackage)) {
9051                Slog.w(TAG, "Signature mismatch restoring " + packageName);
9052                mMonitor = monitorEvent(mMonitor,
9053                        BackupManagerMonitor.LOG_EVENT_ID_SIGNATURE_MISMATCH, mCurrentPackage,
9054                        BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
9055                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
9056                        "Signature mismatch");
9057                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9058                return;
9059            }
9060
9061            // Good to go!  Set up and bind the agent...
9062            mAgent = bindToAgentSynchronous(
9063                    mCurrentPackage.applicationInfo,
9064                    ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL);
9065            if (mAgent == null) {
9066                Slog.w(TAG, "Can't find backup agent for " + packageName);
9067                mMonitor = monitorEvent(mMonitor,
9068                        BackupManagerMonitor.LOG_EVENT_ID_CANT_FIND_AGENT, mCurrentPackage,
9069                        BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
9070                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
9071                        "Restore agent missing");
9072                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9073                return;
9074            }
9075
9076            // Whatever happens next, we've launched the target app now; remember that.
9077            mDidLaunch = true;
9078
9079            // And then finally start the restore on this agent
9080            try {
9081                initiateOneRestore(mCurrentPackage, metaInfo.versionCode);
9082                ++mCount;
9083            } catch (Exception e) {
9084                Slog.e(TAG, "Error when attempting restore: " + e.toString());
9085                keyValueAgentErrorCleanup();
9086                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9087            }
9088        }
9089
9090        // Guts of a key/value restore operation
9091        void initiateOneRestore(PackageInfo app, int appVersionCode) {
9092            final String packageName = app.packageName;
9093
9094            if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
9095
9096            // !!! TODO: get the dirs from the transport
9097            mBackupDataName = new File(mDataDir, packageName + ".restore");
9098            mStageName = new File(mDataDir, packageName + ".stage");
9099            mNewStateName = new File(mStateDir, packageName + ".new");
9100            mSavedStateName = new File(mStateDir, packageName);
9101
9102            // don't stage the 'android' package where the wallpaper data lives.  this is
9103            // an optimization: we know there's no widget data hosted/published by that
9104            // package, and this way we avoid doing a spurious copy of MB-sized wallpaper
9105            // data following the download.
9106            boolean staging = !packageName.equals("android");
9107            ParcelFileDescriptor stage;
9108            File downloadFile = (staging) ? mStageName : mBackupDataName;
9109
9110            try {
9111                // Run the transport's restore pass
9112                stage = ParcelFileDescriptor.open(downloadFile,
9113                        ParcelFileDescriptor.MODE_READ_WRITE |
9114                        ParcelFileDescriptor.MODE_CREATE |
9115                        ParcelFileDescriptor.MODE_TRUNCATE);
9116
9117                if (mTransport.getRestoreData(stage) != BackupTransport.TRANSPORT_OK) {
9118                    // Transport-level failure, so we wind everything up and
9119                    // terminate the restore operation.
9120                    Slog.e(TAG, "Error getting restore data for " + packageName);
9121                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
9122                    stage.close();
9123                    downloadFile.delete();
9124                    executeNextState(UnifiedRestoreState.FINAL);
9125                    return;
9126                }
9127
9128                // We have the data from the transport. Now we extract and strip
9129                // any per-package metadata (typically widget-related information)
9130                // if appropriate
9131                if (staging) {
9132                    stage.close();
9133                    stage = ParcelFileDescriptor.open(downloadFile,
9134                            ParcelFileDescriptor.MODE_READ_ONLY);
9135
9136                    mBackupData = ParcelFileDescriptor.open(mBackupDataName,
9137                            ParcelFileDescriptor.MODE_READ_WRITE |
9138                            ParcelFileDescriptor.MODE_CREATE |
9139                            ParcelFileDescriptor.MODE_TRUNCATE);
9140
9141                    BackupDataInput in = new BackupDataInput(stage.getFileDescriptor());
9142                    BackupDataOutput out = new BackupDataOutput(mBackupData.getFileDescriptor());
9143                    byte[] buffer = new byte[8192]; // will grow when needed
9144                    while (in.readNextHeader()) {
9145                        final String key = in.getKey();
9146                        final int size = in.getDataSize();
9147
9148                        // is this a special key?
9149                        if (key.equals(KEY_WIDGET_STATE)) {
9150                            if (DEBUG) {
9151                                Slog.i(TAG, "Restoring widget state for " + packageName);
9152                            }
9153                            mWidgetData = new byte[size];
9154                            in.readEntityData(mWidgetData, 0, size);
9155                        } else {
9156                            if (size > buffer.length) {
9157                                buffer = new byte[size];
9158                            }
9159                            in.readEntityData(buffer, 0, size);
9160                            out.writeEntityHeader(key, size);
9161                            out.writeEntityData(buffer, size);
9162                        }
9163                    }
9164
9165                    mBackupData.close();
9166                }
9167
9168                // Okay, we have the data.  Now have the agent do the restore.
9169                stage.close();
9170
9171                mBackupData = ParcelFileDescriptor.open(mBackupDataName,
9172                        ParcelFileDescriptor.MODE_READ_ONLY);
9173
9174                mNewState = ParcelFileDescriptor.open(mNewStateName,
9175                        ParcelFileDescriptor.MODE_READ_WRITE |
9176                        ParcelFileDescriptor.MODE_CREATE |
9177                        ParcelFileDescriptor.MODE_TRUNCATE);
9178
9179                // Kick off the restore, checking for hung agents.  The timeout or
9180                // the operationComplete() callback will schedule the next step,
9181                // so we do not do that here.
9182                prepareOperationTimeout(mEphemeralOpToken, TIMEOUT_RESTORE_INTERVAL,
9183                        this, OP_TYPE_RESTORE_WAIT);
9184                mAgent.doRestore(mBackupData, appVersionCode, mNewState,
9185                        mEphemeralOpToken, mBackupManagerBinder);
9186            } catch (Exception e) {
9187                Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
9188                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
9189                        packageName, e.toString());
9190                keyValueAgentErrorCleanup();    // clears any pending timeout messages as well
9191
9192                // After a restore failure we go back to running the queue.  If there
9193                // are no more packages to be restored that will be handled by the
9194                // next step.
9195                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9196            }
9197        }
9198
9199        // state RESTORE_FULL : restore one package via streaming engine
9200        private void restoreFull() {
9201            // None of this can run on the work looper here, so we spin asynchronous
9202            // work like this:
9203            //
9204            //   StreamFeederThread: read data from mTransport.getNextFullRestoreDataChunk()
9205            //                       write it into the pipe to the engine
9206            //   EngineThread: FullRestoreEngine thread communicating with the target app
9207            //
9208            // When finished, StreamFeederThread executes next state as appropriate on the
9209            // backup looper, and the overall unified restore task resumes
9210            try {
9211                StreamFeederThread feeder = new StreamFeederThread();
9212                if (MORE_DEBUG) {
9213                    Slog.i(TAG, "Spinning threads for stream restore of "
9214                            + mCurrentPackage.packageName);
9215                }
9216                new Thread(feeder, "unified-stream-feeder").start();
9217
9218                // At this point the feeder is responsible for advancing the restore
9219                // state, so we're done here.
9220            } catch (IOException e) {
9221                // Unable to instantiate the feeder thread -- we need to bail on the
9222                // current target.  We haven't asked the transport for data yet, though,
9223                // so we can do that simply by going back to running the restore queue.
9224                Slog.e(TAG, "Unable to construct pipes for stream restore!");
9225                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9226            }
9227        }
9228
9229        // state RESTORE_FINISHED : provide the "no more data" signpost callback at the end
9230        private void restoreFinished() {
9231            if (DEBUG) {
9232                Slog.d(TAG, "restoreFinished packageName=" + mCurrentPackage.packageName);
9233            }
9234            try {
9235                prepareOperationTimeout(mEphemeralOpToken, TIMEOUT_RESTORE_FINISHED_INTERVAL, this,
9236                        OP_TYPE_RESTORE_WAIT);
9237                mAgent.doRestoreFinished(mEphemeralOpToken, mBackupManagerBinder);
9238                // If we get this far, the callback or timeout will schedule the
9239                // next restore state, so we're done
9240            } catch (Exception e) {
9241                final String packageName = mCurrentPackage.packageName;
9242                Slog.e(TAG, "Unable to finalize restore of " + packageName);
9243                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
9244                        packageName, e.toString());
9245                keyValueAgentErrorCleanup();
9246                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9247            }
9248        }
9249
9250        class StreamFeederThread extends RestoreEngine implements Runnable, BackupRestoreTask {
9251            final String TAG = "StreamFeederThread";
9252            FullRestoreEngine mEngine;
9253            EngineThread mEngineThread;
9254
9255            // pipe through which we read data from the transport. [0] read, [1] write
9256            ParcelFileDescriptor[] mTransportPipes;
9257
9258            // pipe through which the engine will read data.  [0] read, [1] write
9259            ParcelFileDescriptor[] mEnginePipes;
9260
9261            private final int mEphemeralOpToken;
9262
9263            public StreamFeederThread() throws IOException {
9264                mEphemeralOpToken = generateRandomIntegerToken();
9265                mTransportPipes = ParcelFileDescriptor.createPipe();
9266                mEnginePipes = ParcelFileDescriptor.createPipe();
9267                setRunning(true);
9268            }
9269
9270            @Override
9271            public void run() {
9272                UnifiedRestoreState nextState = UnifiedRestoreState.RUNNING_QUEUE;
9273                int status = BackupTransport.TRANSPORT_OK;
9274
9275                EventLog.writeEvent(EventLogTags.FULL_RESTORE_PACKAGE,
9276                        mCurrentPackage.packageName);
9277
9278                mEngine = new FullRestoreEngine(this, null, mMonitor, mCurrentPackage, false, false, mEphemeralOpToken);
9279                mEngineThread = new EngineThread(mEngine, mEnginePipes[0]);
9280
9281                ParcelFileDescriptor eWriteEnd = mEnginePipes[1];
9282                ParcelFileDescriptor tReadEnd = mTransportPipes[0];
9283                ParcelFileDescriptor tWriteEnd = mTransportPipes[1];
9284
9285                int bufferSize = 32 * 1024;
9286                byte[] buffer = new byte[bufferSize];
9287                FileOutputStream engineOut = new FileOutputStream(eWriteEnd.getFileDescriptor());
9288                FileInputStream transportIn = new FileInputStream(tReadEnd.getFileDescriptor());
9289
9290                // spin up the engine and start moving data to it
9291                new Thread(mEngineThread, "unified-restore-engine").start();
9292
9293                try {
9294                    while (status == BackupTransport.TRANSPORT_OK) {
9295                        // have the transport write some of the restoring data to us
9296                        int result = mTransport.getNextFullRestoreDataChunk(tWriteEnd);
9297                        if (result > 0) {
9298                            // The transport wrote this many bytes of restore data to the
9299                            // pipe, so pass it along to the engine.
9300                            if (MORE_DEBUG) {
9301                                Slog.v(TAG, "  <- transport provided chunk size " + result);
9302                            }
9303                            if (result > bufferSize) {
9304                                bufferSize = result;
9305                                buffer = new byte[bufferSize];
9306                            }
9307                            int toCopy = result;
9308                            while (toCopy > 0) {
9309                                int n = transportIn.read(buffer, 0, toCopy);
9310                                engineOut.write(buffer, 0, n);
9311                                toCopy -= n;
9312                                if (MORE_DEBUG) {
9313                                    Slog.v(TAG, "  -> wrote " + n + " to engine, left=" + toCopy);
9314                                }
9315                            }
9316                        } else if (result == BackupTransport.NO_MORE_DATA) {
9317                            // Clean finish.  Wind up and we're done!
9318                            if (MORE_DEBUG) {
9319                                Slog.i(TAG, "Got clean full-restore EOF for "
9320                                        + mCurrentPackage.packageName);
9321                            }
9322                            status = BackupTransport.TRANSPORT_OK;
9323                            break;
9324                        } else {
9325                            // Transport reported some sort of failure; the fall-through
9326                            // handling will deal properly with that.
9327                            Slog.e(TAG, "Error " + result + " streaming restore for "
9328                                    + mCurrentPackage.packageName);
9329                            EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
9330                            status = result;
9331                        }
9332                    }
9333                    if (MORE_DEBUG) Slog.v(TAG, "Done copying to engine, falling through");
9334                } catch (IOException e) {
9335                    // We lost our ability to communicate via the pipes.  That's worrying
9336                    // but potentially recoverable; abandon this package's restore but
9337                    // carry on with the next restore target.
9338                    Slog.e(TAG, "Unable to route data for restore");
9339                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
9340                            mCurrentPackage.packageName, "I/O error on pipes");
9341                    status = BackupTransport.AGENT_ERROR;
9342                } catch (Exception e) {
9343                    // The transport threw; terminate the whole operation.  Closing
9344                    // the sockets will wake up the engine and it will then tidy up the
9345                    // remote end.
9346                    Slog.e(TAG, "Transport failed during restore: " + e.getMessage());
9347                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
9348                    status = BackupTransport.TRANSPORT_ERROR;
9349                } finally {
9350                    // Close the transport pipes and *our* end of the engine pipe,
9351                    // but leave the engine thread's end open so that it properly
9352                    // hits EOF and winds up its operations.
9353                    IoUtils.closeQuietly(mEnginePipes[1]);
9354                    IoUtils.closeQuietly(mTransportPipes[0]);
9355                    IoUtils.closeQuietly(mTransportPipes[1]);
9356
9357                    // Don't proceed until the engine has wound up operations
9358                    mEngineThread.waitForResult();
9359
9360                    // Now we're really done with this one too
9361                    IoUtils.closeQuietly(mEnginePipes[0]);
9362
9363                    // In all cases we want to remember whether we launched
9364                    // the target app as part of our work so far.
9365                    mDidLaunch = (mEngine.getAgent() != null);
9366
9367                    // If we hit a transport-level error, we are done with everything;
9368                    // if we hit an agent error we just go back to running the queue.
9369                    if (status == BackupTransport.TRANSPORT_OK) {
9370                        // Clean finish means we issue the restore-finished callback
9371                        nextState = UnifiedRestoreState.RESTORE_FINISHED;
9372
9373                        // the engine bound the target's agent, so recover that binding
9374                        // to use for the callback.
9375                        mAgent = mEngine.getAgent();
9376
9377                        // and the restored widget data, if any
9378                        mWidgetData = mEngine.getWidgetData();
9379                    } else {
9380                        // Something went wrong somewhere.  Whether it was at the transport
9381                        // level is immaterial; we need to tell the transport to bail
9382                        try {
9383                            mTransport.abortFullRestore();
9384                        } catch (Exception e) {
9385                            // transport itself is dead; make sure we handle this as a
9386                            // fatal error
9387                            Slog.e(TAG, "Transport threw from abortFullRestore: " + e.getMessage());
9388                            status = BackupTransport.TRANSPORT_ERROR;
9389                        }
9390
9391                        // We also need to wipe the current target's data, as it's probably
9392                        // in an incoherent state.
9393                        clearApplicationDataSynchronous(mCurrentPackage.packageName);
9394
9395                        // Schedule the next state based on the nature of our failure
9396                        if (status == BackupTransport.TRANSPORT_ERROR) {
9397                            nextState = UnifiedRestoreState.FINAL;
9398                        } else {
9399                            nextState = UnifiedRestoreState.RUNNING_QUEUE;
9400                        }
9401                    }
9402                    executeNextState(nextState);
9403                    setRunning(false);
9404                }
9405            }
9406
9407            // BackupRestoreTask interface, specifically for timeout handling
9408
9409            @Override
9410            public void execute() { /* intentionally empty */ }
9411
9412            @Override
9413            public void operationComplete(long result) { /* intentionally empty */ }
9414
9415            // The app has timed out handling a restoring file
9416            @Override
9417            public void handleCancel(boolean cancelAll) {
9418                removeOperation(mEphemeralOpToken);
9419                if (DEBUG) {
9420                    Slog.w(TAG, "Full-data restore target timed out; shutting down");
9421                }
9422
9423                mMonitor = monitorEvent(mMonitor,
9424                        BackupManagerMonitor.LOG_EVENT_ID_FULL_RESTORE_TIMEOUT,
9425                        mCurrentPackage, BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT, null);
9426                mEngineThread.handleTimeout();
9427
9428                IoUtils.closeQuietly(mEnginePipes[1]);
9429                mEnginePipes[1] = null;
9430                IoUtils.closeQuietly(mEnginePipes[0]);
9431                mEnginePipes[0] = null;
9432            }
9433        }
9434
9435        class EngineThread implements Runnable {
9436            FullRestoreEngine mEngine;
9437            FileInputStream mEngineStream;
9438
9439            EngineThread(FullRestoreEngine engine, ParcelFileDescriptor engineSocket) {
9440                mEngine = engine;
9441                engine.setRunning(true);
9442                // We *do* want this FileInputStream to own the underlying fd, so that
9443                // when we are finished with it, it closes this end of the pipe in a way
9444                // that signals its other end.
9445                mEngineStream = new FileInputStream(engineSocket.getFileDescriptor(), true);
9446            }
9447
9448            public boolean isRunning() {
9449                return mEngine.isRunning();
9450            }
9451
9452            public int waitForResult() {
9453                return mEngine.waitForResult();
9454            }
9455
9456            @Override
9457            public void run() {
9458                try {
9459                    while (mEngine.isRunning()) {
9460                        // Tell it to be sure to leave the agent instance up after finishing
9461                        mEngine.restoreOneFile(mEngineStream, false);
9462                    }
9463                } finally {
9464                    // Because mEngineStream adopted its underlying FD, this also
9465                    // closes this end of the pipe.
9466                    IoUtils.closeQuietly(mEngineStream);
9467                }
9468            }
9469
9470            public void handleTimeout() {
9471                IoUtils.closeQuietly(mEngineStream);
9472                mEngine.handleTimeout();
9473            }
9474        }
9475
9476        // state FINAL : tear everything down and we're done.
9477        private void finalizeRestore() {
9478            if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
9479
9480            try {
9481                mTransport.finishRestore();
9482            } catch (Exception e) {
9483                Slog.e(TAG, "Error finishing restore", e);
9484            }
9485
9486            // Tell the observer we're done
9487            if (mObserver != null) {
9488                try {
9489                    mObserver.restoreFinished(mStatus);
9490                } catch (RemoteException e) {
9491                    Slog.d(TAG, "Restore observer died at restoreFinished");
9492                }
9493            }
9494
9495            // Clear any ongoing session timeout.
9496            mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
9497
9498            // If we have a PM token, we must under all circumstances be sure to
9499            // handshake when we've finished.
9500            if (mPmToken > 0) {
9501                if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
9502                try {
9503                    mPackageManagerBinder.finishPackageInstall(mPmToken, mDidLaunch);
9504                } catch (RemoteException e) { /* can't happen */ }
9505            } else {
9506                // We were invoked via an active restore session, not by the Package
9507                // Manager, so start up the session timeout again.
9508                mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_SESSION_TIMEOUT,
9509                        TIMEOUT_RESTORE_INTERVAL);
9510            }
9511
9512            // Kick off any work that may be needed regarding app widget restores
9513            // TODO: http://b/22388012
9514            AppWidgetBackupBridge.restoreFinished(UserHandle.USER_SYSTEM);
9515
9516            // If this was a full-system restore, record the ancestral
9517            // dataset information
9518            if (mIsSystemRestore && mPmAgent != null) {
9519                mAncestralPackages = mPmAgent.getRestoredPackages();
9520                mAncestralToken = mToken;
9521                writeRestoreTokens();
9522            }
9523
9524            // done; we can finally release the wakelock and be legitimately done.
9525            Slog.i(TAG, "Restore complete.");
9526
9527            synchronized (mPendingRestores) {
9528                if (mPendingRestores.size() > 0) {
9529                    if (DEBUG) {
9530                        Slog.d(TAG, "Starting next pending restore.");
9531                    }
9532                    PerformUnifiedRestoreTask task = mPendingRestores.remove();
9533                    mBackupHandler.sendMessage(
9534                            mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, task));
9535
9536                } else {
9537                    mIsRestoreInProgress = false;
9538                    if (MORE_DEBUG) {
9539                        Slog.d(TAG, "No pending restores.");
9540                    }
9541                }
9542            }
9543
9544            mWakelock.release();
9545        }
9546
9547        void keyValueAgentErrorCleanup() {
9548            // If the agent fails restore, it might have put the app's data
9549            // into an incoherent state.  For consistency we wipe its data
9550            // again in this case before continuing with normal teardown
9551            clearApplicationDataSynchronous(mCurrentPackage.packageName);
9552            keyValueAgentCleanup();
9553        }
9554
9555        // TODO: clean up naming; this is now used at finish by both k/v and stream restores
9556        void keyValueAgentCleanup() {
9557            mBackupDataName.delete();
9558            mStageName.delete();
9559            try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
9560            try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
9561            mBackupData = mNewState = null;
9562
9563            // if everything went okay, remember the recorded state now
9564            //
9565            // !!! TODO: the restored data could be migrated on the server
9566            // side into the current dataset.  In that case the new state file
9567            // we just created would reflect the data already extant in the
9568            // backend, so there'd be nothing more to do.  Until that happens,
9569            // however, we need to make sure that we record the data to the
9570            // current backend dataset.  (Yes, this means shipping the data over
9571            // the wire in both directions.  That's bad, but consistency comes
9572            // first, then efficiency.)  Once we introduce server-side data
9573            // migration to the newly-restored device's dataset, we will change
9574            // the following from a discard of the newly-written state to the
9575            // "correct" operation of renaming into the canonical state blob.
9576            mNewStateName.delete();                      // TODO: remove; see above comment
9577            //mNewStateName.renameTo(mSavedStateName);   // TODO: replace with this
9578
9579            // If this wasn't the PM pseudopackage, tear down the agent side
9580            if (mCurrentPackage.applicationInfo != null) {
9581                // unbind and tidy up even on timeout or failure
9582                try {
9583                    mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
9584
9585                    // The agent was probably running with a stub Application object,
9586                    // which isn't a valid run mode for the main app logic.  Shut
9587                    // down the app so that next time it's launched, it gets the
9588                    // usual full initialization.  Note that this is only done for
9589                    // full-system restores: when a single app has requested a restore,
9590                    // it is explicitly not killed following that operation.
9591                    //
9592                    // We execute this kill when these conditions hold:
9593                    //    1. it's not a system-uid process,
9594                    //    2. the app did not request its own restore (mTargetPackage == null), and either
9595                    //    3a. the app is a full-data target (TYPE_FULL_STREAM) or
9596                    //     b. the app does not state android:killAfterRestore="false" in its manifest
9597                    final int appFlags = mCurrentPackage.applicationInfo.flags;
9598                    final boolean killAfterRestore =
9599                            (mCurrentPackage.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
9600                            && ((mRestoreDescription.getDataType() == RestoreDescription.TYPE_FULL_STREAM)
9601                                    || ((appFlags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0));
9602
9603                    if (mTargetPackage == null && killAfterRestore) {
9604                        if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
9605                                + mCurrentPackage.applicationInfo.processName);
9606                        mActivityManager.killApplicationProcess(
9607                                mCurrentPackage.applicationInfo.processName,
9608                                mCurrentPackage.applicationInfo.uid);
9609                    }
9610                } catch (RemoteException e) {
9611                    // can't happen; we run in the same process as the activity manager
9612                }
9613            }
9614
9615            // The caller is responsible for reestablishing the state machine; our
9616            // responsibility here is to clear the decks for whatever comes next.
9617            mBackupHandler.removeMessages(MSG_RESTORE_OPERATION_TIMEOUT, this);
9618        }
9619
9620        @Override
9621        public void operationComplete(long unusedResult) {
9622            removeOperation(mEphemeralOpToken);
9623            if (MORE_DEBUG) {
9624                Slog.i(TAG, "operationComplete() during restore: target="
9625                        + mCurrentPackage.packageName
9626                        + " state=" + mState);
9627            }
9628
9629            final UnifiedRestoreState nextState;
9630            switch (mState) {
9631                case INITIAL:
9632                    // We've just (manually) restored the PMBA.  It doesn't need the
9633                    // additional restore-finished callback so we bypass that and go
9634                    // directly to running the queue.
9635                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
9636                    break;
9637
9638                case RESTORE_KEYVALUE:
9639                case RESTORE_FULL: {
9640                    // Okay, we've just heard back from the agent that it's done with
9641                    // the restore itself.  We now have to send the same agent its
9642                    // doRestoreFinished() callback, so roll into that state.
9643                    nextState = UnifiedRestoreState.RESTORE_FINISHED;
9644                    break;
9645                }
9646
9647                case RESTORE_FINISHED: {
9648                    // Okay, we're done with this package.  Tidy up and go on to the next
9649                    // app in the queue.
9650                    int size = (int) mBackupDataName.length();
9651                    EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE,
9652                            mCurrentPackage.packageName, size);
9653
9654                    // Just go back to running the restore queue
9655                    keyValueAgentCleanup();
9656
9657                    // If there was widget state associated with this app, get the OS to
9658                    // incorporate it into current bookeeping and then pass that along to
9659                    // the app as part of the restore-time work.
9660                    if (mWidgetData != null) {
9661                        restoreWidgetData(mCurrentPackage.packageName, mWidgetData);
9662                    }
9663
9664                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
9665                    break;
9666                }
9667
9668                default: {
9669                    // Some kind of horrible semantic error; we're in an unexpected state.
9670                    // Back off hard and wind up.
9671                    Slog.e(TAG, "Unexpected restore callback into state " + mState);
9672                    keyValueAgentErrorCleanup();
9673                    nextState = UnifiedRestoreState.FINAL;
9674                    break;
9675                }
9676            }
9677
9678            executeNextState(nextState);
9679        }
9680
9681        // A call to agent.doRestore() or agent.doRestoreFinished() has timed out
9682        @Override
9683        public void handleCancel(boolean cancelAll) {
9684            removeOperation(mEphemeralOpToken);
9685            Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
9686            mMonitor = monitorEvent(mMonitor,
9687                    BackupManagerMonitor.LOG_EVENT_ID_KEY_VALUE_RESTORE_TIMEOUT,
9688                    mCurrentPackage, BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT, null);
9689            EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
9690                    mCurrentPackage.packageName, "restore timeout");
9691            // Handle like an agent that threw on invocation: wipe it and go on to the next
9692            keyValueAgentErrorCleanup();
9693            executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9694        }
9695
9696        void executeNextState(UnifiedRestoreState nextState) {
9697            if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
9698                    + this + " nextState=" + nextState);
9699            mState = nextState;
9700            Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
9701            mBackupHandler.sendMessage(msg);
9702        }
9703
9704        // restore observer support
9705        void sendStartRestore(int numPackages) {
9706            if (mObserver != null) {
9707                try {
9708                    mObserver.restoreStarting(numPackages);
9709                } catch (RemoteException e) {
9710                    Slog.w(TAG, "Restore observer went away: startRestore");
9711                    mObserver = null;
9712                }
9713            }
9714        }
9715
9716        void sendOnRestorePackage(String name) {
9717            if (mObserver != null) {
9718                if (mObserver != null) {
9719                    try {
9720                        mObserver.onUpdate(mCount, name);
9721                    } catch (RemoteException e) {
9722                        Slog.d(TAG, "Restore observer died in onUpdate");
9723                        mObserver = null;
9724                    }
9725                }
9726            }
9727        }
9728
9729        void sendEndRestore() {
9730            if (mObserver != null) {
9731                try {
9732                    mObserver.restoreFinished(mStatus);
9733                } catch (RemoteException e) {
9734                    Slog.w(TAG, "Restore observer went away: endRestore");
9735                    mObserver = null;
9736                }
9737            }
9738        }
9739    }
9740
9741    class PerformClearTask implements Runnable {
9742        IBackupTransport mTransport;
9743        PackageInfo mPackage;
9744
9745        PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
9746            mTransport = transport;
9747            mPackage = packageInfo;
9748        }
9749
9750        public void run() {
9751            try {
9752                // Clear the on-device backup state to ensure a full backup next time
9753                File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
9754                File stateFile = new File(stateDir, mPackage.packageName);
9755                stateFile.delete();
9756
9757                // Tell the transport to remove all the persistent storage for the app
9758                // TODO - need to handle failures
9759                mTransport.clearBackupData(mPackage);
9760            } catch (Exception e) {
9761                Slog.e(TAG, "Transport threw clearing data for " + mPackage + ": " + e.getMessage());
9762            } finally {
9763                try {
9764                    // TODO - need to handle failures
9765                    mTransport.finishBackup();
9766                } catch (Exception e) {
9767                    // Nothing we can do here, alas
9768                    Slog.e(TAG, "Unable to mark clear operation finished: " + e.getMessage());
9769                }
9770
9771                // Last but not least, release the cpu
9772                mWakelock.release();
9773            }
9774        }
9775    }
9776
9777    class PerformInitializeTask implements Runnable {
9778        String[] mQueue;
9779        IBackupObserver mObserver;
9780
9781        PerformInitializeTask(String[] transportNames, IBackupObserver observer) {
9782            mQueue = transportNames;
9783            mObserver = observer;
9784        }
9785
9786        private void notifyResult(String target, int status) {
9787            try {
9788                if (mObserver != null) {
9789                    mObserver.onResult(target, status);
9790                }
9791            } catch (RemoteException ignored) {
9792                mObserver = null;       // don't try again
9793            }
9794        }
9795
9796        private void notifyFinished(int status) {
9797            try {
9798                if (mObserver != null) {
9799                    mObserver.backupFinished(status);
9800                }
9801            } catch (RemoteException ignored) {
9802                mObserver = null;
9803            }
9804        }
9805
9806        public void run() {
9807            // mWakelock is *acquired* when execution begins here
9808            int result = BackupTransport.TRANSPORT_OK;
9809            try {
9810                for (String transportName : mQueue) {
9811                    IBackupTransport transport =
9812                            mTransportManager.getTransportBinder(transportName);
9813                    if (transport == null) {
9814                        Slog.e(TAG, "Requested init for " + transportName + " but not found");
9815                        continue;
9816                    }
9817
9818                    Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
9819                    EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
9820                    long startRealtime = SystemClock.elapsedRealtime();
9821                    int status = transport.initializeDevice();
9822
9823                    if (status == BackupTransport.TRANSPORT_OK) {
9824                        status = transport.finishBackup();
9825                    }
9826
9827                    // Okay, the wipe really happened.  Clean up our local bookkeeping.
9828                    if (status == BackupTransport.TRANSPORT_OK) {
9829                        Slog.i(TAG, "Device init successful");
9830                        int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
9831                        EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
9832                        resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
9833                        EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
9834                        synchronized (mQueueLock) {
9835                            recordInitPendingLocked(false, transportName);
9836                        }
9837                        notifyResult(transportName, BackupTransport.TRANSPORT_OK);
9838                    } else {
9839                        // If this didn't work, requeue this one and try again
9840                        // after a suitable interval
9841                        Slog.e(TAG, "Transport error in initializeDevice()");
9842                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
9843                        synchronized (mQueueLock) {
9844                            recordInitPendingLocked(true, transportName);
9845                        }
9846                        notifyResult(transportName, status);
9847                        result = status;
9848
9849                        // do this via another alarm to make sure of the wakelock states
9850                        long delay = transport.requestBackupTime();
9851                        Slog.w(TAG, "Init failed on " + transportName + " resched in " + delay);
9852                        mAlarmManager.set(AlarmManager.RTC_WAKEUP,
9853                                System.currentTimeMillis() + delay, mRunInitIntent);
9854                    }
9855                }
9856            } catch (Exception e) {
9857                Slog.e(TAG, "Unexpected error performing init", e);
9858                result = BackupTransport.TRANSPORT_ERROR;
9859            } finally {
9860                // Done; release the wakelock
9861                notifyFinished(result);
9862                mWakelock.release();
9863            }
9864        }
9865    }
9866
9867    private void dataChangedImpl(String packageName) {
9868        HashSet<String> targets = dataChangedTargets(packageName);
9869        dataChangedImpl(packageName, targets);
9870    }
9871
9872    private void dataChangedImpl(String packageName, HashSet<String> targets) {
9873        // Record that we need a backup pass for the caller.  Since multiple callers
9874        // may share a uid, we need to note all candidates within that uid and schedule
9875        // a backup pass for each of them.
9876        if (targets == null) {
9877            Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
9878                   + " uid=" + Binder.getCallingUid());
9879            return;
9880        }
9881
9882        synchronized (mQueueLock) {
9883            // Note that this client has made data changes that need to be backed up
9884            if (targets.contains(packageName)) {
9885                // Add the caller to the set of pending backups.  If there is
9886                // one already there, then overwrite it, but no harm done.
9887                BackupRequest req = new BackupRequest(packageName);
9888                if (mPendingBackups.put(packageName, req) == null) {
9889                    if (MORE_DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
9890
9891                    // Journal this request in case of crash.  The put()
9892                    // operation returned null when this package was not already
9893                    // in the set; we want to avoid touching the disk redundantly.
9894                    writeToJournalLocked(packageName);
9895                }
9896            }
9897        }
9898
9899        // ...and schedule a backup pass if necessary
9900        KeyValueBackupJob.schedule(mContext);
9901    }
9902
9903    // Note: packageName is currently unused, but may be in the future
9904    private HashSet<String> dataChangedTargets(String packageName) {
9905        // If the caller does not hold the BACKUP permission, it can only request a
9906        // backup of its own data.
9907        if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
9908                Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
9909            synchronized (mBackupParticipants) {
9910                return mBackupParticipants.get(Binder.getCallingUid());
9911            }
9912        }
9913
9914        // a caller with full permission can ask to back up any participating app
9915        HashSet<String> targets = new HashSet<String>();
9916        if (PACKAGE_MANAGER_SENTINEL.equals(packageName)) {
9917            targets.add(PACKAGE_MANAGER_SENTINEL);
9918        } else {
9919            synchronized (mBackupParticipants) {
9920                int N = mBackupParticipants.size();
9921                for (int i = 0; i < N; i++) {
9922                    HashSet<String> s = mBackupParticipants.valueAt(i);
9923                    if (s != null) {
9924                        targets.addAll(s);
9925                    }
9926                }
9927            }
9928        }
9929        return targets;
9930    }
9931
9932    private void writeToJournalLocked(String str) {
9933        RandomAccessFile out = null;
9934        try {
9935            if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
9936            out = new RandomAccessFile(mJournal, "rws");
9937            out.seek(out.length());
9938            out.writeUTF(str);
9939        } catch (IOException e) {
9940            Slog.e(TAG, "Can't write " + str + " to backup journal", e);
9941            mJournal = null;
9942        } finally {
9943            try { if (out != null) out.close(); } catch (IOException e) {}
9944        }
9945    }
9946
9947    // ----- IBackupManager binder interface -----
9948
9949    @Override
9950    public void dataChanged(final String packageName) {
9951        final int callingUserHandle = UserHandle.getCallingUserId();
9952        if (callingUserHandle != UserHandle.USER_SYSTEM) {
9953            // TODO: http://b/22388012
9954            // App is running under a non-owner user profile.  For now, we do not back
9955            // up data from secondary user profiles.
9956            // TODO: backups for all user profiles although don't add backup for profiles
9957            // without adding admin control in DevicePolicyManager.
9958            if (MORE_DEBUG) {
9959                Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
9960                        + callingUserHandle);
9961            }
9962            return;
9963        }
9964
9965        final HashSet<String> targets = dataChangedTargets(packageName);
9966        if (targets == null) {
9967            Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
9968                   + " uid=" + Binder.getCallingUid());
9969            return;
9970        }
9971
9972        mBackupHandler.post(new Runnable() {
9973                public void run() {
9974                    dataChangedImpl(packageName, targets);
9975                }
9976            });
9977    }
9978
9979    // Run an initialize operation for the given transport
9980    @Override
9981    public void initializeTransports(String[] transportNames, IBackupObserver observer) {
9982        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "initializeTransport");
9983        if (MORE_DEBUG) {
9984            Slog.v(TAG, "initializeTransports() of " + transportNames);
9985        }
9986
9987        final long oldId = Binder.clearCallingIdentity();
9988        try {
9989            mWakelock.acquire();
9990            mBackupHandler.post(new PerformInitializeTask(transportNames, observer));
9991        } finally {
9992            Binder.restoreCallingIdentity(oldId);
9993        }
9994    }
9995
9996    // Clear the given package's backup data from the current transport
9997    @Override
9998    public void clearBackupData(String transportName, String packageName) {
9999        if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName + " on " + transportName);
10000        PackageInfo info;
10001        try {
10002            info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
10003        } catch (NameNotFoundException e) {
10004            Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
10005            return;
10006        }
10007
10008        // If the caller does not hold the BACKUP permission, it can only request a
10009        // wipe of its own backed-up data.
10010        HashSet<String> apps;
10011        if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
10012                Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
10013            apps = mBackupParticipants.get(Binder.getCallingUid());
10014        } else {
10015            // a caller with full permission can ask to back up any participating app
10016            // !!! TODO: allow data-clear of ANY app?
10017            if (MORE_DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
10018            apps = new HashSet<String>();
10019            int N = mBackupParticipants.size();
10020            for (int i = 0; i < N; i++) {
10021                HashSet<String> s = mBackupParticipants.valueAt(i);
10022                if (s != null) {
10023                    apps.addAll(s);
10024                }
10025            }
10026        }
10027
10028        // Is the given app an available participant?
10029        if (apps.contains(packageName)) {
10030            // found it; fire off the clear request
10031            if (MORE_DEBUG) Slog.v(TAG, "Found the app - running clear process");
10032            mBackupHandler.removeMessages(MSG_RETRY_CLEAR);
10033            synchronized (mQueueLock) {
10034                final IBackupTransport transport =
10035                        mTransportManager.getTransportBinder(transportName);
10036                if (transport == null) {
10037                    // transport is currently unavailable -- make sure to retry
10038                    Message msg = mBackupHandler.obtainMessage(MSG_RETRY_CLEAR,
10039                            new ClearRetryParams(transportName, packageName));
10040                    mBackupHandler.sendMessageDelayed(msg, TRANSPORT_RETRY_INTERVAL);
10041                    return;
10042                }
10043                long oldId = Binder.clearCallingIdentity();
10044                mWakelock.acquire();
10045                Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
10046                        new ClearParams(transport, info));
10047                mBackupHandler.sendMessage(msg);
10048                Binder.restoreCallingIdentity(oldId);
10049            }
10050        }
10051    }
10052
10053    // Run a backup pass immediately for any applications that have declared
10054    // that they have pending updates.
10055    @Override
10056    public void backupNow() {
10057        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
10058
10059        final PowerSaveState result =
10060                mPowerManager.getPowerSaveState(ServiceType.KEYVALUE_BACKUP);
10061        if (result.batterySaverEnabled) {
10062            if (DEBUG) Slog.v(TAG, "Not running backup while in battery save mode");
10063            KeyValueBackupJob.schedule(mContext);   // try again in several hours
10064        } else {
10065            if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
10066            synchronized (mQueueLock) {
10067                // Fire the intent that kicks off the whole shebang...
10068                try {
10069                    mRunBackupIntent.send();
10070                } catch (PendingIntent.CanceledException e) {
10071                    // should never happen
10072                    Slog.e(TAG, "run-backup intent cancelled!");
10073                }
10074
10075                // ...and cancel any pending scheduled job, because we've just superseded it
10076                KeyValueBackupJob.cancel(mContext);
10077            }
10078        }
10079    }
10080
10081    boolean deviceIsProvisioned() {
10082        final ContentResolver resolver = mContext.getContentResolver();
10083        return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
10084    }
10085
10086    // Run a backup pass for the given packages, writing the resulting data stream
10087    // to the supplied file descriptor.  This method is synchronous and does not return
10088    // to the caller until the backup has been completed.
10089    //
10090    // This is the variant used by 'adb backup'; it requires on-screen confirmation
10091    // by the user because it can be used to offload data over untrusted USB.
10092    @Override
10093    public void adbBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeObbs,
10094            boolean includeShared, boolean doWidgets, boolean doAllApps, boolean includeSystem,
10095            boolean compress, boolean doKeyValue, String[] pkgList) {
10096        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "adbBackup");
10097
10098        final int callingUserHandle = UserHandle.getCallingUserId();
10099        // TODO: http://b/22388012
10100        if (callingUserHandle != UserHandle.USER_SYSTEM) {
10101            throw new IllegalStateException("Backup supported only for the device owner");
10102        }
10103
10104        // Validate
10105        if (!doAllApps) {
10106            if (!includeShared) {
10107                // If we're backing up shared data (sdcard or equivalent), then we can run
10108                // without any supplied app names.  Otherwise, we'd be doing no work, so
10109                // report the error.
10110                if (pkgList == null || pkgList.length == 0) {
10111                    throw new IllegalArgumentException(
10112                            "Backup requested but neither shared nor any apps named");
10113                }
10114            }
10115        }
10116
10117        long oldId = Binder.clearCallingIdentity();
10118        try {
10119            // Doesn't make sense to do a full backup prior to setup
10120            if (!deviceIsProvisioned()) {
10121                Slog.i(TAG, "Backup not supported before setup");
10122                return;
10123            }
10124
10125            if (DEBUG) Slog.v(TAG, "Requesting backup: apks=" + includeApks + " obb=" + includeObbs
10126                    + " shared=" + includeShared + " all=" + doAllApps + " system="
10127                    + includeSystem + " includekeyvalue=" + doKeyValue + " pkgs=" + pkgList);
10128            Slog.i(TAG, "Beginning adb backup...");
10129
10130            AdbBackupParams params = new AdbBackupParams(fd, includeApks, includeObbs,
10131                    includeShared, doWidgets, doAllApps, includeSystem, compress, doKeyValue,
10132                    pkgList);
10133            final int token = generateRandomIntegerToken();
10134            synchronized (mAdbBackupRestoreConfirmations) {
10135                mAdbBackupRestoreConfirmations.put(token, params);
10136            }
10137
10138            // start up the confirmation UI
10139            if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
10140            if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
10141                Slog.e(TAG, "Unable to launch backup confirmation UI");
10142                mAdbBackupRestoreConfirmations.delete(token);
10143                return;
10144            }
10145
10146            // make sure the screen is lit for the user interaction
10147            mPowerManager.userActivity(SystemClock.uptimeMillis(),
10148                    PowerManager.USER_ACTIVITY_EVENT_OTHER,
10149                    0);
10150
10151            // start the confirmation countdown
10152            startConfirmationTimeout(token, params);
10153
10154            // wait for the backup to be performed
10155            if (DEBUG) Slog.d(TAG, "Waiting for backup completion...");
10156            waitForCompletion(params);
10157        } finally {
10158            try {
10159                fd.close();
10160            } catch (IOException e) {
10161                // just eat it
10162            }
10163            Binder.restoreCallingIdentity(oldId);
10164            Slog.d(TAG, "Adb backup processing complete.");
10165        }
10166    }
10167
10168    @Override
10169    public void fullTransportBackup(String[] pkgNames) {
10170        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
10171                "fullTransportBackup");
10172
10173        final int callingUserHandle = UserHandle.getCallingUserId();
10174        // TODO: http://b/22388012
10175        if (callingUserHandle != UserHandle.USER_SYSTEM) {
10176            throw new IllegalStateException("Restore supported only for the device owner");
10177        }
10178
10179        if (!fullBackupAllowable(mTransportManager.getCurrentTransportBinder())) {
10180            Slog.i(TAG, "Full backup not currently possible -- key/value backup not yet run?");
10181        } else {
10182            if (DEBUG) {
10183                Slog.d(TAG, "fullTransportBackup()");
10184            }
10185
10186            final long oldId = Binder.clearCallingIdentity();
10187            try {
10188                CountDownLatch latch = new CountDownLatch(1);
10189                PerformFullTransportBackupTask task = new PerformFullTransportBackupTask(null,
10190                        pkgNames, false, null, latch, null, null, false /* userInitiated */);
10191                // Acquiring wakelock for PerformFullTransportBackupTask before its start.
10192                mWakelock.acquire();
10193                (new Thread(task, "full-transport-master")).start();
10194                do {
10195                    try {
10196                        latch.await();
10197                        break;
10198                    } catch (InterruptedException e) {
10199                        // Just go back to waiting for the latch to indicate completion
10200                    }
10201                } while (true);
10202
10203                // We just ran a backup on these packages, so kick them to the end of the queue
10204                final long now = System.currentTimeMillis();
10205                for (String pkg : pkgNames) {
10206                    enqueueFullBackup(pkg, now);
10207                }
10208            } finally {
10209                Binder.restoreCallingIdentity(oldId);
10210            }
10211        }
10212
10213        if (DEBUG) {
10214            Slog.d(TAG, "Done with full transport backup.");
10215        }
10216    }
10217
10218    @Override
10219    public void adbRestore(ParcelFileDescriptor fd) {
10220        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "adbRestore");
10221
10222        final int callingUserHandle = UserHandle.getCallingUserId();
10223        // TODO: http://b/22388012
10224        if (callingUserHandle != UserHandle.USER_SYSTEM) {
10225            throw new IllegalStateException("Restore supported only for the device owner");
10226        }
10227
10228        long oldId = Binder.clearCallingIdentity();
10229
10230        try {
10231            // Check whether the device has been provisioned -- we don't handle
10232            // full restores prior to completing the setup process.
10233            if (!deviceIsProvisioned()) {
10234                Slog.i(TAG, "Full restore not permitted before setup");
10235                return;
10236            }
10237
10238            Slog.i(TAG, "Beginning restore...");
10239
10240            AdbRestoreParams params = new AdbRestoreParams(fd);
10241            final int token = generateRandomIntegerToken();
10242            synchronized (mAdbBackupRestoreConfirmations) {
10243                mAdbBackupRestoreConfirmations.put(token, params);
10244            }
10245
10246            // start up the confirmation UI
10247            if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
10248            if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
10249                Slog.e(TAG, "Unable to launch restore confirmation");
10250                mAdbBackupRestoreConfirmations.delete(token);
10251                return;
10252            }
10253
10254            // make sure the screen is lit for the user interaction
10255            mPowerManager.userActivity(SystemClock.uptimeMillis(),
10256                    PowerManager.USER_ACTIVITY_EVENT_OTHER,
10257                    0);
10258
10259            // start the confirmation countdown
10260            startConfirmationTimeout(token, params);
10261
10262            // wait for the restore to be performed
10263            if (DEBUG) Slog.d(TAG, "Waiting for restore completion...");
10264            waitForCompletion(params);
10265        } finally {
10266            try {
10267                fd.close();
10268            } catch (IOException e) {
10269                Slog.w(TAG, "Error trying to close fd after adb restore: " + e);
10270            }
10271            Binder.restoreCallingIdentity(oldId);
10272            Slog.i(TAG, "adb restore processing complete.");
10273        }
10274    }
10275
10276    boolean startConfirmationUi(int token, String action) {
10277        try {
10278            Intent confIntent = new Intent(action);
10279            confIntent.setClassName("com.android.backupconfirm",
10280                    "com.android.backupconfirm.BackupRestoreConfirmation");
10281            confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
10282            confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
10283            mContext.startActivityAsUser(confIntent, UserHandle.SYSTEM);
10284        } catch (ActivityNotFoundException e) {
10285            return false;
10286        }
10287        return true;
10288    }
10289
10290    void startConfirmationTimeout(int token, AdbParams params) {
10291        if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
10292                + TIMEOUT_FULL_CONFIRMATION + " millis");
10293        Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
10294                token, 0, params);
10295        mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
10296    }
10297
10298    void waitForCompletion(AdbParams params) {
10299        synchronized (params.latch) {
10300            while (params.latch.get() == false) {
10301                try {
10302                    params.latch.wait();
10303                } catch (InterruptedException e) { /* never interrupted */ }
10304            }
10305        }
10306    }
10307
10308    void signalAdbBackupRestoreCompletion(AdbParams params) {
10309        synchronized (params.latch) {
10310            params.latch.set(true);
10311            params.latch.notifyAll();
10312        }
10313    }
10314
10315    // Confirm that the previously-requested full backup/restore operation can proceed.  This
10316    // is used to require a user-facing disclosure about the operation.
10317    @Override
10318    public void acknowledgeAdbBackupOrRestore(int token, boolean allow,
10319            String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
10320        if (DEBUG) Slog.d(TAG, "acknowledgeAdbBackupOrRestore : token=" + token
10321                + " allow=" + allow);
10322
10323        // TODO: possibly require not just this signature-only permission, but even
10324        // require that the specific designated confirmation-UI app uid is the caller?
10325        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeAdbBackupOrRestore");
10326
10327        long oldId = Binder.clearCallingIdentity();
10328        try {
10329
10330            AdbParams params;
10331            synchronized (mAdbBackupRestoreConfirmations) {
10332                params = mAdbBackupRestoreConfirmations.get(token);
10333                if (params != null) {
10334                    mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
10335                    mAdbBackupRestoreConfirmations.delete(token);
10336
10337                    if (allow) {
10338                        final int verb = params instanceof AdbBackupParams
10339                                ? MSG_RUN_ADB_BACKUP
10340                                : MSG_RUN_ADB_RESTORE;
10341
10342                        params.observer = observer;
10343                        params.curPassword = curPassword;
10344
10345                        params.encryptPassword = encPpassword;
10346
10347                        if (MORE_DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
10348                        mWakelock.acquire();
10349                        Message msg = mBackupHandler.obtainMessage(verb, params);
10350                        mBackupHandler.sendMessage(msg);
10351                    } else {
10352                        Slog.w(TAG, "User rejected full backup/restore operation");
10353                        // indicate completion without having actually transferred any data
10354                        signalAdbBackupRestoreCompletion(params);
10355                    }
10356                } else {
10357                    Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
10358                }
10359            }
10360        } finally {
10361            Binder.restoreCallingIdentity(oldId);
10362        }
10363    }
10364
10365    private static boolean backupSettingMigrated(int userId) {
10366        File base = new File(Environment.getDataDirectory(), "backup");
10367        File enableFile = new File(base, BACKUP_ENABLE_FILE);
10368        return enableFile.exists();
10369    }
10370
10371    private static boolean readBackupEnableState(int userId) {
10372        File base = new File(Environment.getDataDirectory(), "backup");
10373        File enableFile = new File(base, BACKUP_ENABLE_FILE);
10374        if (enableFile.exists()) {
10375            try (FileInputStream fin = new FileInputStream(enableFile)) {
10376                int state = fin.read();
10377                return state != 0;
10378            } catch (IOException e) {
10379                // can't read the file; fall through to assume disabled
10380                Slog.e(TAG, "Cannot read enable state; assuming disabled");
10381            }
10382        } else {
10383            if (DEBUG) {
10384                Slog.i(TAG, "isBackupEnabled() => false due to absent settings file");
10385            }
10386        }
10387        return false;
10388    }
10389
10390    private static void writeBackupEnableState(boolean enable, int userId) {
10391        File base = new File(Environment.getDataDirectory(), "backup");
10392        File enableFile = new File(base, BACKUP_ENABLE_FILE);
10393        File stage = new File(base, BACKUP_ENABLE_FILE + "-stage");
10394        FileOutputStream fout = null;
10395        try {
10396            fout = new FileOutputStream(stage);
10397            fout.write(enable ? 1 : 0);
10398            fout.close();
10399            stage.renameTo(enableFile);
10400            // will be synced immediately by the try-with-resources call to close()
10401        } catch (IOException|RuntimeException e) {
10402            // Whoops; looks like we're doomed.  Roll everything out, disabled,
10403            // including the legacy state.
10404            Slog.e(TAG, "Unable to record backup enable state; reverting to disabled: "
10405                    + e.getMessage());
10406
10407            final ContentResolver r = sInstance.mContext.getContentResolver();
10408            Settings.Secure.putStringForUser(r,
10409                    Settings.Secure.BACKUP_ENABLED, null, userId);
10410            enableFile.delete();
10411            stage.delete();
10412        } finally {
10413            IoUtils.closeQuietly(fout);
10414        }
10415    }
10416
10417    // Enable/disable backups
10418    @Override
10419    public void setBackupEnabled(boolean enable) {
10420        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10421                "setBackupEnabled");
10422
10423        Slog.i(TAG, "Backup enabled => " + enable);
10424
10425        long oldId = Binder.clearCallingIdentity();
10426        try {
10427            boolean wasEnabled = mEnabled;
10428            synchronized (this) {
10429                writeBackupEnableState(enable, UserHandle.USER_SYSTEM);
10430                mEnabled = enable;
10431            }
10432
10433            synchronized (mQueueLock) {
10434                if (enable && !wasEnabled && mProvisioned) {
10435                    // if we've just been enabled, start scheduling backup passes
10436                    KeyValueBackupJob.schedule(mContext);
10437                    scheduleNextFullBackupJob(0);
10438                } else if (!enable) {
10439                    // No longer enabled, so stop running backups
10440                    if (MORE_DEBUG) Slog.i(TAG, "Opting out of backup");
10441
10442                    KeyValueBackupJob.cancel(mContext);
10443
10444                    // This also constitutes an opt-out, so we wipe any data for
10445                    // this device from the backend.  We start that process with
10446                    // an alarm in order to guarantee wakelock states.
10447                    if (wasEnabled && mProvisioned) {
10448                        // NOTE: we currently flush every registered transport, not just
10449                        // the currently-active one.
10450                        String[] allTransports = mTransportManager.getBoundTransportNames();
10451                        // build the set of transports for which we are posting an init
10452                        for (String transport : allTransports) {
10453                            recordInitPendingLocked(true, transport);
10454                        }
10455                        mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
10456                                mRunInitIntent);
10457                    }
10458                }
10459            }
10460        } finally {
10461            Binder.restoreCallingIdentity(oldId);
10462        }
10463    }
10464
10465    // Enable/disable automatic restore of app data at install time
10466    @Override
10467    public void setAutoRestore(boolean doAutoRestore) {
10468        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10469                "setAutoRestore");
10470
10471        Slog.i(TAG, "Auto restore => " + doAutoRestore);
10472
10473        final long oldId = Binder.clearCallingIdentity();
10474        try {
10475            synchronized (this) {
10476                Settings.Secure.putInt(mContext.getContentResolver(),
10477                        Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
10478                mAutoRestore = doAutoRestore;
10479            }
10480        } finally {
10481            Binder.restoreCallingIdentity(oldId);
10482        }
10483    }
10484
10485    // Mark the backup service as having been provisioned
10486    @Override
10487    public void setBackupProvisioned(boolean available) {
10488        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10489                "setBackupProvisioned");
10490        /*
10491         * This is now a no-op; provisioning is simply the device's own setup state.
10492         */
10493    }
10494
10495    // Report whether the backup mechanism is currently enabled
10496    @Override
10497    public boolean isBackupEnabled() {
10498        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
10499        return mEnabled;    // no need to synchronize just to read it
10500    }
10501
10502    // Report the name of the currently active transport
10503    @Override
10504    public String getCurrentTransport() {
10505        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10506                "getCurrentTransport");
10507        String currentTransport = mTransportManager.getCurrentTransportName();
10508        if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + currentTransport);
10509        return currentTransport;
10510    }
10511
10512    // Report all known, available backup transports
10513    @Override
10514    public String[] listAllTransports() {
10515        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
10516
10517        return mTransportManager.getBoundTransportNames();
10518    }
10519
10520    @Override
10521    public ComponentName[] listAllTransportComponents() {
10522        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10523                "listAllTransportComponents");
10524        return mTransportManager.getAllTransportCompenents();
10525    }
10526
10527    @Override
10528    public String[] getTransportWhitelist() {
10529        // No permission check, intentionally.
10530        Set<ComponentName> whitelistedComponents = mTransportManager.getTransportWhitelist();
10531        String[] whitelistedTransports = new String[whitelistedComponents.size()];
10532        int i = 0;
10533        for (ComponentName component : whitelistedComponents) {
10534            whitelistedTransports[i] = component.flattenToShortString();
10535            i++;
10536        }
10537        return whitelistedTransports;
10538    }
10539
10540    // Select which transport to use for the next backup operation.
10541    @Override
10542    public String selectBackupTransport(String transport) {
10543        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10544                "selectBackupTransport");
10545
10546        final long oldId = Binder.clearCallingIdentity();
10547        try {
10548            String prevTransport = mTransportManager.selectTransport(transport);
10549            updateStateForTransport(transport);
10550            Slog.v(TAG, "selectBackupTransport() set " + mTransportManager.getCurrentTransportName()
10551                    + " returning " + prevTransport);
10552            return prevTransport;
10553        } finally {
10554            Binder.restoreCallingIdentity(oldId);
10555        }
10556    }
10557
10558    @Override
10559    public void selectBackupTransportAsync(final ComponentName transport,
10560            final ISelectBackupTransportCallback listener) {
10561        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10562                "selectBackupTransportAsync");
10563
10564        final long oldId = Binder.clearCallingIdentity();
10565
10566        Slog.v(TAG, "selectBackupTransportAsync() called with transport " +
10567                transport.flattenToShortString());
10568
10569        mTransportManager.ensureTransportReady(transport, new SelectBackupTransportCallback() {
10570            @Override
10571            public void onSuccess(String transportName) {
10572                mTransportManager.selectTransport(transportName);
10573                updateStateForTransport(mTransportManager.getCurrentTransportName());
10574                Slog.v(TAG, "Transport successfully selected: " + transport.flattenToShortString());
10575                try {
10576                    listener.onSuccess(transportName);
10577                } catch (RemoteException e) {
10578                    // Nothing to do here.
10579                }
10580            }
10581
10582            @Override
10583            public void onFailure(int reason) {
10584                Slog.v(TAG, "Failed to select transport: " + transport.flattenToShortString());
10585                try {
10586                    listener.onFailure(reason);
10587                } catch (RemoteException e) {
10588                    // Nothing to do here.
10589                }
10590            }
10591        });
10592
10593        Binder.restoreCallingIdentity(oldId);
10594    }
10595
10596    private void updateStateForTransport(String newTransportName) {
10597        // Publish the name change
10598        Settings.Secure.putString(mContext.getContentResolver(),
10599                Settings.Secure.BACKUP_TRANSPORT, newTransportName);
10600
10601        // And update our current-dataset bookkeeping
10602        IBackupTransport transport = mTransportManager.getTransportBinder(newTransportName);
10603        if (transport != null) {
10604            try {
10605                mCurrentToken = transport.getCurrentRestoreSet();
10606            } catch (Exception e) {
10607                // Oops.  We can't know the current dataset token, so reset and figure it out
10608                // when we do the next k/v backup operation on this transport.
10609                mCurrentToken = 0;
10610            }
10611        } else {
10612            // The named transport isn't bound at this particular moment, so we can't
10613            // know yet what its current dataset token is.  Reset as above.
10614            mCurrentToken = 0;
10615        }
10616    }
10617
10618    // Supply the configuration Intent for the given transport.  If the name is not one
10619    // of the available transports, or if the transport does not supply any configuration
10620    // UI, the method returns null.
10621    @Override
10622    public Intent getConfigurationIntent(String transportName) {
10623        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10624                "getConfigurationIntent");
10625
10626        final IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
10627        if (transport != null) {
10628            try {
10629                final Intent intent = transport.configurationIntent();
10630                if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
10631                        + intent);
10632                return intent;
10633            } catch (Exception e) {
10634                /* fall through to return null */
10635                Slog.e(TAG, "Unable to get configuration intent from transport: " + e.getMessage());
10636            }
10637        }
10638
10639        return null;
10640    }
10641
10642    // Supply the configuration summary string for the given transport.  If the name is
10643    // not one of the available transports, or if the transport does not supply any
10644    // summary / destination string, the method can return null.
10645    //
10646    // This string is used VERBATIM as the summary text of the relevant Settings item!
10647    @Override
10648    public String getDestinationString(String transportName) {
10649        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10650                "getDestinationString");
10651
10652        final IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
10653        if (transport != null) {
10654            try {
10655                final String text = transport.currentDestinationString();
10656                if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
10657                return text;
10658            } catch (Exception e) {
10659                /* fall through to return null */
10660                Slog.e(TAG, "Unable to get string from transport: " + e.getMessage());
10661            }
10662        }
10663
10664        return null;
10665    }
10666
10667    // Supply the manage-data intent for the given transport.
10668    @Override
10669    public Intent getDataManagementIntent(String transportName) {
10670        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10671                "getDataManagementIntent");
10672
10673        final IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
10674        if (transport != null) {
10675            try {
10676                final Intent intent = transport.dataManagementIntent();
10677                if (MORE_DEBUG) Slog.d(TAG, "getDataManagementIntent() returning intent "
10678                        + intent);
10679                return intent;
10680            } catch (Exception e) {
10681                /* fall through to return null */
10682                Slog.e(TAG, "Unable to get management intent from transport: " + e.getMessage());
10683            }
10684        }
10685
10686        return null;
10687    }
10688
10689    // Supply the menu label for affordances that fire the manage-data intent
10690    // for the given transport.
10691    @Override
10692    public String getDataManagementLabel(String transportName) {
10693        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10694                "getDataManagementLabel");
10695
10696        final IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
10697        if (transport != null) {
10698            try {
10699                final String text = transport.dataManagementLabel();
10700                if (MORE_DEBUG) Slog.d(TAG, "getDataManagementLabel() returning " + text);
10701                return text;
10702            } catch (Exception e) {
10703                /* fall through to return null */
10704                Slog.e(TAG, "Unable to get management label from transport: " + e.getMessage());
10705            }
10706        }
10707
10708        return null;
10709    }
10710
10711    // Callback: a requested backup agent has been instantiated.  This should only
10712    // be called from the Activity Manager.
10713    @Override
10714    public void agentConnected(String packageName, IBinder agentBinder) {
10715        synchronized(mAgentConnectLock) {
10716            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
10717                Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
10718                IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
10719                mConnectedAgent = agent;
10720                mConnecting = false;
10721            } else {
10722                Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
10723                        + " claiming agent connected");
10724            }
10725            mAgentConnectLock.notifyAll();
10726        }
10727    }
10728
10729    // Callback: a backup agent has failed to come up, or has unexpectedly quit.
10730    // If the agent failed to come up in the first place, the agentBinder argument
10731    // will be null.  This should only be called from the Activity Manager.
10732    @Override
10733    public void agentDisconnected(String packageName) {
10734        // TODO: handle backup being interrupted
10735        synchronized(mAgentConnectLock) {
10736            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
10737                mConnectedAgent = null;
10738                mConnecting = false;
10739            } else {
10740                Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
10741                        + " claiming agent disconnected");
10742            }
10743            mAgentConnectLock.notifyAll();
10744        }
10745    }
10746
10747    // An application being installed will need a restore pass, then the Package Manager
10748    // will need to be told when the restore is finished.
10749    @Override
10750    public void restoreAtInstall(String packageName, int token) {
10751        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
10752            Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
10753                    + " attemping install-time restore");
10754            return;
10755        }
10756
10757        boolean skip = false;
10758
10759        long restoreSet = getAvailableRestoreToken(packageName);
10760        if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
10761                + " token=" + Integer.toHexString(token)
10762                + " restoreSet=" + Long.toHexString(restoreSet));
10763        if (restoreSet == 0) {
10764            if (MORE_DEBUG) Slog.i(TAG, "No restore set");
10765            skip = true;
10766        }
10767
10768        // Do we have a transport to fetch data for us?
10769        IBackupTransport transport = mTransportManager.getCurrentTransportBinder();
10770        if (transport == null) {
10771            if (DEBUG) Slog.w(TAG, "No transport");
10772            skip = true;
10773        }
10774
10775        if (!mAutoRestore) {
10776            if (DEBUG) {
10777                Slog.w(TAG, "Non-restorable state: auto=" + mAutoRestore);
10778            }
10779            skip = true;
10780        }
10781
10782        if (!skip) {
10783            try {
10784                // okay, we're going to attempt a restore of this package from this restore set.
10785                // The eventual message back into the Package Manager to run the post-install
10786                // steps for 'token' will be issued from the restore handling code.
10787
10788                // This can throw and so *must* happen before the wakelock is acquired
10789                String dirName = transport.transportDirName();
10790
10791                mWakelock.acquire();
10792                if (MORE_DEBUG) {
10793                    Slog.d(TAG, "Restore at install of " + packageName);
10794                }
10795                Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
10796                msg.obj = new RestoreParams(transport, dirName, null, null,
10797                        restoreSet, packageName, token);
10798                mBackupHandler.sendMessage(msg);
10799            } catch (Exception e) {
10800                // Calling into the transport broke; back off and proceed with the installation.
10801                Slog.e(TAG, "Unable to contact transport: " + e.getMessage());
10802                skip = true;
10803            }
10804        }
10805
10806        if (skip) {
10807            // Auto-restore disabled or no way to attempt a restore; just tell the Package
10808            // Manager to proceed with the post-install handling for this package.
10809            if (DEBUG) Slog.v(TAG, "Finishing install immediately");
10810            try {
10811                mPackageManagerBinder.finishPackageInstall(token, false);
10812            } catch (RemoteException e) { /* can't happen */ }
10813        }
10814    }
10815
10816    // Hand off a restore session
10817    @Override
10818    public IRestoreSession beginRestoreSession(String packageName, String transport) {
10819        if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
10820                + " transport=" + transport);
10821
10822        boolean needPermission = true;
10823        if (transport == null) {
10824            transport = mTransportManager.getCurrentTransportName();
10825
10826            if (packageName != null) {
10827                PackageInfo app = null;
10828                try {
10829                    app = mPackageManager.getPackageInfo(packageName, 0);
10830                } catch (NameNotFoundException nnf) {
10831                    Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
10832                    throw new IllegalArgumentException("Package " + packageName + " not found");
10833                }
10834
10835                if (app.applicationInfo.uid == Binder.getCallingUid()) {
10836                    // So: using the current active transport, and the caller has asked
10837                    // that its own package will be restored.  In this narrow use case
10838                    // we do not require the caller to hold the permission.
10839                    needPermission = false;
10840                }
10841            }
10842        }
10843
10844        if (needPermission) {
10845            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10846                    "beginRestoreSession");
10847        } else {
10848            if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
10849        }
10850
10851        synchronized(this) {
10852            if (mActiveRestoreSession != null) {
10853                Slog.i(TAG, "Restore session requested but one already active");
10854                return null;
10855            }
10856            if (mBackupRunning) {
10857                Slog.i(TAG, "Restore session requested but currently running backups");
10858                return null;
10859            }
10860            mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
10861            mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_SESSION_TIMEOUT,
10862                    TIMEOUT_RESTORE_INTERVAL);
10863        }
10864        return mActiveRestoreSession;
10865    }
10866
10867    void clearRestoreSession(ActiveRestoreSession currentSession) {
10868        synchronized(this) {
10869            if (currentSession != mActiveRestoreSession) {
10870                Slog.e(TAG, "ending non-current restore session");
10871            } else {
10872                if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
10873                mActiveRestoreSession = null;
10874                mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
10875            }
10876        }
10877    }
10878
10879    // Note that a currently-active backup agent has notified us that it has
10880    // completed the given outstanding asynchronous backup/restore operation.
10881    @Override
10882    public void opComplete(int token, long result) {
10883        if (MORE_DEBUG) {
10884            Slog.v(TAG, "opComplete: " + Integer.toHexString(token) + " result=" + result);
10885        }
10886        Operation op = null;
10887        synchronized (mCurrentOpLock) {
10888            op = mCurrentOperations.get(token);
10889            if (op != null) {
10890                if (op.state == OP_TIMEOUT) {
10891                    // The operation already timed out, and this is a late response.  Tidy up
10892                    // and ignore it; we've already dealt with the timeout.
10893                    op = null;
10894                    mCurrentOperations.delete(token);
10895                } else if (op.state == OP_ACKNOWLEDGED) {
10896                    if (DEBUG) {
10897                        Slog.w(TAG, "Received duplicate ack for token=" +
10898                                Integer.toHexString(token));
10899                    }
10900                    op = null;
10901                    mCurrentOperations.remove(token);
10902                } else if (op.state == OP_PENDING) {
10903                    // Can't delete op from mCurrentOperations. waitUntilOperationComplete can be
10904                    // called after we we receive this call.
10905                    op.state = OP_ACKNOWLEDGED;
10906                }
10907            }
10908            mCurrentOpLock.notifyAll();
10909        }
10910
10911        // The completion callback, if any, is invoked on the handler
10912        if (op != null && op.callback != null) {
10913            Pair<BackupRestoreTask, Long> callbackAndResult = Pair.create(op.callback, result);
10914            Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, callbackAndResult);
10915            mBackupHandler.sendMessage(msg);
10916        }
10917    }
10918
10919    @Override
10920    public boolean isAppEligibleForBackup(String packageName) {
10921        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10922                "isAppEligibleForBackup");
10923        try {
10924            PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName,
10925                    PackageManager.GET_SIGNATURES);
10926            if (!appIsEligibleForBackup(packageInfo.applicationInfo, mPackageManager) ||
10927                    appIsStopped(packageInfo.applicationInfo)) {
10928                return false;
10929            }
10930            IBackupTransport transport = mTransportManager.getCurrentTransportBinder();
10931            if (transport != null) {
10932                try {
10933                    return transport.isAppEligibleForBackup(packageInfo,
10934                        appGetsFullBackup(packageInfo));
10935                } catch (Exception e) {
10936                    Slog.e(TAG, "Unable to ask about eligibility: " + e.getMessage());
10937                }
10938            }
10939            // If transport is not present we couldn't tell that the package is not eligible.
10940            return true;
10941        } catch (NameNotFoundException e) {
10942            return false;
10943        }
10944    }
10945
10946    // ----- Restore session -----
10947
10948    class ActiveRestoreSession extends IRestoreSession.Stub {
10949        private static final String TAG = "RestoreSession";
10950
10951        private String mPackageName;
10952        private IBackupTransport mRestoreTransport = null;
10953        RestoreSet[] mRestoreSets = null;
10954        boolean mEnded = false;
10955        boolean mTimedOut = false;
10956
10957        ActiveRestoreSession(String packageName, String transport) {
10958            mPackageName = packageName;
10959            mRestoreTransport = mTransportManager.getTransportBinder(transport);
10960        }
10961
10962        public void markTimedOut() {
10963            mTimedOut = true;
10964        }
10965
10966        // --- Binder interface ---
10967        public synchronized int getAvailableRestoreSets(IRestoreObserver observer,
10968                IBackupManagerMonitor monitor) {
10969            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10970                    "getAvailableRestoreSets");
10971            if (observer == null) {
10972                throw new IllegalArgumentException("Observer must not be null");
10973            }
10974
10975            if (mEnded) {
10976                throw new IllegalStateException("Restore session already ended");
10977            }
10978
10979            if (mTimedOut) {
10980                Slog.i(TAG, "Session already timed out");
10981                return -1;
10982            }
10983
10984            long oldId = Binder.clearCallingIdentity();
10985            try {
10986                if (mRestoreTransport == null) {
10987                    Slog.w(TAG, "Null transport getting restore sets");
10988                    return -1;
10989                }
10990
10991                // We know we're doing legit work now, so halt the timeout
10992                // until we're done.  It gets started again when the result
10993                // comes in.
10994                mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
10995
10996                // spin off the transport request to our service thread
10997                mWakelock.acquire();
10998                Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
10999                        new RestoreGetSetsParams(mRestoreTransport, this, observer,
11000                                monitor));
11001                mBackupHandler.sendMessage(msg);
11002                return 0;
11003            } catch (Exception e) {
11004                Slog.e(TAG, "Error in getAvailableRestoreSets", e);
11005                return -1;
11006            } finally {
11007                Binder.restoreCallingIdentity(oldId);
11008            }
11009        }
11010
11011        public synchronized int restoreAll(long token, IRestoreObserver observer,
11012                IBackupManagerMonitor monitor) {
11013            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
11014                    "performRestore");
11015
11016            if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
11017                    + " observer=" + observer);
11018
11019            if (mEnded) {
11020                throw new IllegalStateException("Restore session already ended");
11021            }
11022
11023            if (mTimedOut) {
11024                Slog.i(TAG, "Session already timed out");
11025                return -1;
11026            }
11027
11028            if (mRestoreTransport == null || mRestoreSets == null) {
11029                Slog.e(TAG, "Ignoring restoreAll() with no restore set");
11030                return -1;
11031            }
11032
11033            if (mPackageName != null) {
11034                Slog.e(TAG, "Ignoring restoreAll() on single-package session");
11035                return -1;
11036            }
11037
11038            String dirName;
11039            try {
11040                dirName = mRestoreTransport.transportDirName();
11041            } catch (Exception e) {
11042                // Transport went AWOL; fail.
11043                Slog.e(TAG, "Unable to get transport dir for restore: " + e.getMessage());
11044                return -1;
11045            }
11046
11047            synchronized (mQueueLock) {
11048                for (int i = 0; i < mRestoreSets.length; i++) {
11049                    if (token == mRestoreSets[i].token) {
11050                        // Real work, so stop the session timeout until we finalize the restore
11051                        mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
11052
11053                        long oldId = Binder.clearCallingIdentity();
11054                        mWakelock.acquire();
11055                        if (MORE_DEBUG) {
11056                            Slog.d(TAG, "restoreAll() kicking off");
11057                        }
11058                        Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
11059                        msg.obj = new RestoreParams(mRestoreTransport, dirName,
11060                                observer, monitor, token);
11061                        mBackupHandler.sendMessage(msg);
11062                        Binder.restoreCallingIdentity(oldId);
11063                        return 0;
11064                    }
11065                }
11066            }
11067
11068            Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
11069            return -1;
11070        }
11071
11072        // Restores of more than a single package are treated as 'system' restores
11073        public synchronized int restoreSome(long token, IRestoreObserver observer,
11074                IBackupManagerMonitor monitor, String[] packages) {
11075            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
11076                    "performRestore");
11077
11078            if (DEBUG) {
11079                StringBuilder b = new StringBuilder(128);
11080                b.append("restoreSome token=");
11081                b.append(Long.toHexString(token));
11082                b.append(" observer=");
11083                b.append(observer.toString());
11084                b.append(" monitor=");
11085                if (monitor == null) {
11086                    b.append("null");
11087                } else {
11088                    b.append(monitor.toString());
11089                }
11090                b.append(" packages=");
11091                if (packages == null) {
11092                    b.append("null");
11093                } else {
11094                    b.append('{');
11095                    boolean first = true;
11096                    for (String s : packages) {
11097                        if (!first) {
11098                            b.append(", ");
11099                        } else first = false;
11100                        b.append(s);
11101                    }
11102                    b.append('}');
11103                }
11104                Slog.d(TAG, b.toString());
11105            }
11106
11107            if (mEnded) {
11108                throw new IllegalStateException("Restore session already ended");
11109            }
11110
11111            if (mTimedOut) {
11112                Slog.i(TAG, "Session already timed out");
11113                return -1;
11114            }
11115
11116            if (mRestoreTransport == null || mRestoreSets == null) {
11117                Slog.e(TAG, "Ignoring restoreAll() with no restore set");
11118                return -1;
11119            }
11120
11121            if (mPackageName != null) {
11122                Slog.e(TAG, "Ignoring restoreAll() on single-package session");
11123                return -1;
11124            }
11125
11126            String dirName;
11127            try {
11128                dirName = mRestoreTransport.transportDirName();
11129            } catch (Exception e) {
11130                // Transport went AWOL; fail.
11131                Slog.e(TAG, "Unable to get transport name for restoreSome: " + e.getMessage());
11132                return -1;
11133            }
11134
11135            synchronized (mQueueLock) {
11136                for (int i = 0; i < mRestoreSets.length; i++) {
11137                    if (token == mRestoreSets[i].token) {
11138                        // Stop the session timeout until we finalize the restore
11139                        mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
11140
11141                        long oldId = Binder.clearCallingIdentity();
11142                        mWakelock.acquire();
11143                        if (MORE_DEBUG) {
11144                            Slog.d(TAG, "restoreSome() of " + packages.length + " packages");
11145                        }
11146                        Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
11147                        msg.obj = new RestoreParams(mRestoreTransport, dirName, observer, monitor,
11148                                token, packages, packages.length > 1);
11149                        mBackupHandler.sendMessage(msg);
11150                        Binder.restoreCallingIdentity(oldId);
11151                        return 0;
11152                    }
11153                }
11154            }
11155
11156            Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
11157            return -1;
11158        }
11159
11160        public synchronized int restorePackage(String packageName, IRestoreObserver observer,
11161                IBackupManagerMonitor monitor) {
11162            if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer
11163                    + "monitor=" + monitor);
11164
11165            if (mEnded) {
11166                throw new IllegalStateException("Restore session already ended");
11167            }
11168
11169            if (mTimedOut) {
11170                Slog.i(TAG, "Session already timed out");
11171                return -1;
11172            }
11173
11174            if (mPackageName != null) {
11175                if (! mPackageName.equals(packageName)) {
11176                    Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
11177                            + " on session for package " + mPackageName);
11178                    return -1;
11179                }
11180            }
11181
11182            PackageInfo app = null;
11183            try {
11184                app = mPackageManager.getPackageInfo(packageName, 0);
11185            } catch (NameNotFoundException nnf) {
11186                Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
11187                return -1;
11188            }
11189
11190            // If the caller is not privileged and is not coming from the target
11191            // app's uid, throw a permission exception back to the caller.
11192            int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
11193                    Binder.getCallingPid(), Binder.getCallingUid());
11194            if ((perm == PackageManager.PERMISSION_DENIED) &&
11195                    (app.applicationInfo.uid != Binder.getCallingUid())) {
11196                Slog.w(TAG, "restorePackage: bad packageName=" + packageName
11197                        + " or calling uid=" + Binder.getCallingUid());
11198                throw new SecurityException("No permission to restore other packages");
11199            }
11200
11201            // So far so good; we're allowed to try to restore this package.
11202            long oldId = Binder.clearCallingIdentity();
11203            try {
11204                // Check whether there is data for it in the current dataset, falling back
11205                // to the ancestral dataset if not.
11206                long token = getAvailableRestoreToken(packageName);
11207                if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName
11208                        + " token=" + Long.toHexString(token));
11209
11210                // If we didn't come up with a place to look -- no ancestral dataset and
11211                // the app has never been backed up from this device -- there's nothing
11212                // to do but return failure.
11213                if (token == 0) {
11214                    if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
11215                    return -1;
11216                }
11217
11218                String dirName;
11219                try {
11220                    dirName = mRestoreTransport.transportDirName();
11221                } catch (Exception e) {
11222                    // Transport went AWOL; fail.
11223                    Slog.e(TAG, "Unable to get transport dir for restorePackage: " + e.getMessage());
11224                    return -1;
11225                }
11226
11227                // Stop the session timeout until we finalize the restore
11228                mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
11229
11230                // Ready to go:  enqueue the restore request and claim success
11231                mWakelock.acquire();
11232                if (MORE_DEBUG) {
11233                    Slog.d(TAG, "restorePackage() : " + packageName);
11234                }
11235                Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
11236                msg.obj = new RestoreParams(mRestoreTransport, dirName, observer, monitor,
11237                        token, app);
11238                mBackupHandler.sendMessage(msg);
11239            } finally {
11240                Binder.restoreCallingIdentity(oldId);
11241            }
11242            return 0;
11243        }
11244
11245        // Posted to the handler to tear down a restore session in a cleanly synchronized way
11246        class EndRestoreRunnable implements Runnable {
11247            BackupManagerService mBackupManager;
11248            ActiveRestoreSession mSession;
11249
11250            EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
11251                mBackupManager = manager;
11252                mSession = session;
11253            }
11254
11255            public void run() {
11256                // clean up the session's bookkeeping
11257                synchronized (mSession) {
11258                    mSession.mRestoreTransport = null;
11259                    mSession.mEnded = true;
11260                }
11261
11262                // clean up the BackupManagerImpl side of the bookkeeping
11263                // and cancel any pending timeout message
11264                mBackupManager.clearRestoreSession(mSession);
11265            }
11266        }
11267
11268        public synchronized void endRestoreSession() {
11269            if (DEBUG) Slog.d(TAG, "endRestoreSession");
11270
11271            if (mTimedOut) {
11272                Slog.i(TAG, "Session already timed out");
11273                return;
11274            }
11275
11276            if (mEnded) {
11277                throw new IllegalStateException("Restore session already ended");
11278            }
11279
11280            mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
11281        }
11282    }
11283
11284    @Override
11285    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11286        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
11287
11288        long identityToken = Binder.clearCallingIdentity();
11289        try {
11290            if (args != null) {
11291                for (String arg : args) {
11292                    if ("-h".equals(arg)) {
11293                        pw.println("'dumpsys backup' optional arguments:");
11294                        pw.println("  -h       : this help text");
11295                        pw.println("  a[gents] : dump information about defined backup agents");
11296                        return;
11297                    } else if ("agents".startsWith(arg)) {
11298                        dumpAgents(pw);
11299                        return;
11300                    }
11301                }
11302            }
11303            dumpInternal(pw);
11304        } finally {
11305            Binder.restoreCallingIdentity(identityToken);
11306        }
11307    }
11308
11309    private void dumpAgents(PrintWriter pw) {
11310        List<PackageInfo> agentPackages = allAgentPackages();
11311        pw.println("Defined backup agents:");
11312        for (PackageInfo pkg : agentPackages) {
11313            pw.print("  ");
11314            pw.print(pkg.packageName); pw.println(':');
11315            pw.print("      "); pw.println(pkg.applicationInfo.backupAgentName);
11316        }
11317    }
11318
11319    private void dumpInternal(PrintWriter pw) {
11320        synchronized (mQueueLock) {
11321            pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
11322                    + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
11323                    + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
11324            pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
11325            if (mBackupRunning) pw.println("Backup currently running");
11326            pw.println("Last backup pass started: " + mLastBackupPass
11327                    + " (now = " + System.currentTimeMillis() + ')');
11328            pw.println("  next scheduled: " + KeyValueBackupJob.nextScheduled());
11329
11330            pw.println("Transport whitelist:");
11331            for (ComponentName transport : mTransportManager.getTransportWhitelist()) {
11332                pw.print("    ");
11333                pw.println(transport.flattenToShortString());
11334            }
11335
11336            pw.println("Available transports:");
11337            final String[] transports = listAllTransports();
11338            if (transports != null) {
11339                for (String t : listAllTransports()) {
11340                    pw.println((t.equals(mTransportManager.getCurrentTransportName()) ? "  * " : "    ") + t);
11341                    try {
11342                        IBackupTransport transport = mTransportManager.getTransportBinder(t);
11343                        File dir = new File(mBaseStateDir, transport.transportDirName());
11344                        pw.println("       destination: " + transport.currentDestinationString());
11345                        pw.println("       intent: " + transport.configurationIntent());
11346                        for (File f : dir.listFiles()) {
11347                            pw.println("       " + f.getName() + " - " + f.length() + " state bytes");
11348                        }
11349                    } catch (Exception e) {
11350                        Slog.e(TAG, "Error in transport", e);
11351                        pw.println("        Error: " + e);
11352                    }
11353                }
11354            }
11355
11356            pw.println("Pending init: " + mPendingInits.size());
11357            for (String s : mPendingInits) {
11358                pw.println("    " + s);
11359            }
11360
11361            if (DEBUG_BACKUP_TRACE) {
11362                synchronized (mBackupTrace) {
11363                    if (!mBackupTrace.isEmpty()) {
11364                        pw.println("Most recent backup trace:");
11365                        for (String s : mBackupTrace) {
11366                            pw.println("   " + s);
11367                        }
11368                    }
11369                }
11370            }
11371
11372            pw.print("Ancestral: "); pw.println(Long.toHexString(mAncestralToken));
11373            pw.print("Current:   "); pw.println(Long.toHexString(mCurrentToken));
11374
11375            int N = mBackupParticipants.size();
11376            pw.println("Participants:");
11377            for (int i=0; i<N; i++) {
11378                int uid = mBackupParticipants.keyAt(i);
11379                pw.print("  uid: ");
11380                pw.println(uid);
11381                HashSet<String> participants = mBackupParticipants.valueAt(i);
11382                for (String app: participants) {
11383                    pw.println("    " + app);
11384                }
11385            }
11386
11387            pw.println("Ancestral packages: "
11388                    + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
11389            if (mAncestralPackages != null) {
11390                for (String pkg : mAncestralPackages) {
11391                    pw.println("    " + pkg);
11392                }
11393            }
11394
11395            pw.println("Ever backed up: " + mEverStoredApps.size());
11396            for (String pkg : mEverStoredApps) {
11397                pw.println("    " + pkg);
11398            }
11399
11400            pw.println("Pending key/value backup: " + mPendingBackups.size());
11401            for (BackupRequest req : mPendingBackups.values()) {
11402                pw.println("    " + req);
11403            }
11404
11405            pw.println("Full backup queue:" + mFullBackupQueue.size());
11406            for (FullBackupEntry entry : mFullBackupQueue) {
11407                pw.print("    "); pw.print(entry.lastBackup);
11408                pw.print(" : "); pw.println(entry.packageName);
11409            }
11410        }
11411    }
11412
11413    private static void sendBackupOnUpdate(IBackupObserver observer, String packageName,
11414            BackupProgress progress) {
11415        if (observer != null) {
11416            try {
11417                observer.onUpdate(packageName, progress);
11418            } catch (RemoteException e) {
11419                if (DEBUG) {
11420                    Slog.w(TAG, "Backup observer went away: onUpdate");
11421                }
11422            }
11423        }
11424    }
11425
11426    private static void sendBackupOnPackageResult(IBackupObserver observer, String packageName,
11427            int status) {
11428        if (observer != null) {
11429            try {
11430                observer.onResult(packageName, status);
11431            } catch (RemoteException e) {
11432                if (DEBUG) {
11433                    Slog.w(TAG, "Backup observer went away: onResult");
11434                }
11435            }
11436        }
11437    }
11438
11439    private static void sendBackupFinished(IBackupObserver observer, int status) {
11440        if (observer != null) {
11441            try {
11442                observer.backupFinished(status);
11443            } catch (RemoteException e) {
11444                if (DEBUG) {
11445                    Slog.w(TAG, "Backup observer went away: backupFinished");
11446                }
11447            }
11448        }
11449    }
11450
11451    private Bundle putMonitoringExtra(Bundle extras, String key, String value) {
11452        if (extras == null) {
11453            extras = new Bundle();
11454        }
11455        extras.putString(key, value);
11456        return extras;
11457    }
11458
11459    private Bundle putMonitoringExtra(Bundle extras, String key, int value) {
11460        if (extras == null) {
11461            extras = new Bundle();
11462        }
11463        extras.putInt(key, value);
11464        return extras;
11465    }
11466
11467    private Bundle putMonitoringExtra(Bundle extras, String key, long value) {
11468        if (extras == null) {
11469            extras = new Bundle();
11470        }
11471        extras.putLong(key, value);
11472        return extras;
11473    }
11474
11475
11476    private Bundle putMonitoringExtra(Bundle extras, String key, boolean value) {
11477        if (extras == null) {
11478            extras = new Bundle();
11479        }
11480        extras.putBoolean(key, value);
11481        return extras;
11482    }
11483
11484    private static IBackupManagerMonitor monitorEvent(IBackupManagerMonitor monitor, int id,
11485            PackageInfo pkg, int category, Bundle extras) {
11486        if (monitor != null) {
11487            try {
11488                Bundle bundle = new Bundle();
11489                bundle.putInt(BackupManagerMonitor.EXTRA_LOG_EVENT_ID, id);
11490                bundle.putInt(BackupManagerMonitor.EXTRA_LOG_EVENT_CATEGORY, category);
11491                if (pkg != null) {
11492                    bundle.putString(EXTRA_LOG_EVENT_PACKAGE_NAME,
11493                            pkg.packageName);
11494                    bundle.putInt(BackupManagerMonitor.EXTRA_LOG_EVENT_PACKAGE_VERSION,
11495                            pkg.versionCode);
11496                }
11497                if (extras != null) {
11498                    bundle.putAll(extras);
11499                }
11500                monitor.onEvent(bundle);
11501                return monitor;
11502            } catch(RemoteException e) {
11503                if (DEBUG) {
11504                    Slog.w(TAG, "backup manager monitor went away");
11505                }
11506            }
11507        }
11508        return null;
11509    }
11510
11511    @Override
11512    public IBackupManager getBackupManagerBinder() {
11513        return mBackupManagerBinder;
11514    }
11515
11516}
11517