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