BackupManagerService.java revision cba5941c6085dab1566bc047c1ea31f58a2dd4cf
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.FullBackup;
30import android.app.backup.RestoreSet;
31import android.app.backup.IBackupManager;
32import android.app.backup.IFullBackupRestoreObserver;
33import android.app.backup.IRestoreObserver;
34import android.app.backup.IRestoreSession;
35import android.content.ActivityNotFoundException;
36import android.content.BroadcastReceiver;
37import android.content.ComponentName;
38import android.content.ContentResolver;
39import android.content.Context;
40import android.content.Intent;
41import android.content.IntentFilter;
42import android.content.ServiceConnection;
43import android.content.pm.ApplicationInfo;
44import android.content.pm.IPackageDataObserver;
45import android.content.pm.IPackageDeleteObserver;
46import android.content.pm.IPackageInstallObserver;
47import android.content.pm.IPackageManager;
48import android.content.pm.PackageInfo;
49import android.content.pm.PackageManager;
50import android.content.pm.ResolveInfo;
51import android.content.pm.ServiceInfo;
52import android.content.pm.Signature;
53import android.content.pm.PackageManager.NameNotFoundException;
54import android.database.ContentObserver;
55import android.net.Uri;
56import android.os.Binder;
57import android.os.Build;
58import android.os.Bundle;
59import android.os.Environment;
60import android.os.Handler;
61import android.os.HandlerThread;
62import android.os.IBinder;
63import android.os.Looper;
64import android.os.Message;
65import android.os.ParcelFileDescriptor;
66import android.os.PowerManager;
67import android.os.Process;
68import android.os.RemoteException;
69import android.os.SELinux;
70import android.os.ServiceManager;
71import android.os.SystemClock;
72import android.os.UserHandle;
73import android.os.WorkSource;
74import android.os.Environment.UserEnvironment;
75import android.os.storage.IMountService;
76import android.provider.Settings;
77import android.util.EventLog;
78import android.util.Log;
79import android.util.Slog;
80import android.util.SparseArray;
81import android.util.StringBuilderPrinter;
82
83import com.android.internal.backup.BackupConstants;
84import com.android.internal.backup.IBackupTransport;
85import com.android.internal.backup.IObbBackupService;
86import com.android.server.AppWidgetBackupBridge;
87import com.android.server.EventLogTags;
88import com.android.server.SystemService;
89import com.android.server.backup.PackageManagerBackupAgent.Metadata;
90
91import java.io.BufferedInputStream;
92import java.io.BufferedOutputStream;
93import java.io.ByteArrayInputStream;
94import java.io.ByteArrayOutputStream;
95import java.io.DataInputStream;
96import java.io.DataOutputStream;
97import java.io.EOFException;
98import java.io.File;
99import java.io.FileDescriptor;
100import java.io.FileInputStream;
101import java.io.FileNotFoundException;
102import java.io.FileOutputStream;
103import java.io.IOException;
104import java.io.InputStream;
105import java.io.OutputStream;
106import java.io.PrintWriter;
107import java.io.RandomAccessFile;
108import java.security.InvalidAlgorithmParameterException;
109import java.security.InvalidKeyException;
110import java.security.Key;
111import java.security.NoSuchAlgorithmException;
112import java.security.SecureRandom;
113import java.security.spec.InvalidKeySpecException;
114import java.security.spec.KeySpec;
115import java.text.SimpleDateFormat;
116import java.util.ArrayList;
117import java.util.Arrays;
118import java.util.Date;
119import java.util.HashMap;
120import java.util.HashSet;
121import java.util.Iterator;
122import java.util.List;
123import java.util.Map;
124import java.util.Map.Entry;
125import java.util.Random;
126import java.util.Set;
127import java.util.TreeMap;
128import java.util.concurrent.atomic.AtomicBoolean;
129import java.util.zip.Deflater;
130import java.util.zip.DeflaterOutputStream;
131import java.util.zip.InflaterInputStream;
132
133import javax.crypto.BadPaddingException;
134import javax.crypto.Cipher;
135import javax.crypto.CipherInputStream;
136import javax.crypto.CipherOutputStream;
137import javax.crypto.IllegalBlockSizeException;
138import javax.crypto.NoSuchPaddingException;
139import javax.crypto.SecretKey;
140import javax.crypto.SecretKeyFactory;
141import javax.crypto.spec.IvParameterSpec;
142import javax.crypto.spec.PBEKeySpec;
143import javax.crypto.spec.SecretKeySpec;
144
145import libcore.io.ErrnoException;
146import libcore.io.Libcore;
147
148public class BackupManagerService extends IBackupManager.Stub {
149
150    private static final String TAG = "BackupManagerService";
151    private static final boolean DEBUG = true;
152    private static final boolean MORE_DEBUG = false;
153
154    // System-private key used for backing up an app's widget state.  Must
155    // begin with U+FFxx by convention (we reserve all keys starting
156    // with U+FF00 or higher for system use).
157    static final String KEY_WIDGET_STATE = "\uffed\uffedwidget";
158
159    // Historical and current algorithm names
160    static final String PBKDF_CURRENT = "PBKDF2WithHmacSHA1";
161    static final String PBKDF_FALLBACK = "PBKDF2WithHmacSHA1And8bit";
162
163    // Name and current contents version of the full-backup manifest file
164    //
165    // Manifest version history:
166    //
167    // 1 : initial release
168    static final String BACKUP_MANIFEST_FILENAME = "_manifest";
169    static final int BACKUP_MANIFEST_VERSION = 1;
170
171    // External archive format version history:
172    //
173    // 1 : initial release
174    // 2 : no format change per se; version bump to facilitate PBKDF2 version skew detection
175    // 3 : introduced "_meta" metadata file; no other format change per se
176    static final int BACKUP_FILE_VERSION = 3;
177    static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
178    static final int BACKUP_PW_FILE_VERSION = 2;
179    static final String BACKUP_METADATA_FILENAME = "_meta";
180    static final int BACKUP_METADATA_VERSION = 1;
181    static final int BACKUP_WIDGET_METADATA_TOKEN = 0x01FFED01;
182    static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
183
184    static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
185    static final String SERVICE_ACTION_TRANSPORT_HOST = "android.backup.TRANSPORT_HOST";
186
187    // How often we perform a backup pass.  Privileged external callers can
188    // trigger an immediate pass.
189    private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
190
191    // Random variation in backup scheduling time to avoid server load spikes
192    private static final int FUZZ_MILLIS = 5 * 60 * 1000;
193
194    // The amount of time between the initial provisioning of the device and
195    // the first backup pass.
196    private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
197
198    // Retry interval for clear/init when the transport is unavailable
199    private static final long TRANSPORT_RETRY_INTERVAL = 1 * AlarmManager.INTERVAL_HOUR;
200
201    private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
202    private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
203    private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
204    private static final int MSG_RUN_BACKUP = 1;
205    private static final int MSG_RUN_FULL_BACKUP = 2;
206    private static final int MSG_RUN_RESTORE = 3;
207    private static final int MSG_RUN_CLEAR = 4;
208    private static final int MSG_RUN_INITIALIZE = 5;
209    private static final int MSG_RUN_GET_RESTORE_SETS = 6;
210    private static final int MSG_TIMEOUT = 7;
211    private static final int MSG_RESTORE_TIMEOUT = 8;
212    private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
213    private static final int MSG_RUN_FULL_RESTORE = 10;
214    private static final int MSG_RETRY_INIT = 11;
215    private static final int MSG_RETRY_CLEAR = 12;
216    private static final int MSG_WIDGET_BROADCAST = 13;
217
218    // backup task state machine tick
219    static final int MSG_BACKUP_RESTORE_STEP = 20;
220    static final int MSG_OP_COMPLETE = 21;
221
222    // Timeout interval for deciding that a bind or clear-data has taken too long
223    static final long TIMEOUT_INTERVAL = 10 * 1000;
224
225    // Timeout intervals for agent backup & restore operations
226    static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
227    static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
228    static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
229    static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
230
231    // User confirmation timeout for a full backup/restore operation.  It's this long in
232    // order to give them time to enter the backup password.
233    static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
234
235    private Context mContext;
236    private PackageManager mPackageManager;
237    IPackageManager mPackageManagerBinder;
238    private IActivityManager mActivityManager;
239    private PowerManager mPowerManager;
240    private AlarmManager mAlarmManager;
241    private IMountService mMountService;
242    IBackupManager mBackupManagerBinder;
243
244    boolean mEnabled;   // access to this is synchronized on 'this'
245    boolean mProvisioned;
246    boolean mAutoRestore;
247    PowerManager.WakeLock mWakelock;
248    HandlerThread mHandlerThread;
249    BackupHandler mBackupHandler;
250    PendingIntent mRunBackupIntent, mRunInitIntent;
251    BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
252    // map UIDs to the set of participating packages under that UID
253    final SparseArray<HashSet<String>> mBackupParticipants
254            = new SparseArray<HashSet<String>>();
255    // set of backup services that have pending changes
256    class BackupRequest {
257        public String packageName;
258
259        BackupRequest(String pkgName) {
260            packageName = pkgName;
261        }
262
263        public String toString() {
264            return "BackupRequest{pkg=" + packageName + "}";
265        }
266    }
267    // Backups that we haven't started yet.  Keys are package names.
268    HashMap<String,BackupRequest> mPendingBackups
269            = new HashMap<String,BackupRequest>();
270
271    // Pseudoname that we use for the Package Manager metadata "package"
272    static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
273
274    // locking around the pending-backup management
275    final Object mQueueLock = new Object();
276
277    // The thread performing the sequence of queued backups binds to each app's agent
278    // in succession.  Bind notifications are asynchronously delivered through the
279    // Activity Manager; use this lock object to signal when a requested binding has
280    // completed.
281    final Object mAgentConnectLock = new Object();
282    IBackupAgent mConnectedAgent;
283    volatile boolean mBackupRunning;
284    volatile boolean mConnecting;
285    volatile long mLastBackupPass;
286    volatile long mNextBackupPass;
287
288    // For debugging, we maintain a progress trace of operations during backup
289    static final boolean DEBUG_BACKUP_TRACE = true;
290    final List<String> mBackupTrace = new ArrayList<String>();
291
292    // A similar synchronization mechanism around clearing apps' data for restore
293    final Object mClearDataLock = new Object();
294    volatile boolean mClearingData;
295
296    // Transport bookkeeping
297    final HashMap<String,String> mTransportNames
298            = new HashMap<String,String>();             // component name -> registration name
299    final HashMap<String,IBackupTransport> mTransports
300            = new HashMap<String,IBackupTransport>();   // registration name -> binder
301    final ArrayList<TransportConnection> mTransportConnections
302            = new ArrayList<TransportConnection>();
303    String mCurrentTransport;
304    ActiveRestoreSession mActiveRestoreSession;
305
306    // Watch the device provisioning operation during setup
307    ContentObserver mProvisionedObserver;
308
309    public static final class Lifecycle extends SystemService {
310        private final BackupManagerService mService;
311
312        public Lifecycle(Context context) {
313            super(context);
314            mService = new BackupManagerService(context);
315        }
316
317        @Override
318        public void onStart() {
319            publishBinderService(Context.BACKUP_SERVICE, mService);
320        }
321    }
322
323    class ProvisionedObserver extends ContentObserver {
324        public ProvisionedObserver(Handler handler) {
325            super(handler);
326        }
327
328        public void onChange(boolean selfChange) {
329            final boolean wasProvisioned = mProvisioned;
330            final boolean isProvisioned = deviceIsProvisioned();
331            // latch: never unprovision
332            mProvisioned = wasProvisioned || isProvisioned;
333            if (MORE_DEBUG) {
334                Slog.d(TAG, "Provisioning change: was=" + wasProvisioned
335                        + " is=" + isProvisioned + " now=" + mProvisioned);
336            }
337
338            synchronized (mQueueLock) {
339                if (mProvisioned && !wasProvisioned && mEnabled) {
340                    // we're now good to go, so start the backup alarms
341                    if (MORE_DEBUG) Slog.d(TAG, "Now provisioned, so starting backups");
342                    startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
343                }
344            }
345        }
346    }
347
348    class RestoreGetSetsParams {
349        public IBackupTransport transport;
350        public ActiveRestoreSession session;
351        public IRestoreObserver observer;
352
353        RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
354                IRestoreObserver _observer) {
355            transport = _transport;
356            session = _session;
357            observer = _observer;
358        }
359    }
360
361    class RestoreParams {
362        public IBackupTransport transport;
363        public String dirName;
364        public IRestoreObserver observer;
365        public long token;
366        public PackageInfo pkgInfo;
367        public int pmToken; // in post-install restore, the PM's token for this transaction
368        public boolean isSystemRestore;
369        public String[] filterSet;
370
371        // Restore a single package
372        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
373                long _token, PackageInfo _pkg, int _pmToken) {
374            transport = _transport;
375            dirName = _dirName;
376            observer = _obs;
377            token = _token;
378            pkgInfo = _pkg;
379            pmToken = _pmToken;
380            isSystemRestore = false;
381            filterSet = null;
382        }
383
384        // Restore everything possible.  This is the form that Setup Wizard or similar
385        // restore UXes use.
386        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
387                long _token) {
388            transport = _transport;
389            dirName = _dirName;
390            observer = _obs;
391            token = _token;
392            pkgInfo = null;
393            pmToken = 0;
394            isSystemRestore = true;
395            filterSet = null;
396        }
397
398        // Restore some set of packages.  Leave this one up to the caller to specify
399        // whether it's to be considered a system-level restore.
400        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
401                long _token, String[] _filterSet, boolean _isSystemRestore) {
402            transport = _transport;
403            dirName = _dirName;
404            observer = _obs;
405            token = _token;
406            pkgInfo = null;
407            pmToken = 0;
408            isSystemRestore = _isSystemRestore;
409            filterSet = _filterSet;
410        }
411    }
412
413    class ClearParams {
414        public IBackupTransport transport;
415        public PackageInfo packageInfo;
416
417        ClearParams(IBackupTransport _transport, PackageInfo _info) {
418            transport = _transport;
419            packageInfo = _info;
420        }
421    }
422
423    class ClearRetryParams {
424        public String transportName;
425        public String packageName;
426
427        ClearRetryParams(String transport, String pkg) {
428            transportName = transport;
429            packageName = pkg;
430        }
431    }
432
433    class FullParams {
434        public ParcelFileDescriptor fd;
435        public final AtomicBoolean latch;
436        public IFullBackupRestoreObserver observer;
437        public String curPassword;     // filled in by the confirmation step
438        public String encryptPassword;
439
440        FullParams() {
441            latch = new AtomicBoolean(false);
442        }
443    }
444
445    class FullBackupParams extends FullParams {
446        public boolean includeApks;
447        public boolean includeObbs;
448        public boolean includeShared;
449        public boolean doWidgets;
450        public boolean allApps;
451        public boolean includeSystem;
452        public String[] packages;
453
454        FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveObbs,
455                boolean saveShared, boolean alsoWidgets, boolean doAllApps, boolean doSystem,
456                String[] pkgList) {
457            fd = output;
458            includeApks = saveApks;
459            includeObbs = saveObbs;
460            includeShared = saveShared;
461            doWidgets = alsoWidgets;
462            allApps = doAllApps;
463            includeSystem = doSystem;
464            packages = pkgList;
465        }
466    }
467
468    class FullRestoreParams extends FullParams {
469        FullRestoreParams(ParcelFileDescriptor input) {
470            fd = input;
471        }
472    }
473
474    // Bookkeeping of in-flight operations for timeout etc. purposes.  The operation
475    // token is the index of the entry in the pending-operations list.
476    static final int OP_PENDING = 0;
477    static final int OP_ACKNOWLEDGED = 1;
478    static final int OP_TIMEOUT = -1;
479
480    class Operation {
481        public int state;
482        public BackupRestoreTask callback;
483
484        Operation(int initialState, BackupRestoreTask callbackObj) {
485            state = initialState;
486            callback = callbackObj;
487        }
488    }
489    final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
490    final Object mCurrentOpLock = new Object();
491    final Random mTokenGenerator = new Random();
492
493    final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
494
495    // Where we keep our journal files and other bookkeeping
496    File mBaseStateDir;
497    File mDataDir;
498    File mJournalDir;
499    File mJournal;
500
501    // Backup password, if any, and the file where it's saved.  What is stored is not the
502    // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
503    // persisted) salt.  Validation is performed by running the challenge text through the
504    // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
505    // the saved hash string, then the challenge text matches the originally supplied
506    // password text.
507    private final SecureRandom mRng = new SecureRandom();
508    private String mPasswordHash;
509    private File mPasswordHashFile;
510    private int mPasswordVersion;
511    private File mPasswordVersionFile;
512    private byte[] mPasswordSalt;
513
514    // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
515    static final int PBKDF2_HASH_ROUNDS = 10000;
516    static final int PBKDF2_KEY_SIZE = 256;     // bits
517    static final int PBKDF2_SALT_SIZE = 512;    // bits
518    static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
519
520    // Keep a log of all the apps we've ever backed up, and what the
521    // dataset tokens are for both the current backup dataset and
522    // the ancestral dataset.
523    private File mEverStored;
524    HashSet<String> mEverStoredApps = new HashSet<String>();
525
526    static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1;  // increment when the schema changes
527    File mTokenFile;
528    Set<String> mAncestralPackages = null;
529    long mAncestralToken = 0;
530    long mCurrentToken = 0;
531
532    // Persistently track the need to do a full init
533    static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
534    HashSet<String> mPendingInits = new HashSet<String>();  // transport names
535
536    // Utility: build a new random integer token
537    int generateToken() {
538        int token;
539        do {
540            synchronized (mTokenGenerator) {
541                token = mTokenGenerator.nextInt();
542            }
543        } while (token < 0);
544        return token;
545    }
546
547    // ----- Asynchronous backup/restore handler thread -----
548
549    private class BackupHandler extends Handler {
550        public BackupHandler(Looper looper) {
551            super(looper);
552        }
553
554        public void handleMessage(Message msg) {
555
556            switch (msg.what) {
557            case MSG_RUN_BACKUP:
558            {
559                mLastBackupPass = System.currentTimeMillis();
560                mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
561
562                IBackupTransport transport = getTransport(mCurrentTransport);
563                if (transport == null) {
564                    Slog.v(TAG, "Backup requested but no transport available");
565                    synchronized (mQueueLock) {
566                        mBackupRunning = false;
567                    }
568                    mWakelock.release();
569                    break;
570                }
571
572                // snapshot the pending-backup set and work on that
573                ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
574                File oldJournal = mJournal;
575                synchronized (mQueueLock) {
576                    // Do we have any work to do?  Construct the work queue
577                    // then release the synchronization lock to actually run
578                    // the backup.
579                    if (mPendingBackups.size() > 0) {
580                        for (BackupRequest b: mPendingBackups.values()) {
581                            queue.add(b);
582                        }
583                        if (DEBUG) Slog.v(TAG, "clearing pending backups");
584                        mPendingBackups.clear();
585
586                        // Start a new backup-queue journal file too
587                        mJournal = null;
588
589                    }
590                }
591
592                // At this point, we have started a new journal file, and the old
593                // file identity is being passed to the backup processing task.
594                // When it completes successfully, that old journal file will be
595                // deleted.  If we crash prior to that, the old journal is parsed
596                // at next boot and the journaled requests fulfilled.
597                boolean staged = true;
598                if (queue.size() > 0) {
599                    // Spin up a backup state sequence and set it running
600                    try {
601                        String dirName = transport.transportDirName();
602                        PerformBackupTask pbt = new PerformBackupTask(transport, dirName,
603                                queue, oldJournal);
604                        Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
605                        sendMessage(pbtMessage);
606                    } catch (RemoteException e) {
607                        // unable to ask the transport its dir name -- transient failure, since
608                        // the above check succeeded.  Try again next time.
609                        Slog.e(TAG, "Transport became unavailable attempting backup");
610                        staged = false;
611                    }
612                } else {
613                    Slog.v(TAG, "Backup requested but nothing pending");
614                    staged = false;
615                }
616
617                if (!staged) {
618                    // if we didn't actually hand off the wakelock, rewind until next time
619                    synchronized (mQueueLock) {
620                        mBackupRunning = false;
621                    }
622                    mWakelock.release();
623                }
624                break;
625            }
626
627            case MSG_BACKUP_RESTORE_STEP:
628            {
629                try {
630                    BackupRestoreTask task = (BackupRestoreTask) msg.obj;
631                    if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
632                    task.execute();
633                } catch (ClassCastException e) {
634                    Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
635                }
636                break;
637            }
638
639            case MSG_OP_COMPLETE:
640            {
641                try {
642                    BackupRestoreTask task = (BackupRestoreTask) msg.obj;
643                    task.operationComplete();
644                } catch (ClassCastException e) {
645                    Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
646                }
647                break;
648            }
649
650            case MSG_RUN_FULL_BACKUP:
651            {
652                // TODO: refactor full backup to be a looper-based state machine
653                // similar to normal backup/restore.
654                FullBackupParams params = (FullBackupParams)msg.obj;
655                PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
656                        params.observer, params.includeApks, params.includeObbs,
657                        params.includeShared, params.doWidgets,
658                        params.curPassword, params.encryptPassword,
659                        params.allApps, params.includeSystem, params.packages, params.latch);
660                (new Thread(task)).start();
661                break;
662            }
663
664            case MSG_RUN_RESTORE:
665            {
666                RestoreParams params = (RestoreParams)msg.obj;
667                Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
668                PerformRestoreTask task = new PerformRestoreTask(
669                        params.transport, params.dirName, params.observer,
670                        params.token, params.pkgInfo, params.pmToken,
671                        params.isSystemRestore, params.filterSet);
672                Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
673                sendMessage(restoreMsg);
674                break;
675            }
676
677            case MSG_RUN_FULL_RESTORE:
678            {
679                // TODO: refactor full restore to be a looper-based state machine
680                // similar to normal backup/restore.
681                FullRestoreParams params = (FullRestoreParams)msg.obj;
682                PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
683                        params.curPassword, params.encryptPassword,
684                        params.observer, params.latch);
685                (new Thread(task)).start();
686                break;
687            }
688
689            case MSG_RUN_CLEAR:
690            {
691                ClearParams params = (ClearParams)msg.obj;
692                (new PerformClearTask(params.transport, params.packageInfo)).run();
693                break;
694            }
695
696            case MSG_RETRY_CLEAR:
697            {
698                // reenqueues if the transport remains unavailable
699                ClearRetryParams params = (ClearRetryParams)msg.obj;
700                clearBackupData(params.transportName, params.packageName);
701                break;
702            }
703
704            case MSG_RUN_INITIALIZE:
705            {
706                HashSet<String> queue;
707
708                // Snapshot the pending-init queue and work on that
709                synchronized (mQueueLock) {
710                    queue = new HashSet<String>(mPendingInits);
711                    mPendingInits.clear();
712                }
713
714                (new PerformInitializeTask(queue)).run();
715                break;
716            }
717
718            case MSG_RETRY_INIT:
719            {
720                synchronized (mQueueLock) {
721                    recordInitPendingLocked(msg.arg1 != 0, (String)msg.obj);
722                    mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
723                            mRunInitIntent);
724                }
725                break;
726            }
727
728            case MSG_RUN_GET_RESTORE_SETS:
729            {
730                // Like other async operations, this is entered with the wakelock held
731                RestoreSet[] sets = null;
732                RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
733                try {
734                    sets = params.transport.getAvailableRestoreSets();
735                    // cache the result in the active session
736                    synchronized (params.session) {
737                        params.session.mRestoreSets = sets;
738                    }
739                    if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
740                } catch (Exception e) {
741                    Slog.e(TAG, "Error from transport getting set list");
742                } finally {
743                    if (params.observer != null) {
744                        try {
745                            params.observer.restoreSetsAvailable(sets);
746                        } catch (RemoteException re) {
747                            Slog.e(TAG, "Unable to report listing to observer");
748                        } catch (Exception e) {
749                            Slog.e(TAG, "Restore observer threw", e);
750                        }
751                    }
752
753                    // Done: reset the session timeout clock
754                    removeMessages(MSG_RESTORE_TIMEOUT);
755                    sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
756
757                    mWakelock.release();
758                }
759                break;
760            }
761
762            case MSG_TIMEOUT:
763            {
764                handleTimeout(msg.arg1, msg.obj);
765                break;
766            }
767
768            case MSG_RESTORE_TIMEOUT:
769            {
770                synchronized (BackupManagerService.this) {
771                    if (mActiveRestoreSession != null) {
772                        // Client app left the restore session dangling.  We know that it
773                        // can't be in the middle of an actual restore operation because
774                        // the timeout is suspended while a restore is in progress.  Clean
775                        // up now.
776                        Slog.w(TAG, "Restore session timed out; aborting");
777                        post(mActiveRestoreSession.new EndRestoreRunnable(
778                                BackupManagerService.this, mActiveRestoreSession));
779                    }
780                }
781            }
782
783            case MSG_FULL_CONFIRMATION_TIMEOUT:
784            {
785                synchronized (mFullConfirmations) {
786                    FullParams params = mFullConfirmations.get(msg.arg1);
787                    if (params != null) {
788                        Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
789
790                        // Release the waiter; timeout == completion
791                        signalFullBackupRestoreCompletion(params);
792
793                        // Remove the token from the set
794                        mFullConfirmations.delete(msg.arg1);
795
796                        // Report a timeout to the observer, if any
797                        if (params.observer != null) {
798                            try {
799                                params.observer.onTimeout();
800                            } catch (RemoteException e) {
801                                /* don't care if the app has gone away */
802                            }
803                        }
804                    } else {
805                        Slog.d(TAG, "couldn't find params for token " + msg.arg1);
806                    }
807                }
808                break;
809            }
810
811            case MSG_WIDGET_BROADCAST:
812            {
813                final Intent intent = (Intent) msg.obj;
814                mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
815                break;
816            }
817            }
818        }
819    }
820
821    // ----- Debug-only backup operation trace -----
822    void addBackupTrace(String s) {
823        if (DEBUG_BACKUP_TRACE) {
824            synchronized (mBackupTrace) {
825                mBackupTrace.add(s);
826            }
827        }
828    }
829
830    void clearBackupTrace() {
831        if (DEBUG_BACKUP_TRACE) {
832            synchronized (mBackupTrace) {
833                mBackupTrace.clear();
834            }
835        }
836    }
837
838    // ----- Main service implementation -----
839
840    public BackupManagerService(Context context) {
841        mContext = context;
842        mPackageManager = context.getPackageManager();
843        mPackageManagerBinder = AppGlobals.getPackageManager();
844        mActivityManager = ActivityManagerNative.getDefault();
845
846        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
847        mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
848        mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
849
850        mBackupManagerBinder = asInterface(asBinder());
851
852        // spin up the backup/restore handler thread
853        mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
854        mHandlerThread.start();
855        mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
856
857        // Set up our bookkeeping
858        final ContentResolver resolver = context.getContentResolver();
859        boolean areEnabled = Settings.Secure.getInt(resolver,
860                Settings.Secure.BACKUP_ENABLED, 0) != 0;
861        mProvisioned = Settings.Global.getInt(resolver,
862                Settings.Global.DEVICE_PROVISIONED, 0) != 0;
863        mAutoRestore = Settings.Secure.getInt(resolver,
864                Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
865
866        mProvisionedObserver = new ProvisionedObserver(mBackupHandler);
867        resolver.registerContentObserver(
868                Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
869                false, mProvisionedObserver);
870
871        // If Encrypted file systems is enabled or disabled, this call will return the
872        // correct directory.
873        mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
874        mBaseStateDir.mkdirs();
875        if (!SELinux.restorecon(mBaseStateDir)) {
876            Slog.e(TAG, "SELinux restorecon failed on " + mBaseStateDir);
877        }
878        mDataDir = Environment.getDownloadCacheDirectory();
879
880        mPasswordVersion = 1;       // unless we hear otherwise
881        mPasswordVersionFile = new File(mBaseStateDir, "pwversion");
882        if (mPasswordVersionFile.exists()) {
883            FileInputStream fin = null;
884            DataInputStream in = null;
885            try {
886                fin = new FileInputStream(mPasswordVersionFile);
887                in = new DataInputStream(fin);
888                mPasswordVersion = in.readInt();
889            } catch (IOException e) {
890                Slog.e(TAG, "Unable to read backup pw version");
891            } finally {
892                try {
893                    if (in != null) in.close();
894                    if (fin != null) fin.close();
895                } catch (IOException e) {
896                    Slog.w(TAG, "Error closing pw version files");
897                }
898            }
899        }
900
901        mPasswordHashFile = new File(mBaseStateDir, "pwhash");
902        if (mPasswordHashFile.exists()) {
903            FileInputStream fin = null;
904            DataInputStream in = null;
905            try {
906                fin = new FileInputStream(mPasswordHashFile);
907                in = new DataInputStream(new BufferedInputStream(fin));
908                // integer length of the salt array, followed by the salt,
909                // then the hex pw hash string
910                int saltLen = in.readInt();
911                byte[] salt = new byte[saltLen];
912                in.readFully(salt);
913                mPasswordHash = in.readUTF();
914                mPasswordSalt = salt;
915            } catch (IOException e) {
916                Slog.e(TAG, "Unable to read saved backup pw hash");
917            } finally {
918                try {
919                    if (in != null) in.close();
920                    if (fin != null) fin.close();
921                } catch (IOException e) {
922                    Slog.w(TAG, "Unable to close streams");
923                }
924            }
925        }
926
927        // Alarm receivers for scheduled backups & initialization operations
928        mRunBackupReceiver = new RunBackupReceiver();
929        IntentFilter filter = new IntentFilter();
930        filter.addAction(RUN_BACKUP_ACTION);
931        context.registerReceiver(mRunBackupReceiver, filter,
932                android.Manifest.permission.BACKUP, null);
933
934        mRunInitReceiver = new RunInitializeReceiver();
935        filter = new IntentFilter();
936        filter.addAction(RUN_INITIALIZE_ACTION);
937        context.registerReceiver(mRunInitReceiver, filter,
938                android.Manifest.permission.BACKUP, null);
939
940        Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
941        backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
942        mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
943
944        Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
945        backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
946        mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
947
948        // Set up the backup-request journaling
949        mJournalDir = new File(mBaseStateDir, "pending");
950        mJournalDir.mkdirs();   // creates mBaseStateDir along the way
951        mJournal = null;        // will be created on first use
952
953        // Set up the various sorts of package tracking we do
954        initPackageTracking();
955
956        // Build our mapping of uid to backup client services.  This implicitly
957        // schedules a backup pass on the Package Manager metadata the first
958        // time anything needs to be backed up.
959        synchronized (mBackupParticipants) {
960            addPackageParticipantsLocked(null);
961        }
962
963        // Set up our transport options and initialize the default transport
964        // TODO: Don't create transports that we don't need to?
965        mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
966                Settings.Secure.BACKUP_TRANSPORT);
967        if ("".equals(mCurrentTransport)) {
968            mCurrentTransport = null;
969        }
970        if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
971
972        // Find transport hosts and bind to their services
973        Intent transportServiceIntent = new Intent(SERVICE_ACTION_TRANSPORT_HOST);
974        List<ResolveInfo> hosts = mPackageManager.queryIntentServicesAsUser(
975                transportServiceIntent, 0, UserHandle.USER_OWNER);
976        if (DEBUG) {
977            Slog.v(TAG, "Found transports: " + ((hosts == null) ? "null" : hosts.size()));
978        }
979        if (hosts != null) {
980            if (MORE_DEBUG) {
981                for (int i = 0; i < hosts.size(); i++) {
982                    ServiceInfo info = hosts.get(i).serviceInfo;
983                    Slog.v(TAG, "   " + info.packageName + "/" + info.name);
984                }
985            }
986            for (int i = 0; i < hosts.size(); i++) {
987                try {
988                    ServiceInfo info = hosts.get(i).serviceInfo;
989                    PackageInfo packInfo = mPackageManager.getPackageInfo(info.packageName, 0);
990                    if ((packInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
991                        ComponentName svcName = new ComponentName(info.packageName, info.name);
992                        if (DEBUG) {
993                            Slog.i(TAG, "Binding to transport host " + svcName);
994                        }
995                        Intent intent = new Intent(transportServiceIntent);
996                        intent.setComponent(svcName);
997                        TransportConnection connection = new TransportConnection();
998                        mTransportConnections.add(connection);
999                        context.bindServiceAsUser(intent,
1000                                connection, Context.BIND_AUTO_CREATE,
1001                                UserHandle.OWNER);
1002                    } else {
1003                        Slog.w(TAG, "Transport package not privileged: " + info.packageName);
1004                    }
1005                } catch (Exception e) {
1006                    Slog.e(TAG, "Problem resolving transport service: " + e.getMessage());
1007                }
1008            }
1009        }
1010
1011        // Now that we know about valid backup participants, parse any
1012        // leftover journal files into the pending backup set
1013        parseLeftoverJournals();
1014
1015        // Power management
1016        mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
1017
1018        // Start the backup passes going
1019        setBackupEnabled(areEnabled);
1020    }
1021
1022    private class RunBackupReceiver extends BroadcastReceiver {
1023        public void onReceive(Context context, Intent intent) {
1024            if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
1025                synchronized (mQueueLock) {
1026                    if (mPendingInits.size() > 0) {
1027                        // If there are pending init operations, we process those
1028                        // and then settle into the usual periodic backup schedule.
1029                        if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
1030                        try {
1031                            mAlarmManager.cancel(mRunInitIntent);
1032                            mRunInitIntent.send();
1033                        } catch (PendingIntent.CanceledException ce) {
1034                            Slog.e(TAG, "Run init intent cancelled");
1035                            // can't really do more than bail here
1036                        }
1037                    } else {
1038                        // Don't run backups now if we're disabled or not yet
1039                        // fully set up.
1040                        if (mEnabled && mProvisioned) {
1041                            if (!mBackupRunning) {
1042                                if (DEBUG) Slog.v(TAG, "Running a backup pass");
1043
1044                                // Acquire the wakelock and pass it to the backup thread.  it will
1045                                // be released once backup concludes.
1046                                mBackupRunning = true;
1047                                mWakelock.acquire();
1048
1049                                Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
1050                                mBackupHandler.sendMessage(msg);
1051                            } else {
1052                                Slog.i(TAG, "Backup time but one already running");
1053                            }
1054                        } else {
1055                            Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
1056                        }
1057                    }
1058                }
1059            }
1060        }
1061    }
1062
1063    private class RunInitializeReceiver extends BroadcastReceiver {
1064        public void onReceive(Context context, Intent intent) {
1065            if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
1066                synchronized (mQueueLock) {
1067                    if (DEBUG) Slog.v(TAG, "Running a device init");
1068
1069                    // Acquire the wakelock and pass it to the init thread.  it will
1070                    // be released once init concludes.
1071                    mWakelock.acquire();
1072
1073                    Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
1074                    mBackupHandler.sendMessage(msg);
1075                }
1076            }
1077        }
1078    }
1079
1080    private void initPackageTracking() {
1081        if (DEBUG) Slog.v(TAG, "Initializing package tracking");
1082
1083        // Remember our ancestral dataset
1084        mTokenFile = new File(mBaseStateDir, "ancestral");
1085        try {
1086            RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
1087            int version = tf.readInt();
1088            if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
1089                mAncestralToken = tf.readLong();
1090                mCurrentToken = tf.readLong();
1091
1092                int numPackages = tf.readInt();
1093                if (numPackages >= 0) {
1094                    mAncestralPackages = new HashSet<String>();
1095                    for (int i = 0; i < numPackages; i++) {
1096                        String pkgName = tf.readUTF();
1097                        mAncestralPackages.add(pkgName);
1098                    }
1099                }
1100            }
1101            tf.close();
1102        } catch (FileNotFoundException fnf) {
1103            // Probably innocuous
1104            Slog.v(TAG, "No ancestral data");
1105        } catch (IOException e) {
1106            Slog.w(TAG, "Unable to read token file", e);
1107        }
1108
1109        // Keep a log of what apps we've ever backed up.  Because we might have
1110        // rebooted in the middle of an operation that was removing something from
1111        // this log, we sanity-check its contents here and reconstruct it.
1112        mEverStored = new File(mBaseStateDir, "processed");
1113        File tempProcessedFile = new File(mBaseStateDir, "processed.new");
1114
1115        // If we were in the middle of removing something from the ever-backed-up
1116        // file, there might be a transient "processed.new" file still present.
1117        // Ignore it -- we'll validate "processed" against the current package set.
1118        if (tempProcessedFile.exists()) {
1119            tempProcessedFile.delete();
1120        }
1121
1122        // If there are previous contents, parse them out then start a new
1123        // file to continue the recordkeeping.
1124        if (mEverStored.exists()) {
1125            RandomAccessFile temp = null;
1126            RandomAccessFile in = null;
1127
1128            try {
1129                temp = new RandomAccessFile(tempProcessedFile, "rws");
1130                in = new RandomAccessFile(mEverStored, "r");
1131
1132                while (true) {
1133                    PackageInfo info;
1134                    String pkg = in.readUTF();
1135                    try {
1136                        info = mPackageManager.getPackageInfo(pkg, 0);
1137                        mEverStoredApps.add(pkg);
1138                        temp.writeUTF(pkg);
1139                        if (MORE_DEBUG) Slog.v(TAG, "   + " + pkg);
1140                    } catch (NameNotFoundException e) {
1141                        // nope, this package was uninstalled; don't include it
1142                        if (MORE_DEBUG) Slog.v(TAG, "   - " + pkg);
1143                    }
1144                }
1145            } catch (EOFException e) {
1146                // Once we've rewritten the backup history log, atomically replace the
1147                // old one with the new one then reopen the file for continuing use.
1148                if (!tempProcessedFile.renameTo(mEverStored)) {
1149                    Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
1150                }
1151            } catch (IOException e) {
1152                Slog.e(TAG, "Error in processed file", e);
1153            } finally {
1154                try { if (temp != null) temp.close(); } catch (IOException e) {}
1155                try { if (in != null) in.close(); } catch (IOException e) {}
1156            }
1157        }
1158
1159        // Register for broadcasts about package install, etc., so we can
1160        // update the provider list.
1161        IntentFilter filter = new IntentFilter();
1162        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1163        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1164        filter.addDataScheme("package");
1165        mContext.registerReceiver(mBroadcastReceiver, filter);
1166        // Register for events related to sdcard installation.
1167        IntentFilter sdFilter = new IntentFilter();
1168        sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1169        sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1170        mContext.registerReceiver(mBroadcastReceiver, sdFilter);
1171    }
1172
1173    private void parseLeftoverJournals() {
1174        for (File f : mJournalDir.listFiles()) {
1175            if (mJournal == null || f.compareTo(mJournal) != 0) {
1176                // This isn't the current journal, so it must be a leftover.  Read
1177                // out the package names mentioned there and schedule them for
1178                // backup.
1179                RandomAccessFile in = null;
1180                try {
1181                    Slog.i(TAG, "Found stale backup journal, scheduling");
1182                    in = new RandomAccessFile(f, "r");
1183                    while (true) {
1184                        String packageName = in.readUTF();
1185                        Slog.i(TAG, "  " + packageName);
1186                        dataChangedImpl(packageName);
1187                    }
1188                } catch (EOFException e) {
1189                    // no more data; we're done
1190                } catch (Exception e) {
1191                    Slog.e(TAG, "Can't read " + f, e);
1192                } finally {
1193                    // close/delete the file
1194                    try { if (in != null) in.close(); } catch (IOException e) {}
1195                    f.delete();
1196                }
1197            }
1198        }
1199    }
1200
1201    private SecretKey buildPasswordKey(String algorithm, String pw, byte[] salt, int rounds) {
1202        return buildCharArrayKey(algorithm, pw.toCharArray(), salt, rounds);
1203    }
1204
1205    private SecretKey buildCharArrayKey(String algorithm, char[] pwArray, byte[] salt, int rounds) {
1206        try {
1207            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
1208            KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1209            return keyFactory.generateSecret(ks);
1210        } catch (InvalidKeySpecException e) {
1211            Slog.e(TAG, "Invalid key spec for PBKDF2!");
1212        } catch (NoSuchAlgorithmException e) {
1213            Slog.e(TAG, "PBKDF2 unavailable!");
1214        }
1215        return null;
1216    }
1217
1218    private String buildPasswordHash(String algorithm, String pw, byte[] salt, int rounds) {
1219        SecretKey key = buildPasswordKey(algorithm, pw, salt, rounds);
1220        if (key != null) {
1221            return byteArrayToHex(key.getEncoded());
1222        }
1223        return null;
1224    }
1225
1226    private String byteArrayToHex(byte[] data) {
1227        StringBuilder buf = new StringBuilder(data.length * 2);
1228        for (int i = 0; i < data.length; i++) {
1229            buf.append(Byte.toHexString(data[i], true));
1230        }
1231        return buf.toString();
1232    }
1233
1234    private byte[] hexToByteArray(String digits) {
1235        final int bytes = digits.length() / 2;
1236        if (2*bytes != digits.length()) {
1237            throw new IllegalArgumentException("Hex string must have an even number of digits");
1238        }
1239
1240        byte[] result = new byte[bytes];
1241        for (int i = 0; i < digits.length(); i += 2) {
1242            result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1243        }
1244        return result;
1245    }
1246
1247    private byte[] makeKeyChecksum(String algorithm, byte[] pwBytes, byte[] salt, int rounds) {
1248        char[] mkAsChar = new char[pwBytes.length];
1249        for (int i = 0; i < pwBytes.length; i++) {
1250            mkAsChar[i] = (char) pwBytes[i];
1251        }
1252
1253        Key checksum = buildCharArrayKey(algorithm, mkAsChar, salt, rounds);
1254        return checksum.getEncoded();
1255    }
1256
1257    // Used for generating random salts or passwords
1258    private byte[] randomBytes(int bits) {
1259        byte[] array = new byte[bits / 8];
1260        mRng.nextBytes(array);
1261        return array;
1262    }
1263
1264    // Backup password management
1265    boolean passwordMatchesSaved(String algorithm, String candidatePw, int rounds) {
1266        // First, on an encrypted device we require matching the device pw
1267        final boolean isEncrypted;
1268        try {
1269            isEncrypted = (mMountService.getEncryptionState() !=
1270                    IMountService.ENCRYPTION_STATE_NONE);
1271            if (isEncrypted) {
1272                if (DEBUG) {
1273                    Slog.i(TAG, "Device encrypted; verifying against device data pw");
1274                }
1275                // 0 means the password validated
1276                // -2 means device not encrypted
1277                // Any other result is either password failure or an error condition,
1278                // so we refuse the match
1279                final int result = mMountService.verifyEncryptionPassword(candidatePw);
1280                if (result == 0) {
1281                    if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
1282                    return true;
1283                } else if (result != -2) {
1284                    if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
1285                    return false;
1286                } else {
1287                    // ...else the device is supposedly not encrypted.  HOWEVER, the
1288                    // query about the encryption state said that the device *is*
1289                    // encrypted, so ... we may have a problem.  Log it and refuse
1290                    // the backup.
1291                    Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
1292                    return false;
1293                }
1294            }
1295        } catch (Exception e) {
1296            // Something went wrong talking to the mount service.  This is very bad;
1297            // assume that we fail password validation.
1298            return false;
1299        }
1300
1301        if (mPasswordHash == null) {
1302            // no current password case -- require that 'currentPw' be null or empty
1303            if (candidatePw == null || "".equals(candidatePw)) {
1304                return true;
1305            } // else the non-empty candidate does not match the empty stored pw
1306        } else {
1307            // hash the stated current pw and compare to the stored one
1308            if (candidatePw != null && candidatePw.length() > 0) {
1309                String currentPwHash = buildPasswordHash(algorithm, candidatePw, mPasswordSalt, rounds);
1310                if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1311                    // candidate hash matches the stored hash -- the password matches
1312                    return true;
1313                }
1314            } // else the stored pw is nonempty but the candidate is empty; no match
1315        }
1316        return false;
1317    }
1318
1319    @Override
1320    public boolean setBackupPassword(String currentPw, String newPw) {
1321        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1322                "setBackupPassword");
1323
1324        // When processing v1 passwords we may need to try two different PBKDF2 checksum regimes
1325        final boolean pbkdf2Fallback = (mPasswordVersion < BACKUP_PW_FILE_VERSION);
1326
1327        // If the supplied pw doesn't hash to the the saved one, fail.  The password
1328        // might be caught in the legacy crypto mismatch; verify that too.
1329        if (!passwordMatchesSaved(PBKDF_CURRENT, currentPw, PBKDF2_HASH_ROUNDS)
1330                && !(pbkdf2Fallback && passwordMatchesSaved(PBKDF_FALLBACK,
1331                        currentPw, PBKDF2_HASH_ROUNDS))) {
1332            return false;
1333        }
1334
1335        // Snap up to current on the pw file version
1336        mPasswordVersion = BACKUP_PW_FILE_VERSION;
1337        FileOutputStream pwFout = null;
1338        DataOutputStream pwOut = null;
1339        try {
1340            pwFout = new FileOutputStream(mPasswordVersionFile);
1341            pwOut = new DataOutputStream(pwFout);
1342            pwOut.writeInt(mPasswordVersion);
1343        } catch (IOException e) {
1344            Slog.e(TAG, "Unable to write backup pw version; password not changed");
1345            return false;
1346        } finally {
1347            try {
1348                if (pwOut != null) pwOut.close();
1349                if (pwFout != null) pwFout.close();
1350            } catch (IOException e) {
1351                Slog.w(TAG, "Unable to close pw version record");
1352            }
1353        }
1354
1355        // Clearing the password is okay
1356        if (newPw == null || newPw.isEmpty()) {
1357            if (mPasswordHashFile.exists()) {
1358                if (!mPasswordHashFile.delete()) {
1359                    // Unable to delete the old pw file, so fail
1360                    Slog.e(TAG, "Unable to clear backup password");
1361                    return false;
1362                }
1363            }
1364            mPasswordHash = null;
1365            mPasswordSalt = null;
1366            return true;
1367        }
1368
1369        try {
1370            // Okay, build the hash of the new backup password
1371            byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1372            String newPwHash = buildPasswordHash(PBKDF_CURRENT, newPw, salt, PBKDF2_HASH_ROUNDS);
1373
1374            OutputStream pwf = null, buffer = null;
1375            DataOutputStream out = null;
1376            try {
1377                pwf = new FileOutputStream(mPasswordHashFile);
1378                buffer = new BufferedOutputStream(pwf);
1379                out = new DataOutputStream(buffer);
1380                // integer length of the salt array, followed by the salt,
1381                // then the hex pw hash string
1382                out.writeInt(salt.length);
1383                out.write(salt);
1384                out.writeUTF(newPwHash);
1385                out.flush();
1386                mPasswordHash = newPwHash;
1387                mPasswordSalt = salt;
1388                return true;
1389            } finally {
1390                if (out != null) out.close();
1391                if (buffer != null) buffer.close();
1392                if (pwf != null) pwf.close();
1393            }
1394        } catch (IOException e) {
1395            Slog.e(TAG, "Unable to set backup password");
1396        }
1397        return false;
1398    }
1399
1400    @Override
1401    public boolean hasBackupPassword() {
1402        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1403                "hasBackupPassword");
1404
1405        try {
1406            return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
1407                || (mPasswordHash != null && mPasswordHash.length() > 0);
1408        } catch (Exception e) {
1409            // If we can't talk to the mount service we have a serious problem; fail
1410            // "secure" i.e. assuming that we require a password
1411            return true;
1412        }
1413    }
1414
1415    private boolean backupPasswordMatches(String currentPw) {
1416        if (hasBackupPassword()) {
1417            final boolean pbkdf2Fallback = (mPasswordVersion < BACKUP_PW_FILE_VERSION);
1418            if (!passwordMatchesSaved(PBKDF_CURRENT, currentPw, PBKDF2_HASH_ROUNDS)
1419                    && !(pbkdf2Fallback && passwordMatchesSaved(PBKDF_FALLBACK,
1420                            currentPw, PBKDF2_HASH_ROUNDS))) {
1421                if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
1422                return false;
1423            }
1424        }
1425        return true;
1426    }
1427
1428    // Maintain persistent state around whether need to do an initialize operation.
1429    // Must be called with the queue lock held.
1430    void recordInitPendingLocked(boolean isPending, String transportName) {
1431        if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
1432                + " on transport " + transportName);
1433        mBackupHandler.removeMessages(MSG_RETRY_INIT);
1434
1435        try {
1436            IBackupTransport transport = getTransport(transportName);
1437            if (transport != null) {
1438                String transportDirName = transport.transportDirName();
1439                File stateDir = new File(mBaseStateDir, transportDirName);
1440                File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1441
1442                if (isPending) {
1443                    // We need an init before we can proceed with sending backup data.
1444                    // Record that with an entry in our set of pending inits, as well as
1445                    // journaling it via creation of a sentinel file.
1446                    mPendingInits.add(transportName);
1447                    try {
1448                        (new FileOutputStream(initPendingFile)).close();
1449                    } catch (IOException ioe) {
1450                        // Something is badly wrong with our permissions; just try to move on
1451                    }
1452                } else {
1453                    // No more initialization needed; wipe the journal and reset our state.
1454                    initPendingFile.delete();
1455                    mPendingInits.remove(transportName);
1456                }
1457                return; // done; don't fall through to the error case
1458            }
1459        } catch (RemoteException e) {
1460            // transport threw when asked its name; fall through to the lookup-failed case
1461        }
1462
1463        // The named transport doesn't exist or threw.  This operation is
1464        // important, so we record the need for a an init and post a message
1465        // to retry the init later.
1466        if (isPending) {
1467            mPendingInits.add(transportName);
1468            mBackupHandler.sendMessageDelayed(
1469                    mBackupHandler.obtainMessage(MSG_RETRY_INIT,
1470                            (isPending ? 1 : 0),
1471                            0,
1472                            transportName),
1473                    TRANSPORT_RETRY_INTERVAL);
1474        }
1475    }
1476
1477    // Reset all of our bookkeeping, in response to having been told that
1478    // the backend data has been wiped [due to idle expiry, for example],
1479    // so we must re-upload all saved settings.
1480    void resetBackupState(File stateFileDir) {
1481        synchronized (mQueueLock) {
1482            // Wipe the "what we've ever backed up" tracking
1483            mEverStoredApps.clear();
1484            mEverStored.delete();
1485
1486            mCurrentToken = 0;
1487            writeRestoreTokens();
1488
1489            // Remove all the state files
1490            for (File sf : stateFileDir.listFiles()) {
1491                // ... but don't touch the needs-init sentinel
1492                if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1493                    sf.delete();
1494                }
1495            }
1496        }
1497
1498        // Enqueue a new backup of every participant
1499        synchronized (mBackupParticipants) {
1500            final int N = mBackupParticipants.size();
1501            for (int i=0; i<N; i++) {
1502                HashSet<String> participants = mBackupParticipants.valueAt(i);
1503                if (participants != null) {
1504                    for (String packageName : participants) {
1505                        dataChangedImpl(packageName);
1506                    }
1507                }
1508            }
1509        }
1510    }
1511
1512    // Add a transport to our set of available backends.  If 'transport' is null, this
1513    // is an unregistration, and the transport's entry is removed from our bookkeeping.
1514    private void registerTransport(String name, String component, IBackupTransport transport) {
1515        synchronized (mTransports) {
1516            if (DEBUG) Slog.v(TAG, "Registering transport "
1517                    + component + "::" + name + " = " + transport);
1518            if (transport != null) {
1519                mTransports.put(name, transport);
1520                mTransportNames.put(component, name);
1521            } else {
1522                mTransports.remove(mTransportNames.get(component));
1523                mTransportNames.remove(component);
1524                // Nothing further to do in the unregistration case
1525                return;
1526            }
1527        }
1528
1529        // If the init sentinel file exists, we need to be sure to perform the init
1530        // as soon as practical.  We also create the state directory at registration
1531        // time to ensure it's present from the outset.
1532        try {
1533            String transportName = transport.transportDirName();
1534            File stateDir = new File(mBaseStateDir, transportName);
1535            stateDir.mkdirs();
1536
1537            File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1538            if (initSentinel.exists()) {
1539                synchronized (mQueueLock) {
1540                    mPendingInits.add(transportName);
1541
1542                    // TODO: pick a better starting time than now + 1 minute
1543                    long delay = 1000 * 60; // one minute, in milliseconds
1544                    mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1545                            System.currentTimeMillis() + delay, mRunInitIntent);
1546                }
1547            }
1548        } catch (RemoteException e) {
1549            // the transport threw when asked its file naming prefs; declare it invalid
1550            Slog.e(TAG, "Unable to register transport as " + name);
1551            mTransportNames.remove(component);
1552            mTransports.remove(name);
1553        }
1554    }
1555
1556    // ----- Track installation/removal of packages -----
1557    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1558        public void onReceive(Context context, Intent intent) {
1559            if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
1560
1561            String action = intent.getAction();
1562            boolean replacing = false;
1563            boolean added = false;
1564            Bundle extras = intent.getExtras();
1565            String pkgList[] = null;
1566            if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
1567                    Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1568                Uri uri = intent.getData();
1569                if (uri == null) {
1570                    return;
1571                }
1572                String pkgName = uri.getSchemeSpecificPart();
1573                if (pkgName != null) {
1574                    pkgList = new String[] { pkgName };
1575                }
1576                added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1577                replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
1578            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
1579                added = true;
1580                pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1581            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1582                added = false;
1583                pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1584            }
1585
1586            if (pkgList == null || pkgList.length == 0) {
1587                return;
1588            }
1589
1590            final int uid = extras.getInt(Intent.EXTRA_UID);
1591            if (added) {
1592                synchronized (mBackupParticipants) {
1593                    if (replacing) {
1594                        // This is the package-replaced case; we just remove the entry
1595                        // under the old uid and fall through to re-add.
1596                        removePackageParticipantsLocked(pkgList, uid);
1597                    }
1598                    addPackageParticipantsLocked(pkgList);
1599                }
1600            } else {
1601                if (replacing) {
1602                    // The package is being updated.  We'll receive a PACKAGE_ADDED shortly.
1603                } else {
1604                    synchronized (mBackupParticipants) {
1605                        removePackageParticipantsLocked(pkgList, uid);
1606                    }
1607                }
1608            }
1609        }
1610    };
1611
1612    // ----- Track connection to transports service -----
1613    class TransportConnection implements ServiceConnection {
1614        @Override
1615        public void onServiceConnected(ComponentName component, IBinder service) {
1616            if (DEBUG) Slog.v(TAG, "Connected to transport " + component);
1617            try {
1618                IBackupTransport transport = IBackupTransport.Stub.asInterface(service);
1619                registerTransport(transport.name(), component.flattenToShortString(), transport);
1620            } catch (RemoteException e) {
1621                Slog.e(TAG, "Unable to register transport " + component);
1622            }
1623        }
1624
1625        @Override
1626        public void onServiceDisconnected(ComponentName component) {
1627            if (DEBUG) Slog.v(TAG, "Disconnected from transport " + component);
1628            registerTransport(null, component.flattenToShortString(), null);
1629        }
1630    };
1631
1632    // Add the backup agents in the given packages to our set of known backup participants.
1633    // If 'packageNames' is null, adds all backup agents in the whole system.
1634    void addPackageParticipantsLocked(String[] packageNames) {
1635        // Look for apps that define the android:backupAgent attribute
1636        List<PackageInfo> targetApps = allAgentPackages();
1637        if (packageNames != null) {
1638            if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1639            for (String packageName : packageNames) {
1640                addPackageParticipantsLockedInner(packageName, targetApps);
1641            }
1642        } else {
1643            if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1644            addPackageParticipantsLockedInner(null, targetApps);
1645        }
1646    }
1647
1648    private void addPackageParticipantsLockedInner(String packageName,
1649            List<PackageInfo> targetPkgs) {
1650        if (MORE_DEBUG) {
1651            Slog.v(TAG, "Examining " + packageName + " for backup agent");
1652        }
1653
1654        for (PackageInfo pkg : targetPkgs) {
1655            if (packageName == null || pkg.packageName.equals(packageName)) {
1656                int uid = pkg.applicationInfo.uid;
1657                HashSet<String> set = mBackupParticipants.get(uid);
1658                if (set == null) {
1659                    set = new HashSet<String>();
1660                    mBackupParticipants.put(uid, set);
1661                }
1662                set.add(pkg.packageName);
1663                if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
1664
1665                // Schedule a backup for it on general principles
1666                if (DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName);
1667                dataChangedImpl(pkg.packageName);
1668            }
1669        }
1670    }
1671
1672    // Remove the given packages' entries from our known active set.
1673    void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
1674        if (packageNames == null) {
1675            Slog.w(TAG, "removePackageParticipants with null list");
1676            return;
1677        }
1678
1679        if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
1680                + " #" + packageNames.length);
1681        for (String pkg : packageNames) {
1682            // Known previous UID, so we know which package set to check
1683            HashSet<String> set = mBackupParticipants.get(oldUid);
1684            if (set != null && set.contains(pkg)) {
1685                removePackageFromSetLocked(set, pkg);
1686                if (set.isEmpty()) {
1687                    if (MORE_DEBUG) Slog.v(TAG, "  last one of this uid; purging set");
1688                    mBackupParticipants.remove(oldUid);
1689                }
1690            }
1691        }
1692    }
1693
1694    private void removePackageFromSetLocked(final HashSet<String> set,
1695            final String packageName) {
1696        if (set.contains(packageName)) {
1697            // Found it.  Remove this one package from the bookkeeping, and
1698            // if it's the last participating app under this uid we drop the
1699            // (now-empty) set as well.
1700            // Note that we deliberately leave it 'known' in the "ever backed up"
1701            // bookkeeping so that its current-dataset data will be retrieved
1702            // if the app is subsequently reinstalled
1703            if (MORE_DEBUG) Slog.v(TAG, "  removing participant " + packageName);
1704            set.remove(packageName);
1705            mPendingBackups.remove(packageName);
1706        }
1707    }
1708
1709    // Returns the set of all applications that define an android:backupAgent attribute
1710    List<PackageInfo> allAgentPackages() {
1711        // !!! TODO: cache this and regenerate only when necessary
1712        int flags = PackageManager.GET_SIGNATURES;
1713        List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1714        int N = packages.size();
1715        for (int a = N-1; a >= 0; a--) {
1716            PackageInfo pkg = packages.get(a);
1717            try {
1718                ApplicationInfo app = pkg.applicationInfo;
1719                if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
1720                        || app.backupAgentName == null) {
1721                    packages.remove(a);
1722                }
1723                else {
1724                    // we will need the shared library path, so look that up and store it here
1725                    app = mPackageManager.getApplicationInfo(pkg.packageName,
1726                            PackageManager.GET_SHARED_LIBRARY_FILES);
1727                    pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1728                }
1729            } catch (NameNotFoundException e) {
1730                packages.remove(a);
1731            }
1732        }
1733        return packages;
1734    }
1735
1736    // Called from the backup task: record that the given app has been successfully
1737    // backed up at least once
1738    void logBackupComplete(String packageName) {
1739        if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1740
1741        synchronized (mEverStoredApps) {
1742            if (!mEverStoredApps.add(packageName)) return;
1743
1744            RandomAccessFile out = null;
1745            try {
1746                out = new RandomAccessFile(mEverStored, "rws");
1747                out.seek(out.length());
1748                out.writeUTF(packageName);
1749            } catch (IOException e) {
1750                Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
1751            } finally {
1752                try { if (out != null) out.close(); } catch (IOException e) {}
1753            }
1754        }
1755    }
1756
1757    // Remove our awareness of having ever backed up the given package
1758    void removeEverBackedUp(String packageName) {
1759        if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1760        if (MORE_DEBUG) Slog.v(TAG, "New set:");
1761
1762        synchronized (mEverStoredApps) {
1763            // Rewrite the file and rename to overwrite.  If we reboot in the middle,
1764            // we'll recognize on initialization time that the package no longer
1765            // exists and fix it up then.
1766            File tempKnownFile = new File(mBaseStateDir, "processed.new");
1767            RandomAccessFile known = null;
1768            try {
1769                known = new RandomAccessFile(tempKnownFile, "rws");
1770                mEverStoredApps.remove(packageName);
1771                for (String s : mEverStoredApps) {
1772                    known.writeUTF(s);
1773                    if (MORE_DEBUG) Slog.v(TAG, "    " + s);
1774                }
1775                known.close();
1776                known = null;
1777                if (!tempKnownFile.renameTo(mEverStored)) {
1778                    throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1779                }
1780            } catch (IOException e) {
1781                // Bad: we couldn't create the new copy.  For safety's sake we
1782                // abandon the whole process and remove all what's-backed-up
1783                // state entirely, meaning we'll force a backup pass for every
1784                // participant on the next boot or [re]install.
1785                Slog.w(TAG, "Error rewriting " + mEverStored, e);
1786                mEverStoredApps.clear();
1787                tempKnownFile.delete();
1788                mEverStored.delete();
1789            } finally {
1790                try { if (known != null) known.close(); } catch (IOException e) {}
1791            }
1792        }
1793    }
1794
1795    // Persistently record the current and ancestral backup tokens as well
1796    // as the set of packages with data [supposedly] available in the
1797    // ancestral dataset.
1798    void writeRestoreTokens() {
1799        try {
1800            RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
1801
1802            // First, the version number of this record, for futureproofing
1803            af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1804
1805            // Write the ancestral and current tokens
1806            af.writeLong(mAncestralToken);
1807            af.writeLong(mCurrentToken);
1808
1809            // Now write the set of ancestral packages
1810            if (mAncestralPackages == null) {
1811                af.writeInt(-1);
1812            } else {
1813                af.writeInt(mAncestralPackages.size());
1814                if (DEBUG) Slog.v(TAG, "Ancestral packages:  " + mAncestralPackages.size());
1815                for (String pkgName : mAncestralPackages) {
1816                    af.writeUTF(pkgName);
1817                    if (MORE_DEBUG) Slog.v(TAG, "   " + pkgName);
1818                }
1819            }
1820            af.close();
1821        } catch (IOException e) {
1822            Slog.w(TAG, "Unable to write token file:", e);
1823        }
1824    }
1825
1826    // Return the given transport
1827    private IBackupTransport getTransport(String transportName) {
1828        synchronized (mTransports) {
1829            IBackupTransport transport = mTransports.get(transportName);
1830            if (transport == null) {
1831                Slog.w(TAG, "Requested unavailable transport: " + transportName);
1832            }
1833            return transport;
1834        }
1835    }
1836
1837    // fire off a backup agent, blocking until it attaches or times out
1838    IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1839        IBackupAgent agent = null;
1840        synchronized(mAgentConnectLock) {
1841            mConnecting = true;
1842            mConnectedAgent = null;
1843            try {
1844                if (mActivityManager.bindBackupAgent(app, mode)) {
1845                    Slog.d(TAG, "awaiting agent for " + app);
1846
1847                    // success; wait for the agent to arrive
1848                    // only wait 10 seconds for the bind to happen
1849                    long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1850                    while (mConnecting && mConnectedAgent == null
1851                            && (System.currentTimeMillis() < timeoutMark)) {
1852                        try {
1853                            mAgentConnectLock.wait(5000);
1854                        } catch (InterruptedException e) {
1855                            // just bail
1856                            if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
1857                            mActivityManager.clearPendingBackup();
1858                            return null;
1859                        }
1860                    }
1861
1862                    // if we timed out with no connect, abort and move on
1863                    if (mConnecting == true) {
1864                        Slog.w(TAG, "Timeout waiting for agent " + app);
1865                        mActivityManager.clearPendingBackup();
1866                        return null;
1867                    }
1868                    if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
1869                    agent = mConnectedAgent;
1870                }
1871            } catch (RemoteException e) {
1872                // can't happen - ActivityManager is local
1873            }
1874        }
1875        return agent;
1876    }
1877
1878    // clear an application's data, blocking until the operation completes or times out
1879    void clearApplicationDataSynchronous(String packageName) {
1880        // Don't wipe packages marked allowClearUserData=false
1881        try {
1882            PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1883            if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
1884                if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
1885                        + packageName);
1886                return;
1887            }
1888        } catch (NameNotFoundException e) {
1889            Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
1890            return;
1891        }
1892
1893        ClearDataObserver observer = new ClearDataObserver();
1894
1895        synchronized(mClearDataLock) {
1896            mClearingData = true;
1897            try {
1898                mActivityManager.clearApplicationUserData(packageName, observer, 0);
1899            } catch (RemoteException e) {
1900                // can't happen because the activity manager is in this process
1901            }
1902
1903            // only wait 10 seconds for the clear data to happen
1904            long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1905            while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1906                try {
1907                    mClearDataLock.wait(5000);
1908                } catch (InterruptedException e) {
1909                    // won't happen, but still.
1910                    mClearingData = false;
1911                }
1912            }
1913        }
1914    }
1915
1916    class ClearDataObserver extends IPackageDataObserver.Stub {
1917        public void onRemoveCompleted(String packageName, boolean succeeded) {
1918            synchronized(mClearDataLock) {
1919                mClearingData = false;
1920                mClearDataLock.notifyAll();
1921            }
1922        }
1923    }
1924
1925    // Get the restore-set token for the best-available restore set for this package:
1926    // the active set if possible, else the ancestral one.  Returns zero if none available.
1927    long getAvailableRestoreToken(String packageName) {
1928        long token = mAncestralToken;
1929        synchronized (mQueueLock) {
1930            if (mEverStoredApps.contains(packageName)) {
1931                token = mCurrentToken;
1932            }
1933        }
1934        return token;
1935    }
1936
1937    // -----
1938    // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1939
1940    interface BackupRestoreTask {
1941        // Execute one tick of whatever state machine the task implements
1942        void execute();
1943
1944        // An operation that wanted a callback has completed
1945        void operationComplete();
1946
1947        // An operation that wanted a callback has timed out
1948        void handleTimeout();
1949    }
1950
1951    void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1952        if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1953                + " interval=" + interval);
1954        synchronized (mCurrentOpLock) {
1955            mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1956
1957            Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1958            mBackupHandler.sendMessageDelayed(msg, interval);
1959        }
1960    }
1961
1962    // synchronous waiter case
1963    boolean waitUntilOperationComplete(int token) {
1964        if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1965                + Integer.toHexString(token));
1966        int finalState = OP_PENDING;
1967        Operation op = null;
1968        synchronized (mCurrentOpLock) {
1969            while (true) {
1970                op = mCurrentOperations.get(token);
1971                if (op == null) {
1972                    // mysterious disappearance: treat as success with no callback
1973                    break;
1974                } else {
1975                    if (op.state == OP_PENDING) {
1976                        try {
1977                            mCurrentOpLock.wait();
1978                        } catch (InterruptedException e) {}
1979                        // When the wait is notified we loop around and recheck the current state
1980                    } else {
1981                        // No longer pending; we're done
1982                        finalState = op.state;
1983                        break;
1984                    }
1985                }
1986            }
1987        }
1988
1989        mBackupHandler.removeMessages(MSG_TIMEOUT);
1990        if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
1991                + " complete: finalState=" + finalState);
1992        return finalState == OP_ACKNOWLEDGED;
1993    }
1994
1995    void handleTimeout(int token, Object obj) {
1996        // Notify any synchronous waiters
1997        Operation op = null;
1998        synchronized (mCurrentOpLock) {
1999            op = mCurrentOperations.get(token);
2000            if (MORE_DEBUG) {
2001                if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
2002                        + " but no op found");
2003            }
2004            int state = (op != null) ? op.state : OP_TIMEOUT;
2005            if (state == OP_PENDING) {
2006                if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
2007                op.state = OP_TIMEOUT;
2008                mCurrentOperations.put(token, op);
2009            }
2010            mCurrentOpLock.notifyAll();
2011        }
2012
2013        // If there's a TimeoutHandler for this event, call it
2014        if (op != null && op.callback != null) {
2015            op.callback.handleTimeout();
2016        }
2017    }
2018
2019    // ----- Back up a set of applications via a worker thread -----
2020
2021    enum BackupState {
2022        INITIAL,
2023        RUNNING_QUEUE,
2024        FINAL
2025    }
2026
2027    class PerformBackupTask implements BackupRestoreTask {
2028        private static final String TAG = "PerformBackupTask";
2029
2030        IBackupTransport mTransport;
2031        ArrayList<BackupRequest> mQueue;
2032        ArrayList<BackupRequest> mOriginalQueue;
2033        File mStateDir;
2034        File mJournal;
2035        BackupState mCurrentState;
2036
2037        // carried information about the current in-flight operation
2038        IBackupAgent mAgentBinder;
2039        PackageInfo mCurrentPackage;
2040        File mSavedStateName;
2041        File mBackupDataName;
2042        File mNewStateName;
2043        ParcelFileDescriptor mSavedState;
2044        ParcelFileDescriptor mBackupData;
2045        ParcelFileDescriptor mNewState;
2046        int mStatus;
2047        boolean mFinished;
2048
2049        public PerformBackupTask(IBackupTransport transport, String dirName,
2050                ArrayList<BackupRequest> queue, File journal) {
2051            mTransport = transport;
2052            mOriginalQueue = queue;
2053            mJournal = journal;
2054
2055            mStateDir = new File(mBaseStateDir, dirName);
2056
2057            mCurrentState = BackupState.INITIAL;
2058            mFinished = false;
2059
2060            addBackupTrace("STATE => INITIAL");
2061        }
2062
2063        // Main entry point: perform one chunk of work, updating the state as appropriate
2064        // and reposting the next chunk to the primary backup handler thread.
2065        @Override
2066        public void execute() {
2067            switch (mCurrentState) {
2068                case INITIAL:
2069                    beginBackup();
2070                    break;
2071
2072                case RUNNING_QUEUE:
2073                    invokeNextAgent();
2074                    break;
2075
2076                case FINAL:
2077                    if (!mFinished) finalizeBackup();
2078                    else {
2079                        Slog.e(TAG, "Duplicate finish");
2080                    }
2081                    mFinished = true;
2082                    break;
2083            }
2084        }
2085
2086        // We're starting a backup pass.  Initialize the transport and send
2087        // the PM metadata blob if we haven't already.
2088        void beginBackup() {
2089            if (DEBUG_BACKUP_TRACE) {
2090                clearBackupTrace();
2091                StringBuilder b = new StringBuilder(256);
2092                b.append("beginBackup: [");
2093                for (BackupRequest req : mOriginalQueue) {
2094                    b.append(' ');
2095                    b.append(req.packageName);
2096                }
2097                b.append(" ]");
2098                addBackupTrace(b.toString());
2099            }
2100
2101            mAgentBinder = null;
2102            mStatus = BackupConstants.TRANSPORT_OK;
2103
2104            // Sanity check: if the queue is empty we have no work to do.
2105            if (mOriginalQueue.isEmpty()) {
2106                Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
2107                addBackupTrace("queue empty at begin");
2108                executeNextState(BackupState.FINAL);
2109                return;
2110            }
2111
2112            // We need to retain the original queue contents in case of transport
2113            // failure, but we want a working copy that we can manipulate along
2114            // the way.
2115            mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
2116
2117            if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
2118
2119            File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2120            try {
2121                final String transportName = mTransport.transportDirName();
2122                EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
2123
2124                // If we haven't stored package manager metadata yet, we must init the transport.
2125                if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
2126                    Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
2127                    addBackupTrace("initializing transport " + transportName);
2128                    resetBackupState(mStateDir);  // Just to make sure.
2129                    mStatus = mTransport.initializeDevice();
2130
2131                    addBackupTrace("transport.initializeDevice() == " + mStatus);
2132                    if (mStatus == BackupConstants.TRANSPORT_OK) {
2133                        EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
2134                    } else {
2135                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
2136                        Slog.e(TAG, "Transport error in initializeDevice()");
2137                    }
2138                }
2139
2140                // The package manager doesn't have a proper <application> etc, but since
2141                // it's running here in the system process we can just set up its agent
2142                // directly and use a synthetic BackupRequest.  We always run this pass
2143                // because it's cheap and this way we guarantee that we don't get out of
2144                // step even if we're selecting among various transports at run time.
2145                if (mStatus == BackupConstants.TRANSPORT_OK) {
2146                    PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
2147                            mPackageManager, allAgentPackages());
2148                    mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
2149                            IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
2150                    addBackupTrace("PMBA invoke: " + mStatus);
2151                }
2152
2153                if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
2154                    // The backend reports that our dataset has been wiped.  Note this in
2155                    // the event log; the no-success code below will reset the backup
2156                    // state as well.
2157                    EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
2158                }
2159            } catch (Exception e) {
2160                Slog.e(TAG, "Error in backup thread", e);
2161                addBackupTrace("Exception in backup thread: " + e);
2162                mStatus = BackupConstants.TRANSPORT_ERROR;
2163            } finally {
2164                // If we've succeeded so far, invokeAgentForBackup() will have run the PM
2165                // metadata and its completion/timeout callback will continue the state
2166                // machine chain.  If it failed that won't happen; we handle that now.
2167                addBackupTrace("exiting prelim: " + mStatus);
2168                if (mStatus != BackupConstants.TRANSPORT_OK) {
2169                    // if things went wrong at this point, we need to
2170                    // restage everything and try again later.
2171                    resetBackupState(mStateDir);  // Just to make sure.
2172                    executeNextState(BackupState.FINAL);
2173                }
2174            }
2175        }
2176
2177        // Transport has been initialized and the PM metadata submitted successfully
2178        // if that was warranted.  Now we process the single next thing in the queue.
2179        void invokeNextAgent() {
2180            mStatus = BackupConstants.TRANSPORT_OK;
2181            addBackupTrace("invoke q=" + mQueue.size());
2182
2183            // Sanity check that we have work to do.  If not, skip to the end where
2184            // we reestablish the wakelock invariants etc.
2185            if (mQueue.isEmpty()) {
2186                if (DEBUG) Slog.i(TAG, "queue now empty");
2187                executeNextState(BackupState.FINAL);
2188                return;
2189            }
2190
2191            // pop the entry we're going to process on this step
2192            BackupRequest request = mQueue.get(0);
2193            mQueue.remove(0);
2194
2195            Slog.d(TAG, "starting agent for backup of " + request);
2196            addBackupTrace("launch agent for " + request.packageName);
2197
2198            // Verify that the requested app exists; it might be something that
2199            // requested a backup but was then uninstalled.  The request was
2200            // journalled and rather than tamper with the journal it's safer
2201            // to sanity-check here.  This also gives us the classname of the
2202            // package's backup agent.
2203            try {
2204                mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
2205                        PackageManager.GET_SIGNATURES);
2206                if (mCurrentPackage.applicationInfo.backupAgentName == null) {
2207                    // The manifest has changed but we had a stale backup request pending.
2208                    // This won't happen again because the app won't be requesting further
2209                    // backups.
2210                    Slog.i(TAG, "Package " + request.packageName
2211                            + " no longer supports backup; skipping");
2212                    addBackupTrace("skipping - no agent, completion is noop");
2213                    executeNextState(BackupState.RUNNING_QUEUE);
2214                    return;
2215                }
2216
2217                if ((mCurrentPackage.applicationInfo.flags & ApplicationInfo.FLAG_STOPPED) != 0) {
2218                    // The app has been force-stopped or cleared or just installed,
2219                    // and not yet launched out of that state, so just as it won't
2220                    // receive broadcasts, we won't run it for backup.
2221                    addBackupTrace("skipping - stopped");
2222                    executeNextState(BackupState.RUNNING_QUEUE);
2223                    return;
2224                }
2225
2226                IBackupAgent agent = null;
2227                try {
2228                    mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
2229                    agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
2230                            IApplicationThread.BACKUP_MODE_INCREMENTAL);
2231                    addBackupTrace("agent bound; a? = " + (agent != null));
2232                    if (agent != null) {
2233                        mAgentBinder = agent;
2234                        mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
2235                        // at this point we'll either get a completion callback from the
2236                        // agent, or a timeout message on the main handler.  either way, we're
2237                        // done here as long as we're successful so far.
2238                    } else {
2239                        // Timeout waiting for the agent
2240                        mStatus = BackupConstants.AGENT_ERROR;
2241                    }
2242                } catch (SecurityException ex) {
2243                    // Try for the next one.
2244                    Slog.d(TAG, "error in bind/backup", ex);
2245                    mStatus = BackupConstants.AGENT_ERROR;
2246                            addBackupTrace("agent SE");
2247                }
2248            } catch (NameNotFoundException e) {
2249                Slog.d(TAG, "Package does not exist; skipping");
2250                addBackupTrace("no such package");
2251                mStatus = BackupConstants.AGENT_UNKNOWN;
2252            } finally {
2253                mWakelock.setWorkSource(null);
2254
2255                // If there was an agent error, no timeout/completion handling will occur.
2256                // That means we need to direct to the next state ourselves.
2257                if (mStatus != BackupConstants.TRANSPORT_OK) {
2258                    BackupState nextState = BackupState.RUNNING_QUEUE;
2259                    mAgentBinder = null;
2260
2261                    // An agent-level failure means we reenqueue this one agent for
2262                    // a later retry, but otherwise proceed normally.
2263                    if (mStatus == BackupConstants.AGENT_ERROR) {
2264                        if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2265                                + " - restaging");
2266                        dataChangedImpl(request.packageName);
2267                        mStatus = BackupConstants.TRANSPORT_OK;
2268                        if (mQueue.isEmpty()) nextState = BackupState.FINAL;
2269                    } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2270                        // Failed lookup of the app, so we couldn't bring up an agent, but
2271                        // we're otherwise fine.  Just drop it and go on to the next as usual.
2272                        mStatus = BackupConstants.TRANSPORT_OK;
2273                    } else {
2274                        // Transport-level failure means we reenqueue everything
2275                        revertAndEndBackup();
2276                        nextState = BackupState.FINAL;
2277                    }
2278
2279                    executeNextState(nextState);
2280                } else {
2281                    // success case
2282                    addBackupTrace("expecting completion/timeout callback");
2283                }
2284            }
2285        }
2286
2287        void finalizeBackup() {
2288            addBackupTrace("finishing");
2289
2290            // Either backup was successful, in which case we of course do not need
2291            // this pass's journal any more; or it failed, in which case we just
2292            // re-enqueued all of these packages in the current active journal.
2293            // Either way, we no longer need this pass's journal.
2294            if (mJournal != null && !mJournal.delete()) {
2295                Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2296            }
2297
2298            // If everything actually went through and this is the first time we've
2299            // done a backup, we can now record what the current backup dataset token
2300            // is.
2301            if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
2302                addBackupTrace("success; recording token");
2303                try {
2304                    mCurrentToken = mTransport.getCurrentRestoreSet();
2305                    writeRestoreTokens();
2306                } catch (RemoteException e) {
2307                    // nothing for it at this point, unfortunately, but this will be
2308                    // recorded the next time we fully succeed.
2309                    addBackupTrace("transport threw returning token");
2310                }
2311            }
2312
2313            // Set up the next backup pass - at this point we can set mBackupRunning
2314            // to false to allow another pass to fire, because we're done with the
2315            // state machine sequence and the wakelock is refcounted.
2316            synchronized (mQueueLock) {
2317                mBackupRunning = false;
2318                if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
2319                    // Make sure we back up everything and perform the one-time init
2320                    clearMetadata();
2321                    if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
2322                    addBackupTrace("init required; rerunning");
2323                    backupNow();
2324                }
2325            }
2326
2327            // Only once we're entirely finished do we release the wakelock
2328            clearBackupTrace();
2329            Slog.i(TAG, "Backup pass finished.");
2330            mWakelock.release();
2331        }
2332
2333        // Remove the PM metadata state. This will generate an init on the next pass.
2334        void clearMetadata() {
2335            final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2336            if (pmState.exists()) pmState.delete();
2337        }
2338
2339        // Invoke an agent's doBackup() and start a timeout message spinning on the main
2340        // handler in case it doesn't get back to us.
2341        int invokeAgentForBackup(String packageName, IBackupAgent agent,
2342                IBackupTransport transport) {
2343            if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2344            addBackupTrace("invoking " + packageName);
2345
2346            mSavedStateName = new File(mStateDir, packageName);
2347            mBackupDataName = new File(mDataDir, packageName + ".data");
2348            mNewStateName = new File(mStateDir, packageName + ".new");
2349            if (MORE_DEBUG) Slog.d(TAG, "data file: " + mBackupDataName);
2350
2351            mSavedState = null;
2352            mBackupData = null;
2353            mNewState = null;
2354
2355            final int token = generateToken();
2356            try {
2357                // Look up the package info & signatures.  This is first so that if it
2358                // throws an exception, there's no file setup yet that would need to
2359                // be unraveled.
2360                if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
2361                    // The metadata 'package' is synthetic; construct one and make
2362                    // sure our global state is pointed at it
2363                    mCurrentPackage = new PackageInfo();
2364                    mCurrentPackage.packageName = packageName;
2365                }
2366
2367                // In a full backup, we pass a null ParcelFileDescriptor as
2368                // the saved-state "file". This is by definition an incremental,
2369                // so we build a saved state file to pass.
2370                mSavedState = ParcelFileDescriptor.open(mSavedStateName,
2371                        ParcelFileDescriptor.MODE_READ_ONLY |
2372                        ParcelFileDescriptor.MODE_CREATE);  // Make an empty file if necessary
2373
2374                mBackupData = ParcelFileDescriptor.open(mBackupDataName,
2375                        ParcelFileDescriptor.MODE_READ_WRITE |
2376                        ParcelFileDescriptor.MODE_CREATE |
2377                        ParcelFileDescriptor.MODE_TRUNCATE);
2378
2379                if (!SELinux.restorecon(mBackupDataName)) {
2380                    Slog.e(TAG, "SELinux restorecon failed on " + mBackupDataName);
2381                }
2382
2383                mNewState = ParcelFileDescriptor.open(mNewStateName,
2384                        ParcelFileDescriptor.MODE_READ_WRITE |
2385                        ParcelFileDescriptor.MODE_CREATE |
2386                        ParcelFileDescriptor.MODE_TRUNCATE);
2387
2388                // Initiate the target's backup pass
2389                addBackupTrace("setting timeout");
2390                prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
2391                addBackupTrace("calling agent doBackup()");
2392                agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
2393            } catch (Exception e) {
2394                Slog.e(TAG, "Error invoking for backup on " + packageName);
2395                addBackupTrace("exception: " + e);
2396                EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2397                        e.toString());
2398                agentErrorCleanup();
2399                return BackupConstants.AGENT_ERROR;
2400            }
2401
2402            // At this point the agent is off and running.  The next thing to happen will
2403            // either be a callback from the agent, at which point we'll process its data
2404            // for transport, or a timeout.  Either way the next phase will happen in
2405            // response to the TimeoutHandler interface callbacks.
2406            addBackupTrace("invoke success");
2407            return BackupConstants.TRANSPORT_OK;
2408        }
2409
2410        public void failAgent(IBackupAgent agent, String message) {
2411            try {
2412                agent.fail(message);
2413            } catch (Exception e) {
2414                Slog.w(TAG, "Error conveying failure to " + mCurrentPackage.packageName);
2415            }
2416        }
2417
2418        @Override
2419        public void operationComplete() {
2420            // Okay, the agent successfully reported back to us!
2421            final String pkgName = mCurrentPackage.packageName;
2422            final long filepos = mBackupDataName.length();
2423            FileDescriptor fd = mBackupData.getFileDescriptor();
2424            try {
2425                // If it's a 3rd party app, see whether they wrote any protected keys
2426                // and complain mightily if they are attempting shenanigans.
2427                if (mCurrentPackage.applicationInfo != null &&
2428                        (mCurrentPackage.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2429                    ParcelFileDescriptor readFd = ParcelFileDescriptor.open(mBackupDataName,
2430                            ParcelFileDescriptor.MODE_READ_ONLY);
2431                    BackupDataInput in = new BackupDataInput(readFd.getFileDescriptor());
2432                    try {
2433                        while (in.readNextHeader()) {
2434                            final String key = in.getKey();
2435                            if (key != null && key.charAt(0) >= 0xff00) {
2436                                // Not okay: crash them and bail.
2437                                failAgent(mAgentBinder, "Illegal backup key: " + key);
2438                                addBackupTrace("illegal key " + key + " from " + pkgName);
2439                                EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, pkgName,
2440                                        "bad key");
2441                                mBackupHandler.removeMessages(MSG_TIMEOUT);
2442                                agentErrorCleanup();
2443                                // agentErrorCleanup() implicitly executes next state properly
2444                                return;
2445                            }
2446                            in.skipEntityData();
2447                        }
2448                    } finally {
2449                        if (readFd != null) {
2450                            readFd.close();
2451                        }
2452                    }
2453                }
2454
2455                // Piggyback the widget state payload, if any
2456                BackupDataOutput out = new BackupDataOutput(fd);
2457                byte[] widgetState = AppWidgetBackupBridge.getWidgetState(pkgName,
2458                        UserHandle.USER_OWNER);
2459                if (widgetState != null) {
2460                    out.writeEntityHeader(KEY_WIDGET_STATE, widgetState.length);
2461                    out.writeEntityData(widgetState, widgetState.length);
2462                } else {
2463                    // No widget state for this app, but push a 'delete' operation for it
2464                    // in case they're trying to play games with the payload.
2465                    out.writeEntityHeader(KEY_WIDGET_STATE, -1);
2466                }
2467            } catch (IOException e) {
2468                // Hard disk error; recovery/failure policy TBD.  For now roll back,
2469                // but we may want to consider this a transport-level failure (i.e.
2470                // we're in such a bad state that we can't contemplate doing backup
2471                // operations any more during this pass).
2472                Slog.w(TAG, "Unable to save widget state for " + pkgName);
2473                try {
2474                    Libcore.os.ftruncate(fd, filepos);
2475                } catch (ErrnoException ee) {
2476                    Slog.w(TAG, "Unable to roll back!");
2477                }
2478            }
2479
2480            // Spin the data off to the transport and proceed with the next stage.
2481            if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2482                    + pkgName);
2483            mBackupHandler.removeMessages(MSG_TIMEOUT);
2484            clearAgentState();
2485            addBackupTrace("operation complete");
2486
2487            ParcelFileDescriptor backupData = null;
2488            mStatus = BackupConstants.TRANSPORT_OK;
2489            try {
2490                int size = (int) mBackupDataName.length();
2491                if (size > 0) {
2492                    if (mStatus == BackupConstants.TRANSPORT_OK) {
2493                        backupData = ParcelFileDescriptor.open(mBackupDataName,
2494                                ParcelFileDescriptor.MODE_READ_ONLY);
2495                        addBackupTrace("sending data to transport");
2496                        mStatus = mTransport.performBackup(mCurrentPackage, backupData);
2497                    }
2498
2499                    // TODO - We call finishBackup() for each application backed up, because
2500                    // we need to know now whether it succeeded or failed.  Instead, we should
2501                    // hold off on finishBackup() until the end, which implies holding off on
2502                    // renaming *all* the output state files (see below) until that happens.
2503
2504                    addBackupTrace("data delivered: " + mStatus);
2505                    if (mStatus == BackupConstants.TRANSPORT_OK) {
2506                        addBackupTrace("finishing op on transport");
2507                        mStatus = mTransport.finishBackup();
2508                        addBackupTrace("finished: " + mStatus);
2509                    }
2510                } else {
2511                    if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
2512                    addBackupTrace("no data to send");
2513                }
2514
2515                // After successful transport, delete the now-stale data
2516                // and juggle the files so that next time we supply the agent
2517                // with the new state file it just created.
2518                if (mStatus == BackupConstants.TRANSPORT_OK) {
2519                    mBackupDataName.delete();
2520                    mNewStateName.renameTo(mSavedStateName);
2521                    EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, pkgName, size);
2522                    logBackupComplete(pkgName);
2523                } else {
2524                    EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, pkgName);
2525                }
2526            } catch (Exception e) {
2527                Slog.e(TAG, "Transport error backing up " + pkgName, e);
2528                EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, pkgName);
2529                mStatus = BackupConstants.TRANSPORT_ERROR;
2530            } finally {
2531                try { if (backupData != null) backupData.close(); } catch (IOException e) {}
2532            }
2533
2534            // If we encountered an error here it's a transport-level failure.  That
2535            // means we need to halt everything and reschedule everything for next time.
2536            final BackupState nextState;
2537            if (mStatus != BackupConstants.TRANSPORT_OK) {
2538                revertAndEndBackup();
2539                nextState = BackupState.FINAL;
2540            } else {
2541                // Success!  Proceed with the next app if any, otherwise we're done.
2542                nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2543            }
2544
2545            executeNextState(nextState);
2546        }
2547
2548        @Override
2549        public void handleTimeout() {
2550            // Whoops, the current agent timed out running doBackup().  Tidy up and restage
2551            // it for the next time we run a backup pass.
2552            // !!! TODO: keep track of failure counts per agent, and blacklist those which
2553            // fail repeatedly (i.e. have proved themselves to be buggy).
2554            Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2555            EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2556                    "timeout");
2557            addBackupTrace("timeout of " + mCurrentPackage.packageName);
2558            agentErrorCleanup();
2559            dataChangedImpl(mCurrentPackage.packageName);
2560        }
2561
2562        void revertAndEndBackup() {
2563            if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
2564            addBackupTrace("transport error; reverting");
2565            for (BackupRequest request : mOriginalQueue) {
2566                dataChangedImpl(request.packageName);
2567            }
2568            // We also want to reset the backup schedule based on whatever
2569            // the transport suggests by way of retry/backoff time.
2570            restartBackupAlarm();
2571        }
2572
2573        void agentErrorCleanup() {
2574            mBackupDataName.delete();
2575            mNewStateName.delete();
2576            clearAgentState();
2577
2578            executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2579        }
2580
2581        // Cleanup common to both success and failure cases
2582        void clearAgentState() {
2583            try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2584            try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2585            try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2586            mSavedState = mBackupData = mNewState = null;
2587            synchronized (mCurrentOpLock) {
2588                mCurrentOperations.clear();
2589            }
2590
2591            // If this was a pseudopackage there's no associated Activity Manager state
2592            if (mCurrentPackage.applicationInfo != null) {
2593                addBackupTrace("unbinding " + mCurrentPackage.packageName);
2594                try {  // unbind even on timeout, just in case
2595                    mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2596                } catch (RemoteException e) { /* can't happen; activity manager is local */ }
2597            }
2598        }
2599
2600        void restartBackupAlarm() {
2601            addBackupTrace("setting backup trigger");
2602            synchronized (mQueueLock) {
2603                try {
2604                    startBackupAlarmsLocked(mTransport.requestBackupTime());
2605                } catch (RemoteException e) { /* cannot happen */ }
2606            }
2607        }
2608
2609        void executeNextState(BackupState nextState) {
2610            if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2611                    + this + " nextState=" + nextState);
2612            addBackupTrace("executeNextState => " + nextState);
2613            mCurrentState = nextState;
2614            Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2615            mBackupHandler.sendMessage(msg);
2616        }
2617    }
2618
2619
2620    // ----- Full backup/restore to a file/socket -----
2621
2622    abstract class ObbServiceClient {
2623        public IObbBackupService mObbService;
2624        public void setObbBinder(IObbBackupService binder) {
2625            mObbService = binder;
2626        }
2627    }
2628
2629    class FullBackupObbConnection implements ServiceConnection {
2630        volatile IObbBackupService mService;
2631
2632        FullBackupObbConnection() {
2633            mService = null;
2634        }
2635
2636        public void establish() {
2637            if (DEBUG) Slog.i(TAG, "Initiating bind of OBB service on " + this);
2638            Intent obbIntent = new Intent().setComponent(new ComponentName(
2639                    "com.android.sharedstoragebackup",
2640                    "com.android.sharedstoragebackup.ObbBackupService"));
2641            BackupManagerService.this.mContext.bindService(
2642                    obbIntent, this, Context.BIND_AUTO_CREATE);
2643        }
2644
2645        public void tearDown() {
2646            BackupManagerService.this.mContext.unbindService(this);
2647        }
2648
2649        public boolean backupObbs(PackageInfo pkg, OutputStream out) {
2650            boolean success = false;
2651            waitForConnection();
2652
2653            ParcelFileDescriptor[] pipes = null;
2654            try {
2655                pipes = ParcelFileDescriptor.createPipe();
2656                int token = generateToken();
2657                prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
2658                mService.backupObbs(pkg.packageName, pipes[1], token, mBackupManagerBinder);
2659                routeSocketDataToOutput(pipes[0], out);
2660                success = waitUntilOperationComplete(token);
2661            } catch (Exception e) {
2662                Slog.w(TAG, "Unable to back up OBBs for " + pkg, e);
2663            } finally {
2664                try {
2665                    out.flush();
2666                    if (pipes != null) {
2667                        if (pipes[0] != null) pipes[0].close();
2668                        if (pipes[1] != null) pipes[1].close();
2669                    }
2670                } catch (IOException e) {
2671                    Slog.w(TAG, "I/O error closing down OBB backup", e);
2672                }
2673            }
2674            return success;
2675        }
2676
2677        public void restoreObbFile(String pkgName, ParcelFileDescriptor data,
2678                long fileSize, int type, String path, long mode, long mtime,
2679                int token, IBackupManager callbackBinder) {
2680            waitForConnection();
2681
2682            try {
2683                mService.restoreObbFile(pkgName, data, fileSize, type, path, mode, mtime,
2684                        token, callbackBinder);
2685            } catch (Exception e) {
2686                Slog.w(TAG, "Unable to restore OBBs for " + pkgName, e);
2687            }
2688        }
2689
2690        private void waitForConnection() {
2691            synchronized (this) {
2692                while (mService == null) {
2693                    if (DEBUG) Slog.i(TAG, "...waiting for OBB service binding...");
2694                    try {
2695                        this.wait();
2696                    } catch (InterruptedException e) { /* never interrupted */ }
2697                }
2698                if (DEBUG) Slog.i(TAG, "Connected to OBB service; continuing");
2699            }
2700        }
2701
2702        @Override
2703        public void onServiceConnected(ComponentName name, IBinder service) {
2704            synchronized (this) {
2705                mService = IObbBackupService.Stub.asInterface(service);
2706                if (DEBUG) Slog.i(TAG, "OBB service connection " + mService
2707                        + " connected on " + this);
2708                this.notifyAll();
2709            }
2710        }
2711
2712        @Override
2713        public void onServiceDisconnected(ComponentName name) {
2714            synchronized (this) {
2715                mService = null;
2716                if (DEBUG) Slog.i(TAG, "OBB service connection disconnected on " + this);
2717                this.notifyAll();
2718            }
2719        }
2720
2721    }
2722
2723    private void routeSocketDataToOutput(ParcelFileDescriptor inPipe, OutputStream out)
2724            throws IOException {
2725        FileInputStream raw = new FileInputStream(inPipe.getFileDescriptor());
2726        DataInputStream in = new DataInputStream(raw);
2727
2728        byte[] buffer = new byte[32 * 1024];
2729        int chunkTotal;
2730        while ((chunkTotal = in.readInt()) > 0) {
2731            while (chunkTotal > 0) {
2732                int toRead = (chunkTotal > buffer.length) ? buffer.length : chunkTotal;
2733                int nRead = in.read(buffer, 0, toRead);
2734                out.write(buffer, 0, nRead);
2735                chunkTotal -= nRead;
2736            }
2737        }
2738    }
2739
2740    class PerformFullBackupTask extends ObbServiceClient implements Runnable {
2741        ParcelFileDescriptor mOutputFile;
2742        DeflaterOutputStream mDeflater;
2743        IFullBackupRestoreObserver mObserver;
2744        boolean mIncludeApks;
2745        boolean mIncludeObbs;
2746        boolean mIncludeShared;
2747        boolean mDoWidgets;
2748        boolean mAllApps;
2749        final boolean mIncludeSystem;
2750        ArrayList<String> mPackages;
2751        String mCurrentPassword;
2752        String mEncryptPassword;
2753        AtomicBoolean mLatchObject;
2754        File mFilesDir;
2755        File mManifestFile;
2756        File mMetadataFile;
2757
2758
2759        class FullBackupRunner implements Runnable {
2760            PackageInfo mPackage;
2761            byte[] mWidgetData;
2762            IBackupAgent mAgent;
2763            ParcelFileDescriptor mPipe;
2764            int mToken;
2765            boolean mSendApk;
2766            boolean mWriteManifest;
2767
2768            FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
2769                    int token, boolean sendApk, boolean writeManifest, byte[] widgetData)
2770                            throws IOException {
2771                mPackage = pack;
2772                mWidgetData = widgetData;
2773                mAgent = agent;
2774                mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2775                mToken = token;
2776                mSendApk = sendApk;
2777                mWriteManifest = writeManifest;
2778            }
2779
2780            @Override
2781            public void run() {
2782                try {
2783                    BackupDataOutput output = new BackupDataOutput(
2784                            mPipe.getFileDescriptor());
2785
2786                    if (mWriteManifest) {
2787                        final boolean writeWidgetData = mWidgetData != null;
2788                        if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
2789                        writeAppManifest(mPackage, mManifestFile, mSendApk, writeWidgetData);
2790                        FullBackup.backupToTar(mPackage.packageName, null, null,
2791                                mFilesDir.getAbsolutePath(),
2792                                mManifestFile.getAbsolutePath(),
2793                                output);
2794                        mManifestFile.delete();
2795
2796                        // We only need to write a metadata file if we have widget data to stash
2797                        if (writeWidgetData) {
2798                            writeMetadata(mPackage, mMetadataFile, mWidgetData);
2799                            FullBackup.backupToTar(mPackage.packageName, null, null,
2800                                    mFilesDir.getAbsolutePath(),
2801                                    mMetadataFile.getAbsolutePath(),
2802                                    output);
2803                            mMetadataFile.delete();
2804                        }
2805                    }
2806
2807                    if (mSendApk) {
2808                        writeApkToBackup(mPackage, output);
2809                    }
2810
2811                    if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
2812                    prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
2813                    mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2814                } catch (IOException e) {
2815                    Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2816                } catch (RemoteException e) {
2817                    Slog.e(TAG, "Remote agent vanished during full backup of "
2818                            + mPackage.packageName);
2819                } finally {
2820                    try {
2821                        mPipe.close();
2822                    } catch (IOException e) {}
2823                }
2824            }
2825        }
2826
2827        PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
2828                boolean includeApks, boolean includeObbs, boolean includeShared,
2829                boolean doWidgets, String curPassword, String encryptPassword, boolean doAllApps,
2830                boolean doSystem, String[] packages, AtomicBoolean latch) {
2831            mOutputFile = fd;
2832            mObserver = observer;
2833            mIncludeApks = includeApks;
2834            mIncludeObbs = includeObbs;
2835            mIncludeShared = includeShared;
2836            mDoWidgets = doWidgets;
2837            mAllApps = doAllApps;
2838            mIncludeSystem = doSystem;
2839            mPackages = (packages == null)
2840                    ? new ArrayList<String>()
2841                    : new ArrayList<String>(Arrays.asList(packages));
2842            mCurrentPassword = curPassword;
2843            // when backing up, if there is a current backup password, we require that
2844            // the user use a nonempty encryption password as well.  if one is supplied
2845            // in the UI we use that, but if the UI was left empty we fall back to the
2846            // current backup password (which was supplied by the user as well).
2847            if (encryptPassword == null || "".equals(encryptPassword)) {
2848                mEncryptPassword = curPassword;
2849            } else {
2850                mEncryptPassword = encryptPassword;
2851            }
2852            mLatchObject = latch;
2853
2854            mFilesDir = new File("/data/system");
2855            mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2856            mMetadataFile = new File(mFilesDir, BACKUP_METADATA_FILENAME);
2857        }
2858
2859        void addPackagesToSet(TreeMap<String, PackageInfo> set, List<String> pkgNames) {
2860            for (String pkgName : pkgNames) {
2861                if (!set.containsKey(pkgName)) {
2862                    try {
2863                        PackageInfo info = mPackageManager.getPackageInfo(pkgName,
2864                                PackageManager.GET_SIGNATURES);
2865                        set.put(pkgName, info);
2866                    } catch (NameNotFoundException e) {
2867                        Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2868                    }
2869                }
2870            }
2871        }
2872
2873        @Override
2874        public void run() {
2875            Slog.i(TAG, "--- Performing full-dataset backup ---");
2876
2877            TreeMap<String, PackageInfo> packagesToBackup = new TreeMap<String, PackageInfo>();
2878            FullBackupObbConnection obbConnection = new FullBackupObbConnection();
2879            obbConnection.establish();  // we'll want this later
2880
2881            sendStartBackup();
2882
2883            // doAllApps supersedes the package set if any
2884            if (mAllApps) {
2885                List<PackageInfo> allPackages = mPackageManager.getInstalledPackages(
2886                        PackageManager.GET_SIGNATURES);
2887                for (int i = 0; i < allPackages.size(); i++) {
2888                    PackageInfo pkg = allPackages.get(i);
2889                    // Exclude system apps if we've been asked to do so
2890                    if (mIncludeSystem == true
2891                            || ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
2892                        packagesToBackup.put(pkg.packageName, pkg);
2893                    }
2894                }
2895            }
2896
2897            // If we're doing widget state as well, ensure that we have all the involved
2898            // host & provider packages in the set
2899            if (mDoWidgets) {
2900                List<String> pkgs =
2901                        AppWidgetBackupBridge.getWidgetParticipants(UserHandle.USER_OWNER);
2902                if (pkgs != null) {
2903                    if (MORE_DEBUG) {
2904                        Slog.i(TAG, "Adding widget participants to backup set:");
2905                        StringBuilder sb = new StringBuilder(128);
2906                        sb.append("   ");
2907                        for (String s : pkgs) {
2908                            sb.append(' ');
2909                            sb.append(s);
2910                        }
2911                        Slog.i(TAG, sb.toString());
2912                    }
2913                    addPackagesToSet(packagesToBackup, pkgs);
2914                }
2915            }
2916
2917            // Now process the command line argument packages, if any. Note that explicitly-
2918            // named system-partition packages will be included even if includeSystem was
2919            // set to false.
2920            if (mPackages != null) {
2921                addPackagesToSet(packagesToBackup, mPackages);
2922            }
2923
2924            // Now we cull any inapplicable / inappropriate packages from the set
2925            Iterator<Entry<String, PackageInfo>> iter = packagesToBackup.entrySet().iterator();
2926            while (iter.hasNext()) {
2927                PackageInfo pkg = iter.next().getValue();
2928                if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
2929                        || pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
2930                    // Cull any packages that have indicated that backups are not permitted, as well
2931                    // as any explicit mention of the 'special' shared-storage agent package (we
2932                    // handle that one at the end).
2933                    iter.remove();
2934                } else if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
2935                        && (pkg.applicationInfo.backupAgentName == null)) {
2936                    // Cull any packages that run as system-domain uids but do not define their
2937                    // own backup agents
2938                    if (MORE_DEBUG) {
2939                        Slog.i(TAG, "... ignoring non-agent system package " + pkg.packageName);
2940                    }
2941                    iter.remove();
2942                }
2943            }
2944
2945            // flatten the set of packages now so we can explicitly control the ordering
2946            ArrayList<PackageInfo> backupQueue =
2947                    new ArrayList<PackageInfo>(packagesToBackup.values());
2948
2949            FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
2950            OutputStream out = null;
2951
2952            PackageInfo pkg = null;
2953            try {
2954                boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
2955                boolean compressing = COMPRESS_FULL_BACKUPS;
2956                OutputStream finalOutput = ofstream;
2957
2958                // Verify that the given password matches the currently-active
2959                // backup password, if any
2960                if (!backupPasswordMatches(mCurrentPassword)) {
2961                    if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2962                    return;
2963                }
2964
2965                // Write the global file header.  All strings are UTF-8 encoded; lines end
2966                // with a '\n' byte.  Actual backup data begins immediately following the
2967                // final '\n'.
2968                //
2969                // line 1: "ANDROID BACKUP"
2970                // line 2: backup file format version, currently "2"
2971                // line 3: compressed?  "0" if not compressed, "1" if compressed.
2972                // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2973                //
2974                // When line 4 is not "none", then additional header data follows:
2975                //
2976                // line 5: user password salt [hex]
2977                // line 6: master key checksum salt [hex]
2978                // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2979                // line 8: IV of the user key [hex]
2980                // line 9: master key blob [hex]
2981                //     IV of the master key, master key itself, master key checksum hash
2982                //
2983                // The master key checksum is the master key plus its checksum salt, run through
2984                // 10k rounds of PBKDF2.  This is used to verify that the user has supplied the
2985                // correct password for decrypting the archive:  the master key decrypted from
2986                // the archive using the user-supplied password is also run through PBKDF2 in
2987                // this way, and if the result does not match the checksum as stored in the
2988                // archive, then we know that the user-supplied password does not match the
2989                // archive's.
2990                StringBuilder headerbuf = new StringBuilder(1024);
2991
2992                headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
2993                headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2994                headerbuf.append(compressing ? "\n1\n" : "\n0\n");
2995
2996                try {
2997                    // Set up the encryption stage if appropriate, and emit the correct header
2998                    if (encrypting) {
2999                        finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
3000                    } else {
3001                        headerbuf.append("none\n");
3002                    }
3003
3004                    byte[] header = headerbuf.toString().getBytes("UTF-8");
3005                    ofstream.write(header);
3006
3007                    // Set up the compression stage feeding into the encryption stage (if any)
3008                    if (compressing) {
3009                        Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
3010                        finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
3011                    }
3012
3013                    out = finalOutput;
3014                } catch (Exception e) {
3015                    // Should never happen!
3016                    Slog.e(TAG, "Unable to emit archive header", e);
3017                    return;
3018                }
3019
3020                // Shared storage if requested
3021                if (mIncludeShared) {
3022                    try {
3023                        pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
3024                        backupQueue.add(pkg);
3025                    } catch (NameNotFoundException e) {
3026                        Slog.e(TAG, "Unable to find shared-storage backup handler");
3027                    }
3028                }
3029
3030                // Now back up the app data via the agent mechanism
3031                int N = backupQueue.size();
3032                for (int i = 0; i < N; i++) {
3033                    pkg = backupQueue.get(i);
3034                    backupOnePackage(pkg, out);
3035
3036                    // after the app's agent runs to handle its private filesystem
3037                    // contents, back up any OBB content it has on its behalf.
3038                    if (mIncludeObbs) {
3039                        boolean obbOkay = obbConnection.backupObbs(pkg, out);
3040                        if (!obbOkay) {
3041                            throw new RuntimeException("Failure writing OBB stack for " + pkg);
3042                        }
3043                    }
3044                }
3045
3046                // Done!
3047                finalizeBackup(out);
3048            } catch (RemoteException e) {
3049                Slog.e(TAG, "App died during full backup");
3050            } catch (Exception e) {
3051                Slog.e(TAG, "Internal exception during full backup", e);
3052            } finally {
3053                tearDown(pkg);
3054                try {
3055                    if (out != null) out.close();
3056                    mOutputFile.close();
3057                } catch (IOException e) {
3058                    /* nothing we can do about this */
3059                }
3060                synchronized (mCurrentOpLock) {
3061                    mCurrentOperations.clear();
3062                }
3063                synchronized (mLatchObject) {
3064                    mLatchObject.set(true);
3065                    mLatchObject.notifyAll();
3066                }
3067                sendEndBackup();
3068                obbConnection.tearDown();
3069                if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
3070                mWakelock.release();
3071            }
3072        }
3073
3074        private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
3075                OutputStream ofstream) throws Exception {
3076            // User key will be used to encrypt the master key.
3077            byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
3078            SecretKey userKey = buildPasswordKey(PBKDF_CURRENT, mEncryptPassword, newUserSalt,
3079                    PBKDF2_HASH_ROUNDS);
3080
3081            // the master key is random for each backup
3082            byte[] masterPw = new byte[256 / 8];
3083            mRng.nextBytes(masterPw);
3084            byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
3085
3086            // primary encryption of the datastream with the random key
3087            Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
3088            SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
3089            c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
3090            OutputStream finalOutput = new CipherOutputStream(ofstream, c);
3091
3092            // line 4: name of encryption algorithm
3093            headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
3094            headerbuf.append('\n');
3095            // line 5: user password salt [hex]
3096            headerbuf.append(byteArrayToHex(newUserSalt));
3097            headerbuf.append('\n');
3098            // line 6: master key checksum salt [hex]
3099            headerbuf.append(byteArrayToHex(checksumSalt));
3100            headerbuf.append('\n');
3101            // line 7: number of PBKDF2 rounds used [decimal]
3102            headerbuf.append(PBKDF2_HASH_ROUNDS);
3103            headerbuf.append('\n');
3104
3105            // line 8: IV of the user key [hex]
3106            Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
3107            mkC.init(Cipher.ENCRYPT_MODE, userKey);
3108
3109            byte[] IV = mkC.getIV();
3110            headerbuf.append(byteArrayToHex(IV));
3111            headerbuf.append('\n');
3112
3113            // line 9: master IV + key blob, encrypted by the user key [hex].  Blob format:
3114            //    [byte] IV length = Niv
3115            //    [array of Niv bytes] IV itself
3116            //    [byte] master key length = Nmk
3117            //    [array of Nmk bytes] master key itself
3118            //    [byte] MK checksum hash length = Nck
3119            //    [array of Nck bytes] master key checksum hash
3120            //
3121            // The checksum is the (master key + checksum salt), run through the
3122            // stated number of PBKDF2 rounds
3123            IV = c.getIV();
3124            byte[] mk = masterKeySpec.getEncoded();
3125            byte[] checksum = makeKeyChecksum(PBKDF_CURRENT, masterKeySpec.getEncoded(),
3126                    checksumSalt, PBKDF2_HASH_ROUNDS);
3127
3128            ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
3129                    + checksum.length + 3);
3130            DataOutputStream mkOut = new DataOutputStream(blob);
3131            mkOut.writeByte(IV.length);
3132            mkOut.write(IV);
3133            mkOut.writeByte(mk.length);
3134            mkOut.write(mk);
3135            mkOut.writeByte(checksum.length);
3136            mkOut.write(checksum);
3137            mkOut.flush();
3138            byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
3139            headerbuf.append(byteArrayToHex(encryptedMk));
3140            headerbuf.append('\n');
3141
3142            return finalOutput;
3143        }
3144
3145        private void backupOnePackage(PackageInfo pkg, OutputStream out)
3146                throws RemoteException {
3147            Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
3148
3149            IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
3150                    IApplicationThread.BACKUP_MODE_FULL);
3151            if (agent != null) {
3152                ParcelFileDescriptor[] pipes = null;
3153                try {
3154                    pipes = ParcelFileDescriptor.createPipe();
3155
3156                    ApplicationInfo app = pkg.applicationInfo;
3157                    final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
3158                    final boolean sendApk = mIncludeApks
3159                            && !isSharedStorage
3160                            && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
3161                            && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
3162                                (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
3163
3164                    byte[] widgetBlob = AppWidgetBackupBridge.getWidgetState(pkg.packageName,
3165                            UserHandle.USER_OWNER);
3166                    sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
3167
3168                    final int token = generateToken();
3169                    FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
3170                            token, sendApk, !isSharedStorage, widgetBlob);
3171                    pipes[1].close();   // the runner has dup'd it
3172                    pipes[1] = null;
3173                    Thread t = new Thread(runner);
3174                    t.start();
3175
3176                    // Now pull data from the app and stuff it into the compressor
3177                    try {
3178                        routeSocketDataToOutput(pipes[0], out);
3179                    } catch (IOException e) {
3180                        Slog.i(TAG, "Caught exception reading from agent", e);
3181                    }
3182
3183                    if (!waitUntilOperationComplete(token)) {
3184                        Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
3185                    } else {
3186                        if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
3187                    }
3188
3189                } catch (IOException e) {
3190                    Slog.e(TAG, "Error backing up " + pkg.packageName, e);
3191                } finally {
3192                    try {
3193                        // flush after every package
3194                        out.flush();
3195                        if (pipes != null) {
3196                            if (pipes[0] != null) pipes[0].close();
3197                            if (pipes[1] != null) pipes[1].close();
3198                        }
3199                    } catch (IOException e) {
3200                        Slog.w(TAG, "Error bringing down backup stack");
3201                    }
3202                }
3203            } else {
3204                Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
3205            }
3206            tearDown(pkg);
3207        }
3208
3209        private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
3210            // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
3211            final String appSourceDir = pkg.applicationInfo.sourceDir;
3212            final String apkDir = new File(appSourceDir).getParent();
3213            FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
3214                    apkDir, appSourceDir, output);
3215
3216            // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
3217            // doesn't have access to external storage.
3218
3219            // Save associated .obb content if it exists and we did save the apk
3220            // check for .obb and save those too
3221            final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER);
3222            final File obbDir = userEnv.buildExternalStorageAppObbDirs(pkg.packageName)[0];
3223            if (obbDir != null) {
3224                if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
3225                File[] obbFiles = obbDir.listFiles();
3226                if (obbFiles != null) {
3227                    final String obbDirName = obbDir.getAbsolutePath();
3228                    for (File obb : obbFiles) {
3229                        FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
3230                                obbDirName, obb.getAbsolutePath(), output);
3231                    }
3232                }
3233            }
3234        }
3235
3236        private void finalizeBackup(OutputStream out) {
3237            try {
3238                // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
3239                byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
3240                out.write(eof);
3241            } catch (IOException e) {
3242                Slog.w(TAG, "Error attempting to finalize backup stream");
3243            }
3244        }
3245
3246        private void writeAppManifest(PackageInfo pkg, File manifestFile,
3247                boolean withApk, boolean withWidgets) throws IOException {
3248            // Manifest format. All data are strings ending in LF:
3249            //     BACKUP_MANIFEST_VERSION, currently 1
3250            //
3251            // Version 1:
3252            //     package name
3253            //     package's versionCode
3254            //     platform versionCode
3255            //     getInstallerPackageName() for this package (maybe empty)
3256            //     boolean: "1" if archive includes .apk; any other string means not
3257            //     number of signatures == N
3258            // N*:    signature byte array in ascii format per Signature.toCharsString()
3259            StringBuilder builder = new StringBuilder(4096);
3260            StringBuilderPrinter printer = new StringBuilderPrinter(builder);
3261
3262            printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
3263            printer.println(pkg.packageName);
3264            printer.println(Integer.toString(pkg.versionCode));
3265            printer.println(Integer.toString(Build.VERSION.SDK_INT));
3266
3267            String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
3268            printer.println((installerName != null) ? installerName : "");
3269
3270            printer.println(withApk ? "1" : "0");
3271            if (pkg.signatures == null) {
3272                printer.println("0");
3273            } else {
3274                printer.println(Integer.toString(pkg.signatures.length));
3275                for (Signature sig : pkg.signatures) {
3276                    printer.println(sig.toCharsString());
3277                }
3278            }
3279
3280            FileOutputStream outstream = new FileOutputStream(manifestFile);
3281            outstream.write(builder.toString().getBytes());
3282            outstream.close();
3283        }
3284
3285        // Widget metadata format. All header entries are strings ending in LF:
3286        //
3287        // Version 1 header:
3288        //     BACKUP_METADATA_VERSION, currently "1"
3289        //     package name
3290        //
3291        // File data (all integers are binary in network byte order)
3292        // *N: 4 : integer token identifying which metadata blob
3293        //     4 : integer size of this blob = N
3294        //     N : raw bytes of this metadata blob
3295        //
3296        // Currently understood blobs (always in network byte order):
3297        //
3298        //     widgets : metadata token = 0x01FFED01 (BACKUP_WIDGET_METADATA_TOKEN)
3299        //
3300        // Unrecognized blobs are *ignored*, not errors.
3301        private void writeMetadata(PackageInfo pkg, File destination, byte[] widgetData)
3302                throws IOException {
3303            StringBuilder b = new StringBuilder(512);
3304            StringBuilderPrinter printer = new StringBuilderPrinter(b);
3305            printer.println(Integer.toString(BACKUP_METADATA_VERSION));
3306            printer.println(pkg.packageName);
3307
3308            FileOutputStream fout = new FileOutputStream(destination);
3309            BufferedOutputStream bout = new BufferedOutputStream(fout);
3310            DataOutputStream out = new DataOutputStream(bout);
3311            bout.write(b.toString().getBytes());    // bypassing DataOutputStream
3312
3313            if (widgetData != null && widgetData.length > 0) {
3314                out.writeInt(BACKUP_WIDGET_METADATA_TOKEN);
3315                out.writeInt(widgetData.length);
3316                out.write(widgetData);
3317            }
3318            bout.flush();
3319            out.close();
3320        }
3321
3322        private void tearDown(PackageInfo pkg) {
3323            if (pkg != null) {
3324                final ApplicationInfo app = pkg.applicationInfo;
3325                if (app != null) {
3326                    try {
3327                        // unbind and tidy up even on timeout or failure, just in case
3328                        mActivityManager.unbindBackupAgent(app);
3329
3330                        // The agent was running with a stub Application object, so shut it down.
3331                        if (app.uid != Process.SYSTEM_UID
3332                                && app.uid != Process.PHONE_UID) {
3333                            if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
3334                            mActivityManager.killApplicationProcess(app.processName, app.uid);
3335                        } else {
3336                            if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
3337                        }
3338                    } catch (RemoteException e) {
3339                        Slog.d(TAG, "Lost app trying to shut down");
3340                    }
3341                }
3342            }
3343        }
3344
3345        // wrappers for observer use
3346        void sendStartBackup() {
3347            if (mObserver != null) {
3348                try {
3349                    mObserver.onStartBackup();
3350                } catch (RemoteException e) {
3351                    Slog.w(TAG, "full backup observer went away: startBackup");
3352                    mObserver = null;
3353                }
3354            }
3355        }
3356
3357        void sendOnBackupPackage(String name) {
3358            if (mObserver != null) {
3359                try {
3360                    // TODO: use a more user-friendly name string
3361                    mObserver.onBackupPackage(name);
3362                } catch (RemoteException e) {
3363                    Slog.w(TAG, "full backup observer went away: backupPackage");
3364                    mObserver = null;
3365                }
3366            }
3367        }
3368
3369        void sendEndBackup() {
3370            if (mObserver != null) {
3371                try {
3372                    mObserver.onEndBackup();
3373                } catch (RemoteException e) {
3374                    Slog.w(TAG, "full backup observer went away: endBackup");
3375                    mObserver = null;
3376                }
3377            }
3378        }
3379    }
3380
3381
3382    // ----- Full restore from a file/socket -----
3383
3384    // Description of a file in the restore datastream
3385    static class FileMetadata {
3386        String packageName;             // name of the owning app
3387        String installerPackageName;    // name of the market-type app that installed the owner
3388        int type;                       // e.g. BackupAgent.TYPE_DIRECTORY
3389        String domain;                  // e.g. FullBackup.DATABASE_TREE_TOKEN
3390        String path;                    // subpath within the semantic domain
3391        long mode;                      // e.g. 0666 (actually int)
3392        long mtime;                     // last mod time, UTC time_t (actually int)
3393        long size;                      // bytes of content
3394
3395        @Override
3396        public String toString() {
3397            StringBuilder sb = new StringBuilder(128);
3398            sb.append("FileMetadata{");
3399            sb.append(packageName); sb.append(',');
3400            sb.append(type); sb.append(',');
3401            sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
3402            sb.append(size);
3403            sb.append('}');
3404            return sb.toString();
3405        }
3406    }
3407
3408    enum RestorePolicy {
3409        IGNORE,
3410        ACCEPT,
3411        ACCEPT_IF_APK
3412    }
3413
3414    class PerformFullRestoreTask extends ObbServiceClient implements Runnable {
3415        ParcelFileDescriptor mInputFile;
3416        String mCurrentPassword;
3417        String mDecryptPassword;
3418        IFullBackupRestoreObserver mObserver;
3419        AtomicBoolean mLatchObject;
3420        IBackupAgent mAgent;
3421        String mAgentPackage;
3422        ApplicationInfo mTargetApp;
3423        FullBackupObbConnection mObbConnection = null;
3424        ParcelFileDescriptor[] mPipes = null;
3425        byte[] mWidgetData = null;
3426
3427        long mBytes;
3428
3429        // possible handling states for a given package in the restore dataset
3430        final HashMap<String, RestorePolicy> mPackagePolicies
3431                = new HashMap<String, RestorePolicy>();
3432
3433        // installer package names for each encountered app, derived from the manifests
3434        final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
3435
3436        // Signatures for a given package found in its manifest file
3437        final HashMap<String, Signature[]> mManifestSignatures
3438                = new HashMap<String, Signature[]>();
3439
3440        // Packages we've already wiped data on when restoring their first file
3441        final HashSet<String> mClearedPackages = new HashSet<String>();
3442
3443        PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
3444                IFullBackupRestoreObserver observer, AtomicBoolean latch) {
3445            mInputFile = fd;
3446            mCurrentPassword = curPassword;
3447            mDecryptPassword = decryptPassword;
3448            mObserver = observer;
3449            mLatchObject = latch;
3450            mAgent = null;
3451            mAgentPackage = null;
3452            mTargetApp = null;
3453            mObbConnection = new FullBackupObbConnection();
3454
3455            // Which packages we've already wiped data on.  We prepopulate this
3456            // with a whitelist of packages known to be unclearable.
3457            mClearedPackages.add("android");
3458            mClearedPackages.add("com.android.providers.settings");
3459
3460        }
3461
3462        class RestoreFileRunnable implements Runnable {
3463            IBackupAgent mAgent;
3464            FileMetadata mInfo;
3465            ParcelFileDescriptor mSocket;
3466            int mToken;
3467
3468            RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
3469                    ParcelFileDescriptor socket, int token) throws IOException {
3470                mAgent = agent;
3471                mInfo = info;
3472                mToken = token;
3473
3474                // This class is used strictly for process-local binder invocations.  The
3475                // semantics of ParcelFileDescriptor differ in this case; in particular, we
3476                // do not automatically get a 'dup'ed descriptor that we can can continue
3477                // to use asynchronously from the caller.  So, we make sure to dup it ourselves
3478                // before proceeding to do the restore.
3479                mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
3480            }
3481
3482            @Override
3483            public void run() {
3484                try {
3485                    mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
3486                            mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
3487                            mToken, mBackupManagerBinder);
3488                } catch (RemoteException e) {
3489                    // never happens; this is used strictly for local binder calls
3490                }
3491            }
3492        }
3493
3494        @Override
3495        public void run() {
3496            Slog.i(TAG, "--- Performing full-dataset restore ---");
3497            mObbConnection.establish();
3498            sendStartRestore();
3499
3500            // Are we able to restore shared-storage data?
3501            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
3502                mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
3503            }
3504
3505            FileInputStream rawInStream = null;
3506            DataInputStream rawDataIn = null;
3507            try {
3508                if (!backupPasswordMatches(mCurrentPassword)) {
3509                    if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
3510                    return;
3511                }
3512
3513                mBytes = 0;
3514                byte[] buffer = new byte[32 * 1024];
3515                rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
3516                rawDataIn = new DataInputStream(rawInStream);
3517
3518                // First, parse out the unencrypted/uncompressed header
3519                boolean compressed = false;
3520                InputStream preCompressStream = rawInStream;
3521                final InputStream in;
3522
3523                boolean okay = false;
3524                final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
3525                byte[] streamHeader = new byte[headerLen];
3526                rawDataIn.readFully(streamHeader);
3527                byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
3528                if (Arrays.equals(magicBytes, streamHeader)) {
3529                    // okay, header looks good.  now parse out the rest of the fields.
3530                    String s = readHeaderLine(rawInStream);
3531                    final int archiveVersion = Integer.parseInt(s);
3532                    if (archiveVersion <= BACKUP_FILE_VERSION) {
3533                        // okay, it's a version we recognize.  if it's version 1, we may need
3534                        // to try two different PBKDF2 regimes to compare checksums.
3535                        final boolean pbkdf2Fallback = (archiveVersion == 1);
3536
3537                        s = readHeaderLine(rawInStream);
3538                        compressed = (Integer.parseInt(s) != 0);
3539                        s = readHeaderLine(rawInStream);
3540                        if (s.equals("none")) {
3541                            // no more header to parse; we're good to go
3542                            okay = true;
3543                        } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
3544                            preCompressStream = decodeAesHeaderAndInitialize(s, pbkdf2Fallback,
3545                                    rawInStream);
3546                            if (preCompressStream != null) {
3547                                okay = true;
3548                            }
3549                        } else Slog.w(TAG, "Archive is encrypted but no password given");
3550                    } else Slog.w(TAG, "Wrong header version: " + s);
3551                } else Slog.w(TAG, "Didn't read the right header magic");
3552
3553                if (!okay) {
3554                    Slog.w(TAG, "Invalid restore data; aborting.");
3555                    return;
3556                }
3557
3558                // okay, use the right stream layer based on compression
3559                in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
3560
3561                boolean didRestore;
3562                do {
3563                    didRestore = restoreOneFile(in, buffer);
3564                } while (didRestore);
3565
3566                if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
3567            } catch (IOException e) {
3568                Slog.e(TAG, "Unable to read restore input");
3569            } finally {
3570                tearDownPipes();
3571                tearDownAgent(mTargetApp);
3572
3573                try {
3574                    if (rawDataIn != null) rawDataIn.close();
3575                    if (rawInStream != null) rawInStream.close();
3576                    mInputFile.close();
3577                } catch (IOException e) {
3578                    Slog.w(TAG, "Close of restore data pipe threw", e);
3579                    /* nothing we can do about this */
3580                }
3581                synchronized (mCurrentOpLock) {
3582                    mCurrentOperations.clear();
3583                }
3584                synchronized (mLatchObject) {
3585                    mLatchObject.set(true);
3586                    mLatchObject.notifyAll();
3587                }
3588                mObbConnection.tearDown();
3589                sendEndRestore();
3590                Slog.d(TAG, "Full restore pass complete.");
3591                mWakelock.release();
3592            }
3593        }
3594
3595        String readHeaderLine(InputStream in) throws IOException {
3596            int c;
3597            StringBuilder buffer = new StringBuilder(80);
3598            while ((c = in.read()) >= 0) {
3599                if (c == '\n') break;   // consume and discard the newlines
3600                buffer.append((char)c);
3601            }
3602            return buffer.toString();
3603        }
3604
3605        InputStream attemptMasterKeyDecryption(String algorithm, byte[] userSalt, byte[] ckSalt,
3606                int rounds, String userIvHex, String masterKeyBlobHex, InputStream rawInStream,
3607                boolean doLog) {
3608            InputStream result = null;
3609
3610            try {
3611                Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
3612                SecretKey userKey = buildPasswordKey(algorithm, mDecryptPassword, userSalt,
3613                        rounds);
3614                byte[] IV = hexToByteArray(userIvHex);
3615                IvParameterSpec ivSpec = new IvParameterSpec(IV);
3616                c.init(Cipher.DECRYPT_MODE,
3617                        new SecretKeySpec(userKey.getEncoded(), "AES"),
3618                        ivSpec);
3619                byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3620                byte[] mkBlob = c.doFinal(mkCipher);
3621
3622                // first, the master key IV
3623                int offset = 0;
3624                int len = mkBlob[offset++];
3625                IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3626                offset += len;
3627                // then the master key itself
3628                len = mkBlob[offset++];
3629                byte[] mk = Arrays.copyOfRange(mkBlob,
3630                        offset, offset + len);
3631                offset += len;
3632                // and finally the master key checksum hash
3633                len = mkBlob[offset++];
3634                byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3635                        offset, offset + len);
3636
3637                // now validate the decrypted master key against the checksum
3638                byte[] calculatedCk = makeKeyChecksum(algorithm, mk, ckSalt, rounds);
3639                if (Arrays.equals(calculatedCk, mkChecksum)) {
3640                    ivSpec = new IvParameterSpec(IV);
3641                    c.init(Cipher.DECRYPT_MODE,
3642                            new SecretKeySpec(mk, "AES"),
3643                            ivSpec);
3644                    // Only if all of the above worked properly will 'result' be assigned
3645                    result = new CipherInputStream(rawInStream, c);
3646                } else if (doLog) Slog.w(TAG, "Incorrect password");
3647            } catch (InvalidAlgorithmParameterException e) {
3648                if (doLog) Slog.e(TAG, "Needed parameter spec unavailable!", e);
3649            } catch (BadPaddingException e) {
3650                // This case frequently occurs when the wrong password is used to decrypt
3651                // the master key.  Use the identical "incorrect password" log text as is
3652                // used in the checksum failure log in order to avoid providing additional
3653                // information to an attacker.
3654                if (doLog) Slog.w(TAG, "Incorrect password");
3655            } catch (IllegalBlockSizeException e) {
3656                if (doLog) Slog.w(TAG, "Invalid block size in master key");
3657            } catch (NoSuchAlgorithmException e) {
3658                if (doLog) Slog.e(TAG, "Needed decryption algorithm unavailable!");
3659            } catch (NoSuchPaddingException e) {
3660                if (doLog) Slog.e(TAG, "Needed padding mechanism unavailable!");
3661            } catch (InvalidKeyException e) {
3662                if (doLog) Slog.w(TAG, "Illegal password; aborting");
3663            }
3664
3665            return result;
3666        }
3667
3668        InputStream decodeAesHeaderAndInitialize(String encryptionName, boolean pbkdf2Fallback,
3669                InputStream rawInStream) {
3670            InputStream result = null;
3671            try {
3672                if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3673
3674                    String userSaltHex = readHeaderLine(rawInStream); // 5
3675                    byte[] userSalt = hexToByteArray(userSaltHex);
3676
3677                    String ckSaltHex = readHeaderLine(rawInStream); // 6
3678                    byte[] ckSalt = hexToByteArray(ckSaltHex);
3679
3680                    int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3681                    String userIvHex = readHeaderLine(rawInStream); // 8
3682
3683                    String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3684
3685                    // decrypt the master key blob
3686                    result = attemptMasterKeyDecryption(PBKDF_CURRENT, userSalt, ckSalt,
3687                            rounds, userIvHex, masterKeyBlobHex, rawInStream, false);
3688                    if (result == null && pbkdf2Fallback) {
3689                        result = attemptMasterKeyDecryption(PBKDF_FALLBACK, userSalt, ckSalt,
3690                                rounds, userIvHex, masterKeyBlobHex, rawInStream, true);
3691                    }
3692                } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3693            } catch (NumberFormatException e) {
3694                Slog.w(TAG, "Can't parse restore data header");
3695            } catch (IOException e) {
3696                Slog.w(TAG, "Can't read input header");
3697            }
3698
3699            return result;
3700        }
3701
3702        boolean restoreOneFile(InputStream instream, byte[] buffer) {
3703            FileMetadata info;
3704            try {
3705                info = readTarHeaders(instream);
3706                if (info != null) {
3707                    if (MORE_DEBUG) {
3708                        dumpFileMetadata(info);
3709                    }
3710
3711                    final String pkg = info.packageName;
3712                    if (!pkg.equals(mAgentPackage)) {
3713                        // okay, change in package; set up our various
3714                        // bookkeeping if we haven't seen it yet
3715                        if (!mPackagePolicies.containsKey(pkg)) {
3716                            mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3717                        }
3718
3719                        // Clean up the previous agent relationship if necessary,
3720                        // and let the observer know we're considering a new app.
3721                        if (mAgent != null) {
3722                            if (DEBUG) Slog.d(TAG, "Saw new package; finalizing old one");
3723                            // Now we're really done
3724                            tearDownPipes();
3725                            tearDownAgent(mTargetApp);
3726                            mTargetApp = null;
3727                            mAgentPackage = null;
3728                        }
3729                    }
3730
3731                    if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3732                        mPackagePolicies.put(pkg, readAppManifest(info, instream));
3733                        mPackageInstallers.put(pkg, info.installerPackageName);
3734                        // We've read only the manifest content itself at this point,
3735                        // so consume the footer before looping around to the next
3736                        // input file
3737                        skipTarPadding(info.size, instream);
3738                        sendOnRestorePackage(pkg);
3739                    } else if (info.path.equals(BACKUP_METADATA_FILENAME)) {
3740                        // Metadata blobs!
3741                        readMetadata(info, instream);
3742                    } else {
3743                        // Non-manifest, so it's actual file data.  Is this a package
3744                        // we're ignoring?
3745                        boolean okay = true;
3746                        RestorePolicy policy = mPackagePolicies.get(pkg);
3747                        switch (policy) {
3748                            case IGNORE:
3749                                okay = false;
3750                                break;
3751
3752                            case ACCEPT_IF_APK:
3753                                // If we're in accept-if-apk state, then the first file we
3754                                // see MUST be the apk.
3755                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3756                                    if (DEBUG) Slog.d(TAG, "APK file; installing");
3757                                    // Try to install the app.
3758                                    String installerName = mPackageInstallers.get(pkg);
3759                                    okay = installApk(info, installerName, instream);
3760                                    // good to go; promote to ACCEPT
3761                                    mPackagePolicies.put(pkg, (okay)
3762                                            ? RestorePolicy.ACCEPT
3763                                            : RestorePolicy.IGNORE);
3764                                    // At this point we've consumed this file entry
3765                                    // ourselves, so just strip the tar footer and
3766                                    // go on to the next file in the input stream
3767                                    skipTarPadding(info.size, instream);
3768                                    return true;
3769                                } else {
3770                                    // File data before (or without) the apk.  We can't
3771                                    // handle it coherently in this case so ignore it.
3772                                    mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3773                                    okay = false;
3774                                }
3775                                break;
3776
3777                            case ACCEPT:
3778                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3779                                    if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3780                                    // we can take the data without the apk, so we
3781                                    // *want* to do so.  skip the apk by declaring this
3782                                    // one file not-okay without changing the restore
3783                                    // policy for the package.
3784                                    okay = false;
3785                                }
3786                                break;
3787
3788                            default:
3789                                // Something has gone dreadfully wrong when determining
3790                                // the restore policy from the manifest.  Ignore the
3791                                // rest of this package's data.
3792                                Slog.e(TAG, "Invalid policy from manifest");
3793                                okay = false;
3794                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3795                                break;
3796                        }
3797
3798                        // If the policy is satisfied, go ahead and set up to pipe the
3799                        // data to the agent.
3800                        if (DEBUG && okay && mAgent != null) {
3801                            Slog.i(TAG, "Reusing existing agent instance");
3802                        }
3803                        if (okay && mAgent == null) {
3804                            if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3805
3806                            try {
3807                                mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3808
3809                                // If we haven't sent any data to this app yet, we probably
3810                                // need to clear it first.  Check that.
3811                                if (!mClearedPackages.contains(pkg)) {
3812                                    // apps with their own backup agents are
3813                                    // responsible for coherently managing a full
3814                                    // restore.
3815                                    if (mTargetApp.backupAgentName == null) {
3816                                        if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3817                                        clearApplicationDataSynchronous(pkg);
3818                                    } else {
3819                                        if (DEBUG) Slog.d(TAG, "backup agent ("
3820                                                + mTargetApp.backupAgentName + ") => no clear");
3821                                    }
3822                                    mClearedPackages.add(pkg);
3823                                } else {
3824                                    if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3825                                }
3826
3827                                // All set; now set up the IPC and launch the agent
3828                                setUpPipes();
3829                                mAgent = bindToAgentSynchronous(mTargetApp,
3830                                        IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3831                                mAgentPackage = pkg;
3832                            } catch (IOException e) {
3833                                // fall through to error handling
3834                            } catch (NameNotFoundException e) {
3835                                // fall through to error handling
3836                            }
3837
3838                            if (mAgent == null) {
3839                                if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3840                                okay = false;
3841                                tearDownPipes();
3842                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3843                            }
3844                        }
3845
3846                        // Sanity check: make sure we never give data to the wrong app.  This
3847                        // should never happen but a little paranoia here won't go amiss.
3848                        if (okay && !pkg.equals(mAgentPackage)) {
3849                            Slog.e(TAG, "Restoring data for " + pkg
3850                                    + " but agent is for " + mAgentPackage);
3851                            okay = false;
3852                        }
3853
3854                        // At this point we have an agent ready to handle the full
3855                        // restore data as well as a pipe for sending data to
3856                        // that agent.  Tell the agent to start reading from the
3857                        // pipe.
3858                        if (okay) {
3859                            boolean agentSuccess = true;
3860                            long toCopy = info.size;
3861                            final int token = generateToken();
3862                            try {
3863                                prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
3864                                if (info.domain.equals(FullBackup.OBB_TREE_TOKEN)) {
3865                                    if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
3866                                            + " : " + info.path);
3867                                    mObbConnection.restoreObbFile(pkg, mPipes[0],
3868                                            info.size, info.type, info.path, info.mode,
3869                                            info.mtime, token, mBackupManagerBinder);
3870                                } else {
3871                                    if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3872                                            + info.path);
3873                                    // fire up the app's agent listening on the socket.  If
3874                                    // the agent is running in the system process we can't
3875                                    // just invoke it asynchronously, so we provide a thread
3876                                    // for it here.
3877                                    if (mTargetApp.processName.equals("system")) {
3878                                        Slog.d(TAG, "system process agent - spinning a thread");
3879                                        RestoreFileRunnable runner = new RestoreFileRunnable(
3880                                                mAgent, info, mPipes[0], token);
3881                                        new Thread(runner).start();
3882                                    } else {
3883                                        mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3884                                                info.domain, info.path, info.mode, info.mtime,
3885                                                token, mBackupManagerBinder);
3886                                    }
3887                                }
3888                            } catch (IOException e) {
3889                                // couldn't dup the socket for a process-local restore
3890                                Slog.d(TAG, "Couldn't establish restore");
3891                                agentSuccess = false;
3892                                okay = false;
3893                            } catch (RemoteException e) {
3894                                // whoops, remote entity went away.  We'll eat the content
3895                                // ourselves, then, and not copy it over.
3896                                Slog.e(TAG, "Agent crashed during full restore");
3897                                agentSuccess = false;
3898                                okay = false;
3899                            }
3900
3901                            // Copy over the data if the agent is still good
3902                            if (okay) {
3903                                boolean pipeOkay = true;
3904                                FileOutputStream pipe = new FileOutputStream(
3905                                        mPipes[1].getFileDescriptor());
3906                                while (toCopy > 0) {
3907                                    int toRead = (toCopy > buffer.length)
3908                                    ? buffer.length : (int)toCopy;
3909                                    int nRead = instream.read(buffer, 0, toRead);
3910                                    if (nRead >= 0) mBytes += nRead;
3911                                    if (nRead <= 0) break;
3912                                    toCopy -= nRead;
3913
3914                                    // send it to the output pipe as long as things
3915                                    // are still good
3916                                    if (pipeOkay) {
3917                                        try {
3918                                            pipe.write(buffer, 0, nRead);
3919                                        } catch (IOException e) {
3920                                            Slog.e(TAG, "Failed to write to restore pipe", e);
3921                                            pipeOkay = false;
3922                                        }
3923                                    }
3924                                }
3925
3926                                // done sending that file!  Now we just need to consume
3927                                // the delta from info.size to the end of block.
3928                                skipTarPadding(info.size, instream);
3929
3930                                // and now that we've sent it all, wait for the remote
3931                                // side to acknowledge receipt
3932                                agentSuccess = waitUntilOperationComplete(token);
3933                            }
3934
3935                            // okay, if the remote end failed at any point, deal with
3936                            // it by ignoring the rest of the restore on it
3937                            if (!agentSuccess) {
3938                                mBackupHandler.removeMessages(MSG_TIMEOUT);
3939                                tearDownPipes();
3940                                tearDownAgent(mTargetApp);
3941                                mAgent = null;
3942                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3943                            }
3944                        }
3945
3946                        // Problems setting up the agent communication, or an already-
3947                        // ignored package: skip to the next tar stream entry by
3948                        // reading and discarding this file.
3949                        if (!okay) {
3950                            if (DEBUG) Slog.d(TAG, "[discarding file content]");
3951                            long bytesToConsume = (info.size + 511) & ~511;
3952                            while (bytesToConsume > 0) {
3953                                int toRead = (bytesToConsume > buffer.length)
3954                                ? buffer.length : (int)bytesToConsume;
3955                                long nRead = instream.read(buffer, 0, toRead);
3956                                if (nRead >= 0) mBytes += nRead;
3957                                if (nRead <= 0) break;
3958                                bytesToConsume -= nRead;
3959                            }
3960                        }
3961                    }
3962                }
3963            } catch (IOException e) {
3964                if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
3965                // treat as EOF
3966                info = null;
3967            }
3968
3969            return (info != null);
3970        }
3971
3972        void setUpPipes() throws IOException {
3973            mPipes = ParcelFileDescriptor.createPipe();
3974        }
3975
3976        void tearDownPipes() {
3977            if (mPipes != null) {
3978                try {
3979                    mPipes[0].close();
3980                    mPipes[0] = null;
3981                    mPipes[1].close();
3982                    mPipes[1] = null;
3983                } catch (IOException e) {
3984                    Slog.w(TAG, "Couldn't close agent pipes", e);
3985                }
3986                mPipes = null;
3987            }
3988        }
3989
3990        void tearDownAgent(ApplicationInfo app) {
3991            if (mAgent != null) {
3992                try {
3993                    // unbind and tidy up even on timeout or failure, just in case
3994                    mActivityManager.unbindBackupAgent(app);
3995
3996                    // The agent was running with a stub Application object, so shut it down.
3997                    // !!! We hardcode the confirmation UI's package name here rather than use a
3998                    //     manifest flag!  TODO something less direct.
3999                    if (app.uid != Process.SYSTEM_UID
4000                            && !app.packageName.equals("com.android.backupconfirm")) {
4001                        if (DEBUG) Slog.d(TAG, "Killing host process");
4002                        mActivityManager.killApplicationProcess(app.processName, app.uid);
4003                    } else {
4004                        if (DEBUG) Slog.d(TAG, "Not killing after full restore");
4005                    }
4006                } catch (RemoteException e) {
4007                    Slog.d(TAG, "Lost app trying to shut down");
4008                }
4009                mAgent = null;
4010            }
4011        }
4012
4013        class RestoreInstallObserver extends IPackageInstallObserver.Stub {
4014            final AtomicBoolean mDone = new AtomicBoolean();
4015            String mPackageName;
4016            int mResult;
4017
4018            public void reset() {
4019                synchronized (mDone) {
4020                    mDone.set(false);
4021                }
4022            }
4023
4024            public void waitForCompletion() {
4025                synchronized (mDone) {
4026                    while (mDone.get() == false) {
4027                        try {
4028                            mDone.wait();
4029                        } catch (InterruptedException e) { }
4030                    }
4031                }
4032            }
4033
4034            int getResult() {
4035                return mResult;
4036            }
4037
4038            @Override
4039            public void packageInstalled(String packageName, int returnCode)
4040                    throws RemoteException {
4041                synchronized (mDone) {
4042                    mResult = returnCode;
4043                    mPackageName = packageName;
4044                    mDone.set(true);
4045                    mDone.notifyAll();
4046                }
4047            }
4048        }
4049
4050        class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
4051            final AtomicBoolean mDone = new AtomicBoolean();
4052            int mResult;
4053
4054            public void reset() {
4055                synchronized (mDone) {
4056                    mDone.set(false);
4057                }
4058            }
4059
4060            public void waitForCompletion() {
4061                synchronized (mDone) {
4062                    while (mDone.get() == false) {
4063                        try {
4064                            mDone.wait();
4065                        } catch (InterruptedException e) { }
4066                    }
4067                }
4068            }
4069
4070            @Override
4071            public void packageDeleted(String packageName, int returnCode) throws RemoteException {
4072                synchronized (mDone) {
4073                    mResult = returnCode;
4074                    mDone.set(true);
4075                    mDone.notifyAll();
4076                }
4077            }
4078        }
4079
4080        final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
4081        final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
4082
4083        boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
4084            boolean okay = true;
4085
4086            if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
4087
4088            // The file content is an .apk file.  Copy it out to a staging location and
4089            // attempt to install it.
4090            File apkFile = new File(mDataDir, info.packageName);
4091            try {
4092                FileOutputStream apkStream = new FileOutputStream(apkFile);
4093                byte[] buffer = new byte[32 * 1024];
4094                long size = info.size;
4095                while (size > 0) {
4096                    long toRead = (buffer.length < size) ? buffer.length : size;
4097                    int didRead = instream.read(buffer, 0, (int)toRead);
4098                    if (didRead >= 0) mBytes += didRead;
4099                    apkStream.write(buffer, 0, didRead);
4100                    size -= didRead;
4101                }
4102                apkStream.close();
4103
4104                // make sure the installer can read it
4105                apkFile.setReadable(true, false);
4106
4107                // Now install it
4108                Uri packageUri = Uri.fromFile(apkFile);
4109                mInstallObserver.reset();
4110                mPackageManager.installPackage(packageUri, mInstallObserver,
4111                        PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
4112                        installerPackage);
4113                mInstallObserver.waitForCompletion();
4114
4115                if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
4116                    // The only time we continue to accept install of data even if the
4117                    // apk install failed is if we had already determined that we could
4118                    // accept the data regardless.
4119                    if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
4120                        okay = false;
4121                    }
4122                } else {
4123                    // Okay, the install succeeded.  Make sure it was the right app.
4124                    boolean uninstall = false;
4125                    if (!mInstallObserver.mPackageName.equals(info.packageName)) {
4126                        Slog.w(TAG, "Restore stream claimed to include apk for "
4127                                + info.packageName + " but apk was really "
4128                                + mInstallObserver.mPackageName);
4129                        // delete the package we just put in place; it might be fraudulent
4130                        okay = false;
4131                        uninstall = true;
4132                    } else {
4133                        try {
4134                            PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
4135                                    PackageManager.GET_SIGNATURES);
4136                            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
4137                                Slog.w(TAG, "Restore stream contains apk of package "
4138                                        + info.packageName + " but it disallows backup/restore");
4139                                okay = false;
4140                            } else {
4141                                // So far so good -- do the signatures match the manifest?
4142                                Signature[] sigs = mManifestSignatures.get(info.packageName);
4143                                if (signaturesMatch(sigs, pkg)) {
4144                                    // If this is a system-uid app without a declared backup agent,
4145                                    // don't restore any of the file data.
4146                                    if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
4147                                            && (pkg.applicationInfo.backupAgentName == null)) {
4148                                        Slog.w(TAG, "Installed app " + info.packageName
4149                                                + " has restricted uid and no agent");
4150                                        okay = false;
4151                                    }
4152                                } else {
4153                                    Slog.w(TAG, "Installed app " + info.packageName
4154                                            + " signatures do not match restore manifest");
4155                                    okay = false;
4156                                    uninstall = true;
4157                                }
4158                            }
4159                        } catch (NameNotFoundException e) {
4160                            Slog.w(TAG, "Install of package " + info.packageName
4161                                    + " succeeded but now not found");
4162                            okay = false;
4163                        }
4164                    }
4165
4166                    // If we're not okay at this point, we need to delete the package
4167                    // that we just installed.
4168                    if (uninstall) {
4169                        mDeleteObserver.reset();
4170                        mPackageManager.deletePackage(mInstallObserver.mPackageName,
4171                                mDeleteObserver, 0);
4172                        mDeleteObserver.waitForCompletion();
4173                    }
4174                }
4175            } catch (IOException e) {
4176                Slog.e(TAG, "Unable to transcribe restored apk for install");
4177                okay = false;
4178            } finally {
4179                apkFile.delete();
4180            }
4181
4182            return okay;
4183        }
4184
4185        // Given an actual file content size, consume the post-content padding mandated
4186        // by the tar format.
4187        void skipTarPadding(long size, InputStream instream) throws IOException {
4188            long partial = (size + 512) % 512;
4189            if (partial > 0) {
4190                final int needed = 512 - (int)partial;
4191                byte[] buffer = new byte[needed];
4192                if (readExactly(instream, buffer, 0, needed) == needed) {
4193                    mBytes += needed;
4194                } else throw new IOException("Unexpected EOF in padding");
4195            }
4196        }
4197
4198        // Read a widget metadata file, returning the restored blob
4199        void readMetadata(FileMetadata info, InputStream instream) throws IOException {
4200            byte[] data = null;
4201
4202            // Fail on suspiciously large widget dump files
4203            if (info.size > 64 * 1024) {
4204                throw new IOException("Metadata too big; corrupt? size=" + info.size);
4205            }
4206
4207            byte[] buffer = new byte[(int) info.size];
4208            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
4209                mBytes += info.size;
4210            } else throw new IOException("Unexpected EOF in widget data");
4211
4212            String[] str = new String[1];
4213            int offset = extractLine(buffer, 0, str);
4214            int version = Integer.parseInt(str[0]);
4215            if (version == BACKUP_MANIFEST_VERSION) {
4216                offset = extractLine(buffer, offset, str);
4217                final String pkg = str[0];
4218                if (info.packageName.equals(pkg)) {
4219                    // Data checks out -- the rest of the buffer is a concatenation of
4220                    // binary blobs as described in the comment at writeAppWidgetData()
4221                    ByteArrayInputStream bin = new ByteArrayInputStream(buffer,
4222                            offset, buffer.length - offset);
4223                    DataInputStream in = new DataInputStream(bin);
4224                    while (bin.available() > 0) {
4225                        int token = in.readInt();
4226                        int size = in.readInt();
4227                        if (size > 64 * 1024) {
4228                            throw new IOException("Datum "
4229                                    + Integer.toHexString(token)
4230                                    + " too big; corrupt? size=" + info.size);
4231                        }
4232                        switch (token) {
4233                            case BACKUP_WIDGET_METADATA_TOKEN:
4234                            {
4235                                if (MORE_DEBUG) {
4236                                    Slog.i(TAG, "Got widget metadata for " + info.packageName);
4237                                }
4238                                mWidgetData = new byte[size];
4239                                in.read(mWidgetData);
4240                                break;
4241                            }
4242                            default:
4243                            {
4244                                if (DEBUG) {
4245                                    Slog.i(TAG, "Ignoring metadata blob "
4246                                            + Integer.toHexString(token)
4247                                            + " for " + info.packageName);
4248                                }
4249                                in.skipBytes(size);
4250                                break;
4251                            }
4252                        }
4253                    }
4254                } else {
4255                    Slog.w(TAG, "Metadata mismatch: package " + info.packageName
4256                            + " but widget data for " + pkg);
4257                }
4258            } else {
4259                Slog.w(TAG, "Unsupported metadata version " + version);
4260            }
4261        }
4262
4263        // Returns a policy constant; takes a buffer arg to reduce memory churn
4264        RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
4265                throws IOException {
4266            // Fail on suspiciously large manifest files
4267            if (info.size > 64 * 1024) {
4268                throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
4269            }
4270
4271            byte[] buffer = new byte[(int) info.size];
4272            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
4273                mBytes += info.size;
4274            } else throw new IOException("Unexpected EOF in manifest");
4275
4276            RestorePolicy policy = RestorePolicy.IGNORE;
4277            String[] str = new String[1];
4278            int offset = 0;
4279
4280            try {
4281                offset = extractLine(buffer, offset, str);
4282                int version = Integer.parseInt(str[0]);
4283                if (version == BACKUP_MANIFEST_VERSION) {
4284                    offset = extractLine(buffer, offset, str);
4285                    String manifestPackage = str[0];
4286                    // TODO: handle <original-package>
4287                    if (manifestPackage.equals(info.packageName)) {
4288                        offset = extractLine(buffer, offset, str);
4289                        version = Integer.parseInt(str[0]);  // app version
4290                        offset = extractLine(buffer, offset, str);
4291                        int platformVersion = Integer.parseInt(str[0]);
4292                        offset = extractLine(buffer, offset, str);
4293                        info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
4294                        offset = extractLine(buffer, offset, str);
4295                        boolean hasApk = str[0].equals("1");
4296                        offset = extractLine(buffer, offset, str);
4297                        int numSigs = Integer.parseInt(str[0]);
4298                        if (numSigs > 0) {
4299                            Signature[] sigs = new Signature[numSigs];
4300                            for (int i = 0; i < numSigs; i++) {
4301                                offset = extractLine(buffer, offset, str);
4302                                sigs[i] = new Signature(str[0]);
4303                            }
4304                            mManifestSignatures.put(info.packageName, sigs);
4305
4306                            // Okay, got the manifest info we need...
4307                            try {
4308                                PackageInfo pkgInfo = mPackageManager.getPackageInfo(
4309                                        info.packageName, PackageManager.GET_SIGNATURES);
4310                                // Fall through to IGNORE if the app explicitly disallows backup
4311                                final int flags = pkgInfo.applicationInfo.flags;
4312                                if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
4313                                    // Restore system-uid-space packages only if they have
4314                                    // defined a custom backup agent
4315                                    if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
4316                                            || (pkgInfo.applicationInfo.backupAgentName != null)) {
4317                                        // Verify signatures against any installed version; if they
4318                                        // don't match, then we fall though and ignore the data.  The
4319                                        // signatureMatch() method explicitly ignores the signature
4320                                        // check for packages installed on the system partition, because
4321                                        // such packages are signed with the platform cert instead of
4322                                        // the app developer's cert, so they're different on every
4323                                        // device.
4324                                        if (signaturesMatch(sigs, pkgInfo)) {
4325                                            if (pkgInfo.versionCode >= version) {
4326                                                Slog.i(TAG, "Sig + version match; taking data");
4327                                                policy = RestorePolicy.ACCEPT;
4328                                            } else {
4329                                                // The data is from a newer version of the app than
4330                                                // is presently installed.  That means we can only
4331                                                // use it if the matching apk is also supplied.
4332                                                Slog.d(TAG, "Data version " + version
4333                                                        + " is newer than installed version "
4334                                                        + pkgInfo.versionCode + " - requiring apk");
4335                                                policy = RestorePolicy.ACCEPT_IF_APK;
4336                                            }
4337                                        } else {
4338                                            Slog.w(TAG, "Restore manifest signatures do not match "
4339                                                    + "installed application for " + info.packageName);
4340                                        }
4341                                    } else {
4342                                        Slog.w(TAG, "Package " + info.packageName
4343                                                + " is system level with no agent");
4344                                    }
4345                                } else {
4346                                    if (DEBUG) Slog.i(TAG, "Restore manifest from "
4347                                            + info.packageName + " but allowBackup=false");
4348                                }
4349                            } catch (NameNotFoundException e) {
4350                                // Okay, the target app isn't installed.  We can process
4351                                // the restore properly only if the dataset provides the
4352                                // apk file and we can successfully install it.
4353                                if (DEBUG) Slog.i(TAG, "Package " + info.packageName
4354                                        + " not installed; requiring apk in dataset");
4355                                policy = RestorePolicy.ACCEPT_IF_APK;
4356                            }
4357
4358                            if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
4359                                Slog.i(TAG, "Cannot restore package " + info.packageName
4360                                        + " without the matching .apk");
4361                            }
4362                        } else {
4363                            Slog.i(TAG, "Missing signature on backed-up package "
4364                                    + info.packageName);
4365                        }
4366                    } else {
4367                        Slog.i(TAG, "Expected package " + info.packageName
4368                                + " but restore manifest claims " + manifestPackage);
4369                    }
4370                } else {
4371                    Slog.i(TAG, "Unknown restore manifest version " + version
4372                            + " for package " + info.packageName);
4373                }
4374            } catch (NumberFormatException e) {
4375                Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
4376            } catch (IllegalArgumentException e) {
4377                Slog.w(TAG, e.getMessage());
4378            }
4379
4380            return policy;
4381        }
4382
4383        // Builds a line from a byte buffer starting at 'offset', and returns
4384        // the index of the next unconsumed data in the buffer.
4385        int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
4386            final int end = buffer.length;
4387            if (offset >= end) throw new IOException("Incomplete data");
4388
4389            int pos;
4390            for (pos = offset; pos < end; pos++) {
4391                byte c = buffer[pos];
4392                // at LF we declare end of line, and return the next char as the
4393                // starting point for the next time through
4394                if (c == '\n') {
4395                    break;
4396                }
4397            }
4398            outStr[0] = new String(buffer, offset, pos - offset);
4399            pos++;  // may be pointing an extra byte past the end but that's okay
4400            return pos;
4401        }
4402
4403        void dumpFileMetadata(FileMetadata info) {
4404            if (DEBUG) {
4405                StringBuilder b = new StringBuilder(128);
4406
4407                // mode string
4408                b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
4409                b.append(((info.mode & 0400) != 0) ? 'r' : '-');
4410                b.append(((info.mode & 0200) != 0) ? 'w' : '-');
4411                b.append(((info.mode & 0100) != 0) ? 'x' : '-');
4412                b.append(((info.mode & 0040) != 0) ? 'r' : '-');
4413                b.append(((info.mode & 0020) != 0) ? 'w' : '-');
4414                b.append(((info.mode & 0010) != 0) ? 'x' : '-');
4415                b.append(((info.mode & 0004) != 0) ? 'r' : '-');
4416                b.append(((info.mode & 0002) != 0) ? 'w' : '-');
4417                b.append(((info.mode & 0001) != 0) ? 'x' : '-');
4418                b.append(String.format(" %9d ", info.size));
4419
4420                Date stamp = new Date(info.mtime);
4421                b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp));
4422
4423                b.append(info.packageName);
4424                b.append(" :: ");
4425                b.append(info.domain);
4426                b.append(" :: ");
4427                b.append(info.path);
4428
4429                Slog.i(TAG, b.toString());
4430            }
4431        }
4432        // Consume a tar file header block [sequence] and accumulate the relevant metadata
4433        FileMetadata readTarHeaders(InputStream instream) throws IOException {
4434            byte[] block = new byte[512];
4435            FileMetadata info = null;
4436
4437            boolean gotHeader = readTarHeader(instream, block);
4438            if (gotHeader) {
4439                try {
4440                    // okay, presume we're okay, and extract the various metadata
4441                    info = new FileMetadata();
4442                    info.size = extractRadix(block, 124, 12, 8);
4443                    info.mtime = extractRadix(block, 136, 12, 8);
4444                    info.mode = extractRadix(block, 100, 8, 8);
4445
4446                    info.path = extractString(block, 345, 155); // prefix
4447                    String path = extractString(block, 0, 100);
4448                    if (path.length() > 0) {
4449                        if (info.path.length() > 0) info.path += '/';
4450                        info.path += path;
4451                    }
4452
4453                    // tar link indicator field: 1 byte at offset 156 in the header.
4454                    int typeChar = block[156];
4455                    if (typeChar == 'x') {
4456                        // pax extended header, so we need to read that
4457                        gotHeader = readPaxExtendedHeader(instream, info);
4458                        if (gotHeader) {
4459                            // and after a pax extended header comes another real header -- read
4460                            // that to find the real file type
4461                            gotHeader = readTarHeader(instream, block);
4462                        }
4463                        if (!gotHeader) throw new IOException("Bad or missing pax header");
4464
4465                        typeChar = block[156];
4466                    }
4467
4468                    switch (typeChar) {
4469                        case '0': info.type = BackupAgent.TYPE_FILE; break;
4470                        case '5': {
4471                            info.type = BackupAgent.TYPE_DIRECTORY;
4472                            if (info.size != 0) {
4473                                Slog.w(TAG, "Directory entry with nonzero size in header");
4474                                info.size = 0;
4475                            }
4476                            break;
4477                        }
4478                        case 0: {
4479                            // presume EOF
4480                            if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
4481                            return null;
4482                        }
4483                        default: {
4484                            Slog.e(TAG, "Unknown tar entity type: " + typeChar);
4485                            throw new IOException("Unknown entity type " + typeChar);
4486                        }
4487                    }
4488
4489                    // Parse out the path
4490                    //
4491                    // first: apps/shared/unrecognized
4492                    if (FullBackup.SHARED_PREFIX.regionMatches(0,
4493                            info.path, 0, FullBackup.SHARED_PREFIX.length())) {
4494                        // File in shared storage.  !!! TODO: implement this.
4495                        info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
4496                        info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
4497                        info.domain = FullBackup.SHARED_STORAGE_TOKEN;
4498                        if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
4499                    } else if (FullBackup.APPS_PREFIX.regionMatches(0,
4500                            info.path, 0, FullBackup.APPS_PREFIX.length())) {
4501                        // App content!  Parse out the package name and domain
4502
4503                        // strip the apps/ prefix
4504                        info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
4505
4506                        // extract the package name
4507                        int slash = info.path.indexOf('/');
4508                        if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
4509                        info.packageName = info.path.substring(0, slash);
4510                        info.path = info.path.substring(slash+1);
4511
4512                        // if it's a manifest we're done, otherwise parse out the domains
4513                        if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
4514                            slash = info.path.indexOf('/');
4515                            if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
4516                            info.domain = info.path.substring(0, slash);
4517                            info.path = info.path.substring(slash + 1);
4518                        }
4519                    }
4520                } catch (IOException e) {
4521                    if (DEBUG) {
4522                        Slog.e(TAG, "Parse error in header: " + e.getMessage());
4523                        HEXLOG(block);
4524                    }
4525                    throw e;
4526                }
4527            }
4528            return info;
4529        }
4530
4531        private void HEXLOG(byte[] block) {
4532            int offset = 0;
4533            int todo = block.length;
4534            StringBuilder buf = new StringBuilder(64);
4535            while (todo > 0) {
4536                buf.append(String.format("%04x   ", offset));
4537                int numThisLine = (todo > 16) ? 16 : todo;
4538                for (int i = 0; i < numThisLine; i++) {
4539                    buf.append(String.format("%02x ", block[offset+i]));
4540                }
4541                Slog.i("hexdump", buf.toString());
4542                buf.setLength(0);
4543                todo -= numThisLine;
4544                offset += numThisLine;
4545            }
4546        }
4547
4548        // Read exactly the given number of bytes into a buffer at the stated offset.
4549        // Returns false if EOF is encountered before the requested number of bytes
4550        // could be read.
4551        int readExactly(InputStream in, byte[] buffer, int offset, int size)
4552                throws IOException {
4553            if (size <= 0) throw new IllegalArgumentException("size must be > 0");
4554
4555            int soFar = 0;
4556            while (soFar < size) {
4557                int nRead = in.read(buffer, offset + soFar, size - soFar);
4558                if (nRead <= 0) {
4559                    if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
4560                    break;
4561                }
4562                soFar += nRead;
4563            }
4564            return soFar;
4565        }
4566
4567        boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
4568            final int got = readExactly(instream, block, 0, 512);
4569            if (got == 0) return false;     // Clean EOF
4570            if (got < 512) throw new IOException("Unable to read full block header");
4571            mBytes += 512;
4572            return true;
4573        }
4574
4575        // overwrites 'info' fields based on the pax extended header
4576        boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
4577                throws IOException {
4578            // We should never see a pax extended header larger than this
4579            if (info.size > 32*1024) {
4580                Slog.w(TAG, "Suspiciously large pax header size " + info.size
4581                        + " - aborting");
4582                throw new IOException("Sanity failure: pax header size " + info.size);
4583            }
4584
4585            // read whole blocks, not just the content size
4586            int numBlocks = (int)((info.size + 511) >> 9);
4587            byte[] data = new byte[numBlocks * 512];
4588            if (readExactly(instream, data, 0, data.length) < data.length) {
4589                throw new IOException("Unable to read full pax header");
4590            }
4591            mBytes += data.length;
4592
4593            final int contentSize = (int) info.size;
4594            int offset = 0;
4595            do {
4596                // extract the line at 'offset'
4597                int eol = offset+1;
4598                while (eol < contentSize && data[eol] != ' ') eol++;
4599                if (eol >= contentSize) {
4600                    // error: we just hit EOD looking for the end of the size field
4601                    throw new IOException("Invalid pax data");
4602                }
4603                // eol points to the space between the count and the key
4604                int linelen = (int) extractRadix(data, offset, eol - offset, 10);
4605                int key = eol + 1;  // start of key=value
4606                eol = offset + linelen - 1; // trailing LF
4607                int value;
4608                for (value = key+1; data[value] != '=' && value <= eol; value++);
4609                if (value > eol) {
4610                    throw new IOException("Invalid pax declaration");
4611                }
4612
4613                // pax requires that key/value strings be in UTF-8
4614                String keyStr = new String(data, key, value-key, "UTF-8");
4615                // -1 to strip the trailing LF
4616                String valStr = new String(data, value+1, eol-value-1, "UTF-8");
4617
4618                if ("path".equals(keyStr)) {
4619                    info.path = valStr;
4620                } else if ("size".equals(keyStr)) {
4621                    info.size = Long.parseLong(valStr);
4622                } else {
4623                    if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
4624                }
4625
4626                offset += linelen;
4627            } while (offset < contentSize);
4628
4629            return true;
4630        }
4631
4632        long extractRadix(byte[] data, int offset, int maxChars, int radix)
4633                throws IOException {
4634            long value = 0;
4635            final int end = offset + maxChars;
4636            for (int i = offset; i < end; i++) {
4637                final byte b = data[i];
4638                // Numeric fields in tar can terminate with either NUL or SPC
4639                if (b == 0 || b == ' ') break;
4640                if (b < '0' || b > ('0' + radix - 1)) {
4641                    throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
4642                }
4643                value = radix * value + (b - '0');
4644            }
4645            return value;
4646        }
4647
4648        String extractString(byte[] data, int offset, int maxChars) throws IOException {
4649            final int end = offset + maxChars;
4650            int eos = offset;
4651            // tar string fields terminate early with a NUL
4652            while (eos < end && data[eos] != 0) eos++;
4653            return new String(data, offset, eos-offset, "US-ASCII");
4654        }
4655
4656        void sendStartRestore() {
4657            if (mObserver != null) {
4658                try {
4659                    mObserver.onStartRestore();
4660                } catch (RemoteException e) {
4661                    Slog.w(TAG, "full restore observer went away: startRestore");
4662                    mObserver = null;
4663                }
4664            }
4665        }
4666
4667        void sendOnRestorePackage(String name) {
4668            if (mObserver != null) {
4669                try {
4670                    // TODO: use a more user-friendly name string
4671                    mObserver.onRestorePackage(name);
4672                } catch (RemoteException e) {
4673                    Slog.w(TAG, "full restore observer went away: restorePackage");
4674                    mObserver = null;
4675                }
4676            }
4677        }
4678
4679        void sendEndRestore() {
4680            if (mObserver != null) {
4681                try {
4682                    mObserver.onEndRestore();
4683                } catch (RemoteException e) {
4684                    Slog.w(TAG, "full restore observer went away: endRestore");
4685                    mObserver = null;
4686                }
4687            }
4688        }
4689    }
4690
4691    // ----- Restore handling -----
4692
4693    private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4694        // If the target resides on the system partition, we allow it to restore
4695        // data from the like-named package in a restore set even if the signatures
4696        // do not match.  (Unlike general applications, those flashed to the system
4697        // partition will be signed with the device's platform certificate, so on
4698        // different phones the same system app will have different signatures.)
4699        if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4700            if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
4701            return true;
4702        }
4703
4704        // Allow unsigned apps, but not signed on one device and unsigned on the other
4705        // !!! TODO: is this the right policy?
4706        Signature[] deviceSigs = target.signatures;
4707        if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
4708                + " device=" + deviceSigs);
4709        if ((storedSigs == null || storedSigs.length == 0)
4710                && (deviceSigs == null || deviceSigs.length == 0)) {
4711            return true;
4712        }
4713        if (storedSigs == null || deviceSigs == null) {
4714            return false;
4715        }
4716
4717        // !!! TODO: this demands that every stored signature match one
4718        // that is present on device, and does not demand the converse.
4719        // Is this this right policy?
4720        int nStored = storedSigs.length;
4721        int nDevice = deviceSigs.length;
4722
4723        for (int i=0; i < nStored; i++) {
4724            boolean match = false;
4725            for (int j=0; j < nDevice; j++) {
4726                if (storedSigs[i].equals(deviceSigs[j])) {
4727                    match = true;
4728                    break;
4729                }
4730            }
4731            if (!match) {
4732                return false;
4733            }
4734        }
4735        return true;
4736    }
4737
4738    enum RestoreState {
4739        INITIAL,
4740        DOWNLOAD_DATA,
4741        PM_METADATA,
4742        RUNNING_QUEUE,
4743        FINAL
4744    }
4745
4746    class PerformRestoreTask implements BackupRestoreTask {
4747        private IBackupTransport mTransport;
4748        private IRestoreObserver mObserver;
4749        private long mToken;
4750        private PackageInfo mTargetPackage;
4751        private File mStateDir;
4752        private int mPmToken;
4753        private boolean mIsSystemRestore;
4754        private HashSet<String> mFilterSet;
4755        private long mStartRealtime;
4756        private PackageManagerBackupAgent mPmAgent;
4757        private List<PackageInfo> mAgentPackages;
4758        private ArrayList<PackageInfo> mRestorePackages;
4759        private RestoreState mCurrentState;
4760        private int mCount;
4761        private boolean mFinished;
4762        private int mStatus;
4763        private File mBackupDataName;
4764        private File mStageName;
4765        private File mNewStateName;
4766        private File mSavedStateName;
4767        private ParcelFileDescriptor mBackupData;
4768        private ParcelFileDescriptor mNewState;
4769        private PackageInfo mCurrentPackage;
4770        private byte[] mWidgetData;
4771
4772
4773        class RestoreRequest {
4774            public PackageInfo app;
4775            public int storedAppVersion;
4776
4777            RestoreRequest(PackageInfo _app, int _version) {
4778                app = _app;
4779                storedAppVersion = _version;
4780            }
4781        }
4782
4783        PerformRestoreTask(IBackupTransport transport, String dirName, IRestoreObserver observer,
4784                long restoreSetToken, PackageInfo targetPackage, int pmToken,
4785                boolean isSystemRestore, String[] filterSet) {
4786            mCurrentState = RestoreState.INITIAL;
4787            mFinished = false;
4788            mPmAgent = null;
4789
4790            mTransport = transport;
4791            mObserver = observer;
4792            mToken = restoreSetToken;
4793            mTargetPackage = targetPackage;
4794            mPmToken = pmToken;
4795            mIsSystemRestore = isSystemRestore;
4796
4797            if (filterSet != null) {
4798                mFilterSet = new HashSet<String>();
4799                for (String pkg : filterSet) {
4800                    mFilterSet.add(pkg);
4801                }
4802            } else {
4803                mFilterSet = null;
4804            }
4805
4806            mStateDir = new File(mBaseStateDir, dirName);
4807        }
4808
4809        // Execute one tick of whatever state machine the task implements
4810        @Override
4811        public void execute() {
4812            if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4813            switch (mCurrentState) {
4814                case INITIAL:
4815                    beginRestore();
4816                    break;
4817
4818                case DOWNLOAD_DATA:
4819                    downloadRestoreData();
4820                    break;
4821
4822                case PM_METADATA:
4823                    restorePmMetadata();
4824                    break;
4825
4826                case RUNNING_QUEUE:
4827                    restoreNextAgent();
4828                    break;
4829
4830                case FINAL:
4831                    if (!mFinished) finalizeRestore();
4832                    else {
4833                        Slog.e(TAG, "Duplicate finish");
4834                    }
4835                    mFinished = true;
4836                    break;
4837            }
4838        }
4839
4840        // Initialize and set up for the PM metadata restore, which comes first
4841        void beginRestore() {
4842            // Don't account time doing the restore as inactivity of the app
4843            // that has opened a restore session.
4844            mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4845
4846            // Assume error until we successfully init everything
4847            mStatus = BackupConstants.TRANSPORT_ERROR;
4848
4849            try {
4850                // TODO: Log this before getAvailableRestoreSets, somehow
4851                EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
4852
4853                // Get the list of all packages which have backup enabled.
4854                // (Include the Package Manager metadata pseudo-package first.)
4855                mRestorePackages = new ArrayList<PackageInfo>();
4856                PackageInfo omPackage = new PackageInfo();
4857                omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4858                mRestorePackages.add(omPackage);
4859
4860                mAgentPackages = allAgentPackages();
4861                if (mTargetPackage == null) {
4862                    // if there's a filter set, strip out anything that isn't
4863                    // present before proceeding
4864                    if (mFilterSet != null) {
4865                        for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4866                            final PackageInfo pkg = mAgentPackages.get(i);
4867                            if (! mFilterSet.contains(pkg.packageName)) {
4868                                mAgentPackages.remove(i);
4869                            }
4870                        }
4871                        if (MORE_DEBUG) {
4872                            Slog.i(TAG, "Post-filter package set for restore:");
4873                            for (PackageInfo p : mAgentPackages) {
4874                                Slog.i(TAG, "    " + p);
4875                            }
4876                        }
4877                    }
4878                    mRestorePackages.addAll(mAgentPackages);
4879                } else {
4880                    // Just one package to attempt restore of
4881                    mRestorePackages.add(mTargetPackage);
4882                }
4883
4884                // let the observer know that we're running
4885                if (mObserver != null) {
4886                    try {
4887                        // !!! TODO: get an actual count from the transport after
4888                        // its startRestore() runs?
4889                        mObserver.restoreStarting(mRestorePackages.size());
4890                    } catch (RemoteException e) {
4891                        Slog.d(TAG, "Restore observer died at restoreStarting");
4892                        mObserver = null;
4893                    }
4894                }
4895            } catch (RemoteException e) {
4896                // Something has gone catastrophically wrong with the transport
4897                Slog.e(TAG, "Error communicating with transport for restore");
4898                executeNextState(RestoreState.FINAL);
4899                return;
4900            }
4901
4902            mStatus = BackupConstants.TRANSPORT_OK;
4903            executeNextState(RestoreState.DOWNLOAD_DATA);
4904        }
4905
4906        void downloadRestoreData() {
4907            // Note that the download phase can be very time consuming, but we're executing
4908            // it inline here on the looper.  This is "okay" because it is not calling out to
4909            // third party code; the transport is "trusted," and so we assume it is being a
4910            // good citizen and timing out etc when appropriate.
4911            //
4912            // TODO: when appropriate, move the download off the looper and rearrange the
4913            //       error handling around that.
4914            try {
4915                mStatus = mTransport.startRestore(mToken,
4916                        mRestorePackages.toArray(new PackageInfo[0]));
4917                if (mStatus != BackupConstants.TRANSPORT_OK) {
4918                    Slog.e(TAG, "Error starting restore operation");
4919                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4920                    executeNextState(RestoreState.FINAL);
4921                    return;
4922                }
4923            } catch (RemoteException e) {
4924                Slog.e(TAG, "Error communicating with transport for restore");
4925                EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4926                mStatus = BackupConstants.TRANSPORT_ERROR;
4927                executeNextState(RestoreState.FINAL);
4928                return;
4929            }
4930
4931            // Successful download of the data to be parceled out to the apps, so off we go.
4932            executeNextState(RestoreState.PM_METADATA);
4933        }
4934
4935        void restorePmMetadata() {
4936            try {
4937                String packageName = mTransport.nextRestorePackage();
4938                if (packageName == null) {
4939                    Slog.e(TAG, "Error getting first restore package");
4940                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4941                    mStatus = BackupConstants.TRANSPORT_ERROR;
4942                    executeNextState(RestoreState.FINAL);
4943                    return;
4944                } else if (packageName.equals("")) {
4945                    Slog.i(TAG, "No restore data available");
4946                    int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4947                    EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
4948                    mStatus = BackupConstants.TRANSPORT_OK;
4949                    executeNextState(RestoreState.FINAL);
4950                    return;
4951                } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
4952                    Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
4953                            + "\", found only \"" + packageName + "\"");
4954                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
4955                            "Package manager data missing");
4956                    executeNextState(RestoreState.FINAL);
4957                    return;
4958                }
4959
4960                // Pull the Package Manager metadata from the restore set first
4961                PackageInfo omPackage = new PackageInfo();
4962                omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4963                mPmAgent = new PackageManagerBackupAgent(
4964                        mPackageManager, mAgentPackages);
4965                initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()));
4966                // The PM agent called operationComplete() already, because our invocation
4967                // of it is process-local and therefore synchronous.  That means that a
4968                // RUNNING_QUEUE message is already enqueued.  Only if we're unable to
4969                // proceed with running the queue do we remove that pending message and
4970                // jump straight to the FINAL state.
4971
4972                // Verify that the backup set includes metadata.  If not, we can't do
4973                // signature/version verification etc, so we simply do not proceed with
4974                // the restore operation.
4975                if (!mPmAgent.hasMetadata()) {
4976                    Slog.e(TAG, "No restore metadata available, so not restoring settings");
4977                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
4978                    "Package manager restore metadata missing");
4979                    mStatus = BackupConstants.TRANSPORT_ERROR;
4980                    mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4981                    executeNextState(RestoreState.FINAL);
4982                    return;
4983                }
4984            } catch (RemoteException e) {
4985                Slog.e(TAG, "Error communicating with transport for restore");
4986                EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4987                mStatus = BackupConstants.TRANSPORT_ERROR;
4988                mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4989                executeNextState(RestoreState.FINAL);
4990                return;
4991            }
4992
4993            // Metadata is intact, so we can now run the restore queue.  If we get here,
4994            // we have already enqueued the necessary next-step message on the looper.
4995            // We've deferred telling the App Widget service that we might be replacing
4996            // the widget environment with something else, but now we know we've got
4997            // data coming, so we do it here.
4998            if (mIsSystemRestore) {
4999                AppWidgetBackupBridge.restoreStarting(UserHandle.USER_OWNER);
5000            }
5001        }
5002
5003        void restoreNextAgent() {
5004            try {
5005                String packageName = mTransport.nextRestorePackage();
5006
5007                if (packageName == null) {
5008                    Slog.e(TAG, "Error getting next restore package");
5009                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
5010                    executeNextState(RestoreState.FINAL);
5011                    return;
5012                } else if (packageName.equals("")) {
5013                    if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
5014                    int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
5015                    EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
5016                    executeNextState(RestoreState.FINAL);
5017                    return;
5018                }
5019
5020                if (mObserver != null) {
5021                    try {
5022                        mObserver.onUpdate(mCount, packageName);
5023                    } catch (RemoteException e) {
5024                        Slog.d(TAG, "Restore observer died in onUpdate");
5025                        mObserver = null;
5026                    }
5027                }
5028
5029                Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
5030                if (metaInfo == null) {
5031                    Slog.e(TAG, "Missing metadata for " + packageName);
5032                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
5033                            "Package metadata missing");
5034                    executeNextState(RestoreState.RUNNING_QUEUE);
5035                    return;
5036                }
5037
5038                PackageInfo packageInfo;
5039                try {
5040                    int flags = PackageManager.GET_SIGNATURES;
5041                    packageInfo = mPackageManager.getPackageInfo(packageName, flags);
5042                } catch (NameNotFoundException e) {
5043                    Slog.e(TAG, "Invalid package restoring data", e);
5044                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
5045                            "Package missing on device");
5046                    executeNextState(RestoreState.RUNNING_QUEUE);
5047                    return;
5048                }
5049
5050                if (packageInfo.applicationInfo.backupAgentName == null
5051                        || "".equals(packageInfo.applicationInfo.backupAgentName)) {
5052                    if (DEBUG) {
5053                        Slog.i(TAG, "Data exists for package " + packageName
5054                                + " but app has no agent; skipping");
5055                    }
5056                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
5057                            "Package has no agent");
5058                    executeNextState(RestoreState.RUNNING_QUEUE);
5059                    return;
5060                }
5061
5062                if (metaInfo.versionCode > packageInfo.versionCode) {
5063                    // Data is from a "newer" version of the app than we have currently
5064                    // installed.  If the app has not declared that it is prepared to
5065                    // handle this case, we do not attempt the restore.
5066                    if ((packageInfo.applicationInfo.flags
5067                            & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
5068                        String message = "Version " + metaInfo.versionCode
5069                        + " > installed version " + packageInfo.versionCode;
5070                        Slog.w(TAG, "Package " + packageName + ": " + message);
5071                        EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
5072                                packageName, message);
5073                        executeNextState(RestoreState.RUNNING_QUEUE);
5074                        return;
5075                    } else {
5076                        if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
5077                                + " > installed " + packageInfo.versionCode
5078                                + " but restoreAnyVersion");
5079                    }
5080                }
5081
5082                if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
5083                    Slog.w(TAG, "Signature mismatch restoring " + packageName);
5084                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
5085                            "Signature mismatch");
5086                    executeNextState(RestoreState.RUNNING_QUEUE);
5087                    return;
5088                }
5089
5090                if (DEBUG) Slog.v(TAG, "Package " + packageName
5091                        + " restore version [" + metaInfo.versionCode
5092                        + "] is compatible with installed version ["
5093                        + packageInfo.versionCode + "]");
5094
5095                // Then set up and bind the agent
5096                IBackupAgent agent = bindToAgentSynchronous(
5097                        packageInfo.applicationInfo,
5098                        IApplicationThread.BACKUP_MODE_INCREMENTAL);
5099                if (agent == null) {
5100                    Slog.w(TAG, "Can't find backup agent for " + packageName);
5101                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
5102                            "Restore agent missing");
5103                    executeNextState(RestoreState.RUNNING_QUEUE);
5104                    return;
5105                }
5106
5107                // And then finally start the restore on this agent
5108                try {
5109                    initiateOneRestore(packageInfo, metaInfo.versionCode, agent);
5110                    ++mCount;
5111                } catch (Exception e) {
5112                    Slog.e(TAG, "Error when attempting restore: " + e.toString());
5113                    agentErrorCleanup();
5114                    executeNextState(RestoreState.RUNNING_QUEUE);
5115                }
5116            } catch (RemoteException e) {
5117                Slog.e(TAG, "Unable to fetch restore data from transport");
5118                mStatus = BackupConstants.TRANSPORT_ERROR;
5119                executeNextState(RestoreState.FINAL);
5120            }
5121        }
5122
5123        void finalizeRestore() {
5124            if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
5125
5126            try {
5127                mTransport.finishRestore();
5128            } catch (RemoteException e) {
5129                Slog.e(TAG, "Error finishing restore", e);
5130            }
5131
5132            if (mObserver != null) {
5133                try {
5134                    mObserver.restoreFinished(mStatus);
5135                } catch (RemoteException e) {
5136                    Slog.d(TAG, "Restore observer died at restoreFinished");
5137                }
5138            }
5139
5140            // If this was a restoreAll operation, record that this was our
5141            // ancestral dataset, as well as the set of apps that are possibly
5142            // restoreable from the dataset
5143            if (mTargetPackage == null && mPmAgent != null) {
5144                mAncestralPackages = mPmAgent.getRestoredPackages();
5145                mAncestralToken = mToken;
5146                writeRestoreTokens();
5147            }
5148
5149            // We must under all circumstances tell the Package Manager to
5150            // proceed with install notifications if it's waiting for us.
5151            if (mPmToken > 0) {
5152                if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
5153                try {
5154                    mPackageManagerBinder.finishPackageInstall(mPmToken);
5155                } catch (RemoteException e) { /* can't happen */ }
5156            }
5157
5158            // Furthermore we need to reset the session timeout clock
5159            mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5160            mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
5161                    TIMEOUT_RESTORE_INTERVAL);
5162
5163            // Kick off any work that may be needed regarding app widget restores
5164            AppWidgetBackupBridge.restoreFinished(UserHandle.USER_OWNER);
5165
5166            // done; we can finally release the wakelock
5167            Slog.i(TAG, "Restore complete.");
5168            mWakelock.release();
5169        }
5170
5171        // Call asynchronously into the app, passing it the restore data.  The next step
5172        // after this is always a callback, either operationComplete() or handleTimeout().
5173        void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
5174            mCurrentPackage = app;
5175            mWidgetData = null;
5176            final String packageName = app.packageName;
5177
5178            if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
5179
5180            // !!! TODO: get the dirs from the transport
5181            mBackupDataName = new File(mDataDir, packageName + ".restore");
5182            mStageName = new File(mDataDir, packageName + ".stage");
5183            mNewStateName = new File(mStateDir, packageName + ".new");
5184            mSavedStateName = new File(mStateDir, packageName);
5185
5186            // don't stage the 'android' package where the wallpaper data lives.  this is
5187            // an optimization: we know there's no widget data hosted/published by that
5188            // package, and this way we avoid doing a spurious copy of MB-sized wallpaper
5189            // data following the download.
5190            boolean staging = !packageName.equals("android");
5191            ParcelFileDescriptor stage;
5192            File downloadFile = (staging) ? mStageName : mBackupDataName;
5193
5194            final int token = generateToken();
5195            try {
5196                // Run the transport's restore pass
5197                stage = ParcelFileDescriptor.open(downloadFile,
5198                            ParcelFileDescriptor.MODE_READ_WRITE |
5199                            ParcelFileDescriptor.MODE_CREATE |
5200                            ParcelFileDescriptor.MODE_TRUNCATE);
5201
5202                if (!SELinux.restorecon(mBackupDataName)) {
5203                    Slog.e(TAG, "SElinux restorecon failed for " + downloadFile);
5204                }
5205
5206                if (mTransport.getRestoreData(stage) != BackupConstants.TRANSPORT_OK) {
5207                    // Transport-level failure, so we wind everything up and
5208                    // terminate the restore operation.
5209                    Slog.e(TAG, "Error getting restore data for " + packageName);
5210                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
5211                    stage.close();
5212                    downloadFile.delete();
5213                    executeNextState(RestoreState.FINAL);
5214                    return;
5215                }
5216
5217                // We have the data from the transport. Now we extract and strip
5218                // any per-package metadata (typically widget-related information)
5219                // if appropriate
5220                if (staging) {
5221                    stage.close();
5222                    stage = ParcelFileDescriptor.open(downloadFile,
5223                            ParcelFileDescriptor.MODE_READ_ONLY);
5224
5225                    mBackupData = ParcelFileDescriptor.open(mBackupDataName,
5226                            ParcelFileDescriptor.MODE_READ_WRITE |
5227                            ParcelFileDescriptor.MODE_CREATE |
5228                            ParcelFileDescriptor.MODE_TRUNCATE);
5229
5230                    BackupDataInput in = new BackupDataInput(stage.getFileDescriptor());
5231                    BackupDataOutput out = new BackupDataOutput(mBackupData.getFileDescriptor());
5232                    byte[] buffer = new byte[8192]; // will grow when needed
5233                    while (in.readNextHeader()) {
5234                        final String key = in.getKey();
5235                        final int size = in.getDataSize();
5236
5237                        // is this a special key?
5238                        if (key.equals(KEY_WIDGET_STATE)) {
5239                            if (DEBUG) {
5240                                Slog.i(TAG, "Restoring widget state for " + packageName);
5241                            }
5242                            mWidgetData = new byte[size];
5243                            in.readEntityData(mWidgetData, 0, size);
5244                        } else {
5245                            if (size > buffer.length) {
5246                                buffer = new byte[size];
5247                            }
5248                            in.readEntityData(buffer, 0, size);
5249                            out.writeEntityHeader(key, size);
5250                            out.writeEntityData(buffer, size);
5251                        }
5252                    }
5253
5254                    mBackupData.close();
5255                }
5256
5257                // Okay, we have the data.  Now have the agent do the restore.
5258                stage.close();
5259                mBackupData = ParcelFileDescriptor.open(mBackupDataName,
5260                            ParcelFileDescriptor.MODE_READ_ONLY);
5261
5262                mNewState = ParcelFileDescriptor.open(mNewStateName,
5263                            ParcelFileDescriptor.MODE_READ_WRITE |
5264                            ParcelFileDescriptor.MODE_CREATE |
5265                            ParcelFileDescriptor.MODE_TRUNCATE);
5266
5267                // Kick off the restore, checking for hung agents
5268                prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
5269                agent.doRestore(mBackupData, appVersionCode, mNewState,
5270                        token, mBackupManagerBinder);
5271            } catch (Exception e) {
5272                Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
5273                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
5274                agentErrorCleanup();    // clears any pending timeout messages as well
5275
5276                // After a restore failure we go back to running the queue.  If there
5277                // are no more packages to be restored that will be handled by the
5278                // next step.
5279                executeNextState(RestoreState.RUNNING_QUEUE);
5280            }
5281        }
5282
5283        void agentErrorCleanup() {
5284            // If the agent fails restore, it might have put the app's data
5285            // into an incoherent state.  For consistency we wipe its data
5286            // again in this case before continuing with normal teardown
5287            clearApplicationDataSynchronous(mCurrentPackage.packageName);
5288            agentCleanup();
5289        }
5290
5291        void agentCleanup() {
5292            mBackupDataName.delete();
5293            mStageName.delete();
5294            try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
5295            try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
5296            mBackupData = mNewState = null;
5297
5298            // if everything went okay, remember the recorded state now
5299            //
5300            // !!! TODO: the restored data should be migrated on the server
5301            // side into the current dataset.  In that case the new state file
5302            // we just created would reflect the data already extant in the
5303            // backend, so there'd be nothing more to do.  Until that happens,
5304            // however, we need to make sure that we record the data to the
5305            // current backend dataset.  (Yes, this means shipping the data over
5306            // the wire in both directions.  That's bad, but consistency comes
5307            // first, then efficiency.)  Once we introduce server-side data
5308            // migration to the newly-restored device's dataset, we will change
5309            // the following from a discard of the newly-written state to the
5310            // "correct" operation of renaming into the canonical state blob.
5311            mNewStateName.delete();                      // TODO: remove; see above comment
5312            //mNewStateName.renameTo(mSavedStateName);   // TODO: replace with this
5313
5314            // If this wasn't the PM pseudopackage, tear down the agent side
5315            if (mCurrentPackage.applicationInfo != null) {
5316                // unbind and tidy up even on timeout or failure
5317                try {
5318                    mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
5319
5320                    // The agent was probably running with a stub Application object,
5321                    // which isn't a valid run mode for the main app logic.  Shut
5322                    // down the app so that next time it's launched, it gets the
5323                    // usual full initialization.  Note that this is only done for
5324                    // full-system restores: when a single app has requested a restore,
5325                    // it is explicitly not killed following that operation.
5326                    if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
5327                            & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
5328                        if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
5329                                + mCurrentPackage.applicationInfo.processName);
5330                        mActivityManager.killApplicationProcess(
5331                                mCurrentPackage.applicationInfo.processName,
5332                                mCurrentPackage.applicationInfo.uid);
5333                    }
5334                } catch (RemoteException e) {
5335                    // can't happen; we run in the same process as the activity manager
5336                }
5337            }
5338
5339            // The caller is responsible for reestablishing the state machine; our
5340            // responsibility here is to clear the decks for whatever comes next.
5341            mBackupHandler.removeMessages(MSG_TIMEOUT, this);
5342            synchronized (mCurrentOpLock) {
5343                mCurrentOperations.clear();
5344            }
5345        }
5346
5347        // A call to agent.doRestore() has been positively acknowledged as complete
5348        @Override
5349        public void operationComplete() {
5350            int size = (int) mBackupDataName.length();
5351            EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
5352
5353            // Just go back to running the restore queue
5354            agentCleanup();
5355
5356            // If there was widget state associated with this app, get the OS to
5357            // incorporate it into current bookeeping and then pass that along to
5358            // the app as part of the restore operation.
5359            if (mWidgetData != null) {
5360                restoreWidgetData(mCurrentPackage.packageName, mWidgetData);
5361            }
5362
5363            executeNextState(RestoreState.RUNNING_QUEUE);
5364        }
5365
5366        // A call to agent.doRestore() has timed out
5367        @Override
5368        public void handleTimeout() {
5369            Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
5370            EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
5371                    mCurrentPackage.packageName, "restore timeout");
5372            // Handle like an agent that threw on invocation: wipe it and go on to the next
5373            agentErrorCleanup();
5374            executeNextState(RestoreState.RUNNING_QUEUE);
5375        }
5376
5377        void executeNextState(RestoreState nextState) {
5378            if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
5379                    + this + " nextState=" + nextState);
5380            mCurrentState = nextState;
5381            Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
5382            mBackupHandler.sendMessage(msg);
5383        }
5384    }
5385
5386    // Used by both incremental and full restore
5387    void restoreWidgetData(String packageName, byte[] widgetData) {
5388        // Apply the restored widget state and generate the ID update for the app
5389        AppWidgetBackupBridge.restoreWidgetState(packageName, widgetData, UserHandle.USER_OWNER);
5390    }
5391
5392    class PerformClearTask implements Runnable {
5393        IBackupTransport mTransport;
5394        PackageInfo mPackage;
5395
5396        PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
5397            mTransport = transport;
5398            mPackage = packageInfo;
5399        }
5400
5401        public void run() {
5402            try {
5403                // Clear the on-device backup state to ensure a full backup next time
5404                File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
5405                File stateFile = new File(stateDir, mPackage.packageName);
5406                stateFile.delete();
5407
5408                // Tell the transport to remove all the persistent storage for the app
5409                // TODO - need to handle failures
5410                mTransport.clearBackupData(mPackage);
5411            } catch (RemoteException e) {
5412                // can't happen; the transport is local
5413            } catch (Exception e) {
5414                Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
5415            } finally {
5416                try {
5417                    // TODO - need to handle failures
5418                    mTransport.finishBackup();
5419                } catch (RemoteException e) {
5420                    // can't happen; the transport is local
5421                }
5422
5423                // Last but not least, release the cpu
5424                mWakelock.release();
5425            }
5426        }
5427    }
5428
5429    class PerformInitializeTask implements Runnable {
5430        HashSet<String> mQueue;
5431
5432        PerformInitializeTask(HashSet<String> transportNames) {
5433            mQueue = transportNames;
5434        }
5435
5436        public void run() {
5437            try {
5438                for (String transportName : mQueue) {
5439                    IBackupTransport transport = getTransport(transportName);
5440                    if (transport == null) {
5441                        Slog.e(TAG, "Requested init for " + transportName + " but not found");
5442                        continue;
5443                    }
5444
5445                    Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
5446                    EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
5447                    long startRealtime = SystemClock.elapsedRealtime();
5448                    int status = transport.initializeDevice();
5449
5450                    if (status == BackupConstants.TRANSPORT_OK) {
5451                        status = transport.finishBackup();
5452                    }
5453
5454                    // Okay, the wipe really happened.  Clean up our local bookkeeping.
5455                    if (status == BackupConstants.TRANSPORT_OK) {
5456                        Slog.i(TAG, "Device init successful");
5457                        int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
5458                        EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
5459                        resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
5460                        EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
5461                        synchronized (mQueueLock) {
5462                            recordInitPendingLocked(false, transportName);
5463                        }
5464                    } else {
5465                        // If this didn't work, requeue this one and try again
5466                        // after a suitable interval
5467                        Slog.e(TAG, "Transport error in initializeDevice()");
5468                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
5469                        synchronized (mQueueLock) {
5470                            recordInitPendingLocked(true, transportName);
5471                        }
5472                        // do this via another alarm to make sure of the wakelock states
5473                        long delay = transport.requestBackupTime();
5474                        if (DEBUG) Slog.w(TAG, "init failed on "
5475                                + transportName + " resched in " + delay);
5476                        mAlarmManager.set(AlarmManager.RTC_WAKEUP,
5477                                System.currentTimeMillis() + delay, mRunInitIntent);
5478                    }
5479                }
5480            } catch (RemoteException e) {
5481                // can't happen; the transports are local
5482            } catch (Exception e) {
5483                Slog.e(TAG, "Unexpected error performing init", e);
5484            } finally {
5485                // Done; release the wakelock
5486                mWakelock.release();
5487            }
5488        }
5489    }
5490
5491    private void dataChangedImpl(String packageName) {
5492        HashSet<String> targets = dataChangedTargets(packageName);
5493        dataChangedImpl(packageName, targets);
5494    }
5495
5496    private void dataChangedImpl(String packageName, HashSet<String> targets) {
5497        // Record that we need a backup pass for the caller.  Since multiple callers
5498        // may share a uid, we need to note all candidates within that uid and schedule
5499        // a backup pass for each of them.
5500        EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
5501
5502        if (targets == null) {
5503            Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
5504                   + " uid=" + Binder.getCallingUid());
5505            return;
5506        }
5507
5508        synchronized (mQueueLock) {
5509            // Note that this client has made data changes that need to be backed up
5510            if (targets.contains(packageName)) {
5511                // Add the caller to the set of pending backups.  If there is
5512                // one already there, then overwrite it, but no harm done.
5513                BackupRequest req = new BackupRequest(packageName);
5514                if (mPendingBackups.put(packageName, req) == null) {
5515                    if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
5516
5517                    // Journal this request in case of crash.  The put()
5518                    // operation returned null when this package was not already
5519                    // in the set; we want to avoid touching the disk redundantly.
5520                    writeToJournalLocked(packageName);
5521
5522                    if (MORE_DEBUG) {
5523                        int numKeys = mPendingBackups.size();
5524                        Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
5525                        for (BackupRequest b : mPendingBackups.values()) {
5526                            Slog.d(TAG, "    + " + b);
5527                        }
5528                    }
5529                }
5530            }
5531        }
5532    }
5533
5534    // Note: packageName is currently unused, but may be in the future
5535    private HashSet<String> dataChangedTargets(String packageName) {
5536        // If the caller does not hold the BACKUP permission, it can only request a
5537        // backup of its own data.
5538        if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
5539                Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
5540            synchronized (mBackupParticipants) {
5541                return mBackupParticipants.get(Binder.getCallingUid());
5542            }
5543        }
5544
5545        // a caller with full permission can ask to back up any participating app
5546        // !!! TODO: allow backup of ANY app?
5547        HashSet<String> targets = new HashSet<String>();
5548        synchronized (mBackupParticipants) {
5549            int N = mBackupParticipants.size();
5550            for (int i = 0; i < N; i++) {
5551                HashSet<String> s = mBackupParticipants.valueAt(i);
5552                if (s != null) {
5553                    targets.addAll(s);
5554                }
5555            }
5556        }
5557        return targets;
5558    }
5559
5560    private void writeToJournalLocked(String str) {
5561        RandomAccessFile out = null;
5562        try {
5563            if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
5564            out = new RandomAccessFile(mJournal, "rws");
5565            out.seek(out.length());
5566            out.writeUTF(str);
5567        } catch (IOException e) {
5568            Slog.e(TAG, "Can't write " + str + " to backup journal", e);
5569            mJournal = null;
5570        } finally {
5571            try { if (out != null) out.close(); } catch (IOException e) {}
5572        }
5573    }
5574
5575    // ----- IBackupManager binder interface -----
5576
5577    public void dataChanged(final String packageName) {
5578        final int callingUserHandle = UserHandle.getCallingUserId();
5579        if (callingUserHandle != UserHandle.USER_OWNER) {
5580            // App is running under a non-owner user profile.  For now, we do not back
5581            // up data from secondary user profiles.
5582            // TODO: backups for all user profiles.
5583            if (MORE_DEBUG) {
5584                Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
5585                        + callingUserHandle);
5586            }
5587            return;
5588        }
5589
5590        final HashSet<String> targets = dataChangedTargets(packageName);
5591        if (targets == null) {
5592            Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
5593                   + " uid=" + Binder.getCallingUid());
5594            return;
5595        }
5596
5597        mBackupHandler.post(new Runnable() {
5598                public void run() {
5599                    dataChangedImpl(packageName, targets);
5600                }
5601            });
5602    }
5603
5604    // Clear the given package's backup data from the current transport
5605    public void clearBackupData(String transportName, String packageName) {
5606        if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName + " on " + transportName);
5607        PackageInfo info;
5608        try {
5609            info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
5610        } catch (NameNotFoundException e) {
5611            Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
5612            return;
5613        }
5614
5615        // If the caller does not hold the BACKUP permission, it can only request a
5616        // wipe of its own backed-up data.
5617        HashSet<String> apps;
5618        if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
5619                Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
5620            apps = mBackupParticipants.get(Binder.getCallingUid());
5621        } else {
5622            // a caller with full permission can ask to back up any participating app
5623            // !!! TODO: allow data-clear of ANY app?
5624            if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
5625            apps = new HashSet<String>();
5626            int N = mBackupParticipants.size();
5627            for (int i = 0; i < N; i++) {
5628                HashSet<String> s = mBackupParticipants.valueAt(i);
5629                if (s != null) {
5630                    apps.addAll(s);
5631                }
5632            }
5633        }
5634
5635        // Is the given app an available participant?
5636        if (apps.contains(packageName)) {
5637            // found it; fire off the clear request
5638            if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
5639            mBackupHandler.removeMessages(MSG_RETRY_CLEAR);
5640            synchronized (mQueueLock) {
5641                final IBackupTransport transport = getTransport(transportName);
5642                if (transport == null) {
5643                    // transport is currently unavailable -- make sure to retry
5644                    Message msg = mBackupHandler.obtainMessage(MSG_RETRY_CLEAR,
5645                            new ClearRetryParams(transportName, packageName));
5646                    mBackupHandler.sendMessageDelayed(msg, TRANSPORT_RETRY_INTERVAL);
5647                    return;
5648                }
5649                long oldId = Binder.clearCallingIdentity();
5650                mWakelock.acquire();
5651                Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
5652                        new ClearParams(transport, info));
5653                mBackupHandler.sendMessage(msg);
5654                Binder.restoreCallingIdentity(oldId);
5655            }
5656        }
5657    }
5658
5659    // Run a backup pass immediately for any applications that have declared
5660    // that they have pending updates.
5661    public void backupNow() {
5662        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
5663
5664        if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
5665        synchronized (mQueueLock) {
5666            // Because the alarms we are using can jitter, and we want an *immediate*
5667            // backup pass to happen, we restart the timer beginning with "next time,"
5668            // then manually fire the backup trigger intent ourselves.
5669            startBackupAlarmsLocked(BACKUP_INTERVAL);
5670            try {
5671                mRunBackupIntent.send();
5672            } catch (PendingIntent.CanceledException e) {
5673                // should never happen
5674                Slog.e(TAG, "run-backup intent cancelled!");
5675            }
5676        }
5677    }
5678
5679    boolean deviceIsProvisioned() {
5680        final ContentResolver resolver = mContext.getContentResolver();
5681        return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
5682    }
5683
5684    // Run a *full* backup pass for the given package, writing the resulting data stream
5685    // to the supplied file descriptor.  This method is synchronous and does not return
5686    // to the caller until the backup has been completed.
5687    @Override
5688    public void fullBackup(ParcelFileDescriptor fd, boolean includeApks,
5689            boolean includeObbs, boolean includeShared, boolean doWidgets,
5690            boolean doAllApps, boolean includeSystem, String[] pkgList) {
5691        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
5692
5693        final int callingUserHandle = UserHandle.getCallingUserId();
5694        if (callingUserHandle != UserHandle.USER_OWNER) {
5695            throw new IllegalStateException("Backup supported only for the device owner");
5696        }
5697
5698        // Validate
5699        if (!doAllApps) {
5700            if (!includeShared) {
5701                // If we're backing up shared data (sdcard or equivalent), then we can run
5702                // without any supplied app names.  Otherwise, we'd be doing no work, so
5703                // report the error.
5704                if (pkgList == null || pkgList.length == 0) {
5705                    throw new IllegalArgumentException(
5706                            "Backup requested but neither shared nor any apps named");
5707                }
5708            }
5709        }
5710
5711        long oldId = Binder.clearCallingIdentity();
5712        try {
5713            // Doesn't make sense to do a full backup prior to setup
5714            if (!deviceIsProvisioned()) {
5715                Slog.i(TAG, "Full backup not supported before setup");
5716                return;
5717            }
5718
5719            if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
5720                    + " obb=" + includeObbs + " shared=" + includeShared + " all=" + doAllApps
5721                    + " pkgs=" + pkgList);
5722            Slog.i(TAG, "Beginning full backup...");
5723
5724            FullBackupParams params = new FullBackupParams(fd, includeApks, includeObbs,
5725                    includeShared, doWidgets, doAllApps, includeSystem, pkgList);
5726            final int token = generateToken();
5727            synchronized (mFullConfirmations) {
5728                mFullConfirmations.put(token, params);
5729            }
5730
5731            // start up the confirmation UI
5732            if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
5733            if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
5734                Slog.e(TAG, "Unable to launch full backup confirmation");
5735                mFullConfirmations.delete(token);
5736                return;
5737            }
5738
5739            // make sure the screen is lit for the user interaction
5740            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5741
5742            // start the confirmation countdown
5743            startConfirmationTimeout(token, params);
5744
5745            // wait for the backup to be performed
5746            if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5747            waitForCompletion(params);
5748        } finally {
5749            try {
5750                fd.close();
5751            } catch (IOException e) {
5752                // just eat it
5753            }
5754            Binder.restoreCallingIdentity(oldId);
5755            Slog.d(TAG, "Full backup processing complete.");
5756        }
5757    }
5758
5759    public void fullRestore(ParcelFileDescriptor fd) {
5760        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
5761
5762        final int callingUserHandle = UserHandle.getCallingUserId();
5763        if (callingUserHandle != UserHandle.USER_OWNER) {
5764            throw new IllegalStateException("Restore supported only for the device owner");
5765        }
5766
5767        long oldId = Binder.clearCallingIdentity();
5768
5769        try {
5770            // Check whether the device has been provisioned -- we don't handle
5771            // full restores prior to completing the setup process.
5772            if (!deviceIsProvisioned()) {
5773                Slog.i(TAG, "Full restore not permitted before setup");
5774                return;
5775            }
5776
5777            Slog.i(TAG, "Beginning full restore...");
5778
5779            FullRestoreParams params = new FullRestoreParams(fd);
5780            final int token = generateToken();
5781            synchronized (mFullConfirmations) {
5782                mFullConfirmations.put(token, params);
5783            }
5784
5785            // start up the confirmation UI
5786            if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5787            if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5788                Slog.e(TAG, "Unable to launch full restore confirmation");
5789                mFullConfirmations.delete(token);
5790                return;
5791            }
5792
5793            // make sure the screen is lit for the user interaction
5794            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5795
5796            // start the confirmation countdown
5797            startConfirmationTimeout(token, params);
5798
5799            // wait for the restore to be performed
5800            if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5801            waitForCompletion(params);
5802        } finally {
5803            try {
5804                fd.close();
5805            } catch (IOException e) {
5806                Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5807            }
5808            Binder.restoreCallingIdentity(oldId);
5809            Slog.i(TAG, "Full restore processing complete.");
5810        }
5811    }
5812
5813    boolean startConfirmationUi(int token, String action) {
5814        try {
5815            Intent confIntent = new Intent(action);
5816            confIntent.setClassName("com.android.backupconfirm",
5817                    "com.android.backupconfirm.BackupRestoreConfirmation");
5818            confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5819            confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5820            mContext.startActivity(confIntent);
5821        } catch (ActivityNotFoundException e) {
5822            return false;
5823        }
5824        return true;
5825    }
5826
5827    void startConfirmationTimeout(int token, FullParams params) {
5828        if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
5829                + TIMEOUT_FULL_CONFIRMATION + " millis");
5830        Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5831                token, 0, params);
5832        mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
5833    }
5834
5835    void waitForCompletion(FullParams params) {
5836        synchronized (params.latch) {
5837            while (params.latch.get() == false) {
5838                try {
5839                    params.latch.wait();
5840                } catch (InterruptedException e) { /* never interrupted */ }
5841            }
5842        }
5843    }
5844
5845    void signalFullBackupRestoreCompletion(FullParams params) {
5846        synchronized (params.latch) {
5847            params.latch.set(true);
5848            params.latch.notifyAll();
5849        }
5850    }
5851
5852    // Confirm that the previously-requested full backup/restore operation can proceed.  This
5853    // is used to require a user-facing disclosure about the operation.
5854    @Override
5855    public void acknowledgeFullBackupOrRestore(int token, boolean allow,
5856            String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
5857        if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5858                + " allow=" + allow);
5859
5860        // TODO: possibly require not just this signature-only permission, but even
5861        // require that the specific designated confirmation-UI app uid is the caller?
5862        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
5863
5864        long oldId = Binder.clearCallingIdentity();
5865        try {
5866
5867            FullParams params;
5868            synchronized (mFullConfirmations) {
5869                params = mFullConfirmations.get(token);
5870                if (params != null) {
5871                    mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5872                    mFullConfirmations.delete(token);
5873
5874                    if (allow) {
5875                        final int verb = params instanceof FullBackupParams
5876                                ? MSG_RUN_FULL_BACKUP
5877                                : MSG_RUN_FULL_RESTORE;
5878
5879                        params.observer = observer;
5880                        params.curPassword = curPassword;
5881
5882                        boolean isEncrypted;
5883                        try {
5884                            isEncrypted = (mMountService.getEncryptionState() !=
5885                                    IMountService.ENCRYPTION_STATE_NONE);
5886                            if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5887                        } catch (RemoteException e) {
5888                            // couldn't contact the mount service; fail "safe" and assume encryption
5889                            Slog.e(TAG, "Unable to contact mount service!");
5890                            isEncrypted = true;
5891                        }
5892                        params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
5893
5894                        if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
5895                        mWakelock.acquire();
5896                        Message msg = mBackupHandler.obtainMessage(verb, params);
5897                        mBackupHandler.sendMessage(msg);
5898                    } else {
5899                        Slog.w(TAG, "User rejected full backup/restore operation");
5900                        // indicate completion without having actually transferred any data
5901                        signalFullBackupRestoreCompletion(params);
5902                    }
5903                } else {
5904                    Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5905                }
5906            }
5907        } finally {
5908            Binder.restoreCallingIdentity(oldId);
5909        }
5910    }
5911
5912    // Enable/disable the backup service
5913    @Override
5914    public void setBackupEnabled(boolean enable) {
5915        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5916                "setBackupEnabled");
5917
5918        Slog.i(TAG, "Backup enabled => " + enable);
5919
5920        long oldId = Binder.clearCallingIdentity();
5921        try {
5922            boolean wasEnabled = mEnabled;
5923            synchronized (this) {
5924                Settings.Secure.putInt(mContext.getContentResolver(),
5925                        Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
5926                mEnabled = enable;
5927            }
5928
5929            synchronized (mQueueLock) {
5930                if (enable && !wasEnabled && mProvisioned) {
5931                    // if we've just been enabled, start scheduling backup passes
5932                    startBackupAlarmsLocked(BACKUP_INTERVAL);
5933                } else if (!enable) {
5934                    // No longer enabled, so stop running backups
5935                    if (DEBUG) Slog.i(TAG, "Opting out of backup");
5936
5937                    mAlarmManager.cancel(mRunBackupIntent);
5938
5939                    // This also constitutes an opt-out, so we wipe any data for
5940                    // this device from the backend.  We start that process with
5941                    // an alarm in order to guarantee wakelock states.
5942                    if (wasEnabled && mProvisioned) {
5943                        // NOTE: we currently flush every registered transport, not just
5944                        // the currently-active one.
5945                        HashSet<String> allTransports;
5946                        synchronized (mTransports) {
5947                            allTransports = new HashSet<String>(mTransports.keySet());
5948                        }
5949                        // build the set of transports for which we are posting an init
5950                        for (String transport : allTransports) {
5951                            recordInitPendingLocked(true, transport);
5952                        }
5953                        mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5954                                mRunInitIntent);
5955                    }
5956                }
5957            }
5958        } finally {
5959            Binder.restoreCallingIdentity(oldId);
5960        }
5961    }
5962
5963    // Enable/disable automatic restore of app data at install time
5964    public void setAutoRestore(boolean doAutoRestore) {
5965        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5966                "setAutoRestore");
5967
5968        Slog.i(TAG, "Auto restore => " + doAutoRestore);
5969
5970        synchronized (this) {
5971            Settings.Secure.putInt(mContext.getContentResolver(),
5972                    Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5973            mAutoRestore = doAutoRestore;
5974        }
5975    }
5976
5977    // Mark the backup service as having been provisioned
5978    public void setBackupProvisioned(boolean available) {
5979        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5980                "setBackupProvisioned");
5981        /*
5982         * This is now a no-op; provisioning is simply the device's own setup state.
5983         */
5984    }
5985
5986    private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
5987        // We used to use setInexactRepeating(), but that may be linked to
5988        // backups running at :00 more often than not, creating load spikes.
5989        // Schedule at an exact time for now, and also add a bit of "fuzz".
5990
5991        Random random = new Random();
5992        long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5993                random.nextInt(FUZZ_MILLIS);
5994        mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5995                BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
5996        mNextBackupPass = when;
5997    }
5998
5999    // Report whether the backup mechanism is currently enabled
6000    public boolean isBackupEnabled() {
6001        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
6002        return mEnabled;    // no need to synchronize just to read it
6003    }
6004
6005    // Report the name of the currently active transport
6006    public String getCurrentTransport() {
6007        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
6008                "getCurrentTransport");
6009        if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
6010        return mCurrentTransport;
6011    }
6012
6013    // Report all known, available backup transports
6014    public String[] listAllTransports() {
6015        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
6016
6017        String[] list = null;
6018        ArrayList<String> known = new ArrayList<String>();
6019        for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
6020            if (entry.getValue() != null) {
6021                known.add(entry.getKey());
6022            }
6023        }
6024
6025        if (known.size() > 0) {
6026            list = new String[known.size()];
6027            known.toArray(list);
6028        }
6029        return list;
6030    }
6031
6032    // Select which transport to use for the next backup operation.  If the given
6033    // name is not one of the available transports, no action is taken and the method
6034    // returns null.
6035    public String selectBackupTransport(String transport) {
6036        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
6037
6038        synchronized (mTransports) {
6039            String prevTransport = null;
6040            if (mTransports.get(transport) != null) {
6041                prevTransport = mCurrentTransport;
6042                mCurrentTransport = transport;
6043                Settings.Secure.putString(mContext.getContentResolver(),
6044                        Settings.Secure.BACKUP_TRANSPORT, transport);
6045                Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
6046                        + " returning " + prevTransport);
6047            } else {
6048                Slog.w(TAG, "Attempt to select unavailable transport " + transport);
6049            }
6050            return prevTransport;
6051        }
6052    }
6053
6054    // Supply the configuration Intent for the given transport.  If the name is not one
6055    // of the available transports, or if the transport does not supply any configuration
6056    // UI, the method returns null.
6057    public Intent getConfigurationIntent(String transportName) {
6058        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
6059                "getConfigurationIntent");
6060
6061        synchronized (mTransports) {
6062            final IBackupTransport transport = mTransports.get(transportName);
6063            if (transport != null) {
6064                try {
6065                    final Intent intent = transport.configurationIntent();
6066                    if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
6067                            + intent);
6068                    return intent;
6069                } catch (RemoteException e) {
6070                    /* fall through to return null */
6071                }
6072            }
6073        }
6074
6075        return null;
6076    }
6077
6078    // Supply the configuration summary string for the given transport.  If the name is
6079    // not one of the available transports, or if the transport does not supply any
6080    // summary / destination string, the method can return null.
6081    //
6082    // This string is used VERBATIM as the summary text of the relevant Settings item!
6083    public String getDestinationString(String transportName) {
6084        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
6085                "getDestinationString");
6086
6087        synchronized (mTransports) {
6088            final IBackupTransport transport = mTransports.get(transportName);
6089            if (transport != null) {
6090                try {
6091                    final String text = transport.currentDestinationString();
6092                    if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
6093                    return text;
6094                } catch (RemoteException e) {
6095                    /* fall through to return null */
6096                }
6097            }
6098        }
6099
6100        return null;
6101    }
6102
6103    // Callback: a requested backup agent has been instantiated.  This should only
6104    // be called from the Activity Manager.
6105    public void agentConnected(String packageName, IBinder agentBinder) {
6106        synchronized(mAgentConnectLock) {
6107            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
6108                Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
6109                IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
6110                mConnectedAgent = agent;
6111                mConnecting = false;
6112            } else {
6113                Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
6114                        + " claiming agent connected");
6115            }
6116            mAgentConnectLock.notifyAll();
6117        }
6118    }
6119
6120    // Callback: a backup agent has failed to come up, or has unexpectedly quit.
6121    // If the agent failed to come up in the first place, the agentBinder argument
6122    // will be null.  This should only be called from the Activity Manager.
6123    public void agentDisconnected(String packageName) {
6124        // TODO: handle backup being interrupted
6125        synchronized(mAgentConnectLock) {
6126            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
6127                mConnectedAgent = null;
6128                mConnecting = false;
6129            } else {
6130                Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
6131                        + " claiming agent disconnected");
6132            }
6133            mAgentConnectLock.notifyAll();
6134        }
6135    }
6136
6137    // An application being installed will need a restore pass, then the Package Manager
6138    // will need to be told when the restore is finished.
6139    public void restoreAtInstall(String packageName, int token) {
6140        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
6141            Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
6142                    + " attemping install-time restore");
6143            return;
6144        }
6145
6146        boolean skip = false;
6147
6148        long restoreSet = getAvailableRestoreToken(packageName);
6149        if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
6150                + " token=" + Integer.toHexString(token)
6151                + " restoreSet=" + Long.toHexString(restoreSet));
6152        if (restoreSet == 0) {
6153            if (MORE_DEBUG) Slog.i(TAG, "No restore set");
6154            skip = true;
6155        }
6156
6157        // Do we have a transport to fetch data for us?
6158        IBackupTransport transport = getTransport(mCurrentTransport);
6159        if (transport == null) {
6160            if (DEBUG) Slog.w(TAG, "No transport");
6161            skip = true;
6162        }
6163
6164        if (!skip && mAutoRestore && mProvisioned) {
6165            try {
6166                // okay, we're going to attempt a restore of this package from this restore set.
6167                // The eventual message back into the Package Manager to run the post-install
6168                // steps for 'token' will be issued from the restore handling code.
6169
6170                // This can throw and so *must* happen before the wakelock is acquired
6171                String dirName = transport.transportDirName();
6172
6173                // We can use a synthetic PackageInfo here because:
6174                //   1. We know it's valid, since the Package Manager supplied the name
6175                //   2. Only the packageName field will be used by the restore code
6176                PackageInfo pkg = new PackageInfo();
6177                pkg.packageName = packageName;
6178
6179                mWakelock.acquire();
6180                Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
6181                msg.obj = new RestoreParams(transport, dirName, null,
6182                        restoreSet, pkg, token);
6183                mBackupHandler.sendMessage(msg);
6184            } catch (RemoteException e) {
6185                // Binding to the transport broke; back off and proceed with the installation.
6186                Slog.e(TAG, "Unable to contact transport");
6187                skip = true;
6188            }
6189        }
6190
6191        if (skip) {
6192            // Auto-restore disabled or no way to attempt a restore; just tell the Package
6193            // Manager to proceed with the post-install handling for this package.
6194            if (DEBUG) Slog.v(TAG, "Skipping");
6195            try {
6196                mPackageManagerBinder.finishPackageInstall(token);
6197            } catch (RemoteException e) { /* can't happen */ }
6198        }
6199    }
6200
6201    // Hand off a restore session
6202    public IRestoreSession beginRestoreSession(String packageName, String transport) {
6203        if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
6204                + " transport=" + transport);
6205
6206        boolean needPermission = true;
6207        if (transport == null) {
6208            transport = mCurrentTransport;
6209
6210            if (packageName != null) {
6211                PackageInfo app = null;
6212                try {
6213                    app = mPackageManager.getPackageInfo(packageName, 0);
6214                } catch (NameNotFoundException nnf) {
6215                    Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
6216                    throw new IllegalArgumentException("Package " + packageName + " not found");
6217                }
6218
6219                if (app.applicationInfo.uid == Binder.getCallingUid()) {
6220                    // So: using the current active transport, and the caller has asked
6221                    // that its own package will be restored.  In this narrow use case
6222                    // we do not require the caller to hold the permission.
6223                    needPermission = false;
6224                }
6225            }
6226        }
6227
6228        if (needPermission) {
6229            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
6230                    "beginRestoreSession");
6231        } else {
6232            if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
6233        }
6234
6235        synchronized(this) {
6236            if (mActiveRestoreSession != null) {
6237                Slog.d(TAG, "Restore session requested but one already active");
6238                return null;
6239            }
6240            mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
6241            mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
6242        }
6243        return mActiveRestoreSession;
6244    }
6245
6246    void clearRestoreSession(ActiveRestoreSession currentSession) {
6247        synchronized(this) {
6248            if (currentSession != mActiveRestoreSession) {
6249                Slog.e(TAG, "ending non-current restore session");
6250            } else {
6251                if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
6252                mActiveRestoreSession = null;
6253                mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
6254            }
6255        }
6256    }
6257
6258    // Note that a currently-active backup agent has notified us that it has
6259    // completed the given outstanding asynchronous backup/restore operation.
6260    @Override
6261    public void opComplete(int token) {
6262        if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
6263        Operation op = null;
6264        synchronized (mCurrentOpLock) {
6265            op = mCurrentOperations.get(token);
6266            if (op != null) {
6267                op.state = OP_ACKNOWLEDGED;
6268            }
6269            mCurrentOpLock.notifyAll();
6270        }
6271
6272        // The completion callback, if any, is invoked on the handler
6273        if (op != null && op.callback != null) {
6274            Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
6275            mBackupHandler.sendMessage(msg);
6276        }
6277    }
6278
6279    // ----- Restore session -----
6280
6281    class ActiveRestoreSession extends IRestoreSession.Stub {
6282        private static final String TAG = "RestoreSession";
6283
6284        private String mPackageName;
6285        private IBackupTransport mRestoreTransport = null;
6286        RestoreSet[] mRestoreSets = null;
6287        boolean mEnded = false;
6288
6289        ActiveRestoreSession(String packageName, String transport) {
6290            mPackageName = packageName;
6291            mRestoreTransport = getTransport(transport);
6292        }
6293
6294        // --- Binder interface ---
6295        public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
6296            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
6297                    "getAvailableRestoreSets");
6298            if (observer == null) {
6299                throw new IllegalArgumentException("Observer must not be null");
6300            }
6301
6302            if (mEnded) {
6303                throw new IllegalStateException("Restore session already ended");
6304            }
6305
6306            long oldId = Binder.clearCallingIdentity();
6307            try {
6308                if (mRestoreTransport == null) {
6309                    Slog.w(TAG, "Null transport getting restore sets");
6310                    return -1;
6311                }
6312                // spin off the transport request to our service thread
6313                mWakelock.acquire();
6314                Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
6315                        new RestoreGetSetsParams(mRestoreTransport, this, observer));
6316                mBackupHandler.sendMessage(msg);
6317                return 0;
6318            } catch (Exception e) {
6319                Slog.e(TAG, "Error in getAvailableRestoreSets", e);
6320                return -1;
6321            } finally {
6322                Binder.restoreCallingIdentity(oldId);
6323            }
6324        }
6325
6326        public synchronized int restoreAll(long token, IRestoreObserver observer) {
6327            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
6328                    "performRestore");
6329
6330            if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
6331                    + " observer=" + observer);
6332
6333            if (mEnded) {
6334                throw new IllegalStateException("Restore session already ended");
6335            }
6336
6337            if (mRestoreTransport == null || mRestoreSets == null) {
6338                Slog.e(TAG, "Ignoring restoreAll() with no restore set");
6339                return -1;
6340            }
6341
6342            if (mPackageName != null) {
6343                Slog.e(TAG, "Ignoring restoreAll() on single-package session");
6344                return -1;
6345            }
6346
6347            String dirName;
6348            try {
6349                dirName = mRestoreTransport.transportDirName();
6350            } catch (RemoteException e) {
6351                // Transport went AWOL; fail.
6352                Slog.e(TAG, "Unable to contact transport for restore");
6353                return -1;
6354            }
6355
6356            synchronized (mQueueLock) {
6357                for (int i = 0; i < mRestoreSets.length; i++) {
6358                    if (token == mRestoreSets[i].token) {
6359                        long oldId = Binder.clearCallingIdentity();
6360                        mWakelock.acquire();
6361                        Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
6362                        msg.obj = new RestoreParams(mRestoreTransport, dirName,
6363                                observer, token);
6364                        mBackupHandler.sendMessage(msg);
6365                        Binder.restoreCallingIdentity(oldId);
6366                        return 0;
6367                    }
6368                }
6369            }
6370
6371            Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
6372            return -1;
6373        }
6374
6375        // Restores of more than a single package are treated as 'system' restores
6376        public synchronized int restoreSome(long token, IRestoreObserver observer,
6377                String[] packages) {
6378            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
6379                    "performRestore");
6380
6381            if (DEBUG) {
6382                StringBuilder b = new StringBuilder(128);
6383                b.append("restoreSome token=");
6384                b.append(Long.toHexString(token));
6385                b.append(" observer=");
6386                b.append(observer.toString());
6387                b.append(" packages=");
6388                if (packages == null) {
6389                    b.append("null");
6390                } else {
6391                    b.append('{');
6392                    boolean first = true;
6393                    for (String s : packages) {
6394                        if (!first) {
6395                            b.append(", ");
6396                        } else first = false;
6397                        b.append(s);
6398                    }
6399                    b.append('}');
6400                }
6401                Slog.d(TAG, b.toString());
6402            }
6403
6404            if (mEnded) {
6405                throw new IllegalStateException("Restore session already ended");
6406            }
6407
6408            if (mRestoreTransport == null || mRestoreSets == null) {
6409                Slog.e(TAG, "Ignoring restoreAll() with no restore set");
6410                return -1;
6411            }
6412
6413            if (mPackageName != null) {
6414                Slog.e(TAG, "Ignoring restoreAll() on single-package session");
6415                return -1;
6416            }
6417
6418            String dirName;
6419            try {
6420                dirName = mRestoreTransport.transportDirName();
6421            } catch (RemoteException e) {
6422                // Transport went AWOL; fail.
6423                Slog.e(TAG, "Unable to contact transport for restore");
6424                return -1;
6425            }
6426
6427            synchronized (mQueueLock) {
6428                for (int i = 0; i < mRestoreSets.length; i++) {
6429                    if (token == mRestoreSets[i].token) {
6430                        long oldId = Binder.clearCallingIdentity();
6431                        mWakelock.acquire();
6432                        Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
6433                        msg.obj = new RestoreParams(mRestoreTransport, dirName, observer, token,
6434                                packages, packages.length > 1);
6435                        mBackupHandler.sendMessage(msg);
6436                        Binder.restoreCallingIdentity(oldId);
6437                        return 0;
6438                    }
6439                }
6440            }
6441
6442            Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
6443            return -1;
6444        }
6445
6446        public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
6447            if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
6448
6449            if (mEnded) {
6450                throw new IllegalStateException("Restore session already ended");
6451            }
6452
6453            if (mPackageName != null) {
6454                if (! mPackageName.equals(packageName)) {
6455                    Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
6456                            + " on session for package " + mPackageName);
6457                    return -1;
6458                }
6459            }
6460
6461            PackageInfo app = null;
6462            try {
6463                app = mPackageManager.getPackageInfo(packageName, 0);
6464            } catch (NameNotFoundException nnf) {
6465                Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
6466                return -1;
6467            }
6468
6469            // If the caller is not privileged and is not coming from the target
6470            // app's uid, throw a permission exception back to the caller.
6471            int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
6472                    Binder.getCallingPid(), Binder.getCallingUid());
6473            if ((perm == PackageManager.PERMISSION_DENIED) &&
6474                    (app.applicationInfo.uid != Binder.getCallingUid())) {
6475                Slog.w(TAG, "restorePackage: bad packageName=" + packageName
6476                        + " or calling uid=" + Binder.getCallingUid());
6477                throw new SecurityException("No permission to restore other packages");
6478            }
6479
6480            // If the package has no backup agent, we obviously cannot proceed
6481            if (app.applicationInfo.backupAgentName == null) {
6482                Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
6483                return -1;
6484            }
6485
6486            // So far so good; we're allowed to try to restore this package.  Now
6487            // check whether there is data for it in the current dataset, falling back
6488            // to the ancestral dataset if not.
6489            long token = getAvailableRestoreToken(packageName);
6490
6491            // If we didn't come up with a place to look -- no ancestral dataset and
6492            // the app has never been backed up from this device -- there's nothing
6493            // to do but return failure.
6494            if (token == 0) {
6495                if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
6496                return -1;
6497            }
6498
6499            String dirName;
6500            try {
6501                dirName = mRestoreTransport.transportDirName();
6502            } catch (RemoteException e) {
6503                // Transport went AWOL; fail.
6504                Slog.e(TAG, "Unable to contact transport for restore");
6505                return -1;
6506            }
6507
6508            // Ready to go:  enqueue the restore request and claim success
6509            long oldId = Binder.clearCallingIdentity();
6510            mWakelock.acquire();
6511            Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
6512            msg.obj = new RestoreParams(mRestoreTransport, dirName,
6513                    observer, token, app, 0);
6514            mBackupHandler.sendMessage(msg);
6515            Binder.restoreCallingIdentity(oldId);
6516            return 0;
6517        }
6518
6519        // Posted to the handler to tear down a restore session in a cleanly synchronized way
6520        class EndRestoreRunnable implements Runnable {
6521            BackupManagerService mBackupManager;
6522            ActiveRestoreSession mSession;
6523
6524            EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
6525                mBackupManager = manager;
6526                mSession = session;
6527            }
6528
6529            public void run() {
6530                // clean up the session's bookkeeping
6531                synchronized (mSession) {
6532                    try {
6533                        if (mSession.mRestoreTransport != null) {
6534                            mSession.mRestoreTransport.finishRestore();
6535                        }
6536                    } catch (Exception e) {
6537                        Slog.e(TAG, "Error in finishRestore", e);
6538                    } finally {
6539                        mSession.mRestoreTransport = null;
6540                        mSession.mEnded = true;
6541                    }
6542                }
6543
6544                // clean up the BackupManagerImpl side of the bookkeeping
6545                // and cancel any pending timeout message
6546                mBackupManager.clearRestoreSession(mSession);
6547            }
6548        }
6549
6550        public synchronized void endRestoreSession() {
6551            if (DEBUG) Slog.d(TAG, "endRestoreSession");
6552
6553            if (mEnded) {
6554                throw new IllegalStateException("Restore session already ended");
6555            }
6556
6557            mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
6558        }
6559    }
6560
6561    @Override
6562    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6563        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
6564
6565        long identityToken = Binder.clearCallingIdentity();
6566        try {
6567            dumpInternal(pw);
6568        } finally {
6569            Binder.restoreCallingIdentity(identityToken);
6570        }
6571    }
6572
6573    private void dumpInternal(PrintWriter pw) {
6574        synchronized (mQueueLock) {
6575            pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
6576                    + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
6577                    + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
6578            pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
6579            if (mBackupRunning) pw.println("Backup currently running");
6580            pw.println("Last backup pass started: " + mLastBackupPass
6581                    + " (now = " + System.currentTimeMillis() + ')');
6582            pw.println("  next scheduled: " + mNextBackupPass);
6583
6584            pw.println("Available transports:");
6585            for (String t : listAllTransports()) {
6586                pw.println((t.equals(mCurrentTransport) ? "  * " : "    ") + t);
6587                try {
6588                    IBackupTransport transport = getTransport(t);
6589                    File dir = new File(mBaseStateDir, transport.transportDirName());
6590                    pw.println("       destination: " + transport.currentDestinationString());
6591                    pw.println("       intent: " + transport.configurationIntent());
6592                    for (File f : dir.listFiles()) {
6593                        pw.println("       " + f.getName() + " - " + f.length() + " state bytes");
6594                    }
6595                } catch (Exception e) {
6596                    Slog.e(TAG, "Error in transport", e);
6597                    pw.println("        Error: " + e);
6598                }
6599            }
6600
6601            pw.println("Pending init: " + mPendingInits.size());
6602            for (String s : mPendingInits) {
6603                pw.println("    " + s);
6604            }
6605
6606            if (DEBUG_BACKUP_TRACE) {
6607                synchronized (mBackupTrace) {
6608                    if (!mBackupTrace.isEmpty()) {
6609                        pw.println("Most recent backup trace:");
6610                        for (String s : mBackupTrace) {
6611                            pw.println("   " + s);
6612                        }
6613                    }
6614                }
6615            }
6616
6617            int N = mBackupParticipants.size();
6618            pw.println("Participants:");
6619            for (int i=0; i<N; i++) {
6620                int uid = mBackupParticipants.keyAt(i);
6621                pw.print("  uid: ");
6622                pw.println(uid);
6623                HashSet<String> participants = mBackupParticipants.valueAt(i);
6624                for (String app: participants) {
6625                    pw.println("    " + app);
6626                }
6627            }
6628
6629            pw.println("Ancestral packages: "
6630                    + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
6631            if (mAncestralPackages != null) {
6632                for (String pkg : mAncestralPackages) {
6633                    pw.println("    " + pkg);
6634                }
6635            }
6636
6637            pw.println("Ever backed up: " + mEverStoredApps.size());
6638            for (String pkg : mEverStoredApps) {
6639                pw.println("    " + pkg);
6640            }
6641
6642            pw.println("Pending backup: " + mPendingBackups.size());
6643            for (BackupRequest req : mPendingBackups.values()) {
6644                pw.println("    " + req);
6645            }
6646        }
6647    }
6648}
6649