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