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