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