BackupManagerService.java revision b2707afb0cbf955952d313e4c75fd3bfd3a35e98
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 android.app.ActivityManagerNative;
20import android.app.AlarmManager;
21import android.app.AppGlobals;
22import android.app.IActivityManager;
23import android.app.IApplicationThread;
24import android.app.IBackupAgent;
25import android.app.PendingIntent;
26import android.app.backup.BackupAgent;
27import android.app.backup.BackupDataInput;
28import android.app.backup.BackupDataOutput;
29import android.app.backup.BackupTransport;
30import android.app.backup.FullBackup;
31import android.app.backup.RestoreDescription;
32import android.app.backup.RestoreSet;
33import android.app.backup.IBackupManager;
34import android.app.backup.IFullBackupRestoreObserver;
35import android.app.backup.IRestoreObserver;
36import android.app.backup.IRestoreSession;
37import android.content.ActivityNotFoundException;
38import android.content.BroadcastReceiver;
39import android.content.ComponentName;
40import android.content.ContentResolver;
41import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
44import android.content.ServiceConnection;
45import android.content.pm.ApplicationInfo;
46import android.content.pm.IPackageDataObserver;
47import android.content.pm.IPackageDeleteObserver;
48import android.content.pm.IPackageInstallObserver;
49import android.content.pm.IPackageManager;
50import android.content.pm.PackageInfo;
51import android.content.pm.PackageManager;
52import android.content.pm.ResolveInfo;
53import android.content.pm.ServiceInfo;
54import android.content.pm.Signature;
55import android.content.pm.PackageManager.NameNotFoundException;
56import android.database.ContentObserver;
57import android.net.Uri;
58import android.os.Binder;
59import android.os.Build;
60import android.os.Bundle;
61import android.os.Environment;
62import android.os.Handler;
63import android.os.HandlerThread;
64import android.os.IBinder;
65import android.os.Looper;
66import android.os.Message;
67import android.os.ParcelFileDescriptor;
68import android.os.PowerManager;
69import android.os.Process;
70import android.os.RemoteException;
71import android.os.SELinux;
72import android.os.ServiceManager;
73import android.os.SystemClock;
74import android.os.UserHandle;
75import android.os.WorkSource;
76import android.os.Environment.UserEnvironment;
77import android.os.storage.IMountService;
78import android.provider.Settings;
79import android.system.ErrnoException;
80import android.system.Os;
81import android.util.ArrayMap;
82import android.util.AtomicFile;
83import android.util.EventLog;
84import android.util.Log;
85import android.util.Slog;
86import android.util.SparseArray;
87import android.util.StringBuilderPrinter;
88
89import com.android.internal.backup.IBackupTransport;
90import com.android.internal.backup.IObbBackupService;
91import com.android.server.AppWidgetBackupBridge;
92import com.android.server.EventLogTags;
93import com.android.server.SystemService;
94import com.android.server.backup.PackageManagerBackupAgent.Metadata;
95
96import java.io.BufferedInputStream;
97import java.io.BufferedOutputStream;
98import java.io.ByteArrayInputStream;
99import java.io.ByteArrayOutputStream;
100import java.io.DataInputStream;
101import java.io.DataOutputStream;
102import java.io.EOFException;
103import java.io.File;
104import java.io.FileDescriptor;
105import java.io.FileInputStream;
106import java.io.FileNotFoundException;
107import java.io.FileOutputStream;
108import java.io.IOException;
109import java.io.InputStream;
110import java.io.OutputStream;
111import java.io.PrintWriter;
112import java.io.RandomAccessFile;
113import java.security.InvalidAlgorithmParameterException;
114import java.security.InvalidKeyException;
115import java.security.Key;
116import java.security.MessageDigest;
117import java.security.NoSuchAlgorithmException;
118import java.security.SecureRandom;
119import java.security.spec.InvalidKeySpecException;
120import java.security.spec.KeySpec;
121import java.text.SimpleDateFormat;
122import java.util.ArrayList;
123import java.util.Arrays;
124import java.util.Collections;
125import java.util.Date;
126import java.util.HashMap;
127import java.util.HashSet;
128import java.util.Iterator;
129import java.util.List;
130import java.util.Map;
131import java.util.Map.Entry;
132import java.util.Random;
133import java.util.Set;
134import java.util.TreeMap;
135import java.util.concurrent.atomic.AtomicBoolean;
136import java.util.concurrent.atomic.AtomicInteger;
137import java.util.zip.Deflater;
138import java.util.zip.DeflaterOutputStream;
139import java.util.zip.InflaterInputStream;
140
141import javax.crypto.BadPaddingException;
142import javax.crypto.Cipher;
143import javax.crypto.CipherInputStream;
144import javax.crypto.CipherOutputStream;
145import javax.crypto.IllegalBlockSizeException;
146import javax.crypto.NoSuchPaddingException;
147import javax.crypto.SecretKey;
148import javax.crypto.SecretKeyFactory;
149import javax.crypto.spec.IvParameterSpec;
150import javax.crypto.spec.PBEKeySpec;
151import javax.crypto.spec.SecretKeySpec;
152
153import libcore.io.IoUtils;
154
155public class BackupManagerService extends IBackupManager.Stub {
156
157    private static final String TAG = "BackupManagerService";
158    private static final boolean DEBUG = true;
159    private static final boolean MORE_DEBUG = false;
160    private static final boolean DEBUG_SCHEDULING = MORE_DEBUG || true;
161
162    // System-private key used for backing up an app's widget state.  Must
163    // begin with U+FFxx by convention (we reserve all keys starting
164    // with U+FF00 or higher for system use).
165    static final String KEY_WIDGET_STATE = "\uffed\uffedwidget";
166
167    // Historical and current algorithm names
168    static final String PBKDF_CURRENT = "PBKDF2WithHmacSHA1";
169    static final String PBKDF_FALLBACK = "PBKDF2WithHmacSHA1And8bit";
170
171    // Name and current contents version of the full-backup manifest file
172    //
173    // Manifest version history:
174    //
175    // 1 : initial release
176    static final String BACKUP_MANIFEST_FILENAME = "_manifest";
177    static final int BACKUP_MANIFEST_VERSION = 1;
178
179    // External archive format version history:
180    //
181    // 1 : initial release
182    // 2 : no format change per se; version bump to facilitate PBKDF2 version skew detection
183    // 3 : introduced "_meta" metadata file; no other format change per se
184    static final int BACKUP_FILE_VERSION = 3;
185    static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
186    static final int BACKUP_PW_FILE_VERSION = 2;
187    static final String BACKUP_METADATA_FILENAME = "_meta";
188    static final int BACKUP_METADATA_VERSION = 1;
189    static final int BACKUP_WIDGET_METADATA_TOKEN = 0x01FFED01;
190    static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
191
192    static final String SETTINGS_PACKAGE = "com.android.providers.settings";
193    static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
194    static final String SERVICE_ACTION_TRANSPORT_HOST = "android.backup.TRANSPORT_HOST";
195
196    // How often we perform a backup pass.  Privileged external callers can
197    // trigger an immediate pass.
198    private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
199
200    // Random variation in backup scheduling time to avoid server load spikes
201    private static final int FUZZ_MILLIS = 5 * 60 * 1000;
202
203    // The amount of time between the initial provisioning of the device and
204    // the first backup pass.
205    private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
206
207    // Retry interval for clear/init when the transport is unavailable
208    private static final long TRANSPORT_RETRY_INTERVAL = 1 * AlarmManager.INTERVAL_HOUR;
209
210    private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
211    private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
212    private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
213    private static final int MSG_RUN_BACKUP = 1;
214    private static final int MSG_RUN_ADB_BACKUP = 2;
215    private static final int MSG_RUN_RESTORE = 3;
216    private static final int MSG_RUN_CLEAR = 4;
217    private static final int MSG_RUN_INITIALIZE = 5;
218    private static final int MSG_RUN_GET_RESTORE_SETS = 6;
219    private static final int MSG_TIMEOUT = 7;
220    private static final int MSG_RESTORE_TIMEOUT = 8;
221    private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
222    private static final int MSG_RUN_ADB_RESTORE = 10;
223    private static final int MSG_RETRY_INIT = 11;
224    private static final int MSG_RETRY_CLEAR = 12;
225    private static final int MSG_WIDGET_BROADCAST = 13;
226    private static final int MSG_RUN_FULL_TRANSPORT_BACKUP = 14;
227
228    // backup task state machine tick
229    static final int MSG_BACKUP_RESTORE_STEP = 20;
230    static final int MSG_OP_COMPLETE = 21;
231
232    // Timeout interval for deciding that a bind or clear-data has taken too long
233    static final long TIMEOUT_INTERVAL = 10 * 1000;
234
235    // Timeout intervals for agent backup & restore operations
236    static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
237    static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
238    static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
239    static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
240    static final long TIMEOUT_RESTORE_FINISHED_INTERVAL = 30 * 1000;
241
242    // User confirmation timeout for a full backup/restore operation.  It's this long in
243    // order to give them time to enter the backup password.
244    static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
245
246    // How long between attempts to perform a full-data backup of any given app
247    static final long MIN_FULL_BACKUP_INTERVAL = 1000 * 60 * 60 * 24; // one day
248
249    Context mContext;
250    private PackageManager mPackageManager;
251    IPackageManager mPackageManagerBinder;
252    private IActivityManager mActivityManager;
253    private PowerManager mPowerManager;
254    private AlarmManager mAlarmManager;
255    private IMountService mMountService;
256    IBackupManager mBackupManagerBinder;
257
258    boolean mEnabled;   // access to this is synchronized on 'this'
259    boolean mProvisioned;
260    boolean mAutoRestore;
261    PowerManager.WakeLock mWakelock;
262    HandlerThread mHandlerThread;
263    BackupHandler mBackupHandler;
264    PendingIntent mRunBackupIntent, mRunInitIntent;
265    BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
266    // map UIDs to the set of participating packages under that UID
267    final SparseArray<HashSet<String>> mBackupParticipants
268            = new SparseArray<HashSet<String>>();
269    // set of backup services that have pending changes
270    class BackupRequest {
271        public String packageName;
272
273        BackupRequest(String pkgName) {
274            packageName = pkgName;
275        }
276
277        public String toString() {
278            return "BackupRequest{pkg=" + packageName + "}";
279        }
280    }
281    // Backups that we haven't started yet.  Keys are package names.
282    HashMap<String,BackupRequest> mPendingBackups
283            = new HashMap<String,BackupRequest>();
284
285    // Pseudoname that we use for the Package Manager metadata "package"
286    static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
287
288    // locking around the pending-backup management
289    final Object mQueueLock = new Object();
290
291    // The thread performing the sequence of queued backups binds to each app's agent
292    // in succession.  Bind notifications are asynchronously delivered through the
293    // Activity Manager; use this lock object to signal when a requested binding has
294    // completed.
295    final Object mAgentConnectLock = new Object();
296    IBackupAgent mConnectedAgent;
297    volatile boolean mBackupRunning;
298    volatile boolean mConnecting;
299    volatile long mLastBackupPass;
300    volatile long mNextBackupPass;
301
302    // For debugging, we maintain a progress trace of operations during backup
303    static final boolean DEBUG_BACKUP_TRACE = true;
304    final List<String> mBackupTrace = new ArrayList<String>();
305
306    // A similar synchronization mechanism around clearing apps' data for restore
307    final Object mClearDataLock = new Object();
308    volatile boolean mClearingData;
309
310    // Transport bookkeeping
311    final Intent mTransportServiceIntent = new Intent(SERVICE_ACTION_TRANSPORT_HOST);
312    final ArrayMap<String,String> mTransportNames
313            = new ArrayMap<String,String>();             // component name -> registration name
314    final ArrayMap<String,IBackupTransport> mTransports
315            = new ArrayMap<String,IBackupTransport>();   // registration name -> binder
316    final ArrayMap<String,TransportConnection> mTransportConnections
317            = new ArrayMap<String,TransportConnection>();
318    String mCurrentTransport;
319    ActiveRestoreSession mActiveRestoreSession;
320
321    // Watch the device provisioning operation during setup
322    ContentObserver mProvisionedObserver;
323
324    static BackupManagerService sInstance;
325    static BackupManagerService getInstance() {
326        // Always constructed during system bringup, so no need to lazy-init
327        return sInstance;
328    }
329
330    public static final class Lifecycle extends SystemService {
331
332        public Lifecycle(Context context) {
333            super(context);
334            sInstance = new BackupManagerService(context);
335        }
336
337        @Override
338        public void onStart() {
339            publishBinderService(Context.BACKUP_SERVICE, sInstance);
340        }
341
342        @Override
343        public void onBootPhase(int phase) {
344            if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
345                ContentResolver r = sInstance.mContext.getContentResolver();
346                boolean areEnabled = Settings.Secure.getInt(r,
347                        Settings.Secure.BACKUP_ENABLED, 0) != 0;
348                sInstance.setBackupEnabled(areEnabled);
349            }
350        }
351    }
352
353    class ProvisionedObserver extends ContentObserver {
354        public ProvisionedObserver(Handler handler) {
355            super(handler);
356        }
357
358        public void onChange(boolean selfChange) {
359            final boolean wasProvisioned = mProvisioned;
360            final boolean isProvisioned = deviceIsProvisioned();
361            // latch: never unprovision
362            mProvisioned = wasProvisioned || isProvisioned;
363            if (MORE_DEBUG) {
364                Slog.d(TAG, "Provisioning change: was=" + wasProvisioned
365                        + " is=" + isProvisioned + " now=" + mProvisioned);
366            }
367
368            synchronized (mQueueLock) {
369                if (mProvisioned && !wasProvisioned && mEnabled) {
370                    // we're now good to go, so start the backup alarms
371                    if (MORE_DEBUG) Slog.d(TAG, "Now provisioned, so starting backups");
372                    startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
373                }
374            }
375        }
376    }
377
378    class RestoreGetSetsParams {
379        public IBackupTransport transport;
380        public ActiveRestoreSession session;
381        public IRestoreObserver observer;
382
383        RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
384                IRestoreObserver _observer) {
385            transport = _transport;
386            session = _session;
387            observer = _observer;
388        }
389    }
390
391    class RestoreParams {
392        public IBackupTransport transport;
393        public String dirName;
394        public IRestoreObserver observer;
395        public long token;
396        public PackageInfo pkgInfo;
397        public int pmToken; // in post-install restore, the PM's token for this transaction
398        public boolean isSystemRestore;
399        public String[] filterSet;
400
401        // Restore a single package
402        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
403                long _token, PackageInfo _pkg, int _pmToken) {
404            transport = _transport;
405            dirName = _dirName;
406            observer = _obs;
407            token = _token;
408            pkgInfo = _pkg;
409            pmToken = _pmToken;
410            isSystemRestore = false;
411            filterSet = null;
412        }
413
414        // Restore everything possible.  This is the form that Setup Wizard or similar
415        // restore UXes use.
416        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
417                long _token) {
418            transport = _transport;
419            dirName = _dirName;
420            observer = _obs;
421            token = _token;
422            pkgInfo = null;
423            pmToken = 0;
424            isSystemRestore = true;
425            filterSet = null;
426        }
427
428        // Restore some set of packages.  Leave this one up to the caller to specify
429        // whether it's to be considered a system-level restore.
430        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
431                long _token, String[] _filterSet, boolean _isSystemRestore) {
432            transport = _transport;
433            dirName = _dirName;
434            observer = _obs;
435            token = _token;
436            pkgInfo = null;
437            pmToken = 0;
438            isSystemRestore = _isSystemRestore;
439            filterSet = _filterSet;
440        }
441    }
442
443    class ClearParams {
444        public IBackupTransport transport;
445        public PackageInfo packageInfo;
446
447        ClearParams(IBackupTransport _transport, PackageInfo _info) {
448            transport = _transport;
449            packageInfo = _info;
450        }
451    }
452
453    class ClearRetryParams {
454        public String transportName;
455        public String packageName;
456
457        ClearRetryParams(String transport, String pkg) {
458            transportName = transport;
459            packageName = pkg;
460        }
461    }
462
463    class FullParams {
464        public ParcelFileDescriptor fd;
465        public final AtomicBoolean latch;
466        public IFullBackupRestoreObserver observer;
467        public String curPassword;     // filled in by the confirmation step
468        public String encryptPassword;
469
470        FullParams() {
471            latch = new AtomicBoolean(false);
472        }
473    }
474
475    class FullBackupParams extends FullParams {
476        public boolean includeApks;
477        public boolean includeObbs;
478        public boolean includeShared;
479        public boolean doWidgets;
480        public boolean allApps;
481        public boolean includeSystem;
482        public boolean doCompress;
483        public String[] packages;
484
485        FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveObbs,
486                boolean saveShared, boolean alsoWidgets, boolean doAllApps, boolean doSystem,
487                boolean compress, String[] pkgList) {
488            fd = output;
489            includeApks = saveApks;
490            includeObbs = saveObbs;
491            includeShared = saveShared;
492            doWidgets = alsoWidgets;
493            allApps = doAllApps;
494            includeSystem = doSystem;
495            doCompress = compress;
496            packages = pkgList;
497        }
498    }
499
500    class FullRestoreParams extends FullParams {
501        FullRestoreParams(ParcelFileDescriptor input) {
502            fd = input;
503        }
504    }
505
506    // Bookkeeping of in-flight operations for timeout etc. purposes.  The operation
507    // token is the index of the entry in the pending-operations list.
508    static final int OP_PENDING = 0;
509    static final int OP_ACKNOWLEDGED = 1;
510    static final int OP_TIMEOUT = -1;
511
512    class Operation {
513        public int state;
514        public BackupRestoreTask callback;
515
516        Operation(int initialState, BackupRestoreTask callbackObj) {
517            state = initialState;
518            callback = callbackObj;
519        }
520    }
521    final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
522    final Object mCurrentOpLock = new Object();
523    final Random mTokenGenerator = new Random();
524
525    final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
526
527    // Where we keep our journal files and other bookkeeping
528    File mBaseStateDir;
529    File mDataDir;
530    File mJournalDir;
531    File mJournal;
532
533    // Backup password, if any, and the file where it's saved.  What is stored is not the
534    // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
535    // persisted) salt.  Validation is performed by running the challenge text through the
536    // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
537    // the saved hash string, then the challenge text matches the originally supplied
538    // password text.
539    private final SecureRandom mRng = new SecureRandom();
540    private String mPasswordHash;
541    private File mPasswordHashFile;
542    private int mPasswordVersion;
543    private File mPasswordVersionFile;
544    private byte[] mPasswordSalt;
545
546    // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
547    static final int PBKDF2_HASH_ROUNDS = 10000;
548    static final int PBKDF2_KEY_SIZE = 256;     // bits
549    static final int PBKDF2_SALT_SIZE = 512;    // bits
550    static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
551
552    // Keep a log of all the apps we've ever backed up, and what the
553    // dataset tokens are for both the current backup dataset and
554    // the ancestral dataset.
555    private File mEverStored;
556    HashSet<String> mEverStoredApps = new HashSet<String>();
557
558    static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1;  // increment when the schema changes
559    File mTokenFile;
560    Set<String> mAncestralPackages = null;
561    long mAncestralToken = 0;
562    long mCurrentToken = 0;
563
564    // Persistently track the need to do a full init
565    static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
566    HashSet<String> mPendingInits = new HashSet<String>();  // transport names
567
568    // Round-robin queue for scheduling full backup passes
569    static final int SCHEDULE_FILE_VERSION = 1; // current version of the schedule file
570    class FullBackupEntry implements Comparable<FullBackupEntry> {
571        String packageName;
572        long lastBackup;
573
574        FullBackupEntry(String pkg, long when) {
575            packageName = pkg;
576            lastBackup = when;
577        }
578
579        @Override
580        public int compareTo(FullBackupEntry other) {
581            if (lastBackup < other.lastBackup) return -1;
582            else if (lastBackup > other.lastBackup) return 1;
583            else return 0;
584        }
585    }
586
587    File mFullBackupScheduleFile;
588    // If we're running a schedule-driven full backup, this is the task instance doing it
589    PerformFullTransportBackupTask mRunningFullBackupTask; // inside mQueueLock
590    ArrayList<FullBackupEntry> mFullBackupQueue;           // inside mQueueLock
591
592    // Utility: build a new random integer token
593    int generateToken() {
594        int token;
595        do {
596            synchronized (mTokenGenerator) {
597                token = mTokenGenerator.nextInt();
598            }
599        } while (token < 0);
600        return token;
601    }
602
603    // High level policy: apps are ineligible for backup if certain conditions apply
604    public static boolean appIsEligibleForBackup(ApplicationInfo app) {
605        // 1. their manifest states android:allowBackup="false"
606        if ((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
607            return false;
608        }
609
610        // 2. they run as a system-level uid but do not supply their own backup agent
611        if ((app.uid < Process.FIRST_APPLICATION_UID) && (app.backupAgentName == null)) {
612            return false;
613        }
614
615        // 3. it is the special shared-storage backup package used for 'adb backup'
616        if (app.packageName.equals(BackupManagerService.SHARED_BACKUP_AGENT_PACKAGE)) {
617            return false;
618        }
619
620        return true;
621    }
622
623    /* does *not* check overall backup eligibility policy! */
624    public static boolean appGetsFullBackup(PackageInfo pkg) {
625        if (pkg.applicationInfo.backupAgentName != null) {
626            // If it has an agent, it gets full backups only if it says so
627            return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FULL_BACKUP_ONLY) != 0;
628        }
629
630        // No agent means we do full backups for it
631        return true;
632    }
633
634    // ----- Asynchronous backup/restore handler thread -----
635
636    private class BackupHandler extends Handler {
637        public BackupHandler(Looper looper) {
638            super(looper);
639        }
640
641        public void handleMessage(Message msg) {
642
643            switch (msg.what) {
644            case MSG_RUN_BACKUP:
645            {
646                mLastBackupPass = System.currentTimeMillis();
647                mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
648
649                IBackupTransport transport = getTransport(mCurrentTransport);
650                if (transport == null) {
651                    Slog.v(TAG, "Backup requested but no transport available");
652                    synchronized (mQueueLock) {
653                        mBackupRunning = false;
654                    }
655                    mWakelock.release();
656                    break;
657                }
658
659                // snapshot the pending-backup set and work on that
660                ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
661                File oldJournal = mJournal;
662                synchronized (mQueueLock) {
663                    // Do we have any work to do?  Construct the work queue
664                    // then release the synchronization lock to actually run
665                    // the backup.
666                    if (mPendingBackups.size() > 0) {
667                        for (BackupRequest b: mPendingBackups.values()) {
668                            queue.add(b);
669                        }
670                        if (DEBUG) Slog.v(TAG, "clearing pending backups");
671                        mPendingBackups.clear();
672
673                        // Start a new backup-queue journal file too
674                        mJournal = null;
675
676                    }
677                }
678
679                // At this point, we have started a new journal file, and the old
680                // file identity is being passed to the backup processing task.
681                // When it completes successfully, that old journal file will be
682                // deleted.  If we crash prior to that, the old journal is parsed
683                // at next boot and the journaled requests fulfilled.
684                boolean staged = true;
685                if (queue.size() > 0) {
686                    // Spin up a backup state sequence and set it running
687                    try {
688                        String dirName = transport.transportDirName();
689                        PerformBackupTask pbt = new PerformBackupTask(transport, dirName,
690                                queue, oldJournal);
691                        Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
692                        sendMessage(pbtMessage);
693                    } catch (RemoteException e) {
694                        // unable to ask the transport its dir name -- transient failure, since
695                        // the above check succeeded.  Try again next time.
696                        Slog.e(TAG, "Transport became unavailable attempting backup");
697                        staged = false;
698                    }
699                } else {
700                    Slog.v(TAG, "Backup requested but nothing pending");
701                    staged = false;
702                }
703
704                if (!staged) {
705                    // if we didn't actually hand off the wakelock, rewind until next time
706                    synchronized (mQueueLock) {
707                        mBackupRunning = false;
708                    }
709                    mWakelock.release();
710                }
711                break;
712            }
713
714            case MSG_BACKUP_RESTORE_STEP:
715            {
716                try {
717                    BackupRestoreTask task = (BackupRestoreTask) msg.obj;
718                    if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
719                    task.execute();
720                } catch (ClassCastException e) {
721                    Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
722                }
723                break;
724            }
725
726            case MSG_OP_COMPLETE:
727            {
728                try {
729                    BackupRestoreTask task = (BackupRestoreTask) msg.obj;
730                    task.operationComplete();
731                } catch (ClassCastException e) {
732                    Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
733                }
734                break;
735            }
736
737            case MSG_RUN_ADB_BACKUP:
738            {
739                // TODO: refactor full backup to be a looper-based state machine
740                // similar to normal backup/restore.
741                FullBackupParams params = (FullBackupParams)msg.obj;
742                PerformAdbBackupTask task = new PerformAdbBackupTask(params.fd,
743                        params.observer, params.includeApks, params.includeObbs,
744                        params.includeShared, params.doWidgets,
745                        params.curPassword, params.encryptPassword,
746                        params.allApps, params.includeSystem, params.doCompress,
747                        params.packages, params.latch);
748                (new Thread(task, "adb-backup")).start();
749                break;
750            }
751
752            case MSG_RUN_FULL_TRANSPORT_BACKUP:
753            {
754                PerformFullTransportBackupTask task = (PerformFullTransportBackupTask) msg.obj;
755                (new Thread(task, "transport-backup")).start();
756                break;
757            }
758
759            case MSG_RUN_RESTORE:
760            {
761                RestoreParams params = (RestoreParams)msg.obj;
762                Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
763                BackupRestoreTask task = new PerformUnifiedRestoreTask(params.transport,
764                        params.observer, params.token, params.pkgInfo, params.pmToken,
765                        params.isSystemRestore, params.filterSet);
766                Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
767                sendMessage(restoreMsg);
768                break;
769            }
770
771            case MSG_RUN_ADB_RESTORE:
772            {
773                // TODO: refactor full restore to be a looper-based state machine
774                // similar to normal backup/restore.
775                FullRestoreParams params = (FullRestoreParams)msg.obj;
776                PerformAdbRestoreTask task = new PerformAdbRestoreTask(params.fd,
777                        params.curPassword, params.encryptPassword,
778                        params.observer, params.latch);
779                (new Thread(task, "adb-restore")).start();
780                break;
781            }
782
783            case MSG_RUN_CLEAR:
784            {
785                ClearParams params = (ClearParams)msg.obj;
786                (new PerformClearTask(params.transport, params.packageInfo)).run();
787                break;
788            }
789
790            case MSG_RETRY_CLEAR:
791            {
792                // reenqueues if the transport remains unavailable
793                ClearRetryParams params = (ClearRetryParams)msg.obj;
794                clearBackupData(params.transportName, params.packageName);
795                break;
796            }
797
798            case MSG_RUN_INITIALIZE:
799            {
800                HashSet<String> queue;
801
802                // Snapshot the pending-init queue and work on that
803                synchronized (mQueueLock) {
804                    queue = new HashSet<String>(mPendingInits);
805                    mPendingInits.clear();
806                }
807
808                (new PerformInitializeTask(queue)).run();
809                break;
810            }
811
812            case MSG_RETRY_INIT:
813            {
814                synchronized (mQueueLock) {
815                    recordInitPendingLocked(msg.arg1 != 0, (String)msg.obj);
816                    mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
817                            mRunInitIntent);
818                }
819                break;
820            }
821
822            case MSG_RUN_GET_RESTORE_SETS:
823            {
824                // Like other async operations, this is entered with the wakelock held
825                RestoreSet[] sets = null;
826                RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
827                try {
828                    sets = params.transport.getAvailableRestoreSets();
829                    // cache the result in the active session
830                    synchronized (params.session) {
831                        params.session.mRestoreSets = sets;
832                    }
833                    if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
834                } catch (Exception e) {
835                    Slog.e(TAG, "Error from transport getting set list");
836                } finally {
837                    if (params.observer != null) {
838                        try {
839                            params.observer.restoreSetsAvailable(sets);
840                        } catch (RemoteException re) {
841                            Slog.e(TAG, "Unable to report listing to observer");
842                        } catch (Exception e) {
843                            Slog.e(TAG, "Restore observer threw", e);
844                        }
845                    }
846
847                    // Done: reset the session timeout clock
848                    removeMessages(MSG_RESTORE_TIMEOUT);
849                    sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
850
851                    mWakelock.release();
852                }
853                break;
854            }
855
856            case MSG_TIMEOUT:
857            {
858                handleTimeout(msg.arg1, msg.obj);
859                break;
860            }
861
862            case MSG_RESTORE_TIMEOUT:
863            {
864                synchronized (BackupManagerService.this) {
865                    if (mActiveRestoreSession != null) {
866                        // Client app left the restore session dangling.  We know that it
867                        // can't be in the middle of an actual restore operation because
868                        // the timeout is suspended while a restore is in progress.  Clean
869                        // up now.
870                        Slog.w(TAG, "Restore session timed out; aborting");
871                        mActiveRestoreSession.markTimedOut();
872                        post(mActiveRestoreSession.new EndRestoreRunnable(
873                                BackupManagerService.this, mActiveRestoreSession));
874                    }
875                }
876                break;
877            }
878
879            case MSG_FULL_CONFIRMATION_TIMEOUT:
880            {
881                synchronized (mFullConfirmations) {
882                    FullParams params = mFullConfirmations.get(msg.arg1);
883                    if (params != null) {
884                        Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
885
886                        // Release the waiter; timeout == completion
887                        signalFullBackupRestoreCompletion(params);
888
889                        // Remove the token from the set
890                        mFullConfirmations.delete(msg.arg1);
891
892                        // Report a timeout to the observer, if any
893                        if (params.observer != null) {
894                            try {
895                                params.observer.onTimeout();
896                            } catch (RemoteException e) {
897                                /* don't care if the app has gone away */
898                            }
899                        }
900                    } else {
901                        Slog.d(TAG, "couldn't find params for token " + msg.arg1);
902                    }
903                }
904                break;
905            }
906
907            case MSG_WIDGET_BROADCAST:
908            {
909                final Intent intent = (Intent) msg.obj;
910                mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
911                break;
912            }
913            }
914        }
915    }
916
917    // ----- Debug-only backup operation trace -----
918    void addBackupTrace(String s) {
919        if (DEBUG_BACKUP_TRACE) {
920            synchronized (mBackupTrace) {
921                mBackupTrace.add(s);
922            }
923        }
924    }
925
926    void clearBackupTrace() {
927        if (DEBUG_BACKUP_TRACE) {
928            synchronized (mBackupTrace) {
929                mBackupTrace.clear();
930            }
931        }
932    }
933
934    // ----- Main service implementation -----
935
936    public BackupManagerService(Context context) {
937        mContext = context;
938        mPackageManager = context.getPackageManager();
939        mPackageManagerBinder = AppGlobals.getPackageManager();
940        mActivityManager = ActivityManagerNative.getDefault();
941
942        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
943        mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
944        mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
945
946        mBackupManagerBinder = asInterface(asBinder());
947
948        // spin up the backup/restore handler thread
949        mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
950        mHandlerThread.start();
951        mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
952
953        // Set up our bookkeeping
954        final ContentResolver resolver = context.getContentResolver();
955        mProvisioned = Settings.Global.getInt(resolver,
956                Settings.Global.DEVICE_PROVISIONED, 0) != 0;
957        mAutoRestore = Settings.Secure.getInt(resolver,
958                Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
959
960        mProvisionedObserver = new ProvisionedObserver(mBackupHandler);
961        resolver.registerContentObserver(
962                Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
963                false, mProvisionedObserver);
964
965        // If Encrypted file systems is enabled or disabled, this call will return the
966        // correct directory.
967        mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
968        mBaseStateDir.mkdirs();
969        if (!SELinux.restorecon(mBaseStateDir)) {
970            Slog.e(TAG, "SELinux restorecon failed on " + mBaseStateDir);
971        }
972        mDataDir = Environment.getDownloadCacheDirectory();
973
974        mPasswordVersion = 1;       // unless we hear otherwise
975        mPasswordVersionFile = new File(mBaseStateDir, "pwversion");
976        if (mPasswordVersionFile.exists()) {
977            FileInputStream fin = null;
978            DataInputStream in = null;
979            try {
980                fin = new FileInputStream(mPasswordVersionFile);
981                in = new DataInputStream(fin);
982                mPasswordVersion = in.readInt();
983            } catch (IOException e) {
984                Slog.e(TAG, "Unable to read backup pw version");
985            } finally {
986                try {
987                    if (in != null) in.close();
988                    if (fin != null) fin.close();
989                } catch (IOException e) {
990                    Slog.w(TAG, "Error closing pw version files");
991                }
992            }
993        }
994
995        mPasswordHashFile = new File(mBaseStateDir, "pwhash");
996        if (mPasswordHashFile.exists()) {
997            FileInputStream fin = null;
998            DataInputStream in = null;
999            try {
1000                fin = new FileInputStream(mPasswordHashFile);
1001                in = new DataInputStream(new BufferedInputStream(fin));
1002                // integer length of the salt array, followed by the salt,
1003                // then the hex pw hash string
1004                int saltLen = in.readInt();
1005                byte[] salt = new byte[saltLen];
1006                in.readFully(salt);
1007                mPasswordHash = in.readUTF();
1008                mPasswordSalt = salt;
1009            } catch (IOException e) {
1010                Slog.e(TAG, "Unable to read saved backup pw hash");
1011            } finally {
1012                try {
1013                    if (in != null) in.close();
1014                    if (fin != null) fin.close();
1015                } catch (IOException e) {
1016                    Slog.w(TAG, "Unable to close streams");
1017                }
1018            }
1019        }
1020
1021        // Alarm receivers for scheduled backups & initialization operations
1022        mRunBackupReceiver = new RunBackupReceiver();
1023        IntentFilter filter = new IntentFilter();
1024        filter.addAction(RUN_BACKUP_ACTION);
1025        context.registerReceiver(mRunBackupReceiver, filter,
1026                android.Manifest.permission.BACKUP, null);
1027
1028        mRunInitReceiver = new RunInitializeReceiver();
1029        filter = new IntentFilter();
1030        filter.addAction(RUN_INITIALIZE_ACTION);
1031        context.registerReceiver(mRunInitReceiver, filter,
1032                android.Manifest.permission.BACKUP, null);
1033
1034        Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
1035        backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1036        mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
1037
1038        Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
1039        backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1040        mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
1041
1042        // Set up the backup-request journaling
1043        mJournalDir = new File(mBaseStateDir, "pending");
1044        mJournalDir.mkdirs();   // creates mBaseStateDir along the way
1045        mJournal = null;        // will be created on first use
1046
1047        // Set up the various sorts of package tracking we do
1048        mFullBackupScheduleFile = new File(mBaseStateDir, "fb-schedule");
1049        initPackageTracking();
1050
1051        // Build our mapping of uid to backup client services.  This implicitly
1052        // schedules a backup pass on the Package Manager metadata the first
1053        // time anything needs to be backed up.
1054        synchronized (mBackupParticipants) {
1055            addPackageParticipantsLocked(null);
1056        }
1057
1058        // Set up our transport options and initialize the default transport
1059        // TODO: Don't create transports that we don't need to?
1060        mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
1061                Settings.Secure.BACKUP_TRANSPORT);
1062        if ("".equals(mCurrentTransport)) {
1063            mCurrentTransport = null;
1064        }
1065        if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
1066
1067        // Find transport hosts and bind to their services
1068        List<ResolveInfo> hosts = mPackageManager.queryIntentServicesAsUser(
1069                mTransportServiceIntent, 0, UserHandle.USER_OWNER);
1070        if (DEBUG) {
1071            Slog.v(TAG, "Found transports: " + ((hosts == null) ? "null" : hosts.size()));
1072        }
1073        if (hosts != null) {
1074            if (MORE_DEBUG) {
1075                for (int i = 0; i < hosts.size(); i++) {
1076                    ServiceInfo info = hosts.get(i).serviceInfo;
1077                    Slog.v(TAG, "   " + info.packageName + "/" + info.name);
1078                }
1079            }
1080            for (int i = 0; i < hosts.size(); i++) {
1081                try {
1082                    ServiceInfo info = hosts.get(i).serviceInfo;
1083                    PackageInfo packInfo = mPackageManager.getPackageInfo(info.packageName, 0);
1084                    if ((packInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
1085                        bindTransport(info);
1086                    } else {
1087                        Slog.w(TAG, "Transport package not privileged: " + info.packageName);
1088                    }
1089                } catch (Exception e) {
1090                    Slog.e(TAG, "Problem resolving transport service: " + e.getMessage());
1091                }
1092            }
1093        }
1094
1095        // Now that we know about valid backup participants, parse any
1096        // leftover journal files into the pending backup set
1097        parseLeftoverJournals();
1098
1099        // Power management
1100        mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
1101    }
1102
1103    private class RunBackupReceiver extends BroadcastReceiver {
1104        public void onReceive(Context context, Intent intent) {
1105            if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
1106                synchronized (mQueueLock) {
1107                    if (mPendingInits.size() > 0) {
1108                        // If there are pending init operations, we process those
1109                        // and then settle into the usual periodic backup schedule.
1110                        if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
1111                        try {
1112                            mAlarmManager.cancel(mRunInitIntent);
1113                            mRunInitIntent.send();
1114                        } catch (PendingIntent.CanceledException ce) {
1115                            Slog.e(TAG, "Run init intent cancelled");
1116                            // can't really do more than bail here
1117                        }
1118                    } else {
1119                        // Don't run backups now if we're disabled or not yet
1120                        // fully set up.
1121                        if (mEnabled && mProvisioned) {
1122                            if (!mBackupRunning) {
1123                                if (DEBUG) Slog.v(TAG, "Running a backup pass");
1124
1125                                // Acquire the wakelock and pass it to the backup thread.  it will
1126                                // be released once backup concludes.
1127                                mBackupRunning = true;
1128                                mWakelock.acquire();
1129
1130                                Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
1131                                mBackupHandler.sendMessage(msg);
1132                            } else {
1133                                Slog.i(TAG, "Backup time but one already running");
1134                            }
1135                        } else {
1136                            Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
1137                        }
1138                    }
1139                }
1140            }
1141        }
1142    }
1143
1144    private class RunInitializeReceiver extends BroadcastReceiver {
1145        public void onReceive(Context context, Intent intent) {
1146            if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
1147                synchronized (mQueueLock) {
1148                    if (DEBUG) Slog.v(TAG, "Running a device init");
1149
1150                    // Acquire the wakelock and pass it to the init thread.  it will
1151                    // be released once init concludes.
1152                    mWakelock.acquire();
1153
1154                    Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
1155                    mBackupHandler.sendMessage(msg);
1156                }
1157            }
1158        }
1159    }
1160
1161    private void initPackageTracking() {
1162        if (MORE_DEBUG) Slog.v(TAG, "` tracking");
1163
1164        // Remember our ancestral dataset
1165        mTokenFile = new File(mBaseStateDir, "ancestral");
1166        try {
1167            RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
1168            int version = tf.readInt();
1169            if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
1170                mAncestralToken = tf.readLong();
1171                mCurrentToken = tf.readLong();
1172
1173                int numPackages = tf.readInt();
1174                if (numPackages >= 0) {
1175                    mAncestralPackages = new HashSet<String>();
1176                    for (int i = 0; i < numPackages; i++) {
1177                        String pkgName = tf.readUTF();
1178                        mAncestralPackages.add(pkgName);
1179                    }
1180                }
1181            }
1182            tf.close();
1183        } catch (FileNotFoundException fnf) {
1184            // Probably innocuous
1185            Slog.v(TAG, "No ancestral data");
1186        } catch (IOException e) {
1187            Slog.w(TAG, "Unable to read token file", e);
1188        }
1189
1190        // Keep a log of what apps we've ever backed up.  Because we might have
1191        // rebooted in the middle of an operation that was removing something from
1192        // this log, we sanity-check its contents here and reconstruct it.
1193        mEverStored = new File(mBaseStateDir, "processed");
1194        File tempProcessedFile = new File(mBaseStateDir, "processed.new");
1195
1196        // If we were in the middle of removing something from the ever-backed-up
1197        // file, there might be a transient "processed.new" file still present.
1198        // Ignore it -- we'll validate "processed" against the current package set.
1199        if (tempProcessedFile.exists()) {
1200            tempProcessedFile.delete();
1201        }
1202
1203        // If there are previous contents, parse them out then start a new
1204        // file to continue the recordkeeping.
1205        if (mEverStored.exists()) {
1206            RandomAccessFile temp = null;
1207            RandomAccessFile in = null;
1208
1209            try {
1210                temp = new RandomAccessFile(tempProcessedFile, "rws");
1211                in = new RandomAccessFile(mEverStored, "r");
1212
1213                while (true) {
1214                    PackageInfo info;
1215                    String pkg = in.readUTF();
1216                    try {
1217                        info = mPackageManager.getPackageInfo(pkg, 0);
1218                        mEverStoredApps.add(pkg);
1219                        temp.writeUTF(pkg);
1220                        if (MORE_DEBUG) Slog.v(TAG, "   + " + pkg);
1221                    } catch (NameNotFoundException e) {
1222                        // nope, this package was uninstalled; don't include it
1223                        if (MORE_DEBUG) Slog.v(TAG, "   - " + pkg);
1224                    }
1225                }
1226            } catch (EOFException e) {
1227                // Once we've rewritten the backup history log, atomically replace the
1228                // old one with the new one then reopen the file for continuing use.
1229                if (!tempProcessedFile.renameTo(mEverStored)) {
1230                    Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
1231                }
1232            } catch (IOException e) {
1233                Slog.e(TAG, "Error in processed file", e);
1234            } finally {
1235                try { if (temp != null) temp.close(); } catch (IOException e) {}
1236                try { if (in != null) in.close(); } catch (IOException e) {}
1237            }
1238        }
1239
1240        // Resume the full-data backup queue
1241        mFullBackupQueue = readFullBackupSchedule();
1242
1243        // Register for broadcasts about package install, etc., so we can
1244        // update the provider list.
1245        IntentFilter filter = new IntentFilter();
1246        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1247        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1248        filter.addDataScheme("package");
1249        mContext.registerReceiver(mBroadcastReceiver, filter);
1250        // Register for events related to sdcard installation.
1251        IntentFilter sdFilter = new IntentFilter();
1252        sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1253        sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1254        mContext.registerReceiver(mBroadcastReceiver, sdFilter);
1255    }
1256
1257    private ArrayList<FullBackupEntry> readFullBackupSchedule() {
1258        ArrayList<FullBackupEntry> schedule = null;
1259        synchronized (mQueueLock) {
1260            if (mFullBackupScheduleFile.exists()) {
1261                FileInputStream fstream = null;
1262                BufferedInputStream bufStream = null;
1263                DataInputStream in = null;
1264                try {
1265                    fstream = new FileInputStream(mFullBackupScheduleFile);
1266                    bufStream = new BufferedInputStream(fstream);
1267                    in = new DataInputStream(bufStream);
1268
1269                    int version = in.readInt();
1270                    if (version != SCHEDULE_FILE_VERSION) {
1271                        Slog.e(TAG, "Unknown backup schedule version " + version);
1272                        return null;
1273                    }
1274
1275                    int N = in.readInt();
1276                    schedule = new ArrayList<FullBackupEntry>(N);
1277                    for (int i = 0; i < N; i++) {
1278                        String pkgName = in.readUTF();
1279                        long lastBackup = in.readLong();
1280                        schedule.add(new FullBackupEntry(pkgName, lastBackup));
1281                    }
1282                    Collections.sort(schedule);
1283                } catch (Exception e) {
1284                    Slog.e(TAG, "Unable to read backup schedule", e);
1285                    mFullBackupScheduleFile.delete();
1286                    schedule = null;
1287                } finally {
1288                    IoUtils.closeQuietly(in);
1289                    IoUtils.closeQuietly(bufStream);
1290                    IoUtils.closeQuietly(fstream);
1291                }
1292            }
1293
1294            if (schedule == null) {
1295                // no prior queue record, or unable to read it.  Set up the queue
1296                // from scratch.
1297                List<PackageInfo> apps =
1298                        PackageManagerBackupAgent.getStorableApplications(mPackageManager);
1299                final int N = apps.size();
1300                schedule = new ArrayList<FullBackupEntry>(N);
1301                for (int i = 0; i < N; i++) {
1302                    PackageInfo info = apps.get(i);
1303                    if (appGetsFullBackup(info)) {
1304                        schedule.add(new FullBackupEntry(info.packageName, 0));
1305                    }
1306                }
1307                writeFullBackupScheduleAsync();
1308            }
1309        }
1310        return schedule;
1311    }
1312
1313    Runnable mFullBackupScheduleWriter = new Runnable() {
1314        @Override public void run() {
1315            synchronized (mQueueLock) {
1316                try {
1317                    ByteArrayOutputStream bufStream = new ByteArrayOutputStream(4096);
1318                    DataOutputStream bufOut = new DataOutputStream(bufStream);
1319                    bufOut.writeInt(SCHEDULE_FILE_VERSION);
1320
1321                    // version 1:
1322                    //
1323                    // [int] # of packages in the queue = N
1324                    // N * {
1325                    //     [utf8] package name
1326                    //     [long] last backup time for this package
1327                    //     }
1328                    int N = mFullBackupQueue.size();
1329                    bufOut.writeInt(N);
1330
1331                    for (int i = 0; i < N; i++) {
1332                        FullBackupEntry entry = mFullBackupQueue.get(i);
1333                        bufOut.writeUTF(entry.packageName);
1334                        bufOut.writeLong(entry.lastBackup);
1335                    }
1336                    bufOut.flush();
1337
1338                    AtomicFile af = new AtomicFile(mFullBackupScheduleFile);
1339                    FileOutputStream out = af.startWrite();
1340                    out.write(bufStream.toByteArray());
1341                    af.finishWrite(out);
1342                } catch (Exception e) {
1343                    Slog.e(TAG, "Unable to write backup schedule!", e);
1344                }
1345            }
1346        }
1347    };
1348
1349    private void writeFullBackupScheduleAsync() {
1350        mBackupHandler.removeCallbacks(mFullBackupScheduleWriter);
1351        mBackupHandler.post(mFullBackupScheduleWriter);
1352    }
1353
1354    private void parseLeftoverJournals() {
1355        for (File f : mJournalDir.listFiles()) {
1356            if (mJournal == null || f.compareTo(mJournal) != 0) {
1357                // This isn't the current journal, so it must be a leftover.  Read
1358                // out the package names mentioned there and schedule them for
1359                // backup.
1360                RandomAccessFile in = null;
1361                try {
1362                    Slog.i(TAG, "Found stale backup journal, scheduling");
1363                    in = new RandomAccessFile(f, "r");
1364                    while (true) {
1365                        String packageName = in.readUTF();
1366                        if (MORE_DEBUG) Slog.i(TAG, "  " + packageName);
1367                        dataChangedImpl(packageName);
1368                    }
1369                } catch (EOFException e) {
1370                    // no more data; we're done
1371                } catch (Exception e) {
1372                    Slog.e(TAG, "Can't read " + f, e);
1373                } finally {
1374                    // close/delete the file
1375                    try { if (in != null) in.close(); } catch (IOException e) {}
1376                    f.delete();
1377                }
1378            }
1379        }
1380    }
1381
1382    private SecretKey buildPasswordKey(String algorithm, String pw, byte[] salt, int rounds) {
1383        return buildCharArrayKey(algorithm, pw.toCharArray(), salt, rounds);
1384    }
1385
1386    private SecretKey buildCharArrayKey(String algorithm, char[] pwArray, byte[] salt, int rounds) {
1387        try {
1388            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
1389            KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1390            return keyFactory.generateSecret(ks);
1391        } catch (InvalidKeySpecException e) {
1392            Slog.e(TAG, "Invalid key spec for PBKDF2!");
1393        } catch (NoSuchAlgorithmException e) {
1394            Slog.e(TAG, "PBKDF2 unavailable!");
1395        }
1396        return null;
1397    }
1398
1399    private String buildPasswordHash(String algorithm, String pw, byte[] salt, int rounds) {
1400        SecretKey key = buildPasswordKey(algorithm, pw, salt, rounds);
1401        if (key != null) {
1402            return byteArrayToHex(key.getEncoded());
1403        }
1404        return null;
1405    }
1406
1407    private String byteArrayToHex(byte[] data) {
1408        StringBuilder buf = new StringBuilder(data.length * 2);
1409        for (int i = 0; i < data.length; i++) {
1410            buf.append(Byte.toHexString(data[i], true));
1411        }
1412        return buf.toString();
1413    }
1414
1415    private byte[] hexToByteArray(String digits) {
1416        final int bytes = digits.length() / 2;
1417        if (2*bytes != digits.length()) {
1418            throw new IllegalArgumentException("Hex string must have an even number of digits");
1419        }
1420
1421        byte[] result = new byte[bytes];
1422        for (int i = 0; i < digits.length(); i += 2) {
1423            result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1424        }
1425        return result;
1426    }
1427
1428    private byte[] makeKeyChecksum(String algorithm, byte[] pwBytes, byte[] salt, int rounds) {
1429        char[] mkAsChar = new char[pwBytes.length];
1430        for (int i = 0; i < pwBytes.length; i++) {
1431            mkAsChar[i] = (char) pwBytes[i];
1432        }
1433
1434        Key checksum = buildCharArrayKey(algorithm, mkAsChar, salt, rounds);
1435        return checksum.getEncoded();
1436    }
1437
1438    // Used for generating random salts or passwords
1439    private byte[] randomBytes(int bits) {
1440        byte[] array = new byte[bits / 8];
1441        mRng.nextBytes(array);
1442        return array;
1443    }
1444
1445    // Backup password management
1446    boolean passwordMatchesSaved(String algorithm, String candidatePw, int rounds) {
1447        // First, on an encrypted device we require matching the device pw
1448        final boolean isEncrypted;
1449        try {
1450            isEncrypted = (mMountService.getEncryptionState() !=
1451                    IMountService.ENCRYPTION_STATE_NONE);
1452            if (isEncrypted) {
1453                if (DEBUG) {
1454                    Slog.i(TAG, "Device encrypted; verifying against device data pw");
1455                }
1456                // 0 means the password validated
1457                // -2 means device not encrypted
1458                // Any other result is either password failure or an error condition,
1459                // so we refuse the match
1460                final int result = mMountService.verifyEncryptionPassword(candidatePw);
1461                if (result == 0) {
1462                    if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
1463                    return true;
1464                } else if (result != -2) {
1465                    if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
1466                    return false;
1467                } else {
1468                    // ...else the device is supposedly not encrypted.  HOWEVER, the
1469                    // query about the encryption state said that the device *is*
1470                    // encrypted, so ... we may have a problem.  Log it and refuse
1471                    // the backup.
1472                    Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
1473                    return false;
1474                }
1475            }
1476        } catch (Exception e) {
1477            // Something went wrong talking to the mount service.  This is very bad;
1478            // assume that we fail password validation.
1479            return false;
1480        }
1481
1482        if (mPasswordHash == null) {
1483            // no current password case -- require that 'currentPw' be null or empty
1484            if (candidatePw == null || "".equals(candidatePw)) {
1485                return true;
1486            } // else the non-empty candidate does not match the empty stored pw
1487        } else {
1488            // hash the stated current pw and compare to the stored one
1489            if (candidatePw != null && candidatePw.length() > 0) {
1490                String currentPwHash = buildPasswordHash(algorithm, candidatePw, mPasswordSalt, rounds);
1491                if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1492                    // candidate hash matches the stored hash -- the password matches
1493                    return true;
1494                }
1495            } // else the stored pw is nonempty but the candidate is empty; no match
1496        }
1497        return false;
1498    }
1499
1500    @Override
1501    public boolean setBackupPassword(String currentPw, String newPw) {
1502        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1503                "setBackupPassword");
1504
1505        // When processing v1 passwords we may need to try two different PBKDF2 checksum regimes
1506        final boolean pbkdf2Fallback = (mPasswordVersion < BACKUP_PW_FILE_VERSION);
1507
1508        // If the supplied pw doesn't hash to the the saved one, fail.  The password
1509        // might be caught in the legacy crypto mismatch; verify that too.
1510        if (!passwordMatchesSaved(PBKDF_CURRENT, currentPw, PBKDF2_HASH_ROUNDS)
1511                && !(pbkdf2Fallback && passwordMatchesSaved(PBKDF_FALLBACK,
1512                        currentPw, PBKDF2_HASH_ROUNDS))) {
1513            return false;
1514        }
1515
1516        // Snap up to current on the pw file version
1517        mPasswordVersion = BACKUP_PW_FILE_VERSION;
1518        FileOutputStream pwFout = null;
1519        DataOutputStream pwOut = null;
1520        try {
1521            pwFout = new FileOutputStream(mPasswordVersionFile);
1522            pwOut = new DataOutputStream(pwFout);
1523            pwOut.writeInt(mPasswordVersion);
1524        } catch (IOException e) {
1525            Slog.e(TAG, "Unable to write backup pw version; password not changed");
1526            return false;
1527        } finally {
1528            try {
1529                if (pwOut != null) pwOut.close();
1530                if (pwFout != null) pwFout.close();
1531            } catch (IOException e) {
1532                Slog.w(TAG, "Unable to close pw version record");
1533            }
1534        }
1535
1536        // Clearing the password is okay
1537        if (newPw == null || newPw.isEmpty()) {
1538            if (mPasswordHashFile.exists()) {
1539                if (!mPasswordHashFile.delete()) {
1540                    // Unable to delete the old pw file, so fail
1541                    Slog.e(TAG, "Unable to clear backup password");
1542                    return false;
1543                }
1544            }
1545            mPasswordHash = null;
1546            mPasswordSalt = null;
1547            return true;
1548        }
1549
1550        try {
1551            // Okay, build the hash of the new backup password
1552            byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1553            String newPwHash = buildPasswordHash(PBKDF_CURRENT, newPw, salt, PBKDF2_HASH_ROUNDS);
1554
1555            OutputStream pwf = null, buffer = null;
1556            DataOutputStream out = null;
1557            try {
1558                pwf = new FileOutputStream(mPasswordHashFile);
1559                buffer = new BufferedOutputStream(pwf);
1560                out = new DataOutputStream(buffer);
1561                // integer length of the salt array, followed by the salt,
1562                // then the hex pw hash string
1563                out.writeInt(salt.length);
1564                out.write(salt);
1565                out.writeUTF(newPwHash);
1566                out.flush();
1567                mPasswordHash = newPwHash;
1568                mPasswordSalt = salt;
1569                return true;
1570            } finally {
1571                if (out != null) out.close();
1572                if (buffer != null) buffer.close();
1573                if (pwf != null) pwf.close();
1574            }
1575        } catch (IOException e) {
1576            Slog.e(TAG, "Unable to set backup password");
1577        }
1578        return false;
1579    }
1580
1581    @Override
1582    public boolean hasBackupPassword() {
1583        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1584                "hasBackupPassword");
1585
1586        try {
1587            return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
1588                || (mPasswordHash != null && mPasswordHash.length() > 0);
1589        } catch (Exception e) {
1590            // If we can't talk to the mount service we have a serious problem; fail
1591            // "secure" i.e. assuming that we require a password
1592            return true;
1593        }
1594    }
1595
1596    private boolean backupPasswordMatches(String currentPw) {
1597        if (hasBackupPassword()) {
1598            final boolean pbkdf2Fallback = (mPasswordVersion < BACKUP_PW_FILE_VERSION);
1599            if (!passwordMatchesSaved(PBKDF_CURRENT, currentPw, PBKDF2_HASH_ROUNDS)
1600                    && !(pbkdf2Fallback && passwordMatchesSaved(PBKDF_FALLBACK,
1601                            currentPw, PBKDF2_HASH_ROUNDS))) {
1602                if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
1603                return false;
1604            }
1605        }
1606        return true;
1607    }
1608
1609    // Maintain persistent state around whether need to do an initialize operation.
1610    // Must be called with the queue lock held.
1611    void recordInitPendingLocked(boolean isPending, String transportName) {
1612        if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
1613                + " on transport " + transportName);
1614        mBackupHandler.removeMessages(MSG_RETRY_INIT);
1615
1616        try {
1617            IBackupTransport transport = getTransport(transportName);
1618            if (transport != null) {
1619                String transportDirName = transport.transportDirName();
1620                File stateDir = new File(mBaseStateDir, transportDirName);
1621                File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1622
1623                if (isPending) {
1624                    // We need an init before we can proceed with sending backup data.
1625                    // Record that with an entry in our set of pending inits, as well as
1626                    // journaling it via creation of a sentinel file.
1627                    mPendingInits.add(transportName);
1628                    try {
1629                        (new FileOutputStream(initPendingFile)).close();
1630                    } catch (IOException ioe) {
1631                        // Something is badly wrong with our permissions; just try to move on
1632                    }
1633                } else {
1634                    // No more initialization needed; wipe the journal and reset our state.
1635                    initPendingFile.delete();
1636                    mPendingInits.remove(transportName);
1637                }
1638                return; // done; don't fall through to the error case
1639            }
1640        } catch (RemoteException e) {
1641            // transport threw when asked its name; fall through to the lookup-failed case
1642        }
1643
1644        // The named transport doesn't exist or threw.  This operation is
1645        // important, so we record the need for a an init and post a message
1646        // to retry the init later.
1647        if (isPending) {
1648            mPendingInits.add(transportName);
1649            mBackupHandler.sendMessageDelayed(
1650                    mBackupHandler.obtainMessage(MSG_RETRY_INIT,
1651                            (isPending ? 1 : 0),
1652                            0,
1653                            transportName),
1654                    TRANSPORT_RETRY_INTERVAL);
1655        }
1656    }
1657
1658    // Reset all of our bookkeeping, in response to having been told that
1659    // the backend data has been wiped [due to idle expiry, for example],
1660    // so we must re-upload all saved settings.
1661    void resetBackupState(File stateFileDir) {
1662        synchronized (mQueueLock) {
1663            // Wipe the "what we've ever backed up" tracking
1664            mEverStoredApps.clear();
1665            mEverStored.delete();
1666
1667            mCurrentToken = 0;
1668            writeRestoreTokens();
1669
1670            // Remove all the state files
1671            for (File sf : stateFileDir.listFiles()) {
1672                // ... but don't touch the needs-init sentinel
1673                if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1674                    sf.delete();
1675                }
1676            }
1677        }
1678
1679        // Enqueue a new backup of every participant
1680        synchronized (mBackupParticipants) {
1681            final int N = mBackupParticipants.size();
1682            for (int i=0; i<N; i++) {
1683                HashSet<String> participants = mBackupParticipants.valueAt(i);
1684                if (participants != null) {
1685                    for (String packageName : participants) {
1686                        dataChangedImpl(packageName);
1687                    }
1688                }
1689            }
1690        }
1691    }
1692
1693    // Add a transport to our set of available backends.  If 'transport' is null, this
1694    // is an unregistration, and the transport's entry is removed from our bookkeeping.
1695    private void registerTransport(String name, String component, IBackupTransport transport) {
1696        synchronized (mTransports) {
1697            if (DEBUG) Slog.v(TAG, "Registering transport "
1698                    + component + "::" + name + " = " + transport);
1699            if (transport != null) {
1700                mTransports.put(name, transport);
1701                mTransportNames.put(component, name);
1702            } else {
1703                mTransports.remove(mTransportNames.get(component));
1704                mTransportNames.remove(component);
1705                // Nothing further to do in the unregistration case
1706                return;
1707            }
1708        }
1709
1710        // If the init sentinel file exists, we need to be sure to perform the init
1711        // as soon as practical.  We also create the state directory at registration
1712        // time to ensure it's present from the outset.
1713        try {
1714            String transportName = transport.transportDirName();
1715            File stateDir = new File(mBaseStateDir, transportName);
1716            stateDir.mkdirs();
1717
1718            File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1719            if (initSentinel.exists()) {
1720                synchronized (mQueueLock) {
1721                    mPendingInits.add(transportName);
1722
1723                    // TODO: pick a better starting time than now + 1 minute
1724                    long delay = 1000 * 60; // one minute, in milliseconds
1725                    mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1726                            System.currentTimeMillis() + delay, mRunInitIntent);
1727                }
1728            }
1729        } catch (RemoteException e) {
1730            // the transport threw when asked its file naming prefs; declare it invalid
1731            Slog.e(TAG, "Unable to register transport as " + name);
1732            mTransportNames.remove(component);
1733            mTransports.remove(name);
1734        }
1735    }
1736
1737    // ----- Track installation/removal of packages -----
1738    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1739        public void onReceive(Context context, Intent intent) {
1740            if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
1741
1742            String action = intent.getAction();
1743            boolean replacing = false;
1744            boolean added = false;
1745            boolean rebind = false;
1746            Bundle extras = intent.getExtras();
1747            String pkgList[] = null;
1748            if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
1749                    Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1750                Uri uri = intent.getData();
1751                if (uri == null) {
1752                    return;
1753                }
1754                String pkgName = uri.getSchemeSpecificPart();
1755                if (pkgName != null) {
1756                    pkgList = new String[] { pkgName };
1757                }
1758                rebind = added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1759                replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
1760            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
1761                added = true;
1762                pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1763            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1764                added = false;
1765                pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1766            }
1767
1768            if (pkgList == null || pkgList.length == 0) {
1769                return;
1770            }
1771
1772            final int uid = extras.getInt(Intent.EXTRA_UID);
1773            if (added) {
1774                synchronized (mBackupParticipants) {
1775                    if (replacing) {
1776                        // This is the package-replaced case; we just remove the entry
1777                        // under the old uid and fall through to re-add.
1778                        removePackageParticipantsLocked(pkgList, uid);
1779                    }
1780                    addPackageParticipantsLocked(pkgList);
1781                }
1782                // If they're full-backup candidates, add them there instead
1783                for (String packageName : pkgList) {
1784                    try {
1785                        PackageInfo app = mPackageManager.getPackageInfo(packageName, 0);
1786                        long now = System.currentTimeMillis();
1787                        if (appGetsFullBackup(app)) {
1788                            enqueueFullBackup(packageName, now);
1789                            scheduleNextFullBackupJob();
1790                        }
1791
1792                        // if this was the PACKAGE_ADDED conclusion of an upgrade of the package
1793                        // hosting one of our transports, we need to explicitly rebind now.
1794                        if (rebind) {
1795                            synchronized (mTransportConnections) {
1796                                final TransportConnection conn = mTransportConnections.get(packageName);
1797                                if (conn != null) {
1798                                    if (DEBUG) {
1799                                        Slog.i(TAG, "Transport package changed; rebinding");
1800                                    }
1801                                    bindTransport(conn.mTransport);
1802                                }
1803                            }
1804                        }
1805                    } catch (NameNotFoundException e) {
1806                        // doesn't really exist; ignore it
1807                        if (DEBUG) {
1808                            Slog.i(TAG, "Can't resolve new app " + packageName);
1809                        }
1810                    }
1811                }
1812
1813            } else {
1814                if (replacing) {
1815                    // The package is being updated.  We'll receive a PACKAGE_ADDED shortly.
1816                } else {
1817                    synchronized (mBackupParticipants) {
1818                        removePackageParticipantsLocked(pkgList, uid);
1819                    }
1820                }
1821            }
1822        }
1823    };
1824
1825    // ----- Track connection to transports service -----
1826    class TransportConnection implements ServiceConnection {
1827        ServiceInfo mTransport;
1828
1829        public TransportConnection(ServiceInfo transport) {
1830            mTransport = transport;
1831        }
1832
1833        @Override
1834        public void onServiceConnected(ComponentName component, IBinder service) {
1835            if (DEBUG) Slog.v(TAG, "Connected to transport " + component);
1836            final String name = component.flattenToShortString();
1837            try {
1838                IBackupTransport transport = IBackupTransport.Stub.asInterface(service);
1839                registerTransport(transport.name(), name, transport);
1840                EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_LIFECYCLE, name, 1);
1841            } catch (RemoteException e) {
1842                Slog.e(TAG, "Unable to register transport " + component);
1843                EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_LIFECYCLE, name, 0);
1844            }
1845        }
1846
1847        @Override
1848        public void onServiceDisconnected(ComponentName component) {
1849            if (DEBUG) Slog.v(TAG, "Disconnected from transport " + component);
1850            final String name = component.flattenToShortString();
1851            EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_LIFECYCLE, name, 0);
1852            registerTransport(null, name, null);
1853        }
1854    };
1855
1856    void bindTransport(ServiceInfo transport) {
1857        ComponentName svcName = new ComponentName(transport.packageName, transport.name);
1858        if (DEBUG) {
1859            Slog.i(TAG, "Binding to transport host " + svcName);
1860        }
1861        Intent intent = new Intent(mTransportServiceIntent);
1862        intent.setComponent(svcName);
1863
1864        TransportConnection connection;
1865        synchronized (mTransportConnections) {
1866            connection = mTransportConnections.get(transport.packageName);
1867            if (null == connection) {
1868                connection = new TransportConnection(transport);
1869                mTransportConnections.put(transport.packageName, connection);
1870            } else {
1871                // This is a rebind due to package upgrade.  The service won't be
1872                // automatically relaunched for us until we explicitly rebind, but
1873                // we need to unbind the now-orphaned original connection.
1874                mContext.unbindService(connection);
1875            }
1876        }
1877        mContext.bindServiceAsUser(intent,
1878                connection, Context.BIND_AUTO_CREATE,
1879                UserHandle.OWNER);
1880    }
1881
1882    // Add the backup agents in the given packages to our set of known backup participants.
1883    // If 'packageNames' is null, adds all backup agents in the whole system.
1884    void addPackageParticipantsLocked(String[] packageNames) {
1885        // Look for apps that define the android:backupAgent attribute
1886        List<PackageInfo> targetApps = allAgentPackages();
1887        if (packageNames != null) {
1888            if (MORE_DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1889            for (String packageName : packageNames) {
1890                addPackageParticipantsLockedInner(packageName, targetApps);
1891            }
1892        } else {
1893            if (MORE_DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1894            addPackageParticipantsLockedInner(null, targetApps);
1895        }
1896    }
1897
1898    private void addPackageParticipantsLockedInner(String packageName,
1899            List<PackageInfo> targetPkgs) {
1900        if (MORE_DEBUG) {
1901            Slog.v(TAG, "Examining " + packageName + " for backup agent");
1902        }
1903
1904        for (PackageInfo pkg : targetPkgs) {
1905            if (packageName == null || pkg.packageName.equals(packageName)) {
1906                int uid = pkg.applicationInfo.uid;
1907                HashSet<String> set = mBackupParticipants.get(uid);
1908                if (set == null) {
1909                    set = new HashSet<String>();
1910                    mBackupParticipants.put(uid, set);
1911                }
1912                set.add(pkg.packageName);
1913                if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
1914
1915                // Schedule a backup for it on general principles
1916                if (MORE_DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName);
1917                dataChangedImpl(pkg.packageName);
1918            }
1919        }
1920    }
1921
1922    // Remove the given packages' entries from our known active set.
1923    void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
1924        if (packageNames == null) {
1925            Slog.w(TAG, "removePackageParticipants with null list");
1926            return;
1927        }
1928
1929        if (MORE_DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
1930                + " #" + packageNames.length);
1931        for (String pkg : packageNames) {
1932            // Known previous UID, so we know which package set to check
1933            HashSet<String> set = mBackupParticipants.get(oldUid);
1934            if (set != null && set.contains(pkg)) {
1935                removePackageFromSetLocked(set, pkg);
1936                if (set.isEmpty()) {
1937                    if (MORE_DEBUG) Slog.v(TAG, "  last one of this uid; purging set");
1938                    mBackupParticipants.remove(oldUid);
1939                }
1940            }
1941        }
1942    }
1943
1944    private void removePackageFromSetLocked(final HashSet<String> set,
1945            final String packageName) {
1946        if (set.contains(packageName)) {
1947            // Found it.  Remove this one package from the bookkeeping, and
1948            // if it's the last participating app under this uid we drop the
1949            // (now-empty) set as well.
1950            // Note that we deliberately leave it 'known' in the "ever backed up"
1951            // bookkeeping so that its current-dataset data will be retrieved
1952            // if the app is subsequently reinstalled
1953            if (MORE_DEBUG) Slog.v(TAG, "  removing participant " + packageName);
1954            set.remove(packageName);
1955            mPendingBackups.remove(packageName);
1956        }
1957    }
1958
1959    // Returns the set of all applications that define an android:backupAgent attribute
1960    List<PackageInfo> allAgentPackages() {
1961        // !!! TODO: cache this and regenerate only when necessary
1962        int flags = PackageManager.GET_SIGNATURES;
1963        List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1964        int N = packages.size();
1965        for (int a = N-1; a >= 0; a--) {
1966            PackageInfo pkg = packages.get(a);
1967            try {
1968                ApplicationInfo app = pkg.applicationInfo;
1969                if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
1970                        || app.backupAgentName == null) {
1971                    packages.remove(a);
1972                }
1973                else {
1974                    // we will need the shared library path, so look that up and store it here.
1975                    // This is used implicitly when we pass the PackageInfo object off to
1976                    // the Activity Manager to launch the app for backup/restore purposes.
1977                    app = mPackageManager.getApplicationInfo(pkg.packageName,
1978                            PackageManager.GET_SHARED_LIBRARY_FILES);
1979                    pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1980                }
1981            } catch (NameNotFoundException e) {
1982                packages.remove(a);
1983            }
1984        }
1985        return packages;
1986    }
1987
1988    // Called from the backup task: record that the given app has been successfully
1989    // backed up at least once
1990    void logBackupComplete(String packageName) {
1991        if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1992
1993        synchronized (mEverStoredApps) {
1994            if (!mEverStoredApps.add(packageName)) return;
1995
1996            RandomAccessFile out = null;
1997            try {
1998                out = new RandomAccessFile(mEverStored, "rws");
1999                out.seek(out.length());
2000                out.writeUTF(packageName);
2001            } catch (IOException e) {
2002                Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
2003            } finally {
2004                try { if (out != null) out.close(); } catch (IOException e) {}
2005            }
2006        }
2007    }
2008
2009    // Remove our awareness of having ever backed up the given package
2010    void removeEverBackedUp(String packageName) {
2011        if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
2012        if (MORE_DEBUG) Slog.v(TAG, "New set:");
2013
2014        synchronized (mEverStoredApps) {
2015            // Rewrite the file and rename to overwrite.  If we reboot in the middle,
2016            // we'll recognize on initialization time that the package no longer
2017            // exists and fix it up then.
2018            File tempKnownFile = new File(mBaseStateDir, "processed.new");
2019            RandomAccessFile known = null;
2020            try {
2021                known = new RandomAccessFile(tempKnownFile, "rws");
2022                mEverStoredApps.remove(packageName);
2023                for (String s : mEverStoredApps) {
2024                    known.writeUTF(s);
2025                    if (MORE_DEBUG) Slog.v(TAG, "    " + s);
2026                }
2027                known.close();
2028                known = null;
2029                if (!tempKnownFile.renameTo(mEverStored)) {
2030                    throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
2031                }
2032            } catch (IOException e) {
2033                // Bad: we couldn't create the new copy.  For safety's sake we
2034                // abandon the whole process and remove all what's-backed-up
2035                // state entirely, meaning we'll force a backup pass for every
2036                // participant on the next boot or [re]install.
2037                Slog.w(TAG, "Error rewriting " + mEverStored, e);
2038                mEverStoredApps.clear();
2039                tempKnownFile.delete();
2040                mEverStored.delete();
2041            } finally {
2042                try { if (known != null) known.close(); } catch (IOException e) {}
2043            }
2044        }
2045    }
2046
2047    // Persistently record the current and ancestral backup tokens as well
2048    // as the set of packages with data [supposedly] available in the
2049    // ancestral dataset.
2050    void writeRestoreTokens() {
2051        try {
2052            RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
2053
2054            // First, the version number of this record, for futureproofing
2055            af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
2056
2057            // Write the ancestral and current tokens
2058            af.writeLong(mAncestralToken);
2059            af.writeLong(mCurrentToken);
2060
2061            // Now write the set of ancestral packages
2062            if (mAncestralPackages == null) {
2063                af.writeInt(-1);
2064            } else {
2065                af.writeInt(mAncestralPackages.size());
2066                if (DEBUG) Slog.v(TAG, "Ancestral packages:  " + mAncestralPackages.size());
2067                for (String pkgName : mAncestralPackages) {
2068                    af.writeUTF(pkgName);
2069                    if (MORE_DEBUG) Slog.v(TAG, "   " + pkgName);
2070                }
2071            }
2072            af.close();
2073        } catch (IOException e) {
2074            Slog.w(TAG, "Unable to write token file:", e);
2075        }
2076    }
2077
2078    // Return the given transport
2079    private IBackupTransport getTransport(String transportName) {
2080        synchronized (mTransports) {
2081            IBackupTransport transport = mTransports.get(transportName);
2082            if (transport == null) {
2083                Slog.w(TAG, "Requested unavailable transport: " + transportName);
2084            }
2085            return transport;
2086        }
2087    }
2088
2089    // fire off a backup agent, blocking until it attaches or times out
2090    IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
2091        IBackupAgent agent = null;
2092        synchronized(mAgentConnectLock) {
2093            mConnecting = true;
2094            mConnectedAgent = null;
2095            try {
2096                if (mActivityManager.bindBackupAgent(app, mode)) {
2097                    Slog.d(TAG, "awaiting agent for " + app);
2098
2099                    // success; wait for the agent to arrive
2100                    // only wait 10 seconds for the bind to happen
2101                    long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
2102                    while (mConnecting && mConnectedAgent == null
2103                            && (System.currentTimeMillis() < timeoutMark)) {
2104                        try {
2105                            mAgentConnectLock.wait(5000);
2106                        } catch (InterruptedException e) {
2107                            // just bail
2108                            if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
2109                            mActivityManager.clearPendingBackup();
2110                            return null;
2111                        }
2112                    }
2113
2114                    // if we timed out with no connect, abort and move on
2115                    if (mConnecting == true) {
2116                        Slog.w(TAG, "Timeout waiting for agent " + app);
2117                        mActivityManager.clearPendingBackup();
2118                        return null;
2119                    }
2120                    if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
2121                    agent = mConnectedAgent;
2122                }
2123            } catch (RemoteException e) {
2124                // can't happen - ActivityManager is local
2125            }
2126        }
2127        return agent;
2128    }
2129
2130    // clear an application's data, blocking until the operation completes or times out
2131    void clearApplicationDataSynchronous(String packageName) {
2132        // Don't wipe packages marked allowClearUserData=false
2133        try {
2134            PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
2135            if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
2136                if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
2137                        + packageName);
2138                return;
2139            }
2140        } catch (NameNotFoundException e) {
2141            Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
2142            return;
2143        }
2144
2145        ClearDataObserver observer = new ClearDataObserver();
2146
2147        synchronized(mClearDataLock) {
2148            mClearingData = true;
2149            try {
2150                mActivityManager.clearApplicationUserData(packageName, observer, 0);
2151            } catch (RemoteException e) {
2152                // can't happen because the activity manager is in this process
2153            }
2154
2155            // only wait 10 seconds for the clear data to happen
2156            long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
2157            while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
2158                try {
2159                    mClearDataLock.wait(5000);
2160                } catch (InterruptedException e) {
2161                    // won't happen, but still.
2162                    mClearingData = false;
2163                }
2164            }
2165        }
2166    }
2167
2168    class ClearDataObserver extends IPackageDataObserver.Stub {
2169        public void onRemoveCompleted(String packageName, boolean succeeded) {
2170            synchronized(mClearDataLock) {
2171                mClearingData = false;
2172                mClearDataLock.notifyAll();
2173            }
2174        }
2175    }
2176
2177    // Get the restore-set token for the best-available restore set for this package:
2178    // the active set if possible, else the ancestral one.  Returns zero if none available.
2179    long getAvailableRestoreToken(String packageName) {
2180        long token = mAncestralToken;
2181        synchronized (mQueueLock) {
2182            if (mEverStoredApps.contains(packageName)) {
2183                token = mCurrentToken;
2184            }
2185        }
2186        return token;
2187    }
2188
2189    // -----
2190    // Interface and methods used by the asynchronous-with-timeout backup/restore operations
2191
2192    interface BackupRestoreTask {
2193        // Execute one tick of whatever state machine the task implements
2194        void execute();
2195
2196        // An operation that wanted a callback has completed
2197        void operationComplete();
2198
2199        // An operation that wanted a callback has timed out
2200        void handleTimeout();
2201    }
2202
2203    void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
2204        if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
2205                + " interval=" + interval);
2206        synchronized (mCurrentOpLock) {
2207            mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
2208
2209            Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
2210            mBackupHandler.sendMessageDelayed(msg, interval);
2211        }
2212    }
2213
2214    // synchronous waiter case
2215    boolean waitUntilOperationComplete(int token) {
2216        if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
2217                + Integer.toHexString(token));
2218        int finalState = OP_PENDING;
2219        Operation op = null;
2220        synchronized (mCurrentOpLock) {
2221            while (true) {
2222                op = mCurrentOperations.get(token);
2223                if (op == null) {
2224                    // mysterious disappearance: treat as success with no callback
2225                    break;
2226                } else {
2227                    if (op.state == OP_PENDING) {
2228                        try {
2229                            mCurrentOpLock.wait();
2230                        } catch (InterruptedException e) {}
2231                        // When the wait is notified we loop around and recheck the current state
2232                    } else {
2233                        // No longer pending; we're done
2234                        finalState = op.state;
2235                        break;
2236                    }
2237                }
2238            }
2239        }
2240
2241        mBackupHandler.removeMessages(MSG_TIMEOUT);
2242        if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
2243                + " complete: finalState=" + finalState);
2244        return finalState == OP_ACKNOWLEDGED;
2245    }
2246
2247    void handleTimeout(int token, Object obj) {
2248        // Notify any synchronous waiters
2249        Operation op = null;
2250        synchronized (mCurrentOpLock) {
2251            op = mCurrentOperations.get(token);
2252            if (MORE_DEBUG) {
2253                if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
2254                        + " but no op found");
2255            }
2256            int state = (op != null) ? op.state : OP_TIMEOUT;
2257            if (state == OP_PENDING) {
2258                if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
2259                op.state = OP_TIMEOUT;
2260                mCurrentOperations.put(token, op);
2261            }
2262            mCurrentOpLock.notifyAll();
2263        }
2264
2265        // If there's a TimeoutHandler for this event, call it
2266        if (op != null && op.callback != null) {
2267            op.callback.handleTimeout();
2268        }
2269    }
2270
2271    // ----- Back up a set of applications via a worker thread -----
2272
2273    enum BackupState {
2274        INITIAL,
2275        RUNNING_QUEUE,
2276        FINAL
2277    }
2278
2279    class PerformBackupTask implements BackupRestoreTask {
2280        private static final String TAG = "PerformBackupTask";
2281
2282        IBackupTransport mTransport;
2283        ArrayList<BackupRequest> mQueue;
2284        ArrayList<BackupRequest> mOriginalQueue;
2285        File mStateDir;
2286        File mJournal;
2287        BackupState mCurrentState;
2288
2289        // carried information about the current in-flight operation
2290        IBackupAgent mAgentBinder;
2291        PackageInfo mCurrentPackage;
2292        File mSavedStateName;
2293        File mBackupDataName;
2294        File mNewStateName;
2295        ParcelFileDescriptor mSavedState;
2296        ParcelFileDescriptor mBackupData;
2297        ParcelFileDescriptor mNewState;
2298        int mStatus;
2299        boolean mFinished;
2300
2301        public PerformBackupTask(IBackupTransport transport, String dirName,
2302                ArrayList<BackupRequest> queue, File journal) {
2303            mTransport = transport;
2304            mOriginalQueue = queue;
2305            mJournal = journal;
2306
2307            mStateDir = new File(mBaseStateDir, dirName);
2308
2309            mCurrentState = BackupState.INITIAL;
2310            mFinished = false;
2311
2312            addBackupTrace("STATE => INITIAL");
2313        }
2314
2315        // Main entry point: perform one chunk of work, updating the state as appropriate
2316        // and reposting the next chunk to the primary backup handler thread.
2317        @Override
2318        public void execute() {
2319            switch (mCurrentState) {
2320                case INITIAL:
2321                    beginBackup();
2322                    break;
2323
2324                case RUNNING_QUEUE:
2325                    invokeNextAgent();
2326                    break;
2327
2328                case FINAL:
2329                    if (!mFinished) finalizeBackup();
2330                    else {
2331                        Slog.e(TAG, "Duplicate finish");
2332                    }
2333                    mFinished = true;
2334                    break;
2335            }
2336        }
2337
2338        // We're starting a backup pass.  Initialize the transport and send
2339        // the PM metadata blob if we haven't already.
2340        void beginBackup() {
2341            if (DEBUG_BACKUP_TRACE) {
2342                clearBackupTrace();
2343                StringBuilder b = new StringBuilder(256);
2344                b.append("beginBackup: [");
2345                for (BackupRequest req : mOriginalQueue) {
2346                    b.append(' ');
2347                    b.append(req.packageName);
2348                }
2349                b.append(" ]");
2350                addBackupTrace(b.toString());
2351            }
2352
2353            mAgentBinder = null;
2354            mStatus = BackupTransport.TRANSPORT_OK;
2355
2356            // Sanity check: if the queue is empty we have no work to do.
2357            if (mOriginalQueue.isEmpty()) {
2358                Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
2359                addBackupTrace("queue empty at begin");
2360                executeNextState(BackupState.FINAL);
2361                return;
2362            }
2363
2364            // We need to retain the original queue contents in case of transport
2365            // failure, but we want a working copy that we can manipulate along
2366            // the way.
2367            mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
2368
2369            if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
2370
2371            File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2372            try {
2373                final String transportName = mTransport.transportDirName();
2374                EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
2375
2376                // If we haven't stored package manager metadata yet, we must init the transport.
2377                if (mStatus == BackupTransport.TRANSPORT_OK && pmState.length() <= 0) {
2378                    Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
2379                    addBackupTrace("initializing transport " + transportName);
2380                    resetBackupState(mStateDir);  // Just to make sure.
2381                    mStatus = mTransport.initializeDevice();
2382
2383                    addBackupTrace("transport.initializeDevice() == " + mStatus);
2384                    if (mStatus == BackupTransport.TRANSPORT_OK) {
2385                        EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
2386                    } else {
2387                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
2388                        Slog.e(TAG, "Transport error in initializeDevice()");
2389                    }
2390                }
2391
2392                // The package manager doesn't have a proper <application> etc, but since
2393                // it's running here in the system process we can just set up its agent
2394                // directly and use a synthetic BackupRequest.  We always run this pass
2395                // because it's cheap and this way we guarantee that we don't get out of
2396                // step even if we're selecting among various transports at run time.
2397                if (mStatus == BackupTransport.TRANSPORT_OK) {
2398                    PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
2399                            mPackageManager);
2400                    mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
2401                            IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
2402                    addBackupTrace("PMBA invoke: " + mStatus);
2403                }
2404
2405                if (mStatus == BackupTransport.TRANSPORT_NOT_INITIALIZED) {
2406                    // The backend reports that our dataset has been wiped.  Note this in
2407                    // the event log; the no-success code below will reset the backup
2408                    // state as well.
2409                    EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
2410                }
2411            } catch (Exception e) {
2412                Slog.e(TAG, "Error in backup thread", e);
2413                addBackupTrace("Exception in backup thread: " + e);
2414                mStatus = BackupTransport.TRANSPORT_ERROR;
2415            } finally {
2416                // If we've succeeded so far, invokeAgentForBackup() will have run the PM
2417                // metadata and its completion/timeout callback will continue the state
2418                // machine chain.  If it failed that won't happen; we handle that now.
2419                addBackupTrace("exiting prelim: " + mStatus);
2420                if (mStatus != BackupTransport.TRANSPORT_OK) {
2421                    // if things went wrong at this point, we need to
2422                    // restage everything and try again later.
2423                    resetBackupState(mStateDir);  // Just to make sure.
2424                    executeNextState(BackupState.FINAL);
2425                }
2426            }
2427        }
2428
2429        // Transport has been initialized and the PM metadata submitted successfully
2430        // if that was warranted.  Now we process the single next thing in the queue.
2431        void invokeNextAgent() {
2432            mStatus = BackupTransport.TRANSPORT_OK;
2433            addBackupTrace("invoke q=" + mQueue.size());
2434
2435            // Sanity check that we have work to do.  If not, skip to the end where
2436            // we reestablish the wakelock invariants etc.
2437            if (mQueue.isEmpty()) {
2438                if (DEBUG) Slog.i(TAG, "queue now empty");
2439                executeNextState(BackupState.FINAL);
2440                return;
2441            }
2442
2443            // pop the entry we're going to process on this step
2444            BackupRequest request = mQueue.get(0);
2445            mQueue.remove(0);
2446
2447            Slog.d(TAG, "starting agent for backup of " + request);
2448            addBackupTrace("launch agent for " + request.packageName);
2449
2450            // Verify that the requested app exists; it might be something that
2451            // requested a backup but was then uninstalled.  The request was
2452            // journalled and rather than tamper with the journal it's safer
2453            // to sanity-check here.  This also gives us the classname of the
2454            // package's backup agent.
2455            try {
2456                mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
2457                        PackageManager.GET_SIGNATURES);
2458                if (mCurrentPackage.applicationInfo.backupAgentName == null) {
2459                    // The manifest has changed but we had a stale backup request pending.
2460                    // This won't happen again because the app won't be requesting further
2461                    // backups.
2462                    Slog.i(TAG, "Package " + request.packageName
2463                            + " no longer supports backup; skipping");
2464                    addBackupTrace("skipping - no agent, completion is noop");
2465                    executeNextState(BackupState.RUNNING_QUEUE);
2466                    return;
2467                }
2468
2469                if ((mCurrentPackage.applicationInfo.flags & ApplicationInfo.FLAG_STOPPED) != 0) {
2470                    // The app has been force-stopped or cleared or just installed,
2471                    // and not yet launched out of that state, so just as it won't
2472                    // receive broadcasts, we won't run it for backup.
2473                    addBackupTrace("skipping - stopped");
2474                    executeNextState(BackupState.RUNNING_QUEUE);
2475                    return;
2476                }
2477
2478                IBackupAgent agent = null;
2479                try {
2480                    mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
2481                    agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
2482                            IApplicationThread.BACKUP_MODE_INCREMENTAL);
2483                    addBackupTrace("agent bound; a? = " + (agent != null));
2484                    if (agent != null) {
2485                        mAgentBinder = agent;
2486                        mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
2487                        // at this point we'll either get a completion callback from the
2488                        // agent, or a timeout message on the main handler.  either way, we're
2489                        // done here as long as we're successful so far.
2490                    } else {
2491                        // Timeout waiting for the agent
2492                        mStatus = BackupTransport.AGENT_ERROR;
2493                    }
2494                } catch (SecurityException ex) {
2495                    // Try for the next one.
2496                    Slog.d(TAG, "error in bind/backup", ex);
2497                    mStatus = BackupTransport.AGENT_ERROR;
2498                            addBackupTrace("agent SE");
2499                }
2500            } catch (NameNotFoundException e) {
2501                Slog.d(TAG, "Package does not exist; skipping");
2502                addBackupTrace("no such package");
2503                mStatus = BackupTransport.AGENT_UNKNOWN;
2504            } finally {
2505                mWakelock.setWorkSource(null);
2506
2507                // If there was an agent error, no timeout/completion handling will occur.
2508                // That means we need to direct to the next state ourselves.
2509                if (mStatus != BackupTransport.TRANSPORT_OK) {
2510                    BackupState nextState = BackupState.RUNNING_QUEUE;
2511                    mAgentBinder = null;
2512
2513                    // An agent-level failure means we reenqueue this one agent for
2514                    // a later retry, but otherwise proceed normally.
2515                    if (mStatus == BackupTransport.AGENT_ERROR) {
2516                        if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2517                                + " - restaging");
2518                        dataChangedImpl(request.packageName);
2519                        mStatus = BackupTransport.TRANSPORT_OK;
2520                        if (mQueue.isEmpty()) nextState = BackupState.FINAL;
2521                    } else if (mStatus == BackupTransport.AGENT_UNKNOWN) {
2522                        // Failed lookup of the app, so we couldn't bring up an agent, but
2523                        // we're otherwise fine.  Just drop it and go on to the next as usual.
2524                        mStatus = BackupTransport.TRANSPORT_OK;
2525                    } else {
2526                        // Transport-level failure means we reenqueue everything
2527                        revertAndEndBackup();
2528                        nextState = BackupState.FINAL;
2529                    }
2530
2531                    executeNextState(nextState);
2532                } else {
2533                    // success case
2534                    addBackupTrace("expecting completion/timeout callback");
2535                }
2536            }
2537        }
2538
2539        void finalizeBackup() {
2540            addBackupTrace("finishing");
2541
2542            // Either backup was successful, in which case we of course do not need
2543            // this pass's journal any more; or it failed, in which case we just
2544            // re-enqueued all of these packages in the current active journal.
2545            // Either way, we no longer need this pass's journal.
2546            if (mJournal != null && !mJournal.delete()) {
2547                Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2548            }
2549
2550            // If everything actually went through and this is the first time we've
2551            // done a backup, we can now record what the current backup dataset token
2552            // is.
2553            if ((mCurrentToken == 0) && (mStatus == BackupTransport.TRANSPORT_OK)) {
2554                addBackupTrace("success; recording token");
2555                try {
2556                    mCurrentToken = mTransport.getCurrentRestoreSet();
2557                    writeRestoreTokens();
2558                } catch (RemoteException e) {
2559                    // nothing for it at this point, unfortunately, but this will be
2560                    // recorded the next time we fully succeed.
2561                    addBackupTrace("transport threw returning token");
2562                }
2563            }
2564
2565            // Set up the next backup pass - at this point we can set mBackupRunning
2566            // to false to allow another pass to fire, because we're done with the
2567            // state machine sequence and the wakelock is refcounted.
2568            synchronized (mQueueLock) {
2569                mBackupRunning = false;
2570                if (mStatus == BackupTransport.TRANSPORT_NOT_INITIALIZED) {
2571                    // Make sure we back up everything and perform the one-time init
2572                    clearMetadata();
2573                    if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
2574                    addBackupTrace("init required; rerunning");
2575                    backupNow();
2576                }
2577            }
2578
2579            // Only once we're entirely finished do we release the wakelock
2580            clearBackupTrace();
2581            Slog.i(BackupManagerService.TAG, "Backup pass finished.");
2582            mWakelock.release();
2583        }
2584
2585        // Remove the PM metadata state. This will generate an init on the next pass.
2586        void clearMetadata() {
2587            final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2588            if (pmState.exists()) pmState.delete();
2589        }
2590
2591        // Invoke an agent's doBackup() and start a timeout message spinning on the main
2592        // handler in case it doesn't get back to us.
2593        int invokeAgentForBackup(String packageName, IBackupAgent agent,
2594                IBackupTransport transport) {
2595            if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2596            addBackupTrace("invoking " + packageName);
2597
2598            mSavedStateName = new File(mStateDir, packageName);
2599            mBackupDataName = new File(mDataDir, packageName + ".data");
2600            mNewStateName = new File(mStateDir, packageName + ".new");
2601            if (MORE_DEBUG) Slog.d(TAG, "data file: " + mBackupDataName);
2602
2603            mSavedState = null;
2604            mBackupData = null;
2605            mNewState = null;
2606
2607            final int token = generateToken();
2608            try {
2609                // Look up the package info & signatures.  This is first so that if it
2610                // throws an exception, there's no file setup yet that would need to
2611                // be unraveled.
2612                if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
2613                    // The metadata 'package' is synthetic; construct one and make
2614                    // sure our global state is pointed at it
2615                    mCurrentPackage = new PackageInfo();
2616                    mCurrentPackage.packageName = packageName;
2617                }
2618
2619                // In a full backup, we pass a null ParcelFileDescriptor as
2620                // the saved-state "file". This is by definition an incremental,
2621                // so we build a saved state file to pass.
2622                mSavedState = ParcelFileDescriptor.open(mSavedStateName,
2623                        ParcelFileDescriptor.MODE_READ_ONLY |
2624                        ParcelFileDescriptor.MODE_CREATE);  // Make an empty file if necessary
2625
2626                mBackupData = ParcelFileDescriptor.open(mBackupDataName,
2627                        ParcelFileDescriptor.MODE_READ_WRITE |
2628                        ParcelFileDescriptor.MODE_CREATE |
2629                        ParcelFileDescriptor.MODE_TRUNCATE);
2630
2631                if (!SELinux.restorecon(mBackupDataName)) {
2632                    Slog.e(TAG, "SELinux restorecon failed on " + mBackupDataName);
2633                }
2634
2635                mNewState = ParcelFileDescriptor.open(mNewStateName,
2636                        ParcelFileDescriptor.MODE_READ_WRITE |
2637                        ParcelFileDescriptor.MODE_CREATE |
2638                        ParcelFileDescriptor.MODE_TRUNCATE);
2639
2640                // Initiate the target's backup pass
2641                addBackupTrace("setting timeout");
2642                prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
2643                addBackupTrace("calling agent doBackup()");
2644                agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
2645            } catch (Exception e) {
2646                Slog.e(TAG, "Error invoking for backup on " + packageName);
2647                addBackupTrace("exception: " + e);
2648                EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2649                        e.toString());
2650                agentErrorCleanup();
2651                return BackupTransport.AGENT_ERROR;
2652            }
2653
2654            // At this point the agent is off and running.  The next thing to happen will
2655            // either be a callback from the agent, at which point we'll process its data
2656            // for transport, or a timeout.  Either way the next phase will happen in
2657            // response to the TimeoutHandler interface callbacks.
2658            addBackupTrace("invoke success");
2659            return BackupTransport.TRANSPORT_OK;
2660        }
2661
2662        public void failAgent(IBackupAgent agent, String message) {
2663            try {
2664                agent.fail(message);
2665            } catch (Exception e) {
2666                Slog.w(TAG, "Error conveying failure to " + mCurrentPackage.packageName);
2667            }
2668        }
2669
2670        @Override
2671        public void operationComplete() {
2672            // Okay, the agent successfully reported back to us!
2673            final String pkgName = mCurrentPackage.packageName;
2674            final long filepos = mBackupDataName.length();
2675            FileDescriptor fd = mBackupData.getFileDescriptor();
2676            try {
2677                // If it's a 3rd party app, see whether they wrote any protected keys
2678                // and complain mightily if they are attempting shenanigans.
2679                if (mCurrentPackage.applicationInfo != null &&
2680                        (mCurrentPackage.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2681                    ParcelFileDescriptor readFd = ParcelFileDescriptor.open(mBackupDataName,
2682                            ParcelFileDescriptor.MODE_READ_ONLY);
2683                    BackupDataInput in = new BackupDataInput(readFd.getFileDescriptor());
2684                    try {
2685                        while (in.readNextHeader()) {
2686                            final String key = in.getKey();
2687                            if (key != null && key.charAt(0) >= 0xff00) {
2688                                // Not okay: crash them and bail.
2689                                failAgent(mAgentBinder, "Illegal backup key: " + key);
2690                                addBackupTrace("illegal key " + key + " from " + pkgName);
2691                                EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, pkgName,
2692                                        "bad key");
2693                                mBackupHandler.removeMessages(MSG_TIMEOUT);
2694                                agentErrorCleanup();
2695                                // agentErrorCleanup() implicitly executes next state properly
2696                                return;
2697                            }
2698                            in.skipEntityData();
2699                        }
2700                    } finally {
2701                        if (readFd != null) {
2702                            readFd.close();
2703                        }
2704                    }
2705                }
2706
2707                // Piggyback the widget state payload, if any
2708                BackupDataOutput out = new BackupDataOutput(fd);
2709                byte[] widgetState = AppWidgetBackupBridge.getWidgetState(pkgName,
2710                        UserHandle.USER_OWNER);
2711                if (widgetState != null) {
2712                    out.writeEntityHeader(KEY_WIDGET_STATE, widgetState.length);
2713                    out.writeEntityData(widgetState, widgetState.length);
2714                } else {
2715                    // No widget state for this app, but push a 'delete' operation for it
2716                    // in case they're trying to play games with the payload.
2717                    out.writeEntityHeader(KEY_WIDGET_STATE, -1);
2718                }
2719            } catch (IOException e) {
2720                // Hard disk error; recovery/failure policy TBD.  For now roll back,
2721                // but we may want to consider this a transport-level failure (i.e.
2722                // we're in such a bad state that we can't contemplate doing backup
2723                // operations any more during this pass).
2724                Slog.w(TAG, "Unable to save widget state for " + pkgName);
2725                try {
2726                    Os.ftruncate(fd, filepos);
2727                } catch (ErrnoException ee) {
2728                    Slog.w(TAG, "Unable to roll back!");
2729                }
2730            }
2731
2732            // Spin the data off to the transport and proceed with the next stage.
2733            if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2734                    + pkgName);
2735            mBackupHandler.removeMessages(MSG_TIMEOUT);
2736            clearAgentState();
2737            addBackupTrace("operation complete");
2738
2739            ParcelFileDescriptor backupData = null;
2740            mStatus = BackupTransport.TRANSPORT_OK;
2741            try {
2742                int size = (int) mBackupDataName.length();
2743                if (size > 0) {
2744                    if (mStatus == BackupTransport.TRANSPORT_OK) {
2745                        backupData = ParcelFileDescriptor.open(mBackupDataName,
2746                                ParcelFileDescriptor.MODE_READ_ONLY);
2747                        addBackupTrace("sending data to transport");
2748                        mStatus = mTransport.performBackup(mCurrentPackage, backupData);
2749                    }
2750
2751                    // TODO - We call finishBackup() for each application backed up, because
2752                    // we need to know now whether it succeeded or failed.  Instead, we should
2753                    // hold off on finishBackup() until the end, which implies holding off on
2754                    // renaming *all* the output state files (see below) until that happens.
2755
2756                    addBackupTrace("data delivered: " + mStatus);
2757                    if (mStatus == BackupTransport.TRANSPORT_OK) {
2758                        addBackupTrace("finishing op on transport");
2759                        mStatus = mTransport.finishBackup();
2760                        addBackupTrace("finished: " + mStatus);
2761                    }
2762                } else {
2763                    if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
2764                    addBackupTrace("no data to send");
2765                }
2766
2767                // After successful transport, delete the now-stale data
2768                // and juggle the files so that next time we supply the agent
2769                // with the new state file it just created.
2770                if (mStatus == BackupTransport.TRANSPORT_OK) {
2771                    mBackupDataName.delete();
2772                    mNewStateName.renameTo(mSavedStateName);
2773                    EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, pkgName, size);
2774                    logBackupComplete(pkgName);
2775                } else {
2776                    EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, pkgName);
2777                }
2778            } catch (Exception e) {
2779                Slog.e(TAG, "Transport error backing up " + pkgName, e);
2780                EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, pkgName);
2781                mStatus = BackupTransport.TRANSPORT_ERROR;
2782            } finally {
2783                try { if (backupData != null) backupData.close(); } catch (IOException e) {}
2784            }
2785
2786            // If we encountered an error here it's a transport-level failure.  That
2787            // means we need to halt everything and reschedule everything for next time.
2788            final BackupState nextState;
2789            if (mStatus != BackupTransport.TRANSPORT_OK) {
2790                revertAndEndBackup();
2791                nextState = BackupState.FINAL;
2792            } else {
2793                // Success!  Proceed with the next app if any, otherwise we're done.
2794                nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2795            }
2796
2797            executeNextState(nextState);
2798        }
2799
2800        @Override
2801        public void handleTimeout() {
2802            // Whoops, the current agent timed out running doBackup().  Tidy up and restage
2803            // it for the next time we run a backup pass.
2804            // !!! TODO: keep track of failure counts per agent, and blacklist those which
2805            // fail repeatedly (i.e. have proved themselves to be buggy).
2806            Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2807            EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2808                    "timeout");
2809            addBackupTrace("timeout of " + mCurrentPackage.packageName);
2810            agentErrorCleanup();
2811            dataChangedImpl(mCurrentPackage.packageName);
2812        }
2813
2814        void revertAndEndBackup() {
2815            if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
2816            addBackupTrace("transport error; reverting");
2817            for (BackupRequest request : mOriginalQueue) {
2818                dataChangedImpl(request.packageName);
2819            }
2820            // We also want to reset the backup schedule based on whatever
2821            // the transport suggests by way of retry/backoff time.
2822            restartBackupAlarm();
2823        }
2824
2825        void agentErrorCleanup() {
2826            mBackupDataName.delete();
2827            mNewStateName.delete();
2828            clearAgentState();
2829
2830            executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2831        }
2832
2833        // Cleanup common to both success and failure cases
2834        void clearAgentState() {
2835            try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2836            try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2837            try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2838            mSavedState = mBackupData = mNewState = null;
2839            synchronized (mCurrentOpLock) {
2840                mCurrentOperations.clear();
2841            }
2842
2843            // If this was a pseudopackage there's no associated Activity Manager state
2844            if (mCurrentPackage.applicationInfo != null) {
2845                addBackupTrace("unbinding " + mCurrentPackage.packageName);
2846                try {  // unbind even on timeout, just in case
2847                    mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2848                } catch (RemoteException e) { /* can't happen; activity manager is local */ }
2849            }
2850        }
2851
2852        void restartBackupAlarm() {
2853            addBackupTrace("setting backup trigger");
2854            synchronized (mQueueLock) {
2855                try {
2856                    startBackupAlarmsLocked(mTransport.requestBackupTime());
2857                } catch (RemoteException e) { /* cannot happen */ }
2858            }
2859        }
2860
2861        void executeNextState(BackupState nextState) {
2862            if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2863                    + this + " nextState=" + nextState);
2864            addBackupTrace("executeNextState => " + nextState);
2865            mCurrentState = nextState;
2866            Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2867            mBackupHandler.sendMessage(msg);
2868        }
2869    }
2870
2871
2872    // ----- Full backup/restore to a file/socket -----
2873
2874    class FullBackupObbConnection implements ServiceConnection {
2875        volatile IObbBackupService mService;
2876
2877        FullBackupObbConnection() {
2878            mService = null;
2879        }
2880
2881        public void establish() {
2882            if (DEBUG) Slog.i(TAG, "Initiating bind of OBB service on " + this);
2883            Intent obbIntent = new Intent().setComponent(new ComponentName(
2884                    "com.android.sharedstoragebackup",
2885                    "com.android.sharedstoragebackup.ObbBackupService"));
2886            BackupManagerService.this.mContext.bindService(
2887                    obbIntent, this, Context.BIND_AUTO_CREATE);
2888        }
2889
2890        public void tearDown() {
2891            BackupManagerService.this.mContext.unbindService(this);
2892        }
2893
2894        public boolean backupObbs(PackageInfo pkg, OutputStream out) {
2895            boolean success = false;
2896            waitForConnection();
2897
2898            ParcelFileDescriptor[] pipes = null;
2899            try {
2900                pipes = ParcelFileDescriptor.createPipe();
2901                int token = generateToken();
2902                prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
2903                mService.backupObbs(pkg.packageName, pipes[1], token, mBackupManagerBinder);
2904                routeSocketDataToOutput(pipes[0], out);
2905                success = waitUntilOperationComplete(token);
2906            } catch (Exception e) {
2907                Slog.w(TAG, "Unable to back up OBBs for " + pkg, e);
2908            } finally {
2909                try {
2910                    out.flush();
2911                    if (pipes != null) {
2912                        if (pipes[0] != null) pipes[0].close();
2913                        if (pipes[1] != null) pipes[1].close();
2914                    }
2915                } catch (IOException e) {
2916                    Slog.w(TAG, "I/O error closing down OBB backup", e);
2917                }
2918            }
2919            return success;
2920        }
2921
2922        public void restoreObbFile(String pkgName, ParcelFileDescriptor data,
2923                long fileSize, int type, String path, long mode, long mtime,
2924                int token, IBackupManager callbackBinder) {
2925            waitForConnection();
2926
2927            try {
2928                mService.restoreObbFile(pkgName, data, fileSize, type, path, mode, mtime,
2929                        token, callbackBinder);
2930            } catch (Exception e) {
2931                Slog.w(TAG, "Unable to restore OBBs for " + pkgName, e);
2932            }
2933        }
2934
2935        private void waitForConnection() {
2936            synchronized (this) {
2937                while (mService == null) {
2938                    if (DEBUG) Slog.i(TAG, "...waiting for OBB service binding...");
2939                    try {
2940                        this.wait();
2941                    } catch (InterruptedException e) { /* never interrupted */ }
2942                }
2943                if (DEBUG) Slog.i(TAG, "Connected to OBB service; continuing");
2944            }
2945        }
2946
2947        @Override
2948        public void onServiceConnected(ComponentName name, IBinder service) {
2949            synchronized (this) {
2950                mService = IObbBackupService.Stub.asInterface(service);
2951                if (DEBUG) Slog.i(TAG, "OBB service connection " + mService
2952                        + " connected on " + this);
2953                this.notifyAll();
2954            }
2955        }
2956
2957        @Override
2958        public void onServiceDisconnected(ComponentName name) {
2959            synchronized (this) {
2960                mService = null;
2961                if (DEBUG) Slog.i(TAG, "OBB service connection disconnected on " + this);
2962                this.notifyAll();
2963            }
2964        }
2965
2966    }
2967
2968    private void routeSocketDataToOutput(ParcelFileDescriptor inPipe, OutputStream out)
2969            throws IOException {
2970        FileInputStream raw = new FileInputStream(inPipe.getFileDescriptor());
2971        DataInputStream in = new DataInputStream(raw);
2972
2973        byte[] buffer = new byte[32 * 1024];
2974        int chunkTotal;
2975        while ((chunkTotal = in.readInt()) > 0) {
2976            while (chunkTotal > 0) {
2977                int toRead = (chunkTotal > buffer.length) ? buffer.length : chunkTotal;
2978                int nRead = in.read(buffer, 0, toRead);
2979                out.write(buffer, 0, nRead);
2980                chunkTotal -= nRead;
2981            }
2982        }
2983    }
2984
2985    // Core logic for performing one package's full backup, gathering the tarball from the
2986    // application and emitting it to the designated OutputStream.
2987    class FullBackupEngine {
2988        OutputStream mOutput;
2989        IFullBackupRestoreObserver mObserver;
2990        File mFilesDir;
2991        File mManifestFile;
2992        File mMetadataFile;
2993        boolean mIncludeApks;
2994
2995        class FullBackupRunner implements Runnable {
2996            PackageInfo mPackage;
2997            byte[] mWidgetData;
2998            IBackupAgent mAgent;
2999            ParcelFileDescriptor mPipe;
3000            int mToken;
3001            boolean mSendApk;
3002            boolean mWriteManifest;
3003
3004            FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
3005                    int token, boolean sendApk, boolean writeManifest, byte[] widgetData)
3006                            throws IOException {
3007                mPackage = pack;
3008                mWidgetData = widgetData;
3009                mAgent = agent;
3010                mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
3011                mToken = token;
3012                mSendApk = sendApk;
3013                mWriteManifest = writeManifest;
3014            }
3015
3016            @Override
3017            public void run() {
3018                try {
3019                    BackupDataOutput output = new BackupDataOutput(
3020                            mPipe.getFileDescriptor());
3021
3022                    if (mWriteManifest) {
3023                        final boolean writeWidgetData = mWidgetData != null;
3024                        if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
3025                        writeAppManifest(mPackage, mManifestFile, mSendApk, writeWidgetData);
3026                        FullBackup.backupToTar(mPackage.packageName, null, null,
3027                                mFilesDir.getAbsolutePath(),
3028                                mManifestFile.getAbsolutePath(),
3029                                output);
3030                        mManifestFile.delete();
3031
3032                        // We only need to write a metadata file if we have widget data to stash
3033                        if (writeWidgetData) {
3034                            writeMetadata(mPackage, mMetadataFile, mWidgetData);
3035                            FullBackup.backupToTar(mPackage.packageName, null, null,
3036                                    mFilesDir.getAbsolutePath(),
3037                                    mMetadataFile.getAbsolutePath(),
3038                                    output);
3039                            mMetadataFile.delete();
3040                        }
3041                    }
3042
3043                    if (mSendApk) {
3044                        writeApkToBackup(mPackage, output);
3045                    }
3046
3047                    if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
3048                    prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
3049                    mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
3050                } catch (IOException e) {
3051                    Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
3052                } catch (RemoteException e) {
3053                    Slog.e(TAG, "Remote agent vanished during full backup of "
3054                            + mPackage.packageName);
3055                } finally {
3056                    try {
3057                        mPipe.close();
3058                    } catch (IOException e) {}
3059                }
3060            }
3061        }
3062
3063        FullBackupEngine(OutputStream output, String packageName, boolean alsoApks) {
3064            mOutput = output;
3065            mIncludeApks = alsoApks;
3066            mFilesDir = new File("/data/system");
3067            mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
3068            mMetadataFile = new File(mFilesDir, BACKUP_METADATA_FILENAME);
3069        }
3070
3071
3072        public int backupOnePackage(PackageInfo pkg) throws RemoteException {
3073            int result = BackupTransport.TRANSPORT_OK;
3074            Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
3075
3076            IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
3077                    IApplicationThread.BACKUP_MODE_FULL);
3078            if (agent != null) {
3079                ParcelFileDescriptor[] pipes = null;
3080                try {
3081                    pipes = ParcelFileDescriptor.createPipe();
3082
3083                    ApplicationInfo app = pkg.applicationInfo;
3084                    final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
3085                    final boolean sendApk = mIncludeApks
3086                            && !isSharedStorage
3087                            && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
3088                            && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
3089                                (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
3090
3091                    byte[] widgetBlob = AppWidgetBackupBridge.getWidgetState(pkg.packageName,
3092                            UserHandle.USER_OWNER);
3093
3094                    final int token = generateToken();
3095                    FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
3096                            token, sendApk, !isSharedStorage, widgetBlob);
3097                    pipes[1].close();   // the runner has dup'd it
3098                    pipes[1] = null;
3099                    Thread t = new Thread(runner, "app-data-runner");
3100                    t.start();
3101
3102                    // Now pull data from the app and stuff it into the output
3103                    try {
3104                        routeSocketDataToOutput(pipes[0], mOutput);
3105                    } catch (IOException e) {
3106                        Slog.i(TAG, "Caught exception reading from agent", e);
3107                        result = BackupTransport.AGENT_ERROR;
3108                    }
3109
3110                    if (!waitUntilOperationComplete(token)) {
3111                        Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
3112                        result = BackupTransport.AGENT_ERROR;
3113                    } else {
3114                        if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
3115                    }
3116
3117                } catch (IOException e) {
3118                    Slog.e(TAG, "Error backing up " + pkg.packageName, e);
3119                    result = BackupTransport.AGENT_ERROR;
3120                } finally {
3121                    try {
3122                        // flush after every package
3123                        mOutput.flush();
3124                        if (pipes != null) {
3125                            if (pipes[0] != null) pipes[0].close();
3126                            if (pipes[1] != null) pipes[1].close();
3127                        }
3128                    } catch (IOException e) {
3129                        Slog.w(TAG, "Error bringing down backup stack");
3130                        result = BackupTransport.TRANSPORT_ERROR;
3131                    }
3132                }
3133            } else {
3134                Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
3135                result = BackupTransport.AGENT_ERROR;
3136            }
3137            tearDown(pkg);
3138            return result;
3139        }
3140
3141        private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
3142            // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
3143            // TODO: handle backing up split APKs
3144            final String appSourceDir = pkg.applicationInfo.getBaseCodePath();
3145            final String apkDir = new File(appSourceDir).getParent();
3146            FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
3147                    apkDir, appSourceDir, output);
3148
3149            // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
3150            // doesn't have access to external storage.
3151
3152            // Save associated .obb content if it exists and we did save the apk
3153            // check for .obb and save those too
3154            final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER);
3155            final File obbDir = userEnv.buildExternalStorageAppObbDirs(pkg.packageName)[0];
3156            if (obbDir != null) {
3157                if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
3158                File[] obbFiles = obbDir.listFiles();
3159                if (obbFiles != null) {
3160                    final String obbDirName = obbDir.getAbsolutePath();
3161                    for (File obb : obbFiles) {
3162                        FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
3163                                obbDirName, obb.getAbsolutePath(), output);
3164                    }
3165                }
3166            }
3167        }
3168
3169        private void writeAppManifest(PackageInfo pkg, File manifestFile,
3170                boolean withApk, boolean withWidgets) throws IOException {
3171            // Manifest format. All data are strings ending in LF:
3172            //     BACKUP_MANIFEST_VERSION, currently 1
3173            //
3174            // Version 1:
3175            //     package name
3176            //     package's versionCode
3177            //     platform versionCode
3178            //     getInstallerPackageName() for this package (maybe empty)
3179            //     boolean: "1" if archive includes .apk; any other string means not
3180            //     number of signatures == N
3181            // N*:    signature byte array in ascii format per Signature.toCharsString()
3182            StringBuilder builder = new StringBuilder(4096);
3183            StringBuilderPrinter printer = new StringBuilderPrinter(builder);
3184
3185            printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
3186            printer.println(pkg.packageName);
3187            printer.println(Integer.toString(pkg.versionCode));
3188            printer.println(Integer.toString(Build.VERSION.SDK_INT));
3189
3190            String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
3191            printer.println((installerName != null) ? installerName : "");
3192
3193            printer.println(withApk ? "1" : "0");
3194            if (pkg.signatures == null) {
3195                printer.println("0");
3196            } else {
3197                printer.println(Integer.toString(pkg.signatures.length));
3198                for (Signature sig : pkg.signatures) {
3199                    printer.println(sig.toCharsString());
3200                }
3201            }
3202
3203            FileOutputStream outstream = new FileOutputStream(manifestFile);
3204            outstream.write(builder.toString().getBytes());
3205            outstream.close();
3206
3207            // We want the manifest block in the archive stream to be idempotent:
3208            // each time we generate a backup stream for the app, we want the manifest
3209            // block to be identical.  The underlying tar mechanism sees it as a file,
3210            // though, and will propagate its mtime, causing the tar header to vary.
3211            // Avoid this problem by pinning the mtime to zero.
3212            manifestFile.setLastModified(0);
3213        }
3214
3215        // Widget metadata format. All header entries are strings ending in LF:
3216        //
3217        // Version 1 header:
3218        //     BACKUP_METADATA_VERSION, currently "1"
3219        //     package name
3220        //
3221        // File data (all integers are binary in network byte order)
3222        // *N: 4 : integer token identifying which metadata blob
3223        //     4 : integer size of this blob = N
3224        //     N : raw bytes of this metadata blob
3225        //
3226        // Currently understood blobs (always in network byte order):
3227        //
3228        //     widgets : metadata token = 0x01FFED01 (BACKUP_WIDGET_METADATA_TOKEN)
3229        //
3230        // Unrecognized blobs are *ignored*, not errors.
3231        private void writeMetadata(PackageInfo pkg, File destination, byte[] widgetData)
3232                throws IOException {
3233            StringBuilder b = new StringBuilder(512);
3234            StringBuilderPrinter printer = new StringBuilderPrinter(b);
3235            printer.println(Integer.toString(BACKUP_METADATA_VERSION));
3236            printer.println(pkg.packageName);
3237
3238            FileOutputStream fout = new FileOutputStream(destination);
3239            BufferedOutputStream bout = new BufferedOutputStream(fout);
3240            DataOutputStream out = new DataOutputStream(bout);
3241            bout.write(b.toString().getBytes());    // bypassing DataOutputStream
3242
3243            if (widgetData != null && widgetData.length > 0) {
3244                out.writeInt(BACKUP_WIDGET_METADATA_TOKEN);
3245                out.writeInt(widgetData.length);
3246                out.write(widgetData);
3247            }
3248            bout.flush();
3249            out.close();
3250
3251            // As with the manifest file, guarantee idempotence of the archive metadata
3252            // for the widget block by using a fixed mtime on the transient file.
3253            destination.setLastModified(0);
3254        }
3255
3256        private void tearDown(PackageInfo pkg) {
3257            if (pkg != null) {
3258                final ApplicationInfo app = pkg.applicationInfo;
3259                if (app != null) {
3260                    try {
3261                        // unbind and tidy up even on timeout or failure, just in case
3262                        mActivityManager.unbindBackupAgent(app);
3263
3264                        // The agent was running with a stub Application object, so shut it down.
3265                        if (app.uid != Process.SYSTEM_UID
3266                                && app.uid != Process.PHONE_UID) {
3267                            if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
3268                            mActivityManager.killApplicationProcess(app.processName, app.uid);
3269                        } else {
3270                            if (MORE_DEBUG) Slog.d(TAG, "Not killing after backup: " + app.processName);
3271                        }
3272                    } catch (RemoteException e) {
3273                        Slog.d(TAG, "Lost app trying to shut down");
3274                    }
3275                }
3276            }
3277        }
3278    }
3279
3280    // Generic driver skeleton for full backup operations
3281    abstract class FullBackupTask implements Runnable {
3282        IFullBackupRestoreObserver mObserver;
3283
3284        FullBackupTask(IFullBackupRestoreObserver observer) {
3285            mObserver = observer;
3286        }
3287
3288        // wrappers for observer use
3289        final void sendStartBackup() {
3290            if (mObserver != null) {
3291                try {
3292                    mObserver.onStartBackup();
3293                } catch (RemoteException e) {
3294                    Slog.w(TAG, "full backup observer went away: startBackup");
3295                    mObserver = null;
3296                }
3297            }
3298        }
3299
3300        final void sendOnBackupPackage(String name) {
3301            if (mObserver != null) {
3302                try {
3303                    // TODO: use a more user-friendly name string
3304                    mObserver.onBackupPackage(name);
3305                } catch (RemoteException e) {
3306                    Slog.w(TAG, "full backup observer went away: backupPackage");
3307                    mObserver = null;
3308                }
3309            }
3310        }
3311
3312        final void sendEndBackup() {
3313            if (mObserver != null) {
3314                try {
3315                    mObserver.onEndBackup();
3316                } catch (RemoteException e) {
3317                    Slog.w(TAG, "full backup observer went away: endBackup");
3318                    mObserver = null;
3319                }
3320            }
3321        }
3322    }
3323
3324    // Full backup task variant used for adb backup
3325    class PerformAdbBackupTask extends FullBackupTask {
3326        FullBackupEngine mBackupEngine;
3327        final AtomicBoolean mLatch;
3328
3329        ParcelFileDescriptor mOutputFile;
3330        DeflaterOutputStream mDeflater;
3331        boolean mIncludeApks;
3332        boolean mIncludeObbs;
3333        boolean mIncludeShared;
3334        boolean mDoWidgets;
3335        boolean mAllApps;
3336        boolean mIncludeSystem;
3337        boolean mCompress;
3338        ArrayList<String> mPackages;
3339        String mCurrentPassword;
3340        String mEncryptPassword;
3341
3342        PerformAdbBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
3343                boolean includeApks, boolean includeObbs, boolean includeShared,
3344                boolean doWidgets, String curPassword, String encryptPassword, boolean doAllApps,
3345                boolean doSystem, boolean doCompress, String[] packages, AtomicBoolean latch) {
3346            super(observer);
3347            mLatch = latch;
3348
3349            mOutputFile = fd;
3350            mIncludeApks = includeApks;
3351            mIncludeObbs = includeObbs;
3352            mIncludeShared = includeShared;
3353            mDoWidgets = doWidgets;
3354            mAllApps = doAllApps;
3355            mIncludeSystem = doSystem;
3356            mPackages = (packages == null)
3357                    ? new ArrayList<String>()
3358                    : new ArrayList<String>(Arrays.asList(packages));
3359            mCurrentPassword = curPassword;
3360            // when backing up, if there is a current backup password, we require that
3361            // the user use a nonempty encryption password as well.  if one is supplied
3362            // in the UI we use that, but if the UI was left empty we fall back to the
3363            // current backup password (which was supplied by the user as well).
3364            if (encryptPassword == null || "".equals(encryptPassword)) {
3365                mEncryptPassword = curPassword;
3366            } else {
3367                mEncryptPassword = encryptPassword;
3368            }
3369            mCompress = doCompress;
3370        }
3371
3372        void addPackagesToSet(TreeMap<String, PackageInfo> set, List<String> pkgNames) {
3373            for (String pkgName : pkgNames) {
3374                if (!set.containsKey(pkgName)) {
3375                    try {
3376                        PackageInfo info = mPackageManager.getPackageInfo(pkgName,
3377                                PackageManager.GET_SIGNATURES);
3378                        set.put(pkgName, info);
3379                    } catch (NameNotFoundException e) {
3380                        Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
3381                    }
3382                }
3383            }
3384        }
3385
3386        private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
3387                OutputStream ofstream) throws Exception {
3388            // User key will be used to encrypt the master key.
3389            byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
3390            SecretKey userKey = buildPasswordKey(PBKDF_CURRENT, mEncryptPassword, newUserSalt,
3391                    PBKDF2_HASH_ROUNDS);
3392
3393            // the master key is random for each backup
3394            byte[] masterPw = new byte[256 / 8];
3395            mRng.nextBytes(masterPw);
3396            byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
3397
3398            // primary encryption of the datastream with the random key
3399            Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
3400            SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
3401            c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
3402            OutputStream finalOutput = new CipherOutputStream(ofstream, c);
3403
3404            // line 4: name of encryption algorithm
3405            headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
3406            headerbuf.append('\n');
3407            // line 5: user password salt [hex]
3408            headerbuf.append(byteArrayToHex(newUserSalt));
3409            headerbuf.append('\n');
3410            // line 6: master key checksum salt [hex]
3411            headerbuf.append(byteArrayToHex(checksumSalt));
3412            headerbuf.append('\n');
3413            // line 7: number of PBKDF2 rounds used [decimal]
3414            headerbuf.append(PBKDF2_HASH_ROUNDS);
3415            headerbuf.append('\n');
3416
3417            // line 8: IV of the user key [hex]
3418            Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
3419            mkC.init(Cipher.ENCRYPT_MODE, userKey);
3420
3421            byte[] IV = mkC.getIV();
3422            headerbuf.append(byteArrayToHex(IV));
3423            headerbuf.append('\n');
3424
3425            // line 9: master IV + key blob, encrypted by the user key [hex].  Blob format:
3426            //    [byte] IV length = Niv
3427            //    [array of Niv bytes] IV itself
3428            //    [byte] master key length = Nmk
3429            //    [array of Nmk bytes] master key itself
3430            //    [byte] MK checksum hash length = Nck
3431            //    [array of Nck bytes] master key checksum hash
3432            //
3433            // The checksum is the (master key + checksum salt), run through the
3434            // stated number of PBKDF2 rounds
3435            IV = c.getIV();
3436            byte[] mk = masterKeySpec.getEncoded();
3437            byte[] checksum = makeKeyChecksum(PBKDF_CURRENT, masterKeySpec.getEncoded(),
3438                    checksumSalt, PBKDF2_HASH_ROUNDS);
3439
3440            ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
3441                    + checksum.length + 3);
3442            DataOutputStream mkOut = new DataOutputStream(blob);
3443            mkOut.writeByte(IV.length);
3444            mkOut.write(IV);
3445            mkOut.writeByte(mk.length);
3446            mkOut.write(mk);
3447            mkOut.writeByte(checksum.length);
3448            mkOut.write(checksum);
3449            mkOut.flush();
3450            byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
3451            headerbuf.append(byteArrayToHex(encryptedMk));
3452            headerbuf.append('\n');
3453
3454            return finalOutput;
3455        }
3456
3457        private void finalizeBackup(OutputStream out) {
3458            try {
3459                // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
3460                byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
3461                out.write(eof);
3462            } catch (IOException e) {
3463                Slog.w(TAG, "Error attempting to finalize backup stream");
3464            }
3465        }
3466
3467        @Override
3468        public void run() {
3469            Slog.i(TAG, "--- Performing full-dataset adb backup ---");
3470
3471            TreeMap<String, PackageInfo> packagesToBackup = new TreeMap<String, PackageInfo>();
3472            FullBackupObbConnection obbConnection = new FullBackupObbConnection();
3473            obbConnection.establish();  // we'll want this later
3474
3475            sendStartBackup();
3476
3477            // doAllApps supersedes the package set if any
3478            if (mAllApps) {
3479                List<PackageInfo> allPackages = mPackageManager.getInstalledPackages(
3480                        PackageManager.GET_SIGNATURES);
3481                for (int i = 0; i < allPackages.size(); i++) {
3482                    PackageInfo pkg = allPackages.get(i);
3483                    // Exclude system apps if we've been asked to do so
3484                    if (mIncludeSystem == true
3485                            || ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3486                        packagesToBackup.put(pkg.packageName, pkg);
3487                    }
3488                }
3489            }
3490
3491            // If we're doing widget state as well, ensure that we have all the involved
3492            // host & provider packages in the set
3493            if (mDoWidgets) {
3494                List<String> pkgs =
3495                        AppWidgetBackupBridge.getWidgetParticipants(UserHandle.USER_OWNER);
3496                if (pkgs != null) {
3497                    if (MORE_DEBUG) {
3498                        Slog.i(TAG, "Adding widget participants to backup set:");
3499                        StringBuilder sb = new StringBuilder(128);
3500                        sb.append("   ");
3501                        for (String s : pkgs) {
3502                            sb.append(' ');
3503                            sb.append(s);
3504                        }
3505                        Slog.i(TAG, sb.toString());
3506                    }
3507                    addPackagesToSet(packagesToBackup, pkgs);
3508                }
3509            }
3510
3511            // Now process the command line argument packages, if any. Note that explicitly-
3512            // named system-partition packages will be included even if includeSystem was
3513            // set to false.
3514            if (mPackages != null) {
3515                addPackagesToSet(packagesToBackup, mPackages);
3516            }
3517
3518            // Now we cull any inapplicable / inappropriate packages from the set.  This
3519            // includes the special shared-storage agent package; we handle that one
3520            // explicitly at the end of the backup pass.
3521            Iterator<Entry<String, PackageInfo>> iter = packagesToBackup.entrySet().iterator();
3522            while (iter.hasNext()) {
3523                PackageInfo pkg = iter.next().getValue();
3524                if (!appIsEligibleForBackup(pkg.applicationInfo)) {
3525                    iter.remove();
3526                }
3527            }
3528
3529            // flatten the set of packages now so we can explicitly control the ordering
3530            ArrayList<PackageInfo> backupQueue =
3531                    new ArrayList<PackageInfo>(packagesToBackup.values());
3532            FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
3533            OutputStream out = null;
3534
3535            PackageInfo pkg = null;
3536            try {
3537                boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
3538                OutputStream finalOutput = ofstream;
3539
3540                // Verify that the given password matches the currently-active
3541                // backup password, if any
3542                if (!backupPasswordMatches(mCurrentPassword)) {
3543                    if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
3544                    return;
3545                }
3546
3547                // Write the global file header.  All strings are UTF-8 encoded; lines end
3548                // with a '\n' byte.  Actual backup data begins immediately following the
3549                // final '\n'.
3550                //
3551                // line 1: "ANDROID BACKUP"
3552                // line 2: backup file format version, currently "2"
3553                // line 3: compressed?  "0" if not compressed, "1" if compressed.
3554                // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
3555                //
3556                // When line 4 is not "none", then additional header data follows:
3557                //
3558                // line 5: user password salt [hex]
3559                // line 6: master key checksum salt [hex]
3560                // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
3561                // line 8: IV of the user key [hex]
3562                // line 9: master key blob [hex]
3563                //     IV of the master key, master key itself, master key checksum hash
3564                //
3565                // The master key checksum is the master key plus its checksum salt, run through
3566                // 10k rounds of PBKDF2.  This is used to verify that the user has supplied the
3567                // correct password for decrypting the archive:  the master key decrypted from
3568                // the archive using the user-supplied password is also run through PBKDF2 in
3569                // this way, and if the result does not match the checksum as stored in the
3570                // archive, then we know that the user-supplied password does not match the
3571                // archive's.
3572                StringBuilder headerbuf = new StringBuilder(1024);
3573
3574                headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
3575                headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
3576                headerbuf.append(mCompress ? "\n1\n" : "\n0\n");
3577
3578                try {
3579                    // Set up the encryption stage if appropriate, and emit the correct header
3580                    if (encrypting) {
3581                        finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
3582                    } else {
3583                        headerbuf.append("none\n");
3584                    }
3585
3586                    byte[] header = headerbuf.toString().getBytes("UTF-8");
3587                    ofstream.write(header);
3588
3589                    // Set up the compression stage feeding into the encryption stage (if any)
3590                    if (mCompress) {
3591                        Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
3592                        finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
3593                    }
3594
3595                    out = finalOutput;
3596                } catch (Exception e) {
3597                    // Should never happen!
3598                    Slog.e(TAG, "Unable to emit archive header", e);
3599                    return;
3600                }
3601
3602                // Shared storage if requested
3603                if (mIncludeShared) {
3604                    try {
3605                        pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
3606                        backupQueue.add(pkg);
3607                    } catch (NameNotFoundException e) {
3608                        Slog.e(TAG, "Unable to find shared-storage backup handler");
3609                    }
3610                }
3611
3612                // Now actually run the constructed backup sequence
3613                int N = backupQueue.size();
3614                for (int i = 0; i < N; i++) {
3615                    pkg = backupQueue.get(i);
3616                    final boolean isSharedStorage =
3617                            pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
3618
3619                    mBackupEngine = new FullBackupEngine(out, pkg.packageName, mIncludeApks);
3620                    sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
3621                    mBackupEngine.backupOnePackage(pkg);
3622
3623                    // after the app's agent runs to handle its private filesystem
3624                    // contents, back up any OBB content it has on its behalf.
3625                    if (mIncludeObbs) {
3626                        boolean obbOkay = obbConnection.backupObbs(pkg, out);
3627                        if (!obbOkay) {
3628                            throw new RuntimeException("Failure writing OBB stack for " + pkg);
3629                        }
3630                    }
3631                }
3632
3633                // Done!
3634                finalizeBackup(out);
3635            } catch (RemoteException e) {
3636                Slog.e(TAG, "App died during full backup");
3637            } catch (Exception e) {
3638                Slog.e(TAG, "Internal exception during full backup", e);
3639            } finally {
3640                try {
3641                    if (out != null) out.close();
3642                    mOutputFile.close();
3643                } catch (IOException e) {
3644                    /* nothing we can do about this */
3645                }
3646                synchronized (mCurrentOpLock) {
3647                    mCurrentOperations.clear();
3648                }
3649                synchronized (mLatch) {
3650                    mLatch.set(true);
3651                    mLatch.notifyAll();
3652                }
3653                sendEndBackup();
3654                obbConnection.tearDown();
3655                if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
3656                mWakelock.release();
3657            }
3658        }
3659    }
3660
3661    // Full backup task extension used for transport-oriented operation
3662    class PerformFullTransportBackupTask extends FullBackupTask {
3663        static final String TAG = "PFTBT";
3664        ArrayList<PackageInfo> mPackages;
3665        boolean mUpdateSchedule;
3666        AtomicBoolean mLatch;
3667        AtomicBoolean mKeepRunning;     // signal from job scheduler
3668        FullBackupJob mJob;             // if a scheduled job needs to be finished afterwards
3669
3670        PerformFullTransportBackupTask(IFullBackupRestoreObserver observer,
3671                String[] whichPackages, boolean updateSchedule,
3672                FullBackupJob runningJob, AtomicBoolean latch) {
3673            super(observer);
3674            mUpdateSchedule = updateSchedule;
3675            mLatch = latch;
3676            mKeepRunning = new AtomicBoolean(true);
3677            mJob = runningJob;
3678            mPackages = new ArrayList<PackageInfo>(whichPackages.length);
3679
3680            for (String pkg : whichPackages) {
3681                try {
3682                    PackageInfo info = mPackageManager.getPackageInfo(pkg,
3683                            PackageManager.GET_SIGNATURES);
3684                    if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
3685                            || pkg.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
3686                        // Cull any packages that have indicated that backups are not permitted,
3687                        // as well as any explicit mention of the 'special' shared-storage agent
3688                        // package (we handle that one at the end).
3689                        if (MORE_DEBUG) {
3690                            Slog.d(TAG, "Ignoring opted-out package " + pkg);
3691                        }
3692                        continue;
3693                    } else if ((info.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
3694                            && (info.applicationInfo.backupAgentName == null)) {
3695                        // Cull any packages that run as system-domain uids but do not define their
3696                        // own backup agents
3697                        if (MORE_DEBUG) {
3698                            Slog.d(TAG, "Ignoring non-agent system package " + pkg);
3699                        }
3700                        continue;
3701                    }
3702                    mPackages.add(info);
3703                } catch (NameNotFoundException e) {
3704                    Slog.i(TAG, "Requested package " + pkg + " not found; ignoring");
3705                }
3706            }
3707        }
3708
3709        public void setRunning(boolean running) {
3710            mKeepRunning.set(running);
3711        }
3712
3713        @Override
3714        public void run() {
3715            // data from the app, passed to us for bridging to the transport
3716            ParcelFileDescriptor[] enginePipes = null;
3717
3718            // Pipe through which we write data to the transport
3719            ParcelFileDescriptor[] transportPipes = null;
3720
3721            PackageInfo currentPackage;
3722
3723            try {
3724                IBackupTransport transport = getTransport(mCurrentTransport);
3725                if (transport == null) {
3726                    Slog.w(TAG, "Transport not present; full data backup not performed");
3727                    return;
3728                }
3729
3730                // Set up to send data to the transport
3731                final int N = mPackages.size();
3732                for (int i = 0; i < N; i++) {
3733                    currentPackage = mPackages.get(i);
3734                    if (DEBUG) {
3735                        Slog.i(TAG, "Initiating full-data transport backup of "
3736                                + currentPackage.packageName);
3737                    }
3738                    EventLog.writeEvent(EventLogTags.FULL_BACKUP_PACKAGE,
3739                            currentPackage.packageName);
3740
3741                    transportPipes = ParcelFileDescriptor.createPipe();
3742
3743                    // Tell the transport the data's coming
3744                    int result = transport.performFullBackup(currentPackage,
3745                            transportPipes[0]);
3746                    if (result == BackupTransport.TRANSPORT_OK) {
3747                        // The transport has its own copy of the read end of the pipe,
3748                        // so close ours now
3749                        transportPipes[0].close();
3750                        transportPipes[0] = null;
3751
3752                        // Now set up the backup engine / data source end of things
3753                        enginePipes = ParcelFileDescriptor.createPipe();
3754                        AtomicBoolean runnerLatch = new AtomicBoolean(false);
3755                        SinglePackageBackupRunner backupRunner =
3756                                new SinglePackageBackupRunner(enginePipes[1], currentPackage,
3757                                        runnerLatch);
3758                        // The runner dup'd the pipe half, so we close it here
3759                        enginePipes[1].close();
3760                        enginePipes[1] = null;
3761
3762                        // Spin off the runner to fetch the app's data and pipe it
3763                        // into the engine pipes
3764                        (new Thread(backupRunner, "package-backup-bridge")).start();
3765
3766                        // Read data off the engine pipe and pass it to the transport
3767                        // pipe until we hit EOD on the input stream.
3768                        FileInputStream in = new FileInputStream(
3769                                enginePipes[0].getFileDescriptor());
3770                        FileOutputStream out = new FileOutputStream(
3771                                transportPipes[1].getFileDescriptor());
3772                        byte[] buffer = new byte[8192];
3773                        int nRead = 0;
3774                        do {
3775                            if (!mKeepRunning.get()) {
3776                                if (DEBUG_SCHEDULING) {
3777                                    Slog.i(TAG, "Full backup task told to stop");
3778                                }
3779                                break;
3780                            }
3781                            nRead = in.read(buffer);
3782                            if (nRead > 0) {
3783                                out.write(buffer, 0, nRead);
3784                                result = transport.sendBackupData(nRead);
3785                            }
3786                        } while (nRead > 0 && result == BackupTransport.TRANSPORT_OK);
3787
3788                        // If we've lost our running criteria, tell the transport to cancel
3789                        // and roll back this (partial) backup payload; otherwise tell it
3790                        // that we've reached the clean finish state.
3791                        if (!mKeepRunning.get()) {
3792                            result = BackupTransport.TRANSPORT_ERROR;
3793                            transport.cancelFullBackup();
3794                        } else {
3795                            // If we were otherwise in a good state, now interpret the final
3796                            // result based on what finishBackup() returns.  If we're in a
3797                            // failure case already, preserve that result and ignore whatever
3798                            // finishBackup() reports.
3799                            final int finishResult = transport.finishBackup();
3800                            if (result == BackupTransport.TRANSPORT_OK) {
3801                                result = finishResult;
3802                            }
3803                        }
3804
3805                        if (MORE_DEBUG) {
3806                            Slog.i(TAG, "Done trying to send backup data: result=" + result);
3807                        }
3808
3809                        if (result != BackupTransport.TRANSPORT_OK) {
3810                            Slog.e(TAG, "Error " + result
3811                                    + " backing up " + currentPackage.packageName);
3812                        }
3813                    }
3814
3815                    // Roll this package to the end of the backup queue if we're
3816                    // in a queue-driven mode (regardless of success/failure)
3817                    if (mUpdateSchedule) {
3818                        enqueueFullBackup(currentPackage.packageName,
3819                                System.currentTimeMillis());
3820                    }
3821
3822                    if (result == BackupTransport.TRANSPORT_PACKAGE_REJECTED) {
3823                        if (DEBUG) {
3824                            Slog.i(TAG, "Transport rejected backup of "
3825                                    + currentPackage.packageName
3826                                    + ", skipping");
3827                        }
3828                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_AGENT_FAILURE,
3829                                currentPackage.packageName, "transport rejected");
3830                        // do nothing, clean up, and continue looping
3831                    } else if (result != BackupTransport.TRANSPORT_OK) {
3832                        if (DEBUG) {
3833                            Slog.i(TAG, "Transport failed; aborting backup: " + result);
3834                            EventLog.writeEvent(EventLogTags.FULL_BACKUP_TRANSPORT_FAILURE);
3835                            return;
3836                        }
3837                    } else {
3838                        // Success!
3839                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_SUCCESS,
3840                                currentPackage.packageName);
3841                    }
3842                    cleanUpPipes(transportPipes);
3843                    cleanUpPipes(enginePipes);
3844                    currentPackage = null;
3845                }
3846
3847                if (DEBUG) {
3848                    Slog.i(TAG, "Full backup completed.");
3849                }
3850            } catch (Exception e) {
3851                Slog.w(TAG, "Exception trying full transport backup", e);
3852            } finally {
3853                cleanUpPipes(transportPipes);
3854                cleanUpPipes(enginePipes);
3855
3856                if (mJob != null) {
3857                    mJob.finishBackupPass();
3858                }
3859
3860                synchronized (mQueueLock) {
3861                    mRunningFullBackupTask = null;
3862                }
3863
3864                synchronized (mLatch) {
3865                    mLatch.set(true);
3866                    mLatch.notifyAll();
3867                }
3868
3869                // Now that we're actually done with schedule-driven work, reschedule
3870                // the next pass based on the new queue state.
3871                if (mUpdateSchedule) {
3872                    scheduleNextFullBackupJob();
3873                }
3874            }
3875        }
3876
3877        void cleanUpPipes(ParcelFileDescriptor[] pipes) {
3878            if (pipes != null) {
3879                if (pipes[0] != null) {
3880                    ParcelFileDescriptor fd = pipes[0];
3881                    pipes[0] = null;
3882                    try {
3883                        fd.close();
3884                    } catch (IOException e) {
3885                        Slog.w(TAG, "Unable to close pipe!");
3886                    }
3887                }
3888                if (pipes[1] != null) {
3889                    ParcelFileDescriptor fd = pipes[1];
3890                    pipes[1] = null;
3891                    try {
3892                        fd.close();
3893                    } catch (IOException e) {
3894                        Slog.w(TAG, "Unable to close pipe!");
3895                    }
3896                }
3897            }
3898        }
3899
3900        // Run the backup and pipe it back to the given socket -- expects to run on
3901        // a standalone thread.  The  runner owns this half of the pipe, and closes
3902        // it to indicate EOD to the other end.
3903        class SinglePackageBackupRunner implements Runnable {
3904            final ParcelFileDescriptor mOutput;
3905            final PackageInfo mTarget;
3906            final AtomicBoolean mLatch;
3907
3908            SinglePackageBackupRunner(ParcelFileDescriptor output, PackageInfo target,
3909                    AtomicBoolean latch) throws IOException {
3910                int oldfd = output.getFd();
3911                mOutput = ParcelFileDescriptor.dup(output.getFileDescriptor());
3912                mTarget = target;
3913                mLatch = latch;
3914            }
3915
3916            @Override
3917            public void run() {
3918                try {
3919                    FileOutputStream out = new FileOutputStream(mOutput.getFileDescriptor());
3920                    FullBackupEngine engine = new FullBackupEngine(out, mTarget.packageName, false);
3921                    engine.backupOnePackage(mTarget);
3922                } catch (Exception e) {
3923                    Slog.e(TAG, "Exception during full package backup of " + mTarget);
3924                } finally {
3925                    synchronized (mLatch) {
3926                        mLatch.set(true);
3927                        mLatch.notifyAll();
3928                    }
3929                    try {
3930                        mOutput.close();
3931                    } catch (IOException e) {
3932                        Slog.w(TAG, "Error closing transport pipe in runner");
3933                    }
3934                }
3935            }
3936
3937        }
3938    }
3939
3940    // ----- Full-data backup scheduling -----
3941
3942    /**
3943     * Schedule a job to tell us when it's a good time to run a full backup
3944     */
3945    void scheduleNextFullBackupJob() {
3946        synchronized (mQueueLock) {
3947            if (mFullBackupQueue.size() > 0) {
3948                // schedule the next job at the point in the future when the least-recently
3949                // backed up app comes due for backup again; or immediately if it's already
3950                // due.
3951                long upcomingLastBackup = mFullBackupQueue.get(0).lastBackup;
3952                long timeSinceLast = System.currentTimeMillis() - upcomingLastBackup;
3953                final long latency = (timeSinceLast < MIN_FULL_BACKUP_INTERVAL)
3954                        ? (MIN_FULL_BACKUP_INTERVAL - timeSinceLast) : 0;
3955                Runnable r = new Runnable() {
3956                    @Override public void run() {
3957                        FullBackupJob.schedule(mContext, latency);
3958                    }
3959                };
3960                mBackupHandler.postDelayed(r, 2500);
3961            } else {
3962                if (DEBUG_SCHEDULING) {
3963                    Slog.i(TAG, "Full backup queue empty; not scheduling");
3964                }
3965            }
3966        }
3967    }
3968
3969    /**
3970     * Enqueue full backup for the given app, with a note about when it last ran.
3971     */
3972    void enqueueFullBackup(String packageName, long lastBackedUp) {
3973        FullBackupEntry newEntry = new FullBackupEntry(packageName, lastBackedUp);
3974        synchronized (mQueueLock) {
3975            int N = mFullBackupQueue.size();
3976            // First, sanity check that we aren't adding a duplicate.  Slow but
3977            // straightforward; we'll have at most on the order of a few hundred
3978            // items in this list.
3979            for (int i = N-1; i >= 0; i--) {
3980                final FullBackupEntry e = mFullBackupQueue.get(i);
3981                if (packageName.equals(e.packageName)) {
3982                    if (DEBUG) {
3983                        Slog.w(TAG, "Removing schedule queue dupe of " + packageName);
3984                    }
3985                    mFullBackupQueue.remove(i);
3986                }
3987            }
3988
3989            // This is also slow but easy for modest numbers of apps: work backwards
3990            // from the end of the queue until we find an item whose last backup
3991            // time was before this one, then insert this new entry after it.
3992            int which;
3993            for (which = mFullBackupQueue.size() - 1; which >= 0; which--) {
3994                final FullBackupEntry entry = mFullBackupQueue.get(which);
3995                if (entry.lastBackup <= lastBackedUp) {
3996                    mFullBackupQueue.add(which + 1, newEntry);
3997                    break;
3998                }
3999            }
4000            if (which < 0) {
4001                // this one is earlier than any existing one, so prepend
4002                mFullBackupQueue.add(0, newEntry);
4003            }
4004        }
4005        writeFullBackupScheduleAsync();
4006    }
4007
4008    /**
4009     * Conditions are right for a full backup operation, so run one.  The model we use is
4010     * to perform one app backup per scheduled job execution, and to reschedule the job
4011     * with zero latency as long as conditions remain right and we still have work to do.
4012     *
4013     * @return Whether ongoing work will continue.  The return value here will be passed
4014     *         along as the return value to the scheduled job's onStartJob() callback.
4015     */
4016    boolean beginFullBackup(FullBackupJob scheduledJob) {
4017        long now = System.currentTimeMillis();
4018        FullBackupEntry entry = null;
4019
4020        if (DEBUG_SCHEDULING) {
4021            Slog.i(TAG, "Beginning scheduled full backup operation");
4022        }
4023
4024        // Great; we're able to run full backup jobs now.  See if we have any work to do.
4025        synchronized (mQueueLock) {
4026            if (mRunningFullBackupTask != null) {
4027                Slog.e(TAG, "Backup triggered but one already/still running!");
4028                return false;
4029            }
4030
4031            if (mFullBackupQueue.size() == 0) {
4032                // no work to do so just bow out
4033                if (DEBUG) {
4034                    Slog.i(TAG, "Backup queue empty; doing nothing");
4035                }
4036                return false;
4037            }
4038
4039            entry = mFullBackupQueue.get(0);
4040            long timeSinceRun = now - entry.lastBackup;
4041            if (timeSinceRun < MIN_FULL_BACKUP_INTERVAL) {
4042                // It's too early to back up the next thing in the queue, so bow out
4043                if (MORE_DEBUG) {
4044                    Slog.i(TAG, "Device ready but too early to back up next app");
4045                }
4046                final long latency = MIN_FULL_BACKUP_INTERVAL - timeSinceRun;
4047                mBackupHandler.post(new Runnable() {
4048                    @Override public void run() {
4049                        FullBackupJob.schedule(mContext, latency);
4050                    }
4051                });
4052                return false;
4053            }
4054
4055            // Okay, the top thing is runnable now.  Pop it off and get going.
4056            mFullBackupQueue.remove(0);
4057            AtomicBoolean latch = new AtomicBoolean(false);
4058            String[] pkg = new String[] {entry.packageName};
4059            mRunningFullBackupTask = new PerformFullTransportBackupTask(null, pkg, true,
4060                    scheduledJob, latch);
4061            (new Thread(mRunningFullBackupTask)).start();
4062        }
4063
4064        return true;
4065    }
4066
4067    // The job scheduler says our constraints don't hold any more,
4068    // so tear down any ongoing backup task right away.
4069    void endFullBackup() {
4070        synchronized (mQueueLock) {
4071            if (mRunningFullBackupTask != null) {
4072                if (DEBUG_SCHEDULING) {
4073                    Slog.i(TAG, "Telling running backup to stop");
4074                }
4075                mRunningFullBackupTask.setRunning(false);
4076            }
4077        }
4078    }
4079
4080    // ----- Restore infrastructure -----
4081
4082    abstract class RestoreEngine {
4083        static final String TAG = "RestoreEngine";
4084
4085        public static final int SUCCESS = 0;
4086        public static final int TARGET_FAILURE = -2;
4087        public static final int TRANSPORT_FAILURE = -3;
4088
4089        private AtomicBoolean mRunning = new AtomicBoolean(false);
4090        private AtomicInteger mResult = new AtomicInteger(SUCCESS);
4091
4092        public boolean isRunning() {
4093            return mRunning.get();
4094        }
4095
4096        public void setRunning(boolean stillRunning) {
4097            synchronized (mRunning) {
4098                mRunning.set(stillRunning);
4099                mRunning.notifyAll();
4100            }
4101        }
4102
4103        public int waitForResult() {
4104            synchronized (mRunning) {
4105                while (isRunning()) {
4106                    try {
4107                        mRunning.wait();
4108                    } catch (InterruptedException e) {}
4109                }
4110            }
4111            return getResult();
4112        }
4113
4114        public int getResult() {
4115            return mResult.get();
4116        }
4117
4118        public void setResult(int result) {
4119            mResult.set(result);
4120        }
4121
4122        // TODO: abstract restore state and APIs
4123    }
4124
4125    // ----- Full restore from a file/socket -----
4126
4127    // Description of a file in the restore datastream
4128    static class FileMetadata {
4129        String packageName;             // name of the owning app
4130        String installerPackageName;    // name of the market-type app that installed the owner
4131        int type;                       // e.g. BackupAgent.TYPE_DIRECTORY
4132        String domain;                  // e.g. FullBackup.DATABASE_TREE_TOKEN
4133        String path;                    // subpath within the semantic domain
4134        long mode;                      // e.g. 0666 (actually int)
4135        long mtime;                     // last mod time, UTC time_t (actually int)
4136        long size;                      // bytes of content
4137
4138        @Override
4139        public String toString() {
4140            StringBuilder sb = new StringBuilder(128);
4141            sb.append("FileMetadata{");
4142            sb.append(packageName); sb.append(',');
4143            sb.append(type); sb.append(',');
4144            sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
4145            sb.append(size);
4146            sb.append('}');
4147            return sb.toString();
4148        }
4149    }
4150
4151    enum RestorePolicy {
4152        IGNORE,
4153        ACCEPT,
4154        ACCEPT_IF_APK
4155    }
4156
4157    // Full restore engine, used by both adb restore and transport-based full restore
4158    class FullRestoreEngine extends RestoreEngine {
4159        // Dedicated observer, if any
4160        IFullBackupRestoreObserver mObserver;
4161
4162        // Where we're delivering the file data as we go
4163        IBackupAgent mAgent;
4164
4165        // Are we permitted to only deliver a specific package's metadata?
4166        PackageInfo mOnlyPackage;
4167
4168        boolean mAllowApks;
4169        boolean mAllowObbs;
4170
4171        // Which package are we currently handling data for?
4172        String mAgentPackage;
4173
4174        // Info for working with the target app process
4175        ApplicationInfo mTargetApp;
4176
4177        // Machinery for restoring OBBs
4178        FullBackupObbConnection mObbConnection = null;
4179
4180        // possible handling states for a given package in the restore dataset
4181        final HashMap<String, RestorePolicy> mPackagePolicies
4182                = new HashMap<String, RestorePolicy>();
4183
4184        // installer package names for each encountered app, derived from the manifests
4185        final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
4186
4187        // Signatures for a given package found in its manifest file
4188        final HashMap<String, Signature[]> mManifestSignatures
4189                = new HashMap<String, Signature[]>();
4190
4191        // Packages we've already wiped data on when restoring their first file
4192        final HashSet<String> mClearedPackages = new HashSet<String>();
4193
4194        // How much data have we moved?
4195        long mBytes;
4196
4197        // Working buffer
4198        byte[] mBuffer;
4199
4200        // Pipes for moving data
4201        ParcelFileDescriptor[] mPipes = null;
4202
4203        // Widget blob to be restored out-of-band
4204        byte[] mWidgetData = null;
4205
4206        // Runner that can be placed in a separate thread to do in-process
4207        // invocations of the full restore API asynchronously
4208        class RestoreFileRunnable implements Runnable {
4209            IBackupAgent mAgent;
4210            FileMetadata mInfo;
4211            ParcelFileDescriptor mSocket;
4212            int mToken;
4213
4214            RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
4215                    ParcelFileDescriptor socket, int token) throws IOException {
4216                mAgent = agent;
4217                mInfo = info;
4218                mToken = token;
4219
4220                // This class is used strictly for process-local binder invocations.  The
4221                // semantics of ParcelFileDescriptor differ in this case; in particular, we
4222                // do not automatically get a 'dup'ed descriptor that we can can continue
4223                // to use asynchronously from the caller.  So, we make sure to dup it ourselves
4224                // before proceeding to do the restore.
4225                mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
4226            }
4227
4228            @Override
4229            public void run() {
4230                try {
4231                    mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
4232                            mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
4233                            mToken, mBackupManagerBinder);
4234                } catch (RemoteException e) {
4235                    // never happens; this is used strictly for local binder calls
4236                }
4237            }
4238        }
4239
4240        public FullRestoreEngine(IFullBackupRestoreObserver observer, PackageInfo onlyPackage,
4241                boolean allowApks, boolean allowObbs) {
4242            mObserver = observer;
4243            mOnlyPackage = onlyPackage;
4244            mAllowApks = allowApks;
4245            mAllowObbs = allowObbs;
4246            mBuffer = new byte[32 * 1024];
4247            mBytes = 0;
4248        }
4249
4250        public boolean restoreOneFile(InputStream instream) {
4251            if (!isRunning()) {
4252                Slog.w(TAG, "Restore engine used after halting");
4253                return false;
4254            }
4255
4256            FileMetadata info;
4257            try {
4258                if (MORE_DEBUG) {
4259                    Slog.v(TAG, "Reading tar header for restoring file");
4260                }
4261                info = readTarHeaders(instream);
4262                if (info != null) {
4263                    if (MORE_DEBUG) {
4264                        dumpFileMetadata(info);
4265                    }
4266
4267                    final String pkg = info.packageName;
4268                    if (!pkg.equals(mAgentPackage)) {
4269                        // In the single-package case, it's a semantic error to expect
4270                        // one app's data but see a different app's on the wire
4271                        if (mOnlyPackage != null) {
4272                            if (!pkg.equals(mOnlyPackage.packageName)) {
4273                                Slog.w(TAG, "Expected data for " + mOnlyPackage
4274                                        + " but saw " + pkg);
4275                                setResult(RestoreEngine.TRANSPORT_FAILURE);
4276                                setRunning(false);
4277                                return false;
4278                            }
4279                        }
4280
4281                        // okay, change in package; set up our various
4282                        // bookkeeping if we haven't seen it yet
4283                        if (!mPackagePolicies.containsKey(pkg)) {
4284                            mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
4285                        }
4286
4287                        // Clean up the previous agent relationship if necessary,
4288                        // and let the observer know we're considering a new app.
4289                        if (mAgent != null) {
4290                            if (DEBUG) Slog.d(TAG, "Saw new package; finalizing old one");
4291                            // Now we're really done
4292                            tearDownPipes();
4293                            tearDownAgent(mTargetApp);
4294                            mTargetApp = null;
4295                            mAgentPackage = null;
4296                        }
4297                    }
4298
4299                    if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
4300                        mPackagePolicies.put(pkg, readAppManifest(info, instream));
4301                        mPackageInstallers.put(pkg, info.installerPackageName);
4302                        // We've read only the manifest content itself at this point,
4303                        // so consume the footer before looping around to the next
4304                        // input file
4305                        skipTarPadding(info.size, instream);
4306                        sendOnRestorePackage(pkg);
4307                    } else if (info.path.equals(BACKUP_METADATA_FILENAME)) {
4308                        // Metadata blobs!
4309                        readMetadata(info, instream);
4310                    } else {
4311                        // Non-manifest, so it's actual file data.  Is this a package
4312                        // we're ignoring?
4313                        boolean okay = true;
4314                        RestorePolicy policy = mPackagePolicies.get(pkg);
4315                        switch (policy) {
4316                            case IGNORE:
4317                                okay = false;
4318                                break;
4319
4320                            case ACCEPT_IF_APK:
4321                                // If we're in accept-if-apk state, then the first file we
4322                                // see MUST be the apk.
4323                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
4324                                    if (DEBUG) Slog.d(TAG, "APK file; installing");
4325                                    // Try to install the app.
4326                                    String installerName = mPackageInstallers.get(pkg);
4327                                    okay = installApk(info, installerName, instream);
4328                                    // good to go; promote to ACCEPT
4329                                    mPackagePolicies.put(pkg, (okay)
4330                                            ? RestorePolicy.ACCEPT
4331                                                    : RestorePolicy.IGNORE);
4332                                    // At this point we've consumed this file entry
4333                                    // ourselves, so just strip the tar footer and
4334                                    // go on to the next file in the input stream
4335                                    skipTarPadding(info.size, instream);
4336                                    return true;
4337                                } else {
4338                                    // File data before (or without) the apk.  We can't
4339                                    // handle it coherently in this case so ignore it.
4340                                    mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
4341                                    okay = false;
4342                                }
4343                                break;
4344
4345                            case ACCEPT:
4346                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
4347                                    if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
4348                                    // we can take the data without the apk, so we
4349                                    // *want* to do so.  skip the apk by declaring this
4350                                    // one file not-okay without changing the restore
4351                                    // policy for the package.
4352                                    okay = false;
4353                                }
4354                                break;
4355
4356                            default:
4357                                // Something has gone dreadfully wrong when determining
4358                                // the restore policy from the manifest.  Ignore the
4359                                // rest of this package's data.
4360                                Slog.e(TAG, "Invalid policy from manifest");
4361                                okay = false;
4362                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
4363                                break;
4364                        }
4365
4366                        // Is it a *file* we need to drop?
4367                        if (!isRestorableFile(info)) {
4368                            okay = false;
4369                        }
4370
4371                        // If the policy is satisfied, go ahead and set up to pipe the
4372                        // data to the agent.
4373                        if (DEBUG && okay && mAgent != null) {
4374                            Slog.i(TAG, "Reusing existing agent instance");
4375                        }
4376                        if (okay && mAgent == null) {
4377                            if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
4378
4379                            try {
4380                                mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
4381
4382                                // If we haven't sent any data to this app yet, we probably
4383                                // need to clear it first.  Check that.
4384                                if (!mClearedPackages.contains(pkg)) {
4385                                    // apps with their own backup agents are
4386                                    // responsible for coherently managing a full
4387                                    // restore.
4388                                    if (mTargetApp.backupAgentName == null) {
4389                                        if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
4390                                        clearApplicationDataSynchronous(pkg);
4391                                    } else {
4392                                        if (DEBUG) Slog.d(TAG, "backup agent ("
4393                                                + mTargetApp.backupAgentName + ") => no clear");
4394                                    }
4395                                    mClearedPackages.add(pkg);
4396                                } else {
4397                                    if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
4398                                }
4399
4400                                // All set; now set up the IPC and launch the agent
4401                                setUpPipes();
4402                                mAgent = bindToAgentSynchronous(mTargetApp,
4403                                        IApplicationThread.BACKUP_MODE_RESTORE_FULL);
4404                                mAgentPackage = pkg;
4405                            } catch (IOException e) {
4406                                // fall through to error handling
4407                            } catch (NameNotFoundException e) {
4408                                // fall through to error handling
4409                            }
4410
4411                            if (mAgent == null) {
4412                                if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
4413                                okay = false;
4414                                tearDownPipes();
4415                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
4416                            }
4417                        }
4418
4419                        // Sanity check: make sure we never give data to the wrong app.  This
4420                        // should never happen but a little paranoia here won't go amiss.
4421                        if (okay && !pkg.equals(mAgentPackage)) {
4422                            Slog.e(TAG, "Restoring data for " + pkg
4423                                    + " but agent is for " + mAgentPackage);
4424                            okay = false;
4425                        }
4426
4427                        // At this point we have an agent ready to handle the full
4428                        // restore data as well as a pipe for sending data to
4429                        // that agent.  Tell the agent to start reading from the
4430                        // pipe.
4431                        if (okay) {
4432                            boolean agentSuccess = true;
4433                            long toCopy = info.size;
4434                            final int token = generateToken();
4435                            try {
4436                                prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
4437                                if (info.domain.equals(FullBackup.OBB_TREE_TOKEN)) {
4438                                    if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
4439                                            + " : " + info.path);
4440                                    mObbConnection.restoreObbFile(pkg, mPipes[0],
4441                                            info.size, info.type, info.path, info.mode,
4442                                            info.mtime, token, mBackupManagerBinder);
4443                                } else {
4444                                    if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
4445                                            + info.path);
4446                                    // fire up the app's agent listening on the socket.  If
4447                                    // the agent is running in the system process we can't
4448                                    // just invoke it asynchronously, so we provide a thread
4449                                    // for it here.
4450                                    if (mTargetApp.processName.equals("system")) {
4451                                        Slog.d(TAG, "system process agent - spinning a thread");
4452                                        RestoreFileRunnable runner = new RestoreFileRunnable(
4453                                                mAgent, info, mPipes[0], token);
4454                                        new Thread(runner, "restore-sys-runner").start();
4455                                    } else {
4456                                        mAgent.doRestoreFile(mPipes[0], info.size, info.type,
4457                                                info.domain, info.path, info.mode, info.mtime,
4458                                                token, mBackupManagerBinder);
4459                                    }
4460                                }
4461                            } catch (IOException e) {
4462                                // couldn't dup the socket for a process-local restore
4463                                Slog.d(TAG, "Couldn't establish restore");
4464                                agentSuccess = false;
4465                                okay = false;
4466                            } catch (RemoteException e) {
4467                                // whoops, remote entity went away.  We'll eat the content
4468                                // ourselves, then, and not copy it over.
4469                                Slog.e(TAG, "Agent crashed during full restore");
4470                                agentSuccess = false;
4471                                okay = false;
4472                            }
4473
4474                            // Copy over the data if the agent is still good
4475                            if (okay) {
4476                                if (MORE_DEBUG) {
4477                                    Slog.v(TAG, "  copying to restore agent: "
4478                                            + toCopy + " bytes");
4479                                }
4480                                boolean pipeOkay = true;
4481                                FileOutputStream pipe = new FileOutputStream(
4482                                        mPipes[1].getFileDescriptor());
4483                                while (toCopy > 0) {
4484                                    int toRead = (toCopy > mBuffer.length)
4485                                            ? mBuffer.length : (int)toCopy;
4486                                    int nRead = instream.read(mBuffer, 0, toRead);
4487                                    if (nRead >= 0) mBytes += nRead;
4488                                    if (nRead <= 0) break;
4489                                    toCopy -= nRead;
4490
4491                                    // send it to the output pipe as long as things
4492                                    // are still good
4493                                    if (pipeOkay) {
4494                                        try {
4495                                            pipe.write(mBuffer, 0, nRead);
4496                                        } catch (IOException e) {
4497                                            Slog.e(TAG, "Failed to write to restore pipe", e);
4498                                            pipeOkay = false;
4499                                        }
4500                                    }
4501                                }
4502
4503                                // done sending that file!  Now we just need to consume
4504                                // the delta from info.size to the end of block.
4505                                skipTarPadding(info.size, instream);
4506
4507                                // and now that we've sent it all, wait for the remote
4508                                // side to acknowledge receipt
4509                                agentSuccess = waitUntilOperationComplete(token);
4510                            }
4511
4512                            // okay, if the remote end failed at any point, deal with
4513                            // it by ignoring the rest of the restore on it
4514                            if (!agentSuccess) {
4515                                if (DEBUG) {
4516                                    Slog.i(TAG, "Agent failure; ending restore");
4517                                }
4518                                mBackupHandler.removeMessages(MSG_TIMEOUT);
4519                                tearDownPipes();
4520                                tearDownAgent(mTargetApp);
4521                                mAgent = null;
4522                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
4523
4524                                // If this was a single-package restore, we halt immediately
4525                                // with an agent error under these circumstances
4526                                if (mOnlyPackage != null) {
4527                                    setResult(RestoreEngine.TARGET_FAILURE);
4528                                    setRunning(false);
4529                                    return false;
4530                                }
4531                            }
4532                        }
4533
4534                        // Problems setting up the agent communication, an explicitly
4535                        // dropped file, or an already-ignored package: skip to the
4536                        // next stream entry by reading and discarding this file.
4537                        if (!okay) {
4538                            if (DEBUG) Slog.d(TAG, "[discarding file content]");
4539                            long bytesToConsume = (info.size + 511) & ~511;
4540                            while (bytesToConsume > 0) {
4541                                int toRead = (bytesToConsume > mBuffer.length)
4542                                        ? mBuffer.length : (int)bytesToConsume;
4543                                long nRead = instream.read(mBuffer, 0, toRead);
4544                                if (nRead >= 0) mBytes += nRead;
4545                                if (nRead <= 0) break;
4546                                bytesToConsume -= nRead;
4547                            }
4548                        }
4549                    }
4550                }
4551            } catch (IOException e) {
4552                if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
4553                setResult(RestoreEngine.TRANSPORT_FAILURE);
4554                info = null;
4555            }
4556
4557            // If we got here we're either running smoothly or we've finished
4558            if (info == null) {
4559                if (MORE_DEBUG) {
4560                    Slog.i(TAG, "No [more] data for this package; tearing down");
4561                }
4562                tearDownPipes();
4563                tearDownAgent(mTargetApp);
4564                setRunning(false);
4565            }
4566            return (info != null);
4567        }
4568
4569        void setUpPipes() throws IOException {
4570            mPipes = ParcelFileDescriptor.createPipe();
4571        }
4572
4573        void tearDownPipes() {
4574            if (mPipes != null) {
4575                try {
4576                    mPipes[0].close();
4577                    mPipes[0] = null;
4578                    mPipes[1].close();
4579                    mPipes[1] = null;
4580                } catch (IOException e) {
4581                    Slog.w(TAG, "Couldn't close agent pipes", e);
4582                }
4583                mPipes = null;
4584            }
4585        }
4586
4587        void tearDownAgent(ApplicationInfo app) {
4588            if (mAgent != null) {
4589                try {
4590                    // unbind and tidy up even on timeout or failure, just in case
4591                    mActivityManager.unbindBackupAgent(app);
4592
4593                    // The agent was running with a stub Application object, so shut it down.
4594                    // !!! We hardcode the confirmation UI's package name here rather than use a
4595                    //     manifest flag!  TODO something less direct.
4596                    if (app.uid != Process.SYSTEM_UID
4597                            && !app.packageName.equals("com.android.backupconfirm")) {
4598                        if (DEBUG) Slog.d(TAG, "Killing host process");
4599                        mActivityManager.killApplicationProcess(app.processName, app.uid);
4600                    } else {
4601                        if (DEBUG) Slog.d(TAG, "Not killing after full restore");
4602                    }
4603                } catch (RemoteException e) {
4604                    Slog.d(TAG, "Lost app trying to shut down");
4605                }
4606                mAgent = null;
4607            }
4608        }
4609
4610        class RestoreInstallObserver extends IPackageInstallObserver.Stub {
4611            final AtomicBoolean mDone = new AtomicBoolean();
4612            String mPackageName;
4613            int mResult;
4614
4615            public void reset() {
4616                synchronized (mDone) {
4617                    mDone.set(false);
4618                }
4619            }
4620
4621            public void waitForCompletion() {
4622                synchronized (mDone) {
4623                    while (mDone.get() == false) {
4624                        try {
4625                            mDone.wait();
4626                        } catch (InterruptedException e) { }
4627                    }
4628                }
4629            }
4630
4631            int getResult() {
4632                return mResult;
4633            }
4634
4635            @Override
4636            public void packageInstalled(String packageName, int returnCode)
4637                    throws RemoteException {
4638                synchronized (mDone) {
4639                    mResult = returnCode;
4640                    mPackageName = packageName;
4641                    mDone.set(true);
4642                    mDone.notifyAll();
4643                }
4644            }
4645        }
4646
4647        class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
4648            final AtomicBoolean mDone = new AtomicBoolean();
4649            int mResult;
4650
4651            public void reset() {
4652                synchronized (mDone) {
4653                    mDone.set(false);
4654                }
4655            }
4656
4657            public void waitForCompletion() {
4658                synchronized (mDone) {
4659                    while (mDone.get() == false) {
4660                        try {
4661                            mDone.wait();
4662                        } catch (InterruptedException e) { }
4663                    }
4664                }
4665            }
4666
4667            @Override
4668            public void packageDeleted(String packageName, int returnCode) throws RemoteException {
4669                synchronized (mDone) {
4670                    mResult = returnCode;
4671                    mDone.set(true);
4672                    mDone.notifyAll();
4673                }
4674            }
4675        }
4676
4677        final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
4678        final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
4679
4680        boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
4681            boolean okay = true;
4682
4683            if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
4684
4685            // The file content is an .apk file.  Copy it out to a staging location and
4686            // attempt to install it.
4687            File apkFile = new File(mDataDir, info.packageName);
4688            try {
4689                FileOutputStream apkStream = new FileOutputStream(apkFile);
4690                byte[] buffer = new byte[32 * 1024];
4691                long size = info.size;
4692                while (size > 0) {
4693                    long toRead = (buffer.length < size) ? buffer.length : size;
4694                    int didRead = instream.read(buffer, 0, (int)toRead);
4695                    if (didRead >= 0) mBytes += didRead;
4696                    apkStream.write(buffer, 0, didRead);
4697                    size -= didRead;
4698                }
4699                apkStream.close();
4700
4701                // make sure the installer can read it
4702                apkFile.setReadable(true, false);
4703
4704                // Now install it
4705                Uri packageUri = Uri.fromFile(apkFile);
4706                mInstallObserver.reset();
4707                mPackageManager.installPackage(packageUri, mInstallObserver,
4708                        PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
4709                        installerPackage);
4710                mInstallObserver.waitForCompletion();
4711
4712                if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
4713                    // The only time we continue to accept install of data even if the
4714                    // apk install failed is if we had already determined that we could
4715                    // accept the data regardless.
4716                    if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
4717                        okay = false;
4718                    }
4719                } else {
4720                    // Okay, the install succeeded.  Make sure it was the right app.
4721                    boolean uninstall = false;
4722                    if (!mInstallObserver.mPackageName.equals(info.packageName)) {
4723                        Slog.w(TAG, "Restore stream claimed to include apk for "
4724                                + info.packageName + " but apk was really "
4725                                + mInstallObserver.mPackageName);
4726                        // delete the package we just put in place; it might be fraudulent
4727                        okay = false;
4728                        uninstall = true;
4729                    } else {
4730                        try {
4731                            PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
4732                                    PackageManager.GET_SIGNATURES);
4733                            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
4734                                Slog.w(TAG, "Restore stream contains apk of package "
4735                                        + info.packageName + " but it disallows backup/restore");
4736                                okay = false;
4737                            } else {
4738                                // So far so good -- do the signatures match the manifest?
4739                                Signature[] sigs = mManifestSignatures.get(info.packageName);
4740                                if (signaturesMatch(sigs, pkg)) {
4741                                    // If this is a system-uid app without a declared backup agent,
4742                                    // don't restore any of the file data.
4743                                    if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
4744                                            && (pkg.applicationInfo.backupAgentName == null)) {
4745                                        Slog.w(TAG, "Installed app " + info.packageName
4746                                                + " has restricted uid and no agent");
4747                                        okay = false;
4748                                    }
4749                                } else {
4750                                    Slog.w(TAG, "Installed app " + info.packageName
4751                                            + " signatures do not match restore manifest");
4752                                    okay = false;
4753                                    uninstall = true;
4754                                }
4755                            }
4756                        } catch (NameNotFoundException e) {
4757                            Slog.w(TAG, "Install of package " + info.packageName
4758                                    + " succeeded but now not found");
4759                            okay = false;
4760                        }
4761                    }
4762
4763                    // If we're not okay at this point, we need to delete the package
4764                    // that we just installed.
4765                    if (uninstall) {
4766                        mDeleteObserver.reset();
4767                        mPackageManager.deletePackage(mInstallObserver.mPackageName,
4768                                mDeleteObserver, 0);
4769                        mDeleteObserver.waitForCompletion();
4770                    }
4771                }
4772            } catch (IOException e) {
4773                Slog.e(TAG, "Unable to transcribe restored apk for install");
4774                okay = false;
4775            } finally {
4776                apkFile.delete();
4777            }
4778
4779            return okay;
4780        }
4781
4782        // Given an actual file content size, consume the post-content padding mandated
4783        // by the tar format.
4784        void skipTarPadding(long size, InputStream instream) throws IOException {
4785            long partial = (size + 512) % 512;
4786            if (partial > 0) {
4787                final int needed = 512 - (int)partial;
4788                if (MORE_DEBUG) {
4789                    Slog.i(TAG, "Skipping tar padding: " + needed + " bytes");
4790                }
4791                byte[] buffer = new byte[needed];
4792                if (readExactly(instream, buffer, 0, needed) == needed) {
4793                    mBytes += needed;
4794                } else throw new IOException("Unexpected EOF in padding");
4795            }
4796        }
4797
4798        // Read a widget metadata file, returning the restored blob
4799        void readMetadata(FileMetadata info, InputStream instream) throws IOException {
4800            // Fail on suspiciously large widget dump files
4801            if (info.size > 64 * 1024) {
4802                throw new IOException("Metadata too big; corrupt? size=" + info.size);
4803            }
4804
4805            byte[] buffer = new byte[(int) info.size];
4806            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
4807                mBytes += info.size;
4808            } else throw new IOException("Unexpected EOF in widget data");
4809
4810            String[] str = new String[1];
4811            int offset = extractLine(buffer, 0, str);
4812            int version = Integer.parseInt(str[0]);
4813            if (version == BACKUP_MANIFEST_VERSION) {
4814                offset = extractLine(buffer, offset, str);
4815                final String pkg = str[0];
4816                if (info.packageName.equals(pkg)) {
4817                    // Data checks out -- the rest of the buffer is a concatenation of
4818                    // binary blobs as described in the comment at writeAppWidgetData()
4819                    ByteArrayInputStream bin = new ByteArrayInputStream(buffer,
4820                            offset, buffer.length - offset);
4821                    DataInputStream in = new DataInputStream(bin);
4822                    while (bin.available() > 0) {
4823                        int token = in.readInt();
4824                        int size = in.readInt();
4825                        if (size > 64 * 1024) {
4826                            throw new IOException("Datum "
4827                                    + Integer.toHexString(token)
4828                                    + " too big; corrupt? size=" + info.size);
4829                        }
4830                        switch (token) {
4831                            case BACKUP_WIDGET_METADATA_TOKEN:
4832                            {
4833                                if (MORE_DEBUG) {
4834                                    Slog.i(TAG, "Got widget metadata for " + info.packageName);
4835                                }
4836                                mWidgetData = new byte[size];
4837                                in.read(mWidgetData);
4838                                break;
4839                            }
4840                            default:
4841                            {
4842                                if (DEBUG) {
4843                                    Slog.i(TAG, "Ignoring metadata blob "
4844                                            + Integer.toHexString(token)
4845                                            + " for " + info.packageName);
4846                                }
4847                                in.skipBytes(size);
4848                                break;
4849                            }
4850                        }
4851                    }
4852                } else {
4853                    Slog.w(TAG, "Metadata mismatch: package " + info.packageName
4854                            + " but widget data for " + pkg);
4855                }
4856            } else {
4857                Slog.w(TAG, "Unsupported metadata version " + version);
4858            }
4859        }
4860
4861        // Returns a policy constant
4862        RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
4863                throws IOException {
4864            // Fail on suspiciously large manifest files
4865            if (info.size > 64 * 1024) {
4866                throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
4867            }
4868
4869            byte[] buffer = new byte[(int) info.size];
4870            if (MORE_DEBUG) {
4871                Slog.i(TAG, "   readAppManifest() looking for " + info.size + " bytes, "
4872                        + mBytes + " already consumed");
4873            }
4874            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
4875                mBytes += info.size;
4876            } else throw new IOException("Unexpected EOF in manifest");
4877
4878            RestorePolicy policy = RestorePolicy.IGNORE;
4879            String[] str = new String[1];
4880            int offset = 0;
4881
4882            try {
4883                offset = extractLine(buffer, offset, str);
4884                int version = Integer.parseInt(str[0]);
4885                if (version == BACKUP_MANIFEST_VERSION) {
4886                    offset = extractLine(buffer, offset, str);
4887                    String manifestPackage = str[0];
4888                    // TODO: handle <original-package>
4889                    if (manifestPackage.equals(info.packageName)) {
4890                        offset = extractLine(buffer, offset, str);
4891                        version = Integer.parseInt(str[0]);  // app version
4892                        offset = extractLine(buffer, offset, str);
4893                        int platformVersion = Integer.parseInt(str[0]);
4894                        offset = extractLine(buffer, offset, str);
4895                        info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
4896                        offset = extractLine(buffer, offset, str);
4897                        boolean hasApk = str[0].equals("1");
4898                        offset = extractLine(buffer, offset, str);
4899                        int numSigs = Integer.parseInt(str[0]);
4900                        if (numSigs > 0) {
4901                            Signature[] sigs = new Signature[numSigs];
4902                            for (int i = 0; i < numSigs; i++) {
4903                                offset = extractLine(buffer, offset, str);
4904                                sigs[i] = new Signature(str[0]);
4905                            }
4906                            mManifestSignatures.put(info.packageName, sigs);
4907
4908                            // Okay, got the manifest info we need...
4909                            try {
4910                                PackageInfo pkgInfo = mPackageManager.getPackageInfo(
4911                                        info.packageName, PackageManager.GET_SIGNATURES);
4912                                // Fall through to IGNORE if the app explicitly disallows backup
4913                                final int flags = pkgInfo.applicationInfo.flags;
4914                                if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
4915                                    // Restore system-uid-space packages only if they have
4916                                    // defined a custom backup agent
4917                                    if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
4918                                            || (pkgInfo.applicationInfo.backupAgentName != null)) {
4919                                        // Verify signatures against any installed version; if they
4920                                        // don't match, then we fall though and ignore the data.  The
4921                                        // signatureMatch() method explicitly ignores the signature
4922                                        // check for packages installed on the system partition, because
4923                                        // such packages are signed with the platform cert instead of
4924                                        // the app developer's cert, so they're different on every
4925                                        // device.
4926                                        if (signaturesMatch(sigs, pkgInfo)) {
4927                                            if (pkgInfo.versionCode >= version) {
4928                                                Slog.i(TAG, "Sig + version match; taking data");
4929                                                policy = RestorePolicy.ACCEPT;
4930                                            } else {
4931                                                // The data is from a newer version of the app than
4932                                                // is presently installed.  That means we can only
4933                                                // use it if the matching apk is also supplied.
4934                                                if (mAllowApks) {
4935                                                    Slog.i(TAG, "Data version " + version
4936                                                            + " is newer than installed version "
4937                                                            + pkgInfo.versionCode
4938                                                            + " - requiring apk");
4939                                                    policy = RestorePolicy.ACCEPT_IF_APK;
4940                                                } else {
4941                                                    Slog.i(TAG, "Data requires newer version "
4942                                                            + version + "; ignoring");
4943                                                    policy = RestorePolicy.IGNORE;
4944                                                }
4945                                            }
4946                                        } else {
4947                                            Slog.w(TAG, "Restore manifest signatures do not match "
4948                                                    + "installed application for " + info.packageName);
4949                                        }
4950                                    } else {
4951                                        Slog.w(TAG, "Package " + info.packageName
4952                                                + " is system level with no agent");
4953                                    }
4954                                } else {
4955                                    if (DEBUG) Slog.i(TAG, "Restore manifest from "
4956                                            + info.packageName + " but allowBackup=false");
4957                                }
4958                            } catch (NameNotFoundException e) {
4959                                // Okay, the target app isn't installed.  We can process
4960                                // the restore properly only if the dataset provides the
4961                                // apk file and we can successfully install it.
4962                                if (mAllowApks) {
4963                                    if (DEBUG) Slog.i(TAG, "Package " + info.packageName
4964                                            + " not installed; requiring apk in dataset");
4965                                    policy = RestorePolicy.ACCEPT_IF_APK;
4966                                } else {
4967                                    policy = RestorePolicy.IGNORE;
4968                                }
4969                            }
4970
4971                            if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
4972                                Slog.i(TAG, "Cannot restore package " + info.packageName
4973                                        + " without the matching .apk");
4974                            }
4975                        } else {
4976                            Slog.i(TAG, "Missing signature on backed-up package "
4977                                    + info.packageName);
4978                        }
4979                    } else {
4980                        Slog.i(TAG, "Expected package " + info.packageName
4981                                + " but restore manifest claims " + manifestPackage);
4982                    }
4983                } else {
4984                    Slog.i(TAG, "Unknown restore manifest version " + version
4985                            + " for package " + info.packageName);
4986                }
4987            } catch (NumberFormatException e) {
4988                Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
4989            } catch (IllegalArgumentException e) {
4990                Slog.w(TAG, e.getMessage());
4991            }
4992
4993            return policy;
4994        }
4995
4996        // Builds a line from a byte buffer starting at 'offset', and returns
4997        // the index of the next unconsumed data in the buffer.
4998        int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
4999            final int end = buffer.length;
5000            if (offset >= end) throw new IOException("Incomplete data");
5001
5002            int pos;
5003            for (pos = offset; pos < end; pos++) {
5004                byte c = buffer[pos];
5005                // at LF we declare end of line, and return the next char as the
5006                // starting point for the next time through
5007                if (c == '\n') {
5008                    break;
5009                }
5010            }
5011            outStr[0] = new String(buffer, offset, pos - offset);
5012            pos++;  // may be pointing an extra byte past the end but that's okay
5013            return pos;
5014        }
5015
5016        void dumpFileMetadata(FileMetadata info) {
5017            if (DEBUG) {
5018                StringBuilder b = new StringBuilder(128);
5019
5020                // mode string
5021                b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
5022                b.append(((info.mode & 0400) != 0) ? 'r' : '-');
5023                b.append(((info.mode & 0200) != 0) ? 'w' : '-');
5024                b.append(((info.mode & 0100) != 0) ? 'x' : '-');
5025                b.append(((info.mode & 0040) != 0) ? 'r' : '-');
5026                b.append(((info.mode & 0020) != 0) ? 'w' : '-');
5027                b.append(((info.mode & 0010) != 0) ? 'x' : '-');
5028                b.append(((info.mode & 0004) != 0) ? 'r' : '-');
5029                b.append(((info.mode & 0002) != 0) ? 'w' : '-');
5030                b.append(((info.mode & 0001) != 0) ? 'x' : '-');
5031                b.append(String.format(" %9d ", info.size));
5032
5033                Date stamp = new Date(info.mtime);
5034                b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp));
5035
5036                b.append(info.packageName);
5037                b.append(" :: ");
5038                b.append(info.domain);
5039                b.append(" :: ");
5040                b.append(info.path);
5041
5042                Slog.i(TAG, b.toString());
5043            }
5044        }
5045
5046        // Consume a tar file header block [sequence] and accumulate the relevant metadata
5047        FileMetadata readTarHeaders(InputStream instream) throws IOException {
5048            byte[] block = new byte[512];
5049            FileMetadata info = null;
5050
5051            boolean gotHeader = readTarHeader(instream, block);
5052            if (gotHeader) {
5053                try {
5054                    // okay, presume we're okay, and extract the various metadata
5055                    info = new FileMetadata();
5056                    info.size = extractRadix(block, 124, 12, 8);
5057                    info.mtime = extractRadix(block, 136, 12, 8);
5058                    info.mode = extractRadix(block, 100, 8, 8);
5059
5060                    info.path = extractString(block, 345, 155); // prefix
5061                    String path = extractString(block, 0, 100);
5062                    if (path.length() > 0) {
5063                        if (info.path.length() > 0) info.path += '/';
5064                        info.path += path;
5065                    }
5066
5067                    // tar link indicator field: 1 byte at offset 156 in the header.
5068                    int typeChar = block[156];
5069                    if (typeChar == 'x') {
5070                        // pax extended header, so we need to read that
5071                        gotHeader = readPaxExtendedHeader(instream, info);
5072                        if (gotHeader) {
5073                            // and after a pax extended header comes another real header -- read
5074                            // that to find the real file type
5075                            gotHeader = readTarHeader(instream, block);
5076                        }
5077                        if (!gotHeader) throw new IOException("Bad or missing pax header");
5078
5079                        typeChar = block[156];
5080                    }
5081
5082                    switch (typeChar) {
5083                        case '0': info.type = BackupAgent.TYPE_FILE; break;
5084                        case '5': {
5085                            info.type = BackupAgent.TYPE_DIRECTORY;
5086                            if (info.size != 0) {
5087                                Slog.w(TAG, "Directory entry with nonzero size in header");
5088                                info.size = 0;
5089                            }
5090                            break;
5091                        }
5092                        case 0: {
5093                            // presume EOF
5094                            if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
5095                            return null;
5096                        }
5097                        default: {
5098                            Slog.e(TAG, "Unknown tar entity type: " + typeChar);
5099                            throw new IOException("Unknown entity type " + typeChar);
5100                        }
5101                    }
5102
5103                    // Parse out the path
5104                    //
5105                    // first: apps/shared/unrecognized
5106                    if (FullBackup.SHARED_PREFIX.regionMatches(0,
5107                            info.path, 0, FullBackup.SHARED_PREFIX.length())) {
5108                        // File in shared storage.  !!! TODO: implement this.
5109                        info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
5110                        info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
5111                        info.domain = FullBackup.SHARED_STORAGE_TOKEN;
5112                        if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
5113                    } else if (FullBackup.APPS_PREFIX.regionMatches(0,
5114                            info.path, 0, FullBackup.APPS_PREFIX.length())) {
5115                        // App content!  Parse out the package name and domain
5116
5117                        // strip the apps/ prefix
5118                        info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
5119
5120                        // extract the package name
5121                        int slash = info.path.indexOf('/');
5122                        if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
5123                        info.packageName = info.path.substring(0, slash);
5124                        info.path = info.path.substring(slash+1);
5125
5126                        // if it's a manifest we're done, otherwise parse out the domains
5127                        if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
5128                            slash = info.path.indexOf('/');
5129                            if (slash < 0) {
5130                                throw new IOException("Illegal semantic path in non-manifest "
5131                                        + info.path);
5132                            }
5133                            info.domain = info.path.substring(0, slash);
5134                            info.path = info.path.substring(slash + 1);
5135                        }
5136                    }
5137                } catch (IOException e) {
5138                    if (DEBUG) {
5139                        Slog.e(TAG, "Parse error in header: " + e.getMessage());
5140                        HEXLOG(block);
5141                    }
5142                    throw e;
5143                }
5144            }
5145            return info;
5146        }
5147
5148        private boolean isRestorableFile(FileMetadata info) {
5149            if (FullBackup.CACHE_TREE_TOKEN.equals(info.domain)) {
5150                if (MORE_DEBUG) {
5151                    Slog.i(TAG, "Dropping cache file path " + info.path);
5152                }
5153                return false;
5154            }
5155
5156            if (FullBackup.ROOT_TREE_TOKEN.equals(info.domain)) {
5157                // It's possible this is "no-backup" dir contents in an archive stream
5158                // produced on a device running a version of the OS that predates that
5159                // API.  Respect the no-backup intention and don't let the data get to
5160                // the app.
5161                if (info.path.startsWith("no_backup/")) {
5162                    if (MORE_DEBUG) {
5163                        Slog.i(TAG, "Dropping no_backup file path " + info.path);
5164                    }
5165                    return false;
5166                }
5167            }
5168
5169            // The path needs to be canonical
5170            if (info.path.contains("..") || info.path.contains("//")) {
5171                if (MORE_DEBUG) {
5172                    Slog.w(TAG, "Dropping invalid path " + info.path);
5173                }
5174                return false;
5175            }
5176
5177            // Otherwise we think this file is good to go
5178            return true;
5179        }
5180
5181        private void HEXLOG(byte[] block) {
5182            int offset = 0;
5183            int todo = block.length;
5184            StringBuilder buf = new StringBuilder(64);
5185            while (todo > 0) {
5186                buf.append(String.format("%04x   ", offset));
5187                int numThisLine = (todo > 16) ? 16 : todo;
5188                for (int i = 0; i < numThisLine; i++) {
5189                    buf.append(String.format("%02x ", block[offset+i]));
5190                }
5191                Slog.i("hexdump", buf.toString());
5192                buf.setLength(0);
5193                todo -= numThisLine;
5194                offset += numThisLine;
5195            }
5196        }
5197
5198        // Read exactly the given number of bytes into a buffer at the stated offset.
5199        // Returns false if EOF is encountered before the requested number of bytes
5200        // could be read.
5201        int readExactly(InputStream in, byte[] buffer, int offset, int size)
5202                throws IOException {
5203            if (size <= 0) throw new IllegalArgumentException("size must be > 0");
5204if (MORE_DEBUG) Slog.i(TAG, "  ... readExactly(" + size + ") called");
5205            int soFar = 0;
5206            while (soFar < size) {
5207                int nRead = in.read(buffer, offset + soFar, size - soFar);
5208                if (nRead <= 0) {
5209                    if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
5210                    break;
5211                }
5212                soFar += nRead;
5213if (MORE_DEBUG) Slog.v(TAG, "   + got " + nRead + "; now wanting " + (size - soFar));
5214            }
5215            return soFar;
5216        }
5217
5218        boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
5219            final int got = readExactly(instream, block, 0, 512);
5220            if (got == 0) return false;     // Clean EOF
5221            if (got < 512) throw new IOException("Unable to read full block header");
5222            mBytes += 512;
5223            return true;
5224        }
5225
5226        // overwrites 'info' fields based on the pax extended header
5227        boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
5228                throws IOException {
5229            // We should never see a pax extended header larger than this
5230            if (info.size > 32*1024) {
5231                Slog.w(TAG, "Suspiciously large pax header size " + info.size
5232                        + " - aborting");
5233                throw new IOException("Sanity failure: pax header size " + info.size);
5234            }
5235
5236            // read whole blocks, not just the content size
5237            int numBlocks = (int)((info.size + 511) >> 9);
5238            byte[] data = new byte[numBlocks * 512];
5239            if (readExactly(instream, data, 0, data.length) < data.length) {
5240                throw new IOException("Unable to read full pax header");
5241            }
5242            mBytes += data.length;
5243
5244            final int contentSize = (int) info.size;
5245            int offset = 0;
5246            do {
5247                // extract the line at 'offset'
5248                int eol = offset+1;
5249                while (eol < contentSize && data[eol] != ' ') eol++;
5250                if (eol >= contentSize) {
5251                    // error: we just hit EOD looking for the end of the size field
5252                    throw new IOException("Invalid pax data");
5253                }
5254                // eol points to the space between the count and the key
5255                int linelen = (int) extractRadix(data, offset, eol - offset, 10);
5256                int key = eol + 1;  // start of key=value
5257                eol = offset + linelen - 1; // trailing LF
5258                int value;
5259                for (value = key+1; data[value] != '=' && value <= eol; value++);
5260                if (value > eol) {
5261                    throw new IOException("Invalid pax declaration");
5262                }
5263
5264                // pax requires that key/value strings be in UTF-8
5265                String keyStr = new String(data, key, value-key, "UTF-8");
5266                // -1 to strip the trailing LF
5267                String valStr = new String(data, value+1, eol-value-1, "UTF-8");
5268
5269                if ("path".equals(keyStr)) {
5270                    info.path = valStr;
5271                } else if ("size".equals(keyStr)) {
5272                    info.size = Long.parseLong(valStr);
5273                } else {
5274                    if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
5275                }
5276
5277                offset += linelen;
5278            } while (offset < contentSize);
5279
5280            return true;
5281        }
5282
5283        long extractRadix(byte[] data, int offset, int maxChars, int radix)
5284                throws IOException {
5285            long value = 0;
5286            final int end = offset + maxChars;
5287            for (int i = offset; i < end; i++) {
5288                final byte b = data[i];
5289                // Numeric fields in tar can terminate with either NUL or SPC
5290                if (b == 0 || b == ' ') break;
5291                if (b < '0' || b > ('0' + radix - 1)) {
5292                    throw new IOException("Invalid number in header: '" + (char)b
5293                            + "' for radix " + radix);
5294                }
5295                value = radix * value + (b - '0');
5296            }
5297            return value;
5298        }
5299
5300        String extractString(byte[] data, int offset, int maxChars) throws IOException {
5301            final int end = offset + maxChars;
5302            int eos = offset;
5303            // tar string fields terminate early with a NUL
5304            while (eos < end && data[eos] != 0) eos++;
5305            return new String(data, offset, eos-offset, "US-ASCII");
5306        }
5307
5308        void sendStartRestore() {
5309            if (mObserver != null) {
5310                try {
5311                    mObserver.onStartRestore();
5312                } catch (RemoteException e) {
5313                    Slog.w(TAG, "full restore observer went away: startRestore");
5314                    mObserver = null;
5315                }
5316            }
5317        }
5318
5319        void sendOnRestorePackage(String name) {
5320            if (mObserver != null) {
5321                try {
5322                    // TODO: use a more user-friendly name string
5323                    mObserver.onRestorePackage(name);
5324                } catch (RemoteException e) {
5325                    Slog.w(TAG, "full restore observer went away: restorePackage");
5326                    mObserver = null;
5327                }
5328            }
5329        }
5330
5331        void sendEndRestore() {
5332            if (mObserver != null) {
5333                try {
5334                    mObserver.onEndRestore();
5335                } catch (RemoteException e) {
5336                    Slog.w(TAG, "full restore observer went away: endRestore");
5337                    mObserver = null;
5338                }
5339            }
5340        }
5341    }
5342
5343    // ***** end new engine class ***
5344
5345    class PerformAdbRestoreTask implements Runnable {
5346        ParcelFileDescriptor mInputFile;
5347        String mCurrentPassword;
5348        String mDecryptPassword;
5349        IFullBackupRestoreObserver mObserver;
5350        AtomicBoolean mLatchObject;
5351        IBackupAgent mAgent;
5352        String mAgentPackage;
5353        ApplicationInfo mTargetApp;
5354        FullBackupObbConnection mObbConnection = null;
5355        ParcelFileDescriptor[] mPipes = null;
5356        byte[] mWidgetData = null;
5357
5358        long mBytes;
5359
5360        // possible handling states for a given package in the restore dataset
5361        final HashMap<String, RestorePolicy> mPackagePolicies
5362                = new HashMap<String, RestorePolicy>();
5363
5364        // installer package names for each encountered app, derived from the manifests
5365        final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
5366
5367        // Signatures for a given package found in its manifest file
5368        final HashMap<String, Signature[]> mManifestSignatures
5369                = new HashMap<String, Signature[]>();
5370
5371        // Packages we've already wiped data on when restoring their first file
5372        final HashSet<String> mClearedPackages = new HashSet<String>();
5373
5374        PerformAdbRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
5375                IFullBackupRestoreObserver observer, AtomicBoolean latch) {
5376            mInputFile = fd;
5377            mCurrentPassword = curPassword;
5378            mDecryptPassword = decryptPassword;
5379            mObserver = observer;
5380            mLatchObject = latch;
5381            mAgent = null;
5382            mAgentPackage = null;
5383            mTargetApp = null;
5384            mObbConnection = new FullBackupObbConnection();
5385
5386            // Which packages we've already wiped data on.  We prepopulate this
5387            // with a whitelist of packages known to be unclearable.
5388            mClearedPackages.add("android");
5389            mClearedPackages.add(SETTINGS_PACKAGE);
5390        }
5391
5392        class RestoreFileRunnable implements Runnable {
5393            IBackupAgent mAgent;
5394            FileMetadata mInfo;
5395            ParcelFileDescriptor mSocket;
5396            int mToken;
5397
5398            RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
5399                    ParcelFileDescriptor socket, int token) throws IOException {
5400                mAgent = agent;
5401                mInfo = info;
5402                mToken = token;
5403
5404                // This class is used strictly for process-local binder invocations.  The
5405                // semantics of ParcelFileDescriptor differ in this case; in particular, we
5406                // do not automatically get a 'dup'ed descriptor that we can can continue
5407                // to use asynchronously from the caller.  So, we make sure to dup it ourselves
5408                // before proceeding to do the restore.
5409                mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
5410            }
5411
5412            @Override
5413            public void run() {
5414                try {
5415                    mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
5416                            mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
5417                            mToken, mBackupManagerBinder);
5418                } catch (RemoteException e) {
5419                    // never happens; this is used strictly for local binder calls
5420                }
5421            }
5422        }
5423
5424        @Override
5425        public void run() {
5426            Slog.i(TAG, "--- Performing full-dataset restore ---");
5427            mObbConnection.establish();
5428            sendStartRestore();
5429
5430            // Are we able to restore shared-storage data?
5431            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
5432                mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
5433            }
5434
5435            FileInputStream rawInStream = null;
5436            DataInputStream rawDataIn = null;
5437            try {
5438                if (!backupPasswordMatches(mCurrentPassword)) {
5439                    if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
5440                    return;
5441                }
5442
5443                mBytes = 0;
5444                byte[] buffer = new byte[32 * 1024];
5445                rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
5446                rawDataIn = new DataInputStream(rawInStream);
5447
5448                // First, parse out the unencrypted/uncompressed header
5449                boolean compressed = false;
5450                InputStream preCompressStream = rawInStream;
5451                final InputStream in;
5452
5453                boolean okay = false;
5454                final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
5455                byte[] streamHeader = new byte[headerLen];
5456                rawDataIn.readFully(streamHeader);
5457                byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
5458                if (Arrays.equals(magicBytes, streamHeader)) {
5459                    // okay, header looks good.  now parse out the rest of the fields.
5460                    String s = readHeaderLine(rawInStream);
5461                    final int archiveVersion = Integer.parseInt(s);
5462                    if (archiveVersion <= BACKUP_FILE_VERSION) {
5463                        // okay, it's a version we recognize.  if it's version 1, we may need
5464                        // to try two different PBKDF2 regimes to compare checksums.
5465                        final boolean pbkdf2Fallback = (archiveVersion == 1);
5466
5467                        s = readHeaderLine(rawInStream);
5468                        compressed = (Integer.parseInt(s) != 0);
5469                        s = readHeaderLine(rawInStream);
5470                        if (s.equals("none")) {
5471                            // no more header to parse; we're good to go
5472                            okay = true;
5473                        } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
5474                            preCompressStream = decodeAesHeaderAndInitialize(s, pbkdf2Fallback,
5475                                    rawInStream);
5476                            if (preCompressStream != null) {
5477                                okay = true;
5478                            }
5479                        } else Slog.w(TAG, "Archive is encrypted but no password given");
5480                    } else Slog.w(TAG, "Wrong header version: " + s);
5481                } else Slog.w(TAG, "Didn't read the right header magic");
5482
5483                if (!okay) {
5484                    Slog.w(TAG, "Invalid restore data; aborting.");
5485                    return;
5486                }
5487
5488                // okay, use the right stream layer based on compression
5489                in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
5490
5491                boolean didRestore;
5492                do {
5493                    didRestore = restoreOneFile(in, buffer);
5494                } while (didRestore);
5495
5496                if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
5497            } catch (IOException e) {
5498                Slog.e(TAG, "Unable to read restore input");
5499            } finally {
5500                tearDownPipes();
5501                tearDownAgent(mTargetApp);
5502
5503                try {
5504                    if (rawDataIn != null) rawDataIn.close();
5505                    if (rawInStream != null) rawInStream.close();
5506                    mInputFile.close();
5507                } catch (IOException e) {
5508                    Slog.w(TAG, "Close of restore data pipe threw", e);
5509                    /* nothing we can do about this */
5510                }
5511                synchronized (mCurrentOpLock) {
5512                    mCurrentOperations.clear();
5513                }
5514                synchronized (mLatchObject) {
5515                    mLatchObject.set(true);
5516                    mLatchObject.notifyAll();
5517                }
5518                mObbConnection.tearDown();
5519                sendEndRestore();
5520                Slog.d(TAG, "Full restore pass complete.");
5521                mWakelock.release();
5522            }
5523        }
5524
5525        String readHeaderLine(InputStream in) throws IOException {
5526            int c;
5527            StringBuilder buffer = new StringBuilder(80);
5528            while ((c = in.read()) >= 0) {
5529                if (c == '\n') break;   // consume and discard the newlines
5530                buffer.append((char)c);
5531            }
5532            return buffer.toString();
5533        }
5534
5535        InputStream attemptMasterKeyDecryption(String algorithm, byte[] userSalt, byte[] ckSalt,
5536                int rounds, String userIvHex, String masterKeyBlobHex, InputStream rawInStream,
5537                boolean doLog) {
5538            InputStream result = null;
5539
5540            try {
5541                Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
5542                SecretKey userKey = buildPasswordKey(algorithm, mDecryptPassword, userSalt,
5543                        rounds);
5544                byte[] IV = hexToByteArray(userIvHex);
5545                IvParameterSpec ivSpec = new IvParameterSpec(IV);
5546                c.init(Cipher.DECRYPT_MODE,
5547                        new SecretKeySpec(userKey.getEncoded(), "AES"),
5548                        ivSpec);
5549                byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
5550                byte[] mkBlob = c.doFinal(mkCipher);
5551
5552                // first, the master key IV
5553                int offset = 0;
5554                int len = mkBlob[offset++];
5555                IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
5556                offset += len;
5557                // then the master key itself
5558                len = mkBlob[offset++];
5559                byte[] mk = Arrays.copyOfRange(mkBlob,
5560                        offset, offset + len);
5561                offset += len;
5562                // and finally the master key checksum hash
5563                len = mkBlob[offset++];
5564                byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
5565                        offset, offset + len);
5566
5567                // now validate the decrypted master key against the checksum
5568                byte[] calculatedCk = makeKeyChecksum(algorithm, mk, ckSalt, rounds);
5569                if (Arrays.equals(calculatedCk, mkChecksum)) {
5570                    ivSpec = new IvParameterSpec(IV);
5571                    c.init(Cipher.DECRYPT_MODE,
5572                            new SecretKeySpec(mk, "AES"),
5573                            ivSpec);
5574                    // Only if all of the above worked properly will 'result' be assigned
5575                    result = new CipherInputStream(rawInStream, c);
5576                } else if (doLog) Slog.w(TAG, "Incorrect password");
5577            } catch (InvalidAlgorithmParameterException e) {
5578                if (doLog) Slog.e(TAG, "Needed parameter spec unavailable!", e);
5579            } catch (BadPaddingException e) {
5580                // This case frequently occurs when the wrong password is used to decrypt
5581                // the master key.  Use the identical "incorrect password" log text as is
5582                // used in the checksum failure log in order to avoid providing additional
5583                // information to an attacker.
5584                if (doLog) Slog.w(TAG, "Incorrect password");
5585            } catch (IllegalBlockSizeException e) {
5586                if (doLog) Slog.w(TAG, "Invalid block size in master key");
5587            } catch (NoSuchAlgorithmException e) {
5588                if (doLog) Slog.e(TAG, "Needed decryption algorithm unavailable!");
5589            } catch (NoSuchPaddingException e) {
5590                if (doLog) Slog.e(TAG, "Needed padding mechanism unavailable!");
5591            } catch (InvalidKeyException e) {
5592                if (doLog) Slog.w(TAG, "Illegal password; aborting");
5593            }
5594
5595            return result;
5596        }
5597
5598        InputStream decodeAesHeaderAndInitialize(String encryptionName, boolean pbkdf2Fallback,
5599                InputStream rawInStream) {
5600            InputStream result = null;
5601            try {
5602                if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
5603
5604                    String userSaltHex = readHeaderLine(rawInStream); // 5
5605                    byte[] userSalt = hexToByteArray(userSaltHex);
5606
5607                    String ckSaltHex = readHeaderLine(rawInStream); // 6
5608                    byte[] ckSalt = hexToByteArray(ckSaltHex);
5609
5610                    int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
5611                    String userIvHex = readHeaderLine(rawInStream); // 8
5612
5613                    String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
5614
5615                    // decrypt the master key blob
5616                    result = attemptMasterKeyDecryption(PBKDF_CURRENT, userSalt, ckSalt,
5617                            rounds, userIvHex, masterKeyBlobHex, rawInStream, false);
5618                    if (result == null && pbkdf2Fallback) {
5619                        result = attemptMasterKeyDecryption(PBKDF_FALLBACK, userSalt, ckSalt,
5620                                rounds, userIvHex, masterKeyBlobHex, rawInStream, true);
5621                    }
5622                } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
5623            } catch (NumberFormatException e) {
5624                Slog.w(TAG, "Can't parse restore data header");
5625            } catch (IOException e) {
5626                Slog.w(TAG, "Can't read input header");
5627            }
5628
5629            return result;
5630        }
5631
5632        boolean restoreOneFile(InputStream instream, byte[] buffer) {
5633            FileMetadata info;
5634            try {
5635                info = readTarHeaders(instream);
5636                if (info != null) {
5637                    if (MORE_DEBUG) {
5638                        dumpFileMetadata(info);
5639                    }
5640
5641                    final String pkg = info.packageName;
5642                    if (!pkg.equals(mAgentPackage)) {
5643                        // okay, change in package; set up our various
5644                        // bookkeeping if we haven't seen it yet
5645                        if (!mPackagePolicies.containsKey(pkg)) {
5646                            mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5647                        }
5648
5649                        // Clean up the previous agent relationship if necessary,
5650                        // and let the observer know we're considering a new app.
5651                        if (mAgent != null) {
5652                            if (DEBUG) Slog.d(TAG, "Saw new package; finalizing old one");
5653                            // Now we're really done
5654                            tearDownPipes();
5655                            tearDownAgent(mTargetApp);
5656                            mTargetApp = null;
5657                            mAgentPackage = null;
5658                        }
5659                    }
5660
5661                    if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
5662                        mPackagePolicies.put(pkg, readAppManifest(info, instream));
5663                        mPackageInstallers.put(pkg, info.installerPackageName);
5664                        // We've read only the manifest content itself at this point,
5665                        // so consume the footer before looping around to the next
5666                        // input file
5667                        skipTarPadding(info.size, instream);
5668                        sendOnRestorePackage(pkg);
5669                    } else if (info.path.equals(BACKUP_METADATA_FILENAME)) {
5670                        // Metadata blobs!
5671                        readMetadata(info, instream);
5672                    } else {
5673                        // Non-manifest, so it's actual file data.  Is this a package
5674                        // we're ignoring?
5675                        boolean okay = true;
5676                        RestorePolicy policy = mPackagePolicies.get(pkg);
5677                        switch (policy) {
5678                            case IGNORE:
5679                                okay = false;
5680                                break;
5681
5682                            case ACCEPT_IF_APK:
5683                                // If we're in accept-if-apk state, then the first file we
5684                                // see MUST be the apk.
5685                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
5686                                    if (DEBUG) Slog.d(TAG, "APK file; installing");
5687                                    // Try to install the app.
5688                                    String installerName = mPackageInstallers.get(pkg);
5689                                    okay = installApk(info, installerName, instream);
5690                                    // good to go; promote to ACCEPT
5691                                    mPackagePolicies.put(pkg, (okay)
5692                                            ? RestorePolicy.ACCEPT
5693                                            : RestorePolicy.IGNORE);
5694                                    // At this point we've consumed this file entry
5695                                    // ourselves, so just strip the tar footer and
5696                                    // go on to the next file in the input stream
5697                                    skipTarPadding(info.size, instream);
5698                                    return true;
5699                                } else {
5700                                    // File data before (or without) the apk.  We can't
5701                                    // handle it coherently in this case so ignore it.
5702                                    mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5703                                    okay = false;
5704                                }
5705                                break;
5706
5707                            case ACCEPT:
5708                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
5709                                    if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
5710                                    // we can take the data without the apk, so we
5711                                    // *want* to do so.  skip the apk by declaring this
5712                                    // one file not-okay without changing the restore
5713                                    // policy for the package.
5714                                    okay = false;
5715                                }
5716                                break;
5717
5718                            default:
5719                                // Something has gone dreadfully wrong when determining
5720                                // the restore policy from the manifest.  Ignore the
5721                                // rest of this package's data.
5722                                Slog.e(TAG, "Invalid policy from manifest");
5723                                okay = false;
5724                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5725                                break;
5726                        }
5727
5728                        // The path needs to be canonical
5729                        if (info.path.contains("..") || info.path.contains("//")) {
5730                            if (MORE_DEBUG) {
5731                                Slog.w(TAG, "Dropping invalid path " + info.path);
5732                            }
5733                            okay = false;
5734                        }
5735
5736                        // If the policy is satisfied, go ahead and set up to pipe the
5737                        // data to the agent.
5738                        if (DEBUG && okay && mAgent != null) {
5739                            Slog.i(TAG, "Reusing existing agent instance");
5740                        }
5741                        if (okay && mAgent == null) {
5742                            if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
5743
5744                            try {
5745                                mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
5746
5747                                // If we haven't sent any data to this app yet, we probably
5748                                // need to clear it first.  Check that.
5749                                if (!mClearedPackages.contains(pkg)) {
5750                                    // apps with their own backup agents are
5751                                    // responsible for coherently managing a full
5752                                    // restore.
5753                                    if (mTargetApp.backupAgentName == null) {
5754                                        if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
5755                                        clearApplicationDataSynchronous(pkg);
5756                                    } else {
5757                                        if (DEBUG) Slog.d(TAG, "backup agent ("
5758                                                + mTargetApp.backupAgentName + ") => no clear");
5759                                    }
5760                                    mClearedPackages.add(pkg);
5761                                } else {
5762                                    if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
5763                                }
5764
5765                                // All set; now set up the IPC and launch the agent
5766                                setUpPipes();
5767                                mAgent = bindToAgentSynchronous(mTargetApp,
5768                                        IApplicationThread.BACKUP_MODE_RESTORE_FULL);
5769                                mAgentPackage = pkg;
5770                            } catch (IOException e) {
5771                                // fall through to error handling
5772                            } catch (NameNotFoundException e) {
5773                                // fall through to error handling
5774                            }
5775
5776                            if (mAgent == null) {
5777                                if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
5778                                okay = false;
5779                                tearDownPipes();
5780                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5781                            }
5782                        }
5783
5784                        // Sanity check: make sure we never give data to the wrong app.  This
5785                        // should never happen but a little paranoia here won't go amiss.
5786                        if (okay && !pkg.equals(mAgentPackage)) {
5787                            Slog.e(TAG, "Restoring data for " + pkg
5788                                    + " but agent is for " + mAgentPackage);
5789                            okay = false;
5790                        }
5791
5792                        // At this point we have an agent ready to handle the full
5793                        // restore data as well as a pipe for sending data to
5794                        // that agent.  Tell the agent to start reading from the
5795                        // pipe.
5796                        if (okay) {
5797                            boolean agentSuccess = true;
5798                            long toCopy = info.size;
5799                            final int token = generateToken();
5800                            try {
5801                                prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
5802                                if (info.domain.equals(FullBackup.OBB_TREE_TOKEN)) {
5803                                    if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
5804                                            + " : " + info.path);
5805                                    mObbConnection.restoreObbFile(pkg, mPipes[0],
5806                                            info.size, info.type, info.path, info.mode,
5807                                            info.mtime, token, mBackupManagerBinder);
5808                                } else {
5809                                    if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
5810                                            + info.path);
5811                                    // fire up the app's agent listening on the socket.  If
5812                                    // the agent is running in the system process we can't
5813                                    // just invoke it asynchronously, so we provide a thread
5814                                    // for it here.
5815                                    if (mTargetApp.processName.equals("system")) {
5816                                        Slog.d(TAG, "system process agent - spinning a thread");
5817                                        RestoreFileRunnable runner = new RestoreFileRunnable(
5818                                                mAgent, info, mPipes[0], token);
5819                                        new Thread(runner, "restore-sys-runner").start();
5820                                    } else {
5821                                        mAgent.doRestoreFile(mPipes[0], info.size, info.type,
5822                                                info.domain, info.path, info.mode, info.mtime,
5823                                                token, mBackupManagerBinder);
5824                                    }
5825                                }
5826                            } catch (IOException e) {
5827                                // couldn't dup the socket for a process-local restore
5828                                Slog.d(TAG, "Couldn't establish restore");
5829                                agentSuccess = false;
5830                                okay = false;
5831                            } catch (RemoteException e) {
5832                                // whoops, remote entity went away.  We'll eat the content
5833                                // ourselves, then, and not copy it over.
5834                                Slog.e(TAG, "Agent crashed during full restore");
5835                                agentSuccess = false;
5836                                okay = false;
5837                            }
5838
5839                            // Copy over the data if the agent is still good
5840                            if (okay) {
5841                                boolean pipeOkay = true;
5842                                FileOutputStream pipe = new FileOutputStream(
5843                                        mPipes[1].getFileDescriptor());
5844                                while (toCopy > 0) {
5845                                    int toRead = (toCopy > buffer.length)
5846                                    ? buffer.length : (int)toCopy;
5847                                    int nRead = instream.read(buffer, 0, toRead);
5848                                    if (nRead >= 0) mBytes += nRead;
5849                                    if (nRead <= 0) break;
5850                                    toCopy -= nRead;
5851
5852                                    // send it to the output pipe as long as things
5853                                    // are still good
5854                                    if (pipeOkay) {
5855                                        try {
5856                                            pipe.write(buffer, 0, nRead);
5857                                        } catch (IOException e) {
5858                                            Slog.e(TAG, "Failed to write to restore pipe", e);
5859                                            pipeOkay = false;
5860                                        }
5861                                    }
5862                                }
5863
5864                                // done sending that file!  Now we just need to consume
5865                                // the delta from info.size to the end of block.
5866                                skipTarPadding(info.size, instream);
5867
5868                                // and now that we've sent it all, wait for the remote
5869                                // side to acknowledge receipt
5870                                agentSuccess = waitUntilOperationComplete(token);
5871                            }
5872
5873                            // okay, if the remote end failed at any point, deal with
5874                            // it by ignoring the rest of the restore on it
5875                            if (!agentSuccess) {
5876                                mBackupHandler.removeMessages(MSG_TIMEOUT);
5877                                tearDownPipes();
5878                                tearDownAgent(mTargetApp);
5879                                mAgent = null;
5880                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5881                            }
5882                        }
5883
5884                        // Problems setting up the agent communication, or an already-
5885                        // ignored package: skip to the next tar stream entry by
5886                        // reading and discarding this file.
5887                        if (!okay) {
5888                            if (DEBUG) Slog.d(TAG, "[discarding file content]");
5889                            long bytesToConsume = (info.size + 511) & ~511;
5890                            while (bytesToConsume > 0) {
5891                                int toRead = (bytesToConsume > buffer.length)
5892                                ? buffer.length : (int)bytesToConsume;
5893                                long nRead = instream.read(buffer, 0, toRead);
5894                                if (nRead >= 0) mBytes += nRead;
5895                                if (nRead <= 0) break;
5896                                bytesToConsume -= nRead;
5897                            }
5898                        }
5899                    }
5900                }
5901            } catch (IOException e) {
5902                if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
5903                // treat as EOF
5904                info = null;
5905            }
5906
5907            return (info != null);
5908        }
5909
5910        void setUpPipes() throws IOException {
5911            mPipes = ParcelFileDescriptor.createPipe();
5912        }
5913
5914        void tearDownPipes() {
5915            if (mPipes != null) {
5916                try {
5917                    mPipes[0].close();
5918                    mPipes[0] = null;
5919                    mPipes[1].close();
5920                    mPipes[1] = null;
5921                } catch (IOException e) {
5922                    Slog.w(TAG, "Couldn't close agent pipes", e);
5923                }
5924                mPipes = null;
5925            }
5926        }
5927
5928        void tearDownAgent(ApplicationInfo app) {
5929            if (mAgent != null) {
5930                try {
5931                    // unbind and tidy up even on timeout or failure, just in case
5932                    mActivityManager.unbindBackupAgent(app);
5933
5934                    // The agent was running with a stub Application object, so shut it down.
5935                    // !!! We hardcode the confirmation UI's package name here rather than use a
5936                    //     manifest flag!  TODO something less direct.
5937                    if (app.uid != Process.SYSTEM_UID
5938                            && !app.packageName.equals("com.android.backupconfirm")) {
5939                        if (DEBUG) Slog.d(TAG, "Killing host process");
5940                        mActivityManager.killApplicationProcess(app.processName, app.uid);
5941                    } else {
5942                        if (DEBUG) Slog.d(TAG, "Not killing after full restore");
5943                    }
5944                } catch (RemoteException e) {
5945                    Slog.d(TAG, "Lost app trying to shut down");
5946                }
5947                mAgent = null;
5948            }
5949        }
5950
5951        class RestoreInstallObserver extends IPackageInstallObserver.Stub {
5952            final AtomicBoolean mDone = new AtomicBoolean();
5953            String mPackageName;
5954            int mResult;
5955
5956            public void reset() {
5957                synchronized (mDone) {
5958                    mDone.set(false);
5959                }
5960            }
5961
5962            public void waitForCompletion() {
5963                synchronized (mDone) {
5964                    while (mDone.get() == false) {
5965                        try {
5966                            mDone.wait();
5967                        } catch (InterruptedException e) { }
5968                    }
5969                }
5970            }
5971
5972            int getResult() {
5973                return mResult;
5974            }
5975
5976            @Override
5977            public void packageInstalled(String packageName, int returnCode)
5978                    throws RemoteException {
5979                synchronized (mDone) {
5980                    mResult = returnCode;
5981                    mPackageName = packageName;
5982                    mDone.set(true);
5983                    mDone.notifyAll();
5984                }
5985            }
5986        }
5987
5988        class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
5989            final AtomicBoolean mDone = new AtomicBoolean();
5990            int mResult;
5991
5992            public void reset() {
5993                synchronized (mDone) {
5994                    mDone.set(false);
5995                }
5996            }
5997
5998            public void waitForCompletion() {
5999                synchronized (mDone) {
6000                    while (mDone.get() == false) {
6001                        try {
6002                            mDone.wait();
6003                        } catch (InterruptedException e) { }
6004                    }
6005                }
6006            }
6007
6008            @Override
6009            public void packageDeleted(String packageName, int returnCode) throws RemoteException {
6010                synchronized (mDone) {
6011                    mResult = returnCode;
6012                    mDone.set(true);
6013                    mDone.notifyAll();
6014                }
6015            }
6016        }
6017
6018        final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
6019        final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
6020
6021        boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
6022            boolean okay = true;
6023
6024            if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
6025
6026            // The file content is an .apk file.  Copy it out to a staging location and
6027            // attempt to install it.
6028            File apkFile = new File(mDataDir, info.packageName);
6029            try {
6030                FileOutputStream apkStream = new FileOutputStream(apkFile);
6031                byte[] buffer = new byte[32 * 1024];
6032                long size = info.size;
6033                while (size > 0) {
6034                    long toRead = (buffer.length < size) ? buffer.length : size;
6035                    int didRead = instream.read(buffer, 0, (int)toRead);
6036                    if (didRead >= 0) mBytes += didRead;
6037                    apkStream.write(buffer, 0, didRead);
6038                    size -= didRead;
6039                }
6040                apkStream.close();
6041
6042                // make sure the installer can read it
6043                apkFile.setReadable(true, false);
6044
6045                // Now install it
6046                Uri packageUri = Uri.fromFile(apkFile);
6047                mInstallObserver.reset();
6048                mPackageManager.installPackage(packageUri, mInstallObserver,
6049                        PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
6050                        installerPackage);
6051                mInstallObserver.waitForCompletion();
6052
6053                if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
6054                    // The only time we continue to accept install of data even if the
6055                    // apk install failed is if we had already determined that we could
6056                    // accept the data regardless.
6057                    if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
6058                        okay = false;
6059                    }
6060                } else {
6061                    // Okay, the install succeeded.  Make sure it was the right app.
6062                    boolean uninstall = false;
6063                    if (!mInstallObserver.mPackageName.equals(info.packageName)) {
6064                        Slog.w(TAG, "Restore stream claimed to include apk for "
6065                                + info.packageName + " but apk was really "
6066                                + mInstallObserver.mPackageName);
6067                        // delete the package we just put in place; it might be fraudulent
6068                        okay = false;
6069                        uninstall = true;
6070                    } else {
6071                        try {
6072                            PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
6073                                    PackageManager.GET_SIGNATURES);
6074                            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
6075                                Slog.w(TAG, "Restore stream contains apk of package "
6076                                        + info.packageName + " but it disallows backup/restore");
6077                                okay = false;
6078                            } else {
6079                                // So far so good -- do the signatures match the manifest?
6080                                Signature[] sigs = mManifestSignatures.get(info.packageName);
6081                                if (signaturesMatch(sigs, pkg)) {
6082                                    // If this is a system-uid app without a declared backup agent,
6083                                    // don't restore any of the file data.
6084                                    if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
6085                                            && (pkg.applicationInfo.backupAgentName == null)) {
6086                                        Slog.w(TAG, "Installed app " + info.packageName
6087                                                + " has restricted uid and no agent");
6088                                        okay = false;
6089                                    }
6090                                } else {
6091                                    Slog.w(TAG, "Installed app " + info.packageName
6092                                            + " signatures do not match restore manifest");
6093                                    okay = false;
6094                                    uninstall = true;
6095                                }
6096                            }
6097                        } catch (NameNotFoundException e) {
6098                            Slog.w(TAG, "Install of package " + info.packageName
6099                                    + " succeeded but now not found");
6100                            okay = false;
6101                        }
6102                    }
6103
6104                    // If we're not okay at this point, we need to delete the package
6105                    // that we just installed.
6106                    if (uninstall) {
6107                        mDeleteObserver.reset();
6108                        mPackageManager.deletePackage(mInstallObserver.mPackageName,
6109                                mDeleteObserver, 0);
6110                        mDeleteObserver.waitForCompletion();
6111                    }
6112                }
6113            } catch (IOException e) {
6114                Slog.e(TAG, "Unable to transcribe restored apk for install");
6115                okay = false;
6116            } finally {
6117                apkFile.delete();
6118            }
6119
6120            return okay;
6121        }
6122
6123        // Given an actual file content size, consume the post-content padding mandated
6124        // by the tar format.
6125        void skipTarPadding(long size, InputStream instream) throws IOException {
6126            long partial = (size + 512) % 512;
6127            if (partial > 0) {
6128                final int needed = 512 - (int)partial;
6129                byte[] buffer = new byte[needed];
6130                if (readExactly(instream, buffer, 0, needed) == needed) {
6131                    mBytes += needed;
6132                } else throw new IOException("Unexpected EOF in padding");
6133            }
6134        }
6135
6136        // Read a widget metadata file, returning the restored blob
6137        void readMetadata(FileMetadata info, InputStream instream) throws IOException {
6138            // Fail on suspiciously large widget dump files
6139            if (info.size > 64 * 1024) {
6140                throw new IOException("Metadata too big; corrupt? size=" + info.size);
6141            }
6142
6143            byte[] buffer = new byte[(int) info.size];
6144            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
6145                mBytes += info.size;
6146            } else throw new IOException("Unexpected EOF in widget data");
6147
6148            String[] str = new String[1];
6149            int offset = extractLine(buffer, 0, str);
6150            int version = Integer.parseInt(str[0]);
6151            if (version == BACKUP_MANIFEST_VERSION) {
6152                offset = extractLine(buffer, offset, str);
6153                final String pkg = str[0];
6154                if (info.packageName.equals(pkg)) {
6155                    // Data checks out -- the rest of the buffer is a concatenation of
6156                    // binary blobs as described in the comment at writeAppWidgetData()
6157                    ByteArrayInputStream bin = new ByteArrayInputStream(buffer,
6158                            offset, buffer.length - offset);
6159                    DataInputStream in = new DataInputStream(bin);
6160                    while (bin.available() > 0) {
6161                        int token = in.readInt();
6162                        int size = in.readInt();
6163                        if (size > 64 * 1024) {
6164                            throw new IOException("Datum "
6165                                    + Integer.toHexString(token)
6166                                    + " too big; corrupt? size=" + info.size);
6167                        }
6168                        switch (token) {
6169                            case BACKUP_WIDGET_METADATA_TOKEN:
6170                            {
6171                                if (MORE_DEBUG) {
6172                                    Slog.i(TAG, "Got widget metadata for " + info.packageName);
6173                                }
6174                                mWidgetData = new byte[size];
6175                                in.read(mWidgetData);
6176                                break;
6177                            }
6178                            default:
6179                            {
6180                                if (DEBUG) {
6181                                    Slog.i(TAG, "Ignoring metadata blob "
6182                                            + Integer.toHexString(token)
6183                                            + " for " + info.packageName);
6184                                }
6185                                in.skipBytes(size);
6186                                break;
6187                            }
6188                        }
6189                    }
6190                } else {
6191                    Slog.w(TAG, "Metadata mismatch: package " + info.packageName
6192                            + " but widget data for " + pkg);
6193                }
6194            } else {
6195                Slog.w(TAG, "Unsupported metadata version " + version);
6196            }
6197        }
6198
6199        // Returns a policy constant; takes a buffer arg to reduce memory churn
6200        RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
6201                throws IOException {
6202            // Fail on suspiciously large manifest files
6203            if (info.size > 64 * 1024) {
6204                throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
6205            }
6206
6207            byte[] buffer = new byte[(int) info.size];
6208            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
6209                mBytes += info.size;
6210            } else throw new IOException("Unexpected EOF in manifest");
6211
6212            RestorePolicy policy = RestorePolicy.IGNORE;
6213            String[] str = new String[1];
6214            int offset = 0;
6215
6216            try {
6217                offset = extractLine(buffer, offset, str);
6218                int version = Integer.parseInt(str[0]);
6219                if (version == BACKUP_MANIFEST_VERSION) {
6220                    offset = extractLine(buffer, offset, str);
6221                    String manifestPackage = str[0];
6222                    // TODO: handle <original-package>
6223                    if (manifestPackage.equals(info.packageName)) {
6224                        offset = extractLine(buffer, offset, str);
6225                        version = Integer.parseInt(str[0]);  // app version
6226                        offset = extractLine(buffer, offset, str);
6227                        int platformVersion = Integer.parseInt(str[0]);
6228                        offset = extractLine(buffer, offset, str);
6229                        info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
6230                        offset = extractLine(buffer, offset, str);
6231                        boolean hasApk = str[0].equals("1");
6232                        offset = extractLine(buffer, offset, str);
6233                        int numSigs = Integer.parseInt(str[0]);
6234                        if (numSigs > 0) {
6235                            Signature[] sigs = new Signature[numSigs];
6236                            for (int i = 0; i < numSigs; i++) {
6237                                offset = extractLine(buffer, offset, str);
6238                                sigs[i] = new Signature(str[0]);
6239                            }
6240                            mManifestSignatures.put(info.packageName, sigs);
6241
6242                            // Okay, got the manifest info we need...
6243                            try {
6244                                PackageInfo pkgInfo = mPackageManager.getPackageInfo(
6245                                        info.packageName, PackageManager.GET_SIGNATURES);
6246                                // Fall through to IGNORE if the app explicitly disallows backup
6247                                final int flags = pkgInfo.applicationInfo.flags;
6248                                if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
6249                                    // Restore system-uid-space packages only if they have
6250                                    // defined a custom backup agent
6251                                    if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
6252                                            || (pkgInfo.applicationInfo.backupAgentName != null)) {
6253                                        // Verify signatures against any installed version; if they
6254                                        // don't match, then we fall though and ignore the data.  The
6255                                        // signatureMatch() method explicitly ignores the signature
6256                                        // check for packages installed on the system partition, because
6257                                        // such packages are signed with the platform cert instead of
6258                                        // the app developer's cert, so they're different on every
6259                                        // device.
6260                                        if (signaturesMatch(sigs, pkgInfo)) {
6261                                            if (pkgInfo.versionCode >= version) {
6262                                                Slog.i(TAG, "Sig + version match; taking data");
6263                                                policy = RestorePolicy.ACCEPT;
6264                                            } else {
6265                                                // The data is from a newer version of the app than
6266                                                // is presently installed.  That means we can only
6267                                                // use it if the matching apk is also supplied.
6268                                                Slog.d(TAG, "Data version " + version
6269                                                        + " is newer than installed version "
6270                                                        + pkgInfo.versionCode + " - requiring apk");
6271                                                policy = RestorePolicy.ACCEPT_IF_APK;
6272                                            }
6273                                        } else {
6274                                            Slog.w(TAG, "Restore manifest signatures do not match "
6275                                                    + "installed application for " + info.packageName);
6276                                        }
6277                                    } else {
6278                                        Slog.w(TAG, "Package " + info.packageName
6279                                                + " is system level with no agent");
6280                                    }
6281                                } else {
6282                                    if (DEBUG) Slog.i(TAG, "Restore manifest from "
6283                                            + info.packageName + " but allowBackup=false");
6284                                }
6285                            } catch (NameNotFoundException e) {
6286                                // Okay, the target app isn't installed.  We can process
6287                                // the restore properly only if the dataset provides the
6288                                // apk file and we can successfully install it.
6289                                if (DEBUG) Slog.i(TAG, "Package " + info.packageName
6290                                        + " not installed; requiring apk in dataset");
6291                                policy = RestorePolicy.ACCEPT_IF_APK;
6292                            }
6293
6294                            if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
6295                                Slog.i(TAG, "Cannot restore package " + info.packageName
6296                                        + " without the matching .apk");
6297                            }
6298                        } else {
6299                            Slog.i(TAG, "Missing signature on backed-up package "
6300                                    + info.packageName);
6301                        }
6302                    } else {
6303                        Slog.i(TAG, "Expected package " + info.packageName
6304                                + " but restore manifest claims " + manifestPackage);
6305                    }
6306                } else {
6307                    Slog.i(TAG, "Unknown restore manifest version " + version
6308                            + " for package " + info.packageName);
6309                }
6310            } catch (NumberFormatException e) {
6311                Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
6312            } catch (IllegalArgumentException e) {
6313                Slog.w(TAG, e.getMessage());
6314            }
6315
6316            return policy;
6317        }
6318
6319        // Builds a line from a byte buffer starting at 'offset', and returns
6320        // the index of the next unconsumed data in the buffer.
6321        int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
6322            final int end = buffer.length;
6323            if (offset >= end) throw new IOException("Incomplete data");
6324
6325            int pos;
6326            for (pos = offset; pos < end; pos++) {
6327                byte c = buffer[pos];
6328                // at LF we declare end of line, and return the next char as the
6329                // starting point for the next time through
6330                if (c == '\n') {
6331                    break;
6332                }
6333            }
6334            outStr[0] = new String(buffer, offset, pos - offset);
6335            pos++;  // may be pointing an extra byte past the end but that's okay
6336            return pos;
6337        }
6338
6339        void dumpFileMetadata(FileMetadata info) {
6340            if (DEBUG) {
6341                StringBuilder b = new StringBuilder(128);
6342
6343                // mode string
6344                b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
6345                b.append(((info.mode & 0400) != 0) ? 'r' : '-');
6346                b.append(((info.mode & 0200) != 0) ? 'w' : '-');
6347                b.append(((info.mode & 0100) != 0) ? 'x' : '-');
6348                b.append(((info.mode & 0040) != 0) ? 'r' : '-');
6349                b.append(((info.mode & 0020) != 0) ? 'w' : '-');
6350                b.append(((info.mode & 0010) != 0) ? 'x' : '-');
6351                b.append(((info.mode & 0004) != 0) ? 'r' : '-');
6352                b.append(((info.mode & 0002) != 0) ? 'w' : '-');
6353                b.append(((info.mode & 0001) != 0) ? 'x' : '-');
6354                b.append(String.format(" %9d ", info.size));
6355
6356                Date stamp = new Date(info.mtime);
6357                b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp));
6358
6359                b.append(info.packageName);
6360                b.append(" :: ");
6361                b.append(info.domain);
6362                b.append(" :: ");
6363                b.append(info.path);
6364
6365                Slog.i(TAG, b.toString());
6366            }
6367        }
6368        // Consume a tar file header block [sequence] and accumulate the relevant metadata
6369        FileMetadata readTarHeaders(InputStream instream) throws IOException {
6370            byte[] block = new byte[512];
6371            FileMetadata info = null;
6372
6373            boolean gotHeader = readTarHeader(instream, block);
6374            if (gotHeader) {
6375                try {
6376                    // okay, presume we're okay, and extract the various metadata
6377                    info = new FileMetadata();
6378                    info.size = extractRadix(block, 124, 12, 8);
6379                    info.mtime = extractRadix(block, 136, 12, 8);
6380                    info.mode = extractRadix(block, 100, 8, 8);
6381
6382                    info.path = extractString(block, 345, 155); // prefix
6383                    String path = extractString(block, 0, 100);
6384                    if (path.length() > 0) {
6385                        if (info.path.length() > 0) info.path += '/';
6386                        info.path += path;
6387                    }
6388
6389                    // tar link indicator field: 1 byte at offset 156 in the header.
6390                    int typeChar = block[156];
6391                    if (typeChar == 'x') {
6392                        // pax extended header, so we need to read that
6393                        gotHeader = readPaxExtendedHeader(instream, info);
6394                        if (gotHeader) {
6395                            // and after a pax extended header comes another real header -- read
6396                            // that to find the real file type
6397                            gotHeader = readTarHeader(instream, block);
6398                        }
6399                        if (!gotHeader) throw new IOException("Bad or missing pax header");
6400
6401                        typeChar = block[156];
6402                    }
6403
6404                    switch (typeChar) {
6405                        case '0': info.type = BackupAgent.TYPE_FILE; break;
6406                        case '5': {
6407                            info.type = BackupAgent.TYPE_DIRECTORY;
6408                            if (info.size != 0) {
6409                                Slog.w(TAG, "Directory entry with nonzero size in header");
6410                                info.size = 0;
6411                            }
6412                            break;
6413                        }
6414                        case 0: {
6415                            // presume EOF
6416                            if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
6417                            return null;
6418                        }
6419                        default: {
6420                            Slog.e(TAG, "Unknown tar entity type: " + typeChar);
6421                            throw new IOException("Unknown entity type " + typeChar);
6422                        }
6423                    }
6424
6425                    // Parse out the path
6426                    //
6427                    // first: apps/shared/unrecognized
6428                    if (FullBackup.SHARED_PREFIX.regionMatches(0,
6429                            info.path, 0, FullBackup.SHARED_PREFIX.length())) {
6430                        // File in shared storage.  !!! TODO: implement this.
6431                        info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
6432                        info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
6433                        info.domain = FullBackup.SHARED_STORAGE_TOKEN;
6434                        if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
6435                    } else if (FullBackup.APPS_PREFIX.regionMatches(0,
6436                            info.path, 0, FullBackup.APPS_PREFIX.length())) {
6437                        // App content!  Parse out the package name and domain
6438
6439                        // strip the apps/ prefix
6440                        info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
6441
6442                        // extract the package name
6443                        int slash = info.path.indexOf('/');
6444                        if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
6445                        info.packageName = info.path.substring(0, slash);
6446                        info.path = info.path.substring(slash+1);
6447
6448                        // if it's a manifest we're done, otherwise parse out the domains
6449                        if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
6450                            slash = info.path.indexOf('/');
6451                            if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
6452                            info.domain = info.path.substring(0, slash);
6453                            info.path = info.path.substring(slash + 1);
6454                        }
6455                    }
6456                } catch (IOException e) {
6457                    if (DEBUG) {
6458                        Slog.e(TAG, "Parse error in header: " + e.getMessage());
6459                        HEXLOG(block);
6460                    }
6461                    throw e;
6462                }
6463            }
6464            return info;
6465        }
6466
6467        private void HEXLOG(byte[] block) {
6468            int offset = 0;
6469            int todo = block.length;
6470            StringBuilder buf = new StringBuilder(64);
6471            while (todo > 0) {
6472                buf.append(String.format("%04x   ", offset));
6473                int numThisLine = (todo > 16) ? 16 : todo;
6474                for (int i = 0; i < numThisLine; i++) {
6475                    buf.append(String.format("%02x ", block[offset+i]));
6476                }
6477                Slog.i("hexdump", buf.toString());
6478                buf.setLength(0);
6479                todo -= numThisLine;
6480                offset += numThisLine;
6481            }
6482        }
6483
6484        // Read exactly the given number of bytes into a buffer at the stated offset.
6485        // Returns false if EOF is encountered before the requested number of bytes
6486        // could be read.
6487        int readExactly(InputStream in, byte[] buffer, int offset, int size)
6488                throws IOException {
6489            if (size <= 0) throw new IllegalArgumentException("size must be > 0");
6490
6491            int soFar = 0;
6492            while (soFar < size) {
6493                int nRead = in.read(buffer, offset + soFar, size - soFar);
6494                if (nRead <= 0) {
6495                    if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
6496                    break;
6497                }
6498                soFar += nRead;
6499            }
6500            return soFar;
6501        }
6502
6503        boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
6504            final int got = readExactly(instream, block, 0, 512);
6505            if (got == 0) return false;     // Clean EOF
6506            if (got < 512) throw new IOException("Unable to read full block header");
6507            mBytes += 512;
6508            return true;
6509        }
6510
6511        // overwrites 'info' fields based on the pax extended header
6512        boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
6513                throws IOException {
6514            // We should never see a pax extended header larger than this
6515            if (info.size > 32*1024) {
6516                Slog.w(TAG, "Suspiciously large pax header size " + info.size
6517                        + " - aborting");
6518                throw new IOException("Sanity failure: pax header size " + info.size);
6519            }
6520
6521            // read whole blocks, not just the content size
6522            int numBlocks = (int)((info.size + 511) >> 9);
6523            byte[] data = new byte[numBlocks * 512];
6524            if (readExactly(instream, data, 0, data.length) < data.length) {
6525                throw new IOException("Unable to read full pax header");
6526            }
6527            mBytes += data.length;
6528
6529            final int contentSize = (int) info.size;
6530            int offset = 0;
6531            do {
6532                // extract the line at 'offset'
6533                int eol = offset+1;
6534                while (eol < contentSize && data[eol] != ' ') eol++;
6535                if (eol >= contentSize) {
6536                    // error: we just hit EOD looking for the end of the size field
6537                    throw new IOException("Invalid pax data");
6538                }
6539                // eol points to the space between the count and the key
6540                int linelen = (int) extractRadix(data, offset, eol - offset, 10);
6541                int key = eol + 1;  // start of key=value
6542                eol = offset + linelen - 1; // trailing LF
6543                int value;
6544                for (value = key+1; data[value] != '=' && value <= eol; value++);
6545                if (value > eol) {
6546                    throw new IOException("Invalid pax declaration");
6547                }
6548
6549                // pax requires that key/value strings be in UTF-8
6550                String keyStr = new String(data, key, value-key, "UTF-8");
6551                // -1 to strip the trailing LF
6552                String valStr = new String(data, value+1, eol-value-1, "UTF-8");
6553
6554                if ("path".equals(keyStr)) {
6555                    info.path = valStr;
6556                } else if ("size".equals(keyStr)) {
6557                    info.size = Long.parseLong(valStr);
6558                } else {
6559                    if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
6560                }
6561
6562                offset += linelen;
6563            } while (offset < contentSize);
6564
6565            return true;
6566        }
6567
6568        long extractRadix(byte[] data, int offset, int maxChars, int radix)
6569                throws IOException {
6570            long value = 0;
6571            final int end = offset + maxChars;
6572            for (int i = offset; i < end; i++) {
6573                final byte b = data[i];
6574                // Numeric fields in tar can terminate with either NUL or SPC
6575                if (b == 0 || b == ' ') break;
6576                if (b < '0' || b > ('0' + radix - 1)) {
6577                    throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
6578                }
6579                value = radix * value + (b - '0');
6580            }
6581            return value;
6582        }
6583
6584        String extractString(byte[] data, int offset, int maxChars) throws IOException {
6585            final int end = offset + maxChars;
6586            int eos = offset;
6587            // tar string fields terminate early with a NUL
6588            while (eos < end && data[eos] != 0) eos++;
6589            return new String(data, offset, eos-offset, "US-ASCII");
6590        }
6591
6592        void sendStartRestore() {
6593            if (mObserver != null) {
6594                try {
6595                    mObserver.onStartRestore();
6596                } catch (RemoteException e) {
6597                    Slog.w(TAG, "full restore observer went away: startRestore");
6598                    mObserver = null;
6599                }
6600            }
6601        }
6602
6603        void sendOnRestorePackage(String name) {
6604            if (mObserver != null) {
6605                try {
6606                    // TODO: use a more user-friendly name string
6607                    mObserver.onRestorePackage(name);
6608                } catch (RemoteException e) {
6609                    Slog.w(TAG, "full restore observer went away: restorePackage");
6610                    mObserver = null;
6611                }
6612            }
6613        }
6614
6615        void sendEndRestore() {
6616            if (mObserver != null) {
6617                try {
6618                    mObserver.onEndRestore();
6619                } catch (RemoteException e) {
6620                    Slog.w(TAG, "full restore observer went away: endRestore");
6621                    mObserver = null;
6622                }
6623            }
6624        }
6625    }
6626
6627    // ----- Restore handling -----
6628
6629    // new style: we only store the SHA-1 hashes of each sig, not the full block
6630    static boolean signaturesMatch(ArrayList<byte[]> storedSigHashes, PackageInfo target) {
6631        if (target == null) {
6632            return false;
6633        }
6634
6635        // If the target resides on the system partition, we allow it to restore
6636        // data from the like-named package in a restore set even if the signatures
6637        // do not match.  (Unlike general applications, those flashed to the system
6638        // partition will be signed with the device's platform certificate, so on
6639        // different phones the same system app will have different signatures.)
6640        if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6641            if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
6642            return true;
6643        }
6644
6645        // Allow unsigned apps, but not signed on one device and unsigned on the other
6646        // !!! TODO: is this the right policy?
6647        Signature[] deviceSigs = target.signatures;
6648        if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigHashes
6649                + " device=" + deviceSigs);
6650        if ((storedSigHashes == null || storedSigHashes.size() == 0)
6651                && (deviceSigs == null || deviceSigs.length == 0)) {
6652            return true;
6653        }
6654        if (storedSigHashes == null || deviceSigs == null) {
6655            return false;
6656        }
6657
6658        // !!! TODO: this demands that every stored signature match one
6659        // that is present on device, and does not demand the converse.
6660        // Is this this right policy?
6661        final int nStored = storedSigHashes.size();
6662        final int nDevice = deviceSigs.length;
6663
6664        // hash each on-device signature
6665        ArrayList<byte[]> deviceHashes = new ArrayList<byte[]>(nDevice);
6666        for (int i = 0; i < nDevice; i++) {
6667            deviceHashes.add(hashSignature(deviceSigs[i]));
6668        }
6669
6670        // now ensure that each stored sig (hash) matches an on-device sig (hash)
6671        for (int n = 0; n < nStored; n++) {
6672            boolean match = false;
6673            final byte[] storedHash = storedSigHashes.get(n);
6674            for (int i = 0; i < nDevice; i++) {
6675                if (Arrays.equals(storedHash, deviceHashes.get(i))) {
6676                    match = true;
6677                    break;
6678                }
6679            }
6680            // match is false when no on-device sig matched one of the stored ones
6681            if (!match) {
6682                return false;
6683            }
6684        }
6685
6686        return true;
6687    }
6688
6689    static byte[] hashSignature(Signature sig) {
6690        try {
6691            MessageDigest digest = MessageDigest.getInstance("SHA-256");
6692            digest.update(sig.toByteArray());
6693            return digest.digest();
6694        } catch (NoSuchAlgorithmException e) {
6695            Slog.w(TAG, "No SHA-256 algorithm found!");
6696        }
6697        return null;
6698    }
6699
6700    // Old style: directly match the stored vs on device signature blocks
6701    static boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
6702        if (target == null) {
6703            return false;
6704        }
6705
6706        // If the target resides on the system partition, we allow it to restore
6707        // data from the like-named package in a restore set even if the signatures
6708        // do not match.  (Unlike general applications, those flashed to the system
6709        // partition will be signed with the device's platform certificate, so on
6710        // different phones the same system app will have different signatures.)
6711        if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6712            if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
6713            return true;
6714        }
6715
6716        // Allow unsigned apps, but not signed on one device and unsigned on the other
6717        // !!! TODO: is this the right policy?
6718        Signature[] deviceSigs = target.signatures;
6719        if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
6720                + " device=" + deviceSigs);
6721        if ((storedSigs == null || storedSigs.length == 0)
6722                && (deviceSigs == null || deviceSigs.length == 0)) {
6723            return true;
6724        }
6725        if (storedSigs == null || deviceSigs == null) {
6726            return false;
6727        }
6728
6729        // !!! TODO: this demands that every stored signature match one
6730        // that is present on device, and does not demand the converse.
6731        // Is this this right policy?
6732        int nStored = storedSigs.length;
6733        int nDevice = deviceSigs.length;
6734
6735        for (int i=0; i < nStored; i++) {
6736            boolean match = false;
6737            for (int j=0; j < nDevice; j++) {
6738                if (storedSigs[i].equals(deviceSigs[j])) {
6739                    match = true;
6740                    break;
6741                }
6742            }
6743            if (!match) {
6744                return false;
6745            }
6746        }
6747        return true;
6748    }
6749
6750    // Used by both incremental and full restore
6751    void restoreWidgetData(String packageName, byte[] widgetData) {
6752        // Apply the restored widget state and generate the ID update for the app
6753        AppWidgetBackupBridge.restoreWidgetState(packageName, widgetData, UserHandle.USER_OWNER);
6754    }
6755
6756    // *****************************
6757    // NEW UNIFIED RESTORE IMPLEMENTATION
6758    // *****************************
6759
6760    // states of the unified-restore state machine
6761    enum UnifiedRestoreState {
6762        INITIAL,
6763        RUNNING_QUEUE,
6764        RESTORE_KEYVALUE,
6765        RESTORE_FULL,
6766        RESTORE_FINISHED,
6767        FINAL
6768    }
6769
6770    class PerformUnifiedRestoreTask implements BackupRestoreTask {
6771        // Transport we're working with to do the restore
6772        private IBackupTransport mTransport;
6773
6774        // Where per-transport saved state goes
6775        File mStateDir;
6776
6777        // Restore observer; may be null
6778        private IRestoreObserver mObserver;
6779
6780        // Token identifying the dataset to the transport
6781        private long mToken;
6782
6783        // When this is a restore-during-install, this is the token identifying the
6784        // operation to the Package Manager, and we must ensure that we let it know
6785        // when we're finished.
6786        private int mPmToken;
6787
6788        // Is this a whole-system restore, i.e. are we establishing a new ancestral
6789        // dataset to base future restore-at-install operations from?
6790        private boolean mIsSystemRestore;
6791
6792        // If this is a single-package restore, what package are we interested in?
6793        private PackageInfo mTargetPackage;
6794
6795        // In all cases, the calculated list of packages that we are trying to restore
6796        private List<PackageInfo> mAcceptSet;
6797
6798        // Our bookkeeping about the ancestral dataset
6799        private PackageManagerBackupAgent mPmAgent;
6800
6801        // Currently-bound backup agent for restore + restoreFinished purposes
6802        private IBackupAgent mAgent;
6803
6804        // What sort of restore we're doing now
6805        private RestoreDescription mRestoreDescription;
6806
6807        // The package we're currently restoring
6808        private PackageInfo mCurrentPackage;
6809
6810        // Widget-related data handled as part of this restore operation
6811        private byte[] mWidgetData;
6812
6813        // Number of apps restored in this pass
6814        private int mCount;
6815
6816        // When did we start?
6817        private long mStartRealtime;
6818
6819        // State machine progress
6820        private UnifiedRestoreState mState;
6821
6822        // How are things going?
6823        private int mStatus;
6824
6825        // Done?
6826        private boolean mFinished;
6827
6828        // Key/value: bookkeeping about staged data and files for agent access
6829        private File mBackupDataName;
6830        private File mStageName;
6831        private File mSavedStateName;
6832        private File mNewStateName;
6833        ParcelFileDescriptor mBackupData;
6834        ParcelFileDescriptor mNewState;
6835
6836        // Invariant: mWakelock is already held, and this task is responsible for
6837        // releasing it at the end of the restore operation.
6838        PerformUnifiedRestoreTask(IBackupTransport transport, IRestoreObserver observer,
6839                long restoreSetToken, PackageInfo targetPackage, int pmToken,
6840                boolean isFullSystemRestore, String[] filterSet) {
6841            mState = UnifiedRestoreState.INITIAL;
6842            mStartRealtime = SystemClock.elapsedRealtime();
6843
6844            mTransport = transport;
6845            mObserver = observer;
6846            mToken = restoreSetToken;
6847            mPmToken = pmToken;
6848            mTargetPackage = targetPackage;
6849            mIsSystemRestore = isFullSystemRestore;
6850            mFinished = false;
6851
6852            if (targetPackage != null) {
6853                // Single package restore
6854                mAcceptSet = new ArrayList<PackageInfo>();
6855                mAcceptSet.add(targetPackage);
6856            } else {
6857                // Everything possible, or a target set
6858                if (filterSet == null) {
6859                    // We want everything and a pony
6860                    List<PackageInfo> apps =
6861                            PackageManagerBackupAgent.getStorableApplications(mPackageManager);
6862                    filterSet = packagesToNames(apps);
6863                    if (DEBUG) {
6864                        Slog.i(TAG, "Full restore; asking for " + filterSet.length + " apps");
6865                    }
6866                }
6867
6868                mAcceptSet = new ArrayList<PackageInfo>(filterSet.length);
6869
6870                // Pro tem, we insist on moving the settings provider package to last place.
6871                // Keep track of whether it's in the list, and bump it down if so.  We also
6872                // want to do the system package itself first if it's called for.
6873                boolean hasSystem = false;
6874                boolean hasSettings = false;
6875                for (int i = 0; i < filterSet.length; i++) {
6876                    try {
6877                        PackageInfo info = mPackageManager.getPackageInfo(filterSet[i], 0);
6878                        if ("android".equals(info.packageName)) {
6879                            hasSystem = true;
6880                            continue;
6881                        }
6882                        if (SETTINGS_PACKAGE.equals(info.packageName)) {
6883                            hasSettings = true;
6884                            continue;
6885                        }
6886
6887                        if (appIsEligibleForBackup(info.applicationInfo)) {
6888                            mAcceptSet.add(info);
6889                        }
6890                    } catch (NameNotFoundException e) {
6891                        // requested package name doesn't exist; ignore it
6892                    }
6893                }
6894                if (hasSystem) {
6895                    try {
6896                        mAcceptSet.add(0, mPackageManager.getPackageInfo("android", 0));
6897                    } catch (NameNotFoundException e) {
6898                        // won't happen; we know a priori that it's valid
6899                    }
6900                }
6901                if (hasSettings) {
6902                    try {
6903                        mAcceptSet.add(mPackageManager.getPackageInfo(SETTINGS_PACKAGE, 0));
6904                    } catch (NameNotFoundException e) {
6905                        // this one is always valid too
6906                    }
6907                }
6908            }
6909
6910            if (MORE_DEBUG) {
6911                Slog.v(TAG, "Restore; accept set size is " + mAcceptSet.size());
6912                for (PackageInfo info : mAcceptSet) {
6913                    Slog.v(TAG, "   " + info.packageName);
6914                }
6915            }
6916        }
6917
6918        private String[] packagesToNames(List<PackageInfo> apps) {
6919            final int N = apps.size();
6920            String[] names = new String[N];
6921            for (int i = 0; i < N; i++) {
6922                names[i] = apps.get(i).packageName;
6923            }
6924            return names;
6925        }
6926
6927        // Execute one tick of whatever state machine the task implements
6928        @Override
6929        public void execute() {
6930            if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step " + mState);
6931            switch (mState) {
6932                case INITIAL:
6933                    startRestore();
6934                    break;
6935
6936                case RUNNING_QUEUE:
6937                    dispatchNextRestore();
6938                    break;
6939
6940                case RESTORE_KEYVALUE:
6941                    restoreKeyValue();
6942                    break;
6943
6944                case RESTORE_FULL:
6945                    restoreFull();
6946                    break;
6947
6948                case RESTORE_FINISHED:
6949                    restoreFinished();
6950                    break;
6951
6952                case FINAL:
6953                    if (!mFinished) finalizeRestore();
6954                    else {
6955                        Slog.e(TAG, "Duplicate finish");
6956                    }
6957                    mFinished = true;
6958                    break;
6959            }
6960        }
6961
6962        /*
6963         * SKETCH OF OPERATION
6964         *
6965         * create one of these PerformUnifiedRestoreTask objects, telling it which
6966         * dataset & transport to address, and then parameters within the restore
6967         * operation: single target package vs many, etc.
6968         *
6969         * 1. transport.startRestore(token, list-of-packages).  If we need @pm@  it is
6970         * always placed first and the settings provider always placed last [for now].
6971         *
6972         * 1a [if we needed @pm@ then nextRestorePackage() and restore the PMBA inline]
6973         *
6974         *   [ state change => RUNNING_QUEUE ]
6975         *
6976         * NOW ITERATE:
6977         *
6978         * { 3. t.nextRestorePackage()
6979         *   4. does the metadata for this package allow us to restore it?
6980         *      does the on-disk app permit us to restore it? [re-check allowBackup etc]
6981         *   5. is this a key/value dataset?  => key/value agent restore
6982         *       [ state change => RESTORE_KEYVALUE ]
6983         *       5a. spin up agent
6984         *       5b. t.getRestoreData() to stage it properly
6985         *       5c. call into agent to perform restore
6986         *       5d. tear down agent
6987         *       [ state change => RUNNING_QUEUE ]
6988         *
6989         *   6. else it's a stream dataset:
6990         *       [ state change => RESTORE_FULL ]
6991         *       6a. instantiate the engine for a stream restore: engine handles agent lifecycles
6992         *       6b. spin off engine runner on separate thread
6993         *       6c. ITERATE getNextFullRestoreDataChunk() and copy data to engine runner socket
6994         *       [ state change => RUNNING_QUEUE ]
6995         * }
6996         *
6997         *   [ state change => FINAL ]
6998         *
6999         * 7. t.finishRestore(), release wakelock, etc.
7000         *
7001         *
7002         */
7003
7004        // state INITIAL : set up for the restore and read the metadata if necessary
7005        private  void startRestore() {
7006            sendStartRestore(mAcceptSet.size());
7007
7008            try {
7009                String transportDir = mTransport.transportDirName();
7010                mStateDir = new File(mBaseStateDir, transportDir);
7011
7012                // Fetch the current metadata from the dataset first
7013                PackageInfo pmPackage = new PackageInfo();
7014                pmPackage.packageName = PACKAGE_MANAGER_SENTINEL;
7015                mAcceptSet.add(0, pmPackage);
7016
7017                PackageInfo[] packages = mAcceptSet.toArray(new PackageInfo[0]);
7018                mStatus = mTransport.startRestore(mToken, packages);
7019                if (mStatus != BackupTransport.TRANSPORT_OK) {
7020                    Slog.e(TAG, "Transport error " + mStatus + "; no restore possible");
7021                    mStatus = BackupTransport.TRANSPORT_ERROR;
7022                    executeNextState(UnifiedRestoreState.FINAL);
7023                    return;
7024                }
7025
7026                RestoreDescription desc = mTransport.nextRestorePackage();
7027                if (desc == null) {
7028                    Slog.e(TAG, "No restore metadata available; halting");
7029                    mStatus = BackupTransport.TRANSPORT_ERROR;
7030                    executeNextState(UnifiedRestoreState.FINAL);
7031                    return;
7032                }
7033                if (!PACKAGE_MANAGER_SENTINEL.equals(desc.getPackageName())) {
7034                    Slog.e(TAG, "Required metadata but got " + desc.getPackageName());
7035                    mStatus = BackupTransport.TRANSPORT_ERROR;
7036                    executeNextState(UnifiedRestoreState.FINAL);
7037                    return;
7038                }
7039
7040                // Pull the Package Manager metadata from the restore set first
7041                mCurrentPackage = new PackageInfo();
7042                mCurrentPackage.packageName = PACKAGE_MANAGER_SENTINEL;
7043                mPmAgent = new PackageManagerBackupAgent(mPackageManager, null);
7044                mAgent = IBackupAgent.Stub.asInterface(mPmAgent.onBind());
7045                if (MORE_DEBUG) {
7046                    Slog.v(TAG, "initiating restore for PMBA");
7047                }
7048                initiateOneRestore(mCurrentPackage, 0);
7049                // The PM agent called operationComplete() already, because our invocation
7050                // of it is process-local and therefore synchronous.  That means that the
7051                // next-state message (RUNNING_QUEUE) is already enqueued.  Only if we're
7052                // unable to proceed with running the queue do we remove that pending
7053                // message and jump straight to the FINAL state.
7054
7055                // Verify that the backup set includes metadata.  If not, we can't do
7056                // signature/version verification etc, so we simply do not proceed with
7057                // the restore operation.
7058                if (!mPmAgent.hasMetadata()) {
7059                    Slog.e(TAG, "No restore metadata available, so not restoring");
7060                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
7061                            PACKAGE_MANAGER_SENTINEL,
7062                            "Package manager restore metadata missing");
7063                    mStatus = BackupTransport.TRANSPORT_ERROR;
7064                    mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
7065                    executeNextState(UnifiedRestoreState.FINAL);
7066                    return;
7067                }
7068
7069                // Success; cache the metadata and continue as expected with the
7070                // next state already enqueued
7071
7072            } catch (RemoteException e) {
7073                // If we lost the transport at any time, halt
7074                Slog.e(TAG, "Unable to contact transport for restore");
7075                mStatus = BackupTransport.TRANSPORT_ERROR;
7076                mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
7077                executeNextState(UnifiedRestoreState.FINAL);
7078                return;
7079            }
7080        }
7081
7082        // state RUNNING_QUEUE : figure out what the next thing to be restored is,
7083        // and fire the appropriate next step
7084        private void dispatchNextRestore() {
7085            UnifiedRestoreState nextState = UnifiedRestoreState.FINAL;
7086            try {
7087                mRestoreDescription = mTransport.nextRestorePackage();
7088                final String pkgName = (mRestoreDescription != null)
7089                        ? mRestoreDescription.getPackageName() : null;
7090                if (pkgName == null) {
7091                    Slog.e(TAG, "Failure getting next package name");
7092                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
7093                    nextState = UnifiedRestoreState.FINAL;
7094                    return;
7095                } else if (mRestoreDescription == RestoreDescription.NO_MORE_PACKAGES) {
7096                    // Yay we've reached the end cleanly
7097                    if (DEBUG) {
7098                        Slog.v(TAG, "No more packages; finishing restore");
7099                    }
7100                    int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
7101                    EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
7102                    nextState = UnifiedRestoreState.FINAL;
7103                    return;
7104                }
7105
7106                if (DEBUG) {
7107                    Slog.i(TAG, "Next restore package: " + mRestoreDescription);
7108                }
7109                sendOnRestorePackage(pkgName);
7110
7111                Metadata metaInfo = mPmAgent.getRestoredMetadata(pkgName);
7112                if (metaInfo == null) {
7113                    Slog.e(TAG, "No metadata for " + pkgName);
7114                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, pkgName,
7115                            "Package metadata missing");
7116                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
7117                    return;
7118                }
7119
7120                try {
7121                    mCurrentPackage = mPackageManager.getPackageInfo(
7122                            pkgName, PackageManager.GET_SIGNATURES);
7123                } catch (NameNotFoundException e) {
7124                    // Whoops, we thought we could restore this package but it
7125                    // turns out not to be present.  Skip it.
7126                    Slog.e(TAG, "Package not present: " + pkgName);
7127                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, pkgName,
7128                            "Package missing on device");
7129                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
7130                    return;
7131                }
7132
7133                if (metaInfo.versionCode > mCurrentPackage.versionCode) {
7134                    // Data is from a "newer" version of the app than we have currently
7135                    // installed.  If the app has not declared that it is prepared to
7136                    // handle this case, we do not attempt the restore.
7137                    if ((mCurrentPackage.applicationInfo.flags
7138                            & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
7139                        String message = "Version " + metaInfo.versionCode
7140                                + " > installed version " + mCurrentPackage.versionCode;
7141                        Slog.w(TAG, "Package " + pkgName + ": " + message);
7142                        EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
7143                                pkgName, message);
7144                        nextState = UnifiedRestoreState.RUNNING_QUEUE;
7145                        return;
7146                    } else {
7147                        if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
7148                                + " > installed " + mCurrentPackage.versionCode
7149                                + " but restoreAnyVersion");
7150                    }
7151                }
7152
7153                if (DEBUG) Slog.v(TAG, "Package " + pkgName
7154                        + " restore version [" + metaInfo.versionCode
7155                        + "] is compatible with installed version ["
7156                        + mCurrentPackage.versionCode + "]");
7157
7158                // Reset per-package preconditions and fire the appropriate next state
7159                mWidgetData = null;
7160                final int type = mRestoreDescription.getDataType();
7161                if (type == RestoreDescription.TYPE_KEY_VALUE) {
7162                    nextState = UnifiedRestoreState.RESTORE_KEYVALUE;
7163                } else if (type == RestoreDescription.TYPE_FULL_STREAM) {
7164                    nextState = UnifiedRestoreState.RESTORE_FULL;
7165                } else {
7166                    // Unknown restore type; ignore this package and move on
7167                    Slog.e(TAG, "Unrecognized restore type " + type);
7168                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
7169                    return;
7170                }
7171            } catch (RemoteException e) {
7172                Slog.e(TAG, "Can't get next target from transport; ending restore");
7173                EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
7174                nextState = UnifiedRestoreState.FINAL;
7175                return;
7176            } finally {
7177                executeNextState(nextState);
7178            }
7179        }
7180
7181        // state RESTORE_KEYVALUE : restore one package via key/value API set
7182        private void restoreKeyValue() {
7183            // Initiating the restore will pass responsibility for the state machine's
7184            // progress to the agent callback, so we do not always execute the
7185            // next state here.
7186            final String packageName = mCurrentPackage.packageName;
7187            // Validate some semantic requirements that apply in this way
7188            // only to the key/value restore API flow
7189            if (mCurrentPackage.applicationInfo.backupAgentName == null
7190                    || "".equals(mCurrentPackage.applicationInfo.backupAgentName)) {
7191                if (DEBUG) {
7192                    Slog.i(TAG, "Data exists for package " + packageName
7193                            + " but app has no agent; skipping");
7194                }
7195                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
7196                        "Package has no agent");
7197                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
7198                return;
7199            }
7200
7201            Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
7202            if (!signaturesMatch(metaInfo.sigHashes, mCurrentPackage)) {
7203                Slog.w(TAG, "Signature mismatch restoring " + packageName);
7204                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
7205                        "Signature mismatch");
7206                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
7207                return;
7208            }
7209
7210            // Good to go!  Set up and bind the agent...
7211            mAgent = bindToAgentSynchronous(
7212                    mCurrentPackage.applicationInfo,
7213                    IApplicationThread.BACKUP_MODE_INCREMENTAL);
7214            if (mAgent == null) {
7215                Slog.w(TAG, "Can't find backup agent for " + packageName);
7216                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
7217                        "Restore agent missing");
7218                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
7219                return;
7220            }
7221
7222            // And then finally start the restore on this agent
7223            try {
7224                initiateOneRestore(mCurrentPackage, metaInfo.versionCode);
7225                ++mCount;
7226            } catch (Exception e) {
7227                Slog.e(TAG, "Error when attempting restore: " + e.toString());
7228                keyValueAgentErrorCleanup();
7229                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
7230            }
7231        }
7232
7233        // Guts of a key/value restore operation
7234        void initiateOneRestore(PackageInfo app, int appVersionCode) {
7235            final String packageName = app.packageName;
7236
7237            if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
7238
7239            // !!! TODO: get the dirs from the transport
7240            mBackupDataName = new File(mDataDir, packageName + ".restore");
7241            mStageName = new File(mDataDir, packageName + ".stage");
7242            mNewStateName = new File(mStateDir, packageName + ".new");
7243            mSavedStateName = new File(mStateDir, packageName);
7244
7245            // don't stage the 'android' package where the wallpaper data lives.  this is
7246            // an optimization: we know there's no widget data hosted/published by that
7247            // package, and this way we avoid doing a spurious copy of MB-sized wallpaper
7248            // data following the download.
7249            boolean staging = !packageName.equals("android");
7250            ParcelFileDescriptor stage;
7251            File downloadFile = (staging) ? mStageName : mBackupDataName;
7252
7253            final int token = generateToken();
7254            try {
7255                // Run the transport's restore pass
7256                stage = ParcelFileDescriptor.open(downloadFile,
7257                        ParcelFileDescriptor.MODE_READ_WRITE |
7258                        ParcelFileDescriptor.MODE_CREATE |
7259                        ParcelFileDescriptor.MODE_TRUNCATE);
7260
7261                if (!SELinux.restorecon(mBackupDataName)) {
7262                    Slog.e(TAG, "SElinux restorecon failed for " + downloadFile);
7263                }
7264
7265                if (mTransport.getRestoreData(stage) != BackupTransport.TRANSPORT_OK) {
7266                    // Transport-level failure, so we wind everything up and
7267                    // terminate the restore operation.
7268                    Slog.e(TAG, "Error getting restore data for " + packageName);
7269                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
7270                    stage.close();
7271                    downloadFile.delete();
7272                    executeNextState(UnifiedRestoreState.FINAL);
7273                    return;
7274                }
7275
7276                // We have the data from the transport. Now we extract and strip
7277                // any per-package metadata (typically widget-related information)
7278                // if appropriate
7279                if (staging) {
7280                    stage.close();
7281                    stage = ParcelFileDescriptor.open(downloadFile,
7282                            ParcelFileDescriptor.MODE_READ_ONLY);
7283
7284                    mBackupData = ParcelFileDescriptor.open(mBackupDataName,
7285                            ParcelFileDescriptor.MODE_READ_WRITE |
7286                            ParcelFileDescriptor.MODE_CREATE |
7287                            ParcelFileDescriptor.MODE_TRUNCATE);
7288
7289                    BackupDataInput in = new BackupDataInput(stage.getFileDescriptor());
7290                    BackupDataOutput out = new BackupDataOutput(mBackupData.getFileDescriptor());
7291                    byte[] buffer = new byte[8192]; // will grow when needed
7292                    while (in.readNextHeader()) {
7293                        final String key = in.getKey();
7294                        final int size = in.getDataSize();
7295
7296                        // is this a special key?
7297                        if (key.equals(KEY_WIDGET_STATE)) {
7298                            if (DEBUG) {
7299                                Slog.i(TAG, "Restoring widget state for " + packageName);
7300                            }
7301                            mWidgetData = new byte[size];
7302                            in.readEntityData(mWidgetData, 0, size);
7303                        } else {
7304                            if (size > buffer.length) {
7305                                buffer = new byte[size];
7306                            }
7307                            in.readEntityData(buffer, 0, size);
7308                            out.writeEntityHeader(key, size);
7309                            out.writeEntityData(buffer, size);
7310                        }
7311                    }
7312
7313                    mBackupData.close();
7314                }
7315
7316                // Okay, we have the data.  Now have the agent do the restore.
7317                stage.close();
7318                mBackupData = ParcelFileDescriptor.open(mBackupDataName,
7319                        ParcelFileDescriptor.MODE_READ_ONLY);
7320
7321                mNewState = ParcelFileDescriptor.open(mNewStateName,
7322                        ParcelFileDescriptor.MODE_READ_WRITE |
7323                        ParcelFileDescriptor.MODE_CREATE |
7324                        ParcelFileDescriptor.MODE_TRUNCATE);
7325
7326                // Kick off the restore, checking for hung agents.  The timeout or
7327                // the operationComplete() callback will schedule the next step,
7328                // so we do not do that here.
7329                prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
7330                mAgent.doRestore(mBackupData, appVersionCode, mNewState,
7331                        token, mBackupManagerBinder);
7332            } catch (Exception e) {
7333                Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
7334                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
7335                        packageName, e.toString());
7336                keyValueAgentErrorCleanup();    // clears any pending timeout messages as well
7337
7338                // After a restore failure we go back to running the queue.  If there
7339                // are no more packages to be restored that will be handled by the
7340                // next step.
7341                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
7342            }
7343        }
7344
7345        // state RESTORE_FULL : restore one package via streaming engine
7346        private void restoreFull() {
7347            // None of this can run on the work looper here, so we spin asynchronous
7348            // work like this:
7349            //
7350            //   StreamFeederThread: read data from mTransport.getNextFullRestoreDataChunk()
7351            //                       write it into the pipe to the engine
7352            //   EngineThread: FullRestoreEngine thread communicating with the target app
7353            //
7354            // When finished, StreamFeederThread executes next state as appropriate on the
7355            // backup looper, and the overall unified restore task resumes
7356            try {
7357                StreamFeederThread feeder = new StreamFeederThread();
7358                if (DEBUG) {
7359                    Slog.i(TAG, "Spinning threads for stream restore of "
7360                            + mCurrentPackage.packageName);
7361                }
7362                new Thread(feeder, "unified-stream-feeder").start();
7363
7364                // At this point the feeder is responsible for advancing the restore
7365                // state, so we're done here.
7366            } catch (IOException e) {
7367                // Unable to instantiate the feeder thread -- we need to bail on the
7368                // current target.  We haven't asked the transport for data yet, though,
7369                // so we can do that simply by going back to running the restore queue.
7370                Slog.e(TAG, "Unable to construct pipes for stream restore!");
7371                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
7372            }
7373        }
7374
7375        // state RESTORE_FINISHED : provide the "no more data" signpost callback at the end
7376        private void restoreFinished() {
7377            try {
7378                final int token = generateToken();
7379                prepareOperationTimeout(token, TIMEOUT_RESTORE_FINISHED_INTERVAL, this);
7380                mAgent.doRestoreFinished(token, mBackupManagerBinder);
7381                // If we get this far, the callback or timeout will schedule the
7382                // next restore state, so we're done
7383            } catch (Exception e) {
7384                Slog.e(TAG, "Unable to finalize restore of " + mCurrentPackage.packageName);
7385                executeNextState(UnifiedRestoreState.FINAL);
7386            }
7387        }
7388
7389        class StreamFeederThread extends RestoreEngine implements Runnable {
7390            final String TAG = "StreamFeederThread";
7391            FullRestoreEngine mEngine;
7392
7393            // pipe through which we read data from the transport. [0] read, [1] write
7394            ParcelFileDescriptor[] mTransportPipes;
7395
7396            // pipe through which the engine will read data.  [0] read, [1] write
7397            ParcelFileDescriptor[] mEnginePipes;
7398
7399            public StreamFeederThread() throws IOException {
7400                mTransportPipes = ParcelFileDescriptor.createPipe();
7401                mEnginePipes = ParcelFileDescriptor.createPipe();
7402                setRunning(true);
7403            }
7404
7405            @Override
7406            public void run() {
7407                UnifiedRestoreState nextState = UnifiedRestoreState.RUNNING_QUEUE;
7408                int status = BackupTransport.TRANSPORT_OK;
7409
7410                EventLog.writeEvent(EventLogTags.FULL_RESTORE_PACKAGE,
7411                        mCurrentPackage.packageName);
7412
7413                mEngine = new FullRestoreEngine(null, mCurrentPackage, false, false);
7414                EngineThread eThread = new EngineThread(mEngine, mEnginePipes[0]);
7415
7416                ParcelFileDescriptor eWriteEnd = mEnginePipes[1];
7417                ParcelFileDescriptor tReadEnd = mTransportPipes[0];
7418                ParcelFileDescriptor tWriteEnd = mTransportPipes[1];
7419
7420                int bufferSize = 32 * 1024;
7421                byte[] buffer = new byte[bufferSize];
7422                FileOutputStream engineOut = new FileOutputStream(eWriteEnd.getFileDescriptor());
7423                FileInputStream transportIn = new FileInputStream(tReadEnd.getFileDescriptor());
7424
7425                // spin up the engine and start moving data to it
7426                new Thread(eThread, "unified-restore-engine").start();
7427
7428                try {
7429                    while (status == BackupTransport.TRANSPORT_OK) {
7430                        // have the transport write some of the restoring data to us
7431                        int result = mTransport.getNextFullRestoreDataChunk(tWriteEnd);
7432                        if (result > 0) {
7433                            // The transport wrote this many bytes of restore data to the
7434                            // pipe, so pass it along to the engine.
7435                            if (MORE_DEBUG) {
7436                                Slog.v(TAG, "  <- transport provided chunk size " + result);
7437                            }
7438                            if (result > bufferSize) {
7439                                bufferSize = result;
7440                                buffer = new byte[bufferSize];
7441                            }
7442                            int toCopy = result;
7443                            while (toCopy > 0) {
7444                                int n = transportIn.read(buffer, 0, toCopy);
7445                                engineOut.write(buffer, 0, n);
7446                                toCopy -= n;
7447                                if (MORE_DEBUG) {
7448                                    Slog.v(TAG, "  -> wrote " + n + " to engine, left=" + toCopy);
7449                                }
7450                            }
7451                        } else if (result == BackupTransport.NO_MORE_DATA) {
7452                            // Clean finish.  Wind up and we're done!
7453                            if (MORE_DEBUG) {
7454                                Slog.i(TAG, "Got clean full-restore EOF for "
7455                                        + mCurrentPackage.packageName);
7456                            }
7457                            status = BackupTransport.TRANSPORT_OK;
7458                            break;
7459                        } else {
7460                            // Transport reported some sort of failure; the fall-through
7461                            // handling will deal properly with that.
7462                            Slog.e(TAG, "Error " + result + " streaming restore for "
7463                                    + mCurrentPackage.packageName);
7464                            EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
7465                            status = result;
7466                        }
7467                    }
7468                    if (MORE_DEBUG) Slog.v(TAG, "Done copying to engine, falling through");
7469                } catch (IOException e) {
7470                    // We lost our ability to communicate via the pipes.  That's worrying
7471                    // but potentially recoverable; abandon this package's restore but
7472                    // carry on with the next restore target.
7473                    Slog.e(TAG, "Unable to route data for restore");
7474                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
7475                            mCurrentPackage.packageName, "I/O error on pipes");
7476                    status = BackupTransport.AGENT_ERROR;
7477                } catch (RemoteException e) {
7478                    // The transport went away; terminate the whole operation.  Closing
7479                    // the sockets will wake up the engine and it will then tidy up the
7480                    // remote end.
7481                    Slog.e(TAG, "Transport failed during restore");
7482                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
7483                    status = BackupTransport.TRANSPORT_ERROR;
7484                } finally {
7485                    // Close the transport pipes and *our* end of the engine pipe,
7486                    // but leave the engine thread's end open so that it properly
7487                    // hits EOF and winds up its operations.
7488                    IoUtils.closeQuietly(mEnginePipes[1]);
7489                    IoUtils.closeQuietly(mTransportPipes[0]);
7490                    IoUtils.closeQuietly(mTransportPipes[1]);
7491
7492                    // Don't proceed until the engine has torn down the agent etc
7493                    eThread.waitForResult();
7494
7495                    if (MORE_DEBUG) {
7496                        Slog.i(TAG, "engine thread finished; proceeding");
7497                    }
7498
7499                    // Now we're really done with this one too
7500                    IoUtils.closeQuietly(mEnginePipes[0]);
7501
7502                    // If we hit a transport-level error, we are done with everything;
7503                    // if we hit an agent error we just go back to running the queue.
7504                    if (status == BackupTransport.TRANSPORT_OK) {
7505                        // Clean finish, so just carry on
7506                        nextState = UnifiedRestoreState.RUNNING_QUEUE;
7507                    } else {
7508                        // Something went wrong somewhere.  Whether it was at the transport
7509                        // level is immaterial; we need to tell the transport to bail
7510                        try {
7511                            mTransport.abortFullRestore();
7512                        } catch (RemoteException e) {
7513                            // transport itself is dead; make sure we handle this as a
7514                            // fatal error
7515                            status = BackupTransport.TRANSPORT_ERROR;
7516                        }
7517
7518                        // We also need to wipe the current target's data, as it's probably
7519                        // in an incoherent state.
7520                        clearApplicationDataSynchronous(mCurrentPackage.packageName);
7521
7522                        // Schedule the next state based on the nature of our failure
7523                        if (status == BackupTransport.TRANSPORT_ERROR) {
7524                            nextState = UnifiedRestoreState.FINAL;
7525                        } else {
7526                            nextState = UnifiedRestoreState.RUNNING_QUEUE;
7527                        }
7528                    }
7529                    executeNextState(nextState);
7530                    setRunning(false);
7531                }
7532            }
7533
7534        }
7535
7536        class EngineThread implements Runnable {
7537            FullRestoreEngine mEngine;
7538            FileInputStream mEngineStream;
7539
7540            EngineThread(FullRestoreEngine engine, ParcelFileDescriptor engineSocket) {
7541                mEngine = engine;
7542                engine.setRunning(true);
7543                mEngineStream = new FileInputStream(engineSocket.getFileDescriptor());
7544            }
7545
7546            public boolean isRunning() {
7547                return mEngine.isRunning();
7548            }
7549
7550            public int waitForResult() {
7551                return mEngine.waitForResult();
7552            }
7553
7554            @Override
7555            public void run() {
7556                while (mEngine.isRunning()) {
7557                    mEngine.restoreOneFile(mEngineStream);
7558                }
7559            }
7560        }
7561
7562        // state FINAL : tear everything down and we're done.
7563        private void finalizeRestore() {
7564            if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
7565
7566            try {
7567                mTransport.finishRestore();
7568            } catch (Exception e) {
7569                Slog.e(TAG, "Error finishing restore", e);
7570            }
7571
7572            // Tell the observer we're done
7573            if (mObserver != null) {
7574                try {
7575                    mObserver.restoreFinished(mStatus);
7576                } catch (RemoteException e) {
7577                    Slog.d(TAG, "Restore observer died at restoreFinished");
7578                }
7579            }
7580
7581            // Clear any ongoing session timeout.
7582            mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
7583
7584            // If we have a PM token, we must under all circumstances be sure to
7585            // handshake when we've finished.
7586            if (mPmToken > 0) {
7587                if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
7588                try {
7589                    mPackageManagerBinder.finishPackageInstall(mPmToken);
7590                } catch (RemoteException e) { /* can't happen */ }
7591            } else {
7592                // We were invoked via an active restore session, not by the Package
7593                // Manager, so start up the session timeout again.
7594                mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
7595                        TIMEOUT_RESTORE_INTERVAL);
7596            }
7597
7598            // Kick off any work that may be needed regarding app widget restores
7599            AppWidgetBackupBridge.restoreFinished(UserHandle.USER_OWNER);
7600
7601            // If this was a full-system restore, record the ancestral
7602            // dataset information
7603            if (mIsSystemRestore) {
7604                mAncestralPackages = mPmAgent.getRestoredPackages();
7605                mAncestralToken = mToken;
7606                writeRestoreTokens();
7607            }
7608
7609            // done; we can finally release the wakelock and be legitimately done.
7610            Slog.i(TAG, "Restore complete.");
7611            mWakelock.release();
7612        }
7613
7614        void keyValueAgentErrorCleanup() {
7615            // If the agent fails restore, it might have put the app's data
7616            // into an incoherent state.  For consistency we wipe its data
7617            // again in this case before continuing with normal teardown
7618            clearApplicationDataSynchronous(mCurrentPackage.packageName);
7619            keyValueAgentCleanup();
7620        }
7621
7622        void keyValueAgentCleanup() {
7623            mBackupDataName.delete();
7624            mStageName.delete();
7625            try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
7626            try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
7627            mBackupData = mNewState = null;
7628
7629            // if everything went okay, remember the recorded state now
7630            //
7631            // !!! TODO: the restored data could be migrated on the server
7632            // side into the current dataset.  In that case the new state file
7633            // we just created would reflect the data already extant in the
7634            // backend, so there'd be nothing more to do.  Until that happens,
7635            // however, we need to make sure that we record the data to the
7636            // current backend dataset.  (Yes, this means shipping the data over
7637            // the wire in both directions.  That's bad, but consistency comes
7638            // first, then efficiency.)  Once we introduce server-side data
7639            // migration to the newly-restored device's dataset, we will change
7640            // the following from a discard of the newly-written state to the
7641            // "correct" operation of renaming into the canonical state blob.
7642            mNewStateName.delete();                      // TODO: remove; see above comment
7643            //mNewStateName.renameTo(mSavedStateName);   // TODO: replace with this
7644
7645            // If this wasn't the PM pseudopackage, tear down the agent side
7646            if (mCurrentPackage.applicationInfo != null) {
7647                // unbind and tidy up even on timeout or failure
7648                try {
7649                    mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
7650
7651                    // The agent was probably running with a stub Application object,
7652                    // which isn't a valid run mode for the main app logic.  Shut
7653                    // down the app so that next time it's launched, it gets the
7654                    // usual full initialization.  Note that this is only done for
7655                    // full-system restores: when a single app has requested a restore,
7656                    // it is explicitly not killed following that operation.
7657                    if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
7658                            & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
7659                        if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
7660                                + mCurrentPackage.applicationInfo.processName);
7661                        mActivityManager.killApplicationProcess(
7662                                mCurrentPackage.applicationInfo.processName,
7663                                mCurrentPackage.applicationInfo.uid);
7664                    }
7665                } catch (RemoteException e) {
7666                    // can't happen; we run in the same process as the activity manager
7667                }
7668            }
7669
7670            // The caller is responsible for reestablishing the state machine; our
7671            // responsibility here is to clear the decks for whatever comes next.
7672            mBackupHandler.removeMessages(MSG_TIMEOUT, this);
7673            synchronized (mCurrentOpLock) {
7674                mCurrentOperations.clear();
7675            }
7676        }
7677
7678        @Override
7679        public void operationComplete() {
7680            if (MORE_DEBUG) {
7681                Slog.i(TAG, "operationComplete() during restore: target="
7682                        + mCurrentPackage.packageName
7683                        + " state=" + mState);
7684            }
7685
7686            final UnifiedRestoreState nextState;
7687            switch (mState) {
7688                case INITIAL:
7689                    // We've just (manually) restored the PMBA.  It doesn't need the
7690                    // additional restore-finished callback so we bypass that and go
7691                    // directly to running the queue.
7692                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
7693                    break;
7694
7695                case RESTORE_KEYVALUE:
7696                case RESTORE_FULL: {
7697                    // Okay, we've just heard back from the agent that it's done with
7698                    // the restore itself.  We now have to send the same agent its
7699                    // doRestoreFinished() callback, so roll into that state.
7700                    nextState = UnifiedRestoreState.RESTORE_FINISHED;
7701                    break;
7702                }
7703
7704                case RESTORE_FINISHED: {
7705                    // Okay, we're done with this package.  Tidy up and go on to the next
7706                    // app in the queue.
7707                    int size = (int) mBackupDataName.length();
7708                    EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE,
7709                            mCurrentPackage.packageName, size);
7710
7711                    // Just go back to running the restore queue
7712                    keyValueAgentCleanup();
7713
7714                    // If there was widget state associated with this app, get the OS to
7715                    // incorporate it into current bookeeping and then pass that along to
7716                    // the app as part of the restore-time work.
7717                    if (mWidgetData != null) {
7718                        restoreWidgetData(mCurrentPackage.packageName, mWidgetData);
7719                    }
7720
7721                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
7722                    break;
7723                }
7724
7725                default: {
7726                    // Some kind of horrible semantic error; we're in an unexpected state.
7727                    // Back off hard and wind up.
7728                    Slog.e(TAG, "Unexpected restore callback into state " + mState);
7729                    keyValueAgentErrorCleanup();
7730                    nextState = UnifiedRestoreState.FINAL;
7731                    break;
7732                }
7733            }
7734
7735            executeNextState(nextState);
7736        }
7737
7738        // A call to agent.doRestore() or agent.doRestoreFinished() has timed out
7739        @Override
7740        public void handleTimeout() {
7741            Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
7742            EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
7743                    mCurrentPackage.packageName, "restore timeout");
7744            // Handle like an agent that threw on invocation: wipe it and go on to the next
7745            keyValueAgentErrorCleanup();
7746            executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
7747        }
7748
7749        void executeNextState(UnifiedRestoreState nextState) {
7750            if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
7751                    + this + " nextState=" + nextState);
7752            mState = nextState;
7753            Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
7754            mBackupHandler.sendMessage(msg);
7755        }
7756
7757        // restore observer support
7758        void sendStartRestore(int numPackages) {
7759            if (mObserver != null) {
7760                try {
7761                    mObserver.restoreStarting(numPackages);
7762                } catch (RemoteException e) {
7763                    Slog.w(TAG, "Restore observer went away: startRestore");
7764                    mObserver = null;
7765                }
7766            }
7767        }
7768
7769        void sendOnRestorePackage(String name) {
7770            if (mObserver != null) {
7771                if (mObserver != null) {
7772                    try {
7773                        mObserver.onUpdate(mCount, name);
7774                    } catch (RemoteException e) {
7775                        Slog.d(TAG, "Restore observer died in onUpdate");
7776                        mObserver = null;
7777                    }
7778                }
7779            }
7780        }
7781
7782        void sendEndRestore() {
7783            if (mObserver != null) {
7784                try {
7785                    mObserver.restoreFinished(mStatus);
7786                } catch (RemoteException e) {
7787                    Slog.w(TAG, "Restore observer went away: endRestore");
7788                    mObserver = null;
7789                }
7790            }
7791        }
7792    }
7793
7794    class PerformClearTask implements Runnable {
7795        IBackupTransport mTransport;
7796        PackageInfo mPackage;
7797
7798        PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
7799            mTransport = transport;
7800            mPackage = packageInfo;
7801        }
7802
7803        public void run() {
7804            try {
7805                // Clear the on-device backup state to ensure a full backup next time
7806                File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
7807                File stateFile = new File(stateDir, mPackage.packageName);
7808                stateFile.delete();
7809
7810                // Tell the transport to remove all the persistent storage for the app
7811                // TODO - need to handle failures
7812                mTransport.clearBackupData(mPackage);
7813            } catch (RemoteException e) {
7814                // can't happen; the transport is local
7815            } catch (Exception e) {
7816                Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
7817            } finally {
7818                try {
7819                    // TODO - need to handle failures
7820                    mTransport.finishBackup();
7821                } catch (RemoteException e) {
7822                    // can't happen; the transport is local
7823                }
7824
7825                // Last but not least, release the cpu
7826                mWakelock.release();
7827            }
7828        }
7829    }
7830
7831    class PerformInitializeTask implements Runnable {
7832        HashSet<String> mQueue;
7833
7834        PerformInitializeTask(HashSet<String> transportNames) {
7835            mQueue = transportNames;
7836        }
7837
7838        public void run() {
7839            try {
7840                for (String transportName : mQueue) {
7841                    IBackupTransport transport = getTransport(transportName);
7842                    if (transport == null) {
7843                        Slog.e(TAG, "Requested init for " + transportName + " but not found");
7844                        continue;
7845                    }
7846
7847                    Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
7848                    EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
7849                    long startRealtime = SystemClock.elapsedRealtime();
7850                    int status = transport.initializeDevice();
7851
7852                    if (status == BackupTransport.TRANSPORT_OK) {
7853                        status = transport.finishBackup();
7854                    }
7855
7856                    // Okay, the wipe really happened.  Clean up our local bookkeeping.
7857                    if (status == BackupTransport.TRANSPORT_OK) {
7858                        Slog.i(TAG, "Device init successful");
7859                        int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
7860                        EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
7861                        resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
7862                        EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
7863                        synchronized (mQueueLock) {
7864                            recordInitPendingLocked(false, transportName);
7865                        }
7866                    } else {
7867                        // If this didn't work, requeue this one and try again
7868                        // after a suitable interval
7869                        Slog.e(TAG, "Transport error in initializeDevice()");
7870                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
7871                        synchronized (mQueueLock) {
7872                            recordInitPendingLocked(true, transportName);
7873                        }
7874                        // do this via another alarm to make sure of the wakelock states
7875                        long delay = transport.requestBackupTime();
7876                        if (DEBUG) Slog.w(TAG, "init failed on "
7877                                + transportName + " resched in " + delay);
7878                        mAlarmManager.set(AlarmManager.RTC_WAKEUP,
7879                                System.currentTimeMillis() + delay, mRunInitIntent);
7880                    }
7881                }
7882            } catch (RemoteException e) {
7883                // can't happen; the transports are local
7884            } catch (Exception e) {
7885                Slog.e(TAG, "Unexpected error performing init", e);
7886            } finally {
7887                // Done; release the wakelock
7888                mWakelock.release();
7889            }
7890        }
7891    }
7892
7893    private void dataChangedImpl(String packageName) {
7894        HashSet<String> targets = dataChangedTargets(packageName);
7895        dataChangedImpl(packageName, targets);
7896    }
7897
7898    private void dataChangedImpl(String packageName, HashSet<String> targets) {
7899        // Record that we need a backup pass for the caller.  Since multiple callers
7900        // may share a uid, we need to note all candidates within that uid and schedule
7901        // a backup pass for each of them.
7902        EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
7903
7904        if (targets == null) {
7905            Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
7906                   + " uid=" + Binder.getCallingUid());
7907            return;
7908        }
7909
7910        synchronized (mQueueLock) {
7911            // Note that this client has made data changes that need to be backed up
7912            if (targets.contains(packageName)) {
7913                // Add the caller to the set of pending backups.  If there is
7914                // one already there, then overwrite it, but no harm done.
7915                BackupRequest req = new BackupRequest(packageName);
7916                if (mPendingBackups.put(packageName, req) == null) {
7917                    if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
7918
7919                    // Journal this request in case of crash.  The put()
7920                    // operation returned null when this package was not already
7921                    // in the set; we want to avoid touching the disk redundantly.
7922                    writeToJournalLocked(packageName);
7923
7924                    if (MORE_DEBUG) {
7925                        int numKeys = mPendingBackups.size();
7926                        Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
7927                        for (BackupRequest b : mPendingBackups.values()) {
7928                            Slog.d(TAG, "    + " + b);
7929                        }
7930                    }
7931                }
7932            }
7933        }
7934    }
7935
7936    // Note: packageName is currently unused, but may be in the future
7937    private HashSet<String> dataChangedTargets(String packageName) {
7938        // If the caller does not hold the BACKUP permission, it can only request a
7939        // backup of its own data.
7940        if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
7941                Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
7942            synchronized (mBackupParticipants) {
7943                return mBackupParticipants.get(Binder.getCallingUid());
7944            }
7945        }
7946
7947        // a caller with full permission can ask to back up any participating app
7948        // !!! TODO: allow backup of ANY app?
7949        HashSet<String> targets = new HashSet<String>();
7950        synchronized (mBackupParticipants) {
7951            int N = mBackupParticipants.size();
7952            for (int i = 0; i < N; i++) {
7953                HashSet<String> s = mBackupParticipants.valueAt(i);
7954                if (s != null) {
7955                    targets.addAll(s);
7956                }
7957            }
7958        }
7959        return targets;
7960    }
7961
7962    private void writeToJournalLocked(String str) {
7963        RandomAccessFile out = null;
7964        try {
7965            if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
7966            out = new RandomAccessFile(mJournal, "rws");
7967            out.seek(out.length());
7968            out.writeUTF(str);
7969        } catch (IOException e) {
7970            Slog.e(TAG, "Can't write " + str + " to backup journal", e);
7971            mJournal = null;
7972        } finally {
7973            try { if (out != null) out.close(); } catch (IOException e) {}
7974        }
7975    }
7976
7977    // ----- IBackupManager binder interface -----
7978
7979    public void dataChanged(final String packageName) {
7980        final int callingUserHandle = UserHandle.getCallingUserId();
7981        if (callingUserHandle != UserHandle.USER_OWNER) {
7982            // App is running under a non-owner user profile.  For now, we do not back
7983            // up data from secondary user profiles.
7984            // TODO: backups for all user profiles.
7985            if (MORE_DEBUG) {
7986                Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
7987                        + callingUserHandle);
7988            }
7989            return;
7990        }
7991
7992        final HashSet<String> targets = dataChangedTargets(packageName);
7993        if (targets == null) {
7994            Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
7995                   + " uid=" + Binder.getCallingUid());
7996            return;
7997        }
7998
7999        mBackupHandler.post(new Runnable() {
8000                public void run() {
8001                    dataChangedImpl(packageName, targets);
8002                }
8003            });
8004    }
8005
8006    // Clear the given package's backup data from the current transport
8007    public void clearBackupData(String transportName, String packageName) {
8008        if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName + " on " + transportName);
8009        PackageInfo info;
8010        try {
8011            info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
8012        } catch (NameNotFoundException e) {
8013            Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
8014            return;
8015        }
8016
8017        // If the caller does not hold the BACKUP permission, it can only request a
8018        // wipe of its own backed-up data.
8019        HashSet<String> apps;
8020        if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
8021                Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
8022            apps = mBackupParticipants.get(Binder.getCallingUid());
8023        } else {
8024            // a caller with full permission can ask to back up any participating app
8025            // !!! TODO: allow data-clear of ANY app?
8026            if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
8027            apps = new HashSet<String>();
8028            int N = mBackupParticipants.size();
8029            for (int i = 0; i < N; i++) {
8030                HashSet<String> s = mBackupParticipants.valueAt(i);
8031                if (s != null) {
8032                    apps.addAll(s);
8033                }
8034            }
8035        }
8036
8037        // Is the given app an available participant?
8038        if (apps.contains(packageName)) {
8039            // found it; fire off the clear request
8040            if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
8041            mBackupHandler.removeMessages(MSG_RETRY_CLEAR);
8042            synchronized (mQueueLock) {
8043                final IBackupTransport transport = getTransport(transportName);
8044                if (transport == null) {
8045                    // transport is currently unavailable -- make sure to retry
8046                    Message msg = mBackupHandler.obtainMessage(MSG_RETRY_CLEAR,
8047                            new ClearRetryParams(transportName, packageName));
8048                    mBackupHandler.sendMessageDelayed(msg, TRANSPORT_RETRY_INTERVAL);
8049                    return;
8050                }
8051                long oldId = Binder.clearCallingIdentity();
8052                mWakelock.acquire();
8053                Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
8054                        new ClearParams(transport, info));
8055                mBackupHandler.sendMessage(msg);
8056                Binder.restoreCallingIdentity(oldId);
8057            }
8058        }
8059    }
8060
8061    // Run a backup pass immediately for any applications that have declared
8062    // that they have pending updates.
8063    public void backupNow() {
8064        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
8065
8066        if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
8067        synchronized (mQueueLock) {
8068            // Because the alarms we are using can jitter, and we want an *immediate*
8069            // backup pass to happen, we restart the timer beginning with "next time,"
8070            // then manually fire the backup trigger intent ourselves.
8071            startBackupAlarmsLocked(BACKUP_INTERVAL);
8072            try {
8073                mRunBackupIntent.send();
8074            } catch (PendingIntent.CanceledException e) {
8075                // should never happen
8076                Slog.e(TAG, "run-backup intent cancelled!");
8077            }
8078        }
8079    }
8080
8081    boolean deviceIsProvisioned() {
8082        final ContentResolver resolver = mContext.getContentResolver();
8083        return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
8084    }
8085
8086    // Run a *full* backup pass for the given packages, writing the resulting data stream
8087    // to the supplied file descriptor.  This method is synchronous and does not return
8088    // to the caller until the backup has been completed.
8089    //
8090    // This is the variant used by 'adb backup'; it requires on-screen confirmation
8091    // by the user because it can be used to offload data over untrusted USB.
8092    @Override
8093    public void fullBackup(ParcelFileDescriptor fd, boolean includeApks,
8094            boolean includeObbs, boolean includeShared, boolean doWidgets,
8095            boolean doAllApps, boolean includeSystem, boolean compress, String[] pkgList) {
8096        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
8097
8098        final int callingUserHandle = UserHandle.getCallingUserId();
8099        if (callingUserHandle != UserHandle.USER_OWNER) {
8100            throw new IllegalStateException("Backup supported only for the device owner");
8101        }
8102
8103        // Validate
8104        if (!doAllApps) {
8105            if (!includeShared) {
8106                // If we're backing up shared data (sdcard or equivalent), then we can run
8107                // without any supplied app names.  Otherwise, we'd be doing no work, so
8108                // report the error.
8109                if (pkgList == null || pkgList.length == 0) {
8110                    throw new IllegalArgumentException(
8111                            "Backup requested but neither shared nor any apps named");
8112                }
8113            }
8114        }
8115
8116        long oldId = Binder.clearCallingIdentity();
8117        try {
8118            // Doesn't make sense to do a full backup prior to setup
8119            if (!deviceIsProvisioned()) {
8120                Slog.i(TAG, "Full backup not supported before setup");
8121                return;
8122            }
8123
8124            if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
8125                    + " obb=" + includeObbs + " shared=" + includeShared + " all=" + doAllApps
8126                    + " pkgs=" + pkgList);
8127            Slog.i(TAG, "Beginning full backup...");
8128
8129            FullBackupParams params = new FullBackupParams(fd, includeApks, includeObbs,
8130                    includeShared, doWidgets, doAllApps, includeSystem, compress, pkgList);
8131            final int token = generateToken();
8132            synchronized (mFullConfirmations) {
8133                mFullConfirmations.put(token, params);
8134            }
8135
8136            // start up the confirmation UI
8137            if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
8138            if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
8139                Slog.e(TAG, "Unable to launch full backup confirmation");
8140                mFullConfirmations.delete(token);
8141                return;
8142            }
8143
8144            // make sure the screen is lit for the user interaction
8145            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
8146
8147            // start the confirmation countdown
8148            startConfirmationTimeout(token, params);
8149
8150            // wait for the backup to be performed
8151            if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
8152            waitForCompletion(params);
8153        } finally {
8154            try {
8155                fd.close();
8156            } catch (IOException e) {
8157                // just eat it
8158            }
8159            Binder.restoreCallingIdentity(oldId);
8160            Slog.d(TAG, "Full backup processing complete.");
8161        }
8162    }
8163
8164    @Override
8165    public void fullTransportBackup(String[] pkgNames) {
8166        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
8167                "fullTransportBackup");
8168
8169        final int callingUserHandle = UserHandle.getCallingUserId();
8170        if (callingUserHandle != UserHandle.USER_OWNER) {
8171            throw new IllegalStateException("Restore supported only for the device owner");
8172        }
8173
8174        if (DEBUG) {
8175            Slog.d(TAG, "fullTransportBackup()");
8176        }
8177
8178        AtomicBoolean latch = new AtomicBoolean(false);
8179        PerformFullTransportBackupTask task =
8180                new PerformFullTransportBackupTask(null, pkgNames, false, null, latch);
8181        (new Thread(task, "full-transport-master")).start();
8182        synchronized (latch) {
8183            try {
8184                while (latch.get() == false) {
8185                    latch.wait();
8186                }
8187            } catch (InterruptedException e) {}
8188        }
8189        if (DEBUG) {
8190            Slog.d(TAG, "Done with full transport backup.");
8191        }
8192    }
8193
8194    @Override
8195    public void fullRestore(ParcelFileDescriptor fd) {
8196        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
8197
8198        final int callingUserHandle = UserHandle.getCallingUserId();
8199        if (callingUserHandle != UserHandle.USER_OWNER) {
8200            throw new IllegalStateException("Restore supported only for the device owner");
8201        }
8202
8203        long oldId = Binder.clearCallingIdentity();
8204
8205        try {
8206            // Check whether the device has been provisioned -- we don't handle
8207            // full restores prior to completing the setup process.
8208            if (!deviceIsProvisioned()) {
8209                Slog.i(TAG, "Full restore not permitted before setup");
8210                return;
8211            }
8212
8213            Slog.i(TAG, "Beginning full restore...");
8214
8215            FullRestoreParams params = new FullRestoreParams(fd);
8216            final int token = generateToken();
8217            synchronized (mFullConfirmations) {
8218                mFullConfirmations.put(token, params);
8219            }
8220
8221            // start up the confirmation UI
8222            if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
8223            if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
8224                Slog.e(TAG, "Unable to launch full restore confirmation");
8225                mFullConfirmations.delete(token);
8226                return;
8227            }
8228
8229            // make sure the screen is lit for the user interaction
8230            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
8231
8232            // start the confirmation countdown
8233            startConfirmationTimeout(token, params);
8234
8235            // wait for the restore to be performed
8236            if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
8237            waitForCompletion(params);
8238        } finally {
8239            try {
8240                fd.close();
8241            } catch (IOException e) {
8242                Slog.w(TAG, "Error trying to close fd after full restore: " + e);
8243            }
8244            Binder.restoreCallingIdentity(oldId);
8245            Slog.i(TAG, "Full restore processing complete.");
8246        }
8247    }
8248
8249    boolean startConfirmationUi(int token, String action) {
8250        try {
8251            Intent confIntent = new Intent(action);
8252            confIntent.setClassName("com.android.backupconfirm",
8253                    "com.android.backupconfirm.BackupRestoreConfirmation");
8254            confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
8255            confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8256            mContext.startActivity(confIntent);
8257        } catch (ActivityNotFoundException e) {
8258            return false;
8259        }
8260        return true;
8261    }
8262
8263    void startConfirmationTimeout(int token, FullParams params) {
8264        if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
8265                + TIMEOUT_FULL_CONFIRMATION + " millis");
8266        Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
8267                token, 0, params);
8268        mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
8269    }
8270
8271    void waitForCompletion(FullParams params) {
8272        synchronized (params.latch) {
8273            while (params.latch.get() == false) {
8274                try {
8275                    params.latch.wait();
8276                } catch (InterruptedException e) { /* never interrupted */ }
8277            }
8278        }
8279    }
8280
8281    void signalFullBackupRestoreCompletion(FullParams params) {
8282        synchronized (params.latch) {
8283            params.latch.set(true);
8284            params.latch.notifyAll();
8285        }
8286    }
8287
8288    // Confirm that the previously-requested full backup/restore operation can proceed.  This
8289    // is used to require a user-facing disclosure about the operation.
8290    @Override
8291    public void acknowledgeFullBackupOrRestore(int token, boolean allow,
8292            String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
8293        if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
8294                + " allow=" + allow);
8295
8296        // TODO: possibly require not just this signature-only permission, but even
8297        // require that the specific designated confirmation-UI app uid is the caller?
8298        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
8299
8300        long oldId = Binder.clearCallingIdentity();
8301        try {
8302
8303            FullParams params;
8304            synchronized (mFullConfirmations) {
8305                params = mFullConfirmations.get(token);
8306                if (params != null) {
8307                    mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
8308                    mFullConfirmations.delete(token);
8309
8310                    if (allow) {
8311                        final int verb = params instanceof FullBackupParams
8312                                ? MSG_RUN_ADB_BACKUP
8313                                : MSG_RUN_ADB_RESTORE;
8314
8315                        params.observer = observer;
8316                        params.curPassword = curPassword;
8317
8318                        boolean isEncrypted;
8319                        try {
8320                            isEncrypted = (mMountService.getEncryptionState() !=
8321                                    IMountService.ENCRYPTION_STATE_NONE);
8322                            if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
8323                        } catch (RemoteException e) {
8324                            // couldn't contact the mount service; fail "safe" and assume encryption
8325                            Slog.e(TAG, "Unable to contact mount service!");
8326                            isEncrypted = true;
8327                        }
8328                        params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
8329
8330                        if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
8331                        mWakelock.acquire();
8332                        Message msg = mBackupHandler.obtainMessage(verb, params);
8333                        mBackupHandler.sendMessage(msg);
8334                    } else {
8335                        Slog.w(TAG, "User rejected full backup/restore operation");
8336                        // indicate completion without having actually transferred any data
8337                        signalFullBackupRestoreCompletion(params);
8338                    }
8339                } else {
8340                    Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
8341                }
8342            }
8343        } finally {
8344            Binder.restoreCallingIdentity(oldId);
8345        }
8346    }
8347
8348    // Enable/disable the backup service
8349    @Override
8350    public void setBackupEnabled(boolean enable) {
8351        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
8352                "setBackupEnabled");
8353
8354        Slog.i(TAG, "Backup enabled => " + enable);
8355
8356        long oldId = Binder.clearCallingIdentity();
8357        try {
8358            boolean wasEnabled = mEnabled;
8359            synchronized (this) {
8360                Settings.Secure.putInt(mContext.getContentResolver(),
8361                        Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
8362                mEnabled = enable;
8363            }
8364
8365            synchronized (mQueueLock) {
8366                if (enable && !wasEnabled && mProvisioned) {
8367                    // if we've just been enabled, start scheduling backup passes
8368                    startBackupAlarmsLocked(BACKUP_INTERVAL);
8369                    scheduleNextFullBackupJob();
8370                } else if (!enable) {
8371                    // No longer enabled, so stop running backups
8372                    if (DEBUG) Slog.i(TAG, "Opting out of backup");
8373
8374                    mAlarmManager.cancel(mRunBackupIntent);
8375
8376                    // This also constitutes an opt-out, so we wipe any data for
8377                    // this device from the backend.  We start that process with
8378                    // an alarm in order to guarantee wakelock states.
8379                    if (wasEnabled && mProvisioned) {
8380                        // NOTE: we currently flush every registered transport, not just
8381                        // the currently-active one.
8382                        HashSet<String> allTransports;
8383                        synchronized (mTransports) {
8384                            allTransports = new HashSet<String>(mTransports.keySet());
8385                        }
8386                        // build the set of transports for which we are posting an init
8387                        for (String transport : allTransports) {
8388                            recordInitPendingLocked(true, transport);
8389                        }
8390                        mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
8391                                mRunInitIntent);
8392                    }
8393                }
8394            }
8395        } finally {
8396            Binder.restoreCallingIdentity(oldId);
8397        }
8398    }
8399
8400    // Enable/disable automatic restore of app data at install time
8401    public void setAutoRestore(boolean doAutoRestore) {
8402        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
8403                "setAutoRestore");
8404
8405        Slog.i(TAG, "Auto restore => " + doAutoRestore);
8406
8407        synchronized (this) {
8408            Settings.Secure.putInt(mContext.getContentResolver(),
8409                    Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
8410            mAutoRestore = doAutoRestore;
8411        }
8412    }
8413
8414    // Mark the backup service as having been provisioned
8415    public void setBackupProvisioned(boolean available) {
8416        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
8417                "setBackupProvisioned");
8418        /*
8419         * This is now a no-op; provisioning is simply the device's own setup state.
8420         */
8421    }
8422
8423    private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
8424        // We used to use setInexactRepeating(), but that may be linked to
8425        // backups running at :00 more often than not, creating load spikes.
8426        // Schedule at an exact time for now, and also add a bit of "fuzz".
8427
8428        Random random = new Random();
8429        long when = System.currentTimeMillis() + delayBeforeFirstBackup +
8430                random.nextInt(FUZZ_MILLIS);
8431        mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
8432                BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
8433        mNextBackupPass = when;
8434    }
8435
8436    // Report whether the backup mechanism is currently enabled
8437    public boolean isBackupEnabled() {
8438        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
8439        return mEnabled;    // no need to synchronize just to read it
8440    }
8441
8442    // Report the name of the currently active transport
8443    public String getCurrentTransport() {
8444        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
8445                "getCurrentTransport");
8446        if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
8447        return mCurrentTransport;
8448    }
8449
8450    // Report all known, available backup transports
8451    public String[] listAllTransports() {
8452        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
8453
8454        String[] list = null;
8455        ArrayList<String> known = new ArrayList<String>();
8456        for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
8457            if (entry.getValue() != null) {
8458                known.add(entry.getKey());
8459            }
8460        }
8461
8462        if (known.size() > 0) {
8463            list = new String[known.size()];
8464            known.toArray(list);
8465        }
8466        return list;
8467    }
8468
8469    // Select which transport to use for the next backup operation.  If the given
8470    // name is not one of the available transports, no action is taken and the method
8471    // returns null.
8472    public String selectBackupTransport(String transport) {
8473        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
8474
8475        synchronized (mTransports) {
8476            String prevTransport = null;
8477            if (mTransports.get(transport) != null) {
8478                prevTransport = mCurrentTransport;
8479                mCurrentTransport = transport;
8480                Settings.Secure.putString(mContext.getContentResolver(),
8481                        Settings.Secure.BACKUP_TRANSPORT, transport);
8482                Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
8483                        + " returning " + prevTransport);
8484            } else {
8485                Slog.w(TAG, "Attempt to select unavailable transport " + transport);
8486            }
8487            return prevTransport;
8488        }
8489    }
8490
8491    // Supply the configuration Intent for the given transport.  If the name is not one
8492    // of the available transports, or if the transport does not supply any configuration
8493    // UI, the method returns null.
8494    public Intent getConfigurationIntent(String transportName) {
8495        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
8496                "getConfigurationIntent");
8497
8498        synchronized (mTransports) {
8499            final IBackupTransport transport = mTransports.get(transportName);
8500            if (transport != null) {
8501                try {
8502                    final Intent intent = transport.configurationIntent();
8503                    if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
8504                            + intent);
8505                    return intent;
8506                } catch (RemoteException e) {
8507                    /* fall through to return null */
8508                }
8509            }
8510        }
8511
8512        return null;
8513    }
8514
8515    // Supply the configuration summary string for the given transport.  If the name is
8516    // not one of the available transports, or if the transport does not supply any
8517    // summary / destination string, the method can return null.
8518    //
8519    // This string is used VERBATIM as the summary text of the relevant Settings item!
8520    public String getDestinationString(String transportName) {
8521        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
8522                "getDestinationString");
8523
8524        synchronized (mTransports) {
8525            final IBackupTransport transport = mTransports.get(transportName);
8526            if (transport != null) {
8527                try {
8528                    final String text = transport.currentDestinationString();
8529                    if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
8530                    return text;
8531                } catch (RemoteException e) {
8532                    /* fall through to return null */
8533                }
8534            }
8535        }
8536
8537        return null;
8538    }
8539
8540    // Supply the manage-data intent for the given transport.
8541    public Intent getDataManagementIntent(String transportName) {
8542        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
8543                "getDataManagementIntent");
8544
8545        synchronized (mTransports) {
8546            final IBackupTransport transport = mTransports.get(transportName);
8547            if (transport != null) {
8548                try {
8549                    final Intent intent = transport.dataManagementIntent();
8550                    if (MORE_DEBUG) Slog.d(TAG, "getDataManagementIntent() returning intent "
8551                            + intent);
8552                    return intent;
8553                } catch (RemoteException e) {
8554                    /* fall through to return null */
8555                }
8556            }
8557        }
8558
8559        return null;
8560    }
8561
8562    // Supply the menu label for affordances that fire the manage-data intent
8563    // for the given transport.
8564    public String getDataManagementLabel(String transportName) {
8565        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
8566                "getDataManagementLabel");
8567
8568        synchronized (mTransports) {
8569            final IBackupTransport transport = mTransports.get(transportName);
8570            if (transport != null) {
8571                try {
8572                    final String text = transport.dataManagementLabel();
8573                    if (MORE_DEBUG) Slog.d(TAG, "getDataManagementLabel() returning " + text);
8574                    return text;
8575                } catch (RemoteException e) {
8576                    /* fall through to return null */
8577                }
8578            }
8579        }
8580
8581        return null;
8582    }
8583
8584    // Callback: a requested backup agent has been instantiated.  This should only
8585    // be called from the Activity Manager.
8586    public void agentConnected(String packageName, IBinder agentBinder) {
8587        synchronized(mAgentConnectLock) {
8588            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
8589                Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
8590                IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
8591                mConnectedAgent = agent;
8592                mConnecting = false;
8593            } else {
8594                Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
8595                        + " claiming agent connected");
8596            }
8597            mAgentConnectLock.notifyAll();
8598        }
8599    }
8600
8601    // Callback: a backup agent has failed to come up, or has unexpectedly quit.
8602    // If the agent failed to come up in the first place, the agentBinder argument
8603    // will be null.  This should only be called from the Activity Manager.
8604    public void agentDisconnected(String packageName) {
8605        // TODO: handle backup being interrupted
8606        synchronized(mAgentConnectLock) {
8607            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
8608                mConnectedAgent = null;
8609                mConnecting = false;
8610            } else {
8611                Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
8612                        + " claiming agent disconnected");
8613            }
8614            mAgentConnectLock.notifyAll();
8615        }
8616    }
8617
8618    // An application being installed will need a restore pass, then the Package Manager
8619    // will need to be told when the restore is finished.
8620    public void restoreAtInstall(String packageName, int token) {
8621        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
8622            Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
8623                    + " attemping install-time restore");
8624            return;
8625        }
8626
8627        boolean skip = false;
8628
8629        long restoreSet = getAvailableRestoreToken(packageName);
8630        if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
8631                + " token=" + Integer.toHexString(token)
8632                + " restoreSet=" + Long.toHexString(restoreSet));
8633        if (restoreSet == 0) {
8634            if (MORE_DEBUG) Slog.i(TAG, "No restore set");
8635            skip = true;
8636        }
8637
8638        // Do we have a transport to fetch data for us?
8639        IBackupTransport transport = getTransport(mCurrentTransport);
8640        if (transport == null) {
8641            if (DEBUG) Slog.w(TAG, "No transport");
8642            skip = true;
8643        }
8644
8645        if (!mAutoRestore || !mProvisioned) {
8646            if (DEBUG) {
8647                Slog.w(TAG, "Non-restorable state: auto=" + mAutoRestore
8648                        + " prov=" + mProvisioned);
8649            }
8650            skip = true;
8651        }
8652
8653        if (!skip) {
8654            try {
8655                // okay, we're going to attempt a restore of this package from this restore set.
8656                // The eventual message back into the Package Manager to run the post-install
8657                // steps for 'token' will be issued from the restore handling code.
8658
8659                // This can throw and so *must* happen before the wakelock is acquired
8660                String dirName = transport.transportDirName();
8661
8662                // We can use a synthetic PackageInfo here because:
8663                //   1. We know it's valid, since the Package Manager supplied the name
8664                //   2. Only the packageName field will be used by the restore code
8665                PackageInfo pkg = new PackageInfo();
8666                pkg.packageName = packageName;
8667
8668                mWakelock.acquire();
8669                if (MORE_DEBUG) {
8670                    Slog.d(TAG, "Restore at install of " + packageName);
8671                }
8672                Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
8673                msg.obj = new RestoreParams(transport, dirName, null,
8674                        restoreSet, pkg, token);
8675                mBackupHandler.sendMessage(msg);
8676            } catch (RemoteException e) {
8677                // Binding to the transport broke; back off and proceed with the installation.
8678                Slog.e(TAG, "Unable to contact transport");
8679                skip = true;
8680            }
8681        }
8682
8683        if (skip) {
8684            // Auto-restore disabled or no way to attempt a restore; just tell the Package
8685            // Manager to proceed with the post-install handling for this package.
8686            if (DEBUG) Slog.v(TAG, "Finishing install immediately");
8687            try {
8688                mPackageManagerBinder.finishPackageInstall(token);
8689            } catch (RemoteException e) { /* can't happen */ }
8690        }
8691    }
8692
8693    // Hand off a restore session
8694    public IRestoreSession beginRestoreSession(String packageName, String transport) {
8695        if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
8696                + " transport=" + transport);
8697
8698        boolean needPermission = true;
8699        if (transport == null) {
8700            transport = mCurrentTransport;
8701
8702            if (packageName != null) {
8703                PackageInfo app = null;
8704                try {
8705                    app = mPackageManager.getPackageInfo(packageName, 0);
8706                } catch (NameNotFoundException nnf) {
8707                    Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
8708                    throw new IllegalArgumentException("Package " + packageName + " not found");
8709                }
8710
8711                if (app.applicationInfo.uid == Binder.getCallingUid()) {
8712                    // So: using the current active transport, and the caller has asked
8713                    // that its own package will be restored.  In this narrow use case
8714                    // we do not require the caller to hold the permission.
8715                    needPermission = false;
8716                }
8717            }
8718        }
8719
8720        if (needPermission) {
8721            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
8722                    "beginRestoreSession");
8723        } else {
8724            if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
8725        }
8726
8727        synchronized(this) {
8728            if (mActiveRestoreSession != null) {
8729                Slog.d(TAG, "Restore session requested but one already active");
8730                return null;
8731            }
8732            mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
8733            mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
8734        }
8735        return mActiveRestoreSession;
8736    }
8737
8738    void clearRestoreSession(ActiveRestoreSession currentSession) {
8739        synchronized(this) {
8740            if (currentSession != mActiveRestoreSession) {
8741                Slog.e(TAG, "ending non-current restore session");
8742            } else {
8743                if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
8744                mActiveRestoreSession = null;
8745                mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
8746            }
8747        }
8748    }
8749
8750    // Note that a currently-active backup agent has notified us that it has
8751    // completed the given outstanding asynchronous backup/restore operation.
8752    @Override
8753    public void opComplete(int token) {
8754        if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
8755        Operation op = null;
8756        synchronized (mCurrentOpLock) {
8757            op = mCurrentOperations.get(token);
8758            if (op != null) {
8759                op.state = OP_ACKNOWLEDGED;
8760            }
8761            mCurrentOpLock.notifyAll();
8762        }
8763
8764        // The completion callback, if any, is invoked on the handler
8765        if (op != null && op.callback != null) {
8766            Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
8767            mBackupHandler.sendMessage(msg);
8768        }
8769    }
8770
8771    // ----- Restore session -----
8772
8773    class ActiveRestoreSession extends IRestoreSession.Stub {
8774        private static final String TAG = "RestoreSession";
8775
8776        private String mPackageName;
8777        private IBackupTransport mRestoreTransport = null;
8778        RestoreSet[] mRestoreSets = null;
8779        boolean mEnded = false;
8780        boolean mTimedOut = false;
8781
8782        ActiveRestoreSession(String packageName, String transport) {
8783            mPackageName = packageName;
8784            mRestoreTransport = getTransport(transport);
8785        }
8786
8787        public void markTimedOut() {
8788            mTimedOut = true;
8789        }
8790
8791        // --- Binder interface ---
8792        public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
8793            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
8794                    "getAvailableRestoreSets");
8795            if (observer == null) {
8796                throw new IllegalArgumentException("Observer must not be null");
8797            }
8798
8799            if (mEnded) {
8800                throw new IllegalStateException("Restore session already ended");
8801            }
8802
8803            if (mTimedOut) {
8804                Slog.i(TAG, "Session already timed out");
8805                return -1;
8806            }
8807
8808            long oldId = Binder.clearCallingIdentity();
8809            try {
8810                if (mRestoreTransport == null) {
8811                    Slog.w(TAG, "Null transport getting restore sets");
8812                    return -1;
8813                }
8814                // spin off the transport request to our service thread
8815                mWakelock.acquire();
8816                Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
8817                        new RestoreGetSetsParams(mRestoreTransport, this, observer));
8818                mBackupHandler.sendMessage(msg);
8819                return 0;
8820            } catch (Exception e) {
8821                Slog.e(TAG, "Error in getAvailableRestoreSets", e);
8822                return -1;
8823            } finally {
8824                Binder.restoreCallingIdentity(oldId);
8825            }
8826        }
8827
8828        public synchronized int restoreAll(long token, IRestoreObserver observer) {
8829            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
8830                    "performRestore");
8831
8832            if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
8833                    + " observer=" + observer);
8834
8835            if (mEnded) {
8836                throw new IllegalStateException("Restore session already ended");
8837            }
8838
8839            if (mTimedOut) {
8840                Slog.i(TAG, "Session already timed out");
8841                return -1;
8842            }
8843
8844            if (mRestoreTransport == null || mRestoreSets == null) {
8845                Slog.e(TAG, "Ignoring restoreAll() with no restore set");
8846                return -1;
8847            }
8848
8849            if (mPackageName != null) {
8850                Slog.e(TAG, "Ignoring restoreAll() on single-package session");
8851                return -1;
8852            }
8853
8854            String dirName;
8855            try {
8856                dirName = mRestoreTransport.transportDirName();
8857            } catch (RemoteException e) {
8858                // Transport went AWOL; fail.
8859                Slog.e(TAG, "Unable to contact transport for restore");
8860                return -1;
8861            }
8862
8863            synchronized (mQueueLock) {
8864                for (int i = 0; i < mRestoreSets.length; i++) {
8865                    if (token == mRestoreSets[i].token) {
8866                        long oldId = Binder.clearCallingIdentity();
8867                        mWakelock.acquire();
8868                        if (MORE_DEBUG) {
8869                            Slog.d(TAG, "restoreAll() kicking off");
8870                        }
8871                        Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
8872                        msg.obj = new RestoreParams(mRestoreTransport, dirName,
8873                                observer, token);
8874                        mBackupHandler.sendMessage(msg);
8875                        Binder.restoreCallingIdentity(oldId);
8876                        return 0;
8877                    }
8878                }
8879            }
8880
8881            Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
8882            return -1;
8883        }
8884
8885        // Restores of more than a single package are treated as 'system' restores
8886        public synchronized int restoreSome(long token, IRestoreObserver observer,
8887                String[] packages) {
8888            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
8889                    "performRestore");
8890
8891            if (DEBUG) {
8892                StringBuilder b = new StringBuilder(128);
8893                b.append("restoreSome token=");
8894                b.append(Long.toHexString(token));
8895                b.append(" observer=");
8896                b.append(observer.toString());
8897                b.append(" packages=");
8898                if (packages == null) {
8899                    b.append("null");
8900                } else {
8901                    b.append('{');
8902                    boolean first = true;
8903                    for (String s : packages) {
8904                        if (!first) {
8905                            b.append(", ");
8906                        } else first = false;
8907                        b.append(s);
8908                    }
8909                    b.append('}');
8910                }
8911                Slog.d(TAG, b.toString());
8912            }
8913
8914            if (mEnded) {
8915                throw new IllegalStateException("Restore session already ended");
8916            }
8917
8918            if (mTimedOut) {
8919                Slog.i(TAG, "Session already timed out");
8920                return -1;
8921            }
8922
8923            if (mRestoreTransport == null || mRestoreSets == null) {
8924                Slog.e(TAG, "Ignoring restoreAll() with no restore set");
8925                return -1;
8926            }
8927
8928            if (mPackageName != null) {
8929                Slog.e(TAG, "Ignoring restoreAll() on single-package session");
8930                return -1;
8931            }
8932
8933            String dirName;
8934            try {
8935                dirName = mRestoreTransport.transportDirName();
8936            } catch (RemoteException e) {
8937                // Transport went AWOL; fail.
8938                Slog.e(TAG, "Unable to contact transport for restore");
8939                return -1;
8940            }
8941
8942            synchronized (mQueueLock) {
8943                for (int i = 0; i < mRestoreSets.length; i++) {
8944                    if (token == mRestoreSets[i].token) {
8945                        long oldId = Binder.clearCallingIdentity();
8946                        mWakelock.acquire();
8947                        if (MORE_DEBUG) {
8948                            Slog.d(TAG, "restoreSome() of " + packages.length + " packages");
8949                        }
8950                        Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
8951                        msg.obj = new RestoreParams(mRestoreTransport, dirName, observer, token,
8952                                packages, packages.length > 1);
8953                        mBackupHandler.sendMessage(msg);
8954                        Binder.restoreCallingIdentity(oldId);
8955                        return 0;
8956                    }
8957                }
8958            }
8959
8960            Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
8961            return -1;
8962        }
8963
8964        public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
8965            if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
8966
8967            if (mEnded) {
8968                throw new IllegalStateException("Restore session already ended");
8969            }
8970
8971            if (mTimedOut) {
8972                Slog.i(TAG, "Session already timed out");
8973                return -1;
8974            }
8975
8976            if (mPackageName != null) {
8977                if (! mPackageName.equals(packageName)) {
8978                    Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
8979                            + " on session for package " + mPackageName);
8980                    return -1;
8981                }
8982            }
8983
8984            PackageInfo app = null;
8985            try {
8986                app = mPackageManager.getPackageInfo(packageName, 0);
8987            } catch (NameNotFoundException nnf) {
8988                Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
8989                return -1;
8990            }
8991
8992            // If the caller is not privileged and is not coming from the target
8993            // app's uid, throw a permission exception back to the caller.
8994            int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
8995                    Binder.getCallingPid(), Binder.getCallingUid());
8996            if ((perm == PackageManager.PERMISSION_DENIED) &&
8997                    (app.applicationInfo.uid != Binder.getCallingUid())) {
8998                Slog.w(TAG, "restorePackage: bad packageName=" + packageName
8999                        + " or calling uid=" + Binder.getCallingUid());
9000                throw new SecurityException("No permission to restore other packages");
9001            }
9002
9003            // So far so good; we're allowed to try to restore this package.  Now
9004            // check whether there is data for it in the current dataset, falling back
9005            // to the ancestral dataset if not.
9006            long token = getAvailableRestoreToken(packageName);
9007
9008            // If we didn't come up with a place to look -- no ancestral dataset and
9009            // the app has never been backed up from this device -- there's nothing
9010            // to do but return failure.
9011            if (token == 0) {
9012                if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
9013                return -1;
9014            }
9015
9016            String dirName;
9017            try {
9018                dirName = mRestoreTransport.transportDirName();
9019            } catch (RemoteException e) {
9020                // Transport went AWOL; fail.
9021                Slog.e(TAG, "Unable to contact transport for restore");
9022                return -1;
9023            }
9024
9025            // Ready to go:  enqueue the restore request and claim success
9026            long oldId = Binder.clearCallingIdentity();
9027            mWakelock.acquire();
9028            if (MORE_DEBUG) {
9029                Slog.d(TAG, "restorePackage() : " + packageName);
9030            }
9031            Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
9032            msg.obj = new RestoreParams(mRestoreTransport, dirName,
9033                    observer, token, app, 0);
9034            mBackupHandler.sendMessage(msg);
9035            Binder.restoreCallingIdentity(oldId);
9036            return 0;
9037        }
9038
9039        // Posted to the handler to tear down a restore session in a cleanly synchronized way
9040        class EndRestoreRunnable implements Runnable {
9041            BackupManagerService mBackupManager;
9042            ActiveRestoreSession mSession;
9043
9044            EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
9045                mBackupManager = manager;
9046                mSession = session;
9047            }
9048
9049            public void run() {
9050                // clean up the session's bookkeeping
9051                synchronized (mSession) {
9052                    try {
9053                        if (mSession.mRestoreTransport != null) {
9054                            mSession.mRestoreTransport.finishRestore();
9055                        }
9056                    } catch (Exception e) {
9057                        Slog.e(TAG, "Error in finishRestore", e);
9058                    } finally {
9059                        mSession.mRestoreTransport = null;
9060                        mSession.mEnded = true;
9061                    }
9062                }
9063
9064                // clean up the BackupManagerImpl side of the bookkeeping
9065                // and cancel any pending timeout message
9066                mBackupManager.clearRestoreSession(mSession);
9067            }
9068        }
9069
9070        public synchronized void endRestoreSession() {
9071            if (DEBUG) Slog.d(TAG, "endRestoreSession");
9072
9073            if (mTimedOut) {
9074                Slog.i(TAG, "Session already timed out");
9075                return;
9076            }
9077
9078            if (mEnded) {
9079                throw new IllegalStateException("Restore session already ended");
9080            }
9081
9082            mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
9083        }
9084    }
9085
9086    @Override
9087    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
9088        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
9089
9090        long identityToken = Binder.clearCallingIdentity();
9091        try {
9092            if (args != null) {
9093                for (String arg : args) {
9094                    if ("-h".equals(arg)) {
9095                        pw.println("'dumpsys backup' optional arguments:");
9096                        pw.println("  -h       : this help text");
9097                        pw.println("  a[gents] : dump information about defined backup agents");
9098                        return;
9099                    } else if ("agents".startsWith(arg)) {
9100                        dumpAgents(pw);
9101                        return;
9102                    }
9103                }
9104            }
9105            dumpInternal(pw);
9106        } finally {
9107            Binder.restoreCallingIdentity(identityToken);
9108        }
9109    }
9110
9111    private void dumpAgents(PrintWriter pw) {
9112        List<PackageInfo> agentPackages = allAgentPackages();
9113        pw.println("Defined backup agents:");
9114        for (PackageInfo pkg : agentPackages) {
9115            pw.print("  ");
9116            pw.print(pkg.packageName); pw.println(':');
9117            pw.print("      "); pw.println(pkg.applicationInfo.backupAgentName);
9118        }
9119    }
9120
9121    private void dumpInternal(PrintWriter pw) {
9122        synchronized (mQueueLock) {
9123            pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
9124                    + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
9125                    + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
9126            pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
9127            if (mBackupRunning) pw.println("Backup currently running");
9128            pw.println("Last backup pass started: " + mLastBackupPass
9129                    + " (now = " + System.currentTimeMillis() + ')');
9130            pw.println("  next scheduled: " + mNextBackupPass);
9131
9132            pw.println("Available transports:");
9133            for (String t : listAllTransports()) {
9134                pw.println((t.equals(mCurrentTransport) ? "  * " : "    ") + t);
9135                try {
9136                    IBackupTransport transport = getTransport(t);
9137                    File dir = new File(mBaseStateDir, transport.transportDirName());
9138                    pw.println("       destination: " + transport.currentDestinationString());
9139                    pw.println("       intent: " + transport.configurationIntent());
9140                    for (File f : dir.listFiles()) {
9141                        pw.println("       " + f.getName() + " - " + f.length() + " state bytes");
9142                    }
9143                } catch (Exception e) {
9144                    Slog.e(TAG, "Error in transport", e);
9145                    pw.println("        Error: " + e);
9146                }
9147            }
9148
9149            pw.println("Pending init: " + mPendingInits.size());
9150            for (String s : mPendingInits) {
9151                pw.println("    " + s);
9152            }
9153
9154            if (DEBUG_BACKUP_TRACE) {
9155                synchronized (mBackupTrace) {
9156                    if (!mBackupTrace.isEmpty()) {
9157                        pw.println("Most recent backup trace:");
9158                        for (String s : mBackupTrace) {
9159                            pw.println("   " + s);
9160                        }
9161                    }
9162                }
9163            }
9164
9165            int N = mBackupParticipants.size();
9166            pw.println("Participants:");
9167            for (int i=0; i<N; i++) {
9168                int uid = mBackupParticipants.keyAt(i);
9169                pw.print("  uid: ");
9170                pw.println(uid);
9171                HashSet<String> participants = mBackupParticipants.valueAt(i);
9172                for (String app: participants) {
9173                    pw.println("    " + app);
9174                }
9175            }
9176
9177            pw.println("Ancestral packages: "
9178                    + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
9179            if (mAncestralPackages != null) {
9180                for (String pkg : mAncestralPackages) {
9181                    pw.println("    " + pkg);
9182                }
9183            }
9184
9185            pw.println("Ever backed up: " + mEverStoredApps.size());
9186            for (String pkg : mEverStoredApps) {
9187                pw.println("    " + pkg);
9188            }
9189
9190            pw.println("Pending key/value backup: " + mPendingBackups.size());
9191            for (BackupRequest req : mPendingBackups.values()) {
9192                pw.println("    " + req);
9193            }
9194
9195            pw.println("Full backup queue:" + mFullBackupQueue.size());
9196            for (FullBackupEntry entry : mFullBackupQueue) {
9197                pw.print("    "); pw.print(entry.lastBackup);
9198                pw.print(" : "); pw.println(entry.packageName);
9199            }
9200        }
9201    }
9202}
9203