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