BackupManagerService.java revision 9158825f9c41869689d6b1786d7c7aa8bdd524ce
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.internal.backup.LocalTransport;
86import com.android.server.EventLogTags;
87import com.android.server.backup.PackageManagerBackupAgent.Metadata;
88
89import java.io.BufferedInputStream;
90import java.io.BufferedOutputStream;
91import java.io.ByteArrayOutputStream;
92import java.io.DataInputStream;
93import java.io.DataOutputStream;
94import java.io.EOFException;
95import java.io.File;
96import java.io.FileDescriptor;
97import java.io.FileInputStream;
98import java.io.FileNotFoundException;
99import java.io.FileOutputStream;
100import java.io.IOException;
101import java.io.InputStream;
102import java.io.OutputStream;
103import java.io.PrintWriter;
104import java.io.RandomAccessFile;
105import java.security.InvalidAlgorithmParameterException;
106import java.security.InvalidKeyException;
107import java.security.Key;
108import java.security.NoSuchAlgorithmException;
109import java.security.SecureRandom;
110import java.security.spec.InvalidKeySpecException;
111import java.security.spec.KeySpec;
112import java.text.SimpleDateFormat;
113import java.util.ArrayList;
114import java.util.Arrays;
115import java.util.Date;
116import java.util.HashMap;
117import java.util.HashSet;
118import java.util.List;
119import java.util.Map;
120import java.util.Random;
121import java.util.Set;
122import java.util.concurrent.atomic.AtomicBoolean;
123import java.util.zip.Deflater;
124import java.util.zip.DeflaterOutputStream;
125import java.util.zip.InflaterInputStream;
126
127import javax.crypto.BadPaddingException;
128import javax.crypto.Cipher;
129import javax.crypto.CipherInputStream;
130import javax.crypto.CipherOutputStream;
131import javax.crypto.IllegalBlockSizeException;
132import javax.crypto.NoSuchPaddingException;
133import javax.crypto.SecretKey;
134import javax.crypto.SecretKeyFactory;
135import javax.crypto.spec.IvParameterSpec;
136import javax.crypto.spec.PBEKeySpec;
137import javax.crypto.spec.SecretKeySpec;
138
139public class BackupManagerService extends IBackupManager.Stub {
140    private static final String TAG = "BackupManagerService";
141    private static final boolean DEBUG = true;
142    private static final boolean MORE_DEBUG = false;
143
144    // Name and current contents version of the full-backup manifest file
145    static final String BACKUP_MANIFEST_FILENAME = "_manifest";
146    static final int BACKUP_MANIFEST_VERSION = 1;
147    static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
148    static final int BACKUP_FILE_VERSION = 1;
149    static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
150
151    static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
152    static final String SERVICE_ACTION_TRANSPORT_HOST = "android.backup.TRANSPORT_HOST";
153
154    // How often we perform a backup pass.  Privileged external callers can
155    // trigger an immediate pass.
156    private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
157
158    // Random variation in backup scheduling time to avoid server load spikes
159    private static final int FUZZ_MILLIS = 5 * 60 * 1000;
160
161    // The amount of time between the initial provisioning of the device and
162    // the first backup pass.
163    private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
164
165    // Retry interval for clear/init when the transport is unavailable
166    private static final long TRANSPORT_RETRY_INTERVAL = 1 * AlarmManager.INTERVAL_HOUR;
167
168    private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
169    private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
170    private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
171    private static final int MSG_RUN_BACKUP = 1;
172    private static final int MSG_RUN_FULL_BACKUP = 2;
173    private static final int MSG_RUN_RESTORE = 3;
174    private static final int MSG_RUN_CLEAR = 4;
175    private static final int MSG_RUN_INITIALIZE = 5;
176    private static final int MSG_RUN_GET_RESTORE_SETS = 6;
177    private static final int MSG_TIMEOUT = 7;
178    private static final int MSG_RESTORE_TIMEOUT = 8;
179    private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
180    private static final int MSG_RUN_FULL_RESTORE = 10;
181    private static final int MSG_RETRY_INIT = 11;
182    private static final int MSG_RETRY_CLEAR = 12;
183
184    // backup task state machine tick
185    static final int MSG_BACKUP_RESTORE_STEP = 20;
186    static final int MSG_OP_COMPLETE = 21;
187
188    // Timeout interval for deciding that a bind or clear-data has taken too long
189    static final long TIMEOUT_INTERVAL = 10 * 1000;
190
191    // Timeout intervals for agent backup & restore operations
192    static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
193    static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
194    static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
195    static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
196
197    // User confirmation timeout for a full backup/restore operation.  It's this long in
198    // order to give them time to enter the backup password.
199    static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
200
201    private Context mContext;
202    private PackageManager mPackageManager;
203    IPackageManager mPackageManagerBinder;
204    private IActivityManager mActivityManager;
205    private PowerManager mPowerManager;
206    private AlarmManager mAlarmManager;
207    private IMountService mMountService;
208    IBackupManager mBackupManagerBinder;
209
210    boolean mEnabled;   // access to this is synchronized on 'this'
211    boolean mProvisioned;
212    boolean mAutoRestore;
213    PowerManager.WakeLock mWakelock;
214    HandlerThread mHandlerThread;
215    BackupHandler mBackupHandler;
216    PendingIntent mRunBackupIntent, mRunInitIntent;
217    BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
218    // map UIDs to the set of participating packages under that UID
219    final SparseArray<HashSet<String>> mBackupParticipants
220            = new SparseArray<HashSet<String>>();
221    // set of backup services that have pending changes
222    class BackupRequest {
223        public String packageName;
224
225        BackupRequest(String pkgName) {
226            packageName = pkgName;
227        }
228
229        public String toString() {
230            return "BackupRequest{pkg=" + packageName + "}";
231        }
232    }
233    // Backups that we haven't started yet.  Keys are package names.
234    HashMap<String,BackupRequest> mPendingBackups
235            = new HashMap<String,BackupRequest>();
236
237    // Pseudoname that we use for the Package Manager metadata "package"
238    static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
239
240    // locking around the pending-backup management
241    final Object mQueueLock = new Object();
242
243    // The thread performing the sequence of queued backups binds to each app's agent
244    // in succession.  Bind notifications are asynchronously delivered through the
245    // Activity Manager; use this lock object to signal when a requested binding has
246    // completed.
247    final Object mAgentConnectLock = new Object();
248    IBackupAgent mConnectedAgent;
249    volatile boolean mBackupRunning;
250    volatile boolean mConnecting;
251    volatile long mLastBackupPass;
252    volatile long mNextBackupPass;
253
254    // For debugging, we maintain a progress trace of operations during backup
255    static final boolean DEBUG_BACKUP_TRACE = true;
256    final List<String> mBackupTrace = new ArrayList<String>();
257
258    // A similar synchronization mechanism around clearing apps' data for restore
259    final Object mClearDataLock = new Object();
260    volatile boolean mClearingData;
261
262    // Transport bookkeeping
263    final HashMap<String,String> mTransportNames
264            = new HashMap<String,String>();             // component name -> registration name
265    final HashMap<String,IBackupTransport> mTransports
266            = new HashMap<String,IBackupTransport>();   // registration name -> binder
267    final ArrayList<TransportConnection> mTransportConnections
268            = new ArrayList<TransportConnection>();
269    String mCurrentTransport;
270    ActiveRestoreSession mActiveRestoreSession;
271
272    // Watch the device provisioning operation during setup
273    ContentObserver mProvisionedObserver;
274
275    class ProvisionedObserver extends ContentObserver {
276        public ProvisionedObserver(Handler handler) {
277            super(handler);
278        }
279
280        public void onChange(boolean selfChange) {
281            final boolean wasProvisioned = mProvisioned;
282            final boolean isProvisioned = deviceIsProvisioned();
283            // latch: never unprovision
284            mProvisioned = wasProvisioned || isProvisioned;
285            if (MORE_DEBUG) {
286                Slog.d(TAG, "Provisioning change: was=" + wasProvisioned
287                        + " is=" + isProvisioned + " now=" + mProvisioned);
288            }
289
290            synchronized (mQueueLock) {
291                if (mProvisioned && !wasProvisioned && mEnabled) {
292                    // we're now good to go, so start the backup alarms
293                    if (MORE_DEBUG) Slog.d(TAG, "Now provisioned, so starting backups");
294                    startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
295                }
296            }
297        }
298    }
299
300    class RestoreGetSetsParams {
301        public IBackupTransport transport;
302        public ActiveRestoreSession session;
303        public IRestoreObserver observer;
304
305        RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
306                IRestoreObserver _observer) {
307            transport = _transport;
308            session = _session;
309            observer = _observer;
310        }
311    }
312
313    class RestoreParams {
314        public IBackupTransport transport;
315        public String dirName;
316        public IRestoreObserver observer;
317        public long token;
318        public PackageInfo pkgInfo;
319        public int pmToken; // in post-install restore, the PM's token for this transaction
320        public boolean needFullBackup;
321        public String[] filterSet;
322
323        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
324                long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
325            transport = _transport;
326            dirName = _dirName;
327            observer = _obs;
328            token = _token;
329            pkgInfo = _pkg;
330            pmToken = _pmToken;
331            needFullBackup = _needFullBackup;
332            filterSet = null;
333        }
334
335        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
336                long _token, boolean _needFullBackup) {
337            transport = _transport;
338            dirName = _dirName;
339            observer = _obs;
340            token = _token;
341            pkgInfo = null;
342            pmToken = 0;
343            needFullBackup = _needFullBackup;
344            filterSet = null;
345        }
346
347        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
348                long _token, String[] _filterSet, boolean _needFullBackup) {
349            transport = _transport;
350            dirName = _dirName;
351            observer = _obs;
352            token = _token;
353            pkgInfo = null;
354            pmToken = 0;
355            needFullBackup = _needFullBackup;
356            filterSet = _filterSet;
357        }
358    }
359
360    class ClearParams {
361        public IBackupTransport transport;
362        public PackageInfo packageInfo;
363
364        ClearParams(IBackupTransport _transport, PackageInfo _info) {
365            transport = _transport;
366            packageInfo = _info;
367        }
368    }
369
370    class ClearRetryParams {
371        public String transportName;
372        public String packageName;
373
374        ClearRetryParams(String transport, String pkg) {
375            transportName = transport;
376            packageName = pkg;
377        }
378    }
379
380    class FullParams {
381        public ParcelFileDescriptor fd;
382        public final AtomicBoolean latch;
383        public IFullBackupRestoreObserver observer;
384        public String curPassword;     // filled in by the confirmation step
385        public String encryptPassword;
386
387        FullParams() {
388            latch = new AtomicBoolean(false);
389        }
390    }
391
392    class FullBackupParams extends FullParams {
393        public boolean includeApks;
394        public boolean includeObbs;
395        public boolean includeShared;
396        public boolean allApps;
397        public boolean includeSystem;
398        public String[] packages;
399
400        FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveObbs,
401                boolean saveShared, boolean doAllApps, boolean doSystem, String[] pkgList) {
402            fd = output;
403            includeApks = saveApks;
404            includeObbs = saveObbs;
405            includeShared = saveShared;
406            allApps = doAllApps;
407            includeSystem = doSystem;
408            packages = pkgList;
409        }
410    }
411
412    class FullRestoreParams extends FullParams {
413        FullRestoreParams(ParcelFileDescriptor input) {
414            fd = input;
415        }
416    }
417
418    // Bookkeeping of in-flight operations for timeout etc. purposes.  The operation
419    // token is the index of the entry in the pending-operations list.
420    static final int OP_PENDING = 0;
421    static final int OP_ACKNOWLEDGED = 1;
422    static final int OP_TIMEOUT = -1;
423
424    class Operation {
425        public int state;
426        public BackupRestoreTask callback;
427
428        Operation(int initialState, BackupRestoreTask callbackObj) {
429            state = initialState;
430            callback = callbackObj;
431        }
432    }
433    final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
434    final Object mCurrentOpLock = new Object();
435    final Random mTokenGenerator = new Random();
436
437    final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
438
439    // Where we keep our journal files and other bookkeeping
440    File mBaseStateDir;
441    File mDataDir;
442    File mJournalDir;
443    File mJournal;
444
445    // Backup password, if any, and the file where it's saved.  What is stored is not the
446    // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
447    // persisted) salt.  Validation is performed by running the challenge text through the
448    // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
449    // the saved hash string, then the challenge text matches the originally supplied
450    // password text.
451    private final SecureRandom mRng = new SecureRandom();
452    private String mPasswordHash;
453    private File mPasswordHashFile;
454    private byte[] mPasswordSalt;
455
456    // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
457    static final int PBKDF2_HASH_ROUNDS = 10000;
458    static final int PBKDF2_KEY_SIZE = 256;     // bits
459    static final int PBKDF2_SALT_SIZE = 512;    // bits
460    static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
461
462    // Keep a log of all the apps we've ever backed up, and what the
463    // dataset tokens are for both the current backup dataset and
464    // the ancestral dataset.
465    private File mEverStored;
466    HashSet<String> mEverStoredApps = new HashSet<String>();
467
468    static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1;  // increment when the schema changes
469    File mTokenFile;
470    Set<String> mAncestralPackages = null;
471    long mAncestralToken = 0;
472    long mCurrentToken = 0;
473
474    // Persistently track the need to do a full init
475    static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
476    HashSet<String> mPendingInits = new HashSet<String>();  // transport names
477
478    // Utility: build a new random integer token
479    int generateToken() {
480        int token;
481        do {
482            synchronized (mTokenGenerator) {
483                token = mTokenGenerator.nextInt();
484            }
485        } while (token < 0);
486        return token;
487    }
488
489    // ----- Asynchronous backup/restore handler thread -----
490
491    private class BackupHandler extends Handler {
492        public BackupHandler(Looper looper) {
493            super(looper);
494        }
495
496        public void handleMessage(Message msg) {
497
498            switch (msg.what) {
499            case MSG_RUN_BACKUP:
500            {
501                mLastBackupPass = System.currentTimeMillis();
502                mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
503
504                IBackupTransport transport = getTransport(mCurrentTransport);
505                if (transport == null) {
506                    Slog.v(TAG, "Backup requested but no transport available");
507                    synchronized (mQueueLock) {
508                        mBackupRunning = false;
509                    }
510                    mWakelock.release();
511                    break;
512                }
513
514                // snapshot the pending-backup set and work on that
515                ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
516                File oldJournal = mJournal;
517                synchronized (mQueueLock) {
518                    // Do we have any work to do?  Construct the work queue
519                    // then release the synchronization lock to actually run
520                    // the backup.
521                    if (mPendingBackups.size() > 0) {
522                        for (BackupRequest b: mPendingBackups.values()) {
523                            queue.add(b);
524                        }
525                        if (DEBUG) Slog.v(TAG, "clearing pending backups");
526                        mPendingBackups.clear();
527
528                        // Start a new backup-queue journal file too
529                        mJournal = null;
530
531                    }
532                }
533
534                // At this point, we have started a new journal file, and the old
535                // file identity is being passed to the backup processing task.
536                // When it completes successfully, that old journal file will be
537                // deleted.  If we crash prior to that, the old journal is parsed
538                // at next boot and the journaled requests fulfilled.
539                boolean staged = true;
540                if (queue.size() > 0) {
541                    // Spin up a backup state sequence and set it running
542                    try {
543                        String dirName = transport.transportDirName();
544                        PerformBackupTask pbt = new PerformBackupTask(transport, dirName,
545                                queue, oldJournal);
546                        Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
547                        sendMessage(pbtMessage);
548                    } catch (RemoteException e) {
549                        // unable to ask the transport its dir name -- transient failure, since
550                        // the above check succeeded.  Try again next time.
551                        Slog.e(TAG, "Transport became unavailable attempting backup");
552                        staged = false;
553                    }
554                } else {
555                    Slog.v(TAG, "Backup requested but nothing pending");
556                    staged = false;
557                }
558
559                if (!staged) {
560                    // if we didn't actually hand off the wakelock, rewind until next time
561                    synchronized (mQueueLock) {
562                        mBackupRunning = false;
563                    }
564                    mWakelock.release();
565                }
566                break;
567            }
568
569            case MSG_BACKUP_RESTORE_STEP:
570            {
571                try {
572                    BackupRestoreTask task = (BackupRestoreTask) msg.obj;
573                    if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
574                    task.execute();
575                } catch (ClassCastException e) {
576                    Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
577                }
578                break;
579            }
580
581            case MSG_OP_COMPLETE:
582            {
583                try {
584                    BackupRestoreTask task = (BackupRestoreTask) msg.obj;
585                    task.operationComplete();
586                } catch (ClassCastException e) {
587                    Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
588                }
589                break;
590            }
591
592            case MSG_RUN_FULL_BACKUP:
593            {
594                // TODO: refactor full backup to be a looper-based state machine
595                // similar to normal backup/restore.
596                FullBackupParams params = (FullBackupParams)msg.obj;
597                PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
598                        params.observer, params.includeApks, params.includeObbs,
599                        params.includeShared, params.curPassword, params.encryptPassword,
600                        params.allApps, params.includeSystem, params.packages, params.latch);
601                (new Thread(task)).start();
602                break;
603            }
604
605            case MSG_RUN_RESTORE:
606            {
607                RestoreParams params = (RestoreParams)msg.obj;
608                Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
609                PerformRestoreTask task = new PerformRestoreTask(
610                        params.transport, params.dirName, params.observer,
611                        params.token, params.pkgInfo, params.pmToken,
612                        params.needFullBackup, params.filterSet);
613                Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
614                sendMessage(restoreMsg);
615                break;
616            }
617
618            case MSG_RUN_FULL_RESTORE:
619            {
620                // TODO: refactor full restore to be a looper-based state machine
621                // similar to normal backup/restore.
622                FullRestoreParams params = (FullRestoreParams)msg.obj;
623                PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
624                        params.curPassword, params.encryptPassword,
625                        params.observer, params.latch);
626                (new Thread(task)).start();
627                break;
628            }
629
630            case MSG_RUN_CLEAR:
631            {
632                ClearParams params = (ClearParams)msg.obj;
633                (new PerformClearTask(params.transport, params.packageInfo)).run();
634                break;
635            }
636
637            case MSG_RETRY_CLEAR:
638            {
639                // reenqueues if the transport remains unavailable
640                ClearRetryParams params = (ClearRetryParams)msg.obj;
641                clearBackupData(params.transportName, params.packageName);
642                break;
643            }
644
645            case MSG_RUN_INITIALIZE:
646            {
647                HashSet<String> queue;
648
649                // Snapshot the pending-init queue and work on that
650                synchronized (mQueueLock) {
651                    queue = new HashSet<String>(mPendingInits);
652                    mPendingInits.clear();
653                }
654
655                (new PerformInitializeTask(queue)).run();
656                break;
657            }
658
659            case MSG_RETRY_INIT:
660            {
661                synchronized (mQueueLock) {
662                    recordInitPendingLocked(msg.arg1 != 0, (String)msg.obj);
663                    mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
664                            mRunInitIntent);
665                }
666                break;
667            }
668
669            case MSG_RUN_GET_RESTORE_SETS:
670            {
671                // Like other async operations, this is entered with the wakelock held
672                RestoreSet[] sets = null;
673                RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
674                try {
675                    sets = params.transport.getAvailableRestoreSets();
676                    // cache the result in the active session
677                    synchronized (params.session) {
678                        params.session.mRestoreSets = sets;
679                    }
680                    if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
681                } catch (Exception e) {
682                    Slog.e(TAG, "Error from transport getting set list");
683                } finally {
684                    if (params.observer != null) {
685                        try {
686                            params.observer.restoreSetsAvailable(sets);
687                        } catch (RemoteException re) {
688                            Slog.e(TAG, "Unable to report listing to observer");
689                        } catch (Exception e) {
690                            Slog.e(TAG, "Restore observer threw", e);
691                        }
692                    }
693
694                    // Done: reset the session timeout clock
695                    removeMessages(MSG_RESTORE_TIMEOUT);
696                    sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
697
698                    mWakelock.release();
699                }
700                break;
701            }
702
703            case MSG_TIMEOUT:
704            {
705                handleTimeout(msg.arg1, msg.obj);
706                break;
707            }
708
709            case MSG_RESTORE_TIMEOUT:
710            {
711                synchronized (BackupManagerService.this) {
712                    if (mActiveRestoreSession != null) {
713                        // Client app left the restore session dangling.  We know that it
714                        // can't be in the middle of an actual restore operation because
715                        // the timeout is suspended while a restore is in progress.  Clean
716                        // up now.
717                        Slog.w(TAG, "Restore session timed out; aborting");
718                        post(mActiveRestoreSession.new EndRestoreRunnable(
719                                BackupManagerService.this, mActiveRestoreSession));
720                    }
721                }
722            }
723
724            case MSG_FULL_CONFIRMATION_TIMEOUT:
725            {
726                synchronized (mFullConfirmations) {
727                    FullParams params = mFullConfirmations.get(msg.arg1);
728                    if (params != null) {
729                        Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
730
731                        // Release the waiter; timeout == completion
732                        signalFullBackupRestoreCompletion(params);
733
734                        // Remove the token from the set
735                        mFullConfirmations.delete(msg.arg1);
736
737                        // Report a timeout to the observer, if any
738                        if (params.observer != null) {
739                            try {
740                                params.observer.onTimeout();
741                            } catch (RemoteException e) {
742                                /* don't care if the app has gone away */
743                            }
744                        }
745                    } else {
746                        Slog.d(TAG, "couldn't find params for token " + msg.arg1);
747                    }
748                }
749                break;
750            }
751            }
752        }
753    }
754
755    // ----- Debug-only backup operation trace -----
756    void addBackupTrace(String s) {
757        if (DEBUG_BACKUP_TRACE) {
758            synchronized (mBackupTrace) {
759                mBackupTrace.add(s);
760            }
761        }
762    }
763
764    void clearBackupTrace() {
765        if (DEBUG_BACKUP_TRACE) {
766            synchronized (mBackupTrace) {
767                mBackupTrace.clear();
768            }
769        }
770    }
771
772    // ----- Main service implementation -----
773
774    public BackupManagerService(Context context) {
775        mContext = context;
776        mPackageManager = context.getPackageManager();
777        mPackageManagerBinder = AppGlobals.getPackageManager();
778        mActivityManager = ActivityManagerNative.getDefault();
779
780        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
781        mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
782        mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
783
784        mBackupManagerBinder = asInterface(asBinder());
785
786        // spin up the backup/restore handler thread
787        mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
788        mHandlerThread.start();
789        mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
790
791        // Set up our bookkeeping
792        final ContentResolver resolver = context.getContentResolver();
793        boolean areEnabled = Settings.Secure.getInt(resolver,
794                Settings.Secure.BACKUP_ENABLED, 0) != 0;
795        mProvisioned = Settings.Global.getInt(resolver,
796                Settings.Global.DEVICE_PROVISIONED, 0) != 0;
797        mAutoRestore = Settings.Secure.getInt(resolver,
798                Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
799
800        mProvisionedObserver = new ProvisionedObserver(mBackupHandler);
801        resolver.registerContentObserver(
802                Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
803                false, mProvisionedObserver);
804
805        // If Encrypted file systems is enabled or disabled, this call will return the
806        // correct directory.
807        mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
808        mBaseStateDir.mkdirs();
809        if (!SELinux.restorecon(mBaseStateDir)) {
810            Slog.e(TAG, "SELinux restorecon failed on " + mBaseStateDir);
811        }
812        mDataDir = Environment.getDownloadCacheDirectory();
813
814        mPasswordHashFile = new File(mBaseStateDir, "pwhash");
815        if (mPasswordHashFile.exists()) {
816            FileInputStream fin = null;
817            DataInputStream in = null;
818            try {
819                fin = new FileInputStream(mPasswordHashFile);
820                in = new DataInputStream(new BufferedInputStream(fin));
821                // integer length of the salt array, followed by the salt,
822                // then the hex pw hash string
823                int saltLen = in.readInt();
824                byte[] salt = new byte[saltLen];
825                in.readFully(salt);
826                mPasswordHash = in.readUTF();
827                mPasswordSalt = salt;
828            } catch (IOException e) {
829                Slog.e(TAG, "Unable to read saved backup pw hash");
830            } finally {
831                try {
832                    if (in != null) in.close();
833                    if (fin != null) fin.close();
834                } catch (IOException e) {
835                    Slog.w(TAG, "Unable to close streams");
836                }
837            }
838        }
839
840        // Alarm receivers for scheduled backups & initialization operations
841        mRunBackupReceiver = new RunBackupReceiver();
842        IntentFilter filter = new IntentFilter();
843        filter.addAction(RUN_BACKUP_ACTION);
844        context.registerReceiver(mRunBackupReceiver, filter,
845                android.Manifest.permission.BACKUP, null);
846
847        mRunInitReceiver = new RunInitializeReceiver();
848        filter = new IntentFilter();
849        filter.addAction(RUN_INITIALIZE_ACTION);
850        context.registerReceiver(mRunInitReceiver, filter,
851                android.Manifest.permission.BACKUP, null);
852
853        Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
854        backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
855        mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
856
857        Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
858        backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
859        mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
860
861        // Set up the backup-request journaling
862        mJournalDir = new File(mBaseStateDir, "pending");
863        mJournalDir.mkdirs();   // creates mBaseStateDir along the way
864        mJournal = null;        // will be created on first use
865
866        // Set up the various sorts of package tracking we do
867        initPackageTracking();
868
869        // Build our mapping of uid to backup client services.  This implicitly
870        // schedules a backup pass on the Package Manager metadata the first
871        // time anything needs to be backed up.
872        synchronized (mBackupParticipants) {
873            addPackageParticipantsLocked(null);
874        }
875
876        // Set up our transport options and initialize the default transport
877        // TODO: Don't create transports that we don't need to?
878        mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
879                Settings.Secure.BACKUP_TRANSPORT);
880        if ("".equals(mCurrentTransport)) {
881            mCurrentTransport = null;
882        }
883        if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
884
885        // Find transport hosts and bind to their services
886        Intent transportServiceIntent = new Intent(SERVICE_ACTION_TRANSPORT_HOST);
887        List<ResolveInfo> hosts = mPackageManager.queryIntentServicesAsUser(
888                transportServiceIntent, 0, UserHandle.USER_OWNER);
889        if (DEBUG) {
890            Slog.v(TAG, "Found transports: " + ((hosts == null) ? "null" : hosts.size()));
891        }
892        if (hosts != null) {
893            if (MORE_DEBUG) {
894                for (int i = 0; i < hosts.size(); i++) {
895                    ServiceInfo info = hosts.get(i).serviceInfo;
896                    Slog.v(TAG, "   " + info.packageName + "/" + info.name);
897                }
898            }
899            for (int i = 0; i < hosts.size(); i++) {
900                try {
901                    ServiceInfo info = hosts.get(i).serviceInfo;
902                    PackageInfo packInfo = mPackageManager.getPackageInfo(info.packageName, 0);
903                    if ((packInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
904                        ComponentName svcName = new ComponentName(info.packageName, info.name);
905                        if (DEBUG) {
906                            Slog.i(TAG, "Binding to transport host " + svcName);
907                        }
908                        Intent intent = new Intent(transportServiceIntent);
909                        intent.setComponent(svcName);
910                        TransportConnection connection = new TransportConnection();
911                        mTransportConnections.add(connection);
912                        context.bindServiceAsUser(intent,
913                                connection, Context.BIND_AUTO_CREATE,
914                                UserHandle.OWNER);
915                    } else {
916                        Slog.w(TAG, "Transport package not privileged: " + info.packageName);
917                    }
918                } catch (Exception e) {
919                    Slog.e(TAG, "Problem resolving transport service: " + e.getMessage());
920                }
921            }
922        }
923
924        // Now that we know about valid backup participants, parse any
925        // leftover journal files into the pending backup set
926        parseLeftoverJournals();
927
928        // Power management
929        mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
930
931        // Start the backup passes going
932        setBackupEnabled(areEnabled);
933    }
934
935    private class RunBackupReceiver extends BroadcastReceiver {
936        public void onReceive(Context context, Intent intent) {
937            if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
938                synchronized (mQueueLock) {
939                    if (mPendingInits.size() > 0) {
940                        // If there are pending init operations, we process those
941                        // and then settle into the usual periodic backup schedule.
942                        if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
943                        try {
944                            mAlarmManager.cancel(mRunInitIntent);
945                            mRunInitIntent.send();
946                        } catch (PendingIntent.CanceledException ce) {
947                            Slog.e(TAG, "Run init intent cancelled");
948                            // can't really do more than bail here
949                        }
950                    } else {
951                        // Don't run backups now if we're disabled or not yet
952                        // fully set up.
953                        if (mEnabled && mProvisioned) {
954                            if (!mBackupRunning) {
955                                if (DEBUG) Slog.v(TAG, "Running a backup pass");
956
957                                // Acquire the wakelock and pass it to the backup thread.  it will
958                                // be released once backup concludes.
959                                mBackupRunning = true;
960                                mWakelock.acquire();
961
962                                Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
963                                mBackupHandler.sendMessage(msg);
964                            } else {
965                                Slog.i(TAG, "Backup time but one already running");
966                            }
967                        } else {
968                            Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
969                        }
970                    }
971                }
972            }
973        }
974    }
975
976    private class RunInitializeReceiver extends BroadcastReceiver {
977        public void onReceive(Context context, Intent intent) {
978            if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
979                synchronized (mQueueLock) {
980                    if (DEBUG) Slog.v(TAG, "Running a device init");
981
982                    // Acquire the wakelock and pass it to the init thread.  it will
983                    // be released once init concludes.
984                    mWakelock.acquire();
985
986                    Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
987                    mBackupHandler.sendMessage(msg);
988                }
989            }
990        }
991    }
992
993    private void initPackageTracking() {
994        if (DEBUG) Slog.v(TAG, "Initializing package tracking");
995
996        // Remember our ancestral dataset
997        mTokenFile = new File(mBaseStateDir, "ancestral");
998        try {
999            RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
1000            int version = tf.readInt();
1001            if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
1002                mAncestralToken = tf.readLong();
1003                mCurrentToken = tf.readLong();
1004
1005                int numPackages = tf.readInt();
1006                if (numPackages >= 0) {
1007                    mAncestralPackages = new HashSet<String>();
1008                    for (int i = 0; i < numPackages; i++) {
1009                        String pkgName = tf.readUTF();
1010                        mAncestralPackages.add(pkgName);
1011                    }
1012                }
1013            }
1014            tf.close();
1015        } catch (FileNotFoundException fnf) {
1016            // Probably innocuous
1017            Slog.v(TAG, "No ancestral data");
1018        } catch (IOException e) {
1019            Slog.w(TAG, "Unable to read token file", e);
1020        }
1021
1022        // Keep a log of what apps we've ever backed up.  Because we might have
1023        // rebooted in the middle of an operation that was removing something from
1024        // this log, we sanity-check its contents here and reconstruct it.
1025        mEverStored = new File(mBaseStateDir, "processed");
1026        File tempProcessedFile = new File(mBaseStateDir, "processed.new");
1027
1028        // If we were in the middle of removing something from the ever-backed-up
1029        // file, there might be a transient "processed.new" file still present.
1030        // Ignore it -- we'll validate "processed" against the current package set.
1031        if (tempProcessedFile.exists()) {
1032            tempProcessedFile.delete();
1033        }
1034
1035        // If there are previous contents, parse them out then start a new
1036        // file to continue the recordkeeping.
1037        if (mEverStored.exists()) {
1038            RandomAccessFile temp = null;
1039            RandomAccessFile in = null;
1040
1041            try {
1042                temp = new RandomAccessFile(tempProcessedFile, "rws");
1043                in = new RandomAccessFile(mEverStored, "r");
1044
1045                while (true) {
1046                    PackageInfo info;
1047                    String pkg = in.readUTF();
1048                    try {
1049                        info = mPackageManager.getPackageInfo(pkg, 0);
1050                        mEverStoredApps.add(pkg);
1051                        temp.writeUTF(pkg);
1052                        if (MORE_DEBUG) Slog.v(TAG, "   + " + pkg);
1053                    } catch (NameNotFoundException e) {
1054                        // nope, this package was uninstalled; don't include it
1055                        if (MORE_DEBUG) Slog.v(TAG, "   - " + pkg);
1056                    }
1057                }
1058            } catch (EOFException e) {
1059                // Once we've rewritten the backup history log, atomically replace the
1060                // old one with the new one then reopen the file for continuing use.
1061                if (!tempProcessedFile.renameTo(mEverStored)) {
1062                    Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
1063                }
1064            } catch (IOException e) {
1065                Slog.e(TAG, "Error in processed file", e);
1066            } finally {
1067                try { if (temp != null) temp.close(); } catch (IOException e) {}
1068                try { if (in != null) in.close(); } catch (IOException e) {}
1069            }
1070        }
1071
1072        // Register for broadcasts about package install, etc., so we can
1073        // update the provider list.
1074        IntentFilter filter = new IntentFilter();
1075        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1076        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1077        filter.addDataScheme("package");
1078        mContext.registerReceiver(mBroadcastReceiver, filter);
1079        // Register for events related to sdcard installation.
1080        IntentFilter sdFilter = new IntentFilter();
1081        sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1082        sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1083        mContext.registerReceiver(mBroadcastReceiver, sdFilter);
1084    }
1085
1086    private void parseLeftoverJournals() {
1087        for (File f : mJournalDir.listFiles()) {
1088            if (mJournal == null || f.compareTo(mJournal) != 0) {
1089                // This isn't the current journal, so it must be a leftover.  Read
1090                // out the package names mentioned there and schedule them for
1091                // backup.
1092                RandomAccessFile in = null;
1093                try {
1094                    Slog.i(TAG, "Found stale backup journal, scheduling");
1095                    in = new RandomAccessFile(f, "r");
1096                    while (true) {
1097                        String packageName = in.readUTF();
1098                        Slog.i(TAG, "  " + packageName);
1099                        dataChangedImpl(packageName);
1100                    }
1101                } catch (EOFException e) {
1102                    // no more data; we're done
1103                } catch (Exception e) {
1104                    Slog.e(TAG, "Can't read " + f, e);
1105                } finally {
1106                    // close/delete the file
1107                    try { if (in != null) in.close(); } catch (IOException e) {}
1108                    f.delete();
1109                }
1110            }
1111        }
1112    }
1113
1114    private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
1115        return buildCharArrayKey(pw.toCharArray(), salt, rounds);
1116    }
1117
1118    private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
1119        try {
1120            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
1121            KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1122            return keyFactory.generateSecret(ks);
1123        } catch (InvalidKeySpecException e) {
1124            Slog.e(TAG, "Invalid key spec for PBKDF2!");
1125        } catch (NoSuchAlgorithmException e) {
1126            Slog.e(TAG, "PBKDF2 unavailable!");
1127        }
1128        return null;
1129    }
1130
1131    private String buildPasswordHash(String pw, byte[] salt, int rounds) {
1132        SecretKey key = buildPasswordKey(pw, salt, rounds);
1133        if (key != null) {
1134            return byteArrayToHex(key.getEncoded());
1135        }
1136        return null;
1137    }
1138
1139    private String byteArrayToHex(byte[] data) {
1140        StringBuilder buf = new StringBuilder(data.length * 2);
1141        for (int i = 0; i < data.length; i++) {
1142            buf.append(Byte.toHexString(data[i], true));
1143        }
1144        return buf.toString();
1145    }
1146
1147    private byte[] hexToByteArray(String digits) {
1148        final int bytes = digits.length() / 2;
1149        if (2*bytes != digits.length()) {
1150            throw new IllegalArgumentException("Hex string must have an even number of digits");
1151        }
1152
1153        byte[] result = new byte[bytes];
1154        for (int i = 0; i < digits.length(); i += 2) {
1155            result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1156        }
1157        return result;
1158    }
1159
1160    private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1161        char[] mkAsChar = new char[pwBytes.length];
1162        for (int i = 0; i < pwBytes.length; i++) {
1163            mkAsChar[i] = (char) pwBytes[i];
1164        }
1165
1166        Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1167        return checksum.getEncoded();
1168    }
1169
1170    // Used for generating random salts or passwords
1171    private byte[] randomBytes(int bits) {
1172        byte[] array = new byte[bits / 8];
1173        mRng.nextBytes(array);
1174        return array;
1175    }
1176
1177    // Backup password management
1178    boolean passwordMatchesSaved(String candidatePw, int rounds) {
1179        // First, on an encrypted device we require matching the device pw
1180        final boolean isEncrypted;
1181        try {
1182            isEncrypted = (mMountService.getEncryptionState() !=
1183                    IMountService.ENCRYPTION_STATE_NONE);
1184            if (isEncrypted) {
1185                if (DEBUG) {
1186                    Slog.i(TAG, "Device encrypted; verifying against device data pw");
1187                }
1188                // 0 means the password validated
1189                // -2 means device not encrypted
1190                // Any other result is either password failure or an error condition,
1191                // so we refuse the match
1192                final int result = mMountService.verifyEncryptionPassword(candidatePw);
1193                if (result == 0) {
1194                    if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
1195                    return true;
1196                } else if (result != -2) {
1197                    if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
1198                    return false;
1199                } else {
1200                    // ...else the device is supposedly not encrypted.  HOWEVER, the
1201                    // query about the encryption state said that the device *is*
1202                    // encrypted, so ... we may have a problem.  Log it and refuse
1203                    // the backup.
1204                    Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
1205                    return false;
1206                }
1207            }
1208        } catch (Exception e) {
1209            // Something went wrong talking to the mount service.  This is very bad;
1210            // assume that we fail password validation.
1211            return false;
1212        }
1213
1214        if (mPasswordHash == null) {
1215            // no current password case -- require that 'currentPw' be null or empty
1216            if (candidatePw == null || "".equals(candidatePw)) {
1217                return true;
1218            } // else the non-empty candidate does not match the empty stored pw
1219        } else {
1220            // hash the stated current pw and compare to the stored one
1221            if (candidatePw != null && candidatePw.length() > 0) {
1222                String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1223                if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1224                    // candidate hash matches the stored hash -- the password matches
1225                    return true;
1226                }
1227            } // else the stored pw is nonempty but the candidate is empty; no match
1228        }
1229        return false;
1230    }
1231
1232    @Override
1233    public boolean setBackupPassword(String currentPw, String newPw) {
1234        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1235                "setBackupPassword");
1236
1237        // If the supplied pw doesn't hash to the the saved one, fail
1238        if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1239            return false;
1240        }
1241
1242        // Clearing the password is okay
1243        if (newPw == null || newPw.isEmpty()) {
1244            if (mPasswordHashFile.exists()) {
1245                if (!mPasswordHashFile.delete()) {
1246                    // Unable to delete the old pw file, so fail
1247                    Slog.e(TAG, "Unable to clear backup password");
1248                    return false;
1249                }
1250            }
1251            mPasswordHash = null;
1252            mPasswordSalt = null;
1253            return true;
1254        }
1255
1256        try {
1257            // Okay, build the hash of the new backup password
1258            byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1259            String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1260
1261            OutputStream pwf = null, buffer = null;
1262            DataOutputStream out = null;
1263            try {
1264                pwf = new FileOutputStream(mPasswordHashFile);
1265                buffer = new BufferedOutputStream(pwf);
1266                out = new DataOutputStream(buffer);
1267                // integer length of the salt array, followed by the salt,
1268                // then the hex pw hash string
1269                out.writeInt(salt.length);
1270                out.write(salt);
1271                out.writeUTF(newPwHash);
1272                out.flush();
1273                mPasswordHash = newPwHash;
1274                mPasswordSalt = salt;
1275                return true;
1276            } finally {
1277                if (out != null) out.close();
1278                if (buffer != null) buffer.close();
1279                if (pwf != null) pwf.close();
1280            }
1281        } catch (IOException e) {
1282            Slog.e(TAG, "Unable to set backup password");
1283        }
1284        return false;
1285    }
1286
1287    @Override
1288    public boolean hasBackupPassword() {
1289        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1290                "hasBackupPassword");
1291
1292        try {
1293            return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
1294                || (mPasswordHash != null && mPasswordHash.length() > 0);
1295        } catch (Exception e) {
1296            // If we can't talk to the mount service we have a serious problem; fail
1297            // "secure" i.e. assuming that we require a password
1298            return true;
1299        }
1300    }
1301
1302    // Maintain persistent state around whether need to do an initialize operation.
1303    // Must be called with the queue lock held.
1304    void recordInitPendingLocked(boolean isPending, String transportName) {
1305        if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
1306                + " on transport " + transportName);
1307        mBackupHandler.removeMessages(MSG_RETRY_INIT);
1308
1309        try {
1310            IBackupTransport transport = getTransport(transportName);
1311            if (transport != null) {
1312                String transportDirName = transport.transportDirName();
1313                File stateDir = new File(mBaseStateDir, transportDirName);
1314                File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1315
1316                if (isPending) {
1317                    // We need an init before we can proceed with sending backup data.
1318                    // Record that with an entry in our set of pending inits, as well as
1319                    // journaling it via creation of a sentinel file.
1320                    mPendingInits.add(transportName);
1321                    try {
1322                        (new FileOutputStream(initPendingFile)).close();
1323                    } catch (IOException ioe) {
1324                        // Something is badly wrong with our permissions; just try to move on
1325                    }
1326                } else {
1327                    // No more initialization needed; wipe the journal and reset our state.
1328                    initPendingFile.delete();
1329                    mPendingInits.remove(transportName);
1330                }
1331                return; // done; don't fall through to the error case
1332            }
1333        } catch (RemoteException e) {
1334            // transport threw when asked its name; fall through to the lookup-failed case
1335        }
1336
1337        // The named transport doesn't exist or threw.  This operation is
1338        // important, so we record the need for a an init and post a message
1339        // to retry the init later.
1340        if (isPending) {
1341            mPendingInits.add(transportName);
1342            mBackupHandler.sendMessageDelayed(
1343                    mBackupHandler.obtainMessage(MSG_RETRY_INIT,
1344                            (isPending ? 1 : 0),
1345                            0,
1346                            transportName),
1347                    TRANSPORT_RETRY_INTERVAL);
1348        }
1349    }
1350
1351    // Reset all of our bookkeeping, in response to having been told that
1352    // the backend data has been wiped [due to idle expiry, for example],
1353    // so we must re-upload all saved settings.
1354    void resetBackupState(File stateFileDir) {
1355        synchronized (mQueueLock) {
1356            // Wipe the "what we've ever backed up" tracking
1357            mEverStoredApps.clear();
1358            mEverStored.delete();
1359
1360            mCurrentToken = 0;
1361            writeRestoreTokens();
1362
1363            // Remove all the state files
1364            for (File sf : stateFileDir.listFiles()) {
1365                // ... but don't touch the needs-init sentinel
1366                if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1367                    sf.delete();
1368                }
1369            }
1370        }
1371
1372        // Enqueue a new backup of every participant
1373        synchronized (mBackupParticipants) {
1374            final int N = mBackupParticipants.size();
1375            for (int i=0; i<N; i++) {
1376                HashSet<String> participants = mBackupParticipants.valueAt(i);
1377                if (participants != null) {
1378                    for (String packageName : participants) {
1379                        dataChangedImpl(packageName);
1380                    }
1381                }
1382            }
1383        }
1384    }
1385
1386    // Add a transport to our set of available backends.  If 'transport' is null, this
1387    // is an unregistration, and the transport's entry is removed from our bookkeeping.
1388    private void registerTransport(String name, String component, IBackupTransport transport) {
1389        synchronized (mTransports) {
1390            if (DEBUG) Slog.v(TAG, "Registering transport "
1391                    + component + "::" + name + " = " + transport);
1392            if (transport != null) {
1393                mTransports.put(name, transport);
1394                mTransportNames.put(component, name);
1395            } else {
1396                mTransports.remove(mTransportNames.get(component));
1397                mTransportNames.remove(component);
1398                // Nothing further to do in the unregistration case
1399                return;
1400            }
1401        }
1402
1403        // If the init sentinel file exists, we need to be sure to perform the init
1404        // as soon as practical.  We also create the state directory at registration
1405        // time to ensure it's present from the outset.
1406        try {
1407            String transportName = transport.transportDirName();
1408            File stateDir = new File(mBaseStateDir, transportName);
1409            stateDir.mkdirs();
1410
1411            File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1412            if (initSentinel.exists()) {
1413                synchronized (mQueueLock) {
1414                    mPendingInits.add(transportName);
1415
1416                    // TODO: pick a better starting time than now + 1 minute
1417                    long delay = 1000 * 60; // one minute, in milliseconds
1418                    mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1419                            System.currentTimeMillis() + delay, mRunInitIntent);
1420                }
1421            }
1422        } catch (RemoteException e) {
1423            // the transport threw when asked its file naming prefs; declare it invalid
1424            Slog.e(TAG, "Unable to register transport as " + name);
1425            mTransportNames.remove(component);
1426            mTransports.remove(name);
1427        }
1428    }
1429
1430    // ----- Track installation/removal of packages -----
1431    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1432        public void onReceive(Context context, Intent intent) {
1433            if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
1434
1435            String action = intent.getAction();
1436            boolean replacing = false;
1437            boolean added = false;
1438            Bundle extras = intent.getExtras();
1439            String pkgList[] = null;
1440            if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
1441                    Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1442                Uri uri = intent.getData();
1443                if (uri == null) {
1444                    return;
1445                }
1446                String pkgName = uri.getSchemeSpecificPart();
1447                if (pkgName != null) {
1448                    pkgList = new String[] { pkgName };
1449                }
1450                added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1451                replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
1452            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
1453                added = true;
1454                pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1455            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1456                added = false;
1457                pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1458            }
1459
1460            if (pkgList == null || pkgList.length == 0) {
1461                return;
1462            }
1463
1464            final int uid = extras.getInt(Intent.EXTRA_UID);
1465            if (added) {
1466                synchronized (mBackupParticipants) {
1467                    if (replacing) {
1468                        // This is the package-replaced case; we just remove the entry
1469                        // under the old uid and fall through to re-add.
1470                        removePackageParticipantsLocked(pkgList, uid);
1471                    }
1472                    addPackageParticipantsLocked(pkgList);
1473                }
1474            } else {
1475                if (replacing) {
1476                    // The package is being updated.  We'll receive a PACKAGE_ADDED shortly.
1477                } else {
1478                    synchronized (mBackupParticipants) {
1479                        removePackageParticipantsLocked(pkgList, uid);
1480                    }
1481                }
1482            }
1483        }
1484    };
1485
1486    // ----- Track connection to transports service -----
1487    class TransportConnection implements ServiceConnection {
1488        @Override
1489        public void onServiceConnected(ComponentName component, IBinder service) {
1490            if (DEBUG) Slog.v(TAG, "Connected to transport " + component);
1491            try {
1492                IBackupTransport transport = IBackupTransport.Stub.asInterface(service);
1493                registerTransport(transport.name(), component.flattenToShortString(), transport);
1494            } catch (RemoteException e) {
1495                Slog.e(TAG, "Unable to register transport " + component);
1496            }
1497        }
1498
1499        @Override
1500        public void onServiceDisconnected(ComponentName component) {
1501            if (DEBUG) Slog.v(TAG, "Disconnected from transport " + component);
1502            registerTransport(null, component.flattenToShortString(), null);
1503        }
1504    };
1505
1506    // Add the backup agents in the given packages to our set of known backup participants.
1507    // If 'packageNames' is null, adds all backup agents in the whole system.
1508    void addPackageParticipantsLocked(String[] packageNames) {
1509        // Look for apps that define the android:backupAgent attribute
1510        List<PackageInfo> targetApps = allAgentPackages();
1511        if (packageNames != null) {
1512            if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1513            for (String packageName : packageNames) {
1514                addPackageParticipantsLockedInner(packageName, targetApps);
1515            }
1516        } else {
1517            if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1518            addPackageParticipantsLockedInner(null, targetApps);
1519        }
1520    }
1521
1522    private void addPackageParticipantsLockedInner(String packageName,
1523            List<PackageInfo> targetPkgs) {
1524        if (MORE_DEBUG) {
1525            Slog.v(TAG, "Examining " + packageName + " for backup agent");
1526        }
1527
1528        for (PackageInfo pkg : targetPkgs) {
1529            if (packageName == null || pkg.packageName.equals(packageName)) {
1530                int uid = pkg.applicationInfo.uid;
1531                HashSet<String> set = mBackupParticipants.get(uid);
1532                if (set == null) {
1533                    set = new HashSet<String>();
1534                    mBackupParticipants.put(uid, set);
1535                }
1536                set.add(pkg.packageName);
1537                if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
1538
1539                // Schedule a backup for it on general principles
1540                if (DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName);
1541                dataChangedImpl(pkg.packageName);
1542            }
1543        }
1544    }
1545
1546    // Remove the given packages' entries from our known active set.
1547    void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
1548        if (packageNames == null) {
1549            Slog.w(TAG, "removePackageParticipants with null list");
1550            return;
1551        }
1552
1553        if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
1554                + " #" + packageNames.length);
1555        for (String pkg : packageNames) {
1556            // Known previous UID, so we know which package set to check
1557            HashSet<String> set = mBackupParticipants.get(oldUid);
1558            if (set != null && set.contains(pkg)) {
1559                removePackageFromSetLocked(set, pkg);
1560                if (set.isEmpty()) {
1561                    if (MORE_DEBUG) Slog.v(TAG, "  last one of this uid; purging set");
1562                    mBackupParticipants.remove(oldUid);
1563                }
1564            }
1565        }
1566    }
1567
1568    private void removePackageFromSetLocked(final HashSet<String> set,
1569            final String packageName) {
1570        if (set.contains(packageName)) {
1571            // Found it.  Remove this one package from the bookkeeping, and
1572            // if it's the last participating app under this uid we drop the
1573            // (now-empty) set as well.
1574            // Note that we deliberately leave it 'known' in the "ever backed up"
1575            // bookkeeping so that its current-dataset data will be retrieved
1576            // if the app is subsequently reinstalled
1577            if (MORE_DEBUG) Slog.v(TAG, "  removing participant " + packageName);
1578            set.remove(packageName);
1579            mPendingBackups.remove(packageName);
1580        }
1581    }
1582
1583    // Returns the set of all applications that define an android:backupAgent attribute
1584    List<PackageInfo> allAgentPackages() {
1585        // !!! TODO: cache this and regenerate only when necessary
1586        int flags = PackageManager.GET_SIGNATURES;
1587        List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1588        int N = packages.size();
1589        for (int a = N-1; a >= 0; a--) {
1590            PackageInfo pkg = packages.get(a);
1591            try {
1592                ApplicationInfo app = pkg.applicationInfo;
1593                if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
1594                        || app.backupAgentName == null) {
1595                    packages.remove(a);
1596                }
1597                else {
1598                    // we will need the shared library path, so look that up and store it here
1599                    app = mPackageManager.getApplicationInfo(pkg.packageName,
1600                            PackageManager.GET_SHARED_LIBRARY_FILES);
1601                    pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1602                }
1603            } catch (NameNotFoundException e) {
1604                packages.remove(a);
1605            }
1606        }
1607        return packages;
1608    }
1609
1610    // Called from the backup task: record that the given app has been successfully
1611    // backed up at least once
1612    void logBackupComplete(String packageName) {
1613        if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1614
1615        synchronized (mEverStoredApps) {
1616            if (!mEverStoredApps.add(packageName)) return;
1617
1618            RandomAccessFile out = null;
1619            try {
1620                out = new RandomAccessFile(mEverStored, "rws");
1621                out.seek(out.length());
1622                out.writeUTF(packageName);
1623            } catch (IOException e) {
1624                Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
1625            } finally {
1626                try { if (out != null) out.close(); } catch (IOException e) {}
1627            }
1628        }
1629    }
1630
1631    // Remove our awareness of having ever backed up the given package
1632    void removeEverBackedUp(String packageName) {
1633        if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1634        if (MORE_DEBUG) Slog.v(TAG, "New set:");
1635
1636        synchronized (mEverStoredApps) {
1637            // Rewrite the file and rename to overwrite.  If we reboot in the middle,
1638            // we'll recognize on initialization time that the package no longer
1639            // exists and fix it up then.
1640            File tempKnownFile = new File(mBaseStateDir, "processed.new");
1641            RandomAccessFile known = null;
1642            try {
1643                known = new RandomAccessFile(tempKnownFile, "rws");
1644                mEverStoredApps.remove(packageName);
1645                for (String s : mEverStoredApps) {
1646                    known.writeUTF(s);
1647                    if (MORE_DEBUG) Slog.v(TAG, "    " + s);
1648                }
1649                known.close();
1650                known = null;
1651                if (!tempKnownFile.renameTo(mEverStored)) {
1652                    throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1653                }
1654            } catch (IOException e) {
1655                // Bad: we couldn't create the new copy.  For safety's sake we
1656                // abandon the whole process and remove all what's-backed-up
1657                // state entirely, meaning we'll force a backup pass for every
1658                // participant on the next boot or [re]install.
1659                Slog.w(TAG, "Error rewriting " + mEverStored, e);
1660                mEverStoredApps.clear();
1661                tempKnownFile.delete();
1662                mEverStored.delete();
1663            } finally {
1664                try { if (known != null) known.close(); } catch (IOException e) {}
1665            }
1666        }
1667    }
1668
1669    // Persistently record the current and ancestral backup tokens as well
1670    // as the set of packages with data [supposedly] available in the
1671    // ancestral dataset.
1672    void writeRestoreTokens() {
1673        try {
1674            RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
1675
1676            // First, the version number of this record, for futureproofing
1677            af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1678
1679            // Write the ancestral and current tokens
1680            af.writeLong(mAncestralToken);
1681            af.writeLong(mCurrentToken);
1682
1683            // Now write the set of ancestral packages
1684            if (mAncestralPackages == null) {
1685                af.writeInt(-1);
1686            } else {
1687                af.writeInt(mAncestralPackages.size());
1688                if (DEBUG) Slog.v(TAG, "Ancestral packages:  " + mAncestralPackages.size());
1689                for (String pkgName : mAncestralPackages) {
1690                    af.writeUTF(pkgName);
1691                    if (MORE_DEBUG) Slog.v(TAG, "   " + pkgName);
1692                }
1693            }
1694            af.close();
1695        } catch (IOException e) {
1696            Slog.w(TAG, "Unable to write token file:", e);
1697        }
1698    }
1699
1700    // Return the given transport
1701    private IBackupTransport getTransport(String transportName) {
1702        synchronized (mTransports) {
1703            IBackupTransport transport = mTransports.get(transportName);
1704            if (transport == null) {
1705                Slog.w(TAG, "Requested unavailable transport: " + transportName);
1706            }
1707            return transport;
1708        }
1709    }
1710
1711    // fire off a backup agent, blocking until it attaches or times out
1712    IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1713        IBackupAgent agent = null;
1714        synchronized(mAgentConnectLock) {
1715            mConnecting = true;
1716            mConnectedAgent = null;
1717            try {
1718                if (mActivityManager.bindBackupAgent(app, mode)) {
1719                    Slog.d(TAG, "awaiting agent for " + app);
1720
1721                    // success; wait for the agent to arrive
1722                    // only wait 10 seconds for the bind to happen
1723                    long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1724                    while (mConnecting && mConnectedAgent == null
1725                            && (System.currentTimeMillis() < timeoutMark)) {
1726                        try {
1727                            mAgentConnectLock.wait(5000);
1728                        } catch (InterruptedException e) {
1729                            // just bail
1730                            if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
1731                            mActivityManager.clearPendingBackup();
1732                            return null;
1733                        }
1734                    }
1735
1736                    // if we timed out with no connect, abort and move on
1737                    if (mConnecting == true) {
1738                        Slog.w(TAG, "Timeout waiting for agent " + app);
1739                        mActivityManager.clearPendingBackup();
1740                        return null;
1741                    }
1742                    if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
1743                    agent = mConnectedAgent;
1744                }
1745            } catch (RemoteException e) {
1746                // can't happen - ActivityManager is local
1747            }
1748        }
1749        return agent;
1750    }
1751
1752    // clear an application's data, blocking until the operation completes or times out
1753    void clearApplicationDataSynchronous(String packageName) {
1754        // Don't wipe packages marked allowClearUserData=false
1755        try {
1756            PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1757            if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
1758                if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
1759                        + packageName);
1760                return;
1761            }
1762        } catch (NameNotFoundException e) {
1763            Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
1764            return;
1765        }
1766
1767        ClearDataObserver observer = new ClearDataObserver();
1768
1769        synchronized(mClearDataLock) {
1770            mClearingData = true;
1771            try {
1772                mActivityManager.clearApplicationUserData(packageName, observer, 0);
1773            } catch (RemoteException e) {
1774                // can't happen because the activity manager is in this process
1775            }
1776
1777            // only wait 10 seconds for the clear data to happen
1778            long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1779            while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1780                try {
1781                    mClearDataLock.wait(5000);
1782                } catch (InterruptedException e) {
1783                    // won't happen, but still.
1784                    mClearingData = false;
1785                }
1786            }
1787        }
1788    }
1789
1790    class ClearDataObserver extends IPackageDataObserver.Stub {
1791        public void onRemoveCompleted(String packageName, boolean succeeded) {
1792            synchronized(mClearDataLock) {
1793                mClearingData = false;
1794                mClearDataLock.notifyAll();
1795            }
1796        }
1797    }
1798
1799    // Get the restore-set token for the best-available restore set for this package:
1800    // the active set if possible, else the ancestral one.  Returns zero if none available.
1801    long getAvailableRestoreToken(String packageName) {
1802        long token = mAncestralToken;
1803        synchronized (mQueueLock) {
1804            if (mEverStoredApps.contains(packageName)) {
1805                token = mCurrentToken;
1806            }
1807        }
1808        return token;
1809    }
1810
1811    // -----
1812    // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1813
1814    interface BackupRestoreTask {
1815        // Execute one tick of whatever state machine the task implements
1816        void execute();
1817
1818        // An operation that wanted a callback has completed
1819        void operationComplete();
1820
1821        // An operation that wanted a callback has timed out
1822        void handleTimeout();
1823    }
1824
1825    void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1826        if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1827                + " interval=" + interval);
1828        synchronized (mCurrentOpLock) {
1829            mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1830
1831            Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1832            mBackupHandler.sendMessageDelayed(msg, interval);
1833        }
1834    }
1835
1836    // synchronous waiter case
1837    boolean waitUntilOperationComplete(int token) {
1838        if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1839                + Integer.toHexString(token));
1840        int finalState = OP_PENDING;
1841        Operation op = null;
1842        synchronized (mCurrentOpLock) {
1843            while (true) {
1844                op = mCurrentOperations.get(token);
1845                if (op == null) {
1846                    // mysterious disappearance: treat as success with no callback
1847                    break;
1848                } else {
1849                    if (op.state == OP_PENDING) {
1850                        try {
1851                            mCurrentOpLock.wait();
1852                        } catch (InterruptedException e) {}
1853                        // When the wait is notified we loop around and recheck the current state
1854                    } else {
1855                        // No longer pending; we're done
1856                        finalState = op.state;
1857                        break;
1858                    }
1859                }
1860            }
1861        }
1862
1863        mBackupHandler.removeMessages(MSG_TIMEOUT);
1864        if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
1865                + " complete: finalState=" + finalState);
1866        return finalState == OP_ACKNOWLEDGED;
1867    }
1868
1869    void handleTimeout(int token, Object obj) {
1870        // Notify any synchronous waiters
1871        Operation op = null;
1872        synchronized (mCurrentOpLock) {
1873            op = mCurrentOperations.get(token);
1874            if (MORE_DEBUG) {
1875                if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1876                        + " but no op found");
1877            }
1878            int state = (op != null) ? op.state : OP_TIMEOUT;
1879            if (state == OP_PENDING) {
1880                if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1881                op.state = OP_TIMEOUT;
1882                mCurrentOperations.put(token, op);
1883            }
1884            mCurrentOpLock.notifyAll();
1885        }
1886
1887        // If there's a TimeoutHandler for this event, call it
1888        if (op != null && op.callback != null) {
1889            op.callback.handleTimeout();
1890        }
1891    }
1892
1893    // ----- Back up a set of applications via a worker thread -----
1894
1895    enum BackupState {
1896        INITIAL,
1897        RUNNING_QUEUE,
1898        FINAL
1899    }
1900
1901    class PerformBackupTask implements BackupRestoreTask {
1902        private static final String TAG = "PerformBackupTask";
1903
1904        IBackupTransport mTransport;
1905        ArrayList<BackupRequest> mQueue;
1906        ArrayList<BackupRequest> mOriginalQueue;
1907        File mStateDir;
1908        File mJournal;
1909        BackupState mCurrentState;
1910
1911        // carried information about the current in-flight operation
1912        PackageInfo mCurrentPackage;
1913        File mSavedStateName;
1914        File mBackupDataName;
1915        File mNewStateName;
1916        ParcelFileDescriptor mSavedState;
1917        ParcelFileDescriptor mBackupData;
1918        ParcelFileDescriptor mNewState;
1919        int mStatus;
1920        boolean mFinished;
1921
1922        public PerformBackupTask(IBackupTransport transport, String dirName,
1923                ArrayList<BackupRequest> queue, File journal) {
1924            mTransport = transport;
1925            mOriginalQueue = queue;
1926            mJournal = journal;
1927
1928            mStateDir = new File(mBaseStateDir, dirName);
1929
1930            mCurrentState = BackupState.INITIAL;
1931            mFinished = false;
1932
1933            addBackupTrace("STATE => INITIAL");
1934        }
1935
1936        // Main entry point: perform one chunk of work, updating the state as appropriate
1937        // and reposting the next chunk to the primary backup handler thread.
1938        @Override
1939        public void execute() {
1940            switch (mCurrentState) {
1941                case INITIAL:
1942                    beginBackup();
1943                    break;
1944
1945                case RUNNING_QUEUE:
1946                    invokeNextAgent();
1947                    break;
1948
1949                case FINAL:
1950                    if (!mFinished) finalizeBackup();
1951                    else {
1952                        Slog.e(TAG, "Duplicate finish");
1953                    }
1954                    mFinished = true;
1955                    break;
1956            }
1957        }
1958
1959        // We're starting a backup pass.  Initialize the transport and send
1960        // the PM metadata blob if we haven't already.
1961        void beginBackup() {
1962            if (DEBUG_BACKUP_TRACE) {
1963                clearBackupTrace();
1964                StringBuilder b = new StringBuilder(256);
1965                b.append("beginBackup: [");
1966                for (BackupRequest req : mOriginalQueue) {
1967                    b.append(' ');
1968                    b.append(req.packageName);
1969                }
1970                b.append(" ]");
1971                addBackupTrace(b.toString());
1972            }
1973
1974            mStatus = BackupConstants.TRANSPORT_OK;
1975
1976            // Sanity check: if the queue is empty we have no work to do.
1977            if (mOriginalQueue.isEmpty()) {
1978                Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
1979                addBackupTrace("queue empty at begin");
1980                executeNextState(BackupState.FINAL);
1981                return;
1982            }
1983
1984            // We need to retain the original queue contents in case of transport
1985            // failure, but we want a working copy that we can manipulate along
1986            // the way.
1987            mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1988
1989            if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1990
1991            File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1992            try {
1993                final String transportName = mTransport.transportDirName();
1994                EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
1995
1996                // If we haven't stored package manager metadata yet, we must init the transport.
1997                if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
1998                    Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
1999                    addBackupTrace("initializing transport " + transportName);
2000                    resetBackupState(mStateDir);  // Just to make sure.
2001                    mStatus = mTransport.initializeDevice();
2002
2003                    addBackupTrace("transport.initializeDevice() == " + mStatus);
2004                    if (mStatus == BackupConstants.TRANSPORT_OK) {
2005                        EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
2006                    } else {
2007                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
2008                        Slog.e(TAG, "Transport error in initializeDevice()");
2009                    }
2010                }
2011
2012                // The package manager doesn't have a proper <application> etc, but since
2013                // it's running here in the system process we can just set up its agent
2014                // directly and use a synthetic BackupRequest.  We always run this pass
2015                // because it's cheap and this way we guarantee that we don't get out of
2016                // step even if we're selecting among various transports at run time.
2017                if (mStatus == BackupConstants.TRANSPORT_OK) {
2018                    PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
2019                            mPackageManager, allAgentPackages());
2020                    mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
2021                            IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
2022                    addBackupTrace("PMBA invoke: " + mStatus);
2023                }
2024
2025                if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
2026                    // The backend reports that our dataset has been wiped.  Note this in
2027                    // the event log; the no-success code below will reset the backup
2028                    // state as well.
2029                    EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
2030                }
2031            } catch (Exception e) {
2032                Slog.e(TAG, "Error in backup thread", e);
2033                addBackupTrace("Exception in backup thread: " + e);
2034                mStatus = BackupConstants.TRANSPORT_ERROR;
2035            } finally {
2036                // If we've succeeded so far, invokeAgentForBackup() will have run the PM
2037                // metadata and its completion/timeout callback will continue the state
2038                // machine chain.  If it failed that won't happen; we handle that now.
2039                addBackupTrace("exiting prelim: " + mStatus);
2040                if (mStatus != BackupConstants.TRANSPORT_OK) {
2041                    // if things went wrong at this point, we need to
2042                    // restage everything and try again later.
2043                    resetBackupState(mStateDir);  // Just to make sure.
2044                    executeNextState(BackupState.FINAL);
2045                }
2046            }
2047        }
2048
2049        // Transport has been initialized and the PM metadata submitted successfully
2050        // if that was warranted.  Now we process the single next thing in the queue.
2051        void invokeNextAgent() {
2052            mStatus = BackupConstants.TRANSPORT_OK;
2053            addBackupTrace("invoke q=" + mQueue.size());
2054
2055            // Sanity check that we have work to do.  If not, skip to the end where
2056            // we reestablish the wakelock invariants etc.
2057            if (mQueue.isEmpty()) {
2058                if (DEBUG) Slog.i(TAG, "queue now empty");
2059                executeNextState(BackupState.FINAL);
2060                return;
2061            }
2062
2063            // pop the entry we're going to process on this step
2064            BackupRequest request = mQueue.get(0);
2065            mQueue.remove(0);
2066
2067            Slog.d(TAG, "starting agent for backup of " + request);
2068            addBackupTrace("launch agent for " + request.packageName);
2069
2070            // Verify that the requested app exists; it might be something that
2071            // requested a backup but was then uninstalled.  The request was
2072            // journalled and rather than tamper with the journal it's safer
2073            // to sanity-check here.  This also gives us the classname of the
2074            // package's backup agent.
2075            try {
2076                mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
2077                        PackageManager.GET_SIGNATURES);
2078                if (mCurrentPackage.applicationInfo.backupAgentName == null) {
2079                    // The manifest has changed but we had a stale backup request pending.
2080                    // This won't happen again because the app won't be requesting further
2081                    // backups.
2082                    Slog.i(TAG, "Package " + request.packageName
2083                            + " no longer supports backup; skipping");
2084                    addBackupTrace("skipping - no agent, completion is noop");
2085                    executeNextState(BackupState.RUNNING_QUEUE);
2086                    return;
2087                }
2088
2089                if ((mCurrentPackage.applicationInfo.flags & ApplicationInfo.FLAG_STOPPED) != 0) {
2090                    // The app has been force-stopped or cleared or just installed,
2091                    // and not yet launched out of that state, so just as it won't
2092                    // receive broadcasts, we won't run it for backup.
2093                    addBackupTrace("skipping - stopped");
2094                    executeNextState(BackupState.RUNNING_QUEUE);
2095                    return;
2096                }
2097
2098                IBackupAgent agent = null;
2099                try {
2100                    mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
2101                    agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
2102                            IApplicationThread.BACKUP_MODE_INCREMENTAL);
2103                    addBackupTrace("agent bound; a? = " + (agent != null));
2104                    if (agent != null) {
2105                        mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
2106                        // at this point we'll either get a completion callback from the
2107                        // agent, or a timeout message on the main handler.  either way, we're
2108                        // done here as long as we're successful so far.
2109                    } else {
2110                        // Timeout waiting for the agent
2111                        mStatus = BackupConstants.AGENT_ERROR;
2112                    }
2113                } catch (SecurityException ex) {
2114                    // Try for the next one.
2115                    Slog.d(TAG, "error in bind/backup", ex);
2116                    mStatus = BackupConstants.AGENT_ERROR;
2117                            addBackupTrace("agent SE");
2118                }
2119            } catch (NameNotFoundException e) {
2120                Slog.d(TAG, "Package does not exist; skipping");
2121                addBackupTrace("no such package");
2122                mStatus = BackupConstants.AGENT_UNKNOWN;
2123            } finally {
2124                mWakelock.setWorkSource(null);
2125
2126                // If there was an agent error, no timeout/completion handling will occur.
2127                // That means we need to direct to the next state ourselves.
2128                if (mStatus != BackupConstants.TRANSPORT_OK) {
2129                    BackupState nextState = BackupState.RUNNING_QUEUE;
2130
2131                    // An agent-level failure means we reenqueue this one agent for
2132                    // a later retry, but otherwise proceed normally.
2133                    if (mStatus == BackupConstants.AGENT_ERROR) {
2134                        if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2135                                + " - restaging");
2136                        dataChangedImpl(request.packageName);
2137                        mStatus = BackupConstants.TRANSPORT_OK;
2138                        if (mQueue.isEmpty()) nextState = BackupState.FINAL;
2139                    } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2140                        // Failed lookup of the app, so we couldn't bring up an agent, but
2141                        // we're otherwise fine.  Just drop it and go on to the next as usual.
2142                        mStatus = BackupConstants.TRANSPORT_OK;
2143                    } else {
2144                        // Transport-level failure means we reenqueue everything
2145                        revertAndEndBackup();
2146                        nextState = BackupState.FINAL;
2147                    }
2148
2149                    executeNextState(nextState);
2150                } else {
2151                    addBackupTrace("expecting completion/timeout callback");
2152                }
2153            }
2154        }
2155
2156        void finalizeBackup() {
2157            addBackupTrace("finishing");
2158
2159            // Either backup was successful, in which case we of course do not need
2160            // this pass's journal any more; or it failed, in which case we just
2161            // re-enqueued all of these packages in the current active journal.
2162            // Either way, we no longer need this pass's journal.
2163            if (mJournal != null && !mJournal.delete()) {
2164                Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2165            }
2166
2167            // If everything actually went through and this is the first time we've
2168            // done a backup, we can now record what the current backup dataset token
2169            // is.
2170            if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
2171                addBackupTrace("success; recording token");
2172                try {
2173                    mCurrentToken = mTransport.getCurrentRestoreSet();
2174                    writeRestoreTokens();
2175                } catch (RemoteException e) {
2176                    // nothing for it at this point, unfortunately, but this will be
2177                    // recorded the next time we fully succeed.
2178                    addBackupTrace("transport threw returning token");
2179                }
2180            }
2181
2182            // Set up the next backup pass - at this point we can set mBackupRunning
2183            // to false to allow another pass to fire, because we're done with the
2184            // state machine sequence and the wakelock is refcounted.
2185            synchronized (mQueueLock) {
2186                mBackupRunning = false;
2187                if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
2188                    // Make sure we back up everything and perform the one-time init
2189                    clearMetadata();
2190                    if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
2191                    addBackupTrace("init required; rerunning");
2192                    backupNow();
2193                }
2194            }
2195
2196            // Only once we're entirely finished do we release the wakelock
2197            clearBackupTrace();
2198            Slog.i(TAG, "Backup pass finished.");
2199            mWakelock.release();
2200        }
2201
2202        // Remove the PM metadata state. This will generate an init on the next pass.
2203        void clearMetadata() {
2204            final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2205            if (pmState.exists()) pmState.delete();
2206        }
2207
2208        // Invoke an agent's doBackup() and start a timeout message spinning on the main
2209        // handler in case it doesn't get back to us.
2210        int invokeAgentForBackup(String packageName, IBackupAgent agent,
2211                IBackupTransport transport) {
2212            if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2213            addBackupTrace("invoking " + packageName);
2214
2215            mSavedStateName = new File(mStateDir, packageName);
2216            mBackupDataName = new File(mDataDir, packageName + ".data");
2217            mNewStateName = new File(mStateDir, packageName + ".new");
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