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