BackupManagerService.java revision ff8b037c10a7ce90cbb6130b49c8cb076e1e7c0f
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.BackupDataOutput;
28import android.app.backup.FullBackup;
29import android.app.backup.RestoreSet;
30import android.app.backup.IBackupManager;
31import android.app.backup.IFullBackupRestoreObserver;
32import android.app.backup.IRestoreObserver;
33import android.app.backup.IRestoreSession;
34import android.content.ActivityNotFoundException;
35import android.content.BroadcastReceiver;
36import android.content.ComponentName;
37import android.content.ContentResolver;
38import android.content.Context;
39import android.content.Intent;
40import android.content.IntentFilter;
41import android.content.ServiceConnection;
42import android.content.pm.ApplicationInfo;
43import android.content.pm.IPackageDataObserver;
44import android.content.pm.IPackageDeleteObserver;
45import android.content.pm.IPackageInstallObserver;
46import android.content.pm.IPackageManager;
47import android.content.pm.PackageInfo;
48import android.content.pm.PackageManager;
49import android.content.pm.ResolveInfo;
50import android.content.pm.ServiceInfo;
51import android.content.pm.Signature;
52import android.content.pm.PackageManager.NameNotFoundException;
53import android.database.ContentObserver;
54import android.net.Uri;
55import android.os.Binder;
56import android.os.Build;
57import android.os.Bundle;
58import android.os.Environment;
59import android.os.Handler;
60import android.os.HandlerThread;
61import android.os.IBinder;
62import android.os.Looper;
63import android.os.Message;
64import android.os.ParcelFileDescriptor;
65import android.os.PowerManager;
66import android.os.Process;
67import android.os.RemoteException;
68import android.os.SELinux;
69import android.os.ServiceManager;
70import android.os.SystemClock;
71import android.os.UserHandle;
72import android.os.WorkSource;
73import android.os.Environment.UserEnvironment;
74import android.os.storage.IMountService;
75import android.provider.Settings;
76import android.util.EventLog;
77import android.util.Log;
78import android.util.Slog;
79import android.util.SparseArray;
80import android.util.StringBuilderPrinter;
81
82import com.android.internal.backup.BackupConstants;
83import com.android.internal.backup.IBackupTransport;
84import com.android.internal.backup.IObbBackupService;
85import com.android.server.EventLogTags;
86import com.android.server.SystemService;
87import com.android.server.backup.PackageManagerBackupAgent.Metadata;
88
89import java.io.BufferedInputStream;
90import java.io.BufferedOutputStream;
91import java.io.ByteArrayOutputStream;
92import java.io.DataInputStream;
93import java.io.DataOutputStream;
94import java.io.EOFException;
95import java.io.File;
96import java.io.FileDescriptor;
97import java.io.FileInputStream;
98import java.io.FileNotFoundException;
99import java.io.FileOutputStream;
100import java.io.IOException;
101import java.io.InputStream;
102import java.io.OutputStream;
103import java.io.PrintWriter;
104import java.io.RandomAccessFile;
105import java.security.InvalidAlgorithmParameterException;
106import java.security.InvalidKeyException;
107import java.security.Key;
108import java.security.NoSuchAlgorithmException;
109import java.security.SecureRandom;
110import java.security.spec.InvalidKeySpecException;
111import java.security.spec.KeySpec;
112import java.text.SimpleDateFormat;
113import java.util.ArrayList;
114import java.util.Arrays;
115import java.util.Date;
116import java.util.HashMap;
117import java.util.HashSet;
118import java.util.List;
119import java.util.Map;
120import java.util.Random;
121import java.util.Set;
122import java.util.concurrent.atomic.AtomicBoolean;
123import java.util.zip.Deflater;
124import java.util.zip.DeflaterOutputStream;
125import java.util.zip.InflaterInputStream;
126
127import javax.crypto.BadPaddingException;
128import javax.crypto.Cipher;
129import javax.crypto.CipherInputStream;
130import javax.crypto.CipherOutputStream;
131import javax.crypto.IllegalBlockSizeException;
132import javax.crypto.NoSuchPaddingException;
133import javax.crypto.SecretKey;
134import javax.crypto.SecretKeyFactory;
135import javax.crypto.spec.IvParameterSpec;
136import javax.crypto.spec.PBEKeySpec;
137import javax.crypto.spec.SecretKeySpec;
138
139public class BackupManagerService extends IBackupManager.Stub {
140
141    private static final String TAG = "BackupManagerService";
142    private static final boolean DEBUG = true;
143    private static final boolean MORE_DEBUG = false;
144
145    // Historical and current algorithm names
146    static final String PBKDF_CURRENT = "PBKDF2WithHmacSHA1";
147    static final String PBKDF_FALLBACK = "PBKDF2WithHmacSHA1And8bit";
148
149    // Name and current contents version of the full-backup manifest file
150    static final String BACKUP_MANIFEST_FILENAME = "_manifest";
151    static final int BACKUP_MANIFEST_VERSION = 1;
152    static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
153    static final int BACKUP_FILE_VERSION = 2;
154    static final int BACKUP_PW_FILE_VERSION = 2;
155    static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
156
157    static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
158    static final String SERVICE_ACTION_TRANSPORT_HOST = "android.backup.TRANSPORT_HOST";
159
160    // How often we perform a backup pass.  Privileged external callers can
161    // trigger an immediate pass.
162    private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
163
164    // Random variation in backup scheduling time to avoid server load spikes
165    private static final int FUZZ_MILLIS = 5 * 60 * 1000;
166
167    // The amount of time between the initial provisioning of the device and
168    // the first backup pass.
169    private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
170
171    // Retry interval for clear/init when the transport is unavailable
172    private static final long TRANSPORT_RETRY_INTERVAL = 1 * AlarmManager.INTERVAL_HOUR;
173
174    private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
175    private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
176    private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
177    private static final int MSG_RUN_BACKUP = 1;
178    private static final int MSG_RUN_FULL_BACKUP = 2;
179    private static final int MSG_RUN_RESTORE = 3;
180    private static final int MSG_RUN_CLEAR = 4;
181    private static final int MSG_RUN_INITIALIZE = 5;
182    private static final int MSG_RUN_GET_RESTORE_SETS = 6;
183    private static final int MSG_TIMEOUT = 7;
184    private static final int MSG_RESTORE_TIMEOUT = 8;
185    private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
186    private static final int MSG_RUN_FULL_RESTORE = 10;
187    private static final int MSG_RETRY_INIT = 11;
188    private static final int MSG_RETRY_CLEAR = 12;
189
190    // backup task state machine tick
191    static final int MSG_BACKUP_RESTORE_STEP = 20;
192    static final int MSG_OP_COMPLETE = 21;
193
194    // Timeout interval for deciding that a bind or clear-data has taken too long
195    static final long TIMEOUT_INTERVAL = 10 * 1000;
196
197    // Timeout intervals for agent backup & restore operations
198    static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
199    static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
200    static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
201    static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
202
203    // User confirmation timeout for a full backup/restore operation.  It's this long in
204    // order to give them time to enter the backup password.
205    static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
206
207    private Context mContext;
208    private PackageManager mPackageManager;
209    IPackageManager mPackageManagerBinder;
210    private IActivityManager mActivityManager;
211    private PowerManager mPowerManager;
212    private AlarmManager mAlarmManager;
213    private IMountService mMountService;
214    IBackupManager mBackupManagerBinder;
215
216    boolean mEnabled;   // access to this is synchronized on 'this'
217    boolean mProvisioned;
218    boolean mAutoRestore;
219    PowerManager.WakeLock mWakelock;
220    HandlerThread mHandlerThread;
221    BackupHandler mBackupHandler;
222    PendingIntent mRunBackupIntent, mRunInitIntent;
223    BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
224    // map UIDs to the set of participating packages under that UID
225    final SparseArray<HashSet<String>> mBackupParticipants
226            = new SparseArray<HashSet<String>>();
227    // set of backup services that have pending changes
228    class BackupRequest {
229        public String packageName;
230
231        BackupRequest(String pkgName) {
232            packageName = pkgName;
233        }
234
235        public String toString() {
236            return "BackupRequest{pkg=" + packageName + "}";
237        }
238    }
239    // Backups that we haven't started yet.  Keys are package names.
240    HashMap<String,BackupRequest> mPendingBackups
241            = new HashMap<String,BackupRequest>();
242
243    // Pseudoname that we use for the Package Manager metadata "package"
244    static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
245
246    // locking around the pending-backup management
247    final Object mQueueLock = new Object();
248
249    // The thread performing the sequence of queued backups binds to each app's agent
250    // in succession.  Bind notifications are asynchronously delivered through the
251    // Activity Manager; use this lock object to signal when a requested binding has
252    // completed.
253    final Object mAgentConnectLock = new Object();
254    IBackupAgent mConnectedAgent;
255    volatile boolean mBackupRunning;
256    volatile boolean mConnecting;
257    volatile long mLastBackupPass;
258    volatile long mNextBackupPass;
259
260    // For debugging, we maintain a progress trace of operations during backup
261    static final boolean DEBUG_BACKUP_TRACE = true;
262    final List<String> mBackupTrace = new ArrayList<String>();
263
264    // A similar synchronization mechanism around clearing apps' data for restore
265    final Object mClearDataLock = new Object();
266    volatile boolean mClearingData;
267
268    // Transport bookkeeping
269    final HashMap<String,String> mTransportNames
270            = new HashMap<String,String>();             // component name -> registration name
271    final HashMap<String,IBackupTransport> mTransports
272            = new HashMap<String,IBackupTransport>();   // registration name -> binder
273    final ArrayList<TransportConnection> mTransportConnections
274            = new ArrayList<TransportConnection>();
275    String mCurrentTransport;
276    ActiveRestoreSession mActiveRestoreSession;
277
278    // Watch the device provisioning operation during setup
279    ContentObserver mProvisionedObserver;
280
281    public static final class Lifecycle extends SystemService {
282        private final BackupManagerService mService;
283
284        public Lifecycle(Context context) {
285            super(context);
286            mService = new BackupManagerService(context);
287        }
288
289        @Override
290        public void onStart() {
291            publishBinderService(Context.BACKUP_SERVICE, mService);
292        }
293    }
294
295    class ProvisionedObserver extends ContentObserver {
296        public ProvisionedObserver(Handler handler) {
297            super(handler);
298        }
299
300        public void onChange(boolean selfChange) {
301            final boolean wasProvisioned = mProvisioned;
302            final boolean isProvisioned = deviceIsProvisioned();
303            // latch: never unprovision
304            mProvisioned = wasProvisioned || isProvisioned;
305            if (MORE_DEBUG) {
306                Slog.d(TAG, "Provisioning change: was=" + wasProvisioned
307                        + " is=" + isProvisioned + " now=" + mProvisioned);
308            }
309
310            synchronized (mQueueLock) {
311                if (mProvisioned && !wasProvisioned && mEnabled) {
312                    // we're now good to go, so start the backup alarms
313                    if (MORE_DEBUG) Slog.d(TAG, "Now provisioned, so starting backups");
314                    startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
315                }
316            }
317        }
318    }
319
320    class RestoreGetSetsParams {
321        public IBackupTransport transport;
322        public ActiveRestoreSession session;
323        public IRestoreObserver observer;
324
325        RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
326                IRestoreObserver _observer) {
327            transport = _transport;
328            session = _session;
329            observer = _observer;
330        }
331    }
332
333    class RestoreParams {
334        public IBackupTransport transport;
335        public String dirName;
336        public IRestoreObserver observer;
337        public long token;
338        public PackageInfo pkgInfo;
339        public int pmToken; // in post-install restore, the PM's token for this transaction
340        public boolean needFullBackup;
341        public String[] filterSet;
342
343        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
344                long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
345            transport = _transport;
346            dirName = _dirName;
347            observer = _obs;
348            token = _token;
349            pkgInfo = _pkg;
350            pmToken = _pmToken;
351            needFullBackup = _needFullBackup;
352            filterSet = null;
353        }
354
355        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
356                long _token, boolean _needFullBackup) {
357            transport = _transport;
358            dirName = _dirName;
359            observer = _obs;
360            token = _token;
361            pkgInfo = null;
362            pmToken = 0;
363            needFullBackup = _needFullBackup;
364            filterSet = null;
365        }
366
367        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
368                long _token, String[] _filterSet, boolean _needFullBackup) {
369            transport = _transport;
370            dirName = _dirName;
371            observer = _obs;
372            token = _token;
373            pkgInfo = null;
374            pmToken = 0;
375            needFullBackup = _needFullBackup;
376            filterSet = _filterSet;
377        }
378    }
379
380    class ClearParams {
381        public IBackupTransport transport;
382        public PackageInfo packageInfo;
383
384        ClearParams(IBackupTransport _transport, PackageInfo _info) {
385            transport = _transport;
386            packageInfo = _info;
387        }
388    }
389
390    class ClearRetryParams {
391        public String transportName;
392        public String packageName;
393
394        ClearRetryParams(String transport, String pkg) {
395            transportName = transport;
396            packageName = pkg;
397        }
398    }
399
400    class FullParams {
401        public ParcelFileDescriptor fd;
402        public final AtomicBoolean latch;
403        public IFullBackupRestoreObserver observer;
404        public String curPassword;     // filled in by the confirmation step
405        public String encryptPassword;
406
407        FullParams() {
408            latch = new AtomicBoolean(false);
409        }
410    }
411
412    class FullBackupParams extends FullParams {
413        public boolean includeApks;
414        public boolean includeObbs;
415        public boolean includeShared;
416        public boolean allApps;
417        public boolean includeSystem;
418        public String[] packages;
419
420        FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveObbs,
421                boolean saveShared, boolean doAllApps, boolean doSystem, String[] pkgList) {
422            fd = output;
423            includeApks = saveApks;
424            includeObbs = saveObbs;
425            includeShared = saveShared;
426            allApps = doAllApps;
427            includeSystem = doSystem;
428            packages = pkgList;
429        }
430    }
431
432    class FullRestoreParams extends FullParams {
433        FullRestoreParams(ParcelFileDescriptor input) {
434            fd = input;
435        }
436    }
437
438    // Bookkeeping of in-flight operations for timeout etc. purposes.  The operation
439    // token is the index of the entry in the pending-operations list.
440    static final int OP_PENDING = 0;
441    static final int OP_ACKNOWLEDGED = 1;
442    static final int OP_TIMEOUT = -1;
443
444    class Operation {
445        public int state;
446        public BackupRestoreTask callback;
447
448        Operation(int initialState, BackupRestoreTask callbackObj) {
449            state = initialState;
450            callback = callbackObj;
451        }
452    }
453    final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
454    final Object mCurrentOpLock = new Object();
455    final Random mTokenGenerator = new Random();
456
457    final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
458
459    // Where we keep our journal files and other bookkeeping
460    File mBaseStateDir;
461    File mDataDir;
462    File mJournalDir;
463    File mJournal;
464
465    // Backup password, if any, and the file where it's saved.  What is stored is not the
466    // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
467    // persisted) salt.  Validation is performed by running the challenge text through the
468    // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
469    // the saved hash string, then the challenge text matches the originally supplied
470    // password text.
471    private final SecureRandom mRng = new SecureRandom();
472    private String mPasswordHash;
473    private File mPasswordHashFile;
474    private int mPasswordVersion;
475    private File mPasswordVersionFile;
476    private byte[] mPasswordSalt;
477
478    // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
479    static final int PBKDF2_HASH_ROUNDS = 10000;
480    static final int PBKDF2_KEY_SIZE = 256;     // bits
481    static final int PBKDF2_SALT_SIZE = 512;    // bits
482    static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
483
484    // Keep a log of all the apps we've ever backed up, and what the
485    // dataset tokens are for both the current backup dataset and
486    // the ancestral dataset.
487    private File mEverStored;
488    HashSet<String> mEverStoredApps = new HashSet<String>();
489
490    static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1;  // increment when the schema changes
491    File mTokenFile;
492    Set<String> mAncestralPackages = null;
493    long mAncestralToken = 0;
494    long mCurrentToken = 0;
495
496    // Persistently track the need to do a full init
497    static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
498    HashSet<String> mPendingInits = new HashSet<String>();  // transport names
499
500    // Utility: build a new random integer token
501    int generateToken() {
502        int token;
503        do {
504            synchronized (mTokenGenerator) {
505                token = mTokenGenerator.nextInt();
506            }
507        } while (token < 0);
508        return token;
509    }
510
511    // ----- Asynchronous backup/restore handler thread -----
512
513    private class BackupHandler extends Handler {
514        public BackupHandler(Looper looper) {
515            super(looper);
516        }
517
518        public void handleMessage(Message msg) {
519
520            switch (msg.what) {
521            case MSG_RUN_BACKUP:
522            {
523                mLastBackupPass = System.currentTimeMillis();
524                mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
525
526                IBackupTransport transport = getTransport(mCurrentTransport);
527                if (transport == null) {
528                    Slog.v(TAG, "Backup requested but no transport available");
529                    synchronized (mQueueLock) {
530                        mBackupRunning = false;
531                    }
532                    mWakelock.release();
533                    break;
534                }
535
536                // snapshot the pending-backup set and work on that
537                ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
538                File oldJournal = mJournal;
539                synchronized (mQueueLock) {
540                    // Do we have any work to do?  Construct the work queue
541                    // then release the synchronization lock to actually run
542                    // the backup.
543                    if (mPendingBackups.size() > 0) {
544                        for (BackupRequest b: mPendingBackups.values()) {
545                            queue.add(b);
546                        }
547                        if (DEBUG) Slog.v(TAG, "clearing pending backups");
548                        mPendingBackups.clear();
549
550                        // Start a new backup-queue journal file too
551                        mJournal = null;
552
553                    }
554                }
555
556                // At this point, we have started a new journal file, and the old
557                // file identity is being passed to the backup processing task.
558                // When it completes successfully, that old journal file will be
559                // deleted.  If we crash prior to that, the old journal is parsed
560                // at next boot and the journaled requests fulfilled.
561                boolean staged = true;
562                if (queue.size() > 0) {
563                    // Spin up a backup state sequence and set it running
564                    try {
565                        String dirName = transport.transportDirName();
566                        PerformBackupTask pbt = new PerformBackupTask(transport, dirName,
567                                queue, oldJournal);
568                        Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
569                        sendMessage(pbtMessage);
570                    } catch (RemoteException e) {
571                        // unable to ask the transport its dir name -- transient failure, since
572                        // the above check succeeded.  Try again next time.
573                        Slog.e(TAG, "Transport became unavailable attempting backup");
574                        staged = false;
575                    }
576                } else {
577                    Slog.v(TAG, "Backup requested but nothing pending");
578                    staged = false;
579                }
580
581                if (!staged) {
582                    // if we didn't actually hand off the wakelock, rewind until next time
583                    synchronized (mQueueLock) {
584                        mBackupRunning = false;
585                    }
586                    mWakelock.release();
587                }
588                break;
589            }
590
591            case MSG_BACKUP_RESTORE_STEP:
592            {
593                try {
594                    BackupRestoreTask task = (BackupRestoreTask) msg.obj;
595                    if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
596                    task.execute();
597                } catch (ClassCastException e) {
598                    Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
599                }
600                break;
601            }
602
603            case MSG_OP_COMPLETE:
604            {
605                try {
606                    BackupRestoreTask task = (BackupRestoreTask) msg.obj;
607                    task.operationComplete();
608                } catch (ClassCastException e) {
609                    Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
610                }
611                break;
612            }
613
614            case MSG_RUN_FULL_BACKUP:
615            {
616                // TODO: refactor full backup to be a looper-based state machine
617                // similar to normal backup/restore.
618                FullBackupParams params = (FullBackupParams)msg.obj;
619                PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
620                        params.observer, params.includeApks, params.includeObbs,
621                        params.includeShared, params.curPassword, params.encryptPassword,
622                        params.allApps, params.includeSystem, params.packages, params.latch);
623                (new Thread(task)).start();
624                break;
625            }
626
627            case MSG_RUN_RESTORE:
628            {
629                RestoreParams params = (RestoreParams)msg.obj;
630                Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
631                PerformRestoreTask task = new PerformRestoreTask(
632                        params.transport, params.dirName, params.observer,
633                        params.token, params.pkgInfo, params.pmToken,
634                        params.needFullBackup, params.filterSet);
635                Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
636                sendMessage(restoreMsg);
637                break;
638            }
639
640            case MSG_RUN_FULL_RESTORE:
641            {
642                // TODO: refactor full restore to be a looper-based state machine
643                // similar to normal backup/restore.
644                FullRestoreParams params = (FullRestoreParams)msg.obj;
645                PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
646                        params.curPassword, params.encryptPassword,
647                        params.observer, params.latch);
648                (new Thread(task)).start();
649                break;
650            }
651
652            case MSG_RUN_CLEAR:
653            {
654                ClearParams params = (ClearParams)msg.obj;
655                (new PerformClearTask(params.transport, params.packageInfo)).run();
656                break;
657            }
658
659            case MSG_RETRY_CLEAR:
660            {
661                // reenqueues if the transport remains unavailable
662                ClearRetryParams params = (ClearRetryParams)msg.obj;
663                clearBackupData(params.transportName, params.packageName);
664                break;
665            }
666
667            case MSG_RUN_INITIALIZE:
668            {
669                HashSet<String> queue;
670
671                // Snapshot the pending-init queue and work on that
672                synchronized (mQueueLock) {
673                    queue = new HashSet<String>(mPendingInits);
674                    mPendingInits.clear();
675                }
676
677                (new PerformInitializeTask(queue)).run();
678                break;
679            }
680
681            case MSG_RETRY_INIT:
682            {
683                synchronized (mQueueLock) {
684                    recordInitPendingLocked(msg.arg1 != 0, (String)msg.obj);
685                    mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
686                            mRunInitIntent);
687                }
688                break;
689            }
690
691            case MSG_RUN_GET_RESTORE_SETS:
692            {
693                // Like other async operations, this is entered with the wakelock held
694                RestoreSet[] sets = null;
695                RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
696                try {
697                    sets = params.transport.getAvailableRestoreSets();
698                    // cache the result in the active session
699                    synchronized (params.session) {
700                        params.session.mRestoreSets = sets;
701                    }
702                    if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
703                } catch (Exception e) {
704                    Slog.e(TAG, "Error from transport getting set list");
705                } finally {
706                    if (params.observer != null) {
707                        try {
708                            params.observer.restoreSetsAvailable(sets);
709                        } catch (RemoteException re) {
710                            Slog.e(TAG, "Unable to report listing to observer");
711                        } catch (Exception e) {
712                            Slog.e(TAG, "Restore observer threw", e);
713                        }
714                    }
715
716                    // Done: reset the session timeout clock
717                    removeMessages(MSG_RESTORE_TIMEOUT);
718                    sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
719
720                    mWakelock.release();
721                }
722                break;
723            }
724
725            case MSG_TIMEOUT:
726            {
727                handleTimeout(msg.arg1, msg.obj);
728                break;
729            }
730
731            case MSG_RESTORE_TIMEOUT:
732            {
733                synchronized (BackupManagerService.this) {
734                    if (mActiveRestoreSession != null) {
735                        // Client app left the restore session dangling.  We know that it
736                        // can't be in the middle of an actual restore operation because
737                        // the timeout is suspended while a restore is in progress.  Clean
738                        // up now.
739                        Slog.w(TAG, "Restore session timed out; aborting");
740                        post(mActiveRestoreSession.new EndRestoreRunnable(
741                                BackupManagerService.this, mActiveRestoreSession));
742                    }
743                }
744            }
745
746            case MSG_FULL_CONFIRMATION_TIMEOUT:
747            {
748                synchronized (mFullConfirmations) {
749                    FullParams params = mFullConfirmations.get(msg.arg1);
750                    if (params != null) {
751                        Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
752
753                        // Release the waiter; timeout == completion
754                        signalFullBackupRestoreCompletion(params);
755
756                        // Remove the token from the set
757                        mFullConfirmations.delete(msg.arg1);
758
759                        // Report a timeout to the observer, if any
760                        if (params.observer != null) {
761                            try {
762                                params.observer.onTimeout();
763                            } catch (RemoteException e) {
764                                /* don't care if the app has gone away */
765                            }
766                        }
767                    } else {
768                        Slog.d(TAG, "couldn't find params for token " + msg.arg1);
769                    }
770                }
771                break;
772            }
773            }
774        }
775    }
776
777    // ----- Debug-only backup operation trace -----
778    void addBackupTrace(String s) {
779        if (DEBUG_BACKUP_TRACE) {
780            synchronized (mBackupTrace) {
781                mBackupTrace.add(s);
782            }
783        }
784    }
785
786    void clearBackupTrace() {
787        if (DEBUG_BACKUP_TRACE) {
788            synchronized (mBackupTrace) {
789                mBackupTrace.clear();
790            }
791        }
792    }
793
794    // ----- Main service implementation -----
795
796    public BackupManagerService(Context context) {
797        mContext = context;
798        mPackageManager = context.getPackageManager();
799        mPackageManagerBinder = AppGlobals.getPackageManager();
800        mActivityManager = ActivityManagerNative.getDefault();
801
802        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
803        mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
804        mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
805
806        mBackupManagerBinder = asInterface(asBinder());
807
808        // spin up the backup/restore handler thread
809        mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
810        mHandlerThread.start();
811        mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
812
813        // Set up our bookkeeping
814        final ContentResolver resolver = context.getContentResolver();
815        boolean areEnabled = Settings.Secure.getInt(resolver,
816                Settings.Secure.BACKUP_ENABLED, 0) != 0;
817        mProvisioned = Settings.Global.getInt(resolver,
818                Settings.Global.DEVICE_PROVISIONED, 0) != 0;
819        mAutoRestore = Settings.Secure.getInt(resolver,
820                Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
821
822        mProvisionedObserver = new ProvisionedObserver(mBackupHandler);
823        resolver.registerContentObserver(
824                Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
825                false, mProvisionedObserver);
826
827        // If Encrypted file systems is enabled or disabled, this call will return the
828        // correct directory.
829        mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
830        mBaseStateDir.mkdirs();
831        if (!SELinux.restorecon(mBaseStateDir)) {
832            Slog.e(TAG, "SELinux restorecon failed on " + mBaseStateDir);
833        }
834        mDataDir = Environment.getDownloadCacheDirectory();
835
836        mPasswordVersion = 1;       // unless we hear otherwise
837        mPasswordVersionFile = new File(mBaseStateDir, "pwversion");
838        if (mPasswordVersionFile.exists()) {
839            FileInputStream fin = null;
840            DataInputStream in = null;
841            try {
842                fin = new FileInputStream(mPasswordVersionFile);
843                in = new DataInputStream(fin);
844                mPasswordVersion = in.readInt();
845            } catch (IOException e) {
846                Slog.e(TAG, "Unable to read backup pw version");
847            } finally {
848                try {
849                    if (in != null) in.close();
850                    if (fin != null) fin.close();
851                } catch (IOException e) {
852                    Slog.w(TAG, "Error closing pw version files");
853                }
854            }
855        }
856
857        mPasswordHashFile = new File(mBaseStateDir, "pwhash");
858        if (mPasswordHashFile.exists()) {
859            FileInputStream fin = null;
860            DataInputStream in = null;
861            try {
862                fin = new FileInputStream(mPasswordHashFile);
863                in = new DataInputStream(new BufferedInputStream(fin));
864                // integer length of the salt array, followed by the salt,
865                // then the hex pw hash string
866                int saltLen = in.readInt();
867                byte[] salt = new byte[saltLen];
868                in.readFully(salt);
869                mPasswordHash = in.readUTF();
870                mPasswordSalt = salt;
871            } catch (IOException e) {
872                Slog.e(TAG, "Unable to read saved backup pw hash");
873            } finally {
874                try {
875                    if (in != null) in.close();
876                    if (fin != null) fin.close();
877                } catch (IOException e) {
878                    Slog.w(TAG, "Unable to close streams");
879                }
880            }
881        }
882
883        // Alarm receivers for scheduled backups & initialization operations
884        mRunBackupReceiver = new RunBackupReceiver();
885        IntentFilter filter = new IntentFilter();
886        filter.addAction(RUN_BACKUP_ACTION);
887        context.registerReceiver(mRunBackupReceiver, filter,
888                android.Manifest.permission.BACKUP, null);
889
890        mRunInitReceiver = new RunInitializeReceiver();
891        filter = new IntentFilter();
892        filter.addAction(RUN_INITIALIZE_ACTION);
893        context.registerReceiver(mRunInitReceiver, filter,
894                android.Manifest.permission.BACKUP, null);
895
896        Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
897        backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
898        mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
899
900        Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
901        backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
902        mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
903
904        // Set up the backup-request journaling
905        mJournalDir = new File(mBaseStateDir, "pending");
906        mJournalDir.mkdirs();   // creates mBaseStateDir along the way
907        mJournal = null;        // will be created on first use
908
909        // Set up the various sorts of package tracking we do
910        initPackageTracking();
911
912        // Build our mapping of uid to backup client services.  This implicitly
913        // schedules a backup pass on the Package Manager metadata the first
914        // time anything needs to be backed up.
915        synchronized (mBackupParticipants) {
916            addPackageParticipantsLocked(null);
917        }
918
919        // Set up our transport options and initialize the default transport
920        // TODO: Don't create transports that we don't need to?
921        mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
922                Settings.Secure.BACKUP_TRANSPORT);
923        if ("".equals(mCurrentTransport)) {
924            mCurrentTransport = null;
925        }
926        if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
927
928        // Find transport hosts and bind to their services
929        Intent transportServiceIntent = new Intent(SERVICE_ACTION_TRANSPORT_HOST);
930        List<ResolveInfo> hosts = mPackageManager.queryIntentServicesAsUser(
931                transportServiceIntent, 0, UserHandle.USER_OWNER);
932        if (DEBUG) {
933            Slog.v(TAG, "Found transports: " + ((hosts == null) ? "null" : hosts.size()));
934        }
935        if (hosts != null) {
936            if (MORE_DEBUG) {
937                for (int i = 0; i < hosts.size(); i++) {
938                    ServiceInfo info = hosts.get(i).serviceInfo;
939                    Slog.v(TAG, "   " + info.packageName + "/" + info.name);
940                }
941            }
942            for (int i = 0; i < hosts.size(); i++) {
943                try {
944                    ServiceInfo info = hosts.get(i).serviceInfo;
945                    PackageInfo packInfo = mPackageManager.getPackageInfo(info.packageName, 0);
946                    if ((packInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
947                        ComponentName svcName = new ComponentName(info.packageName, info.name);
948                        if (DEBUG) {
949                            Slog.i(TAG, "Binding to transport host " + svcName);
950                        }
951                        Intent intent = new Intent(transportServiceIntent);
952                        intent.setComponent(svcName);
953                        TransportConnection connection = new TransportConnection();
954                        mTransportConnections.add(connection);
955                        context.bindServiceAsUser(intent,
956                                connection, Context.BIND_AUTO_CREATE,
957                                UserHandle.OWNER);
958                    } else {
959                        Slog.w(TAG, "Transport package not privileged: " + info.packageName);
960                    }
961                } catch (Exception e) {
962                    Slog.e(TAG, "Problem resolving transport service: " + e.getMessage());
963                }
964            }
965        }
966
967        // Now that we know about valid backup participants, parse any
968        // leftover journal files into the pending backup set
969        parseLeftoverJournals();
970
971        // Power management
972        mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
973
974        // Start the backup passes going
975        setBackupEnabled(areEnabled);
976    }
977
978    private class RunBackupReceiver extends BroadcastReceiver {
979        public void onReceive(Context context, Intent intent) {
980            if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
981                synchronized (mQueueLock) {
982                    if (mPendingInits.size() > 0) {
983                        // If there are pending init operations, we process those
984                        // and then settle into the usual periodic backup schedule.
985                        if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
986                        try {
987                            mAlarmManager.cancel(mRunInitIntent);
988                            mRunInitIntent.send();
989                        } catch (PendingIntent.CanceledException ce) {
990                            Slog.e(TAG, "Run init intent cancelled");
991                            // can't really do more than bail here
992                        }
993                    } else {
994                        // Don't run backups now if we're disabled or not yet
995                        // fully set up.
996                        if (mEnabled && mProvisioned) {
997                            if (!mBackupRunning) {
998                                if (DEBUG) Slog.v(TAG, "Running a backup pass");
999
1000                                // Acquire the wakelock and pass it to the backup thread.  it will
1001                                // be released once backup concludes.
1002                                mBackupRunning = true;
1003                                mWakelock.acquire();
1004
1005                                Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
1006                                mBackupHandler.sendMessage(msg);
1007                            } else {
1008                                Slog.i(TAG, "Backup time but one already running");
1009                            }
1010                        } else {
1011                            Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
1012                        }
1013                    }
1014                }
1015            }
1016        }
1017    }
1018
1019    private class RunInitializeReceiver extends BroadcastReceiver {
1020        public void onReceive(Context context, Intent intent) {
1021            if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
1022                synchronized (mQueueLock) {
1023                    if (DEBUG) Slog.v(TAG, "Running a device init");
1024
1025                    // Acquire the wakelock and pass it to the init thread.  it will
1026                    // be released once init concludes.
1027                    mWakelock.acquire();
1028
1029                    Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
1030                    mBackupHandler.sendMessage(msg);
1031                }
1032            }
1033        }
1034    }
1035
1036    private void initPackageTracking() {
1037        if (DEBUG) Slog.v(TAG, "Initializing package tracking");
1038
1039        // Remember our ancestral dataset
1040        mTokenFile = new File(mBaseStateDir, "ancestral");
1041        try {
1042            RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
1043            int version = tf.readInt();
1044            if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
1045                mAncestralToken = tf.readLong();
1046                mCurrentToken = tf.readLong();
1047
1048                int numPackages = tf.readInt();
1049                if (numPackages >= 0) {
1050                    mAncestralPackages = new HashSet<String>();
1051                    for (int i = 0; i < numPackages; i++) {
1052                        String pkgName = tf.readUTF();
1053                        mAncestralPackages.add(pkgName);
1054                    }
1055                }
1056            }
1057            tf.close();
1058        } catch (FileNotFoundException fnf) {
1059            // Probably innocuous
1060            Slog.v(TAG, "No ancestral data");
1061        } catch (IOException e) {
1062            Slog.w(TAG, "Unable to read token file", e);
1063        }
1064
1065        // Keep a log of what apps we've ever backed up.  Because we might have
1066        // rebooted in the middle of an operation that was removing something from
1067        // this log, we sanity-check its contents here and reconstruct it.
1068        mEverStored = new File(mBaseStateDir, "processed");
1069        File tempProcessedFile = new File(mBaseStateDir, "processed.new");
1070
1071        // If we were in the middle of removing something from the ever-backed-up
1072        // file, there might be a transient "processed.new" file still present.
1073        // Ignore it -- we'll validate "processed" against the current package set.
1074        if (tempProcessedFile.exists()) {
1075            tempProcessedFile.delete();
1076        }
1077
1078        // If there are previous contents, parse them out then start a new
1079        // file to continue the recordkeeping.
1080        if (mEverStored.exists()) {
1081            RandomAccessFile temp = null;
1082            RandomAccessFile in = null;
1083
1084            try {
1085                temp = new RandomAccessFile(tempProcessedFile, "rws");
1086                in = new RandomAccessFile(mEverStored, "r");
1087
1088                while (true) {
1089                    PackageInfo info;
1090                    String pkg = in.readUTF();
1091                    try {
1092                        info = mPackageManager.getPackageInfo(pkg, 0);
1093                        mEverStoredApps.add(pkg);
1094                        temp.writeUTF(pkg);
1095                        if (MORE_DEBUG) Slog.v(TAG, "   + " + pkg);
1096                    } catch (NameNotFoundException e) {
1097                        // nope, this package was uninstalled; don't include it
1098                        if (MORE_DEBUG) Slog.v(TAG, "   - " + pkg);
1099                    }
1100                }
1101            } catch (EOFException e) {
1102                // Once we've rewritten the backup history log, atomically replace the
1103                // old one with the new one then reopen the file for continuing use.
1104                if (!tempProcessedFile.renameTo(mEverStored)) {
1105                    Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
1106                }
1107            } catch (IOException e) {
1108                Slog.e(TAG, "Error in processed file", e);
1109            } finally {
1110                try { if (temp != null) temp.close(); } catch (IOException e) {}
1111                try { if (in != null) in.close(); } catch (IOException e) {}
1112            }
1113        }
1114
1115        // Register for broadcasts about package install, etc., so we can
1116        // update the provider list.
1117        IntentFilter filter = new IntentFilter();
1118        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1119        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1120        filter.addDataScheme("package");
1121        mContext.registerReceiver(mBroadcastReceiver, filter);
1122        // Register for events related to sdcard installation.
1123        IntentFilter sdFilter = new IntentFilter();
1124        sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1125        sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1126        mContext.registerReceiver(mBroadcastReceiver, sdFilter);
1127    }
1128
1129    private void parseLeftoverJournals() {
1130        for (File f : mJournalDir.listFiles()) {
1131            if (mJournal == null || f.compareTo(mJournal) != 0) {
1132                // This isn't the current journal, so it must be a leftover.  Read
1133                // out the package names mentioned there and schedule them for
1134                // backup.
1135                RandomAccessFile in = null;
1136                try {
1137                    Slog.i(TAG, "Found stale backup journal, scheduling");
1138                    in = new RandomAccessFile(f, "r");
1139                    while (true) {
1140                        String packageName = in.readUTF();
1141                        Slog.i(TAG, "  " + packageName);
1142                        dataChangedImpl(packageName);
1143                    }
1144                } catch (EOFException e) {
1145                    // no more data; we're done
1146                } catch (Exception e) {
1147                    Slog.e(TAG, "Can't read " + f, e);
1148                } finally {
1149                    // close/delete the file
1150                    try { if (in != null) in.close(); } catch (IOException e) {}
1151                    f.delete();
1152                }
1153            }
1154        }
1155    }
1156
1157    private SecretKey buildPasswordKey(String algorithm, String pw, byte[] salt, int rounds) {
1158        return buildCharArrayKey(algorithm, pw.toCharArray(), salt, rounds);
1159    }
1160
1161    private SecretKey buildCharArrayKey(String algorithm, char[] pwArray, byte[] salt, int rounds) {
1162        try {
1163            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
1164            KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1165            return keyFactory.generateSecret(ks);
1166        } catch (InvalidKeySpecException e) {
1167            Slog.e(TAG, "Invalid key spec for PBKDF2!");
1168        } catch (NoSuchAlgorithmException e) {
1169            Slog.e(TAG, "PBKDF2 unavailable!");
1170        }
1171        return null;
1172    }
1173
1174    private String buildPasswordHash(String algorithm, String pw, byte[] salt, int rounds) {
1175        SecretKey key = buildPasswordKey(algorithm, pw, salt, rounds);
1176        if (key != null) {
1177            return byteArrayToHex(key.getEncoded());
1178        }
1179        return null;
1180    }
1181
1182    private String byteArrayToHex(byte[] data) {
1183        StringBuilder buf = new StringBuilder(data.length * 2);
1184        for (int i = 0; i < data.length; i++) {
1185            buf.append(Byte.toHexString(data[i], true));
1186        }
1187        return buf.toString();
1188    }
1189
1190    private byte[] hexToByteArray(String digits) {
1191        final int bytes = digits.length() / 2;
1192        if (2*bytes != digits.length()) {
1193            throw new IllegalArgumentException("Hex string must have an even number of digits");
1194        }
1195
1196        byte[] result = new byte[bytes];
1197        for (int i = 0; i < digits.length(); i += 2) {
1198            result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1199        }
1200        return result;
1201    }
1202
1203    private byte[] makeKeyChecksum(String algorithm, byte[] pwBytes, byte[] salt, int rounds) {
1204        char[] mkAsChar = new char[pwBytes.length];
1205        for (int i = 0; i < pwBytes.length; i++) {
1206            mkAsChar[i] = (char) pwBytes[i];
1207        }
1208
1209        Key checksum = buildCharArrayKey(algorithm, mkAsChar, salt, rounds);
1210        return checksum.getEncoded();
1211    }
1212
1213    // Used for generating random salts or passwords
1214    private byte[] randomBytes(int bits) {
1215        byte[] array = new byte[bits / 8];
1216        mRng.nextBytes(array);
1217        return array;
1218    }
1219
1220    // Backup password management
1221    boolean passwordMatchesSaved(String algorithm, String candidatePw, int rounds) {
1222        // First, on an encrypted device we require matching the device pw
1223        final boolean isEncrypted;
1224        try {
1225            isEncrypted = (mMountService.getEncryptionState() !=
1226                    IMountService.ENCRYPTION_STATE_NONE);
1227            if (isEncrypted) {
1228                if (DEBUG) {
1229                    Slog.i(TAG, "Device encrypted; verifying against device data pw");
1230                }
1231                // 0 means the password validated
1232                // -2 means device not encrypted
1233                // Any other result is either password failure or an error condition,
1234                // so we refuse the match
1235                final int result = mMountService.verifyEncryptionPassword(candidatePw);
1236                if (result == 0) {
1237                    if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
1238                    return true;
1239                } else if (result != -2) {
1240                    if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
1241                    return false;
1242                } else {
1243                    // ...else the device is supposedly not encrypted.  HOWEVER, the
1244                    // query about the encryption state said that the device *is*
1245                    // encrypted, so ... we may have a problem.  Log it and refuse
1246                    // the backup.
1247                    Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
1248                    return false;
1249                }
1250            }
1251        } catch (Exception e) {
1252            // Something went wrong talking to the mount service.  This is very bad;
1253            // assume that we fail password validation.
1254            return false;
1255        }
1256
1257        if (mPasswordHash == null) {
1258            // no current password case -- require that 'currentPw' be null or empty
1259            if (candidatePw == null || "".equals(candidatePw)) {
1260                return true;
1261            } // else the non-empty candidate does not match the empty stored pw
1262        } else {
1263            // hash the stated current pw and compare to the stored one
1264            if (candidatePw != null && candidatePw.length() > 0) {
1265                String currentPwHash = buildPasswordHash(algorithm, candidatePw, mPasswordSalt, rounds);
1266                if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1267                    // candidate hash matches the stored hash -- the password matches
1268                    return true;
1269                }
1270            } // else the stored pw is nonempty but the candidate is empty; no match
1271        }
1272        return false;
1273    }
1274
1275    @Override
1276    public boolean setBackupPassword(String currentPw, String newPw) {
1277        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1278                "setBackupPassword");
1279
1280        // When processing v1 passwords we may need to try two different PBKDF2 checksum regimes
1281        final boolean pbkdf2Fallback = (mPasswordVersion < BACKUP_PW_FILE_VERSION);
1282
1283        // If the supplied pw doesn't hash to the the saved one, fail.  The password
1284        // might be caught in the legacy crypto mismatch; verify that too.
1285        if (!passwordMatchesSaved(PBKDF_CURRENT, currentPw, PBKDF2_HASH_ROUNDS)
1286                && !(pbkdf2Fallback && passwordMatchesSaved(PBKDF_FALLBACK,
1287                        currentPw, PBKDF2_HASH_ROUNDS))) {
1288            return false;
1289        }
1290
1291        // Snap up to current on the pw file version
1292        mPasswordVersion = BACKUP_PW_FILE_VERSION;
1293        FileOutputStream pwFout = null;
1294        DataOutputStream pwOut = null;
1295        try {
1296            pwFout = new FileOutputStream(mPasswordVersionFile);
1297            pwOut = new DataOutputStream(pwFout);
1298            pwOut.writeInt(mPasswordVersion);
1299        } catch (IOException e) {
1300            Slog.e(TAG, "Unable to write backup pw version; password not changed");
1301            return false;
1302        } finally {
1303            try {
1304                if (pwOut != null) pwOut.close();
1305                if (pwFout != null) pwFout.close();
1306            } catch (IOException e) {
1307                Slog.w(TAG, "Unable to close pw version record");
1308            }
1309        }
1310
1311        // Snap up to current on the pw file version
1312        mPasswordVersion = BACKUP_PW_FILE_VERSION;
1313        FileOutputStream pwFout = null;
1314        DataOutputStream pwOut = null;
1315        try {
1316            pwFout = new FileOutputStream(mPasswordVersionFile);
1317            pwOut = new DataOutputStream(pwFout);
1318            pwOut.writeInt(mPasswordVersion);
1319        } catch (IOException e) {
1320            Slog.e(TAG, "Unable to write backup pw version; password not changed");
1321            return false;
1322        } finally {
1323            try {
1324                if (pwOut != null) pwOut.close();
1325                if (pwFout != null) pwFout.close();
1326            } catch (IOException e) {
1327                Slog.w(TAG, "Unable to close pw version record");
1328            }
1329        }
1330
1331        // Clearing the password is okay
1332        if (newPw == null || newPw.isEmpty()) {
1333            if (mPasswordHashFile.exists()) {
1334                if (!mPasswordHashFile.delete()) {
1335                    // Unable to delete the old pw file, so fail
1336                    Slog.e(TAG, "Unable to clear backup password");
1337                    return false;
1338                }
1339            }
1340            mPasswordHash = null;
1341            mPasswordSalt = null;
1342            return true;
1343        }
1344
1345        try {
1346            // Okay, build the hash of the new backup password
1347            byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1348            String newPwHash = buildPasswordHash(PBKDF_CURRENT, newPw, salt, PBKDF2_HASH_ROUNDS);
1349
1350            OutputStream pwf = null, buffer = null;
1351            DataOutputStream out = null;
1352            try {
1353                pwf = new FileOutputStream(mPasswordHashFile);
1354                buffer = new BufferedOutputStream(pwf);
1355                out = new DataOutputStream(buffer);
1356                // integer length of the salt array, followed by the salt,
1357                // then the hex pw hash string
1358                out.writeInt(salt.length);
1359                out.write(salt);
1360                out.writeUTF(newPwHash);
1361                out.flush();
1362                mPasswordHash = newPwHash;
1363                mPasswordSalt = salt;
1364                return true;
1365            } finally {
1366                if (out != null) out.close();
1367                if (buffer != null) buffer.close();
1368                if (pwf != null) pwf.close();
1369            }
1370        } catch (IOException e) {
1371            Slog.e(TAG, "Unable to set backup password");
1372        }
1373        return false;
1374    }
1375
1376    @Override
1377    public boolean hasBackupPassword() {
1378        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1379                "hasBackupPassword");
1380
1381        try {
1382            return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
1383                || (mPasswordHash != null && mPasswordHash.length() > 0);
1384        } catch (Exception e) {
1385            // If we can't talk to the mount service we have a serious problem; fail
1386            // "secure" i.e. assuming that we require a password
1387            return true;
1388        }
1389    }
1390
1391    private boolean backupPasswordMatches(String currentPw) {
1392        if (hasBackupPassword()) {
1393            final boolean pbkdf2Fallback = (mPasswordVersion < BACKUP_PW_FILE_VERSION);
1394            if (!passwordMatchesSaved(PBKDF_CURRENT, currentPw, PBKDF2_HASH_ROUNDS)
1395                    && !(pbkdf2Fallback && passwordMatchesSaved(PBKDF_FALLBACK,
1396                            currentPw, PBKDF2_HASH_ROUNDS))) {
1397                if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
1398                return false;
1399            }
1400        }
1401        return true;
1402    }
1403
1404    // Maintain persistent state around whether need to do an initialize operation.
1405    // Must be called with the queue lock held.
1406    void recordInitPendingLocked(boolean isPending, String transportName) {
1407        if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
1408                + " on transport " + transportName);
1409        mBackupHandler.removeMessages(MSG_RETRY_INIT);
1410
1411        try {
1412            IBackupTransport transport = getTransport(transportName);
1413            if (transport != null) {
1414                String transportDirName = transport.transportDirName();
1415                File stateDir = new File(mBaseStateDir, transportDirName);
1416                File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1417
1418                if (isPending) {
1419                    // We need an init before we can proceed with sending backup data.
1420                    // Record that with an entry in our set of pending inits, as well as
1421                    // journaling it via creation of a sentinel file.
1422                    mPendingInits.add(transportName);
1423                    try {
1424                        (new FileOutputStream(initPendingFile)).close();
1425                    } catch (IOException ioe) {
1426                        // Something is badly wrong with our permissions; just try to move on
1427                    }
1428                } else {
1429                    // No more initialization needed; wipe the journal and reset our state.
1430                    initPendingFile.delete();
1431                    mPendingInits.remove(transportName);
1432                }
1433                return; // done; don't fall through to the error case
1434            }
1435        } catch (RemoteException e) {
1436            // transport threw when asked its name; fall through to the lookup-failed case
1437        }
1438
1439        // The named transport doesn't exist or threw.  This operation is
1440        // important, so we record the need for a an init and post a message
1441        // to retry the init later.
1442        if (isPending) {
1443            mPendingInits.add(transportName);
1444            mBackupHandler.sendMessageDelayed(
1445                    mBackupHandler.obtainMessage(MSG_RETRY_INIT,
1446                            (isPending ? 1 : 0),
1447                            0,
1448                            transportName),
1449                    TRANSPORT_RETRY_INTERVAL);
1450        }
1451    }
1452
1453    // Reset all of our bookkeeping, in response to having been told that
1454    // the backend data has been wiped [due to idle expiry, for example],
1455    // so we must re-upload all saved settings.
1456    void resetBackupState(File stateFileDir) {
1457        synchronized (mQueueLock) {
1458            // Wipe the "what we've ever backed up" tracking
1459            mEverStoredApps.clear();
1460            mEverStored.delete();
1461
1462            mCurrentToken = 0;
1463            writeRestoreTokens();
1464
1465            // Remove all the state files
1466            for (File sf : stateFileDir.listFiles()) {
1467                // ... but don't touch the needs-init sentinel
1468                if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1469                    sf.delete();
1470                }
1471            }
1472        }
1473
1474        // Enqueue a new backup of every participant
1475        synchronized (mBackupParticipants) {
1476            final int N = mBackupParticipants.size();
1477            for (int i=0; i<N; i++) {
1478                HashSet<String> participants = mBackupParticipants.valueAt(i);
1479                if (participants != null) {
1480                    for (String packageName : participants) {
1481                        dataChangedImpl(packageName);
1482                    }
1483                }
1484            }
1485        }
1486    }
1487
1488    // Add a transport to our set of available backends.  If 'transport' is null, this
1489    // is an unregistration, and the transport's entry is removed from our bookkeeping.
1490    private void registerTransport(String name, String component, IBackupTransport transport) {
1491        synchronized (mTransports) {
1492            if (DEBUG) Slog.v(TAG, "Registering transport "
1493                    + component + "::" + name + " = " + transport);
1494            if (transport != null) {
1495                mTransports.put(name, transport);
1496                mTransportNames.put(component, name);
1497            } else {
1498                mTransports.remove(mTransportNames.get(component));
1499                mTransportNames.remove(component);
1500                // Nothing further to do in the unregistration case
1501                return;
1502            }
1503        }
1504
1505        // If the init sentinel file exists, we need to be sure to perform the init
1506        // as soon as practical.  We also create the state directory at registration
1507        // time to ensure it's present from the outset.
1508        try {
1509            String transportName = transport.transportDirName();
1510            File stateDir = new File(mBaseStateDir, transportName);
1511            stateDir.mkdirs();
1512
1513            File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1514            if (initSentinel.exists()) {
1515                synchronized (mQueueLock) {
1516                    mPendingInits.add(transportName);
1517
1518                    // TODO: pick a better starting time than now + 1 minute
1519                    long delay = 1000 * 60; // one minute, in milliseconds
1520                    mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1521                            System.currentTimeMillis() + delay, mRunInitIntent);
1522                }
1523            }
1524        } catch (RemoteException e) {
1525            // the transport threw when asked its file naming prefs; declare it invalid
1526            Slog.e(TAG, "Unable to register transport as " + name);
1527            mTransportNames.remove(component);
1528            mTransports.remove(name);
1529        }
1530    }
1531
1532    // ----- Track installation/removal of packages -----
1533    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1534        public void onReceive(Context context, Intent intent) {
1535            if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
1536
1537            String action = intent.getAction();
1538            boolean replacing = false;
1539            boolean added = false;
1540            Bundle extras = intent.getExtras();
1541            String pkgList[] = null;
1542            if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
1543                    Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1544                Uri uri = intent.getData();
1545                if (uri == null) {
1546                    return;
1547                }
1548                String pkgName = uri.getSchemeSpecificPart();
1549                if (pkgName != null) {
1550                    pkgList = new String[] { pkgName };
1551                }
1552                added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1553                replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
1554            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
1555                added = true;
1556                pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1557            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1558                added = false;
1559                pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1560            }
1561
1562            if (pkgList == null || pkgList.length == 0) {
1563                return;
1564            }
1565
1566            final int uid = extras.getInt(Intent.EXTRA_UID);
1567            if (added) {
1568                synchronized (mBackupParticipants) {
1569                    if (replacing) {
1570                        // This is the package-replaced case; we just remove the entry
1571                        // under the old uid and fall through to re-add.
1572                        removePackageParticipantsLocked(pkgList, uid);
1573                    }
1574                    addPackageParticipantsLocked(pkgList);
1575                }
1576            } else {
1577                if (replacing) {
1578                    // The package is being updated.  We'll receive a PACKAGE_ADDED shortly.
1579                } else {
1580                    synchronized (mBackupParticipants) {
1581                        removePackageParticipantsLocked(pkgList, uid);
1582                    }
1583                }
1584            }
1585        }
1586    };
1587
1588    // ----- Track connection to transports service -----
1589    class TransportConnection implements ServiceConnection {
1590        @Override
1591        public void onServiceConnected(ComponentName component, IBinder service) {
1592            if (DEBUG) Slog.v(TAG, "Connected to transport " + component);
1593            try {
1594                IBackupTransport transport = IBackupTransport.Stub.asInterface(service);
1595                registerTransport(transport.name(), component.flattenToShortString(), transport);
1596            } catch (RemoteException e) {
1597                Slog.e(TAG, "Unable to register transport " + component);
1598            }
1599        }
1600
1601        @Override
1602        public void onServiceDisconnected(ComponentName component) {
1603            if (DEBUG) Slog.v(TAG, "Disconnected from transport " + component);
1604            registerTransport(null, component.flattenToShortString(), null);
1605        }
1606    };
1607
1608    // Add the backup agents in the given packages to our set of known backup participants.
1609    // If 'packageNames' is null, adds all backup agents in the whole system.
1610    void addPackageParticipantsLocked(String[] packageNames) {
1611        // Look for apps that define the android:backupAgent attribute
1612        List<PackageInfo> targetApps = allAgentPackages();
1613        if (packageNames != null) {
1614            if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1615            for (String packageName : packageNames) {
1616                addPackageParticipantsLockedInner(packageName, targetApps);
1617            }
1618        } else {
1619            if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1620            addPackageParticipantsLockedInner(null, targetApps);
1621        }
1622    }
1623
1624    private void addPackageParticipantsLockedInner(String packageName,
1625            List<PackageInfo> targetPkgs) {
1626        if (MORE_DEBUG) {
1627            Slog.v(TAG, "Examining " + packageName + " for backup agent");
1628        }
1629
1630        for (PackageInfo pkg : targetPkgs) {
1631            if (packageName == null || pkg.packageName.equals(packageName)) {
1632                int uid = pkg.applicationInfo.uid;
1633                HashSet<String> set = mBackupParticipants.get(uid);
1634                if (set == null) {
1635                    set = new HashSet<String>();
1636                    mBackupParticipants.put(uid, set);
1637                }
1638                set.add(pkg.packageName);
1639                if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
1640
1641                // Schedule a backup for it on general principles
1642                if (DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName);
1643                dataChangedImpl(pkg.packageName);
1644            }
1645        }
1646    }
1647
1648    // Remove the given packages' entries from our known active set.
1649    void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
1650        if (packageNames == null) {
1651            Slog.w(TAG, "removePackageParticipants with null list");
1652            return;
1653        }
1654
1655        if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
1656                + " #" + packageNames.length);
1657        for (String pkg : packageNames) {
1658            // Known previous UID, so we know which package set to check
1659            HashSet<String> set = mBackupParticipants.get(oldUid);
1660            if (set != null && set.contains(pkg)) {
1661                removePackageFromSetLocked(set, pkg);
1662                if (set.isEmpty()) {
1663                    if (MORE_DEBUG) Slog.v(TAG, "  last one of this uid; purging set");
1664                    mBackupParticipants.remove(oldUid);
1665                }
1666            }
1667        }
1668    }
1669
1670    private void removePackageFromSetLocked(final HashSet<String> set,
1671            final String packageName) {
1672        if (set.contains(packageName)) {
1673            // Found it.  Remove this one package from the bookkeeping, and
1674            // if it's the last participating app under this uid we drop the
1675            // (now-empty) set as well.
1676            // Note that we deliberately leave it 'known' in the "ever backed up"
1677            // bookkeeping so that its current-dataset data will be retrieved
1678            // if the app is subsequently reinstalled
1679            if (MORE_DEBUG) Slog.v(TAG, "  removing participant " + packageName);
1680            set.remove(packageName);
1681            mPendingBackups.remove(packageName);
1682        }
1683    }
1684
1685    // Returns the set of all applications that define an android:backupAgent attribute
1686    List<PackageInfo> allAgentPackages() {
1687        // !!! TODO: cache this and regenerate only when necessary
1688        int flags = PackageManager.GET_SIGNATURES;
1689        List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1690        int N = packages.size();
1691        for (int a = N-1; a >= 0; a--) {
1692            PackageInfo pkg = packages.get(a);
1693            try {
1694                ApplicationInfo app = pkg.applicationInfo;
1695                if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
1696                        || app.backupAgentName == null) {
1697                    packages.remove(a);
1698                }
1699                else {
1700                    // we will need the shared library path, so look that up and store it here
1701                    app = mPackageManager.getApplicationInfo(pkg.packageName,
1702                            PackageManager.GET_SHARED_LIBRARY_FILES);
1703                    pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1704                }
1705            } catch (NameNotFoundException e) {
1706                packages.remove(a);
1707            }
1708        }
1709        return packages;
1710    }
1711
1712    // Called from the backup task: record that the given app has been successfully
1713    // backed up at least once
1714    void logBackupComplete(String packageName) {
1715        if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1716
1717        synchronized (mEverStoredApps) {
1718            if (!mEverStoredApps.add(packageName)) return;
1719
1720            RandomAccessFile out = null;
1721            try {
1722                out = new RandomAccessFile(mEverStored, "rws");
1723                out.seek(out.length());
1724                out.writeUTF(packageName);
1725            } catch (IOException e) {
1726                Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
1727            } finally {
1728                try { if (out != null) out.close(); } catch (IOException e) {}
1729            }
1730        }
1731    }
1732
1733    // Remove our awareness of having ever backed up the given package
1734    void removeEverBackedUp(String packageName) {
1735        if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1736        if (MORE_DEBUG) Slog.v(TAG, "New set:");
1737
1738        synchronized (mEverStoredApps) {
1739            // Rewrite the file and rename to overwrite.  If we reboot in the middle,
1740            // we'll recognize on initialization time that the package no longer
1741            // exists and fix it up then.
1742            File tempKnownFile = new File(mBaseStateDir, "processed.new");
1743            RandomAccessFile known = null;
1744            try {
1745                known = new RandomAccessFile(tempKnownFile, "rws");
1746                mEverStoredApps.remove(packageName);
1747                for (String s : mEverStoredApps) {
1748                    known.writeUTF(s);
1749                    if (MORE_DEBUG) Slog.v(TAG, "    " + s);
1750                }
1751                known.close();
1752                known = null;
1753                if (!tempKnownFile.renameTo(mEverStored)) {
1754                    throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1755                }
1756            } catch (IOException e) {
1757                // Bad: we couldn't create the new copy.  For safety's sake we
1758                // abandon the whole process and remove all what's-backed-up
1759                // state entirely, meaning we'll force a backup pass for every
1760                // participant on the next boot or [re]install.
1761                Slog.w(TAG, "Error rewriting " + mEverStored, e);
1762                mEverStoredApps.clear();
1763                tempKnownFile.delete();
1764                mEverStored.delete();
1765            } finally {
1766                try { if (known != null) known.close(); } catch (IOException e) {}
1767            }
1768        }
1769    }
1770
1771    // Persistently record the current and ancestral backup tokens as well
1772    // as the set of packages with data [supposedly] available in the
1773    // ancestral dataset.
1774    void writeRestoreTokens() {
1775        try {
1776            RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
1777
1778            // First, the version number of this record, for futureproofing
1779            af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1780
1781            // Write the ancestral and current tokens
1782            af.writeLong(mAncestralToken);
1783            af.writeLong(mCurrentToken);
1784
1785            // Now write the set of ancestral packages
1786            if (mAncestralPackages == null) {
1787                af.writeInt(-1);
1788            } else {
1789                af.writeInt(mAncestralPackages.size());
1790                if (DEBUG) Slog.v(TAG, "Ancestral packages:  " + mAncestralPackages.size());
1791                for (String pkgName : mAncestralPackages) {
1792                    af.writeUTF(pkgName);
1793                    if (MORE_DEBUG) Slog.v(TAG, "   " + pkgName);
1794                }
1795            }
1796            af.close();
1797        } catch (IOException e) {
1798            Slog.w(TAG, "Unable to write token file:", e);
1799        }
1800    }
1801
1802    // Return the given transport
1803    private IBackupTransport getTransport(String transportName) {
1804        synchronized (mTransports) {
1805            IBackupTransport transport = mTransports.get(transportName);
1806            if (transport == null) {
1807                Slog.w(TAG, "Requested unavailable transport: " + transportName);
1808            }
1809            return transport;
1810        }
1811    }
1812
1813    // fire off a backup agent, blocking until it attaches or times out
1814    IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1815        IBackupAgent agent = null;
1816        synchronized(mAgentConnectLock) {
1817            mConnecting = true;
1818            mConnectedAgent = null;
1819            try {
1820                if (mActivityManager.bindBackupAgent(app, mode)) {
1821                    Slog.d(TAG, "awaiting agent for " + app);
1822
1823                    // success; wait for the agent to arrive
1824                    // only wait 10 seconds for the bind to happen
1825                    long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1826                    while (mConnecting && mConnectedAgent == null
1827                            && (System.currentTimeMillis() < timeoutMark)) {
1828                        try {
1829                            mAgentConnectLock.wait(5000);
1830                        } catch (InterruptedException e) {
1831                            // just bail
1832                            if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
1833                            mActivityManager.clearPendingBackup();
1834                            return null;
1835                        }
1836                    }
1837
1838                    // if we timed out with no connect, abort and move on
1839                    if (mConnecting == true) {
1840                        Slog.w(TAG, "Timeout waiting for agent " + app);
1841                        mActivityManager.clearPendingBackup();
1842                        return null;
1843                    }
1844                    if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
1845                    agent = mConnectedAgent;
1846                }
1847            } catch (RemoteException e) {
1848                // can't happen - ActivityManager is local
1849            }
1850        }
1851        return agent;
1852    }
1853
1854    // clear an application's data, blocking until the operation completes or times out
1855    void clearApplicationDataSynchronous(String packageName) {
1856        // Don't wipe packages marked allowClearUserData=false
1857        try {
1858            PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1859            if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
1860                if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
1861                        + packageName);
1862                return;
1863            }
1864        } catch (NameNotFoundException e) {
1865            Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
1866            return;
1867        }
1868
1869        ClearDataObserver observer = new ClearDataObserver();
1870
1871        synchronized(mClearDataLock) {
1872            mClearingData = true;
1873            try {
1874                mActivityManager.clearApplicationUserData(packageName, observer, 0);
1875            } catch (RemoteException e) {
1876                // can't happen because the activity manager is in this process
1877            }
1878
1879            // only wait 10 seconds for the clear data to happen
1880            long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1881            while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1882                try {
1883                    mClearDataLock.wait(5000);
1884                } catch (InterruptedException e) {
1885                    // won't happen, but still.
1886                    mClearingData = false;
1887                }
1888            }
1889        }
1890    }
1891
1892    class ClearDataObserver extends IPackageDataObserver.Stub {
1893        public void onRemoveCompleted(String packageName, boolean succeeded) {
1894            synchronized(mClearDataLock) {
1895                mClearingData = false;
1896                mClearDataLock.notifyAll();
1897            }
1898        }
1899    }
1900
1901    // Get the restore-set token for the best-available restore set for this package:
1902    // the active set if possible, else the ancestral one.  Returns zero if none available.
1903    long getAvailableRestoreToken(String packageName) {
1904        long token = mAncestralToken;
1905        synchronized (mQueueLock) {
1906            if (mEverStoredApps.contains(packageName)) {
1907                token = mCurrentToken;
1908            }
1909        }
1910        return token;
1911    }
1912
1913    // -----
1914    // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1915
1916    interface BackupRestoreTask {
1917        // Execute one tick of whatever state machine the task implements
1918        void execute();
1919
1920        // An operation that wanted a callback has completed
1921        void operationComplete();
1922
1923        // An operation that wanted a callback has timed out
1924        void handleTimeout();
1925    }
1926
1927    void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1928        if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1929                + " interval=" + interval);
1930        synchronized (mCurrentOpLock) {
1931            mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1932
1933            Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1934            mBackupHandler.sendMessageDelayed(msg, interval);
1935        }
1936    }
1937
1938    // synchronous waiter case
1939    boolean waitUntilOperationComplete(int token) {
1940        if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1941                + Integer.toHexString(token));
1942        int finalState = OP_PENDING;
1943        Operation op = null;
1944        synchronized (mCurrentOpLock) {
1945            while (true) {
1946                op = mCurrentOperations.get(token);
1947                if (op == null) {
1948                    // mysterious disappearance: treat as success with no callback
1949                    break;
1950                } else {
1951                    if (op.state == OP_PENDING) {
1952                        try {
1953                            mCurrentOpLock.wait();
1954                        } catch (InterruptedException e) {}
1955                        // When the wait is notified we loop around and recheck the current state
1956                    } else {
1957                        // No longer pending; we're done
1958                        finalState = op.state;
1959                        break;
1960                    }
1961                }
1962            }
1963        }
1964
1965        mBackupHandler.removeMessages(MSG_TIMEOUT);
1966        if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
1967                + " complete: finalState=" + finalState);
1968        return finalState == OP_ACKNOWLEDGED;
1969    }
1970
1971    void handleTimeout(int token, Object obj) {
1972        // Notify any synchronous waiters
1973        Operation op = null;
1974        synchronized (mCurrentOpLock) {
1975            op = mCurrentOperations.get(token);
1976            if (MORE_DEBUG) {
1977                if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1978                        + " but no op found");
1979            }
1980            int state = (op != null) ? op.state : OP_TIMEOUT;
1981            if (state == OP_PENDING) {
1982                if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1983                op.state = OP_TIMEOUT;
1984                mCurrentOperations.put(token, op);
1985            }
1986            mCurrentOpLock.notifyAll();
1987        }
1988
1989        // If there's a TimeoutHandler for this event, call it
1990        if (op != null && op.callback != null) {
1991            op.callback.handleTimeout();
1992        }
1993    }
1994
1995    // ----- Back up a set of applications via a worker thread -----
1996
1997    enum BackupState {
1998        INITIAL,
1999        RUNNING_QUEUE,
2000        FINAL
2001    }
2002
2003    class PerformBackupTask implements BackupRestoreTask {
2004        private static final String TAG = "PerformBackupTask";
2005
2006        IBackupTransport mTransport;
2007        ArrayList<BackupRequest> mQueue;
2008        ArrayList<BackupRequest> mOriginalQueue;
2009        File mStateDir;
2010        File mJournal;
2011        BackupState mCurrentState;
2012
2013        // carried information about the current in-flight operation
2014        PackageInfo mCurrentPackage;
2015        File mSavedStateName;
2016        File mBackupDataName;
2017        File mNewStateName;
2018        ParcelFileDescriptor mSavedState;
2019        ParcelFileDescriptor mBackupData;
2020        ParcelFileDescriptor mNewState;
2021        int mStatus;
2022        boolean mFinished;
2023
2024        public PerformBackupTask(IBackupTransport transport, String dirName,
2025                ArrayList<BackupRequest> queue, File journal) {
2026            mTransport = transport;
2027            mOriginalQueue = queue;
2028            mJournal = journal;
2029
2030            mStateDir = new File(mBaseStateDir, dirName);
2031
2032            mCurrentState = BackupState.INITIAL;
2033            mFinished = false;
2034
2035            addBackupTrace("STATE => INITIAL");
2036        }
2037
2038        // Main entry point: perform one chunk of work, updating the state as appropriate
2039        // and reposting the next chunk to the primary backup handler thread.
2040        @Override
2041        public void execute() {
2042            switch (mCurrentState) {
2043                case INITIAL:
2044                    beginBackup();
2045                    break;
2046
2047                case RUNNING_QUEUE:
2048                    invokeNextAgent();
2049                    break;
2050
2051                case FINAL:
2052                    if (!mFinished) finalizeBackup();
2053                    else {
2054                        Slog.e(TAG, "Duplicate finish");
2055                    }
2056                    mFinished = true;
2057                    break;
2058            }
2059        }
2060
2061        // We're starting a backup pass.  Initialize the transport and send
2062        // the PM metadata blob if we haven't already.
2063        void beginBackup() {
2064            if (DEBUG_BACKUP_TRACE) {
2065                clearBackupTrace();
2066                StringBuilder b = new StringBuilder(256);
2067                b.append("beginBackup: [");
2068                for (BackupRequest req : mOriginalQueue) {
2069                    b.append(' ');
2070                    b.append(req.packageName);
2071                }
2072                b.append(" ]");
2073                addBackupTrace(b.toString());
2074            }
2075
2076            mStatus = BackupConstants.TRANSPORT_OK;
2077
2078            // Sanity check: if the queue is empty we have no work to do.
2079            if (mOriginalQueue.isEmpty()) {
2080                Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
2081                addBackupTrace("queue empty at begin");
2082                executeNextState(BackupState.FINAL);
2083                return;
2084            }
2085
2086            // We need to retain the original queue contents in case of transport
2087            // failure, but we want a working copy that we can manipulate along
2088            // the way.
2089            mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
2090
2091            if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
2092
2093            File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2094            try {
2095                final String transportName = mTransport.transportDirName();
2096                EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
2097
2098                // If we haven't stored package manager metadata yet, we must init the transport.
2099                if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
2100                    Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
2101                    addBackupTrace("initializing transport " + transportName);
2102                    resetBackupState(mStateDir);  // Just to make sure.
2103                    mStatus = mTransport.initializeDevice();
2104
2105                    addBackupTrace("transport.initializeDevice() == " + mStatus);
2106                    if (mStatus == BackupConstants.TRANSPORT_OK) {
2107                        EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
2108                    } else {
2109                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
2110                        Slog.e(TAG, "Transport error in initializeDevice()");
2111                    }
2112                }
2113
2114                // The package manager doesn't have a proper <application> etc, but since
2115                // it's running here in the system process we can just set up its agent
2116                // directly and use a synthetic BackupRequest.  We always run this pass
2117                // because it's cheap and this way we guarantee that we don't get out of
2118                // step even if we're selecting among various transports at run time.
2119                if (mStatus == BackupConstants.TRANSPORT_OK) {
2120                    PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
2121                            mPackageManager, allAgentPackages());
2122                    mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
2123                            IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
2124                    addBackupTrace("PMBA invoke: " + mStatus);
2125                }
2126
2127                if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
2128                    // The backend reports that our dataset has been wiped.  Note this in
2129                    // the event log; the no-success code below will reset the backup
2130                    // state as well.
2131                    EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
2132                }
2133            } catch (Exception e) {
2134                Slog.e(TAG, "Error in backup thread", e);
2135                addBackupTrace("Exception in backup thread: " + e);
2136                mStatus = BackupConstants.TRANSPORT_ERROR;
2137            } finally {
2138                // If we've succeeded so far, invokeAgentForBackup() will have run the PM
2139                // metadata and its completion/timeout callback will continue the state
2140                // machine chain.  If it failed that won't happen; we handle that now.
2141                addBackupTrace("exiting prelim: " + mStatus);
2142                if (mStatus != BackupConstants.TRANSPORT_OK) {
2143                    // if things went wrong at this point, we need to
2144                    // restage everything and try again later.
2145                    resetBackupState(mStateDir);  // Just to make sure.
2146                    executeNextState(BackupState.FINAL);
2147                }
2148            }
2149        }
2150
2151        // Transport has been initialized and the PM metadata submitted successfully
2152        // if that was warranted.  Now we process the single next thing in the queue.
2153        void invokeNextAgent() {
2154            mStatus = BackupConstants.TRANSPORT_OK;
2155            addBackupTrace("invoke q=" + mQueue.size());
2156
2157            // Sanity check that we have work to do.  If not, skip to the end where
2158            // we reestablish the wakelock invariants etc.
2159            if (mQueue.isEmpty()) {
2160                if (DEBUG) Slog.i(TAG, "queue now empty");
2161                executeNextState(BackupState.FINAL);
2162                return;
2163            }
2164
2165            // pop the entry we're going to process on this step
2166            BackupRequest request = mQueue.get(0);
2167            mQueue.remove(0);
2168
2169            Slog.d(TAG, "starting agent for backup of " + request);
2170            addBackupTrace("launch agent for " + request.packageName);
2171
2172            // Verify that the requested app exists; it might be something that
2173            // requested a backup but was then uninstalled.  The request was
2174            // journalled and rather than tamper with the journal it's safer
2175            // to sanity-check here.  This also gives us the classname of the
2176            // package's backup agent.
2177            try {
2178                mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
2179                        PackageManager.GET_SIGNATURES);
2180                if (mCurrentPackage.applicationInfo.backupAgentName == null) {
2181                    // The manifest has changed but we had a stale backup request pending.
2182                    // This won't happen again because the app won't be requesting further
2183                    // backups.
2184                    Slog.i(TAG, "Package " + request.packageName
2185                            + " no longer supports backup; skipping");
2186                    addBackupTrace("skipping - no agent, completion is noop");
2187                    executeNextState(BackupState.RUNNING_QUEUE);
2188                    return;
2189                }
2190
2191                if ((mCurrentPackage.applicationInfo.flags & ApplicationInfo.FLAG_STOPPED) != 0) {
2192                    // The app has been force-stopped or cleared or just installed,
2193                    // and not yet launched out of that state, so just as it won't
2194                    // receive broadcasts, we won't run it for backup.
2195                    addBackupTrace("skipping - stopped");
2196                    executeNextState(BackupState.RUNNING_QUEUE);
2197                    return;
2198                }
2199
2200                IBackupAgent agent = null;
2201                try {
2202                    mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
2203                    agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
2204                            IApplicationThread.BACKUP_MODE_INCREMENTAL);
2205                    addBackupTrace("agent bound; a? = " + (agent != null));
2206                    if (agent != null) {
2207                        mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
2208                        // at this point we'll either get a completion callback from the
2209                        // agent, or a timeout message on the main handler.  either way, we're
2210                        // done here as long as we're successful so far.
2211                    } else {
2212                        // Timeout waiting for the agent
2213                        mStatus = BackupConstants.AGENT_ERROR;
2214                    }
2215                } catch (SecurityException ex) {
2216                    // Try for the next one.
2217                    Slog.d(TAG, "error in bind/backup", ex);
2218                    mStatus = BackupConstants.AGENT_ERROR;
2219                            addBackupTrace("agent SE");
2220                }
2221            } catch (NameNotFoundException e) {
2222                Slog.d(TAG, "Package does not exist; skipping");
2223                addBackupTrace("no such package");
2224                mStatus = BackupConstants.AGENT_UNKNOWN;
2225            } finally {
2226                mWakelock.setWorkSource(null);
2227
2228                // If there was an agent error, no timeout/completion handling will occur.
2229                // That means we need to direct to the next state ourselves.
2230                if (mStatus != BackupConstants.TRANSPORT_OK) {
2231                    BackupState nextState = BackupState.RUNNING_QUEUE;
2232
2233                    // An agent-level failure means we reenqueue this one agent for
2234                    // a later retry, but otherwise proceed normally.
2235                    if (mStatus == BackupConstants.AGENT_ERROR) {
2236                        if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2237                                + " - restaging");
2238                        dataChangedImpl(request.packageName);
2239                        mStatus = BackupConstants.TRANSPORT_OK;
2240                        if (mQueue.isEmpty()) nextState = BackupState.FINAL;
2241                    } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2242                        // Failed lookup of the app, so we couldn't bring up an agent, but
2243                        // we're otherwise fine.  Just drop it and go on to the next as usual.
2244                        mStatus = BackupConstants.TRANSPORT_OK;
2245                    } else {
2246                        // Transport-level failure means we reenqueue everything
2247                        revertAndEndBackup();
2248                        nextState = BackupState.FINAL;
2249                    }
2250
2251                    executeNextState(nextState);
2252                } else {
2253                    addBackupTrace("expecting completion/timeout callback");
2254                }
2255            }
2256        }
2257
2258        void finalizeBackup() {
2259            addBackupTrace("finishing");
2260
2261            // Either backup was successful, in which case we of course do not need
2262            // this pass's journal any more; or it failed, in which case we just
2263            // re-enqueued all of these packages in the current active journal.
2264            // Either way, we no longer need this pass's journal.
2265            if (mJournal != null && !mJournal.delete()) {
2266                Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2267            }
2268
2269            // If everything actually went through and this is the first time we've
2270            // done a backup, we can now record what the current backup dataset token
2271            // is.
2272            if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
2273                addBackupTrace("success; recording token");
2274                try {
2275                    mCurrentToken = mTransport.getCurrentRestoreSet();
2276                    writeRestoreTokens();
2277                } catch (RemoteException e) {
2278                    // nothing for it at this point, unfortunately, but this will be
2279                    // recorded the next time we fully succeed.
2280                    addBackupTrace("transport threw returning token");
2281                }
2282            }
2283
2284            // Set up the next backup pass - at this point we can set mBackupRunning
2285            // to false to allow another pass to fire, because we're done with the
2286            // state machine sequence and the wakelock is refcounted.
2287            synchronized (mQueueLock) {
2288                mBackupRunning = false;
2289                if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
2290                    // Make sure we back up everything and perform the one-time init
2291                    clearMetadata();
2292                    if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
2293                    addBackupTrace("init required; rerunning");
2294                    backupNow();
2295                }
2296            }
2297
2298            // Only once we're entirely finished do we release the wakelock
2299            clearBackupTrace();
2300            Slog.i(TAG, "Backup pass finished.");
2301            mWakelock.release();
2302        }
2303
2304        // Remove the PM metadata state. This will generate an init on the next pass.
2305        void clearMetadata() {
2306            final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2307            if (pmState.exists()) pmState.delete();
2308        }
2309
2310        // Invoke an agent's doBackup() and start a timeout message spinning on the main
2311        // handler in case it doesn't get back to us.
2312        int invokeAgentForBackup(String packageName, IBackupAgent agent,
2313                IBackupTransport transport) {
2314            if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2315            addBackupTrace("invoking " + packageName);
2316
2317            mSavedStateName = new File(mStateDir, packageName);
2318            mBackupDataName = new File(mDataDir, packageName + ".data");
2319            mNewStateName = new File(mStateDir, packageName + ".new");
2320            if (MORE_DEBUG) Slog.d(TAG, "data file: " + mBackupDataName);
2321
2322            mSavedState = null;
2323            mBackupData = null;
2324            mNewState = null;
2325
2326            final int token = generateToken();
2327            try {
2328                // Look up the package info & signatures.  This is first so that if it
2329                // throws an exception, there's no file setup yet that would need to
2330                // be unraveled.
2331                if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
2332                    // The metadata 'package' is synthetic; construct one and make
2333                    // sure our global state is pointed at it
2334                    mCurrentPackage = new PackageInfo();
2335                    mCurrentPackage.packageName = packageName;
2336                }
2337
2338                // In a full backup, we pass a null ParcelFileDescriptor as
2339                // the saved-state "file". This is by definition an incremental,
2340                // so we build a saved state file to pass.
2341                mSavedState = ParcelFileDescriptor.open(mSavedStateName,
2342                        ParcelFileDescriptor.MODE_READ_ONLY |
2343                        ParcelFileDescriptor.MODE_CREATE);  // Make an empty file if necessary
2344
2345                mBackupData = ParcelFileDescriptor.open(mBackupDataName,
2346                        ParcelFileDescriptor.MODE_READ_WRITE |
2347                        ParcelFileDescriptor.MODE_CREATE |
2348                        ParcelFileDescriptor.MODE_TRUNCATE);
2349
2350                if (!SELinux.restorecon(mBackupDataName)) {
2351                    Slog.e(TAG, "SELinux restorecon failed on " + mBackupDataName);
2352                }
2353
2354                mNewState = ParcelFileDescriptor.open(mNewStateName,
2355                        ParcelFileDescriptor.MODE_READ_WRITE |
2356                        ParcelFileDescriptor.MODE_CREATE |
2357                        ParcelFileDescriptor.MODE_TRUNCATE);
2358
2359                // Initiate the target's backup pass
2360                addBackupTrace("setting timeout");
2361                prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
2362                addBackupTrace("calling agent doBackup()");
2363                agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
2364            } catch (Exception e) {
2365                Slog.e(TAG, "Error invoking for backup on " + packageName);
2366                addBackupTrace("exception: " + e);
2367                EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2368                        e.toString());
2369                agentErrorCleanup();
2370                return BackupConstants.AGENT_ERROR;
2371            }
2372
2373            // At this point the agent is off and running.  The next thing to happen will
2374            // either be a callback from the agent, at which point we'll process its data
2375            // for transport, or a timeout.  Either way the next phase will happen in
2376            // response to the TimeoutHandler interface callbacks.
2377            addBackupTrace("invoke success");
2378            return BackupConstants.TRANSPORT_OK;
2379        }
2380
2381        @Override
2382        public void operationComplete() {
2383            // Okay, the agent successfully reported back to us.  Spin the data off to the
2384            // transport and proceed with the next stage.
2385            if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2386                    + mCurrentPackage.packageName);
2387            mBackupHandler.removeMessages(MSG_TIMEOUT);
2388            clearAgentState();
2389            addBackupTrace("operation complete");
2390
2391            ParcelFileDescriptor backupData = null;
2392            mStatus = BackupConstants.TRANSPORT_OK;
2393            try {
2394                int size = (int) mBackupDataName.length();
2395                if (size > 0) {
2396                    if (mStatus == BackupConstants.TRANSPORT_OK) {
2397                        backupData = ParcelFileDescriptor.open(mBackupDataName,
2398                                ParcelFileDescriptor.MODE_READ_ONLY);
2399                        addBackupTrace("sending data to transport");
2400                        mStatus = mTransport.performBackup(mCurrentPackage, backupData);
2401                    }
2402
2403                    // TODO - We call finishBackup() for each application backed up, because
2404                    // we need to know now whether it succeeded or failed.  Instead, we should
2405                    // hold off on finishBackup() until the end, which implies holding off on
2406                    // renaming *all* the output state files (see below) until that happens.
2407
2408                    addBackupTrace("data delivered: " + mStatus);
2409                    if (mStatus == BackupConstants.TRANSPORT_OK) {
2410                        addBackupTrace("finishing op on transport");
2411                        mStatus = mTransport.finishBackup();
2412                        addBackupTrace("finished: " + mStatus);
2413                    }
2414                } else {
2415                    if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
2416                    addBackupTrace("no data to send");
2417                }
2418
2419                // After successful transport, delete the now-stale data
2420                // and juggle the files so that next time we supply the agent
2421                // with the new state file it just created.
2422                if (mStatus == BackupConstants.TRANSPORT_OK) {
2423                    mBackupDataName.delete();
2424                    mNewStateName.renameTo(mSavedStateName);
2425                    EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2426                            mCurrentPackage.packageName, size);
2427                    logBackupComplete(mCurrentPackage.packageName);
2428                } else {
2429                    EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2430                            mCurrentPackage.packageName);
2431                }
2432            } catch (Exception e) {
2433                Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2434                EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2435                        mCurrentPackage.packageName);
2436                mStatus = BackupConstants.TRANSPORT_ERROR;
2437            } finally {
2438                try { if (backupData != null) backupData.close(); } catch (IOException e) {}
2439            }
2440
2441            // If we encountered an error here it's a transport-level failure.  That
2442            // means we need to halt everything and reschedule everything for next time.
2443            final BackupState nextState;
2444            if (mStatus != BackupConstants.TRANSPORT_OK) {
2445                revertAndEndBackup();
2446                nextState = BackupState.FINAL;
2447            } else {
2448                // Success!  Proceed with the next app if any, otherwise we're done.
2449                nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2450            }
2451
2452            executeNextState(nextState);
2453        }
2454
2455        @Override
2456        public void handleTimeout() {
2457            // Whoops, the current agent timed out running doBackup().  Tidy up and restage
2458            // it for the next time we run a backup pass.
2459            // !!! TODO: keep track of failure counts per agent, and blacklist those which
2460            // fail repeatedly (i.e. have proved themselves to be buggy).
2461            Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2462            EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2463                    "timeout");
2464            addBackupTrace("timeout of " + mCurrentPackage.packageName);
2465            agentErrorCleanup();
2466            dataChangedImpl(mCurrentPackage.packageName);
2467        }
2468
2469        void revertAndEndBackup() {
2470            if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
2471            addBackupTrace("transport error; reverting");
2472            for (BackupRequest request : mOriginalQueue) {
2473                dataChangedImpl(request.packageName);
2474            }
2475            // We also want to reset the backup schedule based on whatever
2476            // the transport suggests by way of retry/backoff time.
2477            restartBackupAlarm();
2478        }
2479
2480        void agentErrorCleanup() {
2481            mBackupDataName.delete();
2482            mNewStateName.delete();
2483            clearAgentState();
2484
2485            executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2486        }
2487
2488        // Cleanup common to both success and failure cases
2489        void clearAgentState() {
2490            try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2491            try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2492            try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2493            mSavedState = mBackupData = mNewState = null;
2494            synchronized (mCurrentOpLock) {
2495                mCurrentOperations.clear();
2496            }
2497
2498            // If this was a pseudopackage there's no associated Activity Manager state
2499            if (mCurrentPackage.applicationInfo != null) {
2500                addBackupTrace("unbinding " + mCurrentPackage.packageName);
2501                try {  // unbind even on timeout, just in case
2502                    mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2503                } catch (RemoteException e) { /* can't happen; activity manager is local */ }
2504            }
2505        }
2506
2507        void restartBackupAlarm() {
2508            addBackupTrace("setting backup trigger");
2509            synchronized (mQueueLock) {
2510                try {
2511                    startBackupAlarmsLocked(mTransport.requestBackupTime());
2512                } catch (RemoteException e) { /* cannot happen */ }
2513            }
2514        }
2515
2516        void executeNextState(BackupState nextState) {
2517            if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2518                    + this + " nextState=" + nextState);
2519            addBackupTrace("executeNextState => " + nextState);
2520            mCurrentState = nextState;
2521            Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2522            mBackupHandler.sendMessage(msg);
2523        }
2524    }
2525
2526
2527    // ----- Full backup/restore to a file/socket -----
2528
2529    abstract class ObbServiceClient {
2530        public IObbBackupService mObbService;
2531        public void setObbBinder(IObbBackupService binder) {
2532            mObbService = binder;
2533        }
2534    }
2535
2536    class FullBackupObbConnection implements ServiceConnection {
2537        volatile IObbBackupService mService;
2538
2539        FullBackupObbConnection() {
2540            mService = null;
2541        }
2542
2543        public void establish() {
2544            if (DEBUG) Slog.i(TAG, "Initiating bind of OBB service on " + this);
2545            Intent obbIntent = new Intent().setComponent(new ComponentName(
2546                    "com.android.sharedstoragebackup",
2547                    "com.android.sharedstoragebackup.ObbBackupService"));
2548            BackupManagerService.this.mContext.bindService(
2549                    obbIntent, this, Context.BIND_AUTO_CREATE);
2550        }
2551
2552        public void tearDown() {
2553            BackupManagerService.this.mContext.unbindService(this);
2554        }
2555
2556        public boolean backupObbs(PackageInfo pkg, OutputStream out) {
2557            boolean success = false;
2558            waitForConnection();
2559
2560            ParcelFileDescriptor[] pipes = null;
2561            try {
2562                pipes = ParcelFileDescriptor.createPipe();
2563                int token = generateToken();
2564                prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
2565                mService.backupObbs(pkg.packageName, pipes[1], token, mBackupManagerBinder);
2566                routeSocketDataToOutput(pipes[0], out);
2567                success = waitUntilOperationComplete(token);
2568            } catch (Exception e) {
2569                Slog.w(TAG, "Unable to back up OBBs for " + pkg, e);
2570            } finally {
2571                try {
2572                    out.flush();
2573                    if (pipes != null) {
2574                        if (pipes[0] != null) pipes[0].close();
2575                        if (pipes[1] != null) pipes[1].close();
2576                    }
2577                } catch (IOException e) {
2578                    Slog.w(TAG, "I/O error closing down OBB backup", e);
2579                }
2580            }
2581            return success;
2582        }
2583
2584        public void restoreObbFile(String pkgName, ParcelFileDescriptor data,
2585                long fileSize, int type, String path, long mode, long mtime,
2586                int token, IBackupManager callbackBinder) {
2587            waitForConnection();
2588
2589            try {
2590                mService.restoreObbFile(pkgName, data, fileSize, type, path, mode, mtime,
2591                        token, callbackBinder);
2592            } catch (Exception e) {
2593                Slog.w(TAG, "Unable to restore OBBs for " + pkgName, e);
2594            }
2595        }
2596
2597        private void waitForConnection() {
2598            synchronized (this) {
2599                while (mService == null) {
2600                    if (DEBUG) Slog.i(TAG, "...waiting for OBB service binding...");
2601                    try {
2602                        this.wait();
2603                    } catch (InterruptedException e) { /* never interrupted */ }
2604                }
2605                if (DEBUG) Slog.i(TAG, "Connected to OBB service; continuing");
2606            }
2607        }
2608
2609        @Override
2610        public void onServiceConnected(ComponentName name, IBinder service) {
2611            synchronized (this) {
2612                mService = IObbBackupService.Stub.asInterface(service);
2613                if (DEBUG) Slog.i(TAG, "OBB service connection " + mService
2614                        + " connected on " + this);
2615                this.notifyAll();
2616            }
2617        }
2618
2619        @Override
2620        public void onServiceDisconnected(ComponentName name) {
2621            synchronized (this) {
2622                mService = null;
2623                if (DEBUG) Slog.i(TAG, "OBB service connection disconnected on " + this);
2624                this.notifyAll();
2625            }
2626        }
2627
2628    }
2629
2630    private void routeSocketDataToOutput(ParcelFileDescriptor inPipe, OutputStream out)
2631            throws IOException {
2632        FileInputStream raw = new FileInputStream(inPipe.getFileDescriptor());
2633        DataInputStream in = new DataInputStream(raw);
2634
2635        byte[] buffer = new byte[32 * 1024];
2636        int chunkTotal;
2637        while ((chunkTotal = in.readInt()) > 0) {
2638            while (chunkTotal > 0) {
2639                int toRead = (chunkTotal > buffer.length) ? buffer.length : chunkTotal;
2640                int nRead = in.read(buffer, 0, toRead);
2641                out.write(buffer, 0, nRead);
2642                chunkTotal -= nRead;
2643            }
2644        }
2645    }
2646
2647    class PerformFullBackupTask extends ObbServiceClient implements Runnable {
2648        ParcelFileDescriptor mOutputFile;
2649        DeflaterOutputStream mDeflater;
2650        IFullBackupRestoreObserver mObserver;
2651        boolean mIncludeApks;
2652        boolean mIncludeObbs;
2653        boolean mIncludeShared;
2654        boolean mAllApps;
2655        final boolean mIncludeSystem;
2656        String[] mPackages;
2657        String mCurrentPassword;
2658        String mEncryptPassword;
2659        AtomicBoolean mLatchObject;
2660        File mFilesDir;
2661        File mManifestFile;
2662
2663
2664        class FullBackupRunner implements Runnable {
2665            PackageInfo mPackage;
2666            IBackupAgent mAgent;
2667            ParcelFileDescriptor mPipe;
2668            int mToken;
2669            boolean mSendApk;
2670            boolean mWriteManifest;
2671
2672            FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
2673                    int token, boolean sendApk, boolean writeManifest)  throws IOException {
2674                mPackage = pack;
2675                mAgent = agent;
2676                mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2677                mToken = token;
2678                mSendApk = sendApk;
2679                mWriteManifest = writeManifest;
2680            }
2681
2682            @Override
2683            public void run() {
2684                try {
2685                    BackupDataOutput output = new BackupDataOutput(
2686                            mPipe.getFileDescriptor());
2687
2688                    if (mWriteManifest) {
2689                        if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
2690                        writeAppManifest(mPackage, mManifestFile, mSendApk);
2691                        FullBackup.backupToTar(mPackage.packageName, null, null,
2692                                mFilesDir.getAbsolutePath(),
2693                                mManifestFile.getAbsolutePath(),
2694                                output);
2695                    }
2696
2697                    if (mSendApk) {
2698                        writeApkToBackup(mPackage, output);
2699                    }
2700
2701                    if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
2702                    prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
2703                    mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2704                } catch (IOException e) {
2705                    Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2706                } catch (RemoteException e) {
2707                    Slog.e(TAG, "Remote agent vanished during full backup of "
2708                            + mPackage.packageName);
2709                } finally {
2710                    try {
2711                        mPipe.close();
2712                    } catch (IOException e) {}
2713                }
2714            }
2715        }
2716
2717        PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
2718                boolean includeApks, boolean includeObbs, boolean includeShared,
2719                String curPassword, String encryptPassword, boolean doAllApps,
2720                boolean doSystem, String[] packages, AtomicBoolean latch) {
2721            mOutputFile = fd;
2722            mObserver = observer;
2723            mIncludeApks = includeApks;
2724            mIncludeObbs = includeObbs;
2725            mIncludeShared = includeShared;
2726            mAllApps = doAllApps;
2727            mIncludeSystem = doSystem;
2728            mPackages = packages;
2729            mCurrentPassword = curPassword;
2730            // when backing up, if there is a current backup password, we require that
2731            // the user use a nonempty encryption password as well.  if one is supplied
2732            // in the UI we use that, but if the UI was left empty we fall back to the
2733            // current backup password (which was supplied by the user as well).
2734            if (encryptPassword == null || "".equals(encryptPassword)) {
2735                mEncryptPassword = curPassword;
2736            } else {
2737                mEncryptPassword = encryptPassword;
2738            }
2739            mLatchObject = latch;
2740
2741            mFilesDir = new File("/data/system");
2742            mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2743        }
2744
2745        @Override
2746        public void run() {
2747            Slog.i(TAG, "--- Performing full-dataset backup ---");
2748
2749            List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
2750            FullBackupObbConnection obbConnection = new FullBackupObbConnection();
2751            obbConnection.establish();  // we'll want this later
2752
2753            sendStartBackup();
2754
2755            // doAllApps supersedes the package set if any
2756            if (mAllApps) {
2757                packagesToBackup = mPackageManager.getInstalledPackages(
2758                        PackageManager.GET_SIGNATURES);
2759                // Exclude system apps if we've been asked to do so
2760                if (mIncludeSystem == false) {
2761                    for (int i = 0; i < packagesToBackup.size(); ) {
2762                        PackageInfo pkg = packagesToBackup.get(i);
2763                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2764                            packagesToBackup.remove(i);
2765                        } else {
2766                            i++;
2767                        }
2768                    }
2769                }
2770            }
2771
2772            // Now process the command line argument packages, if any. Note that explicitly-
2773            // named system-partition packages will be included even if includeSystem was
2774            // set to false.
2775            if (mPackages != null) {
2776                for (String pkgName : mPackages) {
2777                    try {
2778                        packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2779                                PackageManager.GET_SIGNATURES));
2780                    } catch (NameNotFoundException e) {
2781                        Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2782                    }
2783                }
2784            }
2785
2786            // Cull any packages that have indicated that backups are not permitted, as well
2787            // as any explicit mention of the 'special' shared-storage agent package (we
2788            // handle that one at the end).
2789            for (int i = 0; i < packagesToBackup.size(); ) {
2790                PackageInfo pkg = packagesToBackup.get(i);
2791                if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
2792                        || pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
2793                    packagesToBackup.remove(i);
2794                } else {
2795                    i++;
2796                }
2797            }
2798
2799            // Cull any packages that run as system-domain uids but do not define their
2800            // own backup agents
2801            for (int i = 0; i < packagesToBackup.size(); ) {
2802                PackageInfo pkg = packagesToBackup.get(i);
2803                if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
2804                        && (pkg.applicationInfo.backupAgentName == null)) {
2805                    if (MORE_DEBUG) {
2806                        Slog.i(TAG, "... ignoring non-agent system package " + pkg.packageName);
2807                    }
2808                    packagesToBackup.remove(i);
2809                } else {
2810                    i++;
2811                }
2812            }
2813
2814            FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
2815            OutputStream out = null;
2816
2817            PackageInfo pkg = null;
2818            try {
2819                boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
2820                boolean compressing = COMPRESS_FULL_BACKUPS;
2821                OutputStream finalOutput = ofstream;
2822
2823                // Verify that the given password matches the currently-active
2824                // backup password, if any
2825                if (!backupPasswordMatches(mCurrentPassword)) {
2826                    if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2827                    return;
2828                }
2829
2830                // Write the global file header.  All strings are UTF-8 encoded; lines end
2831                // with a '\n' byte.  Actual backup data begins immediately following the
2832                // final '\n'.
2833                //
2834                // line 1: "ANDROID BACKUP"
2835                // line 2: backup file format version, currently "2"
2836                // line 3: compressed?  "0" if not compressed, "1" if compressed.
2837                // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2838                //
2839                // When line 4 is not "none", then additional header data follows:
2840                //
2841                // line 5: user password salt [hex]
2842                // line 6: master key checksum salt [hex]
2843                // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2844                // line 8: IV of the user key [hex]
2845                // line 9: master key blob [hex]
2846                //     IV of the master key, master key itself, master key checksum hash
2847                //
2848                // The master key checksum is the master key plus its checksum salt, run through
2849                // 10k rounds of PBKDF2.  This is used to verify that the user has supplied the
2850                // correct password for decrypting the archive:  the master key decrypted from
2851                // the archive using the user-supplied password is also run through PBKDF2 in
2852                // this way, and if the result does not match the checksum as stored in the
2853                // archive, then we know that the user-supplied password does not match the
2854                // archive's.
2855                StringBuilder headerbuf = new StringBuilder(1024);
2856
2857                headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
2858                headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2859                headerbuf.append(compressing ? "\n1\n" : "\n0\n");
2860
2861                try {
2862                    // Set up the encryption stage if appropriate, and emit the correct header
2863                    if (encrypting) {
2864                        finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2865                    } else {
2866                        headerbuf.append("none\n");
2867                    }
2868
2869                    byte[] header = headerbuf.toString().getBytes("UTF-8");
2870                    ofstream.write(header);
2871
2872                    // Set up the compression stage feeding into the encryption stage (if any)
2873                    if (compressing) {
2874                        Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2875                        finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2876                    }
2877
2878                    out = finalOutput;
2879                } catch (Exception e) {
2880                    // Should never happen!
2881                    Slog.e(TAG, "Unable to emit archive header", e);
2882                    return;
2883                }
2884
2885                // Shared storage if requested
2886                if (mIncludeShared) {
2887                    try {
2888                        pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
2889                        packagesToBackup.add(pkg);
2890                    } catch (NameNotFoundException e) {
2891                        Slog.e(TAG, "Unable to find shared-storage backup handler");
2892                    }
2893                }
2894
2895                // Now back up the app data via the agent mechanism
2896                int N = packagesToBackup.size();
2897                for (int i = 0; i < N; i++) {
2898                    pkg = packagesToBackup.get(i);
2899                    backupOnePackage(pkg, out);
2900
2901                    // after the app's agent runs to handle its private filesystem
2902                    // contents, back up any OBB content it has on its behalf.
2903                    if (mIncludeObbs) {
2904                        boolean obbOkay = obbConnection.backupObbs(pkg, out);
2905                        if (!obbOkay) {
2906                            throw new RuntimeException("Failure writing OBB stack for " + pkg);
2907                        }
2908                    }
2909                }
2910
2911                // Done!
2912                finalizeBackup(out);
2913            } catch (RemoteException e) {
2914                Slog.e(TAG, "App died during full backup");
2915            } catch (Exception e) {
2916                Slog.e(TAG, "Internal exception during full backup", e);
2917            } finally {
2918                tearDown(pkg);
2919                try {
2920                    if (out != null) out.close();
2921                    mOutputFile.close();
2922                } catch (IOException e) {
2923                    /* nothing we can do about this */
2924                }
2925                synchronized (mCurrentOpLock) {
2926                    mCurrentOperations.clear();
2927                }
2928                synchronized (mLatchObject) {
2929                    mLatchObject.set(true);
2930                    mLatchObject.notifyAll();
2931                }
2932                sendEndBackup();
2933                obbConnection.tearDown();
2934                if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
2935                mWakelock.release();
2936            }
2937        }
2938
2939        private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2940                OutputStream ofstream) throws Exception {
2941            // User key will be used to encrypt the master key.
2942            byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
2943            SecretKey userKey = buildPasswordKey(PBKDF_CURRENT, mEncryptPassword, newUserSalt,
2944                    PBKDF2_HASH_ROUNDS);
2945
2946            // the master key is random for each backup
2947            byte[] masterPw = new byte[256 / 8];
2948            mRng.nextBytes(masterPw);
2949            byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2950
2951            // primary encryption of the datastream with the random key
2952            Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2953            SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2954            c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2955            OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2956
2957            // line 4: name of encryption algorithm
2958            headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2959            headerbuf.append('\n');
2960            // line 5: user password salt [hex]
2961            headerbuf.append(byteArrayToHex(newUserSalt));
2962            headerbuf.append('\n');
2963            // line 6: master key checksum salt [hex]
2964            headerbuf.append(byteArrayToHex(checksumSalt));
2965            headerbuf.append('\n');
2966            // line 7: number of PBKDF2 rounds used [decimal]
2967            headerbuf.append(PBKDF2_HASH_ROUNDS);
2968            headerbuf.append('\n');
2969
2970            // line 8: IV of the user key [hex]
2971            Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2972            mkC.init(Cipher.ENCRYPT_MODE, userKey);
2973
2974            byte[] IV = mkC.getIV();
2975            headerbuf.append(byteArrayToHex(IV));
2976            headerbuf.append('\n');
2977
2978            // line 9: master IV + key blob, encrypted by the user key [hex].  Blob format:
2979            //    [byte] IV length = Niv
2980            //    [array of Niv bytes] IV itself
2981            //    [byte] master key length = Nmk
2982            //    [array of Nmk bytes] master key itself
2983            //    [byte] MK checksum hash length = Nck
2984            //    [array of Nck bytes] master key checksum hash
2985            //
2986            // The checksum is the (master key + checksum salt), run through the
2987            // stated number of PBKDF2 rounds
2988            IV = c.getIV();
2989            byte[] mk = masterKeySpec.getEncoded();
2990            byte[] checksum = makeKeyChecksum(PBKDF_CURRENT, masterKeySpec.getEncoded(),
2991                    checksumSalt, PBKDF2_HASH_ROUNDS);
2992
2993            ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2994                    + checksum.length + 3);
2995            DataOutputStream mkOut = new DataOutputStream(blob);
2996            mkOut.writeByte(IV.length);
2997            mkOut.write(IV);
2998            mkOut.writeByte(mk.length);
2999            mkOut.write(mk);
3000            mkOut.writeByte(checksum.length);
3001            mkOut.write(checksum);
3002            mkOut.flush();
3003            byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
3004            headerbuf.append(byteArrayToHex(encryptedMk));
3005            headerbuf.append('\n');
3006
3007            return finalOutput;
3008        }
3009
3010        private void backupOnePackage(PackageInfo pkg, OutputStream out)
3011                throws RemoteException {
3012            Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
3013
3014            IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
3015                    IApplicationThread.BACKUP_MODE_FULL);
3016            if (agent != null) {
3017                ParcelFileDescriptor[] pipes = null;
3018                try {
3019                    pipes = ParcelFileDescriptor.createPipe();
3020
3021                    ApplicationInfo app = pkg.applicationInfo;
3022                    final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
3023                    final boolean sendApk = mIncludeApks
3024                            && !isSharedStorage
3025                            && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
3026                            && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
3027                                (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
3028
3029                    sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
3030
3031                    final int token = generateToken();
3032                    FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
3033                            token, sendApk, !isSharedStorage);
3034                    pipes[1].close();   // the runner has dup'd it
3035                    pipes[1] = null;
3036                    Thread t = new Thread(runner);
3037                    t.start();
3038
3039                    // Now pull data from the app and stuff it into the compressor
3040                    try {
3041                        routeSocketDataToOutput(pipes[0], out);
3042                    } catch (IOException e) {
3043                        Slog.i(TAG, "Caught exception reading from agent", e);
3044                    }
3045
3046                    if (!waitUntilOperationComplete(token)) {
3047                        Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
3048                    } else {
3049                        if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
3050                    }
3051
3052                } catch (IOException e) {
3053                    Slog.e(TAG, "Error backing up " + pkg.packageName, e);
3054                } finally {
3055                    try {
3056                        // flush after every package
3057                        out.flush();
3058                        if (pipes != null) {
3059                            if (pipes[0] != null) pipes[0].close();
3060                            if (pipes[1] != null) pipes[1].close();
3061                        }
3062                    } catch (IOException e) {
3063                        Slog.w(TAG, "Error bringing down backup stack");
3064                    }
3065                }
3066            } else {
3067                Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
3068            }
3069            tearDown(pkg);
3070        }
3071
3072        private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
3073            // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
3074            final String appSourceDir = pkg.applicationInfo.sourceDir;
3075            final String apkDir = new File(appSourceDir).getParent();
3076            FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
3077                    apkDir, appSourceDir, output);
3078
3079            // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
3080            // doesn't have access to external storage.
3081
3082            // Save associated .obb content if it exists and we did save the apk
3083            // check for .obb and save those too
3084            final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER);
3085            final File obbDir = userEnv.buildExternalStorageAppObbDirs(pkg.packageName)[0];
3086            if (obbDir != null) {
3087                if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
3088                File[] obbFiles = obbDir.listFiles();
3089                if (obbFiles != null) {
3090                    final String obbDirName = obbDir.getAbsolutePath();
3091                    for (File obb : obbFiles) {
3092                        FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
3093                                obbDirName, obb.getAbsolutePath(), output);
3094                    }
3095                }
3096            }
3097        }
3098
3099        private void finalizeBackup(OutputStream out) {
3100            try {
3101                // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
3102                byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
3103                out.write(eof);
3104            } catch (IOException e) {
3105                Slog.w(TAG, "Error attempting to finalize backup stream");
3106            }
3107        }
3108
3109        private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
3110                throws IOException {
3111            // Manifest format. All data are strings ending in LF:
3112            //     BACKUP_MANIFEST_VERSION, currently 1
3113            //
3114            // Version 1:
3115            //     package name
3116            //     package's versionCode
3117            //     platform versionCode
3118            //     getInstallerPackageName() for this package (maybe empty)
3119            //     boolean: "1" if archive includes .apk; any other string means not
3120            //     number of signatures == N
3121            // N*:    signature byte array in ascii format per Signature.toCharsString()
3122            StringBuilder builder = new StringBuilder(4096);
3123            StringBuilderPrinter printer = new StringBuilderPrinter(builder);
3124
3125            printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
3126            printer.println(pkg.packageName);
3127            printer.println(Integer.toString(pkg.versionCode));
3128            printer.println(Integer.toString(Build.VERSION.SDK_INT));
3129
3130            String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
3131            printer.println((installerName != null) ? installerName : "");
3132
3133            printer.println(withApk ? "1" : "0");
3134            if (pkg.signatures == null) {
3135                printer.println("0");
3136            } else {
3137                printer.println(Integer.toString(pkg.signatures.length));
3138                for (Signature sig : pkg.signatures) {
3139                    printer.println(sig.toCharsString());
3140                }
3141            }
3142
3143            FileOutputStream outstream = new FileOutputStream(manifestFile);
3144            outstream.write(builder.toString().getBytes());
3145            outstream.close();
3146        }
3147
3148        private void tearDown(PackageInfo pkg) {
3149            if (pkg != null) {
3150                final ApplicationInfo app = pkg.applicationInfo;
3151                if (app != null) {
3152                    try {
3153                        // unbind and tidy up even on timeout or failure, just in case
3154                        mActivityManager.unbindBackupAgent(app);
3155
3156                        // The agent was running with a stub Application object, so shut it down.
3157                        if (app.uid != Process.SYSTEM_UID
3158                                && app.uid != Process.PHONE_UID) {
3159                            if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
3160                            mActivityManager.killApplicationProcess(app.processName, app.uid);
3161                        } else {
3162                            if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
3163                        }
3164                    } catch (RemoteException e) {
3165                        Slog.d(TAG, "Lost app trying to shut down");
3166                    }
3167                }
3168            }
3169        }
3170
3171        // wrappers for observer use
3172        void sendStartBackup() {
3173            if (mObserver != null) {
3174                try {
3175                    mObserver.onStartBackup();
3176                } catch (RemoteException e) {
3177                    Slog.w(TAG, "full backup observer went away: startBackup");
3178                    mObserver = null;
3179                }
3180            }
3181        }
3182
3183        void sendOnBackupPackage(String name) {
3184            if (mObserver != null) {
3185                try {
3186                    // TODO: use a more user-friendly name string
3187                    mObserver.onBackupPackage(name);
3188                } catch (RemoteException e) {
3189                    Slog.w(TAG, "full backup observer went away: backupPackage");
3190                    mObserver = null;
3191                }
3192            }
3193        }
3194
3195        void sendEndBackup() {
3196            if (mObserver != null) {
3197                try {
3198                    mObserver.onEndBackup();
3199                } catch (RemoteException e) {
3200                    Slog.w(TAG, "full backup observer went away: endBackup");
3201                    mObserver = null;
3202                }
3203            }
3204        }
3205    }
3206
3207
3208    // ----- Full restore from a file/socket -----
3209
3210    // Description of a file in the restore datastream
3211    static class FileMetadata {
3212        String packageName;             // name of the owning app
3213        String installerPackageName;    // name of the market-type app that installed the owner
3214        int type;                       // e.g. BackupAgent.TYPE_DIRECTORY
3215        String domain;                  // e.g. FullBackup.DATABASE_TREE_TOKEN
3216        String path;                    // subpath within the semantic domain
3217        long mode;                      // e.g. 0666 (actually int)
3218        long mtime;                     // last mod time, UTC time_t (actually int)
3219        long size;                      // bytes of content
3220
3221        @Override
3222        public String toString() {
3223            StringBuilder sb = new StringBuilder(128);
3224            sb.append("FileMetadata{");
3225            sb.append(packageName); sb.append(',');
3226            sb.append(type); sb.append(',');
3227            sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
3228            sb.append(size);
3229            sb.append('}');
3230            return sb.toString();
3231        }
3232    }
3233
3234    enum RestorePolicy {
3235        IGNORE,
3236        ACCEPT,
3237        ACCEPT_IF_APK
3238    }
3239
3240    class PerformFullRestoreTask extends ObbServiceClient implements Runnable {
3241        ParcelFileDescriptor mInputFile;
3242        String mCurrentPassword;
3243        String mDecryptPassword;
3244        IFullBackupRestoreObserver mObserver;
3245        AtomicBoolean mLatchObject;
3246        IBackupAgent mAgent;
3247        String mAgentPackage;
3248        ApplicationInfo mTargetApp;
3249        FullBackupObbConnection mObbConnection = null;
3250        ParcelFileDescriptor[] mPipes = null;
3251
3252        long mBytes;
3253
3254        // possible handling states for a given package in the restore dataset
3255        final HashMap<String, RestorePolicy> mPackagePolicies
3256                = new HashMap<String, RestorePolicy>();
3257
3258        // installer package names for each encountered app, derived from the manifests
3259        final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
3260
3261        // Signatures for a given package found in its manifest file
3262        final HashMap<String, Signature[]> mManifestSignatures
3263                = new HashMap<String, Signature[]>();
3264
3265        // Packages we've already wiped data on when restoring their first file
3266        final HashSet<String> mClearedPackages = new HashSet<String>();
3267
3268        PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
3269                IFullBackupRestoreObserver observer, AtomicBoolean latch) {
3270            mInputFile = fd;
3271            mCurrentPassword = curPassword;
3272            mDecryptPassword = decryptPassword;
3273            mObserver = observer;
3274            mLatchObject = latch;
3275            mAgent = null;
3276            mAgentPackage = null;
3277            mTargetApp = null;
3278            mObbConnection = new FullBackupObbConnection();
3279
3280            // Which packages we've already wiped data on.  We prepopulate this
3281            // with a whitelist of packages known to be unclearable.
3282            mClearedPackages.add("android");
3283            mClearedPackages.add("com.android.providers.settings");
3284
3285        }
3286
3287        class RestoreFileRunnable implements Runnable {
3288            IBackupAgent mAgent;
3289            FileMetadata mInfo;
3290            ParcelFileDescriptor mSocket;
3291            int mToken;
3292
3293            RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
3294                    ParcelFileDescriptor socket, int token) throws IOException {
3295                mAgent = agent;
3296                mInfo = info;
3297                mToken = token;
3298
3299                // This class is used strictly for process-local binder invocations.  The
3300                // semantics of ParcelFileDescriptor differ in this case; in particular, we
3301                // do not automatically get a 'dup'ed descriptor that we can can continue
3302                // to use asynchronously from the caller.  So, we make sure to dup it ourselves
3303                // before proceeding to do the restore.
3304                mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
3305            }
3306
3307            @Override
3308            public void run() {
3309                try {
3310                    mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
3311                            mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
3312                            mToken, mBackupManagerBinder);
3313                } catch (RemoteException e) {
3314                    // never happens; this is used strictly for local binder calls
3315                }
3316            }
3317        }
3318
3319        @Override
3320        public void run() {
3321            Slog.i(TAG, "--- Performing full-dataset restore ---");
3322            mObbConnection.establish();
3323            sendStartRestore();
3324
3325            // Are we able to restore shared-storage data?
3326            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
3327                mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
3328            }
3329
3330            FileInputStream rawInStream = null;
3331            DataInputStream rawDataIn = null;
3332            try {
3333                if (!backupPasswordMatches(mCurrentPassword)) {
3334                    if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
3335                    return;
3336                }
3337
3338                mBytes = 0;
3339                byte[] buffer = new byte[32 * 1024];
3340                rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
3341                rawDataIn = new DataInputStream(rawInStream);
3342
3343                // First, parse out the unencrypted/uncompressed header
3344                boolean compressed = false;
3345                InputStream preCompressStream = rawInStream;
3346                final InputStream in;
3347
3348                boolean okay = false;
3349                final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
3350                byte[] streamHeader = new byte[headerLen];
3351                rawDataIn.readFully(streamHeader);
3352                byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
3353                if (Arrays.equals(magicBytes, streamHeader)) {
3354                    // okay, header looks good.  now parse out the rest of the fields.
3355                    String s = readHeaderLine(rawInStream);
3356                    final int archiveVersion = Integer.parseInt(s);
3357                    if (archiveVersion <= BACKUP_FILE_VERSION) {
3358                        // okay, it's a version we recognize.  if it's version 1, we may need
3359                        // to try two different PBKDF2 regimes to compare checksums.
3360                        final boolean pbkdf2Fallback = (archiveVersion == 1);
3361
3362                        s = readHeaderLine(rawInStream);
3363                        compressed = (Integer.parseInt(s) != 0);
3364                        s = readHeaderLine(rawInStream);
3365                        if (s.equals("none")) {
3366                            // no more header to parse; we're good to go
3367                            okay = true;
3368                        } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
3369                            preCompressStream = decodeAesHeaderAndInitialize(s, pbkdf2Fallback,
3370                                    rawInStream);
3371                            if (preCompressStream != null) {
3372                                okay = true;
3373                            }
3374                        } else Slog.w(TAG, "Archive is encrypted but no password given");
3375                    } else Slog.w(TAG, "Wrong header version: " + s);
3376                } else Slog.w(TAG, "Didn't read the right header magic");
3377
3378                if (!okay) {
3379                    Slog.w(TAG, "Invalid restore data; aborting.");
3380                    return;
3381                }
3382
3383                // okay, use the right stream layer based on compression
3384                in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
3385
3386                boolean didRestore;
3387                do {
3388                    didRestore = restoreOneFile(in, buffer);
3389                } while (didRestore);
3390
3391                if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
3392            } catch (IOException e) {
3393                Slog.e(TAG, "Unable to read restore input");
3394            } finally {
3395                tearDownPipes();
3396                tearDownAgent(mTargetApp);
3397
3398                try {
3399                    if (rawDataIn != null) rawDataIn.close();
3400                    if (rawInStream != null) rawInStream.close();
3401                    mInputFile.close();
3402                } catch (IOException e) {
3403                    Slog.w(TAG, "Close of restore data pipe threw", e);
3404                    /* nothing we can do about this */
3405                }
3406                synchronized (mCurrentOpLock) {
3407                    mCurrentOperations.clear();
3408                }
3409                synchronized (mLatchObject) {
3410                    mLatchObject.set(true);
3411                    mLatchObject.notifyAll();
3412                }
3413                mObbConnection.tearDown();
3414                sendEndRestore();
3415                Slog.d(TAG, "Full restore pass complete.");
3416                mWakelock.release();
3417            }
3418        }
3419
3420        String readHeaderLine(InputStream in) throws IOException {
3421            int c;
3422            StringBuilder buffer = new StringBuilder(80);
3423            while ((c = in.read()) >= 0) {
3424                if (c == '\n') break;   // consume and discard the newlines
3425                buffer.append((char)c);
3426            }
3427            return buffer.toString();
3428        }
3429
3430        InputStream attemptMasterKeyDecryption(String algorithm, byte[] userSalt, byte[] ckSalt,
3431                int rounds, String userIvHex, String masterKeyBlobHex, InputStream rawInStream,
3432                boolean doLog) {
3433            InputStream result = null;
3434
3435            try {
3436                Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
3437                SecretKey userKey = buildPasswordKey(algorithm, mDecryptPassword, userSalt,
3438                        rounds);
3439                byte[] IV = hexToByteArray(userIvHex);
3440                IvParameterSpec ivSpec = new IvParameterSpec(IV);
3441                c.init(Cipher.DECRYPT_MODE,
3442                        new SecretKeySpec(userKey.getEncoded(), "AES"),
3443                        ivSpec);
3444                byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3445                byte[] mkBlob = c.doFinal(mkCipher);
3446
3447                // first, the master key IV
3448                int offset = 0;
3449                int len = mkBlob[offset++];
3450                IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3451                offset += len;
3452                // then the master key itself
3453                len = mkBlob[offset++];
3454                byte[] mk = Arrays.copyOfRange(mkBlob,
3455                        offset, offset + len);
3456                offset += len;
3457                // and finally the master key checksum hash
3458                len = mkBlob[offset++];
3459                byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3460                        offset, offset + len);
3461
3462                // now validate the decrypted master key against the checksum
3463                byte[] calculatedCk = makeKeyChecksum(algorithm, mk, ckSalt, rounds);
3464                if (Arrays.equals(calculatedCk, mkChecksum)) {
3465                    ivSpec = new IvParameterSpec(IV);
3466                    c.init(Cipher.DECRYPT_MODE,
3467                            new SecretKeySpec(mk, "AES"),
3468                            ivSpec);
3469                    // Only if all of the above worked properly will 'result' be assigned
3470                    result = new CipherInputStream(rawInStream, c);
3471                } else if (doLog) Slog.w(TAG, "Incorrect password");
3472            } catch (InvalidAlgorithmParameterException e) {
3473                if (doLog) Slog.e(TAG, "Needed parameter spec unavailable!", e);
3474            } catch (BadPaddingException e) {
3475                // This case frequently occurs when the wrong password is used to decrypt
3476                // the master key.  Use the identical "incorrect password" log text as is
3477                // used in the checksum failure log in order to avoid providing additional
3478                // information to an attacker.
3479                if (doLog) Slog.w(TAG, "Incorrect password");
3480            } catch (IllegalBlockSizeException e) {
3481                if (doLog) Slog.w(TAG, "Invalid block size in master key");
3482            } catch (NoSuchAlgorithmException e) {
3483                if (doLog) Slog.e(TAG, "Needed decryption algorithm unavailable!");
3484            } catch (NoSuchPaddingException e) {
3485                if (doLog) Slog.e(TAG, "Needed padding mechanism unavailable!");
3486            } catch (InvalidKeyException e) {
3487                if (doLog) Slog.w(TAG, "Illegal password; aborting");
3488            }
3489
3490            return result;
3491        }
3492
3493        InputStream decodeAesHeaderAndInitialize(String encryptionName, boolean pbkdf2Fallback,
3494                InputStream rawInStream) {
3495            InputStream result = null;
3496            try {
3497                if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3498
3499                    String userSaltHex = readHeaderLine(rawInStream); // 5
3500                    byte[] userSalt = hexToByteArray(userSaltHex);
3501
3502                    String ckSaltHex = readHeaderLine(rawInStream); // 6
3503                    byte[] ckSalt = hexToByteArray(ckSaltHex);
3504
3505                    int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3506                    String userIvHex = readHeaderLine(rawInStream); // 8
3507
3508                    String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3509
3510                    // decrypt the master key blob
3511                    result = attemptMasterKeyDecryption(PBKDF_CURRENT, userSalt, ckSalt,
3512                            rounds, userIvHex, masterKeyBlobHex, rawInStream, false);
3513                    if (result == null && pbkdf2Fallback) {
3514                        result = attemptMasterKeyDecryption(PBKDF_FALLBACK, userSalt, ckSalt,
3515                                rounds, userIvHex, masterKeyBlobHex, rawInStream, true);
3516                    }
3517                } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3518            } catch (NumberFormatException e) {
3519                Slog.w(TAG, "Can't parse restore data header");
3520            } catch (IOException e) {
3521                Slog.w(TAG, "Can't read input header");
3522            }
3523
3524            return result;
3525        }
3526
3527        boolean restoreOneFile(InputStream instream, byte[] buffer) {
3528            FileMetadata info;
3529            try {
3530                info = readTarHeaders(instream);
3531                if (info != null) {
3532                    if (MORE_DEBUG) {
3533                        dumpFileMetadata(info);
3534                    }
3535
3536                    final String pkg = info.packageName;
3537                    if (!pkg.equals(mAgentPackage)) {
3538                        // okay, change in package; set up our various
3539                        // bookkeeping if we haven't seen it yet
3540                        if (!mPackagePolicies.containsKey(pkg)) {
3541                            mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3542                        }
3543
3544                        // Clean up the previous agent relationship if necessary,
3545                        // and let the observer know we're considering a new app.
3546                        if (mAgent != null) {
3547                            if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3548                            tearDownPipes();
3549                            tearDownAgent(mTargetApp);
3550                            mTargetApp = null;
3551                            mAgentPackage = null;
3552                        }
3553                    }
3554
3555                    if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3556                        mPackagePolicies.put(pkg, readAppManifest(info, instream));
3557                        mPackageInstallers.put(pkg, info.installerPackageName);
3558                        // We've read only the manifest content itself at this point,
3559                        // so consume the footer before looping around to the next
3560                        // input file
3561                        skipTarPadding(info.size, instream);
3562                        sendOnRestorePackage(pkg);
3563                    } else {
3564                        // Non-manifest, so it's actual file data.  Is this a package
3565                        // we're ignoring?
3566                        boolean okay = true;
3567                        RestorePolicy policy = mPackagePolicies.get(pkg);
3568                        switch (policy) {
3569                            case IGNORE:
3570                                okay = false;
3571                                break;
3572
3573                            case ACCEPT_IF_APK:
3574                                // If we're in accept-if-apk state, then the first file we
3575                                // see MUST be the apk.
3576                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3577                                    if (DEBUG) Slog.d(TAG, "APK file; installing");
3578                                    // Try to install the app.
3579                                    String installerName = mPackageInstallers.get(pkg);
3580                                    okay = installApk(info, installerName, instream);
3581                                    // good to go; promote to ACCEPT
3582                                    mPackagePolicies.put(pkg, (okay)
3583                                            ? RestorePolicy.ACCEPT
3584                                            : RestorePolicy.IGNORE);
3585                                    // At this point we've consumed this file entry
3586                                    // ourselves, so just strip the tar footer and
3587                                    // go on to the next file in the input stream
3588                                    skipTarPadding(info.size, instream);
3589                                    return true;
3590                                } else {
3591                                    // File data before (or without) the apk.  We can't
3592                                    // handle it coherently in this case so ignore it.
3593                                    mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3594                                    okay = false;
3595                                }
3596                                break;
3597
3598                            case ACCEPT:
3599                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3600                                    if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3601                                    // we can take the data without the apk, so we
3602                                    // *want* to do so.  skip the apk by declaring this
3603                                    // one file not-okay without changing the restore
3604                                    // policy for the package.
3605                                    okay = false;
3606                                }
3607                                break;
3608
3609                            default:
3610                                // Something has gone dreadfully wrong when determining
3611                                // the restore policy from the manifest.  Ignore the
3612                                // rest of this package's data.
3613                                Slog.e(TAG, "Invalid policy from manifest");
3614                                okay = false;
3615                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3616                                break;
3617                        }
3618
3619                        // If the policy is satisfied, go ahead and set up to pipe the
3620                        // data to the agent.
3621                        if (DEBUG && okay && mAgent != null) {
3622                            Slog.i(TAG, "Reusing existing agent instance");
3623                        }
3624                        if (okay && mAgent == null) {
3625                            if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3626
3627                            try {
3628                                mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3629
3630                                // If we haven't sent any data to this app yet, we probably
3631                                // need to clear it first.  Check that.
3632                                if (!mClearedPackages.contains(pkg)) {
3633                                    // apps with their own backup agents are
3634                                    // responsible for coherently managing a full
3635                                    // restore.
3636                                    if (mTargetApp.backupAgentName == null) {
3637                                        if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3638                                        clearApplicationDataSynchronous(pkg);
3639                                    } else {
3640                                        if (DEBUG) Slog.d(TAG, "backup agent ("
3641                                                + mTargetApp.backupAgentName + ") => no clear");
3642                                    }
3643                                    mClearedPackages.add(pkg);
3644                                } else {
3645                                    if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3646                                }
3647
3648                                // All set; now set up the IPC and launch the agent
3649                                setUpPipes();
3650                                mAgent = bindToAgentSynchronous(mTargetApp,
3651                                        IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3652                                mAgentPackage = pkg;
3653                            } catch (IOException e) {
3654                                // fall through to error handling
3655                            } catch (NameNotFoundException e) {
3656                                // fall through to error handling
3657                            }
3658
3659                            if (mAgent == null) {
3660                                if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3661                                okay = false;
3662                                tearDownPipes();
3663                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3664                            }
3665                        }
3666
3667                        // Sanity check: make sure we never give data to the wrong app.  This
3668                        // should never happen but a little paranoia here won't go amiss.
3669                        if (okay && !pkg.equals(mAgentPackage)) {
3670                            Slog.e(TAG, "Restoring data for " + pkg
3671                                    + " but agent is for " + mAgentPackage);
3672                            okay = false;
3673                        }
3674
3675                        // At this point we have an agent ready to handle the full
3676                        // restore data as well as a pipe for sending data to
3677                        // that agent.  Tell the agent to start reading from the
3678                        // pipe.
3679                        if (okay) {
3680                            boolean agentSuccess = true;
3681                            long toCopy = info.size;
3682                            final int token = generateToken();
3683                            try {
3684                                prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
3685                                if (info.domain.equals(FullBackup.OBB_TREE_TOKEN)) {
3686                                    if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
3687                                            + " : " + info.path);
3688                                    mObbConnection.restoreObbFile(pkg, mPipes[0],
3689                                            info.size, info.type, info.path, info.mode,
3690                                            info.mtime, token, mBackupManagerBinder);
3691                                } else {
3692                                    if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3693                                            + info.path);
3694                                    // fire up the app's agent listening on the socket.  If
3695                                    // the agent is running in the system process we can't
3696                                    // just invoke it asynchronously, so we provide a thread
3697                                    // for it here.
3698                                    if (mTargetApp.processName.equals("system")) {
3699                                        Slog.d(TAG, "system process agent - spinning a thread");
3700                                        RestoreFileRunnable runner = new RestoreFileRunnable(
3701                                                mAgent, info, mPipes[0], token);
3702                                        new Thread(runner).start();
3703                                    } else {
3704                                        mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3705                                                info.domain, info.path, info.mode, info.mtime,
3706                                                token, mBackupManagerBinder);
3707                                    }
3708                                }
3709                            } catch (IOException e) {
3710                                // couldn't dup the socket for a process-local restore
3711                                Slog.d(TAG, "Couldn't establish restore");
3712                                agentSuccess = false;
3713                                okay = false;
3714                            } catch (RemoteException e) {
3715                                // whoops, remote entity went away.  We'll eat the content
3716                                // ourselves, then, and not copy it over.
3717                                Slog.e(TAG, "Agent crashed during full restore");
3718                                agentSuccess = false;
3719                                okay = false;
3720                            }
3721
3722                            // Copy over the data if the agent is still good
3723                            if (okay) {
3724                                boolean pipeOkay = true;
3725                                FileOutputStream pipe = new FileOutputStream(
3726                                        mPipes[1].getFileDescriptor());
3727                                while (toCopy > 0) {
3728                                    int toRead = (toCopy > buffer.length)
3729                                    ? buffer.length : (int)toCopy;
3730                                    int nRead = instream.read(buffer, 0, toRead);
3731                                    if (nRead >= 0) mBytes += nRead;
3732                                    if (nRead <= 0) break;
3733                                    toCopy -= nRead;
3734
3735                                    // send it to the output pipe as long as things
3736                                    // are still good
3737                                    if (pipeOkay) {
3738                                        try {
3739                                            pipe.write(buffer, 0, nRead);
3740                                        } catch (IOException e) {
3741                                            Slog.e(TAG, "Failed to write to restore pipe", e);
3742                                            pipeOkay = false;
3743                                        }
3744                                    }
3745                                }
3746
3747                                // done sending that file!  Now we just need to consume
3748                                // the delta from info.size to the end of block.
3749                                skipTarPadding(info.size, instream);
3750
3751                                // and now that we've sent it all, wait for the remote
3752                                // side to acknowledge receipt
3753                                agentSuccess = waitUntilOperationComplete(token);
3754                            }
3755
3756                            // okay, if the remote end failed at any point, deal with
3757                            // it by ignoring the rest of the restore on it
3758                            if (!agentSuccess) {
3759                                mBackupHandler.removeMessages(MSG_TIMEOUT);
3760                                tearDownPipes();
3761                                tearDownAgent(mTargetApp);
3762                                mAgent = null;
3763                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3764                            }
3765                        }
3766
3767                        // Problems setting up the agent communication, or an already-
3768                        // ignored package: skip to the next tar stream entry by
3769                        // reading and discarding this file.
3770                        if (!okay) {
3771                            if (DEBUG) Slog.d(TAG, "[discarding file content]");
3772                            long bytesToConsume = (info.size + 511) & ~511;
3773                            while (bytesToConsume > 0) {
3774                                int toRead = (bytesToConsume > buffer.length)
3775                                ? buffer.length : (int)bytesToConsume;
3776                                long nRead = instream.read(buffer, 0, toRead);
3777                                if (nRead >= 0) mBytes += nRead;
3778                                if (nRead <= 0) break;
3779                                bytesToConsume -= nRead;
3780                            }
3781                        }
3782                    }
3783                }
3784            } catch (IOException e) {
3785                if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
3786                // treat as EOF
3787                info = null;
3788            }
3789
3790            return (info != null);
3791        }
3792
3793        void setUpPipes() throws IOException {
3794            mPipes = ParcelFileDescriptor.createPipe();
3795        }
3796
3797        void tearDownPipes() {
3798            if (mPipes != null) {
3799                try {
3800                    mPipes[0].close();
3801                    mPipes[0] = null;
3802                    mPipes[1].close();
3803                    mPipes[1] = null;
3804                } catch (IOException e) {
3805                    Slog.w(TAG, "Couldn't close agent pipes", e);
3806                }
3807                mPipes = null;
3808            }
3809        }
3810
3811        void tearDownAgent(ApplicationInfo app) {
3812            if (mAgent != null) {
3813                try {
3814                    // unbind and tidy up even on timeout or failure, just in case
3815                    mActivityManager.unbindBackupAgent(app);
3816
3817                    // The agent was running with a stub Application object, so shut it down.
3818                    // !!! We hardcode the confirmation UI's package name here rather than use a
3819                    //     manifest flag!  TODO something less direct.
3820                    if (app.uid != Process.SYSTEM_UID
3821                            && !app.packageName.equals("com.android.backupconfirm")) {
3822                        if (DEBUG) Slog.d(TAG, "Killing host process");
3823                        mActivityManager.killApplicationProcess(app.processName, app.uid);
3824                    } else {
3825                        if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3826                    }
3827                } catch (RemoteException e) {
3828                    Slog.d(TAG, "Lost app trying to shut down");
3829                }
3830                mAgent = null;
3831            }
3832        }
3833
3834        class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3835            final AtomicBoolean mDone = new AtomicBoolean();
3836            String mPackageName;
3837            int mResult;
3838
3839            public void reset() {
3840                synchronized (mDone) {
3841                    mDone.set(false);
3842                }
3843            }
3844
3845            public void waitForCompletion() {
3846                synchronized (mDone) {
3847                    while (mDone.get() == false) {
3848                        try {
3849                            mDone.wait();
3850                        } catch (InterruptedException e) { }
3851                    }
3852                }
3853            }
3854
3855            int getResult() {
3856                return mResult;
3857            }
3858
3859            @Override
3860            public void packageInstalled(String packageName, int returnCode)
3861                    throws RemoteException {
3862                synchronized (mDone) {
3863                    mResult = returnCode;
3864                    mPackageName = packageName;
3865                    mDone.set(true);
3866                    mDone.notifyAll();
3867                }
3868            }
3869        }
3870
3871        class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3872            final AtomicBoolean mDone = new AtomicBoolean();
3873            int mResult;
3874
3875            public void reset() {
3876                synchronized (mDone) {
3877                    mDone.set(false);
3878                }
3879            }
3880
3881            public void waitForCompletion() {
3882                synchronized (mDone) {
3883                    while (mDone.get() == false) {
3884                        try {
3885                            mDone.wait();
3886                        } catch (InterruptedException e) { }
3887                    }
3888                }
3889            }
3890
3891            @Override
3892            public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3893                synchronized (mDone) {
3894                    mResult = returnCode;
3895                    mDone.set(true);
3896                    mDone.notifyAll();
3897                }
3898            }
3899        }
3900
3901        final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
3902        final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
3903
3904        boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3905            boolean okay = true;
3906
3907            if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3908
3909            // The file content is an .apk file.  Copy it out to a staging location and
3910            // attempt to install it.
3911            File apkFile = new File(mDataDir, info.packageName);
3912            try {
3913                FileOutputStream apkStream = new FileOutputStream(apkFile);
3914                byte[] buffer = new byte[32 * 1024];
3915                long size = info.size;
3916                while (size > 0) {
3917                    long toRead = (buffer.length < size) ? buffer.length : size;
3918                    int didRead = instream.read(buffer, 0, (int)toRead);
3919                    if (didRead >= 0) mBytes += didRead;
3920                    apkStream.write(buffer, 0, didRead);
3921                    size -= didRead;
3922                }
3923                apkStream.close();
3924
3925                // make sure the installer can read it
3926                apkFile.setReadable(true, false);
3927
3928                // Now install it
3929                Uri packageUri = Uri.fromFile(apkFile);
3930                mInstallObserver.reset();
3931                mPackageManager.installPackage(packageUri, mInstallObserver,
3932                        PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3933                        installerPackage);
3934                mInstallObserver.waitForCompletion();
3935
3936                if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3937                    // The only time we continue to accept install of data even if the
3938                    // apk install failed is if we had already determined that we could
3939                    // accept the data regardless.
3940                    if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3941                        okay = false;
3942                    }
3943                } else {
3944                    // Okay, the install succeeded.  Make sure it was the right app.
3945                    boolean uninstall = false;
3946                    if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3947                        Slog.w(TAG, "Restore stream claimed to include apk for "
3948                                + info.packageName + " but apk was really "
3949                                + mInstallObserver.mPackageName);
3950                        // delete the package we just put in place; it might be fraudulent
3951                        okay = false;
3952                        uninstall = true;
3953                    } else {
3954                        try {
3955                            PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3956                                    PackageManager.GET_SIGNATURES);
3957                            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3958                                Slog.w(TAG, "Restore stream contains apk of package "
3959                                        + info.packageName + " but it disallows backup/restore");
3960                                okay = false;
3961                            } else {
3962                                // So far so good -- do the signatures match the manifest?
3963                                Signature[] sigs = mManifestSignatures.get(info.packageName);
3964                                if (signaturesMatch(sigs, pkg)) {
3965                                    // If this is a system-uid app without a declared backup agent,
3966                                    // don't restore any of the file data.
3967                                    if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
3968                                            && (pkg.applicationInfo.backupAgentName == null)) {
3969                                        Slog.w(TAG, "Installed app " + info.packageName
3970                                                + " has restricted uid and no agent");
3971                                        okay = false;
3972                                    }
3973                                } else {
3974                                    Slog.w(TAG, "Installed app " + info.packageName
3975                                            + " signatures do not match restore manifest");
3976                                    okay = false;
3977                                    uninstall = true;
3978                                }
3979                            }
3980                        } catch (NameNotFoundException e) {
3981                            Slog.w(TAG, "Install of package " + info.packageName
3982                                    + " succeeded but now not found");
3983                            okay = false;
3984                        }
3985                    }
3986
3987                    // If we're not okay at this point, we need to delete the package
3988                    // that we just installed.
3989                    if (uninstall) {
3990                        mDeleteObserver.reset();
3991                        mPackageManager.deletePackage(mInstallObserver.mPackageName,
3992                                mDeleteObserver, 0);
3993                        mDeleteObserver.waitForCompletion();
3994                    }
3995                }
3996            } catch (IOException e) {
3997                Slog.e(TAG, "Unable to transcribe restored apk for install");
3998                okay = false;
3999            } finally {
4000                apkFile.delete();
4001            }
4002
4003            return okay;
4004        }
4005
4006        // Given an actual file content size, consume the post-content padding mandated
4007        // by the tar format.
4008        void skipTarPadding(long size, InputStream instream) throws IOException {
4009            long partial = (size + 512) % 512;
4010            if (partial > 0) {
4011                final int needed = 512 - (int)partial;
4012                byte[] buffer = new byte[needed];
4013                if (readExactly(instream, buffer, 0, needed) == needed) {
4014                    mBytes += needed;
4015                } else throw new IOException("Unexpected EOF in padding");
4016            }
4017        }
4018
4019        // Returns a policy constant; takes a buffer arg to reduce memory churn
4020        RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
4021                throws IOException {
4022            // Fail on suspiciously large manifest files
4023            if (info.size > 64 * 1024) {
4024                throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
4025            }
4026
4027            byte[] buffer = new byte[(int) info.size];
4028            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
4029                mBytes += info.size;
4030            } else throw new IOException("Unexpected EOF in manifest");
4031
4032            RestorePolicy policy = RestorePolicy.IGNORE;
4033            String[] str = new String[1];
4034            int offset = 0;
4035
4036            try {
4037                offset = extractLine(buffer, offset, str);
4038                int version = Integer.parseInt(str[0]);
4039                if (version == BACKUP_MANIFEST_VERSION) {
4040                    offset = extractLine(buffer, offset, str);
4041                    String manifestPackage = str[0];
4042                    // TODO: handle <original-package>
4043                    if (manifestPackage.equals(info.packageName)) {
4044                        offset = extractLine(buffer, offset, str);
4045                        version = Integer.parseInt(str[0]);  // app version
4046                        offset = extractLine(buffer, offset, str);
4047                        int platformVersion = Integer.parseInt(str[0]);
4048                        offset = extractLine(buffer, offset, str);
4049                        info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
4050                        offset = extractLine(buffer, offset, str);
4051                        boolean hasApk = str[0].equals("1");
4052                        offset = extractLine(buffer, offset, str);
4053                        int numSigs = Integer.parseInt(str[0]);
4054                        if (numSigs > 0) {
4055                            Signature[] sigs = new Signature[numSigs];
4056                            for (int i = 0; i < numSigs; i++) {
4057                                offset = extractLine(buffer, offset, str);
4058                                sigs[i] = new Signature(str[0]);
4059                            }
4060                            mManifestSignatures.put(info.packageName, sigs);
4061
4062                            // Okay, got the manifest info we need...
4063                            try {
4064                                PackageInfo pkgInfo = mPackageManager.getPackageInfo(
4065                                        info.packageName, PackageManager.GET_SIGNATURES);
4066                                // Fall through to IGNORE if the app explicitly disallows backup
4067                                final int flags = pkgInfo.applicationInfo.flags;
4068                                if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
4069                                    // Restore system-uid-space packages only if they have
4070                                    // defined a custom backup agent
4071                                    if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
4072                                            || (pkgInfo.applicationInfo.backupAgentName != null)) {
4073                                        // Verify signatures against any installed version; if they
4074                                        // don't match, then we fall though and ignore the data.  The
4075                                        // signatureMatch() method explicitly ignores the signature
4076                                        // check for packages installed on the system partition, because
4077                                        // such packages are signed with the platform cert instead of
4078                                        // the app developer's cert, so they're different on every
4079                                        // device.
4080                                        if (signaturesMatch(sigs, pkgInfo)) {
4081                                            if (pkgInfo.versionCode >= version) {
4082                                                Slog.i(TAG, "Sig + version match; taking data");
4083                                                policy = RestorePolicy.ACCEPT;
4084                                            } else {
4085                                                // The data is from a newer version of the app than
4086                                                // is presently installed.  That means we can only
4087                                                // use it if the matching apk is also supplied.
4088                                                Slog.d(TAG, "Data version " + version
4089                                                        + " is newer than installed version "
4090                                                        + pkgInfo.versionCode + " - requiring apk");
4091                                                policy = RestorePolicy.ACCEPT_IF_APK;
4092                                            }
4093                                        } else {
4094                                            Slog.w(TAG, "Restore manifest signatures do not match "
4095                                                    + "installed application for " + info.packageName);
4096                                        }
4097                                    } else {
4098                                        Slog.w(TAG, "Package " + info.packageName
4099                                                + " is system level with no agent");
4100                                    }
4101                                } else {
4102                                    if (DEBUG) Slog.i(TAG, "Restore manifest from "
4103                                            + info.packageName + " but allowBackup=false");
4104                                }
4105                            } catch (NameNotFoundException e) {
4106                                // Okay, the target app isn't installed.  We can process
4107                                // the restore properly only if the dataset provides the
4108                                // apk file and we can successfully install it.
4109                                if (DEBUG) Slog.i(TAG, "Package " + info.packageName
4110                                        + " not installed; requiring apk in dataset");
4111                                policy = RestorePolicy.ACCEPT_IF_APK;
4112                            }
4113
4114                            if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
4115                                Slog.i(TAG, "Cannot restore package " + info.packageName
4116                                        + " without the matching .apk");
4117                            }
4118                        } else {
4119                            Slog.i(TAG, "Missing signature on backed-up package "
4120                                    + info.packageName);
4121                        }
4122                    } else {
4123                        Slog.i(TAG, "Expected package " + info.packageName
4124                                + " but restore manifest claims " + manifestPackage);
4125                    }
4126                } else {
4127                    Slog.i(TAG, "Unknown restore manifest version " + version
4128                            + " for package " + info.packageName);
4129                }
4130            } catch (NumberFormatException e) {
4131                Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
4132            } catch (IllegalArgumentException e) {
4133                Slog.w(TAG, e.getMessage());
4134            }
4135
4136            return policy;
4137        }
4138
4139        // Builds a line from a byte buffer starting at 'offset', and returns
4140        // the index of the next unconsumed data in the buffer.
4141        int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
4142            final int end = buffer.length;
4143            if (offset >= end) throw new IOException("Incomplete data");
4144
4145            int pos;
4146            for (pos = offset; pos < end; pos++) {
4147                byte c = buffer[pos];
4148                // at LF we declare end of line, and return the next char as the
4149                // starting point for the next time through
4150                if (c == '\n') {
4151                    break;
4152                }
4153            }
4154            outStr[0] = new String(buffer, offset, pos - offset);
4155            pos++;  // may be pointing an extra byte past the end but that's okay
4156            return pos;
4157        }
4158
4159        void dumpFileMetadata(FileMetadata info) {
4160            if (DEBUG) {
4161                StringBuilder b = new StringBuilder(128);
4162
4163                // mode string
4164                b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
4165                b.append(((info.mode & 0400) != 0) ? 'r' : '-');
4166                b.append(((info.mode & 0200) != 0) ? 'w' : '-');
4167                b.append(((info.mode & 0100) != 0) ? 'x' : '-');
4168                b.append(((info.mode & 0040) != 0) ? 'r' : '-');
4169                b.append(((info.mode & 0020) != 0) ? 'w' : '-');
4170                b.append(((info.mode & 0010) != 0) ? 'x' : '-');
4171                b.append(((info.mode & 0004) != 0) ? 'r' : '-');
4172                b.append(((info.mode & 0002) != 0) ? 'w' : '-');
4173                b.append(((info.mode & 0001) != 0) ? 'x' : '-');
4174                b.append(String.format(" %9d ", info.size));
4175
4176                Date stamp = new Date(info.mtime);
4177                b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp));
4178
4179                b.append(info.packageName);
4180                b.append(" :: ");
4181                b.append(info.domain);
4182                b.append(" :: ");
4183                b.append(info.path);
4184
4185                Slog.i(TAG, b.toString());
4186            }
4187        }
4188        // Consume a tar file header block [sequence] and accumulate the relevant metadata
4189        FileMetadata readTarHeaders(InputStream instream) throws IOException {
4190            byte[] block = new byte[512];
4191            FileMetadata info = null;
4192
4193            boolean gotHeader = readTarHeader(instream, block);
4194            if (gotHeader) {
4195                try {
4196                    // okay, presume we're okay, and extract the various metadata
4197                    info = new FileMetadata();
4198                    info.size = extractRadix(block, 124, 12, 8);
4199                    info.mtime = extractRadix(block, 136, 12, 8);
4200                    info.mode = extractRadix(block, 100, 8, 8);
4201
4202                    info.path = extractString(block, 345, 155); // prefix
4203                    String path = extractString(block, 0, 100);
4204                    if (path.length() > 0) {
4205                        if (info.path.length() > 0) info.path += '/';
4206                        info.path += path;
4207                    }
4208
4209                    // tar link indicator field: 1 byte at offset 156 in the header.
4210                    int typeChar = block[156];
4211                    if (typeChar == 'x') {
4212                        // pax extended header, so we need to read that
4213                        gotHeader = readPaxExtendedHeader(instream, info);
4214                        if (gotHeader) {
4215                            // and after a pax extended header comes another real header -- read
4216                            // that to find the real file type
4217                            gotHeader = readTarHeader(instream, block);
4218                        }
4219                        if (!gotHeader) throw new IOException("Bad or missing pax header");
4220
4221                        typeChar = block[156];
4222                    }
4223
4224                    switch (typeChar) {
4225                        case '0': info.type = BackupAgent.TYPE_FILE; break;
4226                        case '5': {
4227                            info.type = BackupAgent.TYPE_DIRECTORY;
4228                            if (info.size != 0) {
4229                                Slog.w(TAG, "Directory entry with nonzero size in header");
4230                                info.size = 0;
4231                            }
4232                            break;
4233                        }
4234                        case 0: {
4235                            // presume EOF
4236                            if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
4237                            return null;
4238                        }
4239                        default: {
4240                            Slog.e(TAG, "Unknown tar entity type: " + typeChar);
4241                            throw new IOException("Unknown entity type " + typeChar);
4242                        }
4243                    }
4244
4245                    // Parse out the path
4246                    //
4247                    // first: apps/shared/unrecognized
4248                    if (FullBackup.SHARED_PREFIX.regionMatches(0,
4249                            info.path, 0, FullBackup.SHARED_PREFIX.length())) {
4250                        // File in shared storage.  !!! TODO: implement this.
4251                        info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
4252                        info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
4253                        info.domain = FullBackup.SHARED_STORAGE_TOKEN;
4254                        if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
4255                    } else if (FullBackup.APPS_PREFIX.regionMatches(0,
4256                            info.path, 0, FullBackup.APPS_PREFIX.length())) {
4257                        // App content!  Parse out the package name and domain
4258
4259                        // strip the apps/ prefix
4260                        info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
4261
4262                        // extract the package name
4263                        int slash = info.path.indexOf('/');
4264                        if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
4265                        info.packageName = info.path.substring(0, slash);
4266                        info.path = info.path.substring(slash+1);
4267
4268                        // if it's a manifest we're done, otherwise parse out the domains
4269                        if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
4270                            slash = info.path.indexOf('/');
4271                            if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
4272                            info.domain = info.path.substring(0, slash);
4273                            info.path = info.path.substring(slash + 1);
4274                        }
4275                    }
4276                } catch (IOException e) {
4277                    if (DEBUG) {
4278                        Slog.e(TAG, "Parse error in header: " + e.getMessage());
4279                        HEXLOG(block);
4280                    }
4281                    throw e;
4282                }
4283            }
4284            return info;
4285        }
4286
4287        private void HEXLOG(byte[] block) {
4288            int offset = 0;
4289            int todo = block.length;
4290            StringBuilder buf = new StringBuilder(64);
4291            while (todo > 0) {
4292                buf.append(String.format("%04x   ", offset));
4293                int numThisLine = (todo > 16) ? 16 : todo;
4294                for (int i = 0; i < numThisLine; i++) {
4295                    buf.append(String.format("%02x ", block[offset+i]));
4296                }
4297                Slog.i("hexdump", buf.toString());
4298                buf.setLength(0);
4299                todo -= numThisLine;
4300                offset += numThisLine;
4301            }
4302        }
4303
4304        // Read exactly the given number of bytes into a buffer at the stated offset.
4305        // Returns false if EOF is encountered before the requested number of bytes
4306        // could be read.
4307        int readExactly(InputStream in, byte[] buffer, int offset, int size)
4308                throws IOException {
4309            if (size <= 0) throw new IllegalArgumentException("size must be > 0");
4310
4311            int soFar = 0;
4312            while (soFar < size) {
4313                int nRead = in.read(buffer, offset + soFar, size - soFar);
4314                if (nRead <= 0) {
4315                    if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
4316                    break;
4317                }
4318                soFar += nRead;
4319            }
4320            return soFar;
4321        }
4322
4323        boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
4324            final int got = readExactly(instream, block, 0, 512);
4325            if (got == 0) return false;     // Clean EOF
4326            if (got < 512) throw new IOException("Unable to read full block header");
4327            mBytes += 512;
4328            return true;
4329        }
4330
4331        // overwrites 'info' fields based on the pax extended header
4332        boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
4333                throws IOException {
4334            // We should never see a pax extended header larger than this
4335            if (info.size > 32*1024) {
4336                Slog.w(TAG, "Suspiciously large pax header size " + info.size
4337                        + " - aborting");
4338                throw new IOException("Sanity failure: pax header size " + info.size);
4339            }
4340
4341            // read whole blocks, not just the content size
4342            int numBlocks = (int)((info.size + 511) >> 9);
4343            byte[] data = new byte[numBlocks * 512];
4344            if (readExactly(instream, data, 0, data.length) < data.length) {
4345                throw new IOException("Unable to read full pax header");
4346            }
4347            mBytes += data.length;
4348
4349            final int contentSize = (int) info.size;
4350            int offset = 0;
4351            do {
4352                // extract the line at 'offset'
4353                int eol = offset+1;
4354                while (eol < contentSize && data[eol] != ' ') eol++;
4355                if (eol >= contentSize) {
4356                    // error: we just hit EOD looking for the end of the size field
4357                    throw new IOException("Invalid pax data");
4358                }
4359                // eol points to the space between the count and the key
4360                int linelen = (int) extractRadix(data, offset, eol - offset, 10);
4361                int key = eol + 1;  // start of key=value
4362                eol = offset + linelen - 1; // trailing LF
4363                int value;
4364                for (value = key+1; data[value] != '=' && value <= eol; value++);
4365                if (value > eol) {
4366                    throw new IOException("Invalid pax declaration");
4367                }
4368
4369                // pax requires that key/value strings be in UTF-8
4370                String keyStr = new String(data, key, value-key, "UTF-8");
4371                // -1 to strip the trailing LF
4372                String valStr = new String(data, value+1, eol-value-1, "UTF-8");
4373
4374                if ("path".equals(keyStr)) {
4375                    info.path = valStr;
4376                } else if ("size".equals(keyStr)) {
4377                    info.size = Long.parseLong(valStr);
4378                } else {
4379                    if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
4380                }
4381
4382                offset += linelen;
4383            } while (offset < contentSize);
4384
4385            return true;
4386        }
4387
4388        long extractRadix(byte[] data, int offset, int maxChars, int radix)
4389                throws IOException {
4390            long value = 0;
4391            final int end = offset + maxChars;
4392            for (int i = offset; i < end; i++) {
4393                final byte b = data[i];
4394                // Numeric fields in tar can terminate with either NUL or SPC
4395                if (b == 0 || b == ' ') break;
4396                if (b < '0' || b > ('0' + radix - 1)) {
4397                    throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
4398                }
4399                value = radix * value + (b - '0');
4400            }
4401            return value;
4402        }
4403
4404        String extractString(byte[] data, int offset, int maxChars) throws IOException {
4405            final int end = offset + maxChars;
4406            int eos = offset;
4407            // tar string fields terminate early with a NUL
4408            while (eos < end && data[eos] != 0) eos++;
4409            return new String(data, offset, eos-offset, "US-ASCII");
4410        }
4411
4412        void sendStartRestore() {
4413            if (mObserver != null) {
4414                try {
4415                    mObserver.onStartRestore();
4416                } catch (RemoteException e) {
4417                    Slog.w(TAG, "full restore observer went away: startRestore");
4418                    mObserver = null;
4419                }
4420            }
4421        }
4422
4423        void sendOnRestorePackage(String name) {
4424            if (mObserver != null) {
4425                try {
4426                    // TODO: use a more user-friendly name string
4427                    mObserver.onRestorePackage(name);
4428                } catch (RemoteException e) {
4429                    Slog.w(TAG, "full restore observer went away: restorePackage");
4430                    mObserver = null;
4431                }
4432            }
4433        }
4434
4435        void sendEndRestore() {
4436            if (mObserver != null) {
4437                try {
4438                    mObserver.onEndRestore();
4439                } catch (RemoteException e) {
4440                    Slog.w(TAG, "full restore observer went away: endRestore");
4441                    mObserver = null;
4442                }
4443            }
4444        }
4445    }
4446
4447    // ----- Restore handling -----
4448
4449    private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4450        // If the target resides on the system partition, we allow it to restore
4451        // data from the like-named package in a restore set even if the signatures
4452        // do not match.  (Unlike general applications, those flashed to the system
4453        // partition will be signed with the device's platform certificate, so on
4454        // different phones the same system app will have different signatures.)
4455        if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4456            if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
4457            return true;
4458        }
4459
4460        // Allow unsigned apps, but not signed on one device and unsigned on the other
4461        // !!! TODO: is this the right policy?
4462        Signature[] deviceSigs = target.signatures;
4463        if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
4464                + " device=" + deviceSigs);
4465        if ((storedSigs == null || storedSigs.length == 0)
4466                && (deviceSigs == null || deviceSigs.length == 0)) {
4467            return true;
4468        }
4469        if (storedSigs == null || deviceSigs == null) {
4470            return false;
4471        }
4472
4473        // !!! TODO: this demands that every stored signature match one
4474        // that is present on device, and does not demand the converse.
4475        // Is this this right policy?
4476        int nStored = storedSigs.length;
4477        int nDevice = deviceSigs.length;
4478
4479        for (int i=0; i < nStored; i++) {
4480            boolean match = false;
4481            for (int j=0; j < nDevice; j++) {
4482                if (storedSigs[i].equals(deviceSigs[j])) {
4483                    match = true;
4484                    break;
4485                }
4486            }
4487            if (!match) {
4488                return false;
4489            }
4490        }
4491        return true;
4492    }
4493
4494    enum RestoreState {
4495        INITIAL,
4496        DOWNLOAD_DATA,
4497        PM_METADATA,
4498        RUNNING_QUEUE,
4499        FINAL
4500    }
4501
4502    class PerformRestoreTask implements BackupRestoreTask {
4503        private IBackupTransport mTransport;
4504        private IRestoreObserver mObserver;
4505        private long mToken;
4506        private PackageInfo mTargetPackage;
4507        private File mStateDir;
4508        private int mPmToken;
4509        private boolean mNeedFullBackup;
4510        private HashSet<String> mFilterSet;
4511        private long mStartRealtime;
4512        private PackageManagerBackupAgent mPmAgent;
4513        private List<PackageInfo> mAgentPackages;
4514        private ArrayList<PackageInfo> mRestorePackages;
4515        private RestoreState mCurrentState;
4516        private int mCount;
4517        private boolean mFinished;
4518        private int mStatus;
4519        private File mBackupDataName;
4520        private File mNewStateName;
4521        private File mSavedStateName;
4522        private ParcelFileDescriptor mBackupData;
4523        private ParcelFileDescriptor mNewState;
4524        private PackageInfo mCurrentPackage;
4525
4526
4527        class RestoreRequest {
4528            public PackageInfo app;
4529            public int storedAppVersion;
4530
4531            RestoreRequest(PackageInfo _app, int _version) {
4532                app = _app;
4533                storedAppVersion = _version;
4534            }
4535        }
4536
4537        PerformRestoreTask(IBackupTransport transport, String dirName, IRestoreObserver observer,
4538                long restoreSetToken, PackageInfo targetPackage, int pmToken,
4539                boolean needFullBackup, String[] filterSet) {
4540            mCurrentState = RestoreState.INITIAL;
4541            mFinished = false;
4542            mPmAgent = null;
4543
4544            mTransport = transport;
4545            mObserver = observer;
4546            mToken = restoreSetToken;
4547            mTargetPackage = targetPackage;
4548            mPmToken = pmToken;
4549            mNeedFullBackup = needFullBackup;
4550
4551            if (filterSet != null) {
4552                mFilterSet = new HashSet<String>();
4553                for (String pkg : filterSet) {
4554                    mFilterSet.add(pkg);
4555                }
4556            } else {
4557                mFilterSet = null;
4558            }
4559
4560            mStateDir = new File(mBaseStateDir, dirName);
4561        }
4562
4563        // Execute one tick of whatever state machine the task implements
4564        @Override
4565        public void execute() {
4566            if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4567            switch (mCurrentState) {
4568                case INITIAL:
4569                    beginRestore();
4570                    break;
4571
4572                case DOWNLOAD_DATA:
4573                    downloadRestoreData();
4574                    break;
4575
4576                case PM_METADATA:
4577                    restorePmMetadata();
4578                    break;
4579
4580                case RUNNING_QUEUE:
4581                    restoreNextAgent();
4582                    break;
4583
4584                case FINAL:
4585                    if (!mFinished) finalizeRestore();
4586                    else {
4587                        Slog.e(TAG, "Duplicate finish");
4588                    }
4589                    mFinished = true;
4590                    break;
4591            }
4592        }
4593
4594        // Initialize and set up for the PM metadata restore, which comes first
4595        void beginRestore() {
4596            // Don't account time doing the restore as inactivity of the app
4597            // that has opened a restore session.
4598            mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4599
4600            // Assume error until we successfully init everything
4601            mStatus = BackupConstants.TRANSPORT_ERROR;
4602
4603            try {
4604                // TODO: Log this before getAvailableRestoreSets, somehow
4605                EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
4606
4607                // Get the list of all packages which have backup enabled.
4608                // (Include the Package Manager metadata pseudo-package first.)
4609                mRestorePackages = new ArrayList<PackageInfo>();
4610                PackageInfo omPackage = new PackageInfo();
4611                omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4612                mRestorePackages.add(omPackage);
4613
4614                mAgentPackages = allAgentPackages();
4615                if (mTargetPackage == null) {
4616                    // if there's a filter set, strip out anything that isn't
4617                    // present before proceeding
4618                    if (mFilterSet != null) {
4619                        for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4620                            final PackageInfo pkg = mAgentPackages.get(i);
4621                            if (! mFilterSet.contains(pkg.packageName)) {
4622                                mAgentPackages.remove(i);
4623                            }
4624                        }
4625                        if (MORE_DEBUG) {
4626                            Slog.i(TAG, "Post-filter package set for restore:");
4627                            for (PackageInfo p : mAgentPackages) {
4628                                Slog.i(TAG, "    " + p);
4629                            }
4630                        }
4631                    }
4632                    mRestorePackages.addAll(mAgentPackages);
4633                } else {
4634                    // Just one package to attempt restore of
4635                    mRestorePackages.add(mTargetPackage);
4636                }
4637
4638                // let the observer know that we're running
4639                if (mObserver != null) {
4640                    try {
4641                        // !!! TODO: get an actual count from the transport after
4642                        // its startRestore() runs?
4643                        mObserver.restoreStarting(mRestorePackages.size());
4644                    } catch (RemoteException e) {
4645                        Slog.d(TAG, "Restore observer died at restoreStarting");
4646                        mObserver = null;
4647                    }
4648                }
4649            } catch (RemoteException e) {
4650                // Something has gone catastrophically wrong with the transport
4651                Slog.e(TAG, "Error communicating with transport for restore");
4652                executeNextState(RestoreState.FINAL);
4653                return;
4654            }
4655
4656            mStatus = BackupConstants.TRANSPORT_OK;
4657            executeNextState(RestoreState.DOWNLOAD_DATA);
4658        }
4659
4660        void downloadRestoreData() {
4661            // Note that the download phase can be very time consuming, but we're executing
4662            // it inline here on the looper.  This is "okay" because it is not calling out to
4663            // third party code; the transport is "trusted," and so we assume it is being a
4664            // good citizen and timing out etc when appropriate.
4665            //
4666            // TODO: when appropriate, move the download off the looper and rearrange the
4667            //       error handling around that.
4668            try {
4669                mStatus = mTransport.startRestore(mToken,
4670                        mRestorePackages.toArray(new PackageInfo[0]));
4671                if (mStatus != BackupConstants.TRANSPORT_OK) {
4672                    Slog.e(TAG, "Error starting restore operation");
4673                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4674                    executeNextState(RestoreState.FINAL);
4675                    return;
4676                }
4677            } catch (RemoteException e) {
4678                Slog.e(TAG, "Error communicating with transport for restore");
4679                EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4680                mStatus = BackupConstants.TRANSPORT_ERROR;
4681                executeNextState(RestoreState.FINAL);
4682                return;
4683            }
4684
4685            // Successful download of the data to be parceled out to the apps, so off we go.
4686            executeNextState(RestoreState.PM_METADATA);
4687        }
4688
4689        void restorePmMetadata() {
4690            try {
4691                String packageName = mTransport.nextRestorePackage();
4692                if (packageName == null) {
4693                    Slog.e(TAG, "Error getting first restore package");
4694                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4695                    mStatus = BackupConstants.TRANSPORT_ERROR;
4696                    executeNextState(RestoreState.FINAL);
4697                    return;
4698                } else if (packageName.equals("")) {
4699                    Slog.i(TAG, "No restore data available");
4700                    int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4701                    EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
4702                    mStatus = BackupConstants.TRANSPORT_OK;
4703                    executeNextState(RestoreState.FINAL);
4704                    return;
4705                } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
4706                    Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
4707                            + "\", found only \"" + packageName + "\"");
4708                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
4709                            "Package manager data missing");
4710                    executeNextState(RestoreState.FINAL);
4711                    return;
4712                }
4713
4714                // Pull the Package Manager metadata from the restore set first
4715                PackageInfo omPackage = new PackageInfo();
4716                omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4717                mPmAgent = new PackageManagerBackupAgent(
4718                        mPackageManager, mAgentPackages);
4719                initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
4720                        mNeedFullBackup);
4721                // The PM agent called operationComplete() already, because our invocation
4722                // of it is process-local and therefore synchronous.  That means that a
4723                // RUNNING_QUEUE message is already enqueued.  Only if we're unable to
4724                // proceed with running the queue do we remove that pending message and
4725                // jump straight to the FINAL state.
4726
4727                // Verify that the backup set includes metadata.  If not, we can't do
4728                // signature/version verification etc, so we simply do not proceed with
4729                // the restore operation.
4730                if (!mPmAgent.hasMetadata()) {
4731                    Slog.e(TAG, "No restore metadata available, so not restoring settings");
4732                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
4733                    "Package manager restore metadata missing");
4734                    mStatus = BackupConstants.TRANSPORT_ERROR;
4735                    mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4736                    executeNextState(RestoreState.FINAL);
4737                    return;
4738                }
4739            } catch (RemoteException e) {
4740                Slog.e(TAG, "Error communicating with transport for restore");
4741                EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4742                mStatus = BackupConstants.TRANSPORT_ERROR;
4743                mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4744                executeNextState(RestoreState.FINAL);
4745                return;
4746            }
4747
4748            // Metadata is intact, so we can now run the restore queue.  If we get here,
4749            // we have already enqueued the necessary next-step message on the looper.
4750        }
4751
4752        void restoreNextAgent() {
4753            try {
4754                String packageName = mTransport.nextRestorePackage();
4755
4756                if (packageName == null) {
4757                    Slog.e(TAG, "Error getting next restore package");
4758                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4759                    executeNextState(RestoreState.FINAL);
4760                    return;
4761                } else if (packageName.equals("")) {
4762                    if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4763                    int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4764                    EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4765                    executeNextState(RestoreState.FINAL);
4766                    return;
4767                }
4768
4769                if (mObserver != null) {
4770                    try {
4771                        mObserver.onUpdate(mCount, packageName);
4772                    } catch (RemoteException e) {
4773                        Slog.d(TAG, "Restore observer died in onUpdate");
4774                        mObserver = null;
4775                    }
4776                }
4777
4778                Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4779                if (metaInfo == null) {
4780                    Slog.e(TAG, "Missing metadata for " + packageName);
4781                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4782                            "Package metadata missing");
4783                    executeNextState(RestoreState.RUNNING_QUEUE);
4784                    return;
4785                }
4786
4787                PackageInfo packageInfo;
4788                try {
4789                    int flags = PackageManager.GET_SIGNATURES;
4790                    packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4791                } catch (NameNotFoundException e) {
4792                    Slog.e(TAG, "Invalid package restoring data", e);
4793                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4794                            "Package missing on device");
4795                    executeNextState(RestoreState.RUNNING_QUEUE);
4796                    return;
4797                }
4798
4799                if (packageInfo.applicationInfo.backupAgentName == null
4800                        || "".equals(packageInfo.applicationInfo.backupAgentName)) {
4801                    if (DEBUG) {
4802                        Slog.i(TAG, "Data exists for package " + packageName
4803                                + " but app has no agent; skipping");
4804                    }
4805                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4806                            "Package has no agent");
4807                    executeNextState(RestoreState.RUNNING_QUEUE);
4808                    return;
4809                }
4810
4811                if (metaInfo.versionCode > packageInfo.versionCode) {
4812                    // Data is from a "newer" version of the app than we have currently
4813                    // installed.  If the app has not declared that it is prepared to
4814                    // handle this case, we do not attempt the restore.
4815                    if ((packageInfo.applicationInfo.flags
4816                            & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4817                        String message = "Version " + metaInfo.versionCode
4818                        + " > installed version " + packageInfo.versionCode;
4819                        Slog.w(TAG, "Package " + packageName + ": " + message);
4820                        EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4821                                packageName, message);
4822                        executeNextState(RestoreState.RUNNING_QUEUE);
4823                        return;
4824                    } else {
4825                        if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4826                                + " > installed " + packageInfo.versionCode
4827                                + " but restoreAnyVersion");
4828                    }
4829                }
4830
4831                if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4832                    Slog.w(TAG, "Signature mismatch restoring " + packageName);
4833                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4834                            "Signature mismatch");
4835                    executeNextState(RestoreState.RUNNING_QUEUE);
4836                    return;
4837                }
4838
4839                if (DEBUG) Slog.v(TAG, "Package " + packageName
4840                        + " restore version [" + metaInfo.versionCode
4841                        + "] is compatible with installed version ["
4842                        + packageInfo.versionCode + "]");
4843
4844                // Then set up and bind the agent
4845                IBackupAgent agent = bindToAgentSynchronous(
4846                        packageInfo.applicationInfo,
4847                        IApplicationThread.BACKUP_MODE_INCREMENTAL);
4848                if (agent == null) {
4849                    Slog.w(TAG, "Can't find backup agent for " + packageName);
4850                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4851                            "Restore agent missing");
4852                    executeNextState(RestoreState.RUNNING_QUEUE);
4853                    return;
4854                }
4855
4856                // And then finally start the restore on this agent
4857                try {
4858                    initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4859                    ++mCount;
4860                } catch (Exception e) {
4861                    Slog.e(TAG, "Error when attempting restore: " + e.toString());
4862                    agentErrorCleanup();
4863                    executeNextState(RestoreState.RUNNING_QUEUE);
4864                }
4865            } catch (RemoteException e) {
4866                Slog.e(TAG, "Unable to fetch restore data from transport");
4867                mStatus = BackupConstants.TRANSPORT_ERROR;
4868                executeNextState(RestoreState.FINAL);
4869            }
4870        }
4871
4872        void finalizeRestore() {
4873            if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4874
4875            try {
4876                mTransport.finishRestore();
4877            } catch (RemoteException e) {
4878                Slog.e(TAG, "Error finishing restore", e);
4879            }
4880
4881            if (mObserver != null) {
4882                try {
4883                    mObserver.restoreFinished(mStatus);
4884                } catch (RemoteException e) {
4885                    Slog.d(TAG, "Restore observer died at restoreFinished");
4886                }
4887            }
4888
4889            // If this was a restoreAll operation, record that this was our
4890            // ancestral dataset, as well as the set of apps that are possibly
4891            // restoreable from the dataset
4892            if (mTargetPackage == null && mPmAgent != null) {
4893                mAncestralPackages = mPmAgent.getRestoredPackages();
4894                mAncestralToken = mToken;
4895                writeRestoreTokens();
4896            }
4897
4898            // We must under all circumstances tell the Package Manager to
4899            // proceed with install notifications if it's waiting for us.
4900            if (mPmToken > 0) {
4901                if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4902                try {
4903                    mPackageManagerBinder.finishPackageInstall(mPmToken);
4904                } catch (RemoteException e) { /* can't happen */ }
4905            }
4906
4907            // Furthermore we need to reset the session timeout clock
4908            mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4909            mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4910                    TIMEOUT_RESTORE_INTERVAL);
4911
4912            // done; we can finally release the wakelock
4913            Slog.i(TAG, "Restore complete.");
4914            mWakelock.release();
4915        }
4916
4917        // Call asynchronously into the app, passing it the restore data.  The next step
4918        // after this is always a callback, either operationComplete() or handleTimeout().
4919        void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
4920                boolean needFullBackup) {
4921            mCurrentPackage = app;
4922            final String packageName = app.packageName;
4923
4924            if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
4925
4926            // !!! TODO: get the dirs from the transport
4927            mBackupDataName = new File(mDataDir, packageName + ".restore");
4928            mNewStateName = new File(mStateDir, packageName + ".new");
4929            mSavedStateName = new File(mStateDir, packageName);
4930
4931            final int token = generateToken();
4932            try {
4933                // Run the transport's restore pass
4934                mBackupData = ParcelFileDescriptor.open(mBackupDataName,
4935                            ParcelFileDescriptor.MODE_READ_WRITE |
4936                            ParcelFileDescriptor.MODE_CREATE |
4937                            ParcelFileDescriptor.MODE_TRUNCATE);
4938
4939                if (!SELinux.restorecon(mBackupDataName)) {
4940                    Slog.e(TAG, "SElinux restorecon failed for " + mBackupDataName);
4941                }
4942
4943                if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
4944                    // Transport-level failure, so we wind everything up and
4945                    // terminate the restore operation.
4946                    Slog.e(TAG, "Error getting restore data for " + packageName);
4947                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4948                    mBackupData.close();
4949                    mBackupDataName.delete();
4950                    executeNextState(RestoreState.FINAL);
4951                    return;
4952                }
4953
4954                // Okay, we have the data.  Now have the agent do the restore.
4955                mBackupData.close();
4956                mBackupData = ParcelFileDescriptor.open(mBackupDataName,
4957                            ParcelFileDescriptor.MODE_READ_ONLY);
4958
4959                mNewState = ParcelFileDescriptor.open(mNewStateName,
4960                            ParcelFileDescriptor.MODE_READ_WRITE |
4961                            ParcelFileDescriptor.MODE_CREATE |
4962                            ParcelFileDescriptor.MODE_TRUNCATE);
4963
4964                // Kick off the restore, checking for hung agents
4965                prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4966                agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
4967            } catch (Exception e) {
4968                Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
4969                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
4970                agentErrorCleanup();    // clears any pending timeout messages as well
4971
4972                // After a restore failure we go back to running the queue.  If there
4973                // are no more packages to be restored that will be handled by the
4974                // next step.
4975                executeNextState(RestoreState.RUNNING_QUEUE);
4976            }
4977        }
4978
4979        void agentErrorCleanup() {
4980            // If the agent fails restore, it might have put the app's data
4981            // into an incoherent state.  For consistency we wipe its data
4982            // again in this case before continuing with normal teardown
4983            clearApplicationDataSynchronous(mCurrentPackage.packageName);
4984            agentCleanup();
4985        }
4986
4987        void agentCleanup() {
4988            mBackupDataName.delete();
4989            try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4990            try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4991            mBackupData = mNewState = null;
4992
4993            // if everything went okay, remember the recorded state now
4994            //
4995            // !!! TODO: the restored data should be migrated on the server
4996            // side into the current dataset.  In that case the new state file
4997            // we just created would reflect the data already extant in the
4998            // backend, so there'd be nothing more to do.  Until that happens,
4999            // however, we need to make sure that we record the data to the
5000            // current backend dataset.  (Yes, this means shipping the data over
5001            // the wire in both directions.  That's bad, but consistency comes
5002            // first, then efficiency.)  Once we introduce server-side data
5003            // migration to the newly-restored device's dataset, we will change
5004            // the following from a discard of the newly-written state to the
5005            // "correct" operation of renaming into the canonical state blob.
5006            mNewStateName.delete();                      // TODO: remove; see above comment
5007            //mNewStateName.renameTo(mSavedStateName);   // TODO: replace with this
5008
5009            // If this wasn't the PM pseudopackage, tear down the agent side
5010            if (mCurrentPackage.applicationInfo != null) {
5011                // unbind and tidy up even on timeout or failure
5012                try {
5013                    mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
5014
5015                    // The agent was probably running with a stub Application object,
5016                    // which isn't a valid run mode for the main app logic.  Shut
5017                    // down the app so that next time it's launched, it gets the
5018                    // usual full initialization.  Note that this is only done for
5019                    // full-system restores: when a single app has requested a restore,
5020                    // it is explicitly not killed following that operation.
5021                    if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
5022                            & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
5023                        if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
5024                                + mCurrentPackage.applicationInfo.processName);
5025                        mActivityManager.killApplicationProcess(
5026                                mCurrentPackage.applicationInfo.processName,
5027                                mCurrentPackage.applicationInfo.uid);
5028                    }
5029                } catch (RemoteException e) {
5030                    // can't happen; we run in the same process as the activity manager
5031                }
5032            }
5033
5034            // The caller is responsible for reestablishing the state machine; our
5035            // responsibility here is to clear the decks for whatever comes next.
5036            mBackupHandler.removeMessages(MSG_TIMEOUT, this);
5037            synchronized (mCurrentOpLock) {
5038                mCurrentOperations.clear();
5039            }
5040        }
5041
5042        // A call to agent.doRestore() has been positively acknowledged as complete
5043        @Override
5044        public void operationComplete() {
5045            int size = (int) mBackupDataName.length();
5046            EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
5047            // Just go back to running the restore queue
5048            agentCleanup();
5049
5050            executeNextState(RestoreState.RUNNING_QUEUE);
5051        }
5052
5053        // A call to agent.doRestore() has timed out
5054        @Override
5055        public void handleTimeout() {
5056            Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
5057            EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
5058                    mCurrentPackage.packageName, "restore timeout");
5059            // Handle like an agent that threw on invocation: wipe it and go on to the next
5060            agentErrorCleanup();
5061            executeNextState(RestoreState.RUNNING_QUEUE);
5062        }
5063
5064        void executeNextState(RestoreState nextState) {
5065            if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
5066                    + this + " nextState=" + nextState);
5067            mCurrentState = nextState;
5068            Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
5069            mBackupHandler.sendMessage(msg);
5070        }
5071    }
5072
5073    class PerformClearTask implements Runnable {
5074        IBackupTransport mTransport;
5075        PackageInfo mPackage;
5076
5077        PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
5078            mTransport = transport;
5079            mPackage = packageInfo;
5080        }
5081
5082        public void run() {
5083            try {
5084                // Clear the on-device backup state to ensure a full backup next time
5085                File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
5086                File stateFile = new File(stateDir, mPackage.packageName);
5087                stateFile.delete();
5088
5089                // Tell the transport to remove all the persistent storage for the app
5090                // TODO - need to handle failures
5091                mTransport.clearBackupData(mPackage);
5092            } catch (RemoteException e) {
5093                // can't happen; the transport is local
5094            } catch (Exception e) {
5095                Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage);
5096            } finally {
5097                try {
5098                    // TODO - need to handle failures
5099                    mTransport.finishBackup();
5100                } catch (RemoteException e) {
5101                    // can't happen; the transport is local
5102                }
5103
5104                // Last but not least, release the cpu
5105                mWakelock.release();
5106            }
5107        }
5108    }
5109
5110    class PerformInitializeTask implements Runnable {
5111        HashSet<String> mQueue;
5112
5113        PerformInitializeTask(HashSet<String> transportNames) {
5114            mQueue = transportNames;
5115        }
5116
5117        public void run() {
5118            try {
5119                for (String transportName : mQueue) {
5120                    IBackupTransport transport = getTransport(transportName);
5121                    if (transport == null) {
5122                        Slog.e(TAG, "Requested init for " + transportName + " but not found");
5123                        continue;
5124                    }
5125
5126                    Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
5127                    EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
5128                    long startRealtime = SystemClock.elapsedRealtime();
5129                    int status = transport.initializeDevice();
5130
5131                    if (status == BackupConstants.TRANSPORT_OK) {
5132                        status = transport.finishBackup();
5133                    }
5134
5135                    // Okay, the wipe really happened.  Clean up our local bookkeeping.
5136                    if (status == BackupConstants.TRANSPORT_OK) {
5137                        Slog.i(TAG, "Device init successful");
5138                        int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
5139                        EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
5140                        resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
5141                        EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
5142                        synchronized (mQueueLock) {
5143                            recordInitPendingLocked(false, transportName);
5144                        }
5145                    } else {
5146                        // If this didn't work, requeue this one and try again
5147                        // after a suitable interval
5148                        Slog.e(TAG, "Transport error in initializeDevice()");
5149                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
5150                        synchronized (mQueueLock) {
5151                            recordInitPendingLocked(true, transportName);
5152                        }
5153                        // do this via another alarm to make sure of the wakelock states
5154                        long delay = transport.requestBackupTime();
5155                        if (DEBUG) Slog.w(TAG, "init failed on "
5156                                + transportName + " resched in " + delay);
5157                        mAlarmManager.set(AlarmManager.RTC_WAKEUP,
5158                                System.currentTimeMillis() + delay, mRunInitIntent);
5159                    }
5160                }
5161            } catch (RemoteException e) {
5162                // can't happen; the transports are local
5163            } catch (Exception e) {
5164                Slog.e(TAG, "Unexpected error performing init", e);
5165            } finally {
5166                // Done; release the wakelock
5167                mWakelock.release();
5168            }
5169        }
5170    }
5171
5172    private void dataChangedImpl(String packageName) {
5173        HashSet<String> targets = dataChangedTargets(packageName);
5174        dataChangedImpl(packageName, targets);
5175    }
5176
5177    private void dataChangedImpl(String packageName, HashSet<String> targets) {
5178        // Record that we need a backup pass for the caller.  Since multiple callers
5179        // may share a uid, we need to note all candidates within that uid and schedule
5180        // a backup pass for each of them.
5181        EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
5182
5183        if (targets == null) {
5184            Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
5185                   + " uid=" + Binder.getCallingUid());
5186            return;
5187        }
5188
5189        synchronized (mQueueLock) {
5190            // Note that this client has made data changes that need to be backed up
5191            if (targets.contains(packageName)) {
5192                // Add the caller to the set of pending backups.  If there is
5193                // one already there, then overwrite it, but no harm done.
5194                BackupRequest req = new BackupRequest(packageName);
5195                if (mPendingBackups.put(packageName, req) == null) {
5196                    if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
5197
5198                    // Journal this request in case of crash.  The put()
5199                    // operation returned null when this package was not already
5200                    // in the set; we want to avoid touching the disk redundantly.
5201                    writeToJournalLocked(packageName);
5202
5203                    if (MORE_DEBUG) {
5204                        int numKeys = mPendingBackups.size();
5205                        Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
5206                        for (BackupRequest b : mPendingBackups.values()) {
5207                            Slog.d(TAG, "    + " + b);
5208                        }
5209                    }
5210                }
5211            }
5212        }
5213    }
5214
5215    // Note: packageName is currently unused, but may be in the future
5216    private HashSet<String> dataChangedTargets(String packageName) {
5217        // If the caller does not hold the BACKUP permission, it can only request a
5218        // backup of its own data.
5219        if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
5220                Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
5221            synchronized (mBackupParticipants) {
5222                return mBackupParticipants.get(Binder.getCallingUid());
5223            }
5224        }
5225
5226        // a caller with full permission can ask to back up any participating app
5227        // !!! TODO: allow backup of ANY app?
5228        HashSet<String> targets = new HashSet<String>();
5229        synchronized (mBackupParticipants) {
5230            int N = mBackupParticipants.size();
5231            for (int i = 0; i < N; i++) {
5232                HashSet<String> s = mBackupParticipants.valueAt(i);
5233                if (s != null) {
5234                    targets.addAll(s);
5235                }
5236            }
5237        }
5238        return targets;
5239    }
5240
5241    private void writeToJournalLocked(String str) {
5242        RandomAccessFile out = null;
5243        try {
5244            if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
5245            out = new RandomAccessFile(mJournal, "rws");
5246            out.seek(out.length());
5247            out.writeUTF(str);
5248        } catch (IOException e) {
5249            Slog.e(TAG, "Can't write " + str + " to backup journal", e);
5250            mJournal = null;
5251        } finally {
5252            try { if (out != null) out.close(); } catch (IOException e) {}
5253        }
5254    }
5255
5256    // ----- IBackupManager binder interface -----
5257
5258    public void dataChanged(final String packageName) {
5259        final int callingUserHandle = UserHandle.getCallingUserId();
5260        if (callingUserHandle != UserHandle.USER_OWNER) {
5261            // App is running under a non-owner user profile.  For now, we do not back
5262            // up data from secondary user profiles.
5263            // TODO: backups for all user profiles.
5264            if (MORE_DEBUG) {
5265                Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
5266                        + callingUserHandle);
5267            }
5268            return;
5269        }
5270
5271        final HashSet<String> targets = dataChangedTargets(packageName);
5272        if (targets == null) {
5273            Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
5274                   + " uid=" + Binder.getCallingUid());
5275            return;
5276        }
5277
5278        mBackupHandler.post(new Runnable() {
5279                public void run() {
5280                    dataChangedImpl(packageName, targets);
5281                }
5282            });
5283    }
5284
5285    // Clear the given package's backup data from the current transport
5286    public void clearBackupData(String transportName, String packageName) {
5287        if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName + " on " + transportName);
5288        PackageInfo info;
5289        try {
5290            info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
5291        } catch (NameNotFoundException e) {
5292            Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
5293            return;
5294        }
5295
5296        // If the caller does not hold the BACKUP permission, it can only request a
5297        // wipe of its own backed-up data.
5298        HashSet<String> apps;
5299        if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
5300                Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
5301            apps = mBackupParticipants.get(Binder.getCallingUid());
5302        } else {
5303            // a caller with full permission can ask to back up any participating app
5304            // !!! TODO: allow data-clear of ANY app?
5305            if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
5306            apps = new HashSet<String>();
5307            int N = mBackupParticipants.size();
5308            for (int i = 0; i < N; i++) {
5309                HashSet<String> s = mBackupParticipants.valueAt(i);
5310                if (s != null) {
5311                    apps.addAll(s);
5312                }
5313            }
5314        }
5315
5316        // Is the given app an available participant?
5317        if (apps.contains(packageName)) {
5318            // found it; fire off the clear request
5319            if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
5320            mBackupHandler.removeMessages(MSG_RETRY_CLEAR);
5321            synchronized (mQueueLock) {
5322                final IBackupTransport transport = getTransport(transportName);
5323                if (transport == null) {
5324                    // transport is currently unavailable -- make sure to retry
5325                    Message msg = mBackupHandler.obtainMessage(MSG_RETRY_CLEAR,
5326                            new ClearRetryParams(transportName, packageName));
5327                    mBackupHandler.sendMessageDelayed(msg, TRANSPORT_RETRY_INTERVAL);
5328                    return;
5329                }
5330                long oldId = Binder.clearCallingIdentity();
5331                mWakelock.acquire();
5332                Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
5333                        new ClearParams(transport, info));
5334                mBackupHandler.sendMessage(msg);
5335                Binder.restoreCallingIdentity(oldId);
5336            }
5337        }
5338    }
5339
5340    // Run a backup pass immediately for any applications that have declared
5341    // that they have pending updates.
5342    public void backupNow() {
5343        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
5344
5345        if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
5346        synchronized (mQueueLock) {
5347            // Because the alarms we are using can jitter, and we want an *immediate*
5348            // backup pass to happen, we restart the timer beginning with "next time,"
5349            // then manually fire the backup trigger intent ourselves.
5350            startBackupAlarmsLocked(BACKUP_INTERVAL);
5351            try {
5352                mRunBackupIntent.send();
5353            } catch (PendingIntent.CanceledException e) {
5354                // should never happen
5355                Slog.e(TAG, "run-backup intent cancelled!");
5356            }
5357        }
5358    }
5359
5360    boolean deviceIsProvisioned() {
5361        final ContentResolver resolver = mContext.getContentResolver();
5362        return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
5363    }
5364
5365    // Run a *full* backup pass for the given package, writing the resulting data stream
5366    // to the supplied file descriptor.  This method is synchronous and does not return
5367    // to the caller until the backup has been completed.
5368    public void fullBackup(ParcelFileDescriptor fd, boolean includeApks,
5369            boolean includeObbs, boolean includeShared,
5370            boolean doAllApps, boolean includeSystem, String[] pkgList) {
5371        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
5372
5373        final int callingUserHandle = UserHandle.getCallingUserId();
5374        if (callingUserHandle != UserHandle.USER_OWNER) {
5375            throw new IllegalStateException("Backup supported only for the device owner");
5376        }
5377
5378        // Validate
5379        if (!doAllApps) {
5380            if (!includeShared) {
5381                // If we're backing up shared data (sdcard or equivalent), then we can run
5382                // without any supplied app names.  Otherwise, we'd be doing no work, so
5383                // report the error.
5384                if (pkgList == null || pkgList.length == 0) {
5385                    throw new IllegalArgumentException(
5386                            "Backup requested but neither shared nor any apps named");
5387                }
5388            }
5389        }
5390
5391        long oldId = Binder.clearCallingIdentity();
5392        try {
5393            // Doesn't make sense to do a full backup prior to setup
5394            if (!deviceIsProvisioned()) {
5395                Slog.i(TAG, "Full backup not supported before setup");
5396                return;
5397            }
5398
5399            if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
5400                    + " obb=" + includeObbs + " shared=" + includeShared + " all=" + doAllApps
5401                    + " pkgs=" + pkgList);
5402            Slog.i(TAG, "Beginning full backup...");
5403
5404            FullBackupParams params = new FullBackupParams(fd, includeApks, includeObbs,
5405                    includeShared, doAllApps, includeSystem, pkgList);
5406            final int token = generateToken();
5407            synchronized (mFullConfirmations) {
5408                mFullConfirmations.put(token, params);
5409            }
5410
5411            // start up the confirmation UI
5412            if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
5413            if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
5414                Slog.e(TAG, "Unable to launch full backup confirmation");
5415                mFullConfirmations.delete(token);
5416                return;
5417            }
5418
5419            // make sure the screen is lit for the user interaction
5420            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5421
5422            // start the confirmation countdown
5423            startConfirmationTimeout(token, params);
5424
5425            // wait for the backup to be performed
5426            if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5427            waitForCompletion(params);
5428        } finally {
5429            try {
5430                fd.close();
5431            } catch (IOException e) {
5432                // just eat it
5433            }
5434            Binder.restoreCallingIdentity(oldId);
5435            Slog.d(TAG, "Full backup processing complete.");
5436        }
5437    }
5438
5439    public void fullRestore(ParcelFileDescriptor fd) {
5440        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
5441
5442        final int callingUserHandle = UserHandle.getCallingUserId();
5443        if (callingUserHandle != UserHandle.USER_OWNER) {
5444            throw new IllegalStateException("Restore supported only for the device owner");
5445        }
5446
5447        long oldId = Binder.clearCallingIdentity();
5448
5449        try {
5450            // Check whether the device has been provisioned -- we don't handle
5451            // full restores prior to completing the setup process.
5452            if (!deviceIsProvisioned()) {
5453                Slog.i(TAG, "Full restore not permitted before setup");
5454                return;
5455            }
5456
5457            Slog.i(TAG, "Beginning full restore...");
5458
5459            FullRestoreParams params = new FullRestoreParams(fd);
5460            final int token = generateToken();
5461            synchronized (mFullConfirmations) {
5462                mFullConfirmations.put(token, params);
5463            }
5464
5465            // start up the confirmation UI
5466            if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5467            if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5468                Slog.e(TAG, "Unable to launch full restore confirmation");
5469                mFullConfirmations.delete(token);
5470                return;
5471            }
5472
5473            // make sure the screen is lit for the user interaction
5474            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5475
5476            // start the confirmation countdown
5477            startConfirmationTimeout(token, params);
5478
5479            // wait for the restore to be performed
5480            if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5481            waitForCompletion(params);
5482        } finally {
5483            try {
5484                fd.close();
5485            } catch (IOException e) {
5486                Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5487            }
5488            Binder.restoreCallingIdentity(oldId);
5489            Slog.i(TAG, "Full restore processing complete.");
5490        }
5491    }
5492
5493    boolean startConfirmationUi(int token, String action) {
5494        try {
5495            Intent confIntent = new Intent(action);
5496            confIntent.setClassName("com.android.backupconfirm",
5497                    "com.android.backupconfirm.BackupRestoreConfirmation");
5498            confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5499            confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5500            mContext.startActivity(confIntent);
5501        } catch (ActivityNotFoundException e) {
5502            return false;
5503        }
5504        return true;
5505    }
5506
5507    void startConfirmationTimeout(int token, FullParams params) {
5508        if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
5509                + TIMEOUT_FULL_CONFIRMATION + " millis");
5510        Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5511                token, 0, params);
5512        mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
5513    }
5514
5515    void waitForCompletion(FullParams params) {
5516        synchronized (params.latch) {
5517            while (params.latch.get() == false) {
5518                try {
5519                    params.latch.wait();
5520                } catch (InterruptedException e) { /* never interrupted */ }
5521            }
5522        }
5523    }
5524
5525    void signalFullBackupRestoreCompletion(FullParams params) {
5526        synchronized (params.latch) {
5527            params.latch.set(true);
5528            params.latch.notifyAll();
5529        }
5530    }
5531
5532    // Confirm that the previously-requested full backup/restore operation can proceed.  This
5533    // is used to require a user-facing disclosure about the operation.
5534    @Override
5535    public void acknowledgeFullBackupOrRestore(int token, boolean allow,
5536            String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
5537        if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5538                + " allow=" + allow);
5539
5540        // TODO: possibly require not just this signature-only permission, but even
5541        // require that the specific designated confirmation-UI app uid is the caller?
5542        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
5543
5544        long oldId = Binder.clearCallingIdentity();
5545        try {
5546
5547            FullParams params;
5548            synchronized (mFullConfirmations) {
5549                params = mFullConfirmations.get(token);
5550                if (params != null) {
5551                    mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5552                    mFullConfirmations.delete(token);
5553
5554                    if (allow) {
5555                        final int verb = params instanceof FullBackupParams
5556                                ? MSG_RUN_FULL_BACKUP
5557                                : MSG_RUN_FULL_RESTORE;
5558
5559                        params.observer = observer;
5560                        params.curPassword = curPassword;
5561
5562                        boolean isEncrypted;
5563                        try {
5564                            isEncrypted = (mMountService.getEncryptionState() !=
5565                                    IMountService.ENCRYPTION_STATE_NONE);
5566                            if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5567                        } catch (RemoteException e) {
5568                            // couldn't contact the mount service; fail "safe" and assume encryption
5569                            Slog.e(TAG, "Unable to contact mount service!");
5570                            isEncrypted = true;
5571                        }
5572                        params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
5573
5574                        if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
5575                        mWakelock.acquire();
5576                        Message msg = mBackupHandler.obtainMessage(verb, params);
5577                        mBackupHandler.sendMessage(msg);
5578                    } else {
5579                        Slog.w(TAG, "User rejected full backup/restore operation");
5580                        // indicate completion without having actually transferred any data
5581                        signalFullBackupRestoreCompletion(params);
5582                    }
5583                } else {
5584                    Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5585                }
5586            }
5587        } finally {
5588            Binder.restoreCallingIdentity(oldId);
5589        }
5590    }
5591
5592    // Enable/disable the backup service
5593    @Override
5594    public void setBackupEnabled(boolean enable) {
5595        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5596                "setBackupEnabled");
5597
5598        Slog.i(TAG, "Backup enabled => " + enable);
5599
5600        long oldId = Binder.clearCallingIdentity();
5601        try {
5602            boolean wasEnabled = mEnabled;
5603            synchronized (this) {
5604                Settings.Secure.putInt(mContext.getContentResolver(),
5605                        Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
5606                mEnabled = enable;
5607            }
5608
5609            synchronized (mQueueLock) {
5610                if (enable && !wasEnabled && mProvisioned) {
5611                    // if we've just been enabled, start scheduling backup passes
5612                    startBackupAlarmsLocked(BACKUP_INTERVAL);
5613                } else if (!enable) {
5614                    // No longer enabled, so stop running backups
5615                    if (DEBUG) Slog.i(TAG, "Opting out of backup");
5616
5617                    mAlarmManager.cancel(mRunBackupIntent);
5618
5619                    // This also constitutes an opt-out, so we wipe any data for
5620                    // this device from the backend.  We start that process with
5621                    // an alarm in order to guarantee wakelock states.
5622                    if (wasEnabled && mProvisioned) {
5623                        // NOTE: we currently flush every registered transport, not just
5624                        // the currently-active one.
5625                        HashSet<String> allTransports;
5626                        synchronized (mTransports) {
5627                            allTransports = new HashSet<String>(mTransports.keySet());
5628                        }
5629                        // build the set of transports for which we are posting an init
5630                        for (String transport : allTransports) {
5631                            recordInitPendingLocked(true, transport);
5632                        }
5633                        mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5634                                mRunInitIntent);
5635                    }
5636                }
5637            }
5638        } finally {
5639            Binder.restoreCallingIdentity(oldId);
5640        }
5641    }
5642
5643    // Enable/disable automatic restore of app data at install time
5644    public void setAutoRestore(boolean doAutoRestore) {
5645        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5646                "setAutoRestore");
5647
5648        Slog.i(TAG, "Auto restore => " + doAutoRestore);
5649
5650        synchronized (this) {
5651            Settings.Secure.putInt(mContext.getContentResolver(),
5652                    Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5653            mAutoRestore = doAutoRestore;
5654        }
5655    }
5656
5657    // Mark the backup service as having been provisioned
5658    public void setBackupProvisioned(boolean available) {
5659        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5660                "setBackupProvisioned");
5661        /*
5662         * This is now a no-op; provisioning is simply the device's own setup state.
5663         */
5664    }
5665
5666    private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
5667        // We used to use setInexactRepeating(), but that may be linked to
5668        // backups running at :00 more often than not, creating load spikes.
5669        // Schedule at an exact time for now, and also add a bit of "fuzz".
5670
5671        Random random = new Random();
5672        long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5673                random.nextInt(FUZZ_MILLIS);
5674        mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5675                BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
5676        mNextBackupPass = when;
5677    }
5678
5679    // Report whether the backup mechanism is currently enabled
5680    public boolean isBackupEnabled() {
5681        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
5682        return mEnabled;    // no need to synchronize just to read it
5683    }
5684
5685    // Report the name of the currently active transport
5686    public String getCurrentTransport() {
5687        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5688                "getCurrentTransport");
5689        if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
5690        return mCurrentTransport;
5691    }
5692
5693    // Report all known, available backup transports
5694    public String[] listAllTransports() {
5695        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
5696
5697        String[] list = null;
5698        ArrayList<String> known = new ArrayList<String>();
5699        for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5700            if (entry.getValue() != null) {
5701                known.add(entry.getKey());
5702            }
5703        }
5704
5705        if (known.size() > 0) {
5706            list = new String[known.size()];
5707            known.toArray(list);
5708        }
5709        return list;
5710    }
5711
5712    // Select which transport to use for the next backup operation.  If the given
5713    // name is not one of the available transports, no action is taken and the method
5714    // returns null.
5715    public String selectBackupTransport(String transport) {
5716        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
5717
5718        synchronized (mTransports) {
5719            String prevTransport = null;
5720            if (mTransports.get(transport) != null) {
5721                prevTransport = mCurrentTransport;
5722                mCurrentTransport = transport;
5723                Settings.Secure.putString(mContext.getContentResolver(),
5724                        Settings.Secure.BACKUP_TRANSPORT, transport);
5725                Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
5726                        + " returning " + prevTransport);
5727            } else {
5728                Slog.w(TAG, "Attempt to select unavailable transport " + transport);
5729            }
5730            return prevTransport;
5731        }
5732    }
5733
5734    // Supply the configuration Intent for the given transport.  If the name is not one
5735    // of the available transports, or if the transport does not supply any configuration
5736    // UI, the method returns null.
5737    public Intent getConfigurationIntent(String transportName) {
5738        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5739                "getConfigurationIntent");
5740
5741        synchronized (mTransports) {
5742            final IBackupTransport transport = mTransports.get(transportName);
5743            if (transport != null) {
5744                try {
5745                    final Intent intent = transport.configurationIntent();
5746                    if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
5747                            + intent);
5748                    return intent;
5749                } catch (RemoteException e) {
5750                    /* fall through to return null */
5751                }
5752            }
5753        }
5754
5755        return null;
5756    }
5757
5758    // Supply the configuration summary string for the given transport.  If the name is
5759    // not one of the available transports, or if the transport does not supply any
5760    // summary / destination string, the method can return null.
5761    //
5762    // This string is used VERBATIM as the summary text of the relevant Settings item!
5763    public String getDestinationString(String transportName) {
5764        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5765                "getDestinationString");
5766
5767        synchronized (mTransports) {
5768            final IBackupTransport transport = mTransports.get(transportName);
5769            if (transport != null) {
5770                try {
5771                    final String text = transport.currentDestinationString();
5772                    if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
5773                    return text;
5774                } catch (RemoteException e) {
5775                    /* fall through to return null */
5776                }
5777            }
5778        }
5779
5780        return null;
5781    }
5782
5783    // Callback: a requested backup agent has been instantiated.  This should only
5784    // be called from the Activity Manager.
5785    public void agentConnected(String packageName, IBinder agentBinder) {
5786        synchronized(mAgentConnectLock) {
5787            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5788                Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
5789                IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5790                mConnectedAgent = agent;
5791                mConnecting = false;
5792            } else {
5793                Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
5794                        + " claiming agent connected");
5795            }
5796            mAgentConnectLock.notifyAll();
5797        }
5798    }
5799
5800    // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5801    // If the agent failed to come up in the first place, the agentBinder argument
5802    // will be null.  This should only be called from the Activity Manager.
5803    public void agentDisconnected(String packageName) {
5804        // TODO: handle backup being interrupted
5805        synchronized(mAgentConnectLock) {
5806            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5807                mConnectedAgent = null;
5808                mConnecting = false;
5809            } else {
5810                Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
5811                        + " claiming agent disconnected");
5812            }
5813            mAgentConnectLock.notifyAll();
5814        }
5815    }
5816
5817    // An application being installed will need a restore pass, then the Package Manager
5818    // will need to be told when the restore is finished.
5819    public void restoreAtInstall(String packageName, int token) {
5820        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
5821            Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
5822                    + " attemping install-time restore");
5823            return;
5824        }
5825
5826        boolean skip = false;
5827
5828        long restoreSet = getAvailableRestoreToken(packageName);
5829        if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
5830                + " token=" + Integer.toHexString(token)
5831                + " restoreSet=" + Long.toHexString(restoreSet));
5832        if (restoreSet == 0) {
5833            if (MORE_DEBUG) Slog.i(TAG, "No restore set");
5834            skip = true;
5835        }
5836
5837        // Do we have a transport to fetch data for us?
5838        IBackupTransport transport = getTransport(mCurrentTransport);
5839        if (transport == null) {
5840            if (DEBUG) Slog.w(TAG, "No transport");
5841            skip = true;
5842        }
5843
5844        if (!skip && mAutoRestore && mProvisioned) {
5845            try {
5846                // okay, we're going to attempt a restore of this package from this restore set.
5847                // The eventual message back into the Package Manager to run the post-install
5848                // steps for 'token' will be issued from the restore handling code.
5849
5850                // This can throw and so *must* happen before the wakelock is acquired
5851                String dirName = transport.transportDirName();
5852
5853                // We can use a synthetic PackageInfo here because:
5854                //   1. We know it's valid, since the Package Manager supplied the name
5855                //   2. Only the packageName field will be used by the restore code
5856                PackageInfo pkg = new PackageInfo();
5857                pkg.packageName = packageName;
5858
5859                mWakelock.acquire();
5860                Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5861                msg.obj = new RestoreParams(transport, dirName, null,
5862                        restoreSet, pkg, token, true);
5863                mBackupHandler.sendMessage(msg);
5864            } catch (RemoteException e) {
5865                // Binding to the transport broke; back off and proceed with the installation.
5866                Slog.e(TAG, "Unable to contact transport");
5867                skip = true;
5868            }
5869        }
5870
5871        if (skip) {
5872            // Auto-restore disabled or no way to attempt a restore; just tell the Package
5873            // Manager to proceed with the post-install handling for this package.
5874            if (DEBUG) Slog.v(TAG, "Skipping");
5875            try {
5876                mPackageManagerBinder.finishPackageInstall(token);
5877            } catch (RemoteException e) { /* can't happen */ }
5878        }
5879    }
5880
5881    // Hand off a restore session
5882    public IRestoreSession beginRestoreSession(String packageName, String transport) {
5883        if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5884                + " transport=" + transport);
5885
5886        boolean needPermission = true;
5887        if (transport == null) {
5888            transport = mCurrentTransport;
5889
5890            if (packageName != null) {
5891                PackageInfo app = null;
5892                try {
5893                    app = mPackageManager.getPackageInfo(packageName, 0);
5894                } catch (NameNotFoundException nnf) {
5895                    Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5896                    throw new IllegalArgumentException("Package " + packageName + " not found");
5897                }
5898
5899                if (app.applicationInfo.uid == Binder.getCallingUid()) {
5900                    // So: using the current active transport, and the caller has asked
5901                    // that its own package will be restored.  In this narrow use case
5902                    // we do not require the caller to hold the permission.
5903                    needPermission = false;
5904                }
5905            }
5906        }
5907
5908        if (needPermission) {
5909            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5910                    "beginRestoreSession");
5911        } else {
5912            if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5913        }
5914
5915        synchronized(this) {
5916            if (mActiveRestoreSession != null) {
5917                Slog.d(TAG, "Restore session requested but one already active");
5918                return null;
5919            }
5920            mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
5921            mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
5922        }
5923        return mActiveRestoreSession;
5924    }
5925
5926    void clearRestoreSession(ActiveRestoreSession currentSession) {
5927        synchronized(this) {
5928            if (currentSession != mActiveRestoreSession) {
5929                Slog.e(TAG, "ending non-current restore session");
5930            } else {
5931                if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5932                mActiveRestoreSession = null;
5933                mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5934            }
5935        }
5936    }
5937
5938    // Note that a currently-active backup agent has notified us that it has
5939    // completed the given outstanding asynchronous backup/restore operation.
5940    @Override
5941    public void opComplete(int token) {
5942        if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5943        Operation op = null;
5944        synchronized (mCurrentOpLock) {
5945            op = mCurrentOperations.get(token);
5946            if (op != null) {
5947                op.state = OP_ACKNOWLEDGED;
5948            }
5949            mCurrentOpLock.notifyAll();
5950        }
5951
5952        // The completion callback, if any, is invoked on the handler
5953        if (op != null && op.callback != null) {
5954            Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5955            mBackupHandler.sendMessage(msg);
5956        }
5957    }
5958
5959    // ----- Restore session -----
5960
5961    class ActiveRestoreSession extends IRestoreSession.Stub {
5962        private static final String TAG = "RestoreSession";
5963
5964        private String mPackageName;
5965        private IBackupTransport mRestoreTransport = null;
5966        RestoreSet[] mRestoreSets = null;
5967        boolean mEnded = false;
5968
5969        ActiveRestoreSession(String packageName, String transport) {
5970            mPackageName = packageName;
5971            mRestoreTransport = getTransport(transport);
5972        }
5973
5974        // --- Binder interface ---
5975        public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
5976            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5977                    "getAvailableRestoreSets");
5978            if (observer == null) {
5979                throw new IllegalArgumentException("Observer must not be null");
5980            }
5981
5982            if (mEnded) {
5983                throw new IllegalStateException("Restore session already ended");
5984            }
5985
5986            long oldId = Binder.clearCallingIdentity();
5987            try {
5988                if (mRestoreTransport == null) {
5989                    Slog.w(TAG, "Null transport getting restore sets");
5990                    return -1;
5991                }
5992                // spin off the transport request to our service thread
5993                mWakelock.acquire();
5994                Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5995                        new RestoreGetSetsParams(mRestoreTransport, this, observer));
5996                mBackupHandler.sendMessage(msg);
5997                return 0;
5998            } catch (Exception e) {
5999                Slog.e(TAG, "Error in getAvailableRestoreSets", e);
6000                return -1;
6001            } finally {
6002                Binder.restoreCallingIdentity(oldId);
6003            }
6004        }
6005
6006        public synchronized int restoreAll(long token, IRestoreObserver observer) {
6007            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
6008                    "performRestore");
6009
6010            if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
6011                    + " observer=" + observer);
6012
6013            if (mEnded) {
6014                throw new IllegalStateException("Restore session already ended");
6015            }
6016
6017            if (mRestoreTransport == null || mRestoreSets == null) {
6018                Slog.e(TAG, "Ignoring restoreAll() with no restore set");
6019                return -1;
6020            }
6021
6022            if (mPackageName != null) {
6023                Slog.e(TAG, "Ignoring restoreAll() on single-package session");
6024                return -1;
6025            }
6026
6027            String dirName;
6028            try {
6029                dirName = mRestoreTransport.transportDirName();
6030            } catch (RemoteException e) {
6031                // Transport went AWOL; fail.
6032                Slog.e(TAG, "Unable to contact transport for restore");
6033                return -1;
6034            }
6035
6036            synchronized (mQueueLock) {
6037                for (int i = 0; i < mRestoreSets.length; i++) {
6038                    if (token == mRestoreSets[i].token) {
6039                        long oldId = Binder.clearCallingIdentity();
6040                        mWakelock.acquire();
6041                        Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
6042                        msg.obj = new RestoreParams(mRestoreTransport, dirName,
6043                                observer, token, true);
6044                        mBackupHandler.sendMessage(msg);
6045                        Binder.restoreCallingIdentity(oldId);
6046                        return 0;
6047                    }
6048                }
6049            }
6050
6051            Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
6052            return -1;
6053        }
6054
6055        public synchronized int restoreSome(long token, IRestoreObserver observer,
6056                String[] packages) {
6057            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
6058                    "performRestore");
6059
6060            if (DEBUG) {
6061                StringBuilder b = new StringBuilder(128);
6062                b.append("restoreSome token=");
6063                b.append(Long.toHexString(token));
6064                b.append(" observer=");
6065                b.append(observer.toString());
6066                b.append(" packages=");
6067                if (packages == null) {
6068                    b.append("null");
6069                } else {
6070                    b.append('{');
6071                    boolean first = true;
6072                    for (String s : packages) {
6073                        if (!first) {
6074                            b.append(", ");
6075                        } else first = false;
6076                        b.append(s);
6077                    }
6078                    b.append('}');
6079                }
6080                Slog.d(TAG, b.toString());
6081            }
6082
6083            if (mEnded) {
6084                throw new IllegalStateException("Restore session already ended");
6085            }
6086
6087            if (mRestoreTransport == null || mRestoreSets == null) {
6088                Slog.e(TAG, "Ignoring restoreAll() with no restore set");
6089                return -1;
6090            }
6091
6092            if (mPackageName != null) {
6093                Slog.e(TAG, "Ignoring restoreAll() on single-package session");
6094                return -1;
6095            }
6096
6097            String dirName;
6098            try {
6099                dirName = mRestoreTransport.transportDirName();
6100            } catch (RemoteException e) {
6101                // Transport went AWOL; fail.
6102                Slog.e(TAG, "Unable to contact transport for restore");
6103                return -1;
6104            }
6105
6106            synchronized (mQueueLock) {
6107                for (int i = 0; i < mRestoreSets.length; i++) {
6108                    if (token == mRestoreSets[i].token) {
6109                        long oldId = Binder.clearCallingIdentity();
6110                        mWakelock.acquire();
6111                        Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
6112                        msg.obj = new RestoreParams(mRestoreTransport, dirName, observer, token,
6113                                packages, true);
6114                        mBackupHandler.sendMessage(msg);
6115                        Binder.restoreCallingIdentity(oldId);
6116                        return 0;
6117                    }
6118                }
6119            }
6120
6121            Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
6122            return -1;
6123        }
6124
6125        public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
6126            if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
6127
6128            if (mEnded) {
6129                throw new IllegalStateException("Restore session already ended");
6130            }
6131
6132            if (mPackageName != null) {
6133                if (! mPackageName.equals(packageName)) {
6134                    Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
6135                            + " on session for package " + mPackageName);
6136                    return -1;
6137                }
6138            }
6139
6140            PackageInfo app = null;
6141            try {
6142                app = mPackageManager.getPackageInfo(packageName, 0);
6143            } catch (NameNotFoundException nnf) {
6144                Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
6145                return -1;
6146            }
6147
6148            // If the caller is not privileged and is not coming from the target
6149            // app's uid, throw a permission exception back to the caller.
6150            int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
6151                    Binder.getCallingPid(), Binder.getCallingUid());
6152            if ((perm == PackageManager.PERMISSION_DENIED) &&
6153                    (app.applicationInfo.uid != Binder.getCallingUid())) {
6154                Slog.w(TAG, "restorePackage: bad packageName=" + packageName
6155                        + " or calling uid=" + Binder.getCallingUid());
6156                throw new SecurityException("No permission to restore other packages");
6157            }
6158
6159            // If the package has no backup agent, we obviously cannot proceed
6160            if (app.applicationInfo.backupAgentName == null) {
6161                Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
6162                return -1;
6163            }
6164
6165            // So far so good; we're allowed to try to restore this package.  Now
6166            // check whether there is data for it in the current dataset, falling back
6167            // to the ancestral dataset if not.
6168            long token = getAvailableRestoreToken(packageName);
6169
6170            // If we didn't come up with a place to look -- no ancestral dataset and
6171            // the app has never been backed up from this device -- there's nothing
6172            // to do but return failure.
6173            if (token == 0) {
6174                if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
6175                return -1;
6176            }
6177
6178            String dirName;
6179            try {
6180                dirName = mRestoreTransport.transportDirName();
6181            } catch (RemoteException e) {
6182                // Transport went AWOL; fail.
6183                Slog.e(TAG, "Unable to contact transport for restore");
6184                return -1;
6185            }
6186
6187            // Ready to go:  enqueue the restore request and claim success
6188            long oldId = Binder.clearCallingIdentity();
6189            mWakelock.acquire();
6190            Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
6191            msg.obj = new RestoreParams(mRestoreTransport, dirName,
6192                    observer, token, app, 0, false);
6193            mBackupHandler.sendMessage(msg);
6194            Binder.restoreCallingIdentity(oldId);
6195            return 0;
6196        }
6197
6198        // Posted to the handler to tear down a restore session in a cleanly synchronized way
6199        class EndRestoreRunnable implements Runnable {
6200            BackupManagerService mBackupManager;
6201            ActiveRestoreSession mSession;
6202
6203            EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
6204                mBackupManager = manager;
6205                mSession = session;
6206            }
6207
6208            public void run() {
6209                // clean up the session's bookkeeping
6210                synchronized (mSession) {
6211                    try {
6212                        if (mSession.mRestoreTransport != null) {
6213                            mSession.mRestoreTransport.finishRestore();
6214                        }
6215                    } catch (Exception e) {
6216                        Slog.e(TAG, "Error in finishRestore", e);
6217                    } finally {
6218                        mSession.mRestoreTransport = null;
6219                        mSession.mEnded = true;
6220                    }
6221                }
6222
6223                // clean up the BackupManagerImpl side of the bookkeeping
6224                // and cancel any pending timeout message
6225                mBackupManager.clearRestoreSession(mSession);
6226            }
6227        }
6228
6229        public synchronized void endRestoreSession() {
6230            if (DEBUG) Slog.d(TAG, "endRestoreSession");
6231
6232            if (mEnded) {
6233                throw new IllegalStateException("Restore session already ended");
6234            }
6235
6236            mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
6237        }
6238    }
6239
6240    @Override
6241    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6242        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
6243
6244        long identityToken = Binder.clearCallingIdentity();
6245        try {
6246            dumpInternal(pw);
6247        } finally {
6248            Binder.restoreCallingIdentity(identityToken);
6249        }
6250    }
6251
6252    private void dumpInternal(PrintWriter pw) {
6253        synchronized (mQueueLock) {
6254            pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
6255                    + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
6256                    + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
6257            pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
6258            if (mBackupRunning) pw.println("Backup currently running");
6259            pw.println("Last backup pass started: " + mLastBackupPass
6260                    + " (now = " + System.currentTimeMillis() + ')');
6261            pw.println("  next scheduled: " + mNextBackupPass);
6262
6263            pw.println("Available transports:");
6264            for (String t : listAllTransports()) {
6265                pw.println((t.equals(mCurrentTransport) ? "  * " : "    ") + t);
6266                try {
6267                    IBackupTransport transport = getTransport(t);
6268                    File dir = new File(mBaseStateDir, transport.transportDirName());
6269                    pw.println("       destination: " + transport.currentDestinationString());
6270                    pw.println("       intent: " + transport.configurationIntent());
6271                    for (File f : dir.listFiles()) {
6272                        pw.println("       " + f.getName() + " - " + f.length() + " state bytes");
6273                    }
6274                } catch (Exception e) {
6275                    Slog.e(TAG, "Error in transport", e);
6276                    pw.println("        Error: " + e);
6277                }
6278            }
6279
6280            pw.println("Pending init: " + mPendingInits.size());
6281            for (String s : mPendingInits) {
6282                pw.println("    " + s);
6283            }
6284
6285            if (DEBUG_BACKUP_TRACE) {
6286                synchronized (mBackupTrace) {
6287                    if (!mBackupTrace.isEmpty()) {
6288                        pw.println("Most recent backup trace:");
6289                        for (String s : mBackupTrace) {
6290                            pw.println("   " + s);
6291                        }
6292                    }
6293                }
6294            }
6295
6296            int N = mBackupParticipants.size();
6297            pw.println("Participants:");
6298            for (int i=0; i<N; i++) {
6299                int uid = mBackupParticipants.keyAt(i);
6300                pw.print("  uid: ");
6301                pw.println(uid);
6302                HashSet<String> participants = mBackupParticipants.valueAt(i);
6303                for (String app: participants) {
6304                    pw.println("    " + app);
6305                }
6306            }
6307
6308            pw.println("Ancestral packages: "
6309                    + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
6310            if (mAncestralPackages != null) {
6311                for (String pkg : mAncestralPackages) {
6312                    pw.println("    " + pkg);
6313                }
6314            }
6315
6316            pw.println("Ever backed up: " + mEverStoredApps.size());
6317            for (String pkg : mEverStoredApps) {
6318                pw.println("    " + pkg);
6319            }
6320
6321            pw.println("Pending backup: " + mPendingBackups.size());
6322            for (BackupRequest req : mPendingBackups.values()) {
6323                pw.println("    " + req);
6324            }
6325        }
6326    }
6327}
6328