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