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