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