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