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