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