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