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