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