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