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