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