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