BackupManagerService.java revision a96694b49b545be38794264a5dbe494de9784da0
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 static android.app.backup.BackupManagerMonitor.EXTRA_LOG_EVENT_PACKAGE_NAME;
20import static android.app.backup.BackupManagerMonitor.EXTRA_LOG_EVENT_PACKAGE_VERSION;
21import static android.app.backup.BackupManagerMonitor.EXTRA_LOG_OLD_VERSION;
22import static android.app.backup.BackupManagerMonitor.EXTRA_LOG_POLICY_ALLOW_APKS;
23import static android.app.backup.BackupManagerMonitor.EXTRA_LOG_MANIFEST_PACKAGE_NAME;
24import static android.app.backup.BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT;
25import static android.app.backup.BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY;
26import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_VERSION_OF_BACKUP_OLDER;
27import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_FULL_RESTORE_SIGNATURE_MISMATCH;
28import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_SYSTEM_APP_NO_AGENT;
29import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_FULL_RESTORE_ALLOW_BACKUP_FALSE;
30import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_APK_NOT_INSTALLED;
31import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_CANNOT_RESTORE_WITHOUT_APK;
32import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_MISSING_SIGNATURE;
33import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_EXPECTED_DIFFERENT_PACKAGE;
34import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_RESTORE_ANY_VERSION;
35import static android.app.backup.BackupManagerMonitor.LOG_EVENT_ID_VERSIONS_MATCH;
36import static android.content.pm.ApplicationInfo.PRIVATE_FLAG_BACKUP_IN_FOREGROUND;
37
38import android.app.ActivityManager;
39import android.app.AlarmManager;
40import android.app.AppGlobals;
41import android.app.ApplicationThreadConstants;
42import android.app.IActivityManager;
43import android.app.IBackupAgent;
44import android.app.PackageInstallObserver;
45import android.app.PendingIntent;
46import android.app.backup.BackupAgent;
47import android.app.backup.BackupDataInput;
48import android.app.backup.BackupDataOutput;
49import android.app.backup.BackupManager;
50import android.app.backup.BackupManagerMonitor;
51import android.app.backup.BackupProgress;
52import android.app.backup.BackupTransport;
53import android.app.backup.FullBackup;
54import android.app.backup.FullBackupDataOutput;
55import android.app.backup.IBackupManager;
56import android.app.backup.IBackupManagerMonitor;
57import android.app.backup.IBackupObserver;
58import android.app.backup.IFullBackupRestoreObserver;
59import android.app.backup.IRestoreObserver;
60import android.app.backup.IRestoreSession;
61import android.app.backup.ISelectBackupTransportCallback;
62import android.app.backup.RestoreDescription;
63import android.app.backup.RestoreSet;
64import android.app.backup.SelectBackupTransportCallback;
65import android.content.ActivityNotFoundException;
66import android.content.BroadcastReceiver;
67import android.content.ComponentName;
68import android.content.ContentResolver;
69import android.content.Context;
70import android.content.Intent;
71import android.content.IntentFilter;
72import android.content.ServiceConnection;
73import android.content.pm.ApplicationInfo;
74import android.content.pm.IPackageDataObserver;
75import android.content.pm.IPackageDeleteObserver;
76import android.content.pm.IPackageManager;
77import android.content.pm.PackageInfo;
78import android.content.pm.PackageManager;
79import android.content.pm.PackageManager.NameNotFoundException;
80import android.content.pm.Signature;
81import android.database.ContentObserver;
82import android.net.Uri;
83import android.os.PowerSaveState;
84import android.os.Binder;
85import android.os.Build;
86import android.os.Bundle;
87import android.os.Environment;
88import android.os.Environment.UserEnvironment;
89import android.os.Handler;
90import android.os.HandlerThread;
91import android.os.IBinder;
92import android.os.Looper;
93import android.os.Message;
94import android.os.ParcelFileDescriptor;
95import android.os.PowerManager;
96import android.os.Process;
97import android.os.RemoteException;
98import android.os.SELinux;
99import android.os.ServiceManager;
100import android.os.SystemClock;
101import android.os.UserHandle;
102import android.os.WorkSource;
103import android.os.storage.IStorageManager;
104import android.os.storage.StorageManager;
105import android.provider.Settings;
106import android.system.ErrnoException;
107import android.system.Os;
108import android.text.TextUtils;
109import android.util.AtomicFile;
110import android.util.EventLog;
111import android.util.Log;
112import android.util.Pair;
113import android.util.Slog;
114import android.util.SparseArray;
115import android.util.StringBuilderPrinter;
116
117import com.android.internal.annotations.GuardedBy;
118import com.android.internal.backup.IBackupTransport;
119import com.android.internal.backup.IObbBackupService;
120import com.android.internal.util.DumpUtils;
121import com.android.server.AppWidgetBackupBridge;
122import com.android.server.EventLogTags;
123import com.android.server.SystemConfig;
124import com.android.server.SystemService;
125import com.android.server.backup.PackageManagerBackupAgent.Metadata;
126
127import com.android.server.power.BatterySaverPolicy.ServiceType;
128import libcore.io.IoUtils;
129
130import java.io.BufferedInputStream;
131import java.io.BufferedOutputStream;
132import java.io.ByteArrayInputStream;
133import java.io.ByteArrayOutputStream;
134import java.io.DataInputStream;
135import java.io.DataOutputStream;
136import java.io.EOFException;
137import java.io.File;
138import java.io.FileDescriptor;
139import java.io.FileInputStream;
140import java.io.FileNotFoundException;
141import java.io.FileOutputStream;
142import java.io.IOException;
143import java.io.InputStream;
144import java.io.OutputStream;
145import java.io.PrintWriter;
146import java.io.RandomAccessFile;
147import java.security.InvalidAlgorithmParameterException;
148import java.security.InvalidKeyException;
149import java.security.Key;
150import java.security.MessageDigest;
151import java.security.NoSuchAlgorithmException;
152import java.security.SecureRandom;
153import java.security.spec.InvalidKeySpecException;
154import java.security.spec.KeySpec;
155import java.text.SimpleDateFormat;
156import java.util.ArrayDeque;
157import java.util.ArrayList;
158import java.util.Arrays;
159import java.util.Collections;
160import java.util.Date;
161import java.util.HashMap;
162import java.util.HashSet;
163import java.util.Iterator;
164import java.util.List;
165import java.util.Map.Entry;
166import java.util.Objects;
167import java.util.Queue;
168import java.util.Random;
169import java.util.Set;
170import java.util.TreeMap;
171import java.util.concurrent.CountDownLatch;
172import java.util.concurrent.TimeUnit;
173import java.util.concurrent.atomic.AtomicBoolean;
174import java.util.concurrent.atomic.AtomicInteger;
175import java.util.concurrent.atomic.AtomicLong;
176import java.util.zip.Deflater;
177import java.util.zip.DeflaterOutputStream;
178import java.util.zip.InflaterInputStream;
179
180import javax.crypto.BadPaddingException;
181import javax.crypto.Cipher;
182import javax.crypto.CipherInputStream;
183import javax.crypto.CipherOutputStream;
184import javax.crypto.IllegalBlockSizeException;
185import javax.crypto.NoSuchPaddingException;
186import javax.crypto.SecretKey;
187import javax.crypto.SecretKeyFactory;
188import javax.crypto.spec.IvParameterSpec;
189import javax.crypto.spec.PBEKeySpec;
190import javax.crypto.spec.SecretKeySpec;
191
192public class BackupManagerService implements BackupManagerServiceInterface {
193
194    private static final String TAG = "BackupManagerService";
195    static final boolean DEBUG = true;
196    static final boolean MORE_DEBUG = false;
197    static final boolean DEBUG_SCHEDULING = MORE_DEBUG || true;
198
199    // File containing backup-enabled state.  Contains a single byte;
200    // nonzero == enabled.  File missing or contains a zero byte == disabled.
201    static final String BACKUP_ENABLE_FILE = "backup_enabled";
202
203    // System-private key used for backing up an app's widget state.  Must
204    // begin with U+FFxx by convention (we reserve all keys starting
205    // with U+FF00 or higher for system use).
206    static final String KEY_WIDGET_STATE = "\uffed\uffedwidget";
207
208    // Historical and current algorithm names
209    static final String PBKDF_CURRENT = "PBKDF2WithHmacSHA1";
210    static final String PBKDF_FALLBACK = "PBKDF2WithHmacSHA1And8bit";
211
212    // Name and current contents version of the full-backup manifest file
213    //
214    // Manifest version history:
215    //
216    // 1 : initial release
217    static final String BACKUP_MANIFEST_FILENAME = "_manifest";
218    static final int BACKUP_MANIFEST_VERSION = 1;
219
220    // External archive format version history:
221    //
222    // 1 : initial release
223    // 2 : no format change per se; version bump to facilitate PBKDF2 version skew detection
224    // 3 : introduced "_meta" metadata file; no other format change per se
225    // 4 : added support for new device-encrypted storage locations
226    // 5 : added support for key-value packages
227    static final int BACKUP_FILE_VERSION = 5;
228    static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
229    static final int BACKUP_PW_FILE_VERSION = 2;
230    static final String BACKUP_METADATA_FILENAME = "_meta";
231    static final int BACKUP_METADATA_VERSION = 1;
232    static final int BACKUP_WIDGET_METADATA_TOKEN = 0x01FFED01;
233
234    static final int TAR_HEADER_LONG_RADIX = 8;
235    static final int TAR_HEADER_OFFSET_FILESIZE = 124;
236    static final int TAR_HEADER_LENGTH_FILESIZE = 12;
237    static final int TAR_HEADER_OFFSET_MODTIME = 136;
238    static final int TAR_HEADER_LENGTH_MODTIME = 12;
239    static final int TAR_HEADER_OFFSET_MODE = 100;
240    static final int TAR_HEADER_LENGTH_MODE = 8;
241    static final int TAR_HEADER_OFFSET_PATH_PREFIX = 345;
242    static final int TAR_HEADER_LENGTH_PATH_PREFIX = 155;
243    static final int TAR_HEADER_OFFSET_PATH = 0;
244    static final int TAR_HEADER_LENGTH_PATH = 100;
245    static final int TAR_HEADER_OFFSET_TYPE_CHAR = 156;
246
247    static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
248
249    static final String SETTINGS_PACKAGE = "com.android.providers.settings";
250    static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
251    static final String SERVICE_ACTION_TRANSPORT_HOST = "android.backup.TRANSPORT_HOST";
252
253    // Retry interval for clear/init when the transport is unavailable
254    private static final long TRANSPORT_RETRY_INTERVAL = 1 * AlarmManager.INTERVAL_HOUR;
255
256    private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
257    private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
258    private static final int MSG_RUN_BACKUP = 1;
259    private static final int MSG_RUN_ADB_BACKUP = 2;
260    private static final int MSG_RUN_RESTORE = 3;
261    private static final int MSG_RUN_CLEAR = 4;
262    private static final int MSG_RUN_INITIALIZE = 5;
263    private static final int MSG_RUN_GET_RESTORE_SETS = 6;
264    private static final int MSG_RESTORE_SESSION_TIMEOUT = 8;
265    private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
266    private static final int MSG_RUN_ADB_RESTORE = 10;
267    private static final int MSG_RETRY_INIT = 11;
268    private static final int MSG_RETRY_CLEAR = 12;
269    private static final int MSG_WIDGET_BROADCAST = 13;
270    private static final int MSG_RUN_FULL_TRANSPORT_BACKUP = 14;
271    private static final int MSG_REQUEST_BACKUP = 15;
272    private static final int MSG_SCHEDULE_BACKUP_PACKAGE = 16;
273    private static final int MSG_BACKUP_OPERATION_TIMEOUT = 17;
274    private static final int MSG_RESTORE_OPERATION_TIMEOUT = 18;
275
276    // backup task state machine tick
277    static final int MSG_BACKUP_RESTORE_STEP = 20;
278    static final int MSG_OP_COMPLETE = 21;
279
280    // Timeout interval for deciding that a bind or clear-data has taken too long
281    static final long TIMEOUT_INTERVAL = 10 * 1000;
282
283    // Timeout intervals for agent backup & restore operations
284    static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
285    static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
286    static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
287    static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
288    static final long TIMEOUT_RESTORE_FINISHED_INTERVAL = 30 * 1000;
289
290    // User confirmation timeout for a full backup/restore operation.  It's this long in
291    // order to give them time to enter the backup password.
292    static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
293
294    // How long between attempts to perform a full-data backup of any given app
295    static final long MIN_FULL_BACKUP_INTERVAL = 1000 * 60 * 60 * 24; // one day
296
297    // If an app is busy when we want to do a full-data backup, how long to defer the retry.
298    // This is fuzzed, so there are two parameters; backoff_min + Rand[0, backoff_fuzz)
299    static final long BUSY_BACKOFF_MIN_MILLIS = 1000 * 60 * 60;  // one hour
300    static final int BUSY_BACKOFF_FUZZ = 1000 * 60 * 60 * 2;  // two hours
301
302    Context mContext;
303    private PackageManager mPackageManager;
304    IPackageManager mPackageManagerBinder;
305    private IActivityManager mActivityManager;
306    private PowerManager mPowerManager;
307    private AlarmManager mAlarmManager;
308    private IStorageManager mStorageManager;
309
310    IBackupManager mBackupManagerBinder;
311
312    private final TransportManager mTransportManager;
313
314    boolean mEnabled;   // access to this is synchronized on 'this'
315    boolean mProvisioned;
316    boolean mAutoRestore;
317    PowerManager.WakeLock mWakelock;
318    HandlerThread mHandlerThread;
319    BackupHandler mBackupHandler;
320    PendingIntent mRunBackupIntent, mRunInitIntent;
321    BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
322    // map UIDs to the set of participating packages under that UID
323    final SparseArray<HashSet<String>> mBackupParticipants
324            = new SparseArray<HashSet<String>>();
325    // set of backup services that have pending changes
326    class BackupRequest {
327        public String packageName;
328
329        BackupRequest(String pkgName) {
330            packageName = pkgName;
331        }
332
333        public String toString() {
334            return "BackupRequest{pkg=" + packageName + "}";
335        }
336    }
337    // Backups that we haven't started yet.  Keys are package names.
338    HashMap<String,BackupRequest> mPendingBackups
339            = new HashMap<String,BackupRequest>();
340
341    // Pseudoname that we use for the Package Manager metadata "package"
342    static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
343
344    // locking around the pending-backup management
345    final Object mQueueLock = new Object();
346
347    // The thread performing the sequence of queued backups binds to each app's agent
348    // in succession.  Bind notifications are asynchronously delivered through the
349    // Activity Manager; use this lock object to signal when a requested binding has
350    // completed.
351    final Object mAgentConnectLock = new Object();
352    IBackupAgent mConnectedAgent;
353    volatile boolean mBackupRunning;
354    volatile boolean mConnecting;
355    volatile long mLastBackupPass;
356
357    // For debugging, we maintain a progress trace of operations during backup
358    static final boolean DEBUG_BACKUP_TRACE = true;
359    final List<String> mBackupTrace = new ArrayList<String>();
360
361    // A similar synchronization mechanism around clearing apps' data for restore
362    final Object mClearDataLock = new Object();
363    volatile boolean mClearingData;
364
365    @GuardedBy("mPendingRestores")
366    private boolean mIsRestoreInProgress;
367    @GuardedBy("mPendingRestores")
368    private final Queue<PerformUnifiedRestoreTask> mPendingRestores = new ArrayDeque<>();
369
370    ActiveRestoreSession mActiveRestoreSession;
371
372    // Watch the device provisioning operation during setup
373    ContentObserver mProvisionedObserver;
374
375    // The published binder is actually to a singleton trampoline object that calls
376    // through to the proper code.  This indirection lets us turn down the heavy
377    // implementation object on the fly without disturbing binders that have been
378    // cached elsewhere in the system.
379    static Trampoline sInstance;
380    static Trampoline getInstance() {
381        // Always constructed during system bringup, so no need to lazy-init
382        return sInstance;
383    }
384
385    public static final class Lifecycle extends SystemService {
386
387        public Lifecycle(Context context) {
388            super(context);
389            sInstance = new Trampoline(context);
390        }
391
392        @Override
393        public void onStart() {
394            publishBinderService(Context.BACKUP_SERVICE, sInstance);
395        }
396
397        @Override
398        public void onUnlockUser(int userId) {
399            if (userId == UserHandle.USER_SYSTEM) {
400                sInstance.initialize(userId);
401
402                // Migrate legacy setting
403                if (!backupSettingMigrated(userId)) {
404                    if (DEBUG) {
405                        Slog.i(TAG, "Backup enable apparently not migrated");
406                    }
407                    final ContentResolver r = sInstance.mContext.getContentResolver();
408                    final int enableState = Settings.Secure.getIntForUser(r,
409                            Settings.Secure.BACKUP_ENABLED, -1, userId);
410                    if (enableState >= 0) {
411                        if (DEBUG) {
412                            Slog.i(TAG, "Migrating enable state " + (enableState != 0));
413                        }
414                        writeBackupEnableState(enableState != 0, userId);
415                        Settings.Secure.putStringForUser(r,
416                                Settings.Secure.BACKUP_ENABLED, null, userId);
417                    } else {
418                        if (DEBUG) {
419                            Slog.i(TAG, "Backup not yet configured; retaining null enable state");
420                        }
421                    }
422                }
423
424                try {
425                    sInstance.setBackupEnabled(readBackupEnableState(userId));
426                } catch (RemoteException e) {
427                    // can't happen; it's a local object
428                }
429            }
430        }
431    }
432
433    class ProvisionedObserver extends ContentObserver {
434        public ProvisionedObserver(Handler handler) {
435            super(handler);
436        }
437
438        public void onChange(boolean selfChange) {
439            final boolean wasProvisioned = mProvisioned;
440            final boolean isProvisioned = deviceIsProvisioned();
441            // latch: never unprovision
442            mProvisioned = wasProvisioned || isProvisioned;
443            if (MORE_DEBUG) {
444                Slog.d(TAG, "Provisioning change: was=" + wasProvisioned
445                        + " is=" + isProvisioned + " now=" + mProvisioned);
446            }
447
448            synchronized (mQueueLock) {
449                if (mProvisioned && !wasProvisioned && mEnabled) {
450                    // we're now good to go, so start the backup alarms
451                    if (MORE_DEBUG) Slog.d(TAG, "Now provisioned, so starting backups");
452                    KeyValueBackupJob.schedule(mContext);
453                    scheduleNextFullBackupJob(0);
454                }
455            }
456        }
457    }
458
459    class RestoreGetSetsParams {
460        public IBackupTransport transport;
461        public ActiveRestoreSession session;
462        public IRestoreObserver observer;
463        public IBackupManagerMonitor monitor;
464
465        RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
466                IRestoreObserver _observer, IBackupManagerMonitor _monitor) {
467            transport = _transport;
468            session = _session;
469            observer = _observer;
470            monitor = _monitor;
471        }
472    }
473
474    class RestoreParams {
475        public IBackupTransport transport;
476        public String dirName;
477        public IRestoreObserver observer;
478        public IBackupManagerMonitor monitor;
479        public long token;
480        public PackageInfo pkgInfo;
481        public int pmToken; // in post-install restore, the PM's token for this transaction
482        public boolean isSystemRestore;
483        public String[] filterSet;
484
485        /**
486         * Restore a single package; no kill after restore
487         */
488        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
489                IBackupManagerMonitor _monitor, long _token, PackageInfo _pkg) {
490            transport = _transport;
491            dirName = _dirName;
492            observer = _obs;
493            monitor = _monitor;
494            token = _token;
495            pkgInfo = _pkg;
496            pmToken = 0;
497            isSystemRestore = false;
498            filterSet = null;
499        }
500
501        /**
502         * Restore at install: PM token needed, kill after restore
503         */
504        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
505                IBackupManagerMonitor _monitor, long _token, String _pkgName, int _pmToken) {
506            transport = _transport;
507            dirName = _dirName;
508            observer = _obs;
509            monitor = _monitor;
510            token = _token;
511            pkgInfo = null;
512            pmToken = _pmToken;
513            isSystemRestore = false;
514            filterSet = new String[] { _pkgName };
515        }
516
517        /**
518         * Restore everything possible.  This is the form that Setup Wizard or similar
519         * restore UXes use.
520         */
521        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
522                IBackupManagerMonitor _monitor, long _token) {
523            transport = _transport;
524            dirName = _dirName;
525            observer = _obs;
526            monitor = _monitor;
527            token = _token;
528            pkgInfo = null;
529            pmToken = 0;
530            isSystemRestore = true;
531            filterSet = null;
532        }
533
534        /**
535         * Restore some set of packages.  Leave this one up to the caller to specify
536         * whether it's to be considered a system-level restore.
537         */
538        RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs,
539                IBackupManagerMonitor _monitor, long _token,
540                String[] _filterSet, boolean _isSystemRestore) {
541            transport = _transport;
542            dirName = _dirName;
543            observer = _obs;
544            monitor = _monitor;
545            token = _token;
546            pkgInfo = null;
547            pmToken = 0;
548            isSystemRestore = _isSystemRestore;
549            filterSet = _filterSet;
550        }
551    }
552
553    class ClearParams {
554        public IBackupTransport transport;
555        public PackageInfo packageInfo;
556
557        ClearParams(IBackupTransport _transport, PackageInfo _info) {
558            transport = _transport;
559            packageInfo = _info;
560        }
561    }
562
563    class ClearRetryParams {
564        public String transportName;
565        public String packageName;
566
567        ClearRetryParams(String transport, String pkg) {
568            transportName = transport;
569            packageName = pkg;
570        }
571    }
572
573    // Parameters used by adbBackup() and adbRestore()
574    class AdbParams {
575        public ParcelFileDescriptor fd;
576        public final AtomicBoolean latch;
577        public IFullBackupRestoreObserver observer;
578        public String curPassword;     // filled in by the confirmation step
579        public String encryptPassword;
580
581        AdbParams() {
582            latch = new AtomicBoolean(false);
583        }
584    }
585
586    class AdbBackupParams extends AdbParams {
587        public boolean includeApks;
588        public boolean includeObbs;
589        public boolean includeShared;
590        public boolean doWidgets;
591        public boolean allApps;
592        public boolean includeSystem;
593        public boolean doCompress;
594        public boolean includeKeyValue;
595        public String[] packages;
596
597        AdbBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveObbs,
598                boolean saveShared, boolean alsoWidgets, boolean doAllApps, boolean doSystem,
599                boolean compress, boolean doKeyValue, String[] pkgList) {
600            fd = output;
601            includeApks = saveApks;
602            includeObbs = saveObbs;
603            includeShared = saveShared;
604            doWidgets = alsoWidgets;
605            allApps = doAllApps;
606            includeSystem = doSystem;
607            doCompress = compress;
608            includeKeyValue = doKeyValue;
609            packages = pkgList;
610        }
611    }
612
613    class AdbRestoreParams extends AdbParams {
614        AdbRestoreParams(ParcelFileDescriptor input) {
615            fd = input;
616        }
617    }
618
619    class BackupParams {
620        public IBackupTransport transport;
621        public String dirName;
622        public ArrayList<String> kvPackages;
623        public ArrayList<String> fullPackages;
624        public IBackupObserver observer;
625        public IBackupManagerMonitor monitor;
626        public boolean userInitiated;
627        public boolean nonIncrementalBackup;
628
629        BackupParams(IBackupTransport transport, String dirName, ArrayList<String> kvPackages,
630                ArrayList<String> fullPackages, IBackupObserver observer,
631                IBackupManagerMonitor monitor,boolean userInitiated, boolean nonIncrementalBackup) {
632            this.transport = transport;
633            this.dirName = dirName;
634            this.kvPackages = kvPackages;
635            this.fullPackages = fullPackages;
636            this.observer = observer;
637            this.monitor = monitor;
638            this.userInitiated = userInitiated;
639            this.nonIncrementalBackup = nonIncrementalBackup;
640        }
641    }
642
643    // Bookkeeping of in-flight operations for timeout etc. purposes.  The operation
644    // token is the index of the entry in the pending-operations list.
645    static final int OP_PENDING = 0;
646    static final int OP_ACKNOWLEDGED = 1;
647    static final int OP_TIMEOUT = -1;
648
649    // Waiting for backup agent to respond during backup operation.
650    static final int OP_TYPE_BACKUP_WAIT = 0;
651
652    // Waiting for backup agent to respond during restore operation.
653    static final int OP_TYPE_RESTORE_WAIT = 1;
654
655    // An entire backup operation spanning multiple packages.
656    private static final int OP_TYPE_BACKUP = 2;
657
658    class Operation {
659        int state;
660        final BackupRestoreTask callback;
661        final int type;
662
663        Operation(int initialState, BackupRestoreTask callbackObj, int type) {
664            state = initialState;
665            callback = callbackObj;
666            this.type = type;
667        }
668    }
669
670    /**
671     * mCurrentOperations contains the list of currently active operations.
672     *
673     * If type of operation is OP_TYPE_WAIT, it are waiting for an ack or timeout.
674     * An operation wraps a BackupRestoreTask within it.
675     * It's the responsibility of this task to remove the operation from this array.
676     *
677     * A BackupRestore task gets notified of ack/timeout for the operation via
678     * BackupRestoreTask#handleCancel, BackupRestoreTask#operationComplete and notifyAll called
679     * on the mCurrentOpLock. {@link BackupManagerService#waitUntilOperationComplete(int)} is
680     * used in various places to 'wait' for notifyAll and detect change of pending state of an
681     * operation. So typically, an operation will be removed from this array by:
682     *   - BackupRestoreTask#handleCancel and
683     *   - BackupRestoreTask#operationComplete OR waitUntilOperationComplete. Do not remove at both
684     *     these places because waitUntilOperationComplete relies on the operation being present to
685     *     determine its completion status.
686     *
687     * If type of operation is OP_BACKUP, it is a task running backups. It provides a handle to
688     * cancel backup tasks.
689     */
690    @GuardedBy("mCurrentOpLock")
691    final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
692    final Object mCurrentOpLock = new Object();
693    final Random mTokenGenerator = new Random();
694
695    final SparseArray<AdbParams> mAdbBackupRestoreConfirmations = new SparseArray<AdbParams>();
696
697    // Where we keep our journal files and other bookkeeping
698    File mBaseStateDir;
699    File mDataDir;
700    File mJournalDir;
701    File mJournal;
702
703    // Backup password, if any, and the file where it's saved.  What is stored is not the
704    // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
705    // persisted) salt.  Validation is performed by running the challenge text through the
706    // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
707    // the saved hash string, then the challenge text matches the originally supplied
708    // password text.
709    private final SecureRandom mRng = new SecureRandom();
710    private String mPasswordHash;
711    private File mPasswordHashFile;
712    private int mPasswordVersion;
713    private File mPasswordVersionFile;
714    private byte[] mPasswordSalt;
715
716    // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
717    static final int PBKDF2_HASH_ROUNDS = 10000;
718    static final int PBKDF2_KEY_SIZE = 256;     // bits
719    static final int PBKDF2_SALT_SIZE = 512;    // bits
720    static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
721
722    // Keep a log of all the apps we've ever backed up, and what the
723    // dataset tokens are for both the current backup dataset and
724    // the ancestral dataset.
725    private File mEverStored;
726    HashSet<String> mEverStoredApps = new HashSet<String>();
727
728    static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1;  // increment when the schema changes
729    File mTokenFile;
730    Set<String> mAncestralPackages = null;
731    long mAncestralToken = 0;
732    long mCurrentToken = 0;
733
734    // Persistently track the need to do a full init
735    static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
736    HashSet<String> mPendingInits = new HashSet<String>();  // transport names
737
738    // Round-robin queue for scheduling full backup passes
739    static final int SCHEDULE_FILE_VERSION = 1; // current version of the schedule file
740    class FullBackupEntry implements Comparable<FullBackupEntry> {
741        String packageName;
742        long lastBackup;
743
744        FullBackupEntry(String pkg, long when) {
745            packageName = pkg;
746            lastBackup = when;
747        }
748
749        @Override
750        public int compareTo(FullBackupEntry other) {
751            if (lastBackup < other.lastBackup) return -1;
752            else if (lastBackup > other.lastBackup) return 1;
753            else return 0;
754        }
755    }
756
757    File mFullBackupScheduleFile;
758    // If we're running a schedule-driven full backup, this is the task instance doing it
759
760    @GuardedBy("mQueueLock")
761    PerformFullTransportBackupTask mRunningFullBackupTask;
762
763    @GuardedBy("mQueueLock")
764    ArrayList<FullBackupEntry> mFullBackupQueue;
765
766    // Utility: build a new random integer token
767    @Override
768    public int generateRandomIntegerToken() {
769        int token;
770        do {
771            synchronized (mTokenGenerator) {
772                token = mTokenGenerator.nextInt();
773            }
774        } while (token < 0);
775        return token;
776    }
777
778    // High level policy: apps are generally ineligible for backup if certain conditions apply
779    public static boolean appIsEligibleForBackup(ApplicationInfo app, PackageManager pm) {
780        // 1. their manifest states android:allowBackup="false"
781        if ((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
782            return false;
783        }
784
785        // 2. they run as a system-level uid but do not supply their own backup agent
786        if ((app.uid < Process.FIRST_APPLICATION_UID) && (app.backupAgentName == null)) {
787            return false;
788        }
789
790        // 3. it is the special shared-storage backup package used for 'adb backup'
791        if (app.packageName.equals(BackupManagerService.SHARED_BACKUP_AGENT_PACKAGE)) {
792            return false;
793        }
794
795        // 4. it is an "instant" app
796        if (app.isInstantApp()) {
797            return false;
798        }
799
800        // Everything else checks out; the only remaining roadblock would be if the
801        // package were disabled
802        return !appIsDisabled(app, pm);
803    }
804
805    // Checks if the app is in a stopped state.  This is not part of the general "eligible for
806    // backup?" check because we *do* still need to restore data to apps in this state (e.g.
807    // newly-installing ones)
808    private static boolean appIsStopped(ApplicationInfo app) {
809        return ((app.flags & ApplicationInfo.FLAG_STOPPED) != 0);
810    }
811
812    private static boolean appIsDisabled(ApplicationInfo app, PackageManager pm) {
813        switch (pm.getApplicationEnabledSetting(app.packageName)) {
814            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED:
815            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER:
816            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED:
817                return true;
818
819            default:
820                return false;
821        }
822    }
823
824    /* does *not* check overall backup eligibility policy! */
825    private static boolean appGetsFullBackup(PackageInfo pkg) {
826        if (pkg.applicationInfo.backupAgentName != null) {
827            // If it has an agent, it gets full backups only if it says so
828            return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FULL_BACKUP_ONLY) != 0;
829        }
830
831        // No agent or fullBackupOnly="true" means we do indeed perform full-data backups for it
832        return true;
833    }
834
835    /* adb backup: is this app only capable of doing key/value?  We say otherwise if
836     * the app has a backup agent and does not say fullBackupOnly,
837     */
838    private static boolean appIsKeyValueOnly(PackageInfo pkg) {
839        return !appGetsFullBackup(pkg);
840    }
841
842    /*
843     * Construct a backup agent instance for the metadata pseudopackage.  This is a
844     * process-local non-lifecycle agent instance, so we manually set up the context
845     * topology for it.
846     */
847    PackageManagerBackupAgent makeMetadataAgent() {
848        PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(mPackageManager);
849        pmAgent.attach(mContext);
850        pmAgent.onCreate();
851        return pmAgent;
852    }
853
854    /*
855     * Same as above but with the explicit package-set configuration.
856     */
857    PackageManagerBackupAgent makeMetadataAgent(List<PackageInfo> packages) {
858        PackageManagerBackupAgent pmAgent =
859                new PackageManagerBackupAgent(mPackageManager, packages);
860        pmAgent.attach(mContext);
861        pmAgent.onCreate();
862        return pmAgent;
863    }
864
865    // ----- Asynchronous backup/restore handler thread -----
866
867    private class BackupHandler extends Handler {
868        public BackupHandler(Looper looper) {
869            super(looper);
870        }
871
872        public void handleMessage(Message msg) {
873
874            switch (msg.what) {
875            case MSG_RUN_BACKUP:
876            {
877                mLastBackupPass = System.currentTimeMillis();
878
879                IBackupTransport transport = mTransportManager.getCurrentTransportBinder();
880                if (transport == null) {
881                    Slog.v(TAG, "Backup requested but no transport available");
882                    synchronized (mQueueLock) {
883                        mBackupRunning = false;
884                    }
885                    mWakelock.release();
886                    break;
887                }
888
889                // snapshot the pending-backup set and work on that
890                ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
891                File oldJournal = mJournal;
892                synchronized (mQueueLock) {
893                    // Do we have any work to do?  Construct the work queue
894                    // then release the synchronization lock to actually run
895                    // the backup.
896                    if (mPendingBackups.size() > 0) {
897                        for (BackupRequest b: mPendingBackups.values()) {
898                            queue.add(b);
899                        }
900                        if (DEBUG) Slog.v(TAG, "clearing pending backups");
901                        mPendingBackups.clear();
902
903                        // Start a new backup-queue journal file too
904                        mJournal = null;
905
906                    }
907                }
908
909                // At this point, we have started a new journal file, and the old
910                // file identity is being passed to the backup processing task.
911                // When it completes successfully, that old journal file will be
912                // deleted.  If we crash prior to that, the old journal is parsed
913                // at next boot and the journaled requests fulfilled.
914                boolean staged = true;
915                if (queue.size() > 0) {
916                    // Spin up a backup state sequence and set it running
917                    try {
918                        String dirName = transport.transportDirName();
919                        PerformBackupTask pbt = new PerformBackupTask(transport, dirName, queue,
920                                oldJournal, null, null, Collections.<String>emptyList(), false,
921                                false /* nonIncremental */);
922                        Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
923                        sendMessage(pbtMessage);
924                    } catch (Exception e) {
925                        // unable to ask the transport its dir name -- transient failure, since
926                        // the above check succeeded.  Try again next time.
927                        Slog.e(TAG, "Transport became unavailable attempting backup"
928                                + " or error initializing backup task", e);
929                        staged = false;
930                    }
931                } else {
932                    Slog.v(TAG, "Backup requested but nothing pending");
933                    staged = false;
934                }
935
936                if (!staged) {
937                    // if we didn't actually hand off the wakelock, rewind until next time
938                    synchronized (mQueueLock) {
939                        mBackupRunning = false;
940                    }
941                    mWakelock.release();
942                }
943                break;
944            }
945
946            case MSG_BACKUP_RESTORE_STEP:
947            {
948                try {
949                    BackupRestoreTask task = (BackupRestoreTask) msg.obj;
950                    if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
951                    task.execute();
952                } catch (ClassCastException e) {
953                    Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
954                }
955                break;
956            }
957
958            case MSG_OP_COMPLETE:
959            {
960                try {
961                    Pair<BackupRestoreTask, Long> taskWithResult =
962                            (Pair<BackupRestoreTask, Long>) msg.obj;
963                    taskWithResult.first.operationComplete(taskWithResult.second);
964                } catch (ClassCastException e) {
965                    Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
966                }
967                break;
968            }
969
970            case MSG_RUN_ADB_BACKUP:
971            {
972                // TODO: refactor full backup to be a looper-based state machine
973                // similar to normal backup/restore.
974                AdbBackupParams params = (AdbBackupParams)msg.obj;
975                PerformAdbBackupTask task = new PerformAdbBackupTask(params.fd,
976                        params.observer, params.includeApks, params.includeObbs,
977                        params.includeShared, params.doWidgets, params.curPassword,
978                        params.encryptPassword, params.allApps, params.includeSystem,
979                        params.doCompress, params.includeKeyValue, params.packages, params.latch);
980                (new Thread(task, "adb-backup")).start();
981                break;
982            }
983
984            case MSG_RUN_FULL_TRANSPORT_BACKUP:
985            {
986                PerformFullTransportBackupTask task = (PerformFullTransportBackupTask) msg.obj;
987                (new Thread(task, "transport-backup")).start();
988                break;
989            }
990
991            case MSG_RUN_RESTORE:
992            {
993                RestoreParams params = (RestoreParams)msg.obj;
994                Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
995
996                PerformUnifiedRestoreTask task = new PerformUnifiedRestoreTask(params.transport,
997                        params.observer, params.monitor, params.token, params.pkgInfo,
998                        params.pmToken, params.isSystemRestore, params.filterSet);
999
1000                synchronized (mPendingRestores) {
1001                    if (mIsRestoreInProgress) {
1002                        if (DEBUG) {
1003                            Slog.d(TAG, "Restore in progress, queueing.");
1004                        }
1005                        mPendingRestores.add(task);
1006                        // This task will be picked up and executed when the the currently running
1007                        // restore task finishes.
1008                    } else {
1009                        if (DEBUG) {
1010                            Slog.d(TAG, "Starting restore.");
1011                        }
1012                        mIsRestoreInProgress = true;
1013                        Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
1014                        sendMessage(restoreMsg);
1015                    }
1016                }
1017                break;
1018            }
1019
1020            case MSG_RUN_ADB_RESTORE:
1021            {
1022                // TODO: refactor full restore to be a looper-based state machine
1023                // similar to normal backup/restore.
1024                AdbRestoreParams params = (AdbRestoreParams)msg.obj;
1025                PerformAdbRestoreTask task = new PerformAdbRestoreTask(params.fd,
1026                        params.curPassword, params.encryptPassword,
1027                        params.observer, params.latch);
1028                (new Thread(task, "adb-restore")).start();
1029                break;
1030            }
1031
1032            case MSG_RUN_CLEAR:
1033            {
1034                ClearParams params = (ClearParams)msg.obj;
1035                (new PerformClearTask(params.transport, params.packageInfo)).run();
1036                break;
1037            }
1038
1039            case MSG_RETRY_CLEAR:
1040            {
1041                // reenqueues if the transport remains unavailable
1042                ClearRetryParams params = (ClearRetryParams)msg.obj;
1043                clearBackupData(params.transportName, params.packageName);
1044                break;
1045            }
1046
1047            case MSG_RUN_INITIALIZE:
1048            {
1049                HashSet<String> queue;
1050
1051                // Snapshot the pending-init queue and work on that
1052                synchronized (mQueueLock) {
1053                    queue = new HashSet<String>(mPendingInits);
1054                    mPendingInits.clear();
1055                }
1056
1057                (new PerformInitializeTask(queue)).run();
1058                break;
1059            }
1060
1061            case MSG_RETRY_INIT:
1062            {
1063                synchronized (mQueueLock) {
1064                    recordInitPendingLocked(msg.arg1 != 0, (String)msg.obj);
1065                    mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1066                            mRunInitIntent);
1067                }
1068                break;
1069            }
1070
1071            case MSG_RUN_GET_RESTORE_SETS:
1072            {
1073                // Like other async operations, this is entered with the wakelock held
1074                RestoreSet[] sets = null;
1075                RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
1076                try {
1077                    sets = params.transport.getAvailableRestoreSets();
1078                    // cache the result in the active session
1079                    synchronized (params.session) {
1080                        params.session.mRestoreSets = sets;
1081                    }
1082                    if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
1083                } catch (Exception e) {
1084                    Slog.e(TAG, "Error from transport getting set list: " + e.getMessage());
1085                } finally {
1086                    if (params.observer != null) {
1087                        try {
1088                            params.observer.restoreSetsAvailable(sets);
1089                        } catch (RemoteException re) {
1090                            Slog.e(TAG, "Unable to report listing to observer");
1091                        } catch (Exception e) {
1092                            Slog.e(TAG, "Restore observer threw: " + e.getMessage());
1093                        }
1094                    }
1095
1096                    // Done: reset the session timeout clock
1097                    removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
1098                    sendEmptyMessageDelayed(MSG_RESTORE_SESSION_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
1099
1100                    mWakelock.release();
1101                }
1102                break;
1103            }
1104
1105            case MSG_BACKUP_OPERATION_TIMEOUT:
1106            case MSG_RESTORE_OPERATION_TIMEOUT:
1107            {
1108                Slog.d(TAG, "Timeout message received for token=" + Integer.toHexString(msg.arg1));
1109                handleCancel(msg.arg1, false);
1110                break;
1111            }
1112
1113            case MSG_RESTORE_SESSION_TIMEOUT:
1114            {
1115                synchronized (BackupManagerService.this) {
1116                    if (mActiveRestoreSession != null) {
1117                        // Client app left the restore session dangling.  We know that it
1118                        // can't be in the middle of an actual restore operation because
1119                        // the timeout is suspended while a restore is in progress.  Clean
1120                        // up now.
1121                        Slog.w(TAG, "Restore session timed out; aborting");
1122                        mActiveRestoreSession.markTimedOut();
1123                        post(mActiveRestoreSession.new EndRestoreRunnable(
1124                                BackupManagerService.this, mActiveRestoreSession));
1125                    }
1126                }
1127                break;
1128            }
1129
1130            case MSG_FULL_CONFIRMATION_TIMEOUT:
1131            {
1132                synchronized (mAdbBackupRestoreConfirmations) {
1133                    AdbParams params = mAdbBackupRestoreConfirmations.get(msg.arg1);
1134                    if (params != null) {
1135                        Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
1136
1137                        // Release the waiter; timeout == completion
1138                        signalAdbBackupRestoreCompletion(params);
1139
1140                        // Remove the token from the set
1141                        mAdbBackupRestoreConfirmations.delete(msg.arg1);
1142
1143                        // Report a timeout to the observer, if any
1144                        if (params.observer != null) {
1145                            try {
1146                                params.observer.onTimeout();
1147                            } catch (RemoteException e) {
1148                                /* don't care if the app has gone away */
1149                            }
1150                        }
1151                    } else {
1152                        Slog.d(TAG, "couldn't find params for token " + msg.arg1);
1153                    }
1154                }
1155                break;
1156            }
1157
1158            case MSG_WIDGET_BROADCAST:
1159            {
1160                final Intent intent = (Intent) msg.obj;
1161                mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
1162                break;
1163            }
1164
1165            case MSG_REQUEST_BACKUP:
1166            {
1167                BackupParams params = (BackupParams)msg.obj;
1168                if (MORE_DEBUG) {
1169                    Slog.d(TAG, "MSG_REQUEST_BACKUP observer=" + params.observer);
1170                }
1171                ArrayList<BackupRequest> kvQueue = new ArrayList<>();
1172                for (String packageName : params.kvPackages) {
1173                    kvQueue.add(new BackupRequest(packageName));
1174                }
1175                mBackupRunning = true;
1176                mWakelock.acquire();
1177
1178                PerformBackupTask pbt = new PerformBackupTask(params.transport, params.dirName,
1179                        kvQueue, null, params.observer, params.monitor, params.fullPackages, true,
1180                        params.nonIncrementalBackup);
1181                Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
1182                sendMessage(pbtMessage);
1183                break;
1184            }
1185
1186            case MSG_SCHEDULE_BACKUP_PACKAGE:
1187            {
1188                String pkgName = (String)msg.obj;
1189                if (MORE_DEBUG) {
1190                    Slog.d(TAG, "MSG_SCHEDULE_BACKUP_PACKAGE " + pkgName);
1191                }
1192                dataChangedImpl(pkgName);
1193                break;
1194            }
1195            }
1196        }
1197    }
1198
1199    // ----- Debug-only backup operation trace -----
1200    void addBackupTrace(String s) {
1201        if (DEBUG_BACKUP_TRACE) {
1202            synchronized (mBackupTrace) {
1203                mBackupTrace.add(s);
1204            }
1205        }
1206    }
1207
1208    void clearBackupTrace() {
1209        if (DEBUG_BACKUP_TRACE) {
1210            synchronized (mBackupTrace) {
1211                mBackupTrace.clear();
1212            }
1213        }
1214    }
1215
1216    // ----- Main service implementation -----
1217
1218    public BackupManagerService(Context context, Trampoline parent) {
1219        mContext = context;
1220        mPackageManager = context.getPackageManager();
1221        mPackageManagerBinder = AppGlobals.getPackageManager();
1222        mActivityManager = ActivityManager.getService();
1223
1224        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1225        mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
1226        mStorageManager = IStorageManager.Stub.asInterface(ServiceManager.getService("mount"));
1227
1228        mBackupManagerBinder = Trampoline.asInterface(parent.asBinder());
1229
1230        // spin up the backup/restore handler thread
1231        mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
1232        mHandlerThread.start();
1233        mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
1234
1235        // Set up our bookkeeping
1236        final ContentResolver resolver = context.getContentResolver();
1237        mProvisioned = Settings.Global.getInt(resolver,
1238                Settings.Global.DEVICE_PROVISIONED, 0) != 0;
1239        mAutoRestore = Settings.Secure.getInt(resolver,
1240                Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
1241
1242        mProvisionedObserver = new ProvisionedObserver(mBackupHandler);
1243        resolver.registerContentObserver(
1244                Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
1245                false, mProvisionedObserver);
1246
1247        // If Encrypted file systems is enabled or disabled, this call will return the
1248        // correct directory.
1249        mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
1250        mBaseStateDir.mkdirs();
1251        if (!SELinux.restorecon(mBaseStateDir)) {
1252            Slog.e(TAG, "SELinux restorecon failed on " + mBaseStateDir);
1253        }
1254
1255        // This dir on /cache is managed directly in init.rc
1256        mDataDir = new File(Environment.getDownloadCacheDirectory(), "backup_stage");
1257
1258        mPasswordVersion = 1;       // unless we hear otherwise
1259        mPasswordVersionFile = new File(mBaseStateDir, "pwversion");
1260        if (mPasswordVersionFile.exists()) {
1261            FileInputStream fin = null;
1262            DataInputStream in = null;
1263            try {
1264                fin = new FileInputStream(mPasswordVersionFile);
1265                in = new DataInputStream(fin);
1266                mPasswordVersion = in.readInt();
1267            } catch (IOException e) {
1268                Slog.e(TAG, "Unable to read backup pw version");
1269            } finally {
1270                try {
1271                    if (in != null) in.close();
1272                    if (fin != null) fin.close();
1273                } catch (IOException e) {
1274                    Slog.w(TAG, "Error closing pw version files");
1275                }
1276            }
1277        }
1278
1279        mPasswordHashFile = new File(mBaseStateDir, "pwhash");
1280        if (mPasswordHashFile.exists()) {
1281            FileInputStream fin = null;
1282            DataInputStream in = null;
1283            try {
1284                fin = new FileInputStream(mPasswordHashFile);
1285                in = new DataInputStream(new BufferedInputStream(fin));
1286                // integer length of the salt array, followed by the salt,
1287                // then the hex pw hash string
1288                int saltLen = in.readInt();
1289                byte[] salt = new byte[saltLen];
1290                in.readFully(salt);
1291                mPasswordHash = in.readUTF();
1292                mPasswordSalt = salt;
1293            } catch (IOException e) {
1294                Slog.e(TAG, "Unable to read saved backup pw hash");
1295            } finally {
1296                try {
1297                    if (in != null) in.close();
1298                    if (fin != null) fin.close();
1299                } catch (IOException e) {
1300                    Slog.w(TAG, "Unable to close streams");
1301                }
1302            }
1303        }
1304
1305        // Alarm receivers for scheduled backups & initialization operations
1306        mRunBackupReceiver = new RunBackupReceiver();
1307        IntentFilter filter = new IntentFilter();
1308        filter.addAction(RUN_BACKUP_ACTION);
1309        context.registerReceiver(mRunBackupReceiver, filter,
1310                android.Manifest.permission.BACKUP, null);
1311
1312        mRunInitReceiver = new RunInitializeReceiver();
1313        filter = new IntentFilter();
1314        filter.addAction(RUN_INITIALIZE_ACTION);
1315        context.registerReceiver(mRunInitReceiver, filter,
1316                android.Manifest.permission.BACKUP, null);
1317
1318        Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
1319        backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1320        mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
1321
1322        Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
1323        backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1324        mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
1325
1326        // Set up the backup-request journaling
1327        mJournalDir = new File(mBaseStateDir, "pending");
1328        mJournalDir.mkdirs();   // creates mBaseStateDir along the way
1329        mJournal = null;        // will be created on first use
1330
1331        // Set up the various sorts of package tracking we do
1332        mFullBackupScheduleFile = new File(mBaseStateDir, "fb-schedule");
1333        initPackageTracking();
1334
1335        // Build our mapping of uid to backup client services.  This implicitly
1336        // schedules a backup pass on the Package Manager metadata the first
1337        // time anything needs to be backed up.
1338        synchronized (mBackupParticipants) {
1339            addPackageParticipantsLocked(null);
1340        }
1341
1342        // Set up our transport options and initialize the default transport
1343        // TODO: Don't create transports that we don't need to?
1344        SystemConfig systemConfig = SystemConfig.getInstance();
1345        Set<ComponentName> transportWhitelist = systemConfig.getBackupTransportWhitelist();
1346
1347        String transport = Settings.Secure.getString(context.getContentResolver(),
1348                Settings.Secure.BACKUP_TRANSPORT);
1349        if (TextUtils.isEmpty(transport)) {
1350            transport = null;
1351        }
1352        String currentTransport = transport;
1353        if (DEBUG) Slog.v(TAG, "Starting with transport " + currentTransport);
1354
1355        mTransportManager = new TransportManager(context, transportWhitelist, currentTransport,
1356                mTransportBoundListener, mHandlerThread.getLooper());
1357        mTransportManager.registerAllTransports();
1358
1359        // Now that we know about valid backup participants, parse any
1360        // leftover journal files into the pending backup set
1361        mBackupHandler.post(() -> parseLeftoverJournals());
1362
1363        // Power management
1364        mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
1365    }
1366
1367    private class RunBackupReceiver extends BroadcastReceiver {
1368        public void onReceive(Context context, Intent intent) {
1369            if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
1370                synchronized (mQueueLock) {
1371                    if (mPendingInits.size() > 0) {
1372                        // If there are pending init operations, we process those
1373                        // and then settle into the usual periodic backup schedule.
1374                        if (MORE_DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
1375                        try {
1376                            mAlarmManager.cancel(mRunInitIntent);
1377                            mRunInitIntent.send();
1378                        } catch (PendingIntent.CanceledException ce) {
1379                            Slog.e(TAG, "Run init intent cancelled");
1380                            // can't really do more than bail here
1381                        }
1382                    } else {
1383                        // Don't run backups now if we're disabled or not yet
1384                        // fully set up.
1385                        if (mEnabled && mProvisioned) {
1386                            if (!mBackupRunning) {
1387                                if (DEBUG) Slog.v(TAG, "Running a backup pass");
1388
1389                                // Acquire the wakelock and pass it to the backup thread.  it will
1390                                // be released once backup concludes.
1391                                mBackupRunning = true;
1392                                mWakelock.acquire();
1393
1394                                Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
1395                                mBackupHandler.sendMessage(msg);
1396                            } else {
1397                                Slog.i(TAG, "Backup time but one already running");
1398                            }
1399                        } else {
1400                            Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
1401                        }
1402                    }
1403                }
1404            }
1405        }
1406    }
1407
1408    private class RunInitializeReceiver extends BroadcastReceiver {
1409        public void onReceive(Context context, Intent intent) {
1410            if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
1411                synchronized (mQueueLock) {
1412                    if (DEBUG) Slog.v(TAG, "Running a device init");
1413
1414                    // Acquire the wakelock and pass it to the init thread.  it will
1415                    // be released once init concludes.
1416                    mWakelock.acquire();
1417
1418                    Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
1419                    mBackupHandler.sendMessage(msg);
1420                }
1421            }
1422        }
1423    }
1424
1425    private void initPackageTracking() {
1426        if (MORE_DEBUG) Slog.v(TAG, "` tracking");
1427
1428        // Remember our ancestral dataset
1429        mTokenFile = new File(mBaseStateDir, "ancestral");
1430        try (DataInputStream tokenStream = new DataInputStream(new BufferedInputStream(
1431                new FileInputStream(mTokenFile)))) {
1432            int version = tokenStream.readInt();
1433            if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
1434                mAncestralToken = tokenStream.readLong();
1435                mCurrentToken = tokenStream.readLong();
1436
1437                int numPackages = tokenStream.readInt();
1438                if (numPackages >= 0) {
1439                    mAncestralPackages = new HashSet<>();
1440                    for (int i = 0; i < numPackages; i++) {
1441                        String pkgName = tokenStream.readUTF();
1442                        mAncestralPackages.add(pkgName);
1443                    }
1444                }
1445            }
1446        } catch (FileNotFoundException fnf) {
1447            // Probably innocuous
1448            Slog.v(TAG, "No ancestral data");
1449        } catch (IOException e) {
1450            Slog.w(TAG, "Unable to read token file", e);
1451        }
1452
1453        // Keep a log of what apps we've ever backed up.  Because we might have
1454        // rebooted in the middle of an operation that was removing something from
1455        // this log, we sanity-check its contents here and reconstruct it.
1456        mEverStored = new File(mBaseStateDir, "processed");
1457        File tempProcessedFile = new File(mBaseStateDir, "processed.new");
1458
1459        // If we were in the middle of removing something from the ever-backed-up
1460        // file, there might be a transient "processed.new" file still present.
1461        // Ignore it -- we'll validate "processed" against the current package set.
1462        if (tempProcessedFile.exists()) {
1463            tempProcessedFile.delete();
1464        }
1465
1466        // If there are previous contents, parse them out then start a new
1467        // file to continue the recordkeeping.
1468        if (mEverStored.exists()) {
1469            DataOutputStream temp = null;
1470            DataInputStream in = null;
1471
1472            try {
1473                temp = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(
1474                        tempProcessedFile)));
1475                in = new DataInputStream(new BufferedInputStream(new FileInputStream(mEverStored)));
1476
1477                // Loop until we hit EOF
1478                while (true) {
1479                    String pkg = in.readUTF();
1480                    try {
1481                        // is this package still present?
1482                        mPackageManager.getPackageInfo(pkg, 0);
1483                        // if we get here then yes it is; remember it
1484                        mEverStoredApps.add(pkg);
1485                        temp.writeUTF(pkg);
1486                        if (MORE_DEBUG) Slog.v(TAG, "   + " + pkg);
1487                    } catch (NameNotFoundException e) {
1488                        // nope, this package was uninstalled; don't include it
1489                        if (MORE_DEBUG) Slog.v(TAG, "   - " + pkg);
1490                    }
1491                }
1492            } catch (EOFException e) {
1493                // Once we've rewritten the backup history log, atomically replace the
1494                // old one with the new one then reopen the file for continuing use.
1495                if (!tempProcessedFile.renameTo(mEverStored)) {
1496                    Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
1497                }
1498            } catch (IOException e) {
1499                Slog.e(TAG, "Error in processed file", e);
1500            } finally {
1501                try { if (temp != null) temp.close(); } catch (IOException e) {}
1502                try { if (in != null) in.close(); } catch (IOException e) {}
1503            }
1504        }
1505
1506        synchronized (mQueueLock) {
1507            // Resume the full-data backup queue
1508            mFullBackupQueue = readFullBackupSchedule();
1509        }
1510
1511        // Register for broadcasts about package install, etc., so we can
1512        // update the provider list.
1513        IntentFilter filter = new IntentFilter();
1514        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1515        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1516        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1517        filter.addDataScheme("package");
1518        mContext.registerReceiver(mBroadcastReceiver, filter);
1519        // Register for events related to sdcard installation.
1520        IntentFilter sdFilter = new IntentFilter();
1521        sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1522        sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1523        mContext.registerReceiver(mBroadcastReceiver, sdFilter);
1524    }
1525
1526    private ArrayList<FullBackupEntry> readFullBackupSchedule() {
1527        boolean changed = false;
1528        ArrayList<FullBackupEntry> schedule = null;
1529        List<PackageInfo> apps =
1530                PackageManagerBackupAgent.getStorableApplications(mPackageManager);
1531
1532        if (mFullBackupScheduleFile.exists()) {
1533            FileInputStream fstream = null;
1534            BufferedInputStream bufStream = null;
1535            DataInputStream in = null;
1536            try {
1537                fstream = new FileInputStream(mFullBackupScheduleFile);
1538                bufStream = new BufferedInputStream(fstream);
1539                in = new DataInputStream(bufStream);
1540
1541                int version = in.readInt();
1542                if (version != SCHEDULE_FILE_VERSION) {
1543                    Slog.e(TAG, "Unknown backup schedule version " + version);
1544                    return null;
1545                }
1546
1547                final int N = in.readInt();
1548                schedule = new ArrayList<FullBackupEntry>(N);
1549
1550                // HashSet instead of ArraySet specifically because we want the eventual
1551                // lookups against O(hundreds) of entries to be as fast as possible, and
1552                // we discard the set immediately after the scan so the extra memory
1553                // overhead is transient.
1554                HashSet<String> foundApps = new HashSet<String>(N);
1555
1556                for (int i = 0; i < N; i++) {
1557                    String pkgName = in.readUTF();
1558                    long lastBackup = in.readLong();
1559                    foundApps.add(pkgName); // all apps that we've addressed already
1560                    try {
1561                        PackageInfo pkg = mPackageManager.getPackageInfo(pkgName, 0);
1562                        if (appGetsFullBackup(pkg)
1563                                && appIsEligibleForBackup(pkg.applicationInfo, mPackageManager)) {
1564                            schedule.add(new FullBackupEntry(pkgName, lastBackup));
1565                        } else {
1566                            if (DEBUG) {
1567                                Slog.i(TAG, "Package " + pkgName
1568                                        + " no longer eligible for full backup");
1569                            }
1570                        }
1571                    } catch (NameNotFoundException e) {
1572                        if (DEBUG) {
1573                            Slog.i(TAG, "Package " + pkgName
1574                                    + " not installed; dropping from full backup");
1575                        }
1576                    }
1577                }
1578
1579                // New apps can arrive "out of band" via OTA and similar, so we also need to
1580                // scan to make sure that we're tracking all full-backup candidates properly
1581                for (PackageInfo app : apps) {
1582                    if (appGetsFullBackup(app)
1583                            && appIsEligibleForBackup(app.applicationInfo, mPackageManager)) {
1584                        if (!foundApps.contains(app.packageName)) {
1585                            if (MORE_DEBUG) {
1586                                Slog.i(TAG, "New full backup app " + app.packageName + " found");
1587                            }
1588                            schedule.add(new FullBackupEntry(app.packageName, 0));
1589                            changed = true;
1590                        }
1591                    }
1592                }
1593
1594                Collections.sort(schedule);
1595            } catch (Exception e) {
1596                Slog.e(TAG, "Unable to read backup schedule", e);
1597                mFullBackupScheduleFile.delete();
1598                schedule = null;
1599            } finally {
1600                IoUtils.closeQuietly(in);
1601                IoUtils.closeQuietly(bufStream);
1602                IoUtils.closeQuietly(fstream);
1603            }
1604        }
1605
1606        if (schedule == null) {
1607            // no prior queue record, or unable to read it.  Set up the queue
1608            // from scratch.
1609            changed = true;
1610            schedule = new ArrayList<FullBackupEntry>(apps.size());
1611            for (PackageInfo info : apps) {
1612                if (appGetsFullBackup(info)
1613                        && appIsEligibleForBackup(info.applicationInfo, mPackageManager)) {
1614                    schedule.add(new FullBackupEntry(info.packageName, 0));
1615                }
1616            }
1617        }
1618
1619        if (changed) {
1620            writeFullBackupScheduleAsync();
1621        }
1622        return schedule;
1623    }
1624
1625    Runnable mFullBackupScheduleWriter = new Runnable() {
1626        @Override public void run() {
1627            synchronized (mQueueLock) {
1628                try {
1629                    ByteArrayOutputStream bufStream = new ByteArrayOutputStream(4096);
1630                    DataOutputStream bufOut = new DataOutputStream(bufStream);
1631                    bufOut.writeInt(SCHEDULE_FILE_VERSION);
1632
1633                    // version 1:
1634                    //
1635                    // [int] # of packages in the queue = N
1636                    // N * {
1637                    //     [utf8] package name
1638                    //     [long] last backup time for this package
1639                    //     }
1640                    int N = mFullBackupQueue.size();
1641                    bufOut.writeInt(N);
1642
1643                    for (int i = 0; i < N; i++) {
1644                        FullBackupEntry entry = mFullBackupQueue.get(i);
1645                        bufOut.writeUTF(entry.packageName);
1646                        bufOut.writeLong(entry.lastBackup);
1647                    }
1648                    bufOut.flush();
1649
1650                    AtomicFile af = new AtomicFile(mFullBackupScheduleFile);
1651                    FileOutputStream out = af.startWrite();
1652                    out.write(bufStream.toByteArray());
1653                    af.finishWrite(out);
1654                } catch (Exception e) {
1655                    Slog.e(TAG, "Unable to write backup schedule!", e);
1656                }
1657            }
1658        }
1659    };
1660
1661    private void writeFullBackupScheduleAsync() {
1662        mBackupHandler.removeCallbacks(mFullBackupScheduleWriter);
1663        mBackupHandler.post(mFullBackupScheduleWriter);
1664    }
1665
1666    private void parseLeftoverJournals() {
1667        for (File f : mJournalDir.listFiles()) {
1668            if (mJournal == null || f.compareTo(mJournal) != 0) {
1669                // This isn't the current journal, so it must be a leftover.  Read
1670                // out the package names mentioned there and schedule them for
1671                // backup.
1672                DataInputStream in = null;
1673                try {
1674                    Slog.i(TAG, "Found stale backup journal, scheduling");
1675                    // Journals will tend to be on the order of a few kilobytes(around 4k), hence,
1676                    // setting the buffer size to 8192.
1677                    InputStream bufferedInputStream = new BufferedInputStream(
1678                            new FileInputStream(f), 8192);
1679                    in = new DataInputStream(bufferedInputStream);
1680                    while (true) {
1681                        String packageName = in.readUTF();
1682                        if (MORE_DEBUG) Slog.i(TAG, "  " + packageName);
1683                        dataChangedImpl(packageName);
1684                    }
1685                } catch (EOFException e) {
1686                    // no more data; we're done
1687                } catch (Exception e) {
1688                    Slog.e(TAG, "Can't read " + f, e);
1689                } finally {
1690                    // close/delete the file
1691                    try { if (in != null) in.close(); } catch (IOException e) {}
1692                    f.delete();
1693                }
1694            }
1695        }
1696    }
1697
1698    private SecretKey buildPasswordKey(String algorithm, String pw, byte[] salt, int rounds) {
1699        return buildCharArrayKey(algorithm, pw.toCharArray(), salt, rounds);
1700    }
1701
1702    private SecretKey buildCharArrayKey(String algorithm, char[] pwArray, byte[] salt, int rounds) {
1703        try {
1704            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
1705            KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1706            return keyFactory.generateSecret(ks);
1707        } catch (InvalidKeySpecException e) {
1708            Slog.e(TAG, "Invalid key spec for PBKDF2!");
1709        } catch (NoSuchAlgorithmException e) {
1710            Slog.e(TAG, "PBKDF2 unavailable!");
1711        }
1712        return null;
1713    }
1714
1715    private String buildPasswordHash(String algorithm, String pw, byte[] salt, int rounds) {
1716        SecretKey key = buildPasswordKey(algorithm, pw, salt, rounds);
1717        if (key != null) {
1718            return byteArrayToHex(key.getEncoded());
1719        }
1720        return null;
1721    }
1722
1723    private String byteArrayToHex(byte[] data) {
1724        StringBuilder buf = new StringBuilder(data.length * 2);
1725        for (int i = 0; i < data.length; i++) {
1726            buf.append(Byte.toHexString(data[i], true));
1727        }
1728        return buf.toString();
1729    }
1730
1731    private byte[] hexToByteArray(String digits) {
1732        final int bytes = digits.length() / 2;
1733        if (2*bytes != digits.length()) {
1734            throw new IllegalArgumentException("Hex string must have an even number of digits");
1735        }
1736
1737        byte[] result = new byte[bytes];
1738        for (int i = 0; i < digits.length(); i += 2) {
1739            result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1740        }
1741        return result;
1742    }
1743
1744    private byte[] makeKeyChecksum(String algorithm, byte[] pwBytes, byte[] salt, int rounds) {
1745        char[] mkAsChar = new char[pwBytes.length];
1746        for (int i = 0; i < pwBytes.length; i++) {
1747            mkAsChar[i] = (char) pwBytes[i];
1748        }
1749
1750        Key checksum = buildCharArrayKey(algorithm, mkAsChar, salt, rounds);
1751        return checksum.getEncoded();
1752    }
1753
1754    // Used for generating random salts or passwords
1755    private byte[] randomBytes(int bits) {
1756        byte[] array = new byte[bits / 8];
1757        mRng.nextBytes(array);
1758        return array;
1759    }
1760
1761    boolean passwordMatchesSaved(String algorithm, String candidatePw, int rounds) {
1762        if (mPasswordHash == null) {
1763            // no current password case -- require that 'currentPw' be null or empty
1764            if (candidatePw == null || "".equals(candidatePw)) {
1765                return true;
1766            } // else the non-empty candidate does not match the empty stored pw
1767        } else {
1768            // hash the stated current pw and compare to the stored one
1769            if (candidatePw != null && candidatePw.length() > 0) {
1770                String currentPwHash = buildPasswordHash(algorithm, candidatePw, mPasswordSalt, rounds);
1771                if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1772                    // candidate hash matches the stored hash -- the password matches
1773                    return true;
1774                }
1775            } // else the stored pw is nonempty but the candidate is empty; no match
1776        }
1777        return false;
1778    }
1779
1780    @Override
1781    public boolean setBackupPassword(String currentPw, String newPw) {
1782        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1783                "setBackupPassword");
1784
1785        // When processing v1 passwords we may need to try two different PBKDF2 checksum regimes
1786        final boolean pbkdf2Fallback = (mPasswordVersion < BACKUP_PW_FILE_VERSION);
1787
1788        // If the supplied pw doesn't hash to the the saved one, fail.  The password
1789        // might be caught in the legacy crypto mismatch; verify that too.
1790        if (!passwordMatchesSaved(PBKDF_CURRENT, currentPw, PBKDF2_HASH_ROUNDS)
1791                && !(pbkdf2Fallback && passwordMatchesSaved(PBKDF_FALLBACK,
1792                        currentPw, PBKDF2_HASH_ROUNDS))) {
1793            return false;
1794        }
1795
1796        // Snap up to current on the pw file version
1797        mPasswordVersion = BACKUP_PW_FILE_VERSION;
1798        FileOutputStream pwFout = null;
1799        DataOutputStream pwOut = null;
1800        try {
1801            pwFout = new FileOutputStream(mPasswordVersionFile);
1802            pwOut = new DataOutputStream(pwFout);
1803            pwOut.writeInt(mPasswordVersion);
1804        } catch (IOException e) {
1805            Slog.e(TAG, "Unable to write backup pw version; password not changed");
1806            return false;
1807        } finally {
1808            try {
1809                if (pwOut != null) pwOut.close();
1810                if (pwFout != null) pwFout.close();
1811            } catch (IOException e) {
1812                Slog.w(TAG, "Unable to close pw version record");
1813            }
1814        }
1815
1816        // Clearing the password is okay
1817        if (newPw == null || newPw.isEmpty()) {
1818            if (mPasswordHashFile.exists()) {
1819                if (!mPasswordHashFile.delete()) {
1820                    // Unable to delete the old pw file, so fail
1821                    Slog.e(TAG, "Unable to clear backup password");
1822                    return false;
1823                }
1824            }
1825            mPasswordHash = null;
1826            mPasswordSalt = null;
1827            return true;
1828        }
1829
1830        try {
1831            // Okay, build the hash of the new backup password
1832            byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1833            String newPwHash = buildPasswordHash(PBKDF_CURRENT, newPw, salt, PBKDF2_HASH_ROUNDS);
1834
1835            OutputStream pwf = null, buffer = null;
1836            DataOutputStream out = null;
1837            try {
1838                pwf = new FileOutputStream(mPasswordHashFile);
1839                buffer = new BufferedOutputStream(pwf);
1840                out = new DataOutputStream(buffer);
1841                // integer length of the salt array, followed by the salt,
1842                // then the hex pw hash string
1843                out.writeInt(salt.length);
1844                out.write(salt);
1845                out.writeUTF(newPwHash);
1846                out.flush();
1847                mPasswordHash = newPwHash;
1848                mPasswordSalt = salt;
1849                return true;
1850            } finally {
1851                if (out != null) out.close();
1852                if (buffer != null) buffer.close();
1853                if (pwf != null) pwf.close();
1854            }
1855        } catch (IOException e) {
1856            Slog.e(TAG, "Unable to set backup password");
1857        }
1858        return false;
1859    }
1860
1861    @Override
1862    public boolean hasBackupPassword() {
1863        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1864                "hasBackupPassword");
1865
1866        return mPasswordHash != null && mPasswordHash.length() > 0;
1867    }
1868
1869    private boolean backupPasswordMatches(String currentPw) {
1870        if (hasBackupPassword()) {
1871            final boolean pbkdf2Fallback = (mPasswordVersion < BACKUP_PW_FILE_VERSION);
1872            if (!passwordMatchesSaved(PBKDF_CURRENT, currentPw, PBKDF2_HASH_ROUNDS)
1873                    && !(pbkdf2Fallback && passwordMatchesSaved(PBKDF_FALLBACK,
1874                            currentPw, PBKDF2_HASH_ROUNDS))) {
1875                if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
1876                return false;
1877            }
1878        }
1879        return true;
1880    }
1881
1882    // Maintain persistent state around whether need to do an initialize operation.
1883    // Must be called with the queue lock held.
1884    void recordInitPendingLocked(boolean isPending, String transportName) {
1885        if (MORE_DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
1886                + " on transport " + transportName);
1887        mBackupHandler.removeMessages(MSG_RETRY_INIT);
1888
1889        try {
1890            IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
1891            if (transport != null) {
1892                String transportDirName = transport.transportDirName();
1893                File stateDir = new File(mBaseStateDir, transportDirName);
1894                File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1895
1896                if (isPending) {
1897                    // We need an init before we can proceed with sending backup data.
1898                    // Record that with an entry in our set of pending inits, as well as
1899                    // journaling it via creation of a sentinel file.
1900                    mPendingInits.add(transportName);
1901                    try {
1902                        (new FileOutputStream(initPendingFile)).close();
1903                    } catch (IOException ioe) {
1904                        // Something is badly wrong with our permissions; just try to move on
1905                    }
1906                } else {
1907                    // No more initialization needed; wipe the journal and reset our state.
1908                    initPendingFile.delete();
1909                    mPendingInits.remove(transportName);
1910                }
1911                return; // done; don't fall through to the error case
1912            }
1913        } catch (Exception e) {
1914            // transport threw when asked its name; fall through to the lookup-failed case
1915            Slog.e(TAG, "Transport " + transportName + " failed to report name: "
1916                    + e.getMessage());
1917        }
1918
1919        // The named transport doesn't exist or threw.  This operation is
1920        // important, so we record the need for a an init and post a message
1921        // to retry the init later.
1922        if (isPending) {
1923            mPendingInits.add(transportName);
1924            mBackupHandler.sendMessageDelayed(
1925                    mBackupHandler.obtainMessage(MSG_RETRY_INIT,
1926                            (isPending ? 1 : 0),
1927                            0,
1928                            transportName),
1929                    TRANSPORT_RETRY_INTERVAL);
1930        }
1931    }
1932
1933    // Reset all of our bookkeeping, in response to having been told that
1934    // the backend data has been wiped [due to idle expiry, for example],
1935    // so we must re-upload all saved settings.
1936    void resetBackupState(File stateFileDir) {
1937        synchronized (mQueueLock) {
1938            // Wipe the "what we've ever backed up" tracking
1939            mEverStoredApps.clear();
1940            mEverStored.delete();
1941
1942            mCurrentToken = 0;
1943            writeRestoreTokens();
1944
1945            // Remove all the state files
1946            for (File sf : stateFileDir.listFiles()) {
1947                // ... but don't touch the needs-init sentinel
1948                if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1949                    sf.delete();
1950                }
1951            }
1952        }
1953
1954        // Enqueue a new backup of every participant
1955        synchronized (mBackupParticipants) {
1956            final int N = mBackupParticipants.size();
1957            for (int i=0; i<N; i++) {
1958                HashSet<String> participants = mBackupParticipants.valueAt(i);
1959                if (participants != null) {
1960                    for (String packageName : participants) {
1961                        dataChangedImpl(packageName);
1962                    }
1963                }
1964            }
1965        }
1966    }
1967
1968    private TransportManager.TransportBoundListener mTransportBoundListener =
1969            new TransportManager.TransportBoundListener() {
1970        @Override
1971        public boolean onTransportBound(IBackupTransport transport) {
1972            // If the init sentinel file exists, we need to be sure to perform the init
1973            // as soon as practical.  We also create the state directory at registration
1974            // time to ensure it's present from the outset.
1975            String name = null;
1976            try {
1977                name = transport.name();
1978                String transportDirName = transport.transportDirName();
1979                File stateDir = new File(mBaseStateDir, transportDirName);
1980                stateDir.mkdirs();
1981
1982                File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1983                if (initSentinel.exists()) {
1984                    synchronized (mQueueLock) {
1985                        mPendingInits.add(name);
1986
1987                        // TODO: pick a better starting time than now + 1 minute
1988                        long delay = 1000 * 60; // one minute, in milliseconds
1989                        mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1990                                System.currentTimeMillis() + delay, mRunInitIntent);
1991                    }
1992                }
1993                return true;
1994            } catch (Exception e) {
1995                // the transport threw when asked its file naming prefs; declare it invalid
1996                Slog.w(TAG, "Failed to regiser transport: " + name);
1997                return false;
1998            }
1999        }
2000    };
2001
2002    // ----- Track installation/removal of packages -----
2003    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
2004        public void onReceive(Context context, Intent intent) {
2005            if (MORE_DEBUG) Slog.d(TAG, "Received broadcast " + intent);
2006
2007            String action = intent.getAction();
2008            boolean replacing = false;
2009            boolean added = false;
2010            boolean changed = false;
2011            Bundle extras = intent.getExtras();
2012            String pkgList[] = null;
2013            if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
2014                    Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
2015                    Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
2016                Uri uri = intent.getData();
2017                if (uri == null) {
2018                    return;
2019                }
2020                String pkgName = uri.getSchemeSpecificPart();
2021                if (pkgName != null) {
2022                    pkgList = new String[] { pkgName };
2023                }
2024                changed = Intent.ACTION_PACKAGE_CHANGED.equals(action);
2025
2026                // At package-changed we only care about looking at new transport states
2027                if (changed) {
2028                    String[] components =
2029                            intent.getStringArrayExtra(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
2030
2031                    if (MORE_DEBUG) {
2032                        Slog.i(TAG, "Package " + pkgName + " changed; rechecking");
2033                        for (int i = 0; i < components.length; i++) {
2034                            Slog.i(TAG, "   * " + components[i]);
2035                        }
2036                    }
2037
2038                    mTransportManager.onPackageChanged(pkgName, components);
2039                    return; // nothing more to do in the PACKAGE_CHANGED case
2040                }
2041
2042                added = Intent.ACTION_PACKAGE_ADDED.equals(action);
2043                replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
2044            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
2045                added = true;
2046                pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
2047            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
2048                added = false;
2049                pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
2050            }
2051
2052            if (pkgList == null || pkgList.length == 0) {
2053                return;
2054            }
2055
2056            final int uid = extras.getInt(Intent.EXTRA_UID);
2057            if (added) {
2058                synchronized (mBackupParticipants) {
2059                    if (replacing) {
2060                        // This is the package-replaced case; we just remove the entry
2061                        // under the old uid and fall through to re-add.  If an app
2062                        // just added key/value backup participation, this picks it up
2063                        // as a known participant.
2064                        removePackageParticipantsLocked(pkgList, uid);
2065                    }
2066                    addPackageParticipantsLocked(pkgList);
2067                }
2068                // If they're full-backup candidates, add them there instead
2069                final long now = System.currentTimeMillis();
2070                for (String packageName : pkgList) {
2071                    try {
2072                        PackageInfo app = mPackageManager.getPackageInfo(packageName, 0);
2073                        if (appGetsFullBackup(app)
2074                                && appIsEligibleForBackup(app.applicationInfo, mPackageManager)) {
2075                            enqueueFullBackup(packageName, now);
2076                            scheduleNextFullBackupJob(0);
2077                        } else {
2078                            // The app might have just transitioned out of full-data into
2079                            // doing key/value backups, or might have just disabled backups
2080                            // entirely.  Make sure it is no longer in the full-data queue.
2081                            synchronized (mQueueLock) {
2082                                dequeueFullBackupLocked(packageName);
2083                            }
2084                            writeFullBackupScheduleAsync();
2085                        }
2086
2087                        mTransportManager.onPackageAdded(packageName);
2088
2089                    } catch (NameNotFoundException e) {
2090                        // doesn't really exist; ignore it
2091                        if (DEBUG) {
2092                            Slog.w(TAG, "Can't resolve new app " + packageName);
2093                        }
2094                    }
2095                }
2096
2097                // Whenever a package is added or updated we need to update
2098                // the package metadata bookkeeping.
2099                dataChangedImpl(PACKAGE_MANAGER_SENTINEL);
2100            } else {
2101                if (replacing) {
2102                    // The package is being updated.  We'll receive a PACKAGE_ADDED shortly.
2103                } else {
2104                    // Outright removal.  In the full-data case, the app will be dropped
2105                    // from the queue when its (now obsolete) name comes up again for
2106                    // backup.
2107                    synchronized (mBackupParticipants) {
2108                        removePackageParticipantsLocked(pkgList, uid);
2109                    }
2110                }
2111                for (String pkgName : pkgList) {
2112                    mTransportManager.onPackageRemoved(pkgName);
2113                }
2114            }
2115        }
2116    };
2117
2118    // Add the backup agents in the given packages to our set of known backup participants.
2119    // If 'packageNames' is null, adds all backup agents in the whole system.
2120    void addPackageParticipantsLocked(String[] packageNames) {
2121        // Look for apps that define the android:backupAgent attribute
2122        List<PackageInfo> targetApps = allAgentPackages();
2123        if (packageNames != null) {
2124            if (MORE_DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
2125            for (String packageName : packageNames) {
2126                addPackageParticipantsLockedInner(packageName, targetApps);
2127            }
2128        } else {
2129            if (MORE_DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
2130            addPackageParticipantsLockedInner(null, targetApps);
2131        }
2132    }
2133
2134    private void addPackageParticipantsLockedInner(String packageName,
2135            List<PackageInfo> targetPkgs) {
2136        if (MORE_DEBUG) {
2137            Slog.v(TAG, "Examining " + packageName + " for backup agent");
2138        }
2139
2140        for (PackageInfo pkg : targetPkgs) {
2141            if (packageName == null || pkg.packageName.equals(packageName)) {
2142                int uid = pkg.applicationInfo.uid;
2143                HashSet<String> set = mBackupParticipants.get(uid);
2144                if (set == null) {
2145                    set = new HashSet<>();
2146                    mBackupParticipants.put(uid, set);
2147                }
2148                set.add(pkg.packageName);
2149                if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
2150
2151                // Schedule a backup for it on general principles
2152                if (MORE_DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName);
2153                Message msg = mBackupHandler
2154                        .obtainMessage(MSG_SCHEDULE_BACKUP_PACKAGE, pkg.packageName);
2155                mBackupHandler.sendMessage(msg);
2156            }
2157        }
2158    }
2159
2160    // Remove the given packages' entries from our known active set.
2161    void removePackageParticipantsLocked(String[] packageNames, int oldUid) {
2162        if (packageNames == null) {
2163            Slog.w(TAG, "removePackageParticipants with null list");
2164            return;
2165        }
2166
2167        if (MORE_DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid
2168                + " #" + packageNames.length);
2169        for (String pkg : packageNames) {
2170            // Known previous UID, so we know which package set to check
2171            HashSet<String> set = mBackupParticipants.get(oldUid);
2172            if (set != null && set.contains(pkg)) {
2173                removePackageFromSetLocked(set, pkg);
2174                if (set.isEmpty()) {
2175                    if (MORE_DEBUG) Slog.v(TAG, "  last one of this uid; purging set");
2176                    mBackupParticipants.remove(oldUid);
2177                }
2178            }
2179        }
2180    }
2181
2182    private void removePackageFromSetLocked(final HashSet<String> set,
2183            final String packageName) {
2184        if (set.contains(packageName)) {
2185            // Found it.  Remove this one package from the bookkeeping, and
2186            // if it's the last participating app under this uid we drop the
2187            // (now-empty) set as well.
2188            // Note that we deliberately leave it 'known' in the "ever backed up"
2189            // bookkeeping so that its current-dataset data will be retrieved
2190            // if the app is subsequently reinstalled
2191            if (MORE_DEBUG) Slog.v(TAG, "  removing participant " + packageName);
2192            set.remove(packageName);
2193            mPendingBackups.remove(packageName);
2194        }
2195    }
2196
2197    // Returns the set of all applications that define an android:backupAgent attribute
2198    List<PackageInfo> allAgentPackages() {
2199        // !!! TODO: cache this and regenerate only when necessary
2200        int flags = PackageManager.GET_SIGNATURES;
2201        List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
2202        int N = packages.size();
2203        for (int a = N-1; a >= 0; a--) {
2204            PackageInfo pkg = packages.get(a);
2205            try {
2206                ApplicationInfo app = pkg.applicationInfo;
2207                if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
2208                        || app.backupAgentName == null
2209                        || (app.flags&ApplicationInfo.FLAG_FULL_BACKUP_ONLY) != 0) {
2210                    packages.remove(a);
2211                }
2212                else {
2213                    // we will need the shared library path, so look that up and store it here.
2214                    // This is used implicitly when we pass the PackageInfo object off to
2215                    // the Activity Manager to launch the app for backup/restore purposes.
2216                    app = mPackageManager.getApplicationInfo(pkg.packageName,
2217                            PackageManager.GET_SHARED_LIBRARY_FILES);
2218                    pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
2219                }
2220            } catch (NameNotFoundException e) {
2221                packages.remove(a);
2222            }
2223        }
2224        return packages;
2225    }
2226
2227    // Called from the backup tasks: record that the given app has been successfully
2228    // backed up at least once.  This includes both key/value and full-data backups
2229    // through the transport.
2230    void logBackupComplete(String packageName) {
2231        if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
2232
2233        synchronized (mEverStoredApps) {
2234            if (!mEverStoredApps.add(packageName)) return;
2235
2236            RandomAccessFile out = null;
2237            try {
2238                out = new RandomAccessFile(mEverStored, "rws");
2239                out.seek(out.length());
2240                out.writeUTF(packageName);
2241            } catch (IOException e) {
2242                Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
2243            } finally {
2244                try { if (out != null) out.close(); } catch (IOException e) {}
2245            }
2246        }
2247    }
2248
2249    // Remove our awareness of having ever backed up the given package
2250    void removeEverBackedUp(String packageName) {
2251        if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
2252        if (MORE_DEBUG) Slog.v(TAG, "New set:");
2253
2254        synchronized (mEverStoredApps) {
2255            // Rewrite the file and rename to overwrite.  If we reboot in the middle,
2256            // we'll recognize on initialization time that the package no longer
2257            // exists and fix it up then.
2258            File tempKnownFile = new File(mBaseStateDir, "processed.new");
2259            RandomAccessFile known = null;
2260            try {
2261                known = new RandomAccessFile(tempKnownFile, "rws");
2262                mEverStoredApps.remove(packageName);
2263                for (String s : mEverStoredApps) {
2264                    known.writeUTF(s);
2265                    if (MORE_DEBUG) Slog.v(TAG, "    " + s);
2266                }
2267                known.close();
2268                known = null;
2269                if (!tempKnownFile.renameTo(mEverStored)) {
2270                    throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
2271                }
2272            } catch (IOException e) {
2273                // Bad: we couldn't create the new copy.  For safety's sake we
2274                // abandon the whole process and remove all what's-backed-up
2275                // state entirely, meaning we'll force a backup pass for every
2276                // participant on the next boot or [re]install.
2277                Slog.w(TAG, "Error rewriting " + mEverStored, e);
2278                mEverStoredApps.clear();
2279                tempKnownFile.delete();
2280                mEverStored.delete();
2281            } finally {
2282                try { if (known != null) known.close(); } catch (IOException e) {}
2283            }
2284        }
2285    }
2286
2287    // Persistently record the current and ancestral backup tokens as well
2288    // as the set of packages with data [supposedly] available in the
2289    // ancestral dataset.
2290    void writeRestoreTokens() {
2291        try {
2292            RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
2293
2294            // First, the version number of this record, for futureproofing
2295            af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
2296
2297            // Write the ancestral and current tokens
2298            af.writeLong(mAncestralToken);
2299            af.writeLong(mCurrentToken);
2300
2301            // Now write the set of ancestral packages
2302            if (mAncestralPackages == null) {
2303                af.writeInt(-1);
2304            } else {
2305                af.writeInt(mAncestralPackages.size());
2306                if (DEBUG) Slog.v(TAG, "Ancestral packages:  " + mAncestralPackages.size());
2307                for (String pkgName : mAncestralPackages) {
2308                    af.writeUTF(pkgName);
2309                    if (MORE_DEBUG) Slog.v(TAG, "   " + pkgName);
2310                }
2311            }
2312            af.close();
2313        } catch (IOException e) {
2314            Slog.w(TAG, "Unable to write token file:", e);
2315        }
2316    }
2317
2318    // What name is this transport registered under...?
2319    private String getTransportName(IBackupTransport transport) {
2320        if (MORE_DEBUG) {
2321            Slog.v(TAG, "Searching for transport name of " + transport);
2322        }
2323        return mTransportManager.getTransportName(transport);
2324    }
2325
2326    // fire off a backup agent, blocking until it attaches or times out
2327    @Override
2328    public IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
2329        IBackupAgent agent = null;
2330        synchronized(mAgentConnectLock) {
2331            mConnecting = true;
2332            mConnectedAgent = null;
2333            try {
2334                if (mActivityManager.bindBackupAgent(app.packageName, mode,
2335                        UserHandle.USER_OWNER)) {
2336                    Slog.d(TAG, "awaiting agent for " + app);
2337
2338                    // success; wait for the agent to arrive
2339                    // only wait 10 seconds for the bind to happen
2340                    long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
2341                    while (mConnecting && mConnectedAgent == null
2342                            && (System.currentTimeMillis() < timeoutMark)) {
2343                        try {
2344                            mAgentConnectLock.wait(5000);
2345                        } catch (InterruptedException e) {
2346                            // just bail
2347                            Slog.w(TAG, "Interrupted: " + e);
2348                            mConnecting = false;
2349                            mConnectedAgent = null;
2350                        }
2351                    }
2352
2353                    // if we timed out with no connect, abort and move on
2354                    if (mConnecting == true) {
2355                        Slog.w(TAG, "Timeout waiting for agent " + app);
2356                        mConnectedAgent = null;
2357                    }
2358                    if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
2359                    agent = mConnectedAgent;
2360                }
2361            } catch (RemoteException e) {
2362                // can't happen - ActivityManager is local
2363            }
2364        }
2365        if (agent == null) {
2366            try {
2367                mActivityManager.clearPendingBackup();
2368            } catch (RemoteException e) {
2369                // can't happen - ActivityManager is local
2370            }
2371        }
2372        return agent;
2373    }
2374
2375    // clear an application's data, blocking until the operation completes or times out
2376    void clearApplicationDataSynchronous(String packageName) {
2377        // Don't wipe packages marked allowClearUserData=false
2378        try {
2379            PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
2380            if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
2381                if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
2382                        + packageName);
2383                return;
2384            }
2385        } catch (NameNotFoundException e) {
2386            Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
2387            return;
2388        }
2389
2390        ClearDataObserver observer = new ClearDataObserver();
2391
2392        synchronized(mClearDataLock) {
2393            mClearingData = true;
2394            try {
2395                mActivityManager.clearApplicationUserData(packageName, observer, 0);
2396            } catch (RemoteException e) {
2397                // can't happen because the activity manager is in this process
2398            }
2399
2400            // only wait 10 seconds for the clear data to happen
2401            long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
2402            while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
2403                try {
2404                    mClearDataLock.wait(5000);
2405                } catch (InterruptedException e) {
2406                    // won't happen, but still.
2407                    mClearingData = false;
2408                }
2409            }
2410        }
2411    }
2412
2413    class ClearDataObserver extends IPackageDataObserver.Stub {
2414        public void onRemoveCompleted(String packageName, boolean succeeded) {
2415            synchronized(mClearDataLock) {
2416                mClearingData = false;
2417                mClearDataLock.notifyAll();
2418            }
2419        }
2420    }
2421
2422    // Get the restore-set token for the best-available restore set for this package:
2423    // the active set if possible, else the ancestral one.  Returns zero if none available.
2424    @Override
2425    public long getAvailableRestoreToken(String packageName) {
2426        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2427                "getAvailableRestoreToken");
2428
2429        long token = mAncestralToken;
2430        synchronized (mQueueLock) {
2431            if (mCurrentToken != 0 && mEverStoredApps.contains(packageName)) {
2432                if (MORE_DEBUG) {
2433                    Slog.i(TAG, "App in ever-stored, so using current token");
2434                }
2435                token = mCurrentToken;
2436            }
2437        }
2438        if (MORE_DEBUG) Slog.i(TAG, "getAvailableRestoreToken() == " + token);
2439        return token;
2440    }
2441
2442    @Override
2443    public int requestBackup(String[] packages, IBackupObserver observer, int flags) {
2444        return requestBackup(packages, observer, null, flags);
2445    }
2446
2447    @Override
2448    public int requestBackup(String[] packages, IBackupObserver observer,
2449            IBackupManagerMonitor monitor, int flags) {
2450        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "requestBackup");
2451
2452        if (packages == null || packages.length < 1) {
2453            Slog.e(TAG, "No packages named for backup request");
2454            sendBackupFinished(observer, BackupManager.ERROR_TRANSPORT_ABORTED);
2455            monitor = monitorEvent(monitor, BackupManagerMonitor.LOG_EVENT_ID_NO_PACKAGES,
2456                    null, BackupManagerMonitor.LOG_EVENT_CATEGORY_TRANSPORT, null);
2457            throw new IllegalArgumentException("No packages are provided for backup");
2458        }
2459
2460        IBackupTransport transport = mTransportManager.getCurrentTransportBinder();
2461        if (transport == null) {
2462            sendBackupFinished(observer, BackupManager.ERROR_TRANSPORT_ABORTED);
2463            monitor = monitorEvent(monitor, BackupManagerMonitor.LOG_EVENT_ID_TRANSPORT_IS_NULL,
2464                    null, BackupManagerMonitor.LOG_EVENT_CATEGORY_TRANSPORT, null);
2465            return BackupManager.ERROR_TRANSPORT_ABORTED;
2466        }
2467
2468        ArrayList<String> fullBackupList = new ArrayList<>();
2469        ArrayList<String> kvBackupList = new ArrayList<>();
2470        for (String packageName : packages) {
2471            if (PACKAGE_MANAGER_SENTINEL.equals(packageName)) {
2472                kvBackupList.add(packageName);
2473                continue;
2474            }
2475            try {
2476                PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName,
2477                        PackageManager.GET_SIGNATURES);
2478                if (!appIsEligibleForBackup(packageInfo.applicationInfo, mPackageManager)) {
2479                    sendBackupOnPackageResult(observer, packageName,
2480                            BackupManager.ERROR_BACKUP_NOT_ALLOWED);
2481                    continue;
2482                }
2483                if (appGetsFullBackup(packageInfo)) {
2484                    fullBackupList.add(packageInfo.packageName);
2485                } else {
2486                    kvBackupList.add(packageInfo.packageName);
2487                }
2488            } catch (NameNotFoundException e) {
2489                sendBackupOnPackageResult(observer, packageName,
2490                        BackupManager.ERROR_PACKAGE_NOT_FOUND);
2491            }
2492        }
2493        EventLog.writeEvent(EventLogTags.BACKUP_REQUESTED, packages.length, kvBackupList.size(),
2494                fullBackupList.size());
2495        if (MORE_DEBUG) {
2496            Slog.i(TAG, "Backup requested for " + packages.length + " packages, of them: " +
2497                fullBackupList.size() + " full backups, " + kvBackupList.size() + " k/v backups");
2498        }
2499
2500        String dirName;
2501        try {
2502            dirName = transport.transportDirName();
2503        } catch (Exception e) {
2504            Slog.e(TAG, "Transport unavailable while attempting backup: " + e.getMessage());
2505            sendBackupFinished(observer, BackupManager.ERROR_TRANSPORT_ABORTED);
2506            return BackupManager.ERROR_TRANSPORT_ABORTED;
2507        }
2508
2509        boolean nonIncrementalBackup = (flags & BackupManager.FLAG_NON_INCREMENTAL_BACKUP) != 0;
2510
2511        Message msg = mBackupHandler.obtainMessage(MSG_REQUEST_BACKUP);
2512        msg.obj = new BackupParams(transport, dirName, kvBackupList, fullBackupList, observer,
2513                monitor, true, nonIncrementalBackup);
2514        mBackupHandler.sendMessage(msg);
2515        return BackupManager.SUCCESS;
2516    }
2517
2518    // Cancel all running backups.
2519    @Override
2520    public void cancelBackups(){
2521        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "cancelBackups");
2522        if (MORE_DEBUG) {
2523            Slog.i(TAG, "cancelBackups() called.");
2524        }
2525        final long oldToken = Binder.clearCallingIdentity();
2526        try {
2527            List<Integer> operationsToCancel = new ArrayList<>();
2528            synchronized (mCurrentOpLock) {
2529                for (int i = 0; i < mCurrentOperations.size(); i++) {
2530                    Operation op = mCurrentOperations.valueAt(i);
2531                    int token = mCurrentOperations.keyAt(i);
2532                    if (op.type == OP_TYPE_BACKUP) {
2533                        operationsToCancel.add(token);
2534                    }
2535                }
2536            }
2537            for (Integer token : operationsToCancel) {
2538                handleCancel(token, true /* cancelAll */);
2539            }
2540            // We don't want the backup jobs to kick in any time soon.
2541            // Reschedules them to run in the distant future.
2542            KeyValueBackupJob.schedule(mContext, BUSY_BACKOFF_MIN_MILLIS);
2543            FullBackupJob.schedule(mContext, 2 * BUSY_BACKOFF_MIN_MILLIS);
2544        } finally {
2545            Binder.restoreCallingIdentity(oldToken);
2546        }
2547    }
2548
2549    @Override
2550    public void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback,
2551        int operationType) {
2552        if (operationType != OP_TYPE_BACKUP_WAIT && operationType != OP_TYPE_RESTORE_WAIT) {
2553            Slog.wtf(TAG, "prepareOperationTimeout() doesn't support operation " +
2554                    Integer.toHexString(token) + " of type " + operationType);
2555            return;
2556        }
2557        if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
2558                + " interval=" + interval + " callback=" + callback);
2559
2560        synchronized (mCurrentOpLock) {
2561            mCurrentOperations.put(token, new Operation(OP_PENDING, callback, operationType));
2562            Message msg = mBackupHandler.obtainMessage(getMessageIdForOperationType(operationType),
2563                    token, 0, callback);
2564            mBackupHandler.sendMessageDelayed(msg, interval);
2565        }
2566    }
2567
2568    private int getMessageIdForOperationType(int operationType) {
2569        switch (operationType) {
2570            case OP_TYPE_BACKUP_WAIT:
2571                return MSG_BACKUP_OPERATION_TIMEOUT;
2572            case OP_TYPE_RESTORE_WAIT:
2573                return MSG_RESTORE_OPERATION_TIMEOUT;
2574            default:
2575                Slog.wtf(TAG, "getMessageIdForOperationType called on invalid operation type: " +
2576                        operationType);
2577                return -1;
2578        }
2579    }
2580
2581    private void removeOperation(int token) {
2582        if (MORE_DEBUG) {
2583            Slog.d(TAG, "Removing operation token=" + Integer.toHexString(token));
2584        }
2585        synchronized (mCurrentOpLock) {
2586            if (mCurrentOperations.get(token) == null) {
2587                Slog.w(TAG, "Duplicate remove for operation. token=" +
2588                        Integer.toHexString(token));
2589            }
2590            mCurrentOperations.remove(token);
2591        }
2592    }
2593
2594    // synchronous waiter case
2595    @Override
2596    public boolean waitUntilOperationComplete(int token) {
2597        if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
2598                + Integer.toHexString(token));
2599        int finalState = OP_PENDING;
2600        Operation op = null;
2601        synchronized (mCurrentOpLock) {
2602            while (true) {
2603                op = mCurrentOperations.get(token);
2604                if (op == null) {
2605                    // mysterious disappearance: treat as success with no callback
2606                    break;
2607                } else {
2608                    if (op.state == OP_PENDING) {
2609                        try {
2610                            mCurrentOpLock.wait();
2611                        } catch (InterruptedException e) {
2612                        }
2613                        // When the wait is notified we loop around and recheck the current state
2614                    } else {
2615                        if (MORE_DEBUG) {
2616                            Slog.d(TAG, "Unblocked waiting for operation token=" +
2617                                    Integer.toHexString(token));
2618                        }
2619                        // No longer pending; we're done
2620                        finalState = op.state;
2621                        break;
2622                    }
2623                }
2624            }
2625        }
2626
2627        removeOperation(token);
2628        if (op != null) {
2629            mBackupHandler.removeMessages(getMessageIdForOperationType(op.type));
2630        }
2631        if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
2632                + " complete: finalState=" + finalState);
2633        return finalState == OP_ACKNOWLEDGED;
2634    }
2635
2636    void handleCancel(int token, boolean cancelAll) {
2637        // Notify any synchronous waiters
2638        Operation op = null;
2639        synchronized (mCurrentOpLock) {
2640            op = mCurrentOperations.get(token);
2641            if (MORE_DEBUG) {
2642                if (op == null) Slog.w(TAG, "Cancel of token " + Integer.toHexString(token)
2643                        + " but no op found");
2644            }
2645            int state = (op != null) ? op.state : OP_TIMEOUT;
2646            if (state == OP_ACKNOWLEDGED) {
2647                // The operation finished cleanly, so we have nothing more to do.
2648                if (DEBUG) {
2649                    Slog.w(TAG, "Operation already got an ack." +
2650                            "Should have been removed from mCurrentOperations.");
2651                }
2652                op = null;
2653                mCurrentOperations.delete(token);
2654            } else if (state == OP_PENDING) {
2655                if (DEBUG) Slog.v(TAG, "Cancel: token=" + Integer.toHexString(token));
2656                op.state = OP_TIMEOUT;
2657                // Can't delete op from mCurrentOperations here. waitUntilOperationComplete may be
2658                // called after we receive cancel here. We need this op's state there.
2659
2660                // Remove all pending timeout messages of types OP_TYPE_BACKUP_WAIT and
2661                // OP_TYPE_RESTORE_WAIT. On the other hand, OP_TYPE_BACKUP cannot time out and
2662                // doesn't require cancellation.
2663                if (op.type == OP_TYPE_BACKUP_WAIT || op.type == OP_TYPE_RESTORE_WAIT) {
2664                    mBackupHandler.removeMessages(getMessageIdForOperationType(op.type));
2665                }
2666            }
2667            mCurrentOpLock.notifyAll();
2668        }
2669
2670        // If there's a TimeoutHandler for this event, call it
2671        if (op != null && op.callback != null) {
2672            if (MORE_DEBUG) {
2673                Slog.v(TAG, "   Invoking cancel on " + op.callback);
2674            }
2675            op.callback.handleCancel(cancelAll);
2676        }
2677    }
2678
2679    // ----- Back up a set of applications via a worker thread -----
2680
2681    enum BackupState {
2682        INITIAL,
2683        RUNNING_QUEUE,
2684        FINAL
2685    }
2686
2687    /**
2688     * This class handles the process of backing up a given list of key/value backup packages.
2689     * Also takes in a list of pending dolly backups and kicks them off when key/value backups
2690     * are done.
2691     *
2692     * Flow:
2693     * If required, backup @pm@.
2694     * For each pending key/value backup package:
2695     *     - Bind to agent.
2696     *     - Call agent.doBackup()
2697     *     - Wait either for cancel/timeout or operationComplete() callback from the agent.
2698     * Start task to perform dolly backups.
2699     *
2700     * There are three entry points into this class:
2701     *     - execute() [Called from the handler thread]
2702     *     - operationComplete(long result) [Called from the handler thread]
2703     *     - handleCancel(boolean cancelAll) [Can be called from any thread]
2704     * These methods synchronize on mCancelLock.
2705     *
2706     * Interaction with mCurrentOperations:
2707     *     - An entry for this task is put into mCurrentOperations for the entire lifetime of the
2708     *       task. This is useful to cancel the task if required.
2709     *     - An ephemeral entry is put into mCurrentOperations each time we are waiting on for
2710     *       response from a backup agent. This is used to plumb timeouts and completion callbacks.
2711     */
2712    class PerformBackupTask implements BackupRestoreTask {
2713        private static final String TAG = "PerformBackupTask";
2714
2715        private final Object mCancelLock = new Object();
2716
2717        IBackupTransport mTransport;
2718        ArrayList<BackupRequest> mQueue;
2719        ArrayList<BackupRequest> mOriginalQueue;
2720        File mStateDir;
2721        File mJournal;
2722        BackupState mCurrentState;
2723        List<String> mPendingFullBackups;
2724        IBackupObserver mObserver;
2725        IBackupManagerMonitor mMonitor;
2726
2727        private final PerformFullTransportBackupTask mFullBackupTask;
2728        private final int mCurrentOpToken;
2729        private volatile int mEphemeralOpToken;
2730
2731        // carried information about the current in-flight operation
2732        IBackupAgent mAgentBinder;
2733        PackageInfo mCurrentPackage;
2734        File mSavedStateName;
2735        File mBackupDataName;
2736        File mNewStateName;
2737        ParcelFileDescriptor mSavedState;
2738        ParcelFileDescriptor mBackupData;
2739        ParcelFileDescriptor mNewState;
2740        int mStatus;
2741        boolean mFinished;
2742        final boolean mUserInitiated;
2743        final boolean mNonIncremental;
2744
2745        private volatile boolean mCancelAll;
2746
2747        public PerformBackupTask(IBackupTransport transport, String dirName,
2748                ArrayList<BackupRequest> queue, File journal, IBackupObserver observer,
2749                IBackupManagerMonitor monitor, List<String> pendingFullBackups,
2750                boolean userInitiated, boolean nonIncremental) {
2751            mTransport = transport;
2752            mOriginalQueue = queue;
2753            mQueue = new ArrayList<>();
2754            mJournal = journal;
2755            mObserver = observer;
2756            mMonitor = monitor;
2757            mPendingFullBackups = pendingFullBackups;
2758            mUserInitiated = userInitiated;
2759            mNonIncremental = nonIncremental;
2760
2761            mStateDir = new File(mBaseStateDir, dirName);
2762            mCurrentOpToken = generateRandomIntegerToken();
2763
2764            mFinished = false;
2765
2766            synchronized (mCurrentOpLock) {
2767                if (isBackupOperationInProgress()) {
2768                    if (DEBUG) {
2769                        Slog.d(TAG, "Skipping backup since one is already in progress.");
2770                    }
2771                    mCancelAll = true;
2772                    mFullBackupTask = null;
2773                    mCurrentState = BackupState.FINAL;
2774                    addBackupTrace("Skipped. Backup already in progress.");
2775                } else {
2776                    mCurrentState = BackupState.INITIAL;
2777                    CountDownLatch latch = new CountDownLatch(1);
2778                    String[] fullBackups =
2779                            mPendingFullBackups.toArray(new String[mPendingFullBackups.size()]);
2780                    mFullBackupTask =
2781                            new PerformFullTransportBackupTask(/*fullBackupRestoreObserver*/ null,
2782                                    fullBackups, /*updateSchedule*/ false, /*runningJob*/ null,
2783                                    latch,
2784                                    mObserver, mMonitor, mUserInitiated);
2785
2786                    registerTask();
2787                    addBackupTrace("STATE => INITIAL");
2788                }
2789            }
2790        }
2791
2792        /**
2793         * Put this task in the repository of running tasks.
2794         */
2795        private void registerTask() {
2796            synchronized (mCurrentOpLock) {
2797                mCurrentOperations.put(mCurrentOpToken, new Operation(OP_PENDING, this,
2798                        OP_TYPE_BACKUP));
2799            }
2800        }
2801
2802        /**
2803         * Remove this task from repository of running tasks.
2804         */
2805        private void unregisterTask() {
2806            removeOperation(mCurrentOpToken);
2807        }
2808
2809        // Main entry point: perform one chunk of work, updating the state as appropriate
2810        // and reposting the next chunk to the primary backup handler thread.
2811        @Override
2812        @GuardedBy("mCancelLock")
2813        public void execute() {
2814            synchronized (mCancelLock) {
2815                switch (mCurrentState) {
2816                    case INITIAL:
2817                        beginBackup();
2818                        break;
2819
2820                    case RUNNING_QUEUE:
2821                        invokeNextAgent();
2822                        break;
2823
2824                    case FINAL:
2825                        if (!mFinished) finalizeBackup();
2826                        else {
2827                            Slog.e(TAG, "Duplicate finish");
2828                        }
2829                        mFinished = true;
2830                        break;
2831                }
2832            }
2833        }
2834
2835        // We're starting a backup pass.  Initialize the transport and send
2836        // the PM metadata blob if we haven't already.
2837        void beginBackup() {
2838            if (DEBUG_BACKUP_TRACE) {
2839                clearBackupTrace();
2840                StringBuilder b = new StringBuilder(256);
2841                b.append("beginBackup: [");
2842                for (BackupRequest req : mOriginalQueue) {
2843                    b.append(' ');
2844                    b.append(req.packageName);
2845                }
2846                b.append(" ]");
2847                addBackupTrace(b.toString());
2848            }
2849
2850            mAgentBinder = null;
2851            mStatus = BackupTransport.TRANSPORT_OK;
2852
2853            // Sanity check: if the queue is empty we have no work to do.
2854            if (mOriginalQueue.isEmpty() && mPendingFullBackups.isEmpty()) {
2855                Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
2856                addBackupTrace("queue empty at begin");
2857                sendBackupFinished(mObserver, BackupManager.SUCCESS);
2858                executeNextState(BackupState.FINAL);
2859                return;
2860            }
2861
2862            // We need to retain the original queue contents in case of transport
2863            // failure, but we want a working copy that we can manipulate along
2864            // the way.
2865            mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
2866
2867            // When the transport is forcing non-incremental key/value payloads, we send the
2868            // metadata only if it explicitly asks for it.
2869            boolean skipPm = mNonIncremental;
2870
2871            // The app metadata pseudopackage might also be represented in the
2872            // backup queue if apps have been added/removed since the last time
2873            // we performed a backup.  Drop it from the working queue now that
2874            // we're committed to evaluating it for backup regardless.
2875            for (int i = 0; i < mQueue.size(); i++) {
2876                if (PACKAGE_MANAGER_SENTINEL.equals(mQueue.get(i).packageName)) {
2877                    if (MORE_DEBUG) {
2878                        Slog.i(TAG, "Metadata in queue; eliding");
2879                    }
2880                    mQueue.remove(i);
2881                    skipPm = false;
2882                    break;
2883                }
2884            }
2885
2886            if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
2887
2888            File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2889            try {
2890                final String transportName = mTransport.transportDirName();
2891                EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
2892
2893                // If we haven't stored package manager metadata yet, we must init the transport.
2894                if (mStatus == BackupTransport.TRANSPORT_OK && pmState.length() <= 0) {
2895                    Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
2896                    addBackupTrace("initializing transport " + transportName);
2897                    resetBackupState(mStateDir);  // Just to make sure.
2898                    mStatus = mTransport.initializeDevice();
2899
2900                    addBackupTrace("transport.initializeDevice() == " + mStatus);
2901                    if (mStatus == BackupTransport.TRANSPORT_OK) {
2902                        EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
2903                    } else {
2904                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
2905                        Slog.e(TAG, "Transport error in initializeDevice()");
2906                    }
2907                }
2908
2909                if (skipPm) {
2910                    Slog.d(TAG, "Skipping backup of package metadata.");
2911                    executeNextState(BackupState.RUNNING_QUEUE);
2912                } else {
2913                    // The package manager doesn't have a proper <application> etc, but since
2914                    // it's running here in the system process we can just set up its agent
2915                    // directly and use a synthetic BackupRequest.  We always run this pass
2916                    // because it's cheap and this way we guarantee that we don't get out of
2917                    // step even if we're selecting among various transports at run time.
2918                    if (mStatus == BackupTransport.TRANSPORT_OK) {
2919                        PackageManagerBackupAgent pmAgent = makeMetadataAgent();
2920                        mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
2921                                IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
2922                        addBackupTrace("PMBA invoke: " + mStatus);
2923
2924                        // Because the PMBA is a local instance, it has already executed its
2925                        // backup callback and returned.  Blow away the lingering (spurious)
2926                        // pending timeout message for it.
2927                        mBackupHandler.removeMessages(MSG_BACKUP_OPERATION_TIMEOUT);
2928                    }
2929                }
2930
2931                if (mStatus == BackupTransport.TRANSPORT_NOT_INITIALIZED) {
2932                    // The backend reports that our dataset has been wiped.  Note this in
2933                    // the event log; the no-success code below will reset the backup
2934                    // state as well.
2935                    EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
2936                }
2937            } catch (Exception e) {
2938                Slog.e(TAG, "Error in backup thread", e);
2939                addBackupTrace("Exception in backup thread: " + e);
2940                mStatus = BackupTransport.TRANSPORT_ERROR;
2941            } finally {
2942                // If we've succeeded so far, invokeAgentForBackup() will have run the PM
2943                // metadata and its completion/timeout callback will continue the state
2944                // machine chain.  If it failed that won't happen; we handle that now.
2945                addBackupTrace("exiting prelim: " + mStatus);
2946                if (mStatus != BackupTransport.TRANSPORT_OK) {
2947                    // if things went wrong at this point, we need to
2948                    // restage everything and try again later.
2949                    resetBackupState(mStateDir);  // Just to make sure.
2950                    // In case of any other error, it's backup transport error.
2951                    sendBackupFinished(mObserver, BackupManager.ERROR_TRANSPORT_ABORTED);
2952                    executeNextState(BackupState.FINAL);
2953                }
2954            }
2955        }
2956
2957        // Transport has been initialized and the PM metadata submitted successfully
2958        // if that was warranted.  Now we process the single next thing in the queue.
2959        void invokeNextAgent() {
2960            mStatus = BackupTransport.TRANSPORT_OK;
2961            addBackupTrace("invoke q=" + mQueue.size());
2962
2963            // Sanity check that we have work to do.  If not, skip to the end where
2964            // we reestablish the wakelock invariants etc.
2965            if (mQueue.isEmpty()) {
2966                if (MORE_DEBUG) Slog.i(TAG, "queue now empty");
2967                executeNextState(BackupState.FINAL);
2968                return;
2969            }
2970
2971            // pop the entry we're going to process on this step
2972            BackupRequest request = mQueue.get(0);
2973            mQueue.remove(0);
2974
2975            Slog.d(TAG, "starting key/value backup of " + request);
2976            addBackupTrace("launch agent for " + request.packageName);
2977
2978            // Verify that the requested app exists; it might be something that
2979            // requested a backup but was then uninstalled.  The request was
2980            // journalled and rather than tamper with the journal it's safer
2981            // to sanity-check here.  This also gives us the classname of the
2982            // package's backup agent.
2983            try {
2984                mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
2985                        PackageManager.GET_SIGNATURES);
2986                if (!appIsEligibleForBackup(mCurrentPackage.applicationInfo, mPackageManager)) {
2987                    // The manifest has changed but we had a stale backup request pending.
2988                    // This won't happen again because the app won't be requesting further
2989                    // backups.
2990                    Slog.i(TAG, "Package " + request.packageName
2991                            + " no longer supports backup; skipping");
2992                    addBackupTrace("skipping - not eligible, completion is noop");
2993                    // Shouldn't happen in case of requested backup, as pre-check was done in
2994                    // #requestBackup(), except to app update done concurrently
2995                    sendBackupOnPackageResult(mObserver, mCurrentPackage.packageName,
2996                            BackupManager.ERROR_BACKUP_NOT_ALLOWED);
2997                    executeNextState(BackupState.RUNNING_QUEUE);
2998                    return;
2999                }
3000
3001                if (appGetsFullBackup(mCurrentPackage)) {
3002                    // It's possible that this app *formerly* was enqueued for key/value backup,
3003                    // but has since been updated and now only supports the full-data path.
3004                    // Don't proceed with a key/value backup for it in this case.
3005                    Slog.i(TAG, "Package " + request.packageName
3006                            + " requests full-data rather than key/value; skipping");
3007                    addBackupTrace("skipping - fullBackupOnly, completion is noop");
3008                    // Shouldn't happen in case of requested backup, as pre-check was done in
3009                    // #requestBackup()
3010                    sendBackupOnPackageResult(mObserver, mCurrentPackage.packageName,
3011                            BackupManager.ERROR_BACKUP_NOT_ALLOWED);
3012                    executeNextState(BackupState.RUNNING_QUEUE);
3013                    return;
3014                }
3015
3016                if (appIsStopped(mCurrentPackage.applicationInfo)) {
3017                    // The app has been force-stopped or cleared or just installed,
3018                    // and not yet launched out of that state, so just as it won't
3019                    // receive broadcasts, we won't run it for backup.
3020                    addBackupTrace("skipping - stopped");
3021                    sendBackupOnPackageResult(mObserver, mCurrentPackage.packageName,
3022                            BackupManager.ERROR_BACKUP_NOT_ALLOWED);
3023                    executeNextState(BackupState.RUNNING_QUEUE);
3024                    return;
3025                }
3026
3027                IBackupAgent agent = null;
3028                try {
3029                    mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
3030                    agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
3031                            ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL);
3032                    addBackupTrace("agent bound; a? = " + (agent != null));
3033                    if (agent != null) {
3034                        mAgentBinder = agent;
3035                        mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
3036                        // at this point we'll either get a completion callback from the
3037                        // agent, or a timeout message on the main handler.  either way, we're
3038                        // done here as long as we're successful so far.
3039                    } else {
3040                        // Timeout waiting for the agent
3041                        mStatus = BackupTransport.AGENT_ERROR;
3042                    }
3043                } catch (SecurityException ex) {
3044                    // Try for the next one.
3045                    Slog.d(TAG, "error in bind/backup", ex);
3046                    mStatus = BackupTransport.AGENT_ERROR;
3047                            addBackupTrace("agent SE");
3048                }
3049            } catch (NameNotFoundException e) {
3050                Slog.d(TAG, "Package does not exist; skipping");
3051                addBackupTrace("no such package");
3052                mStatus = BackupTransport.AGENT_UNKNOWN;
3053            } finally {
3054                mWakelock.setWorkSource(null);
3055
3056                // If there was an agent error, no timeout/completion handling will occur.
3057                // That means we need to direct to the next state ourselves.
3058                if (mStatus != BackupTransport.TRANSPORT_OK) {
3059                    BackupState nextState = BackupState.RUNNING_QUEUE;
3060                    mAgentBinder = null;
3061
3062                    // An agent-level failure means we reenqueue this one agent for
3063                    // a later retry, but otherwise proceed normally.
3064                    if (mStatus == BackupTransport.AGENT_ERROR) {
3065                        if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
3066                                + " - restaging");
3067                        dataChangedImpl(request.packageName);
3068                        mStatus = BackupTransport.TRANSPORT_OK;
3069                        if (mQueue.isEmpty()) nextState = BackupState.FINAL;
3070                        sendBackupOnPackageResult(mObserver, mCurrentPackage.packageName,
3071                                BackupManager.ERROR_AGENT_FAILURE);
3072                    } else if (mStatus == BackupTransport.AGENT_UNKNOWN) {
3073                        // Failed lookup of the app, so we couldn't bring up an agent, but
3074                        // we're otherwise fine.  Just drop it and go on to the next as usual.
3075                        mStatus = BackupTransport.TRANSPORT_OK;
3076                        sendBackupOnPackageResult(mObserver, mCurrentPackage.packageName,
3077                                BackupManager.ERROR_PACKAGE_NOT_FOUND);
3078                    } else {
3079                        // Transport-level failure means we reenqueue everything
3080                        revertAndEndBackup();
3081                        nextState = BackupState.FINAL;
3082                    }
3083
3084                    executeNextState(nextState);
3085                } else {
3086                    // success case
3087                    addBackupTrace("expecting completion/timeout callback");
3088                }
3089            }
3090        }
3091
3092        void finalizeBackup() {
3093            addBackupTrace("finishing");
3094
3095            // Mark packages that we didn't backup (because backup was cancelled, etc.) as needing
3096            // backup.
3097            for (BackupRequest req : mQueue) {
3098                dataChangedImpl(req.packageName);
3099            }
3100
3101            // Either backup was successful, in which case we of course do not need
3102            // this pass's journal any more; or it failed, in which case we just
3103            // re-enqueued all of these packages in the current active journal.
3104            // Either way, we no longer need this pass's journal.
3105            if (mJournal != null && !mJournal.delete()) {
3106                Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
3107            }
3108
3109            // If everything actually went through and this is the first time we've
3110            // done a backup, we can now record what the current backup dataset token
3111            // is.
3112            if ((mCurrentToken == 0) && (mStatus == BackupTransport.TRANSPORT_OK)) {
3113                addBackupTrace("success; recording token");
3114                try {
3115                    mCurrentToken = mTransport.getCurrentRestoreSet();
3116                    writeRestoreTokens();
3117                } catch (Exception e) {
3118                    // nothing for it at this point, unfortunately, but this will be
3119                    // recorded the next time we fully succeed.
3120                    Slog.e(TAG, "Transport threw reporting restore set: " + e.getMessage());
3121                    addBackupTrace("transport threw returning token");
3122                }
3123            }
3124
3125            // Set up the next backup pass - at this point we can set mBackupRunning
3126            // to false to allow another pass to fire, because we're done with the
3127            // state machine sequence and the wakelock is refcounted.
3128            synchronized (mQueueLock) {
3129                mBackupRunning = false;
3130                if (mStatus == BackupTransport.TRANSPORT_NOT_INITIALIZED) {
3131                    // Make sure we back up everything and perform the one-time init
3132                    if (MORE_DEBUG) Slog.d(TAG, "Server requires init; rerunning");
3133                    addBackupTrace("init required; rerunning");
3134                    try {
3135                        final String name = mTransportManager.getTransportName(mTransport);
3136                        if (name != null) {
3137                            mPendingInits.add(name);
3138                        } else {
3139                            if (DEBUG) {
3140                                Slog.w(TAG, "Couldn't find name of transport " + mTransport
3141                                        + " for init");
3142                            }
3143                        }
3144                    } catch (Exception e) {
3145                        Slog.w(TAG, "Failed to query transport name for init: " + e.getMessage());
3146                        // swallow it and proceed; we don't rely on this
3147                    }
3148                    clearMetadata();
3149                    backupNow();
3150                }
3151            }
3152
3153            clearBackupTrace();
3154
3155            unregisterTask();
3156
3157            if (!mCancelAll && mStatus == BackupTransport.TRANSPORT_OK &&
3158                    mPendingFullBackups != null && !mPendingFullBackups.isEmpty()) {
3159                Slog.d(TAG, "Starting full backups for: " + mPendingFullBackups);
3160                // Acquiring wakelock for PerformFullTransportBackupTask before its start.
3161                mWakelock.acquire();
3162                (new Thread(mFullBackupTask, "full-transport-requested")).start();
3163            } else if (mCancelAll) {
3164                if (mFullBackupTask != null) {
3165                    mFullBackupTask.unregisterTask();
3166                }
3167                sendBackupFinished(mObserver, BackupManager.ERROR_BACKUP_CANCELLED);
3168            } else {
3169                mFullBackupTask.unregisterTask();
3170                switch (mStatus) {
3171                    case BackupTransport.TRANSPORT_OK:
3172                        sendBackupFinished(mObserver, BackupManager.SUCCESS);
3173                        break;
3174                    case BackupTransport.TRANSPORT_NOT_INITIALIZED:
3175                        sendBackupFinished(mObserver, BackupManager.ERROR_TRANSPORT_ABORTED);
3176                        break;
3177                    case BackupTransport.TRANSPORT_ERROR:
3178                    default:
3179                        sendBackupFinished(mObserver, BackupManager.ERROR_TRANSPORT_ABORTED);
3180                        break;
3181                }
3182            }
3183            Slog.i(BackupManagerService.TAG, "K/V backup pass finished.");
3184            // Only once we're entirely finished do we release the wakelock for k/v backup.
3185            mWakelock.release();
3186        }
3187
3188        // Remove the PM metadata state. This will generate an init on the next pass.
3189        void clearMetadata() {
3190            final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
3191            if (pmState.exists()) pmState.delete();
3192        }
3193
3194        // Invoke an agent's doBackup() and start a timeout message spinning on the main
3195        // handler in case it doesn't get back to us.
3196        int invokeAgentForBackup(String packageName, IBackupAgent agent,
3197                IBackupTransport transport) {
3198            if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
3199            addBackupTrace("invoking " + packageName);
3200
3201            File blankStateName = new File(mStateDir, "blank_state");
3202            mSavedStateName = new File(mStateDir, packageName);
3203            mBackupDataName = new File(mDataDir, packageName + ".data");
3204            mNewStateName = new File(mStateDir, packageName + ".new");
3205            if (MORE_DEBUG) Slog.d(TAG, "data file: " + mBackupDataName);
3206
3207            mSavedState = null;
3208            mBackupData = null;
3209            mNewState = null;
3210
3211            boolean callingAgent = false;
3212            mEphemeralOpToken = generateRandomIntegerToken();
3213            try {
3214                // Look up the package info & signatures.  This is first so that if it
3215                // throws an exception, there's no file setup yet that would need to
3216                // be unraveled.
3217                if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
3218                    // The metadata 'package' is synthetic; construct one and make
3219                    // sure our global state is pointed at it
3220                    mCurrentPackage = new PackageInfo();
3221                    mCurrentPackage.packageName = packageName;
3222                }
3223
3224                // In a full backup, we pass a null ParcelFileDescriptor as
3225                // the saved-state "file". For key/value backups we pass the old state if
3226                // an incremental backup is required, and a blank state otherwise.
3227                mSavedState = ParcelFileDescriptor.open(
3228                        mNonIncremental ? blankStateName : mSavedStateName,
3229                        ParcelFileDescriptor.MODE_READ_ONLY |
3230                        ParcelFileDescriptor.MODE_CREATE);  // Make an empty file if necessary
3231
3232                mBackupData = ParcelFileDescriptor.open(mBackupDataName,
3233                        ParcelFileDescriptor.MODE_READ_WRITE |
3234                        ParcelFileDescriptor.MODE_CREATE |
3235                        ParcelFileDescriptor.MODE_TRUNCATE);
3236
3237                if (!SELinux.restorecon(mBackupDataName)) {
3238                    Slog.e(TAG, "SELinux restorecon failed on " + mBackupDataName);
3239                }
3240
3241                mNewState = ParcelFileDescriptor.open(mNewStateName,
3242                        ParcelFileDescriptor.MODE_READ_WRITE |
3243                        ParcelFileDescriptor.MODE_CREATE |
3244                        ParcelFileDescriptor.MODE_TRUNCATE);
3245
3246                final long quota = mTransport.getBackupQuota(packageName, false /* isFullBackup */);
3247                callingAgent = true;
3248
3249                // Initiate the target's backup pass
3250                addBackupTrace("setting timeout");
3251                prepareOperationTimeout(mEphemeralOpToken, TIMEOUT_BACKUP_INTERVAL, this,
3252                        OP_TYPE_BACKUP_WAIT);
3253                addBackupTrace("calling agent doBackup()");
3254
3255                agent.doBackup(mSavedState, mBackupData, mNewState, quota, mEphemeralOpToken,
3256                        mBackupManagerBinder);
3257            } catch (Exception e) {
3258                Slog.e(TAG, "Error invoking for backup on " + packageName + ". " + e);
3259                addBackupTrace("exception: " + e);
3260                EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
3261                        e.toString());
3262                errorCleanup();
3263                return callingAgent ? BackupTransport.AGENT_ERROR
3264                        : BackupTransport.TRANSPORT_ERROR;
3265            } finally {
3266                if (mNonIncremental) {
3267                    blankStateName.delete();
3268                }
3269            }
3270
3271            // At this point the agent is off and running.  The next thing to happen will
3272            // either be a callback from the agent, at which point we'll process its data
3273            // for transport, or a timeout.  Either way the next phase will happen in
3274            // response to the TimeoutHandler interface callbacks.
3275            addBackupTrace("invoke success");
3276            return BackupTransport.TRANSPORT_OK;
3277        }
3278
3279        public void failAgent(IBackupAgent agent, String message) {
3280            try {
3281                agent.fail(message);
3282            } catch (Exception e) {
3283                Slog.w(TAG, "Error conveying failure to " + mCurrentPackage.packageName);
3284            }
3285        }
3286
3287        // SHA-1 a byte array and return the result in hex
3288        private String SHA1Checksum(byte[] input) {
3289            final byte[] checksum;
3290            try {
3291                MessageDigest md = MessageDigest.getInstance("SHA-1");
3292                checksum = md.digest(input);
3293            } catch (NoSuchAlgorithmException e) {
3294                Slog.e(TAG, "Unable to use SHA-1!");
3295                return "00";
3296            }
3297
3298            StringBuffer sb = new StringBuffer(checksum.length * 2);
3299            for (int i = 0; i < checksum.length; i++) {
3300                sb.append(Integer.toHexString(checksum[i]));
3301            }
3302            return sb.toString();
3303        }
3304
3305        private void writeWidgetPayloadIfAppropriate(FileDescriptor fd, String pkgName)
3306                throws IOException {
3307            // TODO: http://b/22388012
3308            byte[] widgetState = AppWidgetBackupBridge.getWidgetState(pkgName,
3309                    UserHandle.USER_SYSTEM);
3310            // has the widget state changed since last time?
3311            final File widgetFile = new File(mStateDir, pkgName + "_widget");
3312            final boolean priorStateExists = widgetFile.exists();
3313
3314            if (MORE_DEBUG) {
3315                if (priorStateExists || widgetState != null) {
3316                    Slog.i(TAG, "Checking widget update: state=" + (widgetState != null)
3317                            + " prior=" + priorStateExists);
3318                }
3319            }
3320
3321            if (!priorStateExists && widgetState == null) {
3322                // no prior state, no new state => nothing to do
3323                return;
3324            }
3325
3326            // if the new state is not null, we might need to compare checksums to
3327            // determine whether to update the widget blob in the archive.  If the
3328            // widget state *is* null, we know a priori at this point that we simply
3329            // need to commit a deletion for it.
3330            String newChecksum = null;
3331            if (widgetState != null) {
3332                newChecksum = SHA1Checksum(widgetState);
3333                if (priorStateExists) {
3334                    final String priorChecksum;
3335                    try (
3336                        FileInputStream fin = new FileInputStream(widgetFile);
3337                        DataInputStream in = new DataInputStream(fin)
3338                    ) {
3339                        priorChecksum = in.readUTF();
3340                    }
3341                    if (Objects.equals(newChecksum, priorChecksum)) {
3342                        // Same checksum => no state change => don't rewrite the widget data
3343                        return;
3344                    }
3345                }
3346            } // else widget state *became* empty, so we need to commit a deletion
3347
3348            BackupDataOutput out = new BackupDataOutput(fd);
3349            if (widgetState != null) {
3350                try (
3351                    FileOutputStream fout = new FileOutputStream(widgetFile);
3352                    DataOutputStream stateOut = new DataOutputStream(fout)
3353                ) {
3354                    stateOut.writeUTF(newChecksum);
3355                }
3356
3357                out.writeEntityHeader(KEY_WIDGET_STATE, widgetState.length);
3358                out.writeEntityData(widgetState, widgetState.length);
3359            } else {
3360                // Widget state for this app has been removed; commit a deletion
3361                out.writeEntityHeader(KEY_WIDGET_STATE, -1);
3362                widgetFile.delete();
3363            }
3364        }
3365
3366        @Override
3367        @GuardedBy("mCancelLock")
3368        public void operationComplete(long unusedResult) {
3369            removeOperation(mEphemeralOpToken);
3370            synchronized (mCancelLock) {
3371                // The agent reported back to us!
3372                if (mFinished) {
3373                    Slog.d(TAG, "operationComplete received after task finished.");
3374                    return;
3375                }
3376
3377                if (mBackupData == null) {
3378                    // This callback was racing with our timeout, so we've cleaned up the
3379                    // agent state already and are on to the next thing.  We have nothing
3380                    // further to do here: agent state having been cleared means that we've
3381                    // initiated the appropriate next operation.
3382                    final String pkg = (mCurrentPackage != null)
3383                            ? mCurrentPackage.packageName : "[none]";
3384                    if (MORE_DEBUG) {
3385                        Slog.i(TAG, "Callback after agent teardown: " + pkg);
3386                    }
3387                    addBackupTrace("late opComplete; curPkg = " + pkg);
3388                    return;
3389                }
3390
3391                final String pkgName = mCurrentPackage.packageName;
3392                final long filepos = mBackupDataName.length();
3393                FileDescriptor fd = mBackupData.getFileDescriptor();
3394                try {
3395                    // If it's a 3rd party app, see whether they wrote any protected keys
3396                    // and complain mightily if they are attempting shenanigans.
3397                    if (mCurrentPackage.applicationInfo != null &&
3398                            (mCurrentPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
3399                                    == 0) {
3400                        ParcelFileDescriptor readFd = ParcelFileDescriptor.open(mBackupDataName,
3401                                ParcelFileDescriptor.MODE_READ_ONLY);
3402                        BackupDataInput in = new BackupDataInput(readFd.getFileDescriptor());
3403                        try {
3404                            while (in.readNextHeader()) {
3405                                final String key = in.getKey();
3406                                if (key != null && key.charAt(0) >= 0xff00) {
3407                                    // Not okay: crash them and bail.
3408                                    failAgent(mAgentBinder, "Illegal backup key: " + key);
3409                                    addBackupTrace("illegal key " + key + " from " + pkgName);
3410                                    EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, pkgName,
3411                                            "bad key");
3412                                    mMonitor = monitorEvent(mMonitor,
3413                                            BackupManagerMonitor.LOG_EVENT_ID_ILLEGAL_KEY,
3414                                            mCurrentPackage,
3415                                            BackupManagerMonitor
3416                                                    .LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
3417                                            putMonitoringExtra(null,
3418                                                    BackupManagerMonitor.EXTRA_LOG_ILLEGAL_KEY,
3419                                                    key));
3420                                    mBackupHandler.removeMessages(MSG_BACKUP_OPERATION_TIMEOUT);
3421                                    sendBackupOnPackageResult(mObserver, pkgName,
3422                                            BackupManager.ERROR_AGENT_FAILURE);
3423                                    errorCleanup();
3424                                    // agentErrorCleanup() implicitly executes next state properly
3425                                    return;
3426                                }
3427                                in.skipEntityData();
3428                            }
3429                        } finally {
3430                            if (readFd != null) {
3431                                readFd.close();
3432                            }
3433                        }
3434                    }
3435
3436                    // Piggyback the widget state payload, if any
3437                    writeWidgetPayloadIfAppropriate(fd, pkgName);
3438                } catch (IOException e) {
3439                    // Hard disk error; recovery/failure policy TBD.  For now roll back,
3440                    // but we may want to consider this a transport-level failure (i.e.
3441                    // we're in such a bad state that we can't contemplate doing backup
3442                    // operations any more during this pass).
3443                    Slog.w(TAG, "Unable to save widget state for " + pkgName);
3444                    try {
3445                        Os.ftruncate(fd, filepos);
3446                    } catch (ErrnoException ee) {
3447                        Slog.w(TAG, "Unable to roll back!");
3448                    }
3449                }
3450
3451                // Spin the data off to the transport and proceed with the next stage.
3452                if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
3453                        + pkgName);
3454                mBackupHandler.removeMessages(MSG_BACKUP_OPERATION_TIMEOUT);
3455                clearAgentState();
3456                addBackupTrace("operation complete");
3457
3458                ParcelFileDescriptor backupData = null;
3459                mStatus = BackupTransport.TRANSPORT_OK;
3460                long size = 0;
3461                try {
3462                    size = mBackupDataName.length();
3463                    if (size > 0) {
3464                        if (mStatus == BackupTransport.TRANSPORT_OK) {
3465                            backupData = ParcelFileDescriptor.open(mBackupDataName,
3466                                    ParcelFileDescriptor.MODE_READ_ONLY);
3467                            addBackupTrace("sending data to transport");
3468                            int flags = mUserInitiated ? BackupTransport.FLAG_USER_INITIATED : 0;
3469                            mStatus = mTransport.performBackup(mCurrentPackage, backupData, flags);
3470                        }
3471
3472                        // TODO - We call finishBackup() for each application backed up, because
3473                        // we need to know now whether it succeeded or failed.  Instead, we should
3474                        // hold off on finishBackup() until the end, which implies holding off on
3475                        // renaming *all* the output state files (see below) until that happens.
3476
3477                        addBackupTrace("data delivered: " + mStatus);
3478                        if (mStatus == BackupTransport.TRANSPORT_OK) {
3479                            addBackupTrace("finishing op on transport");
3480                            mStatus = mTransport.finishBackup();
3481                            addBackupTrace("finished: " + mStatus);
3482                        } else if (mStatus == BackupTransport.TRANSPORT_PACKAGE_REJECTED) {
3483                            addBackupTrace("transport rejected package");
3484                        }
3485                    } else {
3486                        if (MORE_DEBUG) Slog.i(TAG,
3487                                "no backup data written; not calling transport");
3488                        addBackupTrace("no data to send");
3489                        mMonitor = monitorEvent(mMonitor,
3490                                BackupManagerMonitor.LOG_EVENT_ID_NO_DATA_TO_SEND,
3491                                mCurrentPackage,
3492                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
3493                                null);
3494                    }
3495
3496                    if (mStatus == BackupTransport.TRANSPORT_OK) {
3497                        // After successful transport, delete the now-stale data
3498                        // and juggle the files so that next time we supply the agent
3499                        // with the new state file it just created.
3500                        mBackupDataName.delete();
3501                        mNewStateName.renameTo(mSavedStateName);
3502                        sendBackupOnPackageResult(mObserver, pkgName, BackupManager.SUCCESS);
3503                        EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, pkgName, size);
3504                        logBackupComplete(pkgName);
3505                    } else if (mStatus == BackupTransport.TRANSPORT_PACKAGE_REJECTED) {
3506                        // The transport has rejected backup of this specific package.  Roll it
3507                        // back but proceed with running the rest of the queue.
3508                        mBackupDataName.delete();
3509                        mNewStateName.delete();
3510                        sendBackupOnPackageResult(mObserver, pkgName,
3511                                BackupManager.ERROR_TRANSPORT_PACKAGE_REJECTED);
3512                        EventLogTags.writeBackupAgentFailure(pkgName, "Transport rejected");
3513                    } else if (mStatus == BackupTransport.TRANSPORT_QUOTA_EXCEEDED) {
3514                        sendBackupOnPackageResult(mObserver, pkgName,
3515                                BackupManager.ERROR_TRANSPORT_QUOTA_EXCEEDED);
3516                        EventLog.writeEvent(EventLogTags.BACKUP_QUOTA_EXCEEDED, pkgName);
3517                    } else {
3518                        // Actual transport-level failure to communicate the data to the backend
3519                        sendBackupOnPackageResult(mObserver, pkgName,
3520                                BackupManager.ERROR_TRANSPORT_ABORTED);
3521                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, pkgName);
3522                    }
3523                } catch (Exception e) {
3524                    sendBackupOnPackageResult(mObserver, pkgName,
3525                            BackupManager.ERROR_TRANSPORT_ABORTED);
3526                    Slog.e(TAG, "Transport error backing up " + pkgName, e);
3527                    EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, pkgName);
3528                    mStatus = BackupTransport.TRANSPORT_ERROR;
3529                } finally {
3530                    try {
3531                        if (backupData != null) backupData.close();
3532                    } catch (IOException e) {
3533                    }
3534                }
3535
3536                final BackupState nextState;
3537                if (mStatus == BackupTransport.TRANSPORT_OK
3538                        || mStatus == BackupTransport.TRANSPORT_PACKAGE_REJECTED) {
3539                    // Success or single-package rejection.  Proceed with the next app if any,
3540                    // otherwise we're done.
3541                    nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
3542                } else if (mStatus == BackupTransport.TRANSPORT_QUOTA_EXCEEDED) {
3543                    if (MORE_DEBUG) {
3544                        Slog.d(TAG, "Package " + mCurrentPackage.packageName +
3545                                " hit quota limit on k/v backup");
3546                    }
3547                    if (mAgentBinder != null) {
3548                        try {
3549                            long quota = mTransport.getBackupQuota(mCurrentPackage.packageName,
3550                                    false);
3551                            mAgentBinder.doQuotaExceeded(size, quota);
3552                        } catch (Exception e) {
3553                            Slog.e(TAG, "Unable to notify about quota exceeded: " + e.getMessage());
3554                        }
3555                    }
3556                    nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
3557                } else {
3558                    // Any other error here indicates a transport-level failure.  That means
3559                    // we need to halt everything and reschedule everything for next time.
3560                    revertAndEndBackup();
3561                    nextState = BackupState.FINAL;
3562                }
3563
3564                executeNextState(nextState);
3565            }
3566        }
3567
3568
3569        @Override
3570        @GuardedBy("mCancelLock")
3571        public void handleCancel(boolean cancelAll) {
3572            removeOperation(mEphemeralOpToken);
3573            synchronized (mCancelLock) {
3574                if (mFinished) {
3575                    // We have already cancelled this operation.
3576                    if (MORE_DEBUG) {
3577                        Slog.d(TAG, "Ignoring stale cancel. cancelAll=" + cancelAll);
3578                    }
3579                    return;
3580                }
3581                mCancelAll = cancelAll;
3582                final String logPackageName = (mCurrentPackage != null)
3583                        ? mCurrentPackage.packageName
3584                        : "no_package_yet";
3585                Slog.i(TAG, "Cancel backing up " + logPackageName);
3586                EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, logPackageName);
3587                addBackupTrace("cancel of " + logPackageName + ", cancelAll=" + cancelAll);
3588                mMonitor = monitorEvent(mMonitor,
3589                        BackupManagerMonitor.LOG_EVENT_ID_KEY_VALUE_BACKUP_CANCEL,
3590                        mCurrentPackage, BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT,
3591                        putMonitoringExtra(null, BackupManagerMonitor.EXTRA_LOG_CANCEL_ALL,
3592                                mCancelAll));
3593                errorCleanup();
3594                if (!cancelAll) {
3595                    // The current agent either timed out or was cancelled running doBackup().
3596                    // Restage it for the next time we run a backup pass.
3597                    // !!! TODO: keep track of failure counts per agent, and blacklist those which
3598                    // fail repeatedly (i.e. have proved themselves to be buggy).
3599                    executeNextState(
3600                            mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
3601                    dataChangedImpl(mCurrentPackage.packageName);
3602                } else {
3603                    finalizeBackup();
3604                }
3605            }
3606        }
3607
3608        void revertAndEndBackup() {
3609            if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
3610            addBackupTrace("transport error; reverting");
3611
3612            // We want to reset the backup schedule based on whatever the transport suggests
3613            // by way of retry/backoff time.
3614            long delay;
3615            try {
3616                delay = mTransport.requestBackupTime();
3617            } catch (Exception e) {
3618                Slog.w(TAG, "Unable to contact transport for recommended backoff: " + e.getMessage());
3619                delay = 0;  // use the scheduler's default
3620            }
3621            KeyValueBackupJob.schedule(mContext, delay);
3622
3623            for (BackupRequest request : mOriginalQueue) {
3624                dataChangedImpl(request.packageName);
3625            }
3626
3627        }
3628
3629        void errorCleanup() {
3630            mBackupDataName.delete();
3631            mNewStateName.delete();
3632            clearAgentState();
3633        }
3634
3635        // Cleanup common to both success and failure cases
3636        void clearAgentState() {
3637            try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
3638            try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
3639            try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
3640            synchronized (mCurrentOpLock) {
3641                // Current-operation callback handling requires the validity of these various
3642                // bits of internal state as an invariant of the operation still being live.
3643                // This means we make sure to clear all of the state in unison inside the lock.
3644                mCurrentOperations.remove(mEphemeralOpToken);
3645                mSavedState = mBackupData = mNewState = null;
3646            }
3647
3648            // If this was a pseudopackage there's no associated Activity Manager state
3649            if (mCurrentPackage.applicationInfo != null) {
3650                addBackupTrace("unbinding " + mCurrentPackage.packageName);
3651                try {  // unbind even on timeout, just in case
3652                    mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
3653                } catch (RemoteException e) { /* can't happen; activity manager is local */ }
3654            }
3655        }
3656
3657        void executeNextState(BackupState nextState) {
3658            if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
3659                    + this + " nextState=" + nextState);
3660            addBackupTrace("executeNextState => " + nextState);
3661            mCurrentState = nextState;
3662            Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
3663            mBackupHandler.sendMessage(msg);
3664        }
3665    }
3666
3667    private boolean isBackupOperationInProgress() {
3668        synchronized (mCurrentOpLock) {
3669            for (int i = 0; i < mCurrentOperations.size(); i++) {
3670                Operation op = mCurrentOperations.valueAt(i);
3671                if (op.type == OP_TYPE_BACKUP && op.state == OP_PENDING) {
3672                    return true;
3673                }
3674            }
3675        }
3676        return false;
3677    }
3678
3679
3680    // ----- Full backup/restore to a file/socket -----
3681
3682    class FullBackupObbConnection implements ServiceConnection {
3683        volatile IObbBackupService mService;
3684
3685        FullBackupObbConnection() {
3686            mService = null;
3687        }
3688
3689        public void establish() {
3690            if (MORE_DEBUG) Slog.i(TAG, "Initiating bind of OBB service on " + this);
3691            Intent obbIntent = new Intent().setComponent(new ComponentName(
3692                    "com.android.sharedstoragebackup",
3693                    "com.android.sharedstoragebackup.ObbBackupService"));
3694            BackupManagerService.this.mContext.bindServiceAsUser(
3695                    obbIntent, this, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM);
3696        }
3697
3698        public void tearDown() {
3699            BackupManagerService.this.mContext.unbindService(this);
3700        }
3701
3702        public boolean backupObbs(PackageInfo pkg, OutputStream out) {
3703            boolean success = false;
3704            waitForConnection();
3705
3706            ParcelFileDescriptor[] pipes = null;
3707            try {
3708                pipes = ParcelFileDescriptor.createPipe();
3709                int token = generateRandomIntegerToken();
3710                prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL,
3711                        null, OP_TYPE_BACKUP_WAIT);
3712                mService.backupObbs(pkg.packageName, pipes[1], token, mBackupManagerBinder);
3713                routeSocketDataToOutput(pipes[0], out);
3714                success = waitUntilOperationComplete(token);
3715            } catch (Exception e) {
3716                Slog.w(TAG, "Unable to back up OBBs for " + pkg, e);
3717            } finally {
3718                try {
3719                    out.flush();
3720                    if (pipes != null) {
3721                        if (pipes[0] != null) pipes[0].close();
3722                        if (pipes[1] != null) pipes[1].close();
3723                    }
3724                } catch (IOException e) {
3725                    Slog.w(TAG, "I/O error closing down OBB backup", e);
3726                }
3727            }
3728            return success;
3729        }
3730
3731        public void restoreObbFile(String pkgName, ParcelFileDescriptor data,
3732                long fileSize, int type, String path, long mode, long mtime,
3733                int token, IBackupManager callbackBinder) {
3734            waitForConnection();
3735
3736            try {
3737                mService.restoreObbFile(pkgName, data, fileSize, type, path, mode, mtime,
3738                        token, callbackBinder);
3739            } catch (Exception e) {
3740                Slog.w(TAG, "Unable to restore OBBs for " + pkgName, e);
3741            }
3742        }
3743
3744        private void waitForConnection() {
3745            synchronized (this) {
3746                while (mService == null) {
3747                    if (MORE_DEBUG) Slog.i(TAG, "...waiting for OBB service binding...");
3748                    try {
3749                        this.wait();
3750                    } catch (InterruptedException e) { /* never interrupted */ }
3751                }
3752                if (MORE_DEBUG) Slog.i(TAG, "Connected to OBB service; continuing");
3753            }
3754        }
3755
3756        @Override
3757        public void onServiceConnected(ComponentName name, IBinder service) {
3758            synchronized (this) {
3759                mService = IObbBackupService.Stub.asInterface(service);
3760                if (MORE_DEBUG) Slog.i(TAG, "OBB service connection " + mService
3761                        + " connected on " + this);
3762                this.notifyAll();
3763            }
3764        }
3765
3766        @Override
3767        public void onServiceDisconnected(ComponentName name) {
3768            synchronized (this) {
3769                mService = null;
3770                if (MORE_DEBUG) Slog.i(TAG, "OBB service connection disconnected on " + this);
3771                this.notifyAll();
3772            }
3773        }
3774
3775    }
3776
3777    static void routeSocketDataToOutput(ParcelFileDescriptor inPipe, OutputStream out)
3778            throws IOException {
3779        // We do not take close() responsibility for the pipe FD
3780        FileInputStream raw = new FileInputStream(inPipe.getFileDescriptor());
3781        DataInputStream in = new DataInputStream(raw);
3782
3783        byte[] buffer = new byte[32 * 1024];
3784        int chunkTotal;
3785        while ((chunkTotal = in.readInt()) > 0) {
3786            while (chunkTotal > 0) {
3787                int toRead = (chunkTotal > buffer.length) ? buffer.length : chunkTotal;
3788                int nRead = in.read(buffer, 0, toRead);
3789                out.write(buffer, 0, nRead);
3790                chunkTotal -= nRead;
3791            }
3792        }
3793    }
3794
3795    @Override
3796    public void tearDownAgentAndKill(ApplicationInfo app) {
3797        if (app == null) {
3798            // Null means the system package, so just quietly move on.  :)
3799            return;
3800        }
3801
3802        try {
3803            // unbind and tidy up even on timeout or failure, just in case
3804            mActivityManager.unbindBackupAgent(app);
3805
3806            // The agent was running with a stub Application object, so shut it down.
3807            // !!! We hardcode the confirmation UI's package name here rather than use a
3808            //     manifest flag!  TODO something less direct.
3809            if (app.uid >= Process.FIRST_APPLICATION_UID
3810                    && !app.packageName.equals("com.android.backupconfirm")) {
3811                if (MORE_DEBUG) Slog.d(TAG, "Killing agent host process");
3812                mActivityManager.killApplicationProcess(app.processName, app.uid);
3813            } else {
3814                if (MORE_DEBUG) Slog.d(TAG, "Not killing after operation: " + app.processName);
3815            }
3816        } catch (RemoteException e) {
3817            Slog.d(TAG, "Lost app trying to shut down");
3818        }
3819    }
3820
3821    // Core logic for performing one package's full backup, gathering the tarball from the
3822    // application and emitting it to the designated OutputStream.
3823
3824    // Callout from the engine to an interested participant that might need to communicate
3825    // with the agent prior to asking it to move data
3826    interface FullBackupPreflight {
3827        /**
3828         * Perform the preflight operation necessary for the given package.
3829         * @param pkg The name of the package being proposed for full-data backup
3830         * @param agent Live BackupAgent binding to the target app's agent
3831         * @return BackupTransport.TRANSPORT_OK to proceed with the backup operation,
3832         *         or one of the other BackupTransport.* error codes as appropriate
3833         */
3834        int preflightFullBackup(PackageInfo pkg, IBackupAgent agent);
3835
3836        long getExpectedSizeOrErrorCode();
3837    };
3838
3839    class FullBackupEngine {
3840        OutputStream mOutput;
3841        FullBackupPreflight mPreflightHook;
3842        BackupRestoreTask mTimeoutMonitor;
3843        IBackupAgent mAgent;
3844        File mFilesDir;
3845        File mManifestFile;
3846        File mMetadataFile;
3847        boolean mIncludeApks;
3848        PackageInfo mPkg;
3849        private final long mQuota;
3850        private final int mOpToken;
3851
3852        class FullBackupRunner implements Runnable {
3853            PackageInfo mPackage;
3854            byte[] mWidgetData;
3855            IBackupAgent mAgent;
3856            ParcelFileDescriptor mPipe;
3857            int mToken;
3858            boolean mSendApk;
3859            boolean mWriteManifest;
3860
3861            FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
3862                             int token, boolean sendApk, boolean writeManifest, byte[] widgetData)
3863                    throws IOException {
3864                mPackage = pack;
3865                mWidgetData = widgetData;
3866                mAgent = agent;
3867                mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
3868                mToken = token;
3869                mSendApk = sendApk;
3870                mWriteManifest = writeManifest;
3871            }
3872
3873            @Override
3874            public void run() {
3875                try {
3876                    FullBackupDataOutput output = new FullBackupDataOutput(mPipe);
3877
3878                    if (mWriteManifest) {
3879                        final boolean writeWidgetData = mWidgetData != null;
3880                        if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
3881                        writeAppManifest(mPackage, mPackageManager, mManifestFile, mSendApk, writeWidgetData);
3882                        FullBackup.backupToTar(mPackage.packageName, null, null,
3883                                mFilesDir.getAbsolutePath(),
3884                                mManifestFile.getAbsolutePath(),
3885                                output);
3886                        mManifestFile.delete();
3887
3888                        // We only need to write a metadata file if we have widget data to stash
3889                        if (writeWidgetData) {
3890                            writeMetadata(mPackage, mMetadataFile, mWidgetData);
3891                            FullBackup.backupToTar(mPackage.packageName, null, null,
3892                                    mFilesDir.getAbsolutePath(),
3893                                    mMetadataFile.getAbsolutePath(),
3894                                    output);
3895                            mMetadataFile.delete();
3896                        }
3897                    }
3898
3899                    if (mSendApk) {
3900                        writeApkToBackup(mPackage, output);
3901                    }
3902
3903                    final boolean isSharedStorage =
3904                            mPackage.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
3905                    final long timeout = isSharedStorage ?
3906                            TIMEOUT_SHARED_BACKUP_INTERVAL : TIMEOUT_FULL_BACKUP_INTERVAL;
3907
3908                    if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
3909                    prepareOperationTimeout(mToken, timeout, mTimeoutMonitor /* in parent class */,
3910                            OP_TYPE_BACKUP_WAIT);
3911                    mAgent.doFullBackup(mPipe, mQuota, mToken, mBackupManagerBinder);
3912                } catch (IOException e) {
3913                    Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
3914                } catch (RemoteException e) {
3915                    Slog.e(TAG, "Remote agent vanished during full backup of "
3916                            + mPackage.packageName);
3917                } finally {
3918                    try {
3919                        mPipe.close();
3920                    } catch (IOException e) {}
3921                }
3922            }
3923        }
3924
3925        FullBackupEngine(OutputStream output, FullBackupPreflight preflightHook, PackageInfo pkg,
3926                         boolean alsoApks, BackupRestoreTask timeoutMonitor, long quota, int opToken) {
3927            mOutput = output;
3928            mPreflightHook = preflightHook;
3929            mPkg = pkg;
3930            mIncludeApks = alsoApks;
3931            mTimeoutMonitor = timeoutMonitor;
3932            mFilesDir = new File("/data/system");
3933            mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
3934            mMetadataFile = new File(mFilesDir, BACKUP_METADATA_FILENAME);
3935            mQuota = quota;
3936            mOpToken = opToken;
3937        }
3938
3939        public int preflightCheck() throws RemoteException {
3940            if (mPreflightHook == null) {
3941                if (MORE_DEBUG) {
3942                    Slog.v(TAG, "No preflight check");
3943                }
3944                return BackupTransport.TRANSPORT_OK;
3945            }
3946            if (initializeAgent()) {
3947                int result = mPreflightHook.preflightFullBackup(mPkg, mAgent);
3948                if (MORE_DEBUG) {
3949                    Slog.v(TAG, "preflight returned " + result);
3950                }
3951                return result;
3952            } else {
3953                Slog.w(TAG, "Unable to bind to full agent for " + mPkg.packageName);
3954                return BackupTransport.AGENT_ERROR;
3955            }
3956        }
3957
3958        public int backupOnePackage() throws RemoteException {
3959            int result = BackupTransport.AGENT_ERROR;
3960
3961            if (initializeAgent()) {
3962                ParcelFileDescriptor[] pipes = null;
3963                try {
3964                    pipes = ParcelFileDescriptor.createPipe();
3965
3966                    ApplicationInfo app = mPkg.applicationInfo;
3967                    final boolean isSharedStorage =
3968                            mPkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
3969                    final boolean sendApk = mIncludeApks
3970                            && !isSharedStorage
3971                            && ((app.privateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) == 0)
3972                            && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
3973                            (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
3974
3975                    // TODO: http://b/22388012
3976                    byte[] widgetBlob = AppWidgetBackupBridge.getWidgetState(mPkg.packageName,
3977                            UserHandle.USER_SYSTEM);
3978
3979                    FullBackupRunner runner = new FullBackupRunner(mPkg, mAgent, pipes[1],
3980                            mOpToken, sendApk, !isSharedStorage, widgetBlob);
3981                    pipes[1].close();   // the runner has dup'd it
3982                    pipes[1] = null;
3983                    Thread t = new Thread(runner, "app-data-runner");
3984                    t.start();
3985
3986                    // Now pull data from the app and stuff it into the output
3987                    routeSocketDataToOutput(pipes[0], mOutput);
3988
3989                    if (!waitUntilOperationComplete(mOpToken)) {
3990                        Slog.e(TAG, "Full backup failed on package " + mPkg.packageName);
3991                    } else {
3992                        if (MORE_DEBUG) {
3993                            Slog.d(TAG, "Full package backup success: " + mPkg.packageName);
3994                        }
3995                        result = BackupTransport.TRANSPORT_OK;
3996                    }
3997                } catch (IOException e) {
3998                    Slog.e(TAG, "Error backing up " + mPkg.packageName + ": " + e.getMessage());
3999                    result = BackupTransport.AGENT_ERROR;
4000                } finally {
4001                    try {
4002                        // flush after every package
4003                        mOutput.flush();
4004                        if (pipes != null) {
4005                            if (pipes[0] != null) pipes[0].close();
4006                            if (pipes[1] != null) pipes[1].close();
4007                        }
4008                    } catch (IOException e) {
4009                        Slog.w(TAG, "Error bringing down backup stack");
4010                        result = BackupTransport.TRANSPORT_ERROR;
4011                    }
4012                }
4013            } else {
4014                Slog.w(TAG, "Unable to bind to full agent for " + mPkg.packageName);
4015            }
4016            tearDown();
4017            return result;
4018        }
4019
4020        public void sendQuotaExceeded(final long backupDataBytes, final long quotaBytes) {
4021            if (initializeAgent()) {
4022                try {
4023                    mAgent.doQuotaExceeded(backupDataBytes, quotaBytes);
4024                } catch (RemoteException e) {
4025                    Slog.e(TAG, "Remote exception while telling agent about quota exceeded");
4026                }
4027            }
4028        }
4029
4030        private boolean initializeAgent() {
4031            if (mAgent == null) {
4032                if (MORE_DEBUG) {
4033                    Slog.d(TAG, "Binding to full backup agent : " + mPkg.packageName);
4034                }
4035                mAgent = bindToAgentSynchronous(mPkg.applicationInfo,
4036                        ApplicationThreadConstants.BACKUP_MODE_FULL);
4037            }
4038            return mAgent != null;
4039        }
4040
4041        private void writeApkToBackup(PackageInfo pkg, FullBackupDataOutput output) {
4042            // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
4043            // TODO: handle backing up split APKs
4044            final String appSourceDir = pkg.applicationInfo.getBaseCodePath();
4045            final String apkDir = new File(appSourceDir).getParent();
4046            FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
4047                    apkDir, appSourceDir, output);
4048
4049            // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM
4050            // doesn't have access to external storage.
4051
4052            // Save associated .obb content if it exists and we did save the apk
4053            // check for .obb and save those too
4054            // TODO: http://b/22388012
4055            final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_SYSTEM);
4056            final File obbDir = userEnv.buildExternalStorageAppObbDirs(pkg.packageName)[0];
4057            if (obbDir != null) {
4058                if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
4059                File[] obbFiles = obbDir.listFiles();
4060                if (obbFiles != null) {
4061                    final String obbDirName = obbDir.getAbsolutePath();
4062                    for (File obb : obbFiles) {
4063                        FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
4064                                obbDirName, obb.getAbsolutePath(), output);
4065                    }
4066                }
4067            }
4068        }
4069
4070        // Widget metadata format. All header entries are strings ending in LF:
4071        //
4072        // Version 1 header:
4073        //     BACKUP_METADATA_VERSION, currently "1"
4074        //     package name
4075        //
4076        // File data (all integers are binary in network byte order)
4077        // *N: 4 : integer token identifying which metadata blob
4078        //     4 : integer size of this blob = N
4079        //     N : raw bytes of this metadata blob
4080        //
4081        // Currently understood blobs (always in network byte order):
4082        //
4083        //     widgets : metadata token = 0x01FFED01 (BACKUP_WIDGET_METADATA_TOKEN)
4084        //
4085        // Unrecognized blobs are *ignored*, not errors.
4086        private void writeMetadata(PackageInfo pkg, File destination, byte[] widgetData)
4087                throws IOException {
4088            StringBuilder b = new StringBuilder(512);
4089            StringBuilderPrinter printer = new StringBuilderPrinter(b);
4090            printer.println(Integer.toString(BACKUP_METADATA_VERSION));
4091            printer.println(pkg.packageName);
4092
4093            FileOutputStream fout = new FileOutputStream(destination);
4094            BufferedOutputStream bout = new BufferedOutputStream(fout);
4095            DataOutputStream out = new DataOutputStream(bout);
4096            bout.write(b.toString().getBytes());    // bypassing DataOutputStream
4097
4098            if (widgetData != null && widgetData.length > 0) {
4099                out.writeInt(BACKUP_WIDGET_METADATA_TOKEN);
4100                out.writeInt(widgetData.length);
4101                out.write(widgetData);
4102            }
4103            bout.flush();
4104            out.close();
4105
4106            // As with the manifest file, guarantee idempotence of the archive metadata
4107            // for the widget block by using a fixed mtime on the transient file.
4108            destination.setLastModified(0);
4109        }
4110
4111        private void tearDown() {
4112            if (mPkg != null) {
4113                tearDownAgentAndKill(mPkg.applicationInfo);
4114            }
4115        }
4116    }
4117
4118    static void writeAppManifest(PackageInfo pkg, PackageManager packageManager, File manifestFile,
4119            boolean withApk, boolean withWidgets) throws IOException {
4120        // Manifest format. All data are strings ending in LF:
4121        //     BACKUP_MANIFEST_VERSION, currently 1
4122        //
4123        // Version 1:
4124        //     package name
4125        //     package's versionCode
4126        //     platform versionCode
4127        //     getInstallerPackageName() for this package (maybe empty)
4128        //     boolean: "1" if archive includes .apk; any other string means not
4129        //     number of signatures == N
4130        // N*:    signature byte array in ascii format per Signature.toCharsString()
4131        StringBuilder builder = new StringBuilder(4096);
4132        StringBuilderPrinter printer = new StringBuilderPrinter(builder);
4133
4134        printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
4135        printer.println(pkg.packageName);
4136        printer.println(Integer.toString(pkg.versionCode));
4137        printer.println(Integer.toString(Build.VERSION.SDK_INT));
4138
4139        String installerName = packageManager.getInstallerPackageName(pkg.packageName);
4140        printer.println((installerName != null) ? installerName : "");
4141
4142        printer.println(withApk ? "1" : "0");
4143        if (pkg.signatures == null) {
4144            printer.println("0");
4145        } else {
4146            printer.println(Integer.toString(pkg.signatures.length));
4147            for (Signature sig : pkg.signatures) {
4148                printer.println(sig.toCharsString());
4149            }
4150        }
4151
4152        FileOutputStream outstream = new FileOutputStream(manifestFile);
4153        outstream.write(builder.toString().getBytes());
4154        outstream.close();
4155
4156        // We want the manifest block in the archive stream to be idempotent:
4157        // each time we generate a backup stream for the app, we want the manifest
4158        // block to be identical.  The underlying tar mechanism sees it as a file,
4159        // though, and will propagate its mtime, causing the tar header to vary.
4160        // Avoid this problem by pinning the mtime to zero.
4161        manifestFile.setLastModified(0);
4162    }
4163
4164    // Generic driver skeleton for full backup operations
4165    abstract class FullBackupTask implements Runnable {
4166        IFullBackupRestoreObserver mObserver;
4167
4168        FullBackupTask(IFullBackupRestoreObserver observer) {
4169            mObserver = observer;
4170        }
4171
4172        // wrappers for observer use
4173        final void sendStartBackup() {
4174            if (mObserver != null) {
4175                try {
4176                    mObserver.onStartBackup();
4177                } catch (RemoteException e) {
4178                    Slog.w(TAG, "full backup observer went away: startBackup");
4179                    mObserver = null;
4180                }
4181            }
4182        }
4183
4184        final void sendOnBackupPackage(String name) {
4185            if (mObserver != null) {
4186                try {
4187                    // TODO: use a more user-friendly name string
4188                    mObserver.onBackupPackage(name);
4189                } catch (RemoteException e) {
4190                    Slog.w(TAG, "full backup observer went away: backupPackage");
4191                    mObserver = null;
4192                }
4193            }
4194        }
4195
4196        final void sendEndBackup() {
4197            if (mObserver != null) {
4198                try {
4199                    mObserver.onEndBackup();
4200                } catch (RemoteException e) {
4201                    Slog.w(TAG, "full backup observer went away: endBackup");
4202                    mObserver = null;
4203                }
4204            }
4205        }
4206    }
4207
4208    boolean deviceIsEncrypted() {
4209        try {
4210            return mStorageManager.getEncryptionState()
4211                     != StorageManager.ENCRYPTION_STATE_NONE
4212                && mStorageManager.getPasswordType()
4213                     != StorageManager.CRYPT_TYPE_DEFAULT;
4214        } catch (Exception e) {
4215            // If we can't talk to the storagemanager service we have a serious problem; fail
4216            // "secure" i.e. assuming that the device is encrypted.
4217            Slog.e(TAG, "Unable to communicate with storagemanager service: " + e.getMessage());
4218            return true;
4219        }
4220    }
4221
4222    // Full backup task variant used for adb backup
4223    class PerformAdbBackupTask extends FullBackupTask implements BackupRestoreTask {
4224        FullBackupEngine mBackupEngine;
4225        final AtomicBoolean mLatch;
4226
4227        ParcelFileDescriptor mOutputFile;
4228        DeflaterOutputStream mDeflater;
4229        boolean mIncludeApks;
4230        boolean mIncludeObbs;
4231        boolean mIncludeShared;
4232        boolean mDoWidgets;
4233        boolean mAllApps;
4234        boolean mIncludeSystem;
4235        boolean mCompress;
4236        boolean mKeyValue;
4237        ArrayList<String> mPackages;
4238        PackageInfo mCurrentTarget;
4239        String mCurrentPassword;
4240        String mEncryptPassword;
4241        private final int mCurrentOpToken;
4242
4243        PerformAdbBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
4244                boolean includeApks, boolean includeObbs, boolean includeShared, boolean doWidgets,
4245                String curPassword, String encryptPassword, boolean doAllApps, boolean doSystem,
4246                boolean doCompress, boolean doKeyValue, String[] packages, AtomicBoolean latch) {
4247            super(observer);
4248            mCurrentOpToken = generateRandomIntegerToken();
4249            mLatch = latch;
4250
4251            mOutputFile = fd;
4252            mIncludeApks = includeApks;
4253            mIncludeObbs = includeObbs;
4254            mIncludeShared = includeShared;
4255            mDoWidgets = doWidgets;
4256            mAllApps = doAllApps;
4257            mIncludeSystem = doSystem;
4258            mPackages = (packages == null)
4259                    ? new ArrayList<String>()
4260                    : new ArrayList<String>(Arrays.asList(packages));
4261            mCurrentPassword = curPassword;
4262            // when backing up, if there is a current backup password, we require that
4263            // the user use a nonempty encryption password as well.  if one is supplied
4264            // in the UI we use that, but if the UI was left empty we fall back to the
4265            // current backup password (which was supplied by the user as well).
4266            if (encryptPassword == null || "".equals(encryptPassword)) {
4267                mEncryptPassword = curPassword;
4268            } else {
4269                mEncryptPassword = encryptPassword;
4270            }
4271            if (MORE_DEBUG) {
4272                Slog.w(TAG, "Encrypting backup with passphrase=" + mEncryptPassword);
4273            }
4274            mCompress = doCompress;
4275            mKeyValue = doKeyValue;
4276        }
4277
4278        void addPackagesToSet(TreeMap<String, PackageInfo> set, List<String> pkgNames) {
4279            for (String pkgName : pkgNames) {
4280                if (!set.containsKey(pkgName)) {
4281                    try {
4282                        PackageInfo info = mPackageManager.getPackageInfo(pkgName,
4283                                PackageManager.GET_SIGNATURES);
4284                        set.put(pkgName, info);
4285                    } catch (NameNotFoundException e) {
4286                        Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
4287                    }
4288                }
4289            }
4290        }
4291
4292        private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
4293                OutputStream ofstream) throws Exception {
4294            // User key will be used to encrypt the master key.
4295            byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
4296            SecretKey userKey = buildPasswordKey(PBKDF_CURRENT, mEncryptPassword, newUserSalt,
4297                    PBKDF2_HASH_ROUNDS);
4298
4299            // the master key is random for each backup
4300            byte[] masterPw = new byte[256 / 8];
4301            mRng.nextBytes(masterPw);
4302            byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
4303
4304            // primary encryption of the datastream with the random key
4305            Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
4306            SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
4307            c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
4308            OutputStream finalOutput = new CipherOutputStream(ofstream, c);
4309
4310            // line 4: name of encryption algorithm
4311            headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
4312            headerbuf.append('\n');
4313            // line 5: user password salt [hex]
4314            headerbuf.append(byteArrayToHex(newUserSalt));
4315            headerbuf.append('\n');
4316            // line 6: master key checksum salt [hex]
4317            headerbuf.append(byteArrayToHex(checksumSalt));
4318            headerbuf.append('\n');
4319            // line 7: number of PBKDF2 rounds used [decimal]
4320            headerbuf.append(PBKDF2_HASH_ROUNDS);
4321            headerbuf.append('\n');
4322
4323            // line 8: IV of the user key [hex]
4324            Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
4325            mkC.init(Cipher.ENCRYPT_MODE, userKey);
4326
4327            byte[] IV = mkC.getIV();
4328            headerbuf.append(byteArrayToHex(IV));
4329            headerbuf.append('\n');
4330
4331            // line 9: master IV + key blob, encrypted by the user key [hex].  Blob format:
4332            //    [byte] IV length = Niv
4333            //    [array of Niv bytes] IV itself
4334            //    [byte] master key length = Nmk
4335            //    [array of Nmk bytes] master key itself
4336            //    [byte] MK checksum hash length = Nck
4337            //    [array of Nck bytes] master key checksum hash
4338            //
4339            // The checksum is the (master key + checksum salt), run through the
4340            // stated number of PBKDF2 rounds
4341            IV = c.getIV();
4342            byte[] mk = masterKeySpec.getEncoded();
4343            byte[] checksum = makeKeyChecksum(PBKDF_CURRENT, masterKeySpec.getEncoded(),
4344                    checksumSalt, PBKDF2_HASH_ROUNDS);
4345
4346            ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
4347                    + checksum.length + 3);
4348            DataOutputStream mkOut = new DataOutputStream(blob);
4349            mkOut.writeByte(IV.length);
4350            mkOut.write(IV);
4351            mkOut.writeByte(mk.length);
4352            mkOut.write(mk);
4353            mkOut.writeByte(checksum.length);
4354            mkOut.write(checksum);
4355            mkOut.flush();
4356            byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
4357            headerbuf.append(byteArrayToHex(encryptedMk));
4358            headerbuf.append('\n');
4359
4360            return finalOutput;
4361        }
4362
4363        private void finalizeBackup(OutputStream out) {
4364            try {
4365                // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
4366                byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
4367                out.write(eof);
4368            } catch (IOException e) {
4369                Slog.w(TAG, "Error attempting to finalize backup stream");
4370            }
4371        }
4372
4373        @Override
4374        public void run() {
4375            String includeKeyValue = mKeyValue ? ", including key-value backups" : "";
4376            Slog.i(TAG, "--- Performing adb backup" + includeKeyValue + " ---");
4377
4378            TreeMap<String, PackageInfo> packagesToBackup = new TreeMap<String, PackageInfo>();
4379            FullBackupObbConnection obbConnection = new FullBackupObbConnection();
4380            obbConnection.establish();  // we'll want this later
4381
4382            sendStartBackup();
4383
4384            // doAllApps supersedes the package set if any
4385            if (mAllApps) {
4386                List<PackageInfo> allPackages = mPackageManager.getInstalledPackages(
4387                        PackageManager.GET_SIGNATURES);
4388                for (int i = 0; i < allPackages.size(); i++) {
4389                    PackageInfo pkg = allPackages.get(i);
4390                    // Exclude system apps if we've been asked to do so
4391                    if (mIncludeSystem == true
4392                            || ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)) {
4393                        packagesToBackup.put(pkg.packageName, pkg);
4394                    }
4395                }
4396            }
4397
4398            // If we're doing widget state as well, ensure that we have all the involved
4399            // host & provider packages in the set
4400            if (mDoWidgets) {
4401                // TODO: http://b/22388012
4402                List<String> pkgs =
4403                        AppWidgetBackupBridge.getWidgetParticipants(UserHandle.USER_SYSTEM);
4404                if (pkgs != null) {
4405                    if (MORE_DEBUG) {
4406                        Slog.i(TAG, "Adding widget participants to backup set:");
4407                        StringBuilder sb = new StringBuilder(128);
4408                        sb.append("   ");
4409                        for (String s : pkgs) {
4410                            sb.append(' ');
4411                            sb.append(s);
4412                        }
4413                        Slog.i(TAG, sb.toString());
4414                    }
4415                    addPackagesToSet(packagesToBackup, pkgs);
4416                }
4417            }
4418
4419            // Now process the command line argument packages, if any. Note that explicitly-
4420            // named system-partition packages will be included even if includeSystem was
4421            // set to false.
4422            if (mPackages != null) {
4423                addPackagesToSet(packagesToBackup, mPackages);
4424            }
4425
4426            // Now we cull any inapplicable / inappropriate packages from the set.  This
4427            // includes the special shared-storage agent package; we handle that one
4428            // explicitly at the end of the backup pass. Packages supporting key-value backup are
4429            // added to their own queue, and handled after packages supporting fullbackup.
4430            ArrayList<PackageInfo> keyValueBackupQueue = new ArrayList<>();
4431            Iterator<Entry<String, PackageInfo>> iter = packagesToBackup.entrySet().iterator();
4432            while (iter.hasNext()) {
4433                PackageInfo pkg = iter.next().getValue();
4434                if (!appIsEligibleForBackup(pkg.applicationInfo, mPackageManager)
4435                        || appIsStopped(pkg.applicationInfo)) {
4436                    iter.remove();
4437                    if (DEBUG) {
4438                        Slog.i(TAG, "Package " + pkg.packageName
4439                                + " is not eligible for backup, removing.");
4440                    }
4441                } else if (appIsKeyValueOnly(pkg)) {
4442                    iter.remove();
4443                    if (DEBUG) {
4444                        Slog.i(TAG, "Package " + pkg.packageName
4445                                + " is key-value.");
4446                    }
4447                    keyValueBackupQueue.add(pkg);
4448                }
4449            }
4450
4451            // flatten the set of packages now so we can explicitly control the ordering
4452            ArrayList<PackageInfo> backupQueue =
4453                    new ArrayList<PackageInfo>(packagesToBackup.values());
4454            FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
4455            OutputStream out = null;
4456
4457            PackageInfo pkg = null;
4458            try {
4459                boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
4460
4461                // Only allow encrypted backups of encrypted devices
4462                if (deviceIsEncrypted() && !encrypting) {
4463                    Slog.e(TAG, "Unencrypted backup of encrypted device; aborting");
4464                    return;
4465                }
4466
4467                OutputStream finalOutput = ofstream;
4468
4469                // Verify that the given password matches the currently-active
4470                // backup password, if any
4471                if (!backupPasswordMatches(mCurrentPassword)) {
4472                    if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
4473                    return;
4474                }
4475
4476                // Write the global file header.  All strings are UTF-8 encoded; lines end
4477                // with a '\n' byte.  Actual backup data begins immediately following the
4478                // final '\n'.
4479                //
4480                // line 1: "ANDROID BACKUP"
4481                // line 2: backup file format version, currently "5"
4482                // line 3: compressed?  "0" if not compressed, "1" if compressed.
4483                // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
4484                //
4485                // When line 4 is not "none", then additional header data follows:
4486                //
4487                // line 5: user password salt [hex]
4488                // line 6: master key checksum salt [hex]
4489                // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
4490                // line 8: IV of the user key [hex]
4491                // line 9: master key blob [hex]
4492                //     IV of the master key, master key itself, master key checksum hash
4493                //
4494                // The master key checksum is the master key plus its checksum salt, run through
4495                // 10k rounds of PBKDF2.  This is used to verify that the user has supplied the
4496                // correct password for decrypting the archive:  the master key decrypted from
4497                // the archive using the user-supplied password is also run through PBKDF2 in
4498                // this way, and if the result does not match the checksum as stored in the
4499                // archive, then we know that the user-supplied password does not match the
4500                // archive's.
4501                StringBuilder headerbuf = new StringBuilder(1024);
4502
4503                headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
4504                headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
4505                headerbuf.append(mCompress ? "\n1\n" : "\n0\n");
4506
4507                try {
4508                    // Set up the encryption stage if appropriate, and emit the correct header
4509                    if (encrypting) {
4510                        finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
4511                    } else {
4512                        headerbuf.append("none\n");
4513                    }
4514
4515                    byte[] header = headerbuf.toString().getBytes("UTF-8");
4516                    ofstream.write(header);
4517
4518                    // Set up the compression stage feeding into the encryption stage (if any)
4519                    if (mCompress) {
4520                        Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
4521                        finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
4522                    }
4523
4524                    out = finalOutput;
4525                } catch (Exception e) {
4526                    // Should never happen!
4527                    Slog.e(TAG, "Unable to emit archive header", e);
4528                    return;
4529                }
4530
4531                // Shared storage if requested
4532                if (mIncludeShared) {
4533                    try {
4534                        pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
4535                        backupQueue.add(pkg);
4536                    } catch (NameNotFoundException e) {
4537                        Slog.e(TAG, "Unable to find shared-storage backup handler");
4538                    }
4539                }
4540
4541                // Now actually run the constructed backup sequence for full backup
4542                int N = backupQueue.size();
4543                for (int i = 0; i < N; i++) {
4544                    pkg = backupQueue.get(i);
4545                    if (DEBUG) {
4546                        Slog.i(TAG,"--- Performing full backup for package " + pkg.packageName
4547                                + " ---");
4548                    }
4549                    final boolean isSharedStorage =
4550                            pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
4551
4552                    mBackupEngine = new FullBackupEngine(out, null, pkg, mIncludeApks, this, Long.MAX_VALUE, mCurrentOpToken);
4553                    sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
4554
4555                    // Don't need to check preflight result as there is no preflight hook.
4556                    mCurrentTarget = pkg;
4557                    mBackupEngine.backupOnePackage();
4558
4559                    // after the app's agent runs to handle its private filesystem
4560                    // contents, back up any OBB content it has on its behalf.
4561                    if (mIncludeObbs) {
4562                        boolean obbOkay = obbConnection.backupObbs(pkg, out);
4563                        if (!obbOkay) {
4564                            throw new RuntimeException("Failure writing OBB stack for " + pkg);
4565                        }
4566                    }
4567                }
4568                // And for key-value backup if enabled
4569                if (mKeyValue) {
4570                    for (PackageInfo keyValuePackage : keyValueBackupQueue) {
4571                        if (DEBUG) {
4572                            Slog.i(TAG, "--- Performing key-value backup for package "
4573                                    + keyValuePackage.packageName + " ---");
4574                        }
4575                        KeyValueAdbBackupEngine kvBackupEngine =
4576                                new KeyValueAdbBackupEngine(out, keyValuePackage,
4577                                        BackupManagerService.this,
4578                                        mPackageManager, mBaseStateDir, mDataDir);
4579                        sendOnBackupPackage(keyValuePackage.packageName);
4580                        kvBackupEngine.backupOnePackage();
4581                    }
4582                }
4583
4584                // Done!
4585                finalizeBackup(out);
4586            } catch (RemoteException e) {
4587                Slog.e(TAG, "App died during full backup");
4588            } catch (Exception e) {
4589                Slog.e(TAG, "Internal exception during full backup", e);
4590            } finally {
4591                try {
4592                    if (out != null) {
4593                        out.flush();
4594                        out.close();
4595                    }
4596                    mOutputFile.close();
4597                } catch (IOException e) {
4598                    /* nothing we can do about this */
4599                }
4600                synchronized (mLatch) {
4601                    mLatch.set(true);
4602                    mLatch.notifyAll();
4603                }
4604                sendEndBackup();
4605                obbConnection.tearDown();
4606                if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
4607                mWakelock.release();
4608            }
4609        }
4610
4611        // BackupRestoreTask methods, used for timeout handling
4612        @Override
4613        public void execute() {
4614            // Unused
4615        }
4616
4617        @Override
4618        public void operationComplete(long result) {
4619            // Unused
4620        }
4621
4622        @Override
4623        public void handleCancel(boolean cancelAll) {
4624            final PackageInfo target = mCurrentTarget;
4625            if (DEBUG) {
4626                Slog.w(TAG, "adb backup cancel of " + target);
4627            }
4628            if (target != null) {
4629                tearDownAgentAndKill(mCurrentTarget.applicationInfo);
4630            }
4631            removeOperation(mCurrentOpToken);
4632        }
4633    }
4634
4635    /**
4636     * Full backup task extension used for transport-oriented operation.
4637     *
4638     * Flow:
4639     * For each requested package:
4640     *     - Spin off a new SinglePackageBackupRunner (mBackupRunner) for the current package.
4641     *     - Wait until preflight is complete. (mBackupRunner.getPreflightResultBlocking())
4642     *     - If preflight data size is within limit, start reading data from agent pipe and writing
4643     *       to transport pipe. While there is data to send, call transport.sendBackupData(int) to
4644     *       tell the transport how many bytes to expect on its pipe.
4645     *     - After sending all data, call transport.finishBackup() if things went well. And
4646     *       transport.cancelFullBackup() otherwise.
4647     *
4648     * Interactions with mCurrentOperations:
4649     *     - An entry for this object is added to mCurrentOperations for the entire lifetime of this
4650     *       object. Used to cancel the operation.
4651     *     - SinglePackageBackupRunner and SinglePackageBackupPreflight will put ephemeral entries
4652     *       to get timeouts or operation complete callbacks.
4653     *
4654     * Handling cancels:
4655     *     - The contract we provide is that the task won't interact with the transport after
4656     *       handleCancel() is done executing.
4657     *     - This task blocks at 3 points: 1. Preflight result check 2. Reading on agent side pipe
4658     *       and 3. Get backup result from mBackupRunner.
4659     *     - Bubbling up handleCancel to mBackupRunner handles all 3: 1. Calls handleCancel on the
4660     *       preflight operation which counts down on the preflight latch. 2. Tears down the agent,
4661     *       so read() returns -1. 3. Notifies mCurrentOpLock which unblocks
4662     *       mBackupRunner.getBackupResultBlocking().
4663     */
4664    class PerformFullTransportBackupTask extends FullBackupTask implements BackupRestoreTask {
4665        static final String TAG = "PFTBT";
4666
4667        private final Object mCancelLock = new Object();
4668
4669        ArrayList<PackageInfo> mPackages;
4670        PackageInfo mCurrentPackage;
4671        boolean mUpdateSchedule;
4672        CountDownLatch mLatch;
4673        FullBackupJob mJob;             // if a scheduled job needs to be finished afterwards
4674        IBackupObserver mBackupObserver;
4675        IBackupManagerMonitor mMonitor;
4676        boolean mUserInitiated;
4677        private volatile IBackupTransport mTransport;
4678        SinglePackageBackupRunner mBackupRunner;
4679        private final int mBackupRunnerOpToken;
4680
4681        // This is true when a backup operation for some package is in progress.
4682        private volatile boolean mIsDoingBackup;
4683        private volatile boolean mCancelAll;
4684        private final int mCurrentOpToken;
4685
4686        PerformFullTransportBackupTask(IFullBackupRestoreObserver observer,
4687                String[] whichPackages, boolean updateSchedule,
4688                FullBackupJob runningJob, CountDownLatch latch, IBackupObserver backupObserver,
4689                IBackupManagerMonitor monitor, boolean userInitiated) {
4690            super(observer);
4691            mUpdateSchedule = updateSchedule;
4692            mLatch = latch;
4693            mJob = runningJob;
4694            mPackages = new ArrayList<PackageInfo>(whichPackages.length);
4695            mBackupObserver = backupObserver;
4696            mMonitor = monitor;
4697            mUserInitiated = userInitiated;
4698            mCurrentOpToken = generateRandomIntegerToken();
4699            mBackupRunnerOpToken = generateRandomIntegerToken();
4700
4701            if (isBackupOperationInProgress()) {
4702                if (DEBUG) {
4703                    Slog.d(TAG, "Skipping full backup. A backup is already in progress.");
4704                }
4705                mCancelAll = true;
4706                return;
4707            }
4708
4709            registerTask();
4710
4711            for (String pkg : whichPackages) {
4712                try {
4713                    PackageInfo info = mPackageManager.getPackageInfo(pkg,
4714                            PackageManager.GET_SIGNATURES);
4715                    mCurrentPackage = info;
4716                    if (!appIsEligibleForBackup(info.applicationInfo, mPackageManager)) {
4717                        // Cull any packages that have indicated that backups are not permitted,
4718                        // that run as system-domain uids but do not define their own backup agents,
4719                        // as well as any explicit mention of the 'special' shared-storage agent
4720                        // package (we handle that one at the end).
4721                        if (MORE_DEBUG) {
4722                            Slog.d(TAG, "Ignoring ineligible package " + pkg);
4723                        }
4724                        mMonitor = monitorEvent(mMonitor,
4725                                BackupManagerMonitor.LOG_EVENT_ID_PACKAGE_INELIGIBLE,
4726                                mCurrentPackage,
4727                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
4728                                null);
4729                        sendBackupOnPackageResult(mBackupObserver, pkg,
4730                            BackupManager.ERROR_BACKUP_NOT_ALLOWED);
4731                        continue;
4732                    } else if (!appGetsFullBackup(info)) {
4733                        // Cull any packages that are found in the queue but now aren't supposed
4734                        // to get full-data backup operations.
4735                        if (MORE_DEBUG) {
4736                            Slog.d(TAG, "Ignoring full-data backup of key/value participant "
4737                                    + pkg);
4738                        }
4739                        mMonitor = monitorEvent(mMonitor,
4740                                BackupManagerMonitor.LOG_EVENT_ID_PACKAGE_KEY_VALUE_PARTICIPANT,
4741                                mCurrentPackage,
4742                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
4743                                null);
4744                        sendBackupOnPackageResult(mBackupObserver, pkg,
4745                                BackupManager.ERROR_BACKUP_NOT_ALLOWED);
4746                        continue;
4747                    } else if (appIsStopped(info.applicationInfo)) {
4748                        // Cull any packages in the 'stopped' state: they've either just been
4749                        // installed or have explicitly been force-stopped by the user.  In both
4750                        // cases we do not want to launch them for backup.
4751                        if (MORE_DEBUG) {
4752                            Slog.d(TAG, "Ignoring stopped package " + pkg);
4753                        }
4754                        mMonitor = monitorEvent(mMonitor,
4755                                BackupManagerMonitor.LOG_EVENT_ID_PACKAGE_STOPPED,
4756                                mCurrentPackage,
4757                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
4758                                null);
4759                        sendBackupOnPackageResult(mBackupObserver, pkg,
4760                                BackupManager.ERROR_BACKUP_NOT_ALLOWED);
4761                        continue;
4762                    }
4763                    mPackages.add(info);
4764                } catch (NameNotFoundException e) {
4765                    Slog.i(TAG, "Requested package " + pkg + " not found; ignoring");
4766                    mMonitor = monitorEvent(mMonitor,
4767                            BackupManagerMonitor.LOG_EVENT_ID_PACKAGE_NOT_FOUND,
4768                            mCurrentPackage,
4769                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
4770                            null);
4771                }
4772            }
4773        }
4774
4775        private void registerTask() {
4776            synchronized (mCurrentOpLock) {
4777                Slog.d(TAG, "backupmanager pftbt token=" + Integer.toHexString(mCurrentOpToken));
4778                mCurrentOperations.put(mCurrentOpToken, new Operation(OP_PENDING, this,
4779                        OP_TYPE_BACKUP));
4780            }
4781        }
4782
4783        private void unregisterTask() {
4784            removeOperation(mCurrentOpToken);
4785        }
4786
4787        @Override
4788        public void execute() {
4789            // Nothing to do.
4790        }
4791
4792        @Override
4793        public void handleCancel(boolean cancelAll) {
4794            synchronized (mCancelLock) {
4795                // We only support 'cancelAll = true' case for this task. Cancelling of a single package
4796
4797                // due to timeout is handled by SinglePackageBackupRunner and SinglePackageBackupPreflight.
4798
4799                if (!cancelAll) {
4800                    Slog.wtf(TAG, "Expected cancelAll to be true.");
4801                }
4802
4803                if (mCancelAll) {
4804                    Slog.d(TAG, "Ignoring duplicate cancel call.");
4805                    return;
4806                }
4807
4808                mCancelAll = true;
4809                if (mIsDoingBackup) {
4810                    BackupManagerService.this.handleCancel(mBackupRunnerOpToken, cancelAll);
4811                    try {
4812                        mTransport.cancelFullBackup();
4813                    } catch (RemoteException e) {
4814                        Slog.w(TAG, "Error calling cancelFullBackup() on transport: " + e);
4815                        // Can't do much.
4816                    }
4817                }
4818            }
4819        }
4820
4821        @Override
4822        public void operationComplete(long result) {
4823            // Nothing to do.
4824        }
4825
4826        @Override
4827        public void run() {
4828
4829            // data from the app, passed to us for bridging to the transport
4830            ParcelFileDescriptor[] enginePipes = null;
4831
4832            // Pipe through which we write data to the transport
4833            ParcelFileDescriptor[] transportPipes = null;
4834
4835            long backoff = 0;
4836            int backupRunStatus = BackupManager.SUCCESS;
4837
4838            try {
4839                if (!mEnabled || !mProvisioned) {
4840                    // Backups are globally disabled, so don't proceed.
4841                    if (DEBUG) {
4842                        Slog.i(TAG, "full backup requested but enabled=" + mEnabled
4843                                + " provisioned=" + mProvisioned + "; ignoring");
4844                    }
4845                    int monitoringEvent;
4846                    if (!mEnabled) {
4847                        monitoringEvent = BackupManagerMonitor.LOG_EVENT_ID_BACKUP_DISABLED;
4848                    } else {
4849                        monitoringEvent = BackupManagerMonitor.LOG_EVENT_ID_DEVICE_NOT_PROVISIONED;
4850                    }
4851                    mMonitor = monitorEvent(mMonitor, monitoringEvent, null,
4852                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
4853                    mUpdateSchedule = false;
4854                    backupRunStatus = BackupManager.ERROR_BACKUP_NOT_ALLOWED;
4855                    return;
4856                }
4857
4858                mTransport = mTransportManager.getCurrentTransportBinder();
4859                if (mTransport == null) {
4860                    Slog.w(TAG, "Transport not present; full data backup not performed");
4861                    backupRunStatus = BackupManager.ERROR_TRANSPORT_ABORTED;
4862                    mMonitor = monitorEvent(mMonitor,
4863                            BackupManagerMonitor.LOG_EVENT_ID_PACKAGE_TRANSPORT_NOT_PRESENT,
4864                            mCurrentPackage, BackupManagerMonitor.LOG_EVENT_CATEGORY_TRANSPORT,
4865                            null);
4866                    return;
4867                }
4868
4869                // Set up to send data to the transport
4870                final int N = mPackages.size();
4871                final byte[] buffer = new byte[8192];
4872                for (int i = 0; i < N; i++) {
4873                    PackageInfo currentPackage = mPackages.get(i);
4874                    String packageName = currentPackage.packageName;
4875                    if (DEBUG) {
4876                        Slog.i(TAG, "Initiating full-data transport backup of " + packageName
4877                                + " token: " + mCurrentOpToken);
4878                    }
4879                    EventLog.writeEvent(EventLogTags.FULL_BACKUP_PACKAGE, packageName);
4880
4881                    transportPipes = ParcelFileDescriptor.createPipe();
4882
4883                    // Tell the transport the data's coming
4884                    int flags = mUserInitiated ? BackupTransport.FLAG_USER_INITIATED : 0;
4885                    int backupPackageStatus;
4886                    long quota = Long.MAX_VALUE;
4887                    synchronized (mCancelLock) {
4888                        if (mCancelAll) {
4889                            break;
4890                        }
4891                        backupPackageStatus = mTransport.performFullBackup(currentPackage,
4892                                transportPipes[0], flags);
4893
4894                        if (backupPackageStatus == BackupTransport.TRANSPORT_OK) {
4895                            quota = mTransport.getBackupQuota(currentPackage.packageName,
4896                                    true /* isFullBackup */);
4897                            // Now set up the backup engine / data source end of things
4898                            enginePipes = ParcelFileDescriptor.createPipe();
4899                            mBackupRunner =
4900                                    new SinglePackageBackupRunner(enginePipes[1], currentPackage,
4901                                            mTransport, quota, mBackupRunnerOpToken);
4902                            // The runner dup'd the pipe half, so we close it here
4903                            enginePipes[1].close();
4904                            enginePipes[1] = null;
4905
4906                            mIsDoingBackup = true;
4907                        }
4908                    }
4909                    if (backupPackageStatus == BackupTransport.TRANSPORT_OK) {
4910
4911                        // The transport has its own copy of the read end of the pipe,
4912                        // so close ours now
4913                        transportPipes[0].close();
4914                        transportPipes[0] = null;
4915
4916                        // Spin off the runner to fetch the app's data and pipe it
4917                        // into the engine pipes
4918                        (new Thread(mBackupRunner, "package-backup-bridge")).start();
4919
4920                        // Read data off the engine pipe and pass it to the transport
4921                        // pipe until we hit EOD on the input stream.  We do not take
4922                        // close() responsibility for these FDs into these stream wrappers.
4923                        FileInputStream in = new FileInputStream(
4924                                enginePipes[0].getFileDescriptor());
4925                        FileOutputStream out = new FileOutputStream(
4926                                transportPipes[1].getFileDescriptor());
4927                        long totalRead = 0;
4928                        final long preflightResult = mBackupRunner.getPreflightResultBlocking();
4929                        // Preflight result is negative if some error happened on preflight.
4930                        if (preflightResult < 0) {
4931                            if (MORE_DEBUG) {
4932                                Slog.d(TAG, "Backup error after preflight of package "
4933                                        + packageName + ": " + preflightResult
4934                                        + ", not running backup.");
4935                            }
4936                            mMonitor = monitorEvent(mMonitor,
4937                                    BackupManagerMonitor.LOG_EVENT_ID_ERROR_PREFLIGHT,
4938                                    mCurrentPackage,
4939                                    BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
4940                                    putMonitoringExtra(null,
4941                                            BackupManagerMonitor.EXTRA_LOG_PREFLIGHT_ERROR,
4942                                            preflightResult));
4943                            backupPackageStatus = (int) preflightResult;
4944                        } else {
4945                            int nRead = 0;
4946                            do {
4947                                nRead = in.read(buffer);
4948                                if (MORE_DEBUG) {
4949                                    Slog.v(TAG, "in.read(buffer) from app: " + nRead);
4950                                }
4951                                if (nRead > 0) {
4952                                    out.write(buffer, 0, nRead);
4953                                    synchronized (mCancelLock) {
4954                                        if (!mCancelAll) {
4955                                            backupPackageStatus = mTransport.sendBackupData(nRead);
4956                                        }
4957                                    }
4958                                    totalRead += nRead;
4959                                    if (mBackupObserver != null && preflightResult > 0) {
4960                                        sendBackupOnUpdate(mBackupObserver, packageName,
4961                                                new BackupProgress(preflightResult, totalRead));
4962                                    }
4963                                }
4964                            } while (nRead > 0
4965                                    && backupPackageStatus == BackupTransport.TRANSPORT_OK);
4966                            // Despite preflight succeeded, package still can hit quota on flight.
4967                            if (backupPackageStatus == BackupTransport.TRANSPORT_QUOTA_EXCEEDED) {
4968                                Slog.w(TAG, "Package hit quota limit in-flight " + packageName
4969                                        + ": " + totalRead + " of " + quota);
4970                                mMonitor = monitorEvent(mMonitor,
4971                                        BackupManagerMonitor.LOG_EVENT_ID_QUOTA_HIT_PREFLIGHT,
4972                                        mCurrentPackage,
4973                                        BackupManagerMonitor.LOG_EVENT_CATEGORY_TRANSPORT,
4974                                        null);
4975                                mBackupRunner.sendQuotaExceeded(totalRead, quota);
4976                            }
4977                        }
4978
4979                        final int backupRunnerResult = mBackupRunner.getBackupResultBlocking();
4980
4981                        synchronized (mCancelLock) {
4982                            mIsDoingBackup = false;
4983                            // If mCancelCurrent is true, we have already called cancelFullBackup().
4984                            if (!mCancelAll) {
4985                                if (backupRunnerResult == BackupTransport.TRANSPORT_OK) {
4986                                    // If we were otherwise in a good state, now interpret the final
4987                                    // result based on what finishBackup() returns.  If we're in a
4988                                    // failure case already, preserve that result and ignore whatever
4989                                    // finishBackup() reports.
4990                                    final int finishResult = mTransport.finishBackup();
4991                                    if (backupPackageStatus == BackupTransport.TRANSPORT_OK) {
4992                                        backupPackageStatus = finishResult;
4993                                    }
4994                                } else {
4995                                    mTransport.cancelFullBackup();
4996                                }
4997                            }
4998                        }
4999
5000                        // A transport-originated error here means that we've hit an error that the
5001                        // runner doesn't know about, so it's still moving data but we're pulling the
5002                        // rug out from under it.  Don't ask for its result:  we already know better
5003                        // and we'll hang if we block waiting for it, since it relies on us to
5004                        // read back the data it's writing into the engine.  Just proceed with
5005                        // a graceful failure.  The runner/engine mechanism will tear itself
5006                        // down cleanly when we close the pipes from this end.  Transport-level
5007                        // errors take precedence over agent/app-specific errors for purposes of
5008                        // determining our course of action.
5009                        if (backupPackageStatus == BackupTransport.TRANSPORT_OK) {
5010                            // We still could fail in backup runner thread.
5011                            if (backupRunnerResult != BackupTransport.TRANSPORT_OK) {
5012                                // If there was an error in runner thread and
5013                                // not TRANSPORT_ERROR here, overwrite it.
5014                                backupPackageStatus = backupRunnerResult;
5015                            }
5016                        } else {
5017                            if (MORE_DEBUG) {
5018                                Slog.i(TAG, "Transport-level failure; cancelling agent work");
5019                            }
5020                        }
5021
5022                        if (MORE_DEBUG) {
5023                            Slog.i(TAG, "Done delivering backup data: result="
5024                                    + backupPackageStatus);
5025                        }
5026
5027                        if (backupPackageStatus != BackupTransport.TRANSPORT_OK) {
5028                            Slog.e(TAG, "Error " + backupPackageStatus + " backing up "
5029                                    + packageName);
5030                        }
5031
5032                        // Also ask the transport how long it wants us to wait before
5033                        // moving on to the next package, if any.
5034                        backoff = mTransport.requestFullBackupTime();
5035                        if (DEBUG_SCHEDULING) {
5036                            Slog.i(TAG, "Transport suggested backoff=" + backoff);
5037                        }
5038
5039                    }
5040
5041                    // Roll this package to the end of the backup queue if we're
5042                    // in a queue-driven mode (regardless of success/failure)
5043                    if (mUpdateSchedule) {
5044                        enqueueFullBackup(packageName, System.currentTimeMillis());
5045                    }
5046
5047                    if (backupPackageStatus == BackupTransport.TRANSPORT_PACKAGE_REJECTED) {
5048                        sendBackupOnPackageResult(mBackupObserver, packageName,
5049                                BackupManager.ERROR_TRANSPORT_PACKAGE_REJECTED);
5050                        if (DEBUG) {
5051                            Slog.i(TAG, "Transport rejected backup of " + packageName
5052                                    + ", skipping");
5053                        }
5054                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_AGENT_FAILURE, packageName,
5055                                "transport rejected");
5056                        // Do nothing, clean up, and continue looping.
5057                    } else if (backupPackageStatus == BackupTransport.TRANSPORT_QUOTA_EXCEEDED) {
5058                        sendBackupOnPackageResult(mBackupObserver, packageName,
5059                                BackupManager.ERROR_TRANSPORT_QUOTA_EXCEEDED);
5060                        if (DEBUG) {
5061                            Slog.i(TAG, "Transport quota exceeded for package: " + packageName);
5062                            EventLog.writeEvent(EventLogTags.FULL_BACKUP_QUOTA_EXCEEDED,
5063                                    packageName);
5064                        }
5065                        // Do nothing, clean up, and continue looping.
5066                    } else if (backupPackageStatus == BackupTransport.AGENT_ERROR) {
5067                        sendBackupOnPackageResult(mBackupObserver, packageName,
5068                                BackupManager.ERROR_AGENT_FAILURE);
5069                        Slog.w(TAG, "Application failure for package: " + packageName);
5070                        EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName);
5071                        tearDownAgentAndKill(currentPackage.applicationInfo);
5072                        // Do nothing, clean up, and continue looping.
5073                    } else if (backupPackageStatus == BackupManager.ERROR_BACKUP_CANCELLED) {
5074                        sendBackupOnPackageResult(mBackupObserver, packageName,
5075                                BackupManager.ERROR_BACKUP_CANCELLED);
5076                        Slog.w(TAG, "Backup cancelled. package=" + packageName +
5077                                ", cancelAll=" + mCancelAll);
5078                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_CANCELLED, packageName);
5079                        tearDownAgentAndKill(currentPackage.applicationInfo);
5080                        // Do nothing, clean up, and continue looping.
5081                    } else if (backupPackageStatus != BackupTransport.TRANSPORT_OK) {
5082                        sendBackupOnPackageResult(mBackupObserver, packageName,
5083                            BackupManager.ERROR_TRANSPORT_ABORTED);
5084                        Slog.w(TAG, "Transport failed; aborting backup: " + backupPackageStatus);
5085                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_TRANSPORT_FAILURE);
5086                        // Abort entire backup pass.
5087                        backupRunStatus = BackupManager.ERROR_TRANSPORT_ABORTED;
5088                        return;
5089                    } else {
5090                        // Success!
5091                        sendBackupOnPackageResult(mBackupObserver, packageName,
5092                                BackupManager.SUCCESS);
5093                        EventLog.writeEvent(EventLogTags.FULL_BACKUP_SUCCESS, packageName);
5094                        logBackupComplete(packageName);
5095                    }
5096                    cleanUpPipes(transportPipes);
5097                    cleanUpPipes(enginePipes);
5098                    if (currentPackage.applicationInfo != null) {
5099                        Slog.i(TAG, "Unbinding agent in " + packageName);
5100                        addBackupTrace("unbinding " + packageName);
5101                        try {
5102                            mActivityManager.unbindBackupAgent(currentPackage.applicationInfo);
5103                        } catch (RemoteException e) { /* can't happen; activity manager is local */ }
5104                    }
5105                }
5106            } catch (Exception e) {
5107                backupRunStatus = BackupManager.ERROR_TRANSPORT_ABORTED;
5108                Slog.w(TAG, "Exception trying full transport backup", e);
5109                mMonitor = monitorEvent(mMonitor,
5110                        BackupManagerMonitor.LOG_EVENT_ID_EXCEPTION_FULL_BACKUP,
5111                        mCurrentPackage,
5112                        BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
5113                        putMonitoringExtra(null,
5114                                BackupManagerMonitor.EXTRA_LOG_EXCEPTION_FULL_BACKUP,
5115                                Log.getStackTraceString(e)));
5116
5117            } finally {
5118
5119                if (mCancelAll) {
5120                    backupRunStatus = BackupManager.ERROR_BACKUP_CANCELLED;
5121                }
5122
5123                if (DEBUG) {
5124                    Slog.i(TAG, "Full backup completed with status: " + backupRunStatus);
5125                }
5126                sendBackupFinished(mBackupObserver, backupRunStatus);
5127
5128                cleanUpPipes(transportPipes);
5129                cleanUpPipes(enginePipes);
5130
5131                unregisterTask();
5132
5133                if (mJob != null) {
5134                    mJob.finishBackupPass();
5135                }
5136
5137                synchronized (mQueueLock) {
5138                    mRunningFullBackupTask = null;
5139                }
5140
5141                mLatch.countDown();
5142
5143                // Now that we're actually done with schedule-driven work, reschedule
5144                // the next pass based on the new queue state.
5145                if (mUpdateSchedule) {
5146                    scheduleNextFullBackupJob(backoff);
5147                }
5148
5149                Slog.i(BackupManagerService.TAG, "Full data backup pass finished.");
5150                mWakelock.release();
5151            }
5152        }
5153
5154        void cleanUpPipes(ParcelFileDescriptor[] pipes) {
5155            if (pipes != null) {
5156                if (pipes[0] != null) {
5157                    ParcelFileDescriptor fd = pipes[0];
5158                    pipes[0] = null;
5159                    try {
5160                        fd.close();
5161                    } catch (IOException e) {
5162                        Slog.w(TAG, "Unable to close pipe!");
5163                    }
5164                }
5165                if (pipes[1] != null) {
5166                    ParcelFileDescriptor fd = pipes[1];
5167                    pipes[1] = null;
5168                    try {
5169                        fd.close();
5170                    } catch (IOException e) {
5171                        Slog.w(TAG, "Unable to close pipe!");
5172                    }
5173                }
5174            }
5175        }
5176
5177        // Run the backup and pipe it back to the given socket -- expects to run on
5178        // a standalone thread.  The  runner owns this half of the pipe, and closes
5179        // it to indicate EOD to the other end.
5180        class SinglePackageBackupPreflight implements BackupRestoreTask, FullBackupPreflight {
5181            final AtomicLong mResult = new AtomicLong(BackupTransport.AGENT_ERROR);
5182            final CountDownLatch mLatch = new CountDownLatch(1);
5183            final IBackupTransport mTransport;
5184            final long mQuota;
5185            private final int mCurrentOpToken;
5186
5187            SinglePackageBackupPreflight(IBackupTransport transport, long quota, int currentOpToken) {
5188                mTransport = transport;
5189                mQuota = quota;
5190                mCurrentOpToken = currentOpToken;
5191            }
5192
5193            @Override
5194            public int preflightFullBackup(PackageInfo pkg, IBackupAgent agent) {
5195                int result;
5196                try {
5197                    prepareOperationTimeout(mCurrentOpToken, TIMEOUT_FULL_BACKUP_INTERVAL,
5198                            this, OP_TYPE_BACKUP_WAIT);
5199                    addBackupTrace("preflighting");
5200                    if (MORE_DEBUG) {
5201                        Slog.d(TAG, "Preflighting full payload of " + pkg.packageName);
5202                    }
5203                    agent.doMeasureFullBackup(mQuota, mCurrentOpToken, mBackupManagerBinder);
5204
5205                    // Now wait to get our result back.  If this backstop timeout is reached without
5206                    // the latch being thrown, flow will continue as though a result or "normal"
5207                    // timeout had been produced.  In case of a real backstop timeout, mResult
5208                    // will still contain the value it was constructed with, AGENT_ERROR, which
5209                    // intentionaly falls into the "just report failure" code.
5210                    mLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
5211
5212                    long totalSize = mResult.get();
5213                    // If preflight timed out, mResult will contain error code as int.
5214                    if (totalSize < 0) {
5215                        return (int) totalSize;
5216                    }
5217                    if (MORE_DEBUG) {
5218                        Slog.v(TAG, "Got preflight response; size=" + totalSize);
5219                    }
5220
5221                    result = mTransport.checkFullBackupSize(totalSize);
5222                    if (result == BackupTransport.TRANSPORT_QUOTA_EXCEEDED) {
5223                        if (MORE_DEBUG) {
5224                            Slog.d(TAG, "Package hit quota limit on preflight " +
5225                                    pkg.packageName + ": " + totalSize + " of " + mQuota);
5226                        }
5227                        agent.doQuotaExceeded(totalSize, mQuota);
5228                    }
5229                } catch (Exception e) {
5230                    Slog.w(TAG, "Exception preflighting " + pkg.packageName + ": " + e.getMessage());
5231                    result = BackupTransport.AGENT_ERROR;
5232                }
5233                return result;
5234            }
5235
5236            @Override
5237            public void execute() {
5238                // Unused.
5239            }
5240
5241            @Override
5242            public void operationComplete(long result) {
5243                // got the callback, and our preflightFullBackup() method is waiting for the result
5244                if (MORE_DEBUG) {
5245                    Slog.i(TAG, "Preflight op complete, result=" + result);
5246                }
5247                mResult.set(result);
5248                mLatch.countDown();
5249                removeOperation(mCurrentOpToken);
5250            }
5251
5252            @Override
5253            public void handleCancel(boolean cancelAll) {
5254                if (MORE_DEBUG) {
5255                    Slog.i(TAG, "Preflight cancelled; failing");
5256                }
5257                mResult.set(BackupTransport.AGENT_ERROR);
5258                mLatch.countDown();
5259                removeOperation(mCurrentOpToken);
5260            }
5261
5262            @Override
5263            public long getExpectedSizeOrErrorCode() {
5264                try {
5265                    mLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
5266                    return mResult.get();
5267                } catch (InterruptedException e) {
5268                    return BackupTransport.NO_MORE_DATA;
5269                }
5270            }
5271        }
5272
5273        class SinglePackageBackupRunner implements Runnable, BackupRestoreTask {
5274            final ParcelFileDescriptor mOutput;
5275            final PackageInfo mTarget;
5276            final SinglePackageBackupPreflight mPreflight;
5277            final CountDownLatch mPreflightLatch;
5278            final CountDownLatch mBackupLatch;
5279            private final int mCurrentOpToken;
5280            private final int mEphemeralToken;
5281            private FullBackupEngine mEngine;
5282            private volatile int mPreflightResult;
5283            private volatile int mBackupResult;
5284            private final long mQuota;
5285            private volatile boolean mIsCancelled;
5286
5287            SinglePackageBackupRunner(ParcelFileDescriptor output, PackageInfo target,
5288                    IBackupTransport transport, long quota, int currentOpToken) throws IOException {
5289                mOutput = ParcelFileDescriptor.dup(output.getFileDescriptor());
5290                mTarget = target;
5291                mCurrentOpToken = currentOpToken;
5292                mEphemeralToken = generateRandomIntegerToken();
5293                mPreflight = new SinglePackageBackupPreflight(transport, quota, mEphemeralToken);
5294                mPreflightLatch = new CountDownLatch(1);
5295                mBackupLatch = new CountDownLatch(1);
5296                mPreflightResult = BackupTransport.AGENT_ERROR;
5297                mBackupResult = BackupTransport.AGENT_ERROR;
5298                mQuota = quota;
5299                registerTask();
5300            }
5301
5302            void registerTask() {
5303                synchronized (mCurrentOpLock) {
5304                    mCurrentOperations.put(mCurrentOpToken, new Operation(OP_PENDING, this,
5305                            OP_TYPE_BACKUP_WAIT));
5306                }
5307            }
5308
5309            void unregisterTask() {
5310                synchronized (mCurrentOpLock) {
5311                    mCurrentOperations.remove(mCurrentOpToken);
5312                }
5313            }
5314
5315            @Override
5316            public void run() {
5317                FileOutputStream out = new FileOutputStream(mOutput.getFileDescriptor());
5318                mEngine = new FullBackupEngine(out, mPreflight, mTarget, false, this, mQuota, mCurrentOpToken);
5319                try {
5320                    try {
5321                        if (!mIsCancelled) {
5322                            mPreflightResult = mEngine.preflightCheck();
5323                        }
5324                    } finally {
5325                        mPreflightLatch.countDown();
5326                    }
5327                    // If there is no error on preflight, continue backup.
5328                    if (mPreflightResult == BackupTransport.TRANSPORT_OK) {
5329                        if (!mIsCancelled) {
5330                            mBackupResult = mEngine.backupOnePackage();
5331                        }
5332                    }
5333                } catch (Exception e) {
5334                    Slog.e(TAG, "Exception during full package backup of " + mTarget.packageName);
5335                } finally {
5336                    unregisterTask();
5337                    mBackupLatch.countDown();
5338                    try {
5339                        mOutput.close();
5340                    } catch (IOException e) {
5341                        Slog.w(TAG, "Error closing transport pipe in runner");
5342                    }
5343                }
5344            }
5345
5346            public void sendQuotaExceeded(final long backupDataBytes, final long quotaBytes) {
5347                mEngine.sendQuotaExceeded(backupDataBytes, quotaBytes);
5348            }
5349
5350            // If preflight succeeded, returns positive number - preflight size,
5351            // otherwise return negative error code.
5352            long getPreflightResultBlocking() {
5353                try {
5354                    mPreflightLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
5355                    if (mIsCancelled) {
5356                        return BackupManager.ERROR_BACKUP_CANCELLED;
5357                    }
5358                    if (mPreflightResult == BackupTransport.TRANSPORT_OK) {
5359                        return mPreflight.getExpectedSizeOrErrorCode();
5360                    } else {
5361                        return mPreflightResult;
5362                    }
5363                } catch (InterruptedException e) {
5364                    return BackupTransport.AGENT_ERROR;
5365                }
5366            }
5367
5368            int getBackupResultBlocking() {
5369                try {
5370                    mBackupLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
5371                    if (mIsCancelled) {
5372                        return BackupManager.ERROR_BACKUP_CANCELLED;
5373                    }
5374                    return mBackupResult;
5375                } catch (InterruptedException e) {
5376                    return BackupTransport.AGENT_ERROR;
5377                }
5378            }
5379
5380
5381            // BackupRestoreTask interface: specifically, timeout detection
5382
5383            @Override
5384            public void execute() { /* intentionally empty */ }
5385
5386            @Override
5387            public void operationComplete(long result) { /* intentionally empty */ }
5388
5389            @Override
5390            public void handleCancel(boolean cancelAll) {
5391                if (DEBUG) {
5392                    Slog.w(TAG, "Full backup cancel of " + mTarget.packageName);
5393                }
5394
5395                mMonitor = monitorEvent(mMonitor,
5396                        BackupManagerMonitor.LOG_EVENT_ID_FULL_BACKUP_CANCEL,
5397                        mCurrentPackage, BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT, null);
5398                mIsCancelled = true;
5399                // Cancel tasks spun off by this task.
5400                BackupManagerService.this.handleCancel(mEphemeralToken, cancelAll);
5401                tearDownAgentAndKill(mTarget.applicationInfo);
5402                // Free up everyone waiting on this task and its children.
5403                mPreflightLatch.countDown();
5404                mBackupLatch.countDown();
5405                // We are done with this operation.
5406                removeOperation(mCurrentOpToken);
5407            }
5408        }
5409    }
5410
5411    // ----- Full-data backup scheduling -----
5412
5413    /**
5414     * Schedule a job to tell us when it's a good time to run a full backup
5415     */
5416    void scheduleNextFullBackupJob(long transportMinLatency) {
5417        synchronized (mQueueLock) {
5418            if (mFullBackupQueue.size() > 0) {
5419                // schedule the next job at the point in the future when the least-recently
5420                // backed up app comes due for backup again; or immediately if it's already
5421                // due.
5422                final long upcomingLastBackup = mFullBackupQueue.get(0).lastBackup;
5423                final long timeSinceLast = System.currentTimeMillis() - upcomingLastBackup;
5424                final long appLatency = (timeSinceLast < MIN_FULL_BACKUP_INTERVAL)
5425                        ? (MIN_FULL_BACKUP_INTERVAL - timeSinceLast) : 0;
5426                final long latency = Math.max(transportMinLatency, appLatency);
5427                Runnable r = new Runnable() {
5428                    @Override public void run() {
5429                        FullBackupJob.schedule(mContext, latency);
5430                    }
5431                };
5432                mBackupHandler.postDelayed(r, 2500);
5433            } else {
5434                if (DEBUG_SCHEDULING) {
5435                    Slog.i(TAG, "Full backup queue empty; not scheduling");
5436                }
5437            }
5438        }
5439    }
5440
5441    /**
5442     * Remove a package from the full-data queue.
5443     */
5444    void dequeueFullBackupLocked(String packageName) {
5445        final int N = mFullBackupQueue.size();
5446        for (int i = N-1; i >= 0; i--) {
5447            final FullBackupEntry e = mFullBackupQueue.get(i);
5448            if (packageName.equals(e.packageName)) {
5449                mFullBackupQueue.remove(i);
5450            }
5451        }
5452    }
5453
5454    /**
5455     * Enqueue full backup for the given app, with a note about when it last ran.
5456     */
5457    void enqueueFullBackup(String packageName, long lastBackedUp) {
5458        FullBackupEntry newEntry = new FullBackupEntry(packageName, lastBackedUp);
5459        synchronized (mQueueLock) {
5460            // First, sanity check that we aren't adding a duplicate.  Slow but
5461            // straightforward; we'll have at most on the order of a few hundred
5462            // items in this list.
5463            dequeueFullBackupLocked(packageName);
5464
5465            // This is also slow but easy for modest numbers of apps: work backwards
5466            // from the end of the queue until we find an item whose last backup
5467            // time was before this one, then insert this new entry after it.  If we're
5468            // adding something new we don't bother scanning, and just prepend.
5469            int which = -1;
5470            if (lastBackedUp > 0) {
5471                for (which = mFullBackupQueue.size() - 1; which >= 0; which--) {
5472                    final FullBackupEntry entry = mFullBackupQueue.get(which);
5473                    if (entry.lastBackup <= lastBackedUp) {
5474                        mFullBackupQueue.add(which + 1, newEntry);
5475                        break;
5476                    }
5477                }
5478            }
5479            if (which < 0) {
5480                // this one is earlier than any existing one, so prepend
5481                mFullBackupQueue.add(0, newEntry);
5482            }
5483        }
5484        writeFullBackupScheduleAsync();
5485    }
5486
5487    private boolean fullBackupAllowable(IBackupTransport transport) {
5488        if (transport == null) {
5489            Slog.w(TAG, "Transport not present; full data backup not performed");
5490            return false;
5491        }
5492
5493        // Don't proceed unless we have already established package metadata
5494        // for the current dataset via a key/value backup pass.
5495        try {
5496            File stateDir = new File(mBaseStateDir, transport.transportDirName());
5497            File pmState = new File(stateDir, PACKAGE_MANAGER_SENTINEL);
5498            if (pmState.length() <= 0) {
5499                if (DEBUG) {
5500                    Slog.i(TAG, "Full backup requested but dataset not yet initialized");
5501                }
5502                return false;
5503            }
5504        } catch (Exception e) {
5505            Slog.w(TAG, "Unable to get transport name: " + e.getMessage());
5506            return false;
5507        }
5508
5509        return true;
5510    }
5511
5512    /**
5513     * Conditions are right for a full backup operation, so run one.  The model we use is
5514     * to perform one app backup per scheduled job execution, and to reschedule the job
5515     * with zero latency as long as conditions remain right and we still have work to do.
5516     *
5517     * <p>This is the "start a full backup operation" entry point called by the scheduled job.
5518     *
5519     * @return Whether ongoing work will continue.  The return value here will be passed
5520     *         along as the return value to the scheduled job's onStartJob() callback.
5521     */
5522    @Override
5523    public boolean beginFullBackup(FullBackupJob scheduledJob) {
5524        long now = System.currentTimeMillis();
5525        FullBackupEntry entry = null;
5526        long latency = MIN_FULL_BACKUP_INTERVAL;
5527
5528        if (!mEnabled || !mProvisioned) {
5529            // Backups are globally disabled, so don't proceed.  We also don't reschedule
5530            // the job driving automatic backups; that job will be scheduled again when
5531            // the user enables backup.
5532            if (MORE_DEBUG) {
5533                Slog.i(TAG, "beginFullBackup but e=" + mEnabled
5534                        + " p=" + mProvisioned + "; ignoring");
5535            }
5536            return false;
5537        }
5538
5539        // Don't run the backup if we're in battery saver mode, but reschedule
5540        // to try again in the not-so-distant future.
5541        final PowerSaveState result =
5542                mPowerManager.getPowerSaveState(ServiceType.FULL_BACKUP);
5543        if (result.batterySaverEnabled) {
5544            if (DEBUG) Slog.i(TAG, "Deferring scheduled full backups in battery saver mode");
5545            FullBackupJob.schedule(mContext, KeyValueBackupJob.BATCH_INTERVAL);
5546            return false;
5547        }
5548
5549        if (DEBUG_SCHEDULING) {
5550            Slog.i(TAG, "Beginning scheduled full backup operation");
5551        }
5552
5553        // Great; we're able to run full backup jobs now.  See if we have any work to do.
5554        synchronized (mQueueLock) {
5555            if (mRunningFullBackupTask != null) {
5556                Slog.e(TAG, "Backup triggered but one already/still running!");
5557                return false;
5558            }
5559
5560            // At this point we think that we have work to do, but possibly not right now.
5561            // Any exit without actually running backups will also require that we
5562            // reschedule the job.
5563            boolean runBackup = true;
5564            boolean headBusy;
5565
5566            do {
5567                // Recheck each time, because culling due to ineligibility may
5568                // have emptied the queue.
5569                if (mFullBackupQueue.size() == 0) {
5570                    // no work to do so just bow out
5571                    if (DEBUG) {
5572                        Slog.i(TAG, "Backup queue empty; doing nothing");
5573                    }
5574                    runBackup = false;
5575                    break;
5576                }
5577
5578                headBusy = false;
5579
5580                if (!fullBackupAllowable(mTransportManager.getCurrentTransportBinder())) {
5581                    if (MORE_DEBUG) {
5582                        Slog.i(TAG, "Preconditions not met; not running full backup");
5583                    }
5584                    runBackup = false;
5585                    // Typically this means we haven't run a key/value backup yet.  Back off
5586                    // full-backup operations by the key/value job's run interval so that
5587                    // next time we run, we are likely to be able to make progress.
5588                    latency = KeyValueBackupJob.BATCH_INTERVAL;
5589                }
5590
5591                if (runBackup) {
5592                    entry = mFullBackupQueue.get(0);
5593                    long timeSinceRun = now - entry.lastBackup;
5594                    runBackup = (timeSinceRun >= MIN_FULL_BACKUP_INTERVAL);
5595                    if (!runBackup) {
5596                        // It's too early to back up the next thing in the queue, so bow out
5597                        if (MORE_DEBUG) {
5598                            Slog.i(TAG, "Device ready but too early to back up next app");
5599                        }
5600                        // Wait until the next app in the queue falls due for a full data backup
5601                        latency = MIN_FULL_BACKUP_INTERVAL - timeSinceRun;
5602                        break;  // we know we aren't doing work yet, so bail.
5603                    }
5604
5605                    try {
5606                        PackageInfo appInfo = mPackageManager.getPackageInfo(entry.packageName, 0);
5607                        if (!appGetsFullBackup(appInfo)) {
5608                            // The head app isn't supposed to get full-data backups [any more];
5609                            // so we cull it and force a loop around to consider the new head
5610                            // app.
5611                            if (MORE_DEBUG) {
5612                                Slog.i(TAG, "Culling package " + entry.packageName
5613                                        + " in full-backup queue but not eligible");
5614                            }
5615                            mFullBackupQueue.remove(0);
5616                            headBusy = true; // force the while() condition
5617                            continue;
5618                        }
5619
5620                        final int privFlags = appInfo.applicationInfo.privateFlags;
5621                        headBusy = (privFlags & PRIVATE_FLAG_BACKUP_IN_FOREGROUND) == 0
5622                                && mActivityManager.isAppForeground(appInfo.applicationInfo.uid);
5623
5624                        if (headBusy) {
5625                            final long nextEligible = System.currentTimeMillis()
5626                                    + BUSY_BACKOFF_MIN_MILLIS
5627                                    + mTokenGenerator.nextInt(BUSY_BACKOFF_FUZZ);
5628                            if (DEBUG_SCHEDULING) {
5629                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
5630                                Slog.i(TAG, "Full backup time but " + entry.packageName
5631                                        + " is busy; deferring to "
5632                                        + sdf.format(new Date(nextEligible)));
5633                            }
5634                            // This relocates the app's entry from the head of the queue to
5635                            // its order-appropriate position further down, so upon looping
5636                            // a new candidate will be considered at the head.
5637                            enqueueFullBackup(entry.packageName,
5638                                    nextEligible - MIN_FULL_BACKUP_INTERVAL);
5639                        }
5640                    } catch (NameNotFoundException nnf) {
5641                        // So, we think we want to back this up, but it turns out the package
5642                        // in question is no longer installed.  We want to drop it from the
5643                        // queue entirely and move on, but if there's nothing else in the queue
5644                        // we should bail entirely.  headBusy cannot have been set to true yet.
5645                        runBackup = (mFullBackupQueue.size() > 1);
5646                    } catch (RemoteException e) {
5647                        // Cannot happen; the Activity Manager is in the same process
5648                    }
5649                }
5650            } while (headBusy);
5651
5652            if (!runBackup) {
5653                if (DEBUG_SCHEDULING) {
5654                    Slog.i(TAG, "Nothing pending full backup; rescheduling +" + latency);
5655                }
5656                final long deferTime = latency;     // pin for the closure
5657                mBackupHandler.post(new Runnable() {
5658                    @Override public void run() {
5659                        FullBackupJob.schedule(mContext, deferTime);
5660                    }
5661                });
5662                return false;
5663            }
5664
5665            // Okay, the top thing is ready for backup now.  Do it.
5666            mFullBackupQueue.remove(0);
5667            CountDownLatch latch = new CountDownLatch(1);
5668            String[] pkg = new String[] {entry.packageName};
5669            mRunningFullBackupTask = new PerformFullTransportBackupTask(null, pkg, true,
5670                    scheduledJob, latch, null, null, false /* userInitiated */);
5671            // Acquiring wakelock for PerformFullTransportBackupTask before its start.
5672            mWakelock.acquire();
5673            (new Thread(mRunningFullBackupTask)).start();
5674        }
5675
5676        return true;
5677    }
5678
5679    // The job scheduler says our constraints don't hold any more,
5680    // so tear down any ongoing backup task right away.
5681    @Override
5682    public void endFullBackup() {
5683        // offload the mRunningFullBackupTask.handleCancel() call to another thread,
5684        // as we might have to wait for mCancelLock
5685        Runnable endFullBackupRunnable = new Runnable() {
5686            @Override
5687            public void run() {
5688                PerformFullTransportBackupTask pftbt = null;
5689                synchronized (mQueueLock) {
5690                    if (mRunningFullBackupTask != null) {
5691                        pftbt = mRunningFullBackupTask;
5692                    }
5693                }
5694                if (pftbt != null) {
5695                    if (DEBUG_SCHEDULING) {
5696                        Slog.i(TAG, "Telling running backup to stop");
5697                    }
5698                    pftbt.handleCancel(true);
5699                }
5700            }
5701        };
5702        new Thread(endFullBackupRunnable, "end-full-backup").start();
5703    }
5704
5705    // ----- Restore infrastructure -----
5706
5707    abstract class RestoreEngine {
5708        static final String TAG = "RestoreEngine";
5709
5710        public static final int SUCCESS = 0;
5711        public static final int TARGET_FAILURE = -2;
5712        public static final int TRANSPORT_FAILURE = -3;
5713
5714        private AtomicBoolean mRunning = new AtomicBoolean(false);
5715        private AtomicInteger mResult = new AtomicInteger(SUCCESS);
5716
5717        public boolean isRunning() {
5718            return mRunning.get();
5719        }
5720
5721        public void setRunning(boolean stillRunning) {
5722            synchronized (mRunning) {
5723                mRunning.set(stillRunning);
5724                mRunning.notifyAll();
5725            }
5726        }
5727
5728        public int waitForResult() {
5729            synchronized (mRunning) {
5730                while (isRunning()) {
5731                    try {
5732                        mRunning.wait();
5733                    } catch (InterruptedException e) {}
5734                }
5735            }
5736            return getResult();
5737        }
5738
5739        public int getResult() {
5740            return mResult.get();
5741        }
5742
5743        public void setResult(int result) {
5744            mResult.set(result);
5745        }
5746
5747        // TODO: abstract restore state and APIs
5748    }
5749
5750    // ----- Full restore from a file/socket -----
5751
5752    enum RestorePolicy {
5753        IGNORE,
5754        ACCEPT,
5755        ACCEPT_IF_APK
5756    }
5757
5758    // Full restore engine, used by both adb restore and transport-based full restore
5759    class FullRestoreEngine extends RestoreEngine {
5760        // Task in charge of monitoring timeouts
5761        BackupRestoreTask mMonitorTask;
5762
5763        // Dedicated observer, if any
5764        IFullBackupRestoreObserver mObserver;
5765
5766        IBackupManagerMonitor mMonitor;
5767
5768        // Where we're delivering the file data as we go
5769        IBackupAgent mAgent;
5770
5771        // Are we permitted to only deliver a specific package's metadata?
5772        PackageInfo mOnlyPackage;
5773
5774        boolean mAllowApks;
5775        boolean mAllowObbs;
5776
5777        // Which package are we currently handling data for?
5778        String mAgentPackage;
5779
5780        // Info for working with the target app process
5781        ApplicationInfo mTargetApp;
5782
5783        // Machinery for restoring OBBs
5784        FullBackupObbConnection mObbConnection = null;
5785
5786        // possible handling states for a given package in the restore dataset
5787        final HashMap<String, RestorePolicy> mPackagePolicies
5788                = new HashMap<String, RestorePolicy>();
5789
5790        // installer package names for each encountered app, derived from the manifests
5791        final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
5792
5793        // Signatures for a given package found in its manifest file
5794        final HashMap<String, Signature[]> mManifestSignatures
5795                = new HashMap<String, Signature[]>();
5796
5797        // Packages we've already wiped data on when restoring their first file
5798        final HashSet<String> mClearedPackages = new HashSet<String>();
5799
5800        // How much data have we moved?
5801        long mBytes;
5802
5803        // Working buffer
5804        byte[] mBuffer;
5805
5806        // Pipes for moving data
5807        ParcelFileDescriptor[] mPipes = null;
5808
5809        // Widget blob to be restored out-of-band
5810        byte[] mWidgetData = null;
5811
5812        private final int mEphemeralOpToken;
5813
5814        // Runner that can be placed in a separate thread to do in-process
5815        // invocations of the full restore API asynchronously. Used by adb restore.
5816        class RestoreFileRunnable implements Runnable {
5817            IBackupAgent mAgent;
5818            FileMetadata mInfo;
5819            ParcelFileDescriptor mSocket;
5820            int mToken;
5821
5822            RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
5823                    ParcelFileDescriptor socket, int token) throws IOException {
5824                mAgent = agent;
5825                mInfo = info;
5826                mToken = token;
5827
5828                // This class is used strictly for process-local binder invocations.  The
5829                // semantics of ParcelFileDescriptor differ in this case; in particular, we
5830                // do not automatically get a 'dup'ed descriptor that we can can continue
5831                // to use asynchronously from the caller.  So, we make sure to dup it ourselves
5832                // before proceeding to do the restore.
5833                mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
5834            }
5835
5836            @Override
5837            public void run() {
5838                try {
5839                    mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
5840                            mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
5841                            mToken, mBackupManagerBinder);
5842                } catch (RemoteException e) {
5843                    // never happens; this is used strictly for local binder calls
5844                }
5845            }
5846        }
5847
5848        public FullRestoreEngine(BackupRestoreTask monitorTask, IFullBackupRestoreObserver observer,
5849                IBackupManagerMonitor monitor, PackageInfo onlyPackage, boolean allowApks,
5850                boolean allowObbs, int ephemeralOpToken) {
5851            mEphemeralOpToken = ephemeralOpToken;
5852            mMonitorTask = monitorTask;
5853            mObserver = observer;
5854            mMonitor = monitor;
5855            mOnlyPackage = onlyPackage;
5856            mAllowApks = allowApks;
5857            mAllowObbs = allowObbs;
5858            mBuffer = new byte[32 * 1024];
5859            mBytes = 0;
5860        }
5861
5862        public IBackupAgent getAgent() {
5863            return mAgent;
5864        }
5865
5866        public byte[] getWidgetData() {
5867            return mWidgetData;
5868        }
5869
5870        public boolean restoreOneFile(InputStream instream, boolean mustKillAgent) {
5871            if (!isRunning()) {
5872                Slog.w(TAG, "Restore engine used after halting");
5873                return false;
5874            }
5875
5876            FileMetadata info;
5877            try {
5878                if (MORE_DEBUG) {
5879                    Slog.v(TAG, "Reading tar header for restoring file");
5880                }
5881                info = readTarHeaders(instream);
5882                if (info != null) {
5883                    if (MORE_DEBUG) {
5884                        dumpFileMetadata(info);
5885                    }
5886
5887                    final String pkg = info.packageName;
5888                    if (!pkg.equals(mAgentPackage)) {
5889                        // In the single-package case, it's a semantic error to expect
5890                        // one app's data but see a different app's on the wire
5891                        if (mOnlyPackage != null) {
5892                            if (!pkg.equals(mOnlyPackage.packageName)) {
5893                                Slog.w(TAG, "Expected data for " + mOnlyPackage
5894                                        + " but saw " + pkg);
5895                                setResult(RestoreEngine.TRANSPORT_FAILURE);
5896                                setRunning(false);
5897                                return false;
5898                            }
5899                        }
5900
5901                        // okay, change in package; set up our various
5902                        // bookkeeping if we haven't seen it yet
5903                        if (!mPackagePolicies.containsKey(pkg)) {
5904                            mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5905                        }
5906
5907                        // Clean up the previous agent relationship if necessary,
5908                        // and let the observer know we're considering a new app.
5909                        if (mAgent != null) {
5910                            if (DEBUG) Slog.d(TAG, "Saw new package; finalizing old one");
5911                            // Now we're really done
5912                            tearDownPipes();
5913                            tearDownAgent(mTargetApp);
5914                            mTargetApp = null;
5915                            mAgentPackage = null;
5916                        }
5917                    }
5918
5919                    if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
5920                        mPackagePolicies.put(pkg, readAppManifest(info, instream));
5921                        mPackageInstallers.put(pkg, info.installerPackageName);
5922                        // We've read only the manifest content itself at this point,
5923                        // so consume the footer before looping around to the next
5924                        // input file
5925                        skipTarPadding(info.size, instream);
5926                        sendOnRestorePackage(pkg);
5927                    } else if (info.path.equals(BACKUP_METADATA_FILENAME)) {
5928                        // Metadata blobs!
5929                        readMetadata(info, instream);
5930                        skipTarPadding(info.size, instream);
5931                    } else {
5932                        // Non-manifest, so it's actual file data.  Is this a package
5933                        // we're ignoring?
5934                        boolean okay = true;
5935                        RestorePolicy policy = mPackagePolicies.get(pkg);
5936                        switch (policy) {
5937                            case IGNORE:
5938                                okay = false;
5939                                break;
5940
5941                            case ACCEPT_IF_APK:
5942                                // If we're in accept-if-apk state, then the first file we
5943                                // see MUST be the apk.
5944                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
5945                                    if (DEBUG) Slog.d(TAG, "APK file; installing");
5946                                    // Try to install the app.
5947                                    String installerName = mPackageInstallers.get(pkg);
5948                                    okay = installApk(info, installerName, instream);
5949                                    // good to go; promote to ACCEPT
5950                                    mPackagePolicies.put(pkg, (okay)
5951                                            ? RestorePolicy.ACCEPT
5952                                                    : RestorePolicy.IGNORE);
5953                                    // At this point we've consumed this file entry
5954                                    // ourselves, so just strip the tar footer and
5955                                    // go on to the next file in the input stream
5956                                    skipTarPadding(info.size, instream);
5957                                    return true;
5958                                } else {
5959                                    // File data before (or without) the apk.  We can't
5960                                    // handle it coherently in this case so ignore it.
5961                                    mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5962                                    okay = false;
5963                                }
5964                                break;
5965
5966                            case ACCEPT:
5967                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
5968                                    if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
5969                                    // we can take the data without the apk, so we
5970                                    // *want* to do so.  skip the apk by declaring this
5971                                    // one file not-okay without changing the restore
5972                                    // policy for the package.
5973                                    okay = false;
5974                                }
5975                                break;
5976
5977                            default:
5978                                // Something has gone dreadfully wrong when determining
5979                                // the restore policy from the manifest.  Ignore the
5980                                // rest of this package's data.
5981                                Slog.e(TAG, "Invalid policy from manifest");
5982                                okay = false;
5983                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
5984                                break;
5985                        }
5986
5987                        // Is it a *file* we need to drop?
5988                        if (!isRestorableFile(info)) {
5989                            okay = false;
5990                        }
5991
5992                        // If the policy is satisfied, go ahead and set up to pipe the
5993                        // data to the agent.
5994                        if (MORE_DEBUG && okay && mAgent != null) {
5995                            Slog.i(TAG, "Reusing existing agent instance");
5996                        }
5997                        if (okay && mAgent == null) {
5998                            if (MORE_DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
5999
6000                            try {
6001                                mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
6002
6003                                // If we haven't sent any data to this app yet, we probably
6004                                // need to clear it first.  Check that.
6005                                if (!mClearedPackages.contains(pkg)) {
6006                                    // apps with their own backup agents are
6007                                    // responsible for coherently managing a full
6008                                    // restore.
6009                                    if (mTargetApp.backupAgentName == null) {
6010                                        if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
6011                                        clearApplicationDataSynchronous(pkg);
6012                                    } else {
6013                                        if (MORE_DEBUG) Slog.d(TAG, "backup agent ("
6014                                                + mTargetApp.backupAgentName + ") => no clear");
6015                                    }
6016                                    mClearedPackages.add(pkg);
6017                                } else {
6018                                    if (MORE_DEBUG) {
6019                                        Slog.d(TAG, "We've initialized this app already; no clear required");
6020                                    }
6021                                }
6022
6023                                // All set; now set up the IPC and launch the agent
6024                                setUpPipes();
6025                                mAgent = bindToAgentSynchronous(mTargetApp,
6026                                        ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL);
6027                                mAgentPackage = pkg;
6028                            } catch (IOException e) {
6029                                // fall through to error handling
6030                            } catch (NameNotFoundException e) {
6031                                // fall through to error handling
6032                            }
6033
6034                            if (mAgent == null) {
6035                                Slog.e(TAG, "Unable to create agent for " + pkg);
6036                                okay = false;
6037                                tearDownPipes();
6038                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
6039                            }
6040                        }
6041
6042                        // Sanity check: make sure we never give data to the wrong app.  This
6043                        // should never happen but a little paranoia here won't go amiss.
6044                        if (okay && !pkg.equals(mAgentPackage)) {
6045                            Slog.e(TAG, "Restoring data for " + pkg
6046                                    + " but agent is for " + mAgentPackage);
6047                            okay = false;
6048                        }
6049
6050                        // At this point we have an agent ready to handle the full
6051                        // restore data as well as a pipe for sending data to
6052                        // that agent.  Tell the agent to start reading from the
6053                        // pipe.
6054                        if (okay) {
6055                            boolean agentSuccess = true;
6056                            long toCopy = info.size;
6057                            try {
6058                                prepareOperationTimeout(mEphemeralOpToken,
6059                                        TIMEOUT_FULL_BACKUP_INTERVAL, mMonitorTask,
6060                                        OP_TYPE_RESTORE_WAIT);
6061
6062                                if (info.domain.equals(FullBackup.OBB_TREE_TOKEN)) {
6063                                    if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
6064                                            + " : " + info.path);
6065                                    mObbConnection.restoreObbFile(pkg, mPipes[0],
6066                                            info.size, info.type, info.path, info.mode,
6067                                            info.mtime, mEphemeralOpToken, mBackupManagerBinder);
6068                                } else {
6069                                    if (MORE_DEBUG) Slog.d(TAG, "Invoking agent to restore file "
6070                                            + info.path);
6071                                    // fire up the app's agent listening on the socket.  If
6072                                    // the agent is running in the system process we can't
6073                                    // just invoke it asynchronously, so we provide a thread
6074                                    // for it here.
6075                                    if (mTargetApp.processName.equals("system")) {
6076                                        Slog.d(TAG, "system process agent - spinning a thread");
6077                                        RestoreFileRunnable runner = new RestoreFileRunnable(
6078                                                mAgent, info, mPipes[0], mEphemeralOpToken);
6079                                        new Thread(runner, "restore-sys-runner").start();
6080                                    } else {
6081                                        mAgent.doRestoreFile(mPipes[0], info.size, info.type,
6082                                                info.domain, info.path, info.mode, info.mtime,
6083                                                mEphemeralOpToken, mBackupManagerBinder);
6084                                    }
6085                                }
6086                            } catch (IOException e) {
6087                                // couldn't dup the socket for a process-local restore
6088                                Slog.d(TAG, "Couldn't establish restore");
6089                                agentSuccess = false;
6090                                okay = false;
6091                            } catch (RemoteException e) {
6092                                // whoops, remote entity went away.  We'll eat the content
6093                                // ourselves, then, and not copy it over.
6094                                Slog.e(TAG, "Agent crashed during full restore");
6095                                agentSuccess = false;
6096                                okay = false;
6097                            }
6098
6099                            // Copy over the data if the agent is still good
6100                            if (okay) {
6101                                if (MORE_DEBUG) {
6102                                    Slog.v(TAG, "  copying to restore agent: "
6103                                            + toCopy + " bytes");
6104                                }
6105                                boolean pipeOkay = true;
6106                                FileOutputStream pipe = new FileOutputStream(
6107                                        mPipes[1].getFileDescriptor());
6108                                while (toCopy > 0) {
6109                                    int toRead = (toCopy > mBuffer.length)
6110                                            ? mBuffer.length : (int)toCopy;
6111                                    int nRead = instream.read(mBuffer, 0, toRead);
6112                                    if (nRead >= 0) mBytes += nRead;
6113                                    if (nRead <= 0) break;
6114                                    toCopy -= nRead;
6115
6116                                    // send it to the output pipe as long as things
6117                                    // are still good
6118                                    if (pipeOkay) {
6119                                        try {
6120                                            pipe.write(mBuffer, 0, nRead);
6121                                        } catch (IOException e) {
6122                                            Slog.e(TAG, "Failed to write to restore pipe: "
6123                                                    + e.getMessage());
6124                                            pipeOkay = false;
6125                                        }
6126                                    }
6127                                }
6128
6129                                // done sending that file!  Now we just need to consume
6130                                // the delta from info.size to the end of block.
6131                                skipTarPadding(info.size, instream);
6132
6133                                // and now that we've sent it all, wait for the remote
6134                                // side to acknowledge receipt
6135                                agentSuccess = waitUntilOperationComplete(mEphemeralOpToken);
6136                            }
6137
6138                            // okay, if the remote end failed at any point, deal with
6139                            // it by ignoring the rest of the restore on it
6140                            if (!agentSuccess) {
6141                                Slog.w(TAG, "Agent failure; ending restore");
6142                                mBackupHandler.removeMessages(MSG_RESTORE_OPERATION_TIMEOUT);
6143                                tearDownPipes();
6144                                tearDownAgent(mTargetApp);
6145                                mAgent = null;
6146                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
6147
6148                                // If this was a single-package restore, we halt immediately
6149                                // with an agent error under these circumstances
6150                                if (mOnlyPackage != null) {
6151                                    setResult(RestoreEngine.TARGET_FAILURE);
6152                                    setRunning(false);
6153                                    return false;
6154                                }
6155                            }
6156                        }
6157
6158                        // Problems setting up the agent communication, an explicitly
6159                        // dropped file, or an already-ignored package: skip to the
6160                        // next stream entry by reading and discarding this file.
6161                        if (!okay) {
6162                            if (MORE_DEBUG) Slog.d(TAG, "[discarding file content]");
6163                            long bytesToConsume = (info.size + 511) & ~511;
6164                            while (bytesToConsume > 0) {
6165                                int toRead = (bytesToConsume > mBuffer.length)
6166                                        ? mBuffer.length : (int)bytesToConsume;
6167                                long nRead = instream.read(mBuffer, 0, toRead);
6168                                if (nRead >= 0) mBytes += nRead;
6169                                if (nRead <= 0) break;
6170                                bytesToConsume -= nRead;
6171                            }
6172                        }
6173                    }
6174                }
6175            } catch (IOException e) {
6176                if (DEBUG) Slog.w(TAG, "io exception on restore socket read: " + e.getMessage());
6177                setResult(RestoreEngine.TRANSPORT_FAILURE);
6178                info = null;
6179            }
6180
6181            // If we got here we're either running smoothly or we've finished
6182            if (info == null) {
6183                if (MORE_DEBUG) {
6184                    Slog.i(TAG, "No [more] data for this package; tearing down");
6185                }
6186                tearDownPipes();
6187                setRunning(false);
6188                if (mustKillAgent) {
6189                    tearDownAgent(mTargetApp);
6190                }
6191            }
6192            return (info != null);
6193        }
6194
6195        void setUpPipes() throws IOException {
6196            mPipes = ParcelFileDescriptor.createPipe();
6197        }
6198
6199        void tearDownPipes() {
6200            // Teardown might arise from the inline restore processing or from the asynchronous
6201            // timeout mechanism, and these might race.  Make sure we don't try to close and
6202            // null out the pipes twice.
6203            synchronized (this) {
6204                if (mPipes != null) {
6205                    try {
6206                        mPipes[0].close();
6207                        mPipes[0] = null;
6208                        mPipes[1].close();
6209                        mPipes[1] = null;
6210                    } catch (IOException e) {
6211                        Slog.w(TAG, "Couldn't close agent pipes", e);
6212                    }
6213                    mPipes = null;
6214                }
6215            }
6216        }
6217
6218        void tearDownAgent(ApplicationInfo app) {
6219            if (mAgent != null) {
6220                tearDownAgentAndKill(app);
6221                mAgent = null;
6222            }
6223        }
6224
6225        void handleTimeout() {
6226            tearDownPipes();
6227            setResult(RestoreEngine.TARGET_FAILURE);
6228            setRunning(false);
6229        }
6230
6231        class RestoreInstallObserver extends PackageInstallObserver {
6232            final AtomicBoolean mDone = new AtomicBoolean();
6233            String mPackageName;
6234            int mResult;
6235
6236            public void reset() {
6237                synchronized (mDone) {
6238                    mDone.set(false);
6239                }
6240            }
6241
6242            public void waitForCompletion() {
6243                synchronized (mDone) {
6244                    while (mDone.get() == false) {
6245                        try {
6246                            mDone.wait();
6247                        } catch (InterruptedException e) { }
6248                    }
6249                }
6250            }
6251
6252            int getResult() {
6253                return mResult;
6254            }
6255
6256            @Override
6257            public void onPackageInstalled(String packageName, int returnCode,
6258                    String msg, Bundle extras) {
6259                synchronized (mDone) {
6260                    mResult = returnCode;
6261                    mPackageName = packageName;
6262                    mDone.set(true);
6263                    mDone.notifyAll();
6264                }
6265            }
6266        }
6267
6268        class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
6269            final AtomicBoolean mDone = new AtomicBoolean();
6270            int mResult;
6271
6272            public void reset() {
6273                synchronized (mDone) {
6274                    mDone.set(false);
6275                }
6276            }
6277
6278            public void waitForCompletion() {
6279                synchronized (mDone) {
6280                    while (mDone.get() == false) {
6281                        try {
6282                            mDone.wait();
6283                        } catch (InterruptedException e) { }
6284                    }
6285                }
6286            }
6287
6288            @Override
6289            public void packageDeleted(String packageName, int returnCode) throws RemoteException {
6290                synchronized (mDone) {
6291                    mResult = returnCode;
6292                    mDone.set(true);
6293                    mDone.notifyAll();
6294                }
6295            }
6296        }
6297
6298        final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
6299        final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
6300
6301        boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
6302            boolean okay = true;
6303
6304            if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
6305
6306            // The file content is an .apk file.  Copy it out to a staging location and
6307            // attempt to install it.
6308            File apkFile = new File(mDataDir, info.packageName);
6309            try {
6310                FileOutputStream apkStream = new FileOutputStream(apkFile);
6311                byte[] buffer = new byte[32 * 1024];
6312                long size = info.size;
6313                while (size > 0) {
6314                    long toRead = (buffer.length < size) ? buffer.length : size;
6315                    int didRead = instream.read(buffer, 0, (int)toRead);
6316                    if (didRead >= 0) mBytes += didRead;
6317                    apkStream.write(buffer, 0, didRead);
6318                    size -= didRead;
6319                }
6320                apkStream.close();
6321
6322                // make sure the installer can read it
6323                apkFile.setReadable(true, false);
6324
6325                // Now install it
6326                Uri packageUri = Uri.fromFile(apkFile);
6327                mInstallObserver.reset();
6328                mPackageManager.installPackage(packageUri, mInstallObserver,
6329                        PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
6330                        installerPackage);
6331                mInstallObserver.waitForCompletion();
6332
6333                if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
6334                    // The only time we continue to accept install of data even if the
6335                    // apk install failed is if we had already determined that we could
6336                    // accept the data regardless.
6337                    if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
6338                        okay = false;
6339                    }
6340                } else {
6341                    // Okay, the install succeeded.  Make sure it was the right app.
6342                    boolean uninstall = false;
6343                    if (!mInstallObserver.mPackageName.equals(info.packageName)) {
6344                        Slog.w(TAG, "Restore stream claimed to include apk for "
6345                                + info.packageName + " but apk was really "
6346                                + mInstallObserver.mPackageName);
6347                        // delete the package we just put in place; it might be fraudulent
6348                        okay = false;
6349                        uninstall = true;
6350                    } else {
6351                        try {
6352                            PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
6353                                    PackageManager.GET_SIGNATURES);
6354                            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
6355                                Slog.w(TAG, "Restore stream contains apk of package "
6356                                        + info.packageName + " but it disallows backup/restore");
6357                                okay = false;
6358                            } else {
6359                                // So far so good -- do the signatures match the manifest?
6360                                Signature[] sigs = mManifestSignatures.get(info.packageName);
6361                                if (signaturesMatch(sigs, pkg)) {
6362                                    // If this is a system-uid app without a declared backup agent,
6363                                    // don't restore any of the file data.
6364                                    if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
6365                                            && (pkg.applicationInfo.backupAgentName == null)) {
6366                                        Slog.w(TAG, "Installed app " + info.packageName
6367                                                + " has restricted uid and no agent");
6368                                        okay = false;
6369                                    }
6370                                } else {
6371                                    Slog.w(TAG, "Installed app " + info.packageName
6372                                            + " signatures do not match restore manifest");
6373                                    okay = false;
6374                                    uninstall = true;
6375                                }
6376                            }
6377                        } catch (NameNotFoundException e) {
6378                            Slog.w(TAG, "Install of package " + info.packageName
6379                                    + " succeeded but now not found");
6380                            okay = false;
6381                        }
6382                    }
6383
6384                    // If we're not okay at this point, we need to delete the package
6385                    // that we just installed.
6386                    if (uninstall) {
6387                        mDeleteObserver.reset();
6388                        mPackageManager.deletePackage(mInstallObserver.mPackageName,
6389                                mDeleteObserver, 0);
6390                        mDeleteObserver.waitForCompletion();
6391                    }
6392                }
6393            } catch (IOException e) {
6394                Slog.e(TAG, "Unable to transcribe restored apk for install");
6395                okay = false;
6396            } finally {
6397                apkFile.delete();
6398            }
6399
6400            return okay;
6401        }
6402
6403        // Given an actual file content size, consume the post-content padding mandated
6404        // by the tar format.
6405        void skipTarPadding(long size, InputStream instream) throws IOException {
6406            long partial = (size + 512) % 512;
6407            if (partial > 0) {
6408                final int needed = 512 - (int)partial;
6409                if (MORE_DEBUG) {
6410                    Slog.i(TAG, "Skipping tar padding: " + needed + " bytes");
6411                }
6412                byte[] buffer = new byte[needed];
6413                if (readExactly(instream, buffer, 0, needed) == needed) {
6414                    mBytes += needed;
6415                } else throw new IOException("Unexpected EOF in padding");
6416            }
6417        }
6418
6419        // Read a widget metadata file, returning the restored blob
6420        void readMetadata(FileMetadata info, InputStream instream) throws IOException {
6421            // Fail on suspiciously large widget dump files
6422            if (info.size > 64 * 1024) {
6423                throw new IOException("Metadata too big; corrupt? size=" + info.size);
6424            }
6425
6426            byte[] buffer = new byte[(int) info.size];
6427            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
6428                mBytes += info.size;
6429            } else throw new IOException("Unexpected EOF in widget data");
6430
6431            String[] str = new String[1];
6432            int offset = extractLine(buffer, 0, str);
6433            int version = Integer.parseInt(str[0]);
6434            if (version == BACKUP_MANIFEST_VERSION) {
6435                offset = extractLine(buffer, offset, str);
6436                final String pkg = str[0];
6437                if (info.packageName.equals(pkg)) {
6438                    // Data checks out -- the rest of the buffer is a concatenation of
6439                    // binary blobs as described in the comment at writeAppWidgetData()
6440                    ByteArrayInputStream bin = new ByteArrayInputStream(buffer,
6441                            offset, buffer.length - offset);
6442                    DataInputStream in = new DataInputStream(bin);
6443                    while (bin.available() > 0) {
6444                        int token = in.readInt();
6445                        int size = in.readInt();
6446                        if (size > 64 * 1024) {
6447                            throw new IOException("Datum "
6448                                    + Integer.toHexString(token)
6449                                    + " too big; corrupt? size=" + info.size);
6450                        }
6451                        switch (token) {
6452                            case BACKUP_WIDGET_METADATA_TOKEN:
6453                            {
6454                                if (MORE_DEBUG) {
6455                                    Slog.i(TAG, "Got widget metadata for " + info.packageName);
6456                                }
6457                                mWidgetData = new byte[size];
6458                                in.read(mWidgetData);
6459                                break;
6460                            }
6461                            default:
6462                            {
6463                                if (DEBUG) {
6464                                    Slog.i(TAG, "Ignoring metadata blob "
6465                                            + Integer.toHexString(token)
6466                                            + " for " + info.packageName);
6467                                }
6468                                in.skipBytes(size);
6469                                break;
6470                            }
6471                        }
6472                    }
6473                } else {
6474                    Slog.w(TAG, "Metadata mismatch: package " + info.packageName
6475                            + " but widget data for " + pkg);
6476
6477                    Bundle monitoringExtras = putMonitoringExtra(null,
6478                            EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName);
6479                    monitoringExtras = putMonitoringExtra(monitoringExtras,
6480                            BackupManagerMonitor.EXTRA_LOG_WIDGET_PACKAGE_NAME, pkg);
6481                    mMonitor = monitorEvent(mMonitor,
6482                            BackupManagerMonitor.LOG_EVENT_ID_WIDGET_METADATA_MISMATCH,
6483                            null,
6484                            LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6485                            monitoringExtras);
6486                }
6487            } else {
6488                Slog.w(TAG, "Unsupported metadata version " + version);
6489
6490                Bundle monitoringExtras = putMonitoringExtra(null, EXTRA_LOG_EVENT_PACKAGE_NAME,
6491                        info.packageName);
6492                monitoringExtras = putMonitoringExtra(monitoringExtras,
6493                        EXTRA_LOG_EVENT_PACKAGE_VERSION, version);
6494                mMonitor = monitorEvent(mMonitor,
6495                        BackupManagerMonitor.LOG_EVENT_ID_WIDGET_UNKNOWN_VERSION,
6496                        null,
6497                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6498                        monitoringExtras);
6499            }
6500        }
6501
6502        // Returns a policy constant
6503        RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
6504                throws IOException {
6505            // Fail on suspiciously large manifest files
6506            if (info.size > 64 * 1024) {
6507                throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
6508            }
6509
6510            byte[] buffer = new byte[(int) info.size];
6511            if (MORE_DEBUG) {
6512                Slog.i(TAG, "   readAppManifest() looking for " + info.size + " bytes, "
6513                        + mBytes + " already consumed");
6514            }
6515            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
6516                mBytes += info.size;
6517            } else throw new IOException("Unexpected EOF in manifest");
6518
6519            RestorePolicy policy = RestorePolicy.IGNORE;
6520            String[] str = new String[1];
6521            int offset = 0;
6522
6523            try {
6524                offset = extractLine(buffer, offset, str);
6525                int version = Integer.parseInt(str[0]);
6526                if (version == BACKUP_MANIFEST_VERSION) {
6527                    offset = extractLine(buffer, offset, str);
6528                    String manifestPackage = str[0];
6529                    // TODO: handle <original-package>
6530                    if (manifestPackage.equals(info.packageName)) {
6531                        offset = extractLine(buffer, offset, str);
6532                        version = Integer.parseInt(str[0]);  // app version
6533                        offset = extractLine(buffer, offset, str);
6534                        // This is the platform version, which we don't use, but we parse it
6535                        // as a safety against corruption in the manifest.
6536                        Integer.parseInt(str[0]);
6537                        offset = extractLine(buffer, offset, str);
6538                        info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
6539                        offset = extractLine(buffer, offset, str);
6540                        boolean hasApk = str[0].equals("1");
6541                        offset = extractLine(buffer, offset, str);
6542                        int numSigs = Integer.parseInt(str[0]);
6543                        if (numSigs > 0) {
6544                            Signature[] sigs = new Signature[numSigs];
6545                            for (int i = 0; i < numSigs; i++) {
6546                                offset = extractLine(buffer, offset, str);
6547                                sigs[i] = new Signature(str[0]);
6548                            }
6549                            mManifestSignatures.put(info.packageName, sigs);
6550
6551                            // Okay, got the manifest info we need...
6552                            try {
6553                                PackageInfo pkgInfo = mPackageManager.getPackageInfo(
6554                                        info.packageName, PackageManager.GET_SIGNATURES);
6555                                // Fall through to IGNORE if the app explicitly disallows backup
6556                                final int flags = pkgInfo.applicationInfo.flags;
6557                                if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
6558                                    // Restore system-uid-space packages only if they have
6559                                    // defined a custom backup agent
6560                                    if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
6561                                            || (pkgInfo.applicationInfo.backupAgentName != null)) {
6562                                        // Verify signatures against any installed version; if they
6563                                        // don't match, then we fall though and ignore the data.  The
6564                                        // signatureMatch() method explicitly ignores the signature
6565                                        // check for packages installed on the system partition, because
6566                                        // such packages are signed with the platform cert instead of
6567                                        // the app developer's cert, so they're different on every
6568                                        // device.
6569                                        if (signaturesMatch(sigs, pkgInfo)) {
6570                                            if ((pkgInfo.applicationInfo.flags
6571                                                    & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) != 0) {
6572                                                Slog.i(TAG, "Package has restoreAnyVersion; taking data");
6573                                                mMonitor = monitorEvent(mMonitor,
6574                                                        LOG_EVENT_ID_RESTORE_ANY_VERSION,
6575                                                        pkgInfo,
6576                                                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6577                                                        null);
6578                                                policy = RestorePolicy.ACCEPT;
6579                                            } else if (pkgInfo.versionCode >= version) {
6580                                                Slog.i(TAG, "Sig + version match; taking data");
6581                                                policy = RestorePolicy.ACCEPT;
6582                                                mMonitor = monitorEvent(mMonitor,
6583                                                        LOG_EVENT_ID_VERSIONS_MATCH,
6584                                                        pkgInfo,
6585                                                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6586                                                        null);
6587                                            } else {
6588                                                // The data is from a newer version of the app than
6589                                                // is presently installed.  That means we can only
6590                                                // use it if the matching apk is also supplied.
6591                                                if (mAllowApks) {
6592                                                    Slog.i(TAG, "Data version " + version
6593                                                            + " is newer than installed version "
6594                                                            + pkgInfo.versionCode
6595                                                            + " - requiring apk");
6596                                                    policy = RestorePolicy.ACCEPT_IF_APK;
6597                                                } else {
6598                                                    Slog.i(TAG, "Data requires newer version "
6599                                                            + version + "; ignoring");
6600                                                    mMonitor = monitorEvent(mMonitor,
6601                                                            LOG_EVENT_ID_VERSION_OF_BACKUP_OLDER,
6602                                                            pkgInfo,
6603                                                            LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6604                                                            putMonitoringExtra(null,
6605                                                                    EXTRA_LOG_OLD_VERSION,
6606                                                                    version));
6607
6608                                                    policy = RestorePolicy.IGNORE;
6609                                                }
6610                                            }
6611                                        } else {
6612                                            Slog.w(TAG, "Restore manifest signatures do not match "
6613                                                    + "installed application for " + info.packageName);
6614                                            mMonitor = monitorEvent(mMonitor,
6615                                                    LOG_EVENT_ID_FULL_RESTORE_SIGNATURE_MISMATCH,
6616                                                    pkgInfo,
6617                                                    LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6618                                                    null);
6619                                        }
6620                                    } else {
6621                                        Slog.w(TAG, "Package " + info.packageName
6622                                                + " is system level with no agent");
6623                                        mMonitor = monitorEvent(mMonitor,
6624                                                LOG_EVENT_ID_SYSTEM_APP_NO_AGENT,
6625                                                pkgInfo,
6626                                                LOG_EVENT_CATEGORY_AGENT,
6627                                                null);
6628                                    }
6629                                } else {
6630                                    if (DEBUG) Slog.i(TAG, "Restore manifest from "
6631                                            + info.packageName + " but allowBackup=false");
6632                                    mMonitor = monitorEvent(mMonitor,
6633                                            LOG_EVENT_ID_FULL_RESTORE_ALLOW_BACKUP_FALSE,
6634                                            pkgInfo,
6635                                            LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6636                                            null);
6637                                }
6638                            } catch (NameNotFoundException e) {
6639                                // Okay, the target app isn't installed.  We can process
6640                                // the restore properly only if the dataset provides the
6641                                // apk file and we can successfully install it.
6642                                if (mAllowApks) {
6643                                    if (DEBUG) Slog.i(TAG, "Package " + info.packageName
6644                                            + " not installed; requiring apk in dataset");
6645                                    policy = RestorePolicy.ACCEPT_IF_APK;
6646                                } else {
6647                                    policy = RestorePolicy.IGNORE;
6648                                }
6649                                Bundle monitoringExtras = putMonitoringExtra(null,
6650                                        EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName);
6651                                monitoringExtras = putMonitoringExtra(monitoringExtras,
6652                                        EXTRA_LOG_POLICY_ALLOW_APKS, mAllowApks);
6653                                mMonitor = monitorEvent(mMonitor,
6654                                        LOG_EVENT_ID_APK_NOT_INSTALLED,
6655                                        null,
6656                                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6657                                        monitoringExtras);
6658                            }
6659
6660                            if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
6661                                Slog.i(TAG, "Cannot restore package " + info.packageName
6662                                        + " without the matching .apk");
6663                                mMonitor = monitorEvent(mMonitor,
6664                                        LOG_EVENT_ID_CANNOT_RESTORE_WITHOUT_APK,
6665                                        null,
6666                                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6667                                        putMonitoringExtra(null,
6668                                                EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName));
6669                            }
6670                        } else {
6671                            Slog.i(TAG, "Missing signature on backed-up package "
6672                                    + info.packageName);
6673                            mMonitor = monitorEvent(mMonitor,
6674                                    LOG_EVENT_ID_MISSING_SIGNATURE,
6675                                    null,
6676                                    LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6677                                    putMonitoringExtra(null,
6678                                            EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName));
6679                        }
6680                    } else {
6681                        Slog.i(TAG, "Expected package " + info.packageName
6682                                + " but restore manifest claims " + manifestPackage);
6683                        Bundle monitoringExtras = putMonitoringExtra(null,
6684                                EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName);
6685                        monitoringExtras = putMonitoringExtra(monitoringExtras,
6686                                EXTRA_LOG_MANIFEST_PACKAGE_NAME, manifestPackage);
6687                        mMonitor = monitorEvent(mMonitor,
6688                                LOG_EVENT_ID_EXPECTED_DIFFERENT_PACKAGE,
6689                                null,
6690                                LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6691                                monitoringExtras);
6692                    }
6693                } else {
6694                    Slog.i(TAG, "Unknown restore manifest version " + version
6695                            + " for package " + info.packageName);
6696                    Bundle monitoringExtras = putMonitoringExtra(null,
6697                            EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName);
6698                    monitoringExtras = putMonitoringExtra(monitoringExtras,
6699                            EXTRA_LOG_EVENT_PACKAGE_VERSION, version);
6700                    mMonitor = monitorEvent(mMonitor,
6701                            BackupManagerMonitor.LOG_EVENT_ID_UNKNOWN_VERSION,
6702                            null,
6703                            LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6704                            monitoringExtras);
6705
6706                }
6707            } catch (NumberFormatException e) {
6708                Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
6709                mMonitor = monitorEvent(mMonitor,
6710                        BackupManagerMonitor.LOG_EVENT_ID_CORRUPT_MANIFEST,
6711                        null,
6712                        LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
6713                        putMonitoringExtra(null, EXTRA_LOG_EVENT_PACKAGE_NAME, info.packageName));
6714            } catch (IllegalArgumentException e) {
6715                Slog.w(TAG, e.getMessage());
6716            }
6717
6718            return policy;
6719        }
6720
6721        // Builds a line from a byte buffer starting at 'offset', and returns
6722        // the index of the next unconsumed data in the buffer.
6723        int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
6724            final int end = buffer.length;
6725            if (offset >= end) throw new IOException("Incomplete data");
6726
6727            int pos;
6728            for (pos = offset; pos < end; pos++) {
6729                byte c = buffer[pos];
6730                // at LF we declare end of line, and return the next char as the
6731                // starting point for the next time through
6732                if (c == '\n') {
6733                    break;
6734                }
6735            }
6736            outStr[0] = new String(buffer, offset, pos - offset);
6737            pos++;  // may be pointing an extra byte past the end but that's okay
6738            return pos;
6739        }
6740
6741        void dumpFileMetadata(FileMetadata info) {
6742            if (MORE_DEBUG) {
6743                StringBuilder b = new StringBuilder(128);
6744
6745                // mode string
6746                b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
6747                b.append(((info.mode & 0400) != 0) ? 'r' : '-');
6748                b.append(((info.mode & 0200) != 0) ? 'w' : '-');
6749                b.append(((info.mode & 0100) != 0) ? 'x' : '-');
6750                b.append(((info.mode & 0040) != 0) ? 'r' : '-');
6751                b.append(((info.mode & 0020) != 0) ? 'w' : '-');
6752                b.append(((info.mode & 0010) != 0) ? 'x' : '-');
6753                b.append(((info.mode & 0004) != 0) ? 'r' : '-');
6754                b.append(((info.mode & 0002) != 0) ? 'w' : '-');
6755                b.append(((info.mode & 0001) != 0) ? 'x' : '-');
6756                b.append(String.format(" %9d ", info.size));
6757
6758                Date stamp = new Date(info.mtime);
6759                b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp));
6760
6761                b.append(info.packageName);
6762                b.append(" :: ");
6763                b.append(info.domain);
6764                b.append(" :: ");
6765                b.append(info.path);
6766
6767                Slog.i(TAG, b.toString());
6768            }
6769        }
6770
6771        // Consume a tar file header block [sequence] and accumulate the relevant metadata
6772        FileMetadata readTarHeaders(InputStream instream) throws IOException {
6773            byte[] block = new byte[512];
6774            FileMetadata info = null;
6775
6776            boolean gotHeader = readTarHeader(instream, block);
6777            if (gotHeader) {
6778                try {
6779                    // okay, presume we're okay, and extract the various metadata
6780                    info = new FileMetadata();
6781                    info.size = extractRadix(block, TAR_HEADER_OFFSET_FILESIZE,
6782                            TAR_HEADER_LENGTH_FILESIZE, TAR_HEADER_LONG_RADIX);
6783                    info.mtime = extractRadix(block, TAR_HEADER_OFFSET_MODTIME,
6784                            TAR_HEADER_LENGTH_MODTIME, TAR_HEADER_LONG_RADIX);
6785                    info.mode = extractRadix(block, TAR_HEADER_OFFSET_MODE,
6786                            TAR_HEADER_LENGTH_MODE, TAR_HEADER_LONG_RADIX);
6787
6788                    info.path = extractString(block, TAR_HEADER_OFFSET_PATH_PREFIX,
6789                            TAR_HEADER_LENGTH_PATH_PREFIX);
6790                    String path = extractString(block, TAR_HEADER_OFFSET_PATH,
6791                            TAR_HEADER_LENGTH_PATH);
6792                    if (path.length() > 0) {
6793                        if (info.path.length() > 0) info.path += '/';
6794                        info.path += path;
6795                    }
6796
6797                    // tar link indicator field: 1 byte at offset 156 in the header.
6798                    int typeChar = block[TAR_HEADER_OFFSET_TYPE_CHAR];
6799                    if (typeChar == 'x') {
6800                        // pax extended header, so we need to read that
6801                        gotHeader = readPaxExtendedHeader(instream, info);
6802                        if (gotHeader) {
6803                            // and after a pax extended header comes another real header -- read
6804                            // that to find the real file type
6805                            gotHeader = readTarHeader(instream, block);
6806                        }
6807                        if (!gotHeader) throw new IOException("Bad or missing pax header");
6808
6809                        typeChar = block[TAR_HEADER_OFFSET_TYPE_CHAR];
6810                    }
6811
6812                    switch (typeChar) {
6813                        case '0': info.type = BackupAgent.TYPE_FILE; break;
6814                        case '5': {
6815                            info.type = BackupAgent.TYPE_DIRECTORY;
6816                            if (info.size != 0) {
6817                                Slog.w(TAG, "Directory entry with nonzero size in header");
6818                                info.size = 0;
6819                            }
6820                            break;
6821                        }
6822                        case 0: {
6823                            // presume EOF
6824                            if (MORE_DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
6825                            return null;
6826                        }
6827                        default: {
6828                            Slog.e(TAG, "Unknown tar entity type: " + typeChar);
6829                            throw new IOException("Unknown entity type " + typeChar);
6830                        }
6831                    }
6832
6833                    // Parse out the path
6834                    //
6835                    // first: apps/shared/unrecognized
6836                    if (FullBackup.SHARED_PREFIX.regionMatches(0,
6837                            info.path, 0, FullBackup.SHARED_PREFIX.length())) {
6838                        // File in shared storage.  !!! TODO: implement this.
6839                        info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
6840                        info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
6841                        info.domain = FullBackup.SHARED_STORAGE_TOKEN;
6842                        if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
6843                    } else if (FullBackup.APPS_PREFIX.regionMatches(0,
6844                            info.path, 0, FullBackup.APPS_PREFIX.length())) {
6845                        // App content!  Parse out the package name and domain
6846
6847                        // strip the apps/ prefix
6848                        info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
6849
6850                        // extract the package name
6851                        int slash = info.path.indexOf('/');
6852                        if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
6853                        info.packageName = info.path.substring(0, slash);
6854                        info.path = info.path.substring(slash+1);
6855
6856                        // if it's a manifest or metadata payload we're done, otherwise parse
6857                        // out the domain into which the file will be restored
6858                        if (!info.path.equals(BACKUP_MANIFEST_FILENAME)
6859                                && !info.path.equals(BACKUP_METADATA_FILENAME)) {
6860                            slash = info.path.indexOf('/');
6861                            if (slash < 0) {
6862                                throw new IOException("Illegal semantic path in non-manifest "
6863                                        + info.path);
6864                            }
6865                            info.domain = info.path.substring(0, slash);
6866                            info.path = info.path.substring(slash + 1);
6867                        }
6868                    }
6869                } catch (IOException e) {
6870                    if (DEBUG) {
6871                        Slog.e(TAG, "Parse error in header: " + e.getMessage());
6872                        if (MORE_DEBUG) {
6873                            HEXLOG(block);
6874                        }
6875                    }
6876                    throw e;
6877                }
6878            }
6879            return info;
6880        }
6881
6882        private boolean isRestorableFile(FileMetadata info) {
6883            if (FullBackup.CACHE_TREE_TOKEN.equals(info.domain)) {
6884                if (MORE_DEBUG) {
6885                    Slog.i(TAG, "Dropping cache file path " + info.path);
6886                }
6887                return false;
6888            }
6889
6890            if (FullBackup.ROOT_TREE_TOKEN.equals(info.domain)) {
6891                // It's possible this is "no-backup" dir contents in an archive stream
6892                // produced on a device running a version of the OS that predates that
6893                // API.  Respect the no-backup intention and don't let the data get to
6894                // the app.
6895                if (info.path.startsWith("no_backup/")) {
6896                    if (MORE_DEBUG) {
6897                        Slog.i(TAG, "Dropping no_backup file path " + info.path);
6898                    }
6899                    return false;
6900                }
6901            }
6902
6903            // The path needs to be canonical
6904            if (info.path.contains("..") || info.path.contains("//")) {
6905                if (MORE_DEBUG) {
6906                    Slog.w(TAG, "Dropping invalid path " + info.path);
6907                }
6908                return false;
6909            }
6910
6911            // Otherwise we think this file is good to go
6912            return true;
6913        }
6914
6915        private void HEXLOG(byte[] block) {
6916            int offset = 0;
6917            int todo = block.length;
6918            StringBuilder buf = new StringBuilder(64);
6919            while (todo > 0) {
6920                buf.append(String.format("%04x   ", offset));
6921                int numThisLine = (todo > 16) ? 16 : todo;
6922                for (int i = 0; i < numThisLine; i++) {
6923                    buf.append(String.format("%02x ", block[offset+i]));
6924                }
6925                Slog.i("hexdump", buf.toString());
6926                buf.setLength(0);
6927                todo -= numThisLine;
6928                offset += numThisLine;
6929            }
6930        }
6931
6932        // Read exactly the given number of bytes into a buffer at the stated offset.
6933        // Returns false if EOF is encountered before the requested number of bytes
6934        // could be read.
6935        int readExactly(InputStream in, byte[] buffer, int offset, int size)
6936                throws IOException {
6937            if (size <= 0) throw new IllegalArgumentException("size must be > 0");
6938if (MORE_DEBUG) Slog.i(TAG, "  ... readExactly(" + size + ") called");
6939            int soFar = 0;
6940            while (soFar < size) {
6941                int nRead = in.read(buffer, offset + soFar, size - soFar);
6942                if (nRead <= 0) {
6943                    if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
6944                    break;
6945                }
6946                soFar += nRead;
6947if (MORE_DEBUG) Slog.v(TAG, "   + got " + nRead + "; now wanting " + (size - soFar));
6948            }
6949            return soFar;
6950        }
6951
6952        boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
6953            final int got = readExactly(instream, block, 0, 512);
6954            if (got == 0) return false;     // Clean EOF
6955            if (got < 512) throw new IOException("Unable to read full block header");
6956            mBytes += 512;
6957            return true;
6958        }
6959
6960        // overwrites 'info' fields based on the pax extended header
6961        boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
6962                throws IOException {
6963            // We should never see a pax extended header larger than this
6964            if (info.size > 32*1024) {
6965                Slog.w(TAG, "Suspiciously large pax header size " + info.size
6966                        + " - aborting");
6967                throw new IOException("Sanity failure: pax header size " + info.size);
6968            }
6969
6970            // read whole blocks, not just the content size
6971            int numBlocks = (int)((info.size + 511) >> 9);
6972            byte[] data = new byte[numBlocks * 512];
6973            if (readExactly(instream, data, 0, data.length) < data.length) {
6974                throw new IOException("Unable to read full pax header");
6975            }
6976            mBytes += data.length;
6977
6978            final int contentSize = (int) info.size;
6979            int offset = 0;
6980            do {
6981                // extract the line at 'offset'
6982                int eol = offset+1;
6983                while (eol < contentSize && data[eol] != ' ') eol++;
6984                if (eol >= contentSize) {
6985                    // error: we just hit EOD looking for the end of the size field
6986                    throw new IOException("Invalid pax data");
6987                }
6988                // eol points to the space between the count and the key
6989                int linelen = (int) extractRadix(data, offset, eol - offset, 10);
6990                int key = eol + 1;  // start of key=value
6991                eol = offset + linelen - 1; // trailing LF
6992                int value;
6993                for (value = key+1; data[value] != '=' && value <= eol; value++);
6994                if (value > eol) {
6995                    throw new IOException("Invalid pax declaration");
6996                }
6997
6998                // pax requires that key/value strings be in UTF-8
6999                String keyStr = new String(data, key, value-key, "UTF-8");
7000                // -1 to strip the trailing LF
7001                String valStr = new String(data, value+1, eol-value-1, "UTF-8");
7002
7003                if ("path".equals(keyStr)) {
7004                    info.path = valStr;
7005                } else if ("size".equals(keyStr)) {
7006                    info.size = Long.parseLong(valStr);
7007                } else {
7008                    if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
7009                }
7010
7011                offset += linelen;
7012            } while (offset < contentSize);
7013
7014            return true;
7015        }
7016
7017        long extractRadix(byte[] data, int offset, int maxChars, int radix)
7018                throws IOException {
7019            long value = 0;
7020            final int end = offset + maxChars;
7021            for (int i = offset; i < end; i++) {
7022                final byte b = data[i];
7023                // Numeric fields in tar can terminate with either NUL or SPC
7024                if (b == 0 || b == ' ') break;
7025                if (b < '0' || b > ('0' + radix - 1)) {
7026                    throw new IOException("Invalid number in header: '" + (char)b
7027                            + "' for radix " + radix);
7028                }
7029                value = radix * value + (b - '0');
7030            }
7031            return value;
7032        }
7033
7034        String extractString(byte[] data, int offset, int maxChars) throws IOException {
7035            final int end = offset + maxChars;
7036            int eos = offset;
7037            // tar string fields terminate early with a NUL
7038            while (eos < end && data[eos] != 0) eos++;
7039            return new String(data, offset, eos-offset, "US-ASCII");
7040        }
7041
7042        void sendStartRestore() {
7043            if (mObserver != null) {
7044                try {
7045                    mObserver.onStartRestore();
7046                } catch (RemoteException e) {
7047                    Slog.w(TAG, "full restore observer went away: startRestore");
7048                    mObserver = null;
7049                }
7050            }
7051        }
7052
7053        void sendOnRestorePackage(String name) {
7054            if (mObserver != null) {
7055                try {
7056                    // TODO: use a more user-friendly name string
7057                    mObserver.onRestorePackage(name);
7058                } catch (RemoteException e) {
7059                    Slog.w(TAG, "full restore observer went away: restorePackage");
7060                    mObserver = null;
7061                }
7062            }
7063        }
7064
7065        void sendEndRestore() {
7066            if (mObserver != null) {
7067                try {
7068                    mObserver.onEndRestore();
7069                } catch (RemoteException e) {
7070                    Slog.w(TAG, "full restore observer went away: endRestore");
7071                    mObserver = null;
7072                }
7073            }
7074        }
7075    }
7076
7077    // ***** end new engine class ***
7078
7079    // Used for synchronizing doRestoreFinished during adb restore
7080    class AdbRestoreFinishedLatch implements BackupRestoreTask {
7081        static final String TAG = "AdbRestoreFinishedLatch";
7082        final CountDownLatch mLatch;
7083        private final int mCurrentOpToken;
7084
7085        AdbRestoreFinishedLatch(int currentOpToken) {
7086            mLatch = new CountDownLatch(1);
7087            mCurrentOpToken = currentOpToken;
7088        }
7089
7090        void await() {
7091            boolean latched = false;
7092            try {
7093                latched = mLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
7094            } catch (InterruptedException e) {
7095                Slog.w(TAG, "Interrupted!");
7096            }
7097        }
7098
7099        @Override
7100        public void execute() {
7101            // Unused
7102        }
7103
7104        @Override
7105        public void operationComplete(long result) {
7106            if (MORE_DEBUG) {
7107                Slog.w(TAG, "adb onRestoreFinished() complete");
7108            }
7109            mLatch.countDown();
7110            removeOperation(mCurrentOpToken);
7111        }
7112
7113        @Override
7114        public void handleCancel(boolean cancelAll) {
7115            if (DEBUG) {
7116                Slog.w(TAG, "adb onRestoreFinished() timed out");
7117            }
7118            mLatch.countDown();
7119            removeOperation(mCurrentOpToken);
7120        }
7121    }
7122
7123    class PerformAdbRestoreTask implements Runnable {
7124        ParcelFileDescriptor mInputFile;
7125        String mCurrentPassword;
7126        String mDecryptPassword;
7127        IFullBackupRestoreObserver mObserver;
7128        AtomicBoolean mLatchObject;
7129        IBackupAgent mAgent;
7130        PackageManagerBackupAgent mPackageManagerBackupAgent;
7131        String mAgentPackage;
7132        ApplicationInfo mTargetApp;
7133        FullBackupObbConnection mObbConnection = null;
7134        ParcelFileDescriptor[] mPipes = null;
7135        byte[] mWidgetData = null;
7136
7137        long mBytes;
7138
7139        // Runner that can be placed on a separate thread to do in-process invocation
7140        // of the "restore finished" API asynchronously.  Used by adb restore.
7141        class RestoreFinishedRunnable implements Runnable {
7142            final IBackupAgent mAgent;
7143            final int mToken;
7144
7145            RestoreFinishedRunnable(IBackupAgent agent, int token) {
7146                mAgent = agent;
7147                mToken = token;
7148            }
7149
7150            @Override
7151            public void run() {
7152                try {
7153                    mAgent.doRestoreFinished(mToken, mBackupManagerBinder);
7154                } catch (RemoteException e) {
7155                    // never happens; this is used only for local binder calls
7156                }
7157            }
7158        }
7159
7160        // possible handling states for a given package in the restore dataset
7161        final HashMap<String, RestorePolicy> mPackagePolicies
7162                = new HashMap<String, RestorePolicy>();
7163
7164        // installer package names for each encountered app, derived from the manifests
7165        final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
7166
7167        // Signatures for a given package found in its manifest file
7168        final HashMap<String, Signature[]> mManifestSignatures
7169                = new HashMap<String, Signature[]>();
7170
7171        // Packages we've already wiped data on when restoring their first file
7172        final HashSet<String> mClearedPackages = new HashSet<String>();
7173
7174        PerformAdbRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
7175                IFullBackupRestoreObserver observer, AtomicBoolean latch) {
7176            mInputFile = fd;
7177            mCurrentPassword = curPassword;
7178            mDecryptPassword = decryptPassword;
7179            mObserver = observer;
7180            mLatchObject = latch;
7181            mAgent = null;
7182            mPackageManagerBackupAgent = makeMetadataAgent();
7183            mAgentPackage = null;
7184            mTargetApp = null;
7185            mObbConnection = new FullBackupObbConnection();
7186
7187            // Which packages we've already wiped data on.  We prepopulate this
7188            // with a whitelist of packages known to be unclearable.
7189            mClearedPackages.add("android");
7190            mClearedPackages.add(SETTINGS_PACKAGE);
7191        }
7192
7193        class RestoreFileRunnable implements Runnable {
7194            IBackupAgent mAgent;
7195            FileMetadata mInfo;
7196            ParcelFileDescriptor mSocket;
7197            int mToken;
7198
7199            RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
7200                    ParcelFileDescriptor socket, int token) throws IOException {
7201                mAgent = agent;
7202                mInfo = info;
7203                mToken = token;
7204
7205                // This class is used strictly for process-local binder invocations.  The
7206                // semantics of ParcelFileDescriptor differ in this case; in particular, we
7207                // do not automatically get a 'dup'ed descriptor that we can can continue
7208                // to use asynchronously from the caller.  So, we make sure to dup it ourselves
7209                // before proceeding to do the restore.
7210                mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
7211            }
7212
7213            @Override
7214            public void run() {
7215                try {
7216                    mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
7217                            mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
7218                            mToken, mBackupManagerBinder);
7219                } catch (RemoteException e) {
7220                    // never happens; this is used strictly for local binder calls
7221                }
7222            }
7223        }
7224
7225        @Override
7226        public void run() {
7227            Slog.i(TAG, "--- Performing full-dataset restore ---");
7228            mObbConnection.establish();
7229            sendStartRestore();
7230
7231            // Are we able to restore shared-storage data?
7232            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
7233                mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
7234            }
7235
7236            FileInputStream rawInStream = null;
7237            DataInputStream rawDataIn = null;
7238            try {
7239                if (!backupPasswordMatches(mCurrentPassword)) {
7240                    if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
7241                    return;
7242                }
7243
7244                mBytes = 0;
7245                byte[] buffer = new byte[32 * 1024];
7246                rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
7247                rawDataIn = new DataInputStream(rawInStream);
7248
7249                // First, parse out the unencrypted/uncompressed header
7250                boolean compressed = false;
7251                InputStream preCompressStream = rawInStream;
7252                final InputStream in;
7253
7254                boolean okay = false;
7255                final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
7256                byte[] streamHeader = new byte[headerLen];
7257                rawDataIn.readFully(streamHeader);
7258                byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
7259                if (Arrays.equals(magicBytes, streamHeader)) {
7260                    // okay, header looks good.  now parse out the rest of the fields.
7261                    String s = readHeaderLine(rawInStream);
7262                    final int archiveVersion = Integer.parseInt(s);
7263                    if (archiveVersion <= BACKUP_FILE_VERSION) {
7264                        // okay, it's a version we recognize.  if it's version 1, we may need
7265                        // to try two different PBKDF2 regimes to compare checksums.
7266                        final boolean pbkdf2Fallback = (archiveVersion == 1);
7267
7268                        s = readHeaderLine(rawInStream);
7269                        compressed = (Integer.parseInt(s) != 0);
7270                        s = readHeaderLine(rawInStream);
7271                        if (s.equals("none")) {
7272                            // no more header to parse; we're good to go
7273                            okay = true;
7274                        } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
7275                            preCompressStream = decodeAesHeaderAndInitialize(s, pbkdf2Fallback,
7276                                    rawInStream);
7277                            if (preCompressStream != null) {
7278                                okay = true;
7279                            }
7280                        } else Slog.w(TAG, "Archive is encrypted but no password given");
7281                    } else Slog.w(TAG, "Wrong header version: " + s);
7282                } else Slog.w(TAG, "Didn't read the right header magic");
7283
7284                if (!okay) {
7285                    Slog.w(TAG, "Invalid restore data; aborting.");
7286                    return;
7287                }
7288
7289                // okay, use the right stream layer based on compression
7290                in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
7291
7292                boolean didRestore;
7293                do {
7294                    didRestore = restoreOneFile(in, buffer);
7295                } while (didRestore);
7296
7297                if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
7298            } catch (IOException e) {
7299                Slog.e(TAG, "Unable to read restore input");
7300            } finally {
7301                tearDownPipes();
7302                tearDownAgent(mTargetApp, true);
7303
7304                try {
7305                    if (rawDataIn != null) rawDataIn.close();
7306                    if (rawInStream != null) rawInStream.close();
7307                    mInputFile.close();
7308                } catch (IOException e) {
7309                    Slog.w(TAG, "Close of restore data pipe threw", e);
7310                    /* nothing we can do about this */
7311                }
7312                synchronized (mLatchObject) {
7313                    mLatchObject.set(true);
7314                    mLatchObject.notifyAll();
7315                }
7316                mObbConnection.tearDown();
7317                sendEndRestore();
7318                Slog.d(TAG, "Full restore pass complete.");
7319                mWakelock.release();
7320            }
7321        }
7322
7323        String readHeaderLine(InputStream in) throws IOException {
7324            int c;
7325            StringBuilder buffer = new StringBuilder(80);
7326            while ((c = in.read()) >= 0) {
7327                if (c == '\n') break;   // consume and discard the newlines
7328                buffer.append((char)c);
7329            }
7330            return buffer.toString();
7331        }
7332
7333        InputStream attemptMasterKeyDecryption(String algorithm, byte[] userSalt, byte[] ckSalt,
7334                int rounds, String userIvHex, String masterKeyBlobHex, InputStream rawInStream,
7335                boolean doLog) {
7336            InputStream result = null;
7337
7338            try {
7339                Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
7340                SecretKey userKey = buildPasswordKey(algorithm, mDecryptPassword, userSalt,
7341                        rounds);
7342                byte[] IV = hexToByteArray(userIvHex);
7343                IvParameterSpec ivSpec = new IvParameterSpec(IV);
7344                c.init(Cipher.DECRYPT_MODE,
7345                        new SecretKeySpec(userKey.getEncoded(), "AES"),
7346                        ivSpec);
7347                byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
7348                byte[] mkBlob = c.doFinal(mkCipher);
7349
7350                // first, the master key IV
7351                int offset = 0;
7352                int len = mkBlob[offset++];
7353                IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
7354                offset += len;
7355                // then the master key itself
7356                len = mkBlob[offset++];
7357                byte[] mk = Arrays.copyOfRange(mkBlob,
7358                        offset, offset + len);
7359                offset += len;
7360                // and finally the master key checksum hash
7361                len = mkBlob[offset++];
7362                byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
7363                        offset, offset + len);
7364
7365                // now validate the decrypted master key against the checksum
7366                byte[] calculatedCk = makeKeyChecksum(algorithm, mk, ckSalt, rounds);
7367                if (Arrays.equals(calculatedCk, mkChecksum)) {
7368                    ivSpec = new IvParameterSpec(IV);
7369                    c.init(Cipher.DECRYPT_MODE,
7370                            new SecretKeySpec(mk, "AES"),
7371                            ivSpec);
7372                    // Only if all of the above worked properly will 'result' be assigned
7373                    result = new CipherInputStream(rawInStream, c);
7374                } else if (doLog) Slog.w(TAG, "Incorrect password");
7375            } catch (InvalidAlgorithmParameterException e) {
7376                if (doLog) Slog.e(TAG, "Needed parameter spec unavailable!", e);
7377            } catch (BadPaddingException e) {
7378                // This case frequently occurs when the wrong password is used to decrypt
7379                // the master key.  Use the identical "incorrect password" log text as is
7380                // used in the checksum failure log in order to avoid providing additional
7381                // information to an attacker.
7382                if (doLog) Slog.w(TAG, "Incorrect password");
7383            } catch (IllegalBlockSizeException e) {
7384                if (doLog) Slog.w(TAG, "Invalid block size in master key");
7385            } catch (NoSuchAlgorithmException e) {
7386                if (doLog) Slog.e(TAG, "Needed decryption algorithm unavailable!");
7387            } catch (NoSuchPaddingException e) {
7388                if (doLog) Slog.e(TAG, "Needed padding mechanism unavailable!");
7389            } catch (InvalidKeyException e) {
7390                if (doLog) Slog.w(TAG, "Illegal password; aborting");
7391            }
7392
7393            return result;
7394        }
7395
7396        InputStream decodeAesHeaderAndInitialize(String encryptionName, boolean pbkdf2Fallback,
7397                InputStream rawInStream) {
7398            InputStream result = null;
7399            try {
7400                if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
7401
7402                    String userSaltHex = readHeaderLine(rawInStream); // 5
7403                    byte[] userSalt = hexToByteArray(userSaltHex);
7404
7405                    String ckSaltHex = readHeaderLine(rawInStream); // 6
7406                    byte[] ckSalt = hexToByteArray(ckSaltHex);
7407
7408                    int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
7409                    String userIvHex = readHeaderLine(rawInStream); // 8
7410
7411                    String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
7412
7413                    // decrypt the master key blob
7414                    result = attemptMasterKeyDecryption(PBKDF_CURRENT, userSalt, ckSalt,
7415                            rounds, userIvHex, masterKeyBlobHex, rawInStream, false);
7416                    if (result == null && pbkdf2Fallback) {
7417                        result = attemptMasterKeyDecryption(PBKDF_FALLBACK, userSalt, ckSalt,
7418                                rounds, userIvHex, masterKeyBlobHex, rawInStream, true);
7419                    }
7420                } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
7421            } catch (NumberFormatException e) {
7422                Slog.w(TAG, "Can't parse restore data header");
7423            } catch (IOException e) {
7424                Slog.w(TAG, "Can't read input header");
7425            }
7426
7427            return result;
7428        }
7429
7430        boolean restoreOneFile(InputStream instream, byte[] buffer) {
7431            FileMetadata info;
7432            try {
7433                info = readTarHeaders(instream);
7434                if (info != null) {
7435                    if (MORE_DEBUG) {
7436                        dumpFileMetadata(info);
7437                    }
7438
7439                    final String pkg = info.packageName;
7440                    if (!pkg.equals(mAgentPackage)) {
7441                        // okay, change in package; set up our various
7442                        // bookkeeping if we haven't seen it yet
7443                        if (!mPackagePolicies.containsKey(pkg)) {
7444                            mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7445                        }
7446
7447                        // Clean up the previous agent relationship if necessary,
7448                        // and let the observer know we're considering a new app.
7449                        if (mAgent != null) {
7450                            if (DEBUG) Slog.d(TAG, "Saw new package; finalizing old one");
7451                            // Now we're really done
7452                            tearDownPipes();
7453                            tearDownAgent(mTargetApp, true);
7454                            mTargetApp = null;
7455                            mAgentPackage = null;
7456                        }
7457                    }
7458
7459                    if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
7460                        mPackagePolicies.put(pkg, readAppManifest(info, instream));
7461                        mPackageInstallers.put(pkg, info.installerPackageName);
7462                        // We've read only the manifest content itself at this point,
7463                        // so consume the footer before looping around to the next
7464                        // input file
7465                        skipTarPadding(info.size, instream);
7466                        sendOnRestorePackage(pkg);
7467                    } else if (info.path.equals(BACKUP_METADATA_FILENAME)) {
7468                        // Metadata blobs!
7469                        readMetadata(info, instream);
7470                        skipTarPadding(info.size, instream);
7471                    } else {
7472                        // Non-manifest, so it's actual file data.  Is this a package
7473                        // we're ignoring?
7474                        boolean okay = true;
7475                        RestorePolicy policy = mPackagePolicies.get(pkg);
7476                        switch (policy) {
7477                            case IGNORE:
7478                                okay = false;
7479                                break;
7480
7481                            case ACCEPT_IF_APK:
7482                                // If we're in accept-if-apk state, then the first file we
7483                                // see MUST be the apk.
7484                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
7485                                    if (DEBUG) Slog.d(TAG, "APK file; installing");
7486                                    // Try to install the app.
7487                                    String installerName = mPackageInstallers.get(pkg);
7488                                    okay = installApk(info, installerName, instream);
7489                                    // good to go; promote to ACCEPT
7490                                    mPackagePolicies.put(pkg, (okay)
7491                                            ? RestorePolicy.ACCEPT
7492                                            : RestorePolicy.IGNORE);
7493                                    // At this point we've consumed this file entry
7494                                    // ourselves, so just strip the tar footer and
7495                                    // go on to the next file in the input stream
7496                                    skipTarPadding(info.size, instream);
7497                                    return true;
7498                                } else {
7499                                    // File data before (or without) the apk.  We can't
7500                                    // handle it coherently in this case so ignore it.
7501                                    mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7502                                    okay = false;
7503                                }
7504                                break;
7505
7506                            case ACCEPT:
7507                                if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
7508                                    if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
7509                                    // we can take the data without the apk, so we
7510                                    // *want* to do so.  skip the apk by declaring this
7511                                    // one file not-okay without changing the restore
7512                                    // policy for the package.
7513                                    okay = false;
7514                                }
7515                                break;
7516
7517                            default:
7518                                // Something has gone dreadfully wrong when determining
7519                                // the restore policy from the manifest.  Ignore the
7520                                // rest of this package's data.
7521                                Slog.e(TAG, "Invalid policy from manifest");
7522                                okay = false;
7523                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7524                                break;
7525                        }
7526
7527                        // The path needs to be canonical
7528                        if (info.path.contains("..") || info.path.contains("//")) {
7529                            if (MORE_DEBUG) {
7530                                Slog.w(TAG, "Dropping invalid path " + info.path);
7531                            }
7532                            okay = false;
7533                        }
7534
7535                        // If the policy is satisfied, go ahead and set up to pipe the
7536                        // data to the agent.
7537                        if (DEBUG && okay && mAgent != null) {
7538                            Slog.i(TAG, "Reusing existing agent instance");
7539                        }
7540                        if (okay && mAgent == null) {
7541                            if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
7542
7543                            try {
7544                                mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
7545
7546                                // If we haven't sent any data to this app yet, we probably
7547                                // need to clear it first.  Check that.
7548                                if (!mClearedPackages.contains(pkg)) {
7549                                    // apps with their own backup agents are
7550                                    // responsible for coherently managing a full
7551                                    // restore.
7552                                    if (mTargetApp.backupAgentName == null) {
7553                                        if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
7554                                        clearApplicationDataSynchronous(pkg);
7555                                    } else {
7556                                        if (DEBUG) Slog.d(TAG, "backup agent ("
7557                                                + mTargetApp.backupAgentName + ") => no clear");
7558                                    }
7559                                    mClearedPackages.add(pkg);
7560                                } else {
7561                                    if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
7562                                }
7563
7564                                // All set; now set up the IPC and launch the agent
7565                                setUpPipes();
7566                                mAgent = bindToAgentSynchronous(mTargetApp,
7567                                        ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL);
7568                                mAgentPackage = pkg;
7569                            } catch (IOException e) {
7570                                // fall through to error handling
7571                            } catch (NameNotFoundException e) {
7572                                // fall through to error handling
7573                            }
7574
7575                            if (mAgent == null) {
7576                                if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
7577                                okay = false;
7578                                tearDownPipes();
7579                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7580                            }
7581                        }
7582
7583                        // Sanity check: make sure we never give data to the wrong app.  This
7584                        // should never happen but a little paranoia here won't go amiss.
7585                        if (okay && !pkg.equals(mAgentPackage)) {
7586                            Slog.e(TAG, "Restoring data for " + pkg
7587                                    + " but agent is for " + mAgentPackage);
7588                            okay = false;
7589                        }
7590
7591                        // At this point we have an agent ready to handle the full
7592                        // restore data as well as a pipe for sending data to
7593                        // that agent.  Tell the agent to start reading from the
7594                        // pipe.
7595                        if (okay) {
7596                            boolean agentSuccess = true;
7597                            long toCopy = info.size;
7598                            final boolean isSharedStorage = pkg.equals(SHARED_BACKUP_AGENT_PACKAGE);
7599                            final long timeout = isSharedStorage ?
7600                                    TIMEOUT_SHARED_BACKUP_INTERVAL : TIMEOUT_RESTORE_INTERVAL;
7601                            final int token = generateRandomIntegerToken();
7602                            try {
7603                                prepareOperationTimeout(token, timeout, null,
7604                                        OP_TYPE_RESTORE_WAIT);
7605                                if (FullBackup.OBB_TREE_TOKEN.equals(info.domain)) {
7606                                    if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg
7607                                            + " : " + info.path);
7608                                    mObbConnection.restoreObbFile(pkg, mPipes[0],
7609                                            info.size, info.type, info.path, info.mode,
7610                                            info.mtime, token, mBackupManagerBinder);
7611                                } else if (FullBackup.KEY_VALUE_DATA_TOKEN.equals(info.domain)) {
7612                                    if (DEBUG) Slog.d(TAG, "Restoring key-value file for " + pkg
7613                                            + " : " + info.path);
7614                                    KeyValueAdbRestoreEngine restoreEngine =
7615                                            new KeyValueAdbRestoreEngine(BackupManagerService.this,
7616                                                    mDataDir, info, mPipes[0], mAgent, token);
7617                                    new Thread(restoreEngine, "restore-key-value-runner").start();
7618                                } else {
7619                                    if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
7620                                            + info.path);
7621                                    // fire up the app's agent listening on the socket.  If
7622                                    // the agent is running in the system process we can't
7623                                    // just invoke it asynchronously, so we provide a thread
7624                                    // for it here.
7625                                    if (mTargetApp.processName.equals("system")) {
7626                                        Slog.d(TAG, "system process agent - spinning a thread");
7627                                        RestoreFileRunnable runner = new RestoreFileRunnable(
7628                                                mAgent, info, mPipes[0], token);
7629                                        new Thread(runner, "restore-sys-runner").start();
7630                                    } else {
7631                                        mAgent.doRestoreFile(mPipes[0], info.size, info.type,
7632                                                info.domain, info.path, info.mode, info.mtime,
7633                                                token, mBackupManagerBinder);
7634                                    }
7635                                }
7636                            } catch (IOException e) {
7637                                // couldn't dup the socket for a process-local restore
7638                                Slog.d(TAG, "Couldn't establish restore");
7639                                agentSuccess = false;
7640                                okay = false;
7641                            } catch (RemoteException e) {
7642                                // whoops, remote entity went away.  We'll eat the content
7643                                // ourselves, then, and not copy it over.
7644                                Slog.e(TAG, "Agent crashed during full restore");
7645                                agentSuccess = false;
7646                                okay = false;
7647                            }
7648
7649                            // Copy over the data if the agent is still good
7650                            if (okay) {
7651                                boolean pipeOkay = true;
7652                                FileOutputStream pipe = new FileOutputStream(
7653                                        mPipes[1].getFileDescriptor());
7654                                while (toCopy > 0) {
7655                                    int toRead = (toCopy > buffer.length)
7656                                    ? buffer.length : (int)toCopy;
7657                                    int nRead = instream.read(buffer, 0, toRead);
7658                                    if (nRead >= 0) mBytes += nRead;
7659                                    if (nRead <= 0) break;
7660                                    toCopy -= nRead;
7661
7662                                    // send it to the output pipe as long as things
7663                                    // are still good
7664                                    if (pipeOkay) {
7665                                        try {
7666                                            pipe.write(buffer, 0, nRead);
7667                                        } catch (IOException e) {
7668                                            Slog.e(TAG, "Failed to write to restore pipe", e);
7669                                            pipeOkay = false;
7670                                        }
7671                                    }
7672                                }
7673
7674                                // done sending that file!  Now we just need to consume
7675                                // the delta from info.size to the end of block.
7676                                skipTarPadding(info.size, instream);
7677
7678                                // and now that we've sent it all, wait for the remote
7679                                // side to acknowledge receipt
7680                                agentSuccess = waitUntilOperationComplete(token);
7681                            }
7682
7683                            // okay, if the remote end failed at any point, deal with
7684                            // it by ignoring the rest of the restore on it
7685                            if (!agentSuccess) {
7686                                if (DEBUG) {
7687                                    Slog.d(TAG, "Agent failure restoring " + pkg + "; now ignoring");
7688                                }
7689                                mBackupHandler.removeMessages(MSG_RESTORE_OPERATION_TIMEOUT);
7690                                tearDownPipes();
7691                                tearDownAgent(mTargetApp, false);
7692                                mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
7693                            }
7694                        }
7695
7696                        // Problems setting up the agent communication, or an already-
7697                        // ignored package: skip to the next tar stream entry by
7698                        // reading and discarding this file.
7699                        if (!okay) {
7700                            if (DEBUG) Slog.d(TAG, "[discarding file content]");
7701                            long bytesToConsume = (info.size + 511) & ~511;
7702                            while (bytesToConsume > 0) {
7703                                int toRead = (bytesToConsume > buffer.length)
7704                                ? buffer.length : (int)bytesToConsume;
7705                                long nRead = instream.read(buffer, 0, toRead);
7706                                if (nRead >= 0) mBytes += nRead;
7707                                if (nRead <= 0) break;
7708                                bytesToConsume -= nRead;
7709                            }
7710                        }
7711                    }
7712                }
7713            } catch (IOException e) {
7714                if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
7715                // treat as EOF
7716                info = null;
7717            }
7718
7719            return (info != null);
7720        }
7721
7722        void setUpPipes() throws IOException {
7723            mPipes = ParcelFileDescriptor.createPipe();
7724        }
7725
7726        void tearDownPipes() {
7727            if (mPipes != null) {
7728                try {
7729                    mPipes[0].close();
7730                    mPipes[0] = null;
7731                    mPipes[1].close();
7732                    mPipes[1] = null;
7733                } catch (IOException e) {
7734                    Slog.w(TAG, "Couldn't close agent pipes", e);
7735                }
7736                mPipes = null;
7737            }
7738        }
7739
7740        void tearDownAgent(ApplicationInfo app, boolean doRestoreFinished) {
7741            if (mAgent != null) {
7742                try {
7743                    // In the adb restore case, we do restore-finished here
7744                    if (doRestoreFinished) {
7745                        final int token = generateRandomIntegerToken();
7746                        final AdbRestoreFinishedLatch latch = new AdbRestoreFinishedLatch(token);
7747                        prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, latch,
7748                                OP_TYPE_RESTORE_WAIT);
7749                        if (mTargetApp.processName.equals("system")) {
7750                            if (MORE_DEBUG) {
7751                                Slog.d(TAG, "system agent - restoreFinished on thread");
7752                            }
7753                            Runnable runner = new RestoreFinishedRunnable(mAgent, token);
7754                            new Thread(runner, "restore-sys-finished-runner").start();
7755                        } else {
7756                            mAgent.doRestoreFinished(token, mBackupManagerBinder);
7757                        }
7758
7759                        latch.await();
7760                    }
7761
7762                    // unbind and tidy up even on timeout or failure, just in case
7763                    mActivityManager.unbindBackupAgent(app);
7764
7765                    // The agent was running with a stub Application object, so shut it down.
7766                    // !!! We hardcode the confirmation UI's package name here rather than use a
7767                    //     manifest flag!  TODO something less direct.
7768                    if (app.uid >= Process.FIRST_APPLICATION_UID
7769                            && !app.packageName.equals("com.android.backupconfirm")) {
7770                        if (DEBUG) Slog.d(TAG, "Killing host process");
7771                        mActivityManager.killApplicationProcess(app.processName, app.uid);
7772                    } else {
7773                        if (DEBUG) Slog.d(TAG, "Not killing after full restore");
7774                    }
7775                } catch (RemoteException e) {
7776                    Slog.d(TAG, "Lost app trying to shut down");
7777                }
7778                mAgent = null;
7779            }
7780        }
7781
7782        class RestoreInstallObserver extends PackageInstallObserver {
7783            final AtomicBoolean mDone = new AtomicBoolean();
7784            String mPackageName;
7785            int mResult;
7786
7787            public void reset() {
7788                synchronized (mDone) {
7789                    mDone.set(false);
7790                }
7791            }
7792
7793            public void waitForCompletion() {
7794                synchronized (mDone) {
7795                    while (mDone.get() == false) {
7796                        try {
7797                            mDone.wait();
7798                        } catch (InterruptedException e) { }
7799                    }
7800                }
7801            }
7802
7803            int getResult() {
7804                return mResult;
7805            }
7806
7807            @Override
7808            public void onPackageInstalled(String packageName, int returnCode,
7809                    String msg, Bundle extras) {
7810                synchronized (mDone) {
7811                    mResult = returnCode;
7812                    mPackageName = packageName;
7813                    mDone.set(true);
7814                    mDone.notifyAll();
7815                }
7816            }
7817        }
7818
7819        class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
7820            final AtomicBoolean mDone = new AtomicBoolean();
7821            int mResult;
7822
7823            public void reset() {
7824                synchronized (mDone) {
7825                    mDone.set(false);
7826                }
7827            }
7828
7829            public void waitForCompletion() {
7830                synchronized (mDone) {
7831                    while (mDone.get() == false) {
7832                        try {
7833                            mDone.wait();
7834                        } catch (InterruptedException e) { }
7835                    }
7836                }
7837            }
7838
7839            @Override
7840            public void packageDeleted(String packageName, int returnCode) throws RemoteException {
7841                synchronized (mDone) {
7842                    mResult = returnCode;
7843                    mDone.set(true);
7844                    mDone.notifyAll();
7845                }
7846            }
7847        }
7848
7849        final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
7850        final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
7851
7852        boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
7853            boolean okay = true;
7854
7855            if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
7856
7857            // The file content is an .apk file.  Copy it out to a staging location and
7858            // attempt to install it.
7859            File apkFile = new File(mDataDir, info.packageName);
7860            try {
7861                FileOutputStream apkStream = new FileOutputStream(apkFile);
7862                byte[] buffer = new byte[32 * 1024];
7863                long size = info.size;
7864                while (size > 0) {
7865                    long toRead = (buffer.length < size) ? buffer.length : size;
7866                    int didRead = instream.read(buffer, 0, (int)toRead);
7867                    if (didRead >= 0) mBytes += didRead;
7868                    apkStream.write(buffer, 0, didRead);
7869                    size -= didRead;
7870                }
7871                apkStream.close();
7872
7873                // make sure the installer can read it
7874                apkFile.setReadable(true, false);
7875
7876                // Now install it
7877                Uri packageUri = Uri.fromFile(apkFile);
7878                mInstallObserver.reset();
7879                mPackageManager.installPackage(packageUri, mInstallObserver,
7880                        PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
7881                        installerPackage);
7882                mInstallObserver.waitForCompletion();
7883
7884                if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
7885                    // The only time we continue to accept install of data even if the
7886                    // apk install failed is if we had already determined that we could
7887                    // accept the data regardless.
7888                    if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
7889                        okay = false;
7890                    }
7891                } else {
7892                    // Okay, the install succeeded.  Make sure it was the right app.
7893                    boolean uninstall = false;
7894                    if (!mInstallObserver.mPackageName.equals(info.packageName)) {
7895                        Slog.w(TAG, "Restore stream claimed to include apk for "
7896                                + info.packageName + " but apk was really "
7897                                + mInstallObserver.mPackageName);
7898                        // delete the package we just put in place; it might be fraudulent
7899                        okay = false;
7900                        uninstall = true;
7901                    } else {
7902                        try {
7903                            PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
7904                                    PackageManager.GET_SIGNATURES);
7905                            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
7906                                Slog.w(TAG, "Restore stream contains apk of package "
7907                                        + info.packageName + " but it disallows backup/restore");
7908                                okay = false;
7909                            } else {
7910                                // So far so good -- do the signatures match the manifest?
7911                                Signature[] sigs = mManifestSignatures.get(info.packageName);
7912                                if (signaturesMatch(sigs, pkg)) {
7913                                    // If this is a system-uid app without a declared backup agent,
7914                                    // don't restore any of the file data.
7915                                    if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID)
7916                                            && (pkg.applicationInfo.backupAgentName == null)) {
7917                                        Slog.w(TAG, "Installed app " + info.packageName
7918                                                + " has restricted uid and no agent");
7919                                        okay = false;
7920                                    }
7921                                } else {
7922                                    Slog.w(TAG, "Installed app " + info.packageName
7923                                            + " signatures do not match restore manifest");
7924                                    okay = false;
7925                                    uninstall = true;
7926                                }
7927                            }
7928                        } catch (NameNotFoundException e) {
7929                            Slog.w(TAG, "Install of package " + info.packageName
7930                                    + " succeeded but now not found");
7931                            okay = false;
7932                        }
7933                    }
7934
7935                    // If we're not okay at this point, we need to delete the package
7936                    // that we just installed.
7937                    if (uninstall) {
7938                        mDeleteObserver.reset();
7939                        mPackageManager.deletePackage(mInstallObserver.mPackageName,
7940                                mDeleteObserver, 0);
7941                        mDeleteObserver.waitForCompletion();
7942                    }
7943                }
7944            } catch (IOException e) {
7945                Slog.e(TAG, "Unable to transcribe restored apk for install");
7946                okay = false;
7947            } finally {
7948                apkFile.delete();
7949            }
7950
7951            return okay;
7952        }
7953
7954        // Given an actual file content size, consume the post-content padding mandated
7955        // by the tar format.
7956        void skipTarPadding(long size, InputStream instream) throws IOException {
7957            long partial = (size + 512) % 512;
7958            if (partial > 0) {
7959                final int needed = 512 - (int)partial;
7960                byte[] buffer = new byte[needed];
7961                if (readExactly(instream, buffer, 0, needed) == needed) {
7962                    mBytes += needed;
7963                } else throw new IOException("Unexpected EOF in padding");
7964            }
7965        }
7966
7967        // Read a widget metadata file, returning the restored blob
7968        void readMetadata(FileMetadata info, InputStream instream) throws IOException {
7969            // Fail on suspiciously large widget dump files
7970            if (info.size > 64 * 1024) {
7971                throw new IOException("Metadata too big; corrupt? size=" + info.size);
7972            }
7973
7974            byte[] buffer = new byte[(int) info.size];
7975            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
7976                mBytes += info.size;
7977            } else throw new IOException("Unexpected EOF in widget data");
7978
7979            String[] str = new String[1];
7980            int offset = extractLine(buffer, 0, str);
7981            int version = Integer.parseInt(str[0]);
7982            if (version == BACKUP_MANIFEST_VERSION) {
7983                offset = extractLine(buffer, offset, str);
7984                final String pkg = str[0];
7985                if (info.packageName.equals(pkg)) {
7986                    // Data checks out -- the rest of the buffer is a concatenation of
7987                    // binary blobs as described in the comment at writeAppWidgetData()
7988                    ByteArrayInputStream bin = new ByteArrayInputStream(buffer,
7989                            offset, buffer.length - offset);
7990                    DataInputStream in = new DataInputStream(bin);
7991                    while (bin.available() > 0) {
7992                        int token = in.readInt();
7993                        int size = in.readInt();
7994                        if (size > 64 * 1024) {
7995                            throw new IOException("Datum "
7996                                    + Integer.toHexString(token)
7997                                    + " too big; corrupt? size=" + info.size);
7998                        }
7999                        switch (token) {
8000                            case BACKUP_WIDGET_METADATA_TOKEN:
8001                            {
8002                                if (MORE_DEBUG) {
8003                                    Slog.i(TAG, "Got widget metadata for " + info.packageName);
8004                                }
8005                                mWidgetData = new byte[size];
8006                                in.read(mWidgetData);
8007                                break;
8008                            }
8009                            default:
8010                            {
8011                                if (DEBUG) {
8012                                    Slog.i(TAG, "Ignoring metadata blob "
8013                                            + Integer.toHexString(token)
8014                                            + " for " + info.packageName);
8015                                }
8016                                in.skipBytes(size);
8017                                break;
8018                            }
8019                        }
8020                    }
8021                } else {
8022                    Slog.w(TAG, "Metadata mismatch: package " + info.packageName
8023                            + " but widget data for " + pkg);
8024                }
8025            } else {
8026                Slog.w(TAG, "Unsupported metadata version " + version);
8027            }
8028        }
8029
8030        // Returns a policy constant; takes a buffer arg to reduce memory churn
8031        RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
8032                throws IOException {
8033            // Fail on suspiciously large manifest files
8034            if (info.size > 64 * 1024) {
8035                throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
8036            }
8037
8038            byte[] buffer = new byte[(int) info.size];
8039            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
8040                mBytes += info.size;
8041            } else throw new IOException("Unexpected EOF in manifest");
8042
8043            RestorePolicy policy = RestorePolicy.IGNORE;
8044            String[] str = new String[1];
8045            int offset = 0;
8046
8047            try {
8048                offset = extractLine(buffer, offset, str);
8049                int version = Integer.parseInt(str[0]);
8050                if (version == BACKUP_MANIFEST_VERSION) {
8051                    offset = extractLine(buffer, offset, str);
8052                    String manifestPackage = str[0];
8053                    // TODO: handle <original-package>
8054                    if (manifestPackage.equals(info.packageName)) {
8055                        offset = extractLine(buffer, offset, str);
8056                        version = Integer.parseInt(str[0]);  // app version
8057                        offset = extractLine(buffer, offset, str);
8058                        // This is the platform version, which we don't use, but we parse it
8059                        // as a safety against corruption in the manifest.
8060                        Integer.parseInt(str[0]);
8061                        offset = extractLine(buffer, offset, str);
8062                        info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
8063                        offset = extractLine(buffer, offset, str);
8064                        boolean hasApk = str[0].equals("1");
8065                        offset = extractLine(buffer, offset, str);
8066                        int numSigs = Integer.parseInt(str[0]);
8067                        if (numSigs > 0) {
8068                            Signature[] sigs = new Signature[numSigs];
8069                            for (int i = 0; i < numSigs; i++) {
8070                                offset = extractLine(buffer, offset, str);
8071                                sigs[i] = new Signature(str[0]);
8072                            }
8073                            mManifestSignatures.put(info.packageName, sigs);
8074
8075                            // Okay, got the manifest info we need...
8076                            try {
8077                                PackageInfo pkgInfo = mPackageManager.getPackageInfo(
8078                                        info.packageName, PackageManager.GET_SIGNATURES);
8079                                // Fall through to IGNORE if the app explicitly disallows backup
8080                                final int flags = pkgInfo.applicationInfo.flags;
8081                                if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
8082                                    // Restore system-uid-space packages only if they have
8083                                    // defined a custom backup agent
8084                                    if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
8085                                            || (pkgInfo.applicationInfo.backupAgentName != null)) {
8086                                        // Verify signatures against any installed version; if they
8087                                        // don't match, then we fall though and ignore the data.  The
8088                                        // signatureMatch() method explicitly ignores the signature
8089                                        // check for packages installed on the system partition, because
8090                                        // such packages are signed with the platform cert instead of
8091                                        // the app developer's cert, so they're different on every
8092                                        // device.
8093                                        if (signaturesMatch(sigs, pkgInfo)) {
8094                                            if ((pkgInfo.applicationInfo.flags
8095                                                    & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) != 0) {
8096                                                Slog.i(TAG, "Package has restoreAnyVersion; taking data");
8097                                                policy = RestorePolicy.ACCEPT;
8098                                            } else if (pkgInfo.versionCode >= version) {
8099                                                Slog.i(TAG, "Sig + version match; taking data");
8100                                                policy = RestorePolicy.ACCEPT;
8101                                            } else {
8102                                                // The data is from a newer version of the app than
8103                                                // is presently installed.  That means we can only
8104                                                // use it if the matching apk is also supplied.
8105                                                Slog.d(TAG, "Data version " + version
8106                                                        + " is newer than installed version "
8107                                                        + pkgInfo.versionCode + " - requiring apk");
8108                                                policy = RestorePolicy.ACCEPT_IF_APK;
8109                                            }
8110                                        } else {
8111                                            Slog.w(TAG, "Restore manifest signatures do not match "
8112                                                    + "installed application for " + info.packageName);
8113                                        }
8114                                    } else {
8115                                        Slog.w(TAG, "Package " + info.packageName
8116                                                + " is system level with no agent");
8117                                    }
8118                                } else {
8119                                    if (DEBUG) Slog.i(TAG, "Restore manifest from "
8120                                            + info.packageName + " but allowBackup=false");
8121                                }
8122                            } catch (NameNotFoundException e) {
8123                                // Okay, the target app isn't installed.  We can process
8124                                // the restore properly only if the dataset provides the
8125                                // apk file and we can successfully install it.
8126                                if (DEBUG) Slog.i(TAG, "Package " + info.packageName
8127                                        + " not installed; requiring apk in dataset");
8128                                policy = RestorePolicy.ACCEPT_IF_APK;
8129                            }
8130
8131                            if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
8132                                Slog.i(TAG, "Cannot restore package " + info.packageName
8133                                        + " without the matching .apk");
8134                            }
8135                        } else {
8136                            Slog.i(TAG, "Missing signature on backed-up package "
8137                                    + info.packageName);
8138                        }
8139                    } else {
8140                        Slog.i(TAG, "Expected package " + info.packageName
8141                                + " but restore manifest claims " + manifestPackage);
8142                    }
8143                } else {
8144                    Slog.i(TAG, "Unknown restore manifest version " + version
8145                            + " for package " + info.packageName);
8146                }
8147            } catch (NumberFormatException e) {
8148                Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
8149            } catch (IllegalArgumentException e) {
8150                Slog.w(TAG, e.getMessage());
8151            }
8152
8153            return policy;
8154        }
8155
8156        // Builds a line from a byte buffer starting at 'offset', and returns
8157        // the index of the next unconsumed data in the buffer.
8158        int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
8159            final int end = buffer.length;
8160            if (offset >= end) throw new IOException("Incomplete data");
8161
8162            int pos;
8163            for (pos = offset; pos < end; pos++) {
8164                byte c = buffer[pos];
8165                // at LF we declare end of line, and return the next char as the
8166                // starting point for the next time through
8167                if (c == '\n') {
8168                    break;
8169                }
8170            }
8171            outStr[0] = new String(buffer, offset, pos - offset);
8172            pos++;  // may be pointing an extra byte past the end but that's okay
8173            return pos;
8174        }
8175
8176        void dumpFileMetadata(FileMetadata info) {
8177            if (DEBUG) {
8178                StringBuilder b = new StringBuilder(128);
8179
8180                // mode string
8181                b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
8182                b.append(((info.mode & 0400) != 0) ? 'r' : '-');
8183                b.append(((info.mode & 0200) != 0) ? 'w' : '-');
8184                b.append(((info.mode & 0100) != 0) ? 'x' : '-');
8185                b.append(((info.mode & 0040) != 0) ? 'r' : '-');
8186                b.append(((info.mode & 0020) != 0) ? 'w' : '-');
8187                b.append(((info.mode & 0010) != 0) ? 'x' : '-');
8188                b.append(((info.mode & 0004) != 0) ? 'r' : '-');
8189                b.append(((info.mode & 0002) != 0) ? 'w' : '-');
8190                b.append(((info.mode & 0001) != 0) ? 'x' : '-');
8191                b.append(String.format(" %9d ", info.size));
8192
8193                Date stamp = new Date(info.mtime);
8194                b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp));
8195
8196                b.append(info.packageName);
8197                b.append(" :: ");
8198                b.append(info.domain);
8199                b.append(" :: ");
8200                b.append(info.path);
8201
8202                Slog.i(TAG, b.toString());
8203            }
8204        }
8205
8206        // Consume a tar file header block [sequence] and accumulate the relevant metadata
8207        FileMetadata readTarHeaders(InputStream instream) throws IOException {
8208            byte[] block = new byte[512];
8209            FileMetadata info = null;
8210
8211            boolean gotHeader = readTarHeader(instream, block);
8212            if (gotHeader) {
8213                try {
8214                    // okay, presume we're okay, and extract the various metadata
8215                    info = new FileMetadata();
8216                    info.size = extractRadix(block, 124, 12, 8);
8217                    info.mtime = extractRadix(block, 136, 12, 8);
8218                    info.mode = extractRadix(block, 100, 8, 8);
8219
8220                    info.path = extractString(block, 345, 155); // prefix
8221                    String path = extractString(block, 0, 100);
8222                    if (path.length() > 0) {
8223                        if (info.path.length() > 0) info.path += '/';
8224                        info.path += path;
8225                    }
8226
8227                    // tar link indicator field: 1 byte at offset 156 in the header.
8228                    int typeChar = block[156];
8229                    if (typeChar == 'x') {
8230                        // pax extended header, so we need to read that
8231                        gotHeader = readPaxExtendedHeader(instream, info);
8232                        if (gotHeader) {
8233                            // and after a pax extended header comes another real header -- read
8234                            // that to find the real file type
8235                            gotHeader = readTarHeader(instream, block);
8236                        }
8237                        if (!gotHeader) throw new IOException("Bad or missing pax header");
8238
8239                        typeChar = block[156];
8240                    }
8241
8242                    switch (typeChar) {
8243                        case '0': info.type = BackupAgent.TYPE_FILE; break;
8244                        case '5': {
8245                            info.type = BackupAgent.TYPE_DIRECTORY;
8246                            if (info.size != 0) {
8247                                Slog.w(TAG, "Directory entry with nonzero size in header");
8248                                info.size = 0;
8249                            }
8250                            break;
8251                        }
8252                        case 0: {
8253                            // presume EOF
8254                            if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
8255                            return null;
8256                        }
8257                        default: {
8258                            Slog.e(TAG, "Unknown tar entity type: " + typeChar);
8259                            throw new IOException("Unknown entity type " + typeChar);
8260                        }
8261                    }
8262
8263                    // Parse out the path
8264                    //
8265                    // first: apps/shared/unrecognized
8266                    if (FullBackup.SHARED_PREFIX.regionMatches(0,
8267                            info.path, 0, FullBackup.SHARED_PREFIX.length())) {
8268                        // File in shared storage.  !!! TODO: implement this.
8269                        info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
8270                        info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
8271                        info.domain = FullBackup.SHARED_STORAGE_TOKEN;
8272                        if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
8273                    } else if (FullBackup.APPS_PREFIX.regionMatches(0,
8274                            info.path, 0, FullBackup.APPS_PREFIX.length())) {
8275                        // App content!  Parse out the package name and domain
8276
8277                        // strip the apps/ prefix
8278                        info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
8279
8280                        // extract the package name
8281                        int slash = info.path.indexOf('/');
8282                        if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
8283                        info.packageName = info.path.substring(0, slash);
8284                        info.path = info.path.substring(slash+1);
8285
8286                        // if it's a manifest or metadata payload we're done, otherwise parse
8287                        // out the domain into which the file will be restored
8288                        if (!info.path.equals(BACKUP_MANIFEST_FILENAME)
8289                                && !info.path.equals(BACKUP_METADATA_FILENAME)) {
8290                            slash = info.path.indexOf('/');
8291                            if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
8292                            info.domain = info.path.substring(0, slash);
8293                            info.path = info.path.substring(slash + 1);
8294                        }
8295                    }
8296                } catch (IOException e) {
8297                    if (DEBUG) {
8298                        Slog.e(TAG, "Parse error in header: " + e.getMessage());
8299                        HEXLOG(block);
8300                    }
8301                    throw e;
8302                }
8303            }
8304            return info;
8305        }
8306
8307        private void HEXLOG(byte[] block) {
8308            int offset = 0;
8309            int todo = block.length;
8310            StringBuilder buf = new StringBuilder(64);
8311            while (todo > 0) {
8312                buf.append(String.format("%04x   ", offset));
8313                int numThisLine = (todo > 16) ? 16 : todo;
8314                for (int i = 0; i < numThisLine; i++) {
8315                    buf.append(String.format("%02x ", block[offset+i]));
8316                }
8317                Slog.i("hexdump", buf.toString());
8318                buf.setLength(0);
8319                todo -= numThisLine;
8320                offset += numThisLine;
8321            }
8322        }
8323
8324        // Read exactly the given number of bytes into a buffer at the stated offset.
8325        // Returns false if EOF is encountered before the requested number of bytes
8326        // could be read.
8327        int readExactly(InputStream in, byte[] buffer, int offset, int size)
8328                throws IOException {
8329            if (size <= 0) throw new IllegalArgumentException("size must be > 0");
8330
8331            int soFar = 0;
8332            while (soFar < size) {
8333                int nRead = in.read(buffer, offset + soFar, size - soFar);
8334                if (nRead <= 0) {
8335                    if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
8336                    break;
8337                }
8338                soFar += nRead;
8339            }
8340            return soFar;
8341        }
8342
8343        boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
8344            final int got = readExactly(instream, block, 0, 512);
8345            if (got == 0) return false;     // Clean EOF
8346            if (got < 512) throw new IOException("Unable to read full block header");
8347            mBytes += 512;
8348            return true;
8349        }
8350
8351        // overwrites 'info' fields based on the pax extended header
8352        boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
8353                throws IOException {
8354            // We should never see a pax extended header larger than this
8355            if (info.size > 32*1024) {
8356                Slog.w(TAG, "Suspiciously large pax header size " + info.size
8357                        + " - aborting");
8358                throw new IOException("Sanity failure: pax header size " + info.size);
8359            }
8360
8361            // read whole blocks, not just the content size
8362            int numBlocks = (int)((info.size + 511) >> 9);
8363            byte[] data = new byte[numBlocks * 512];
8364            if (readExactly(instream, data, 0, data.length) < data.length) {
8365                throw new IOException("Unable to read full pax header");
8366            }
8367            mBytes += data.length;
8368
8369            final int contentSize = (int) info.size;
8370            int offset = 0;
8371            do {
8372                // extract the line at 'offset'
8373                int eol = offset+1;
8374                while (eol < contentSize && data[eol] != ' ') eol++;
8375                if (eol >= contentSize) {
8376                    // error: we just hit EOD looking for the end of the size field
8377                    throw new IOException("Invalid pax data");
8378                }
8379                // eol points to the space between the count and the key
8380                int linelen = (int) extractRadix(data, offset, eol - offset, 10);
8381                int key = eol + 1;  // start of key=value
8382                eol = offset + linelen - 1; // trailing LF
8383                int value;
8384                for (value = key+1; data[value] != '=' && value <= eol; value++);
8385                if (value > eol) {
8386                    throw new IOException("Invalid pax declaration");
8387                }
8388
8389                // pax requires that key/value strings be in UTF-8
8390                String keyStr = new String(data, key, value-key, "UTF-8");
8391                // -1 to strip the trailing LF
8392                String valStr = new String(data, value+1, eol-value-1, "UTF-8");
8393
8394                if ("path".equals(keyStr)) {
8395                    info.path = valStr;
8396                } else if ("size".equals(keyStr)) {
8397                    info.size = Long.parseLong(valStr);
8398                } else {
8399                    if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
8400                }
8401
8402                offset += linelen;
8403            } while (offset < contentSize);
8404
8405            return true;
8406        }
8407
8408        long extractRadix(byte[] data, int offset, int maxChars, int radix)
8409                throws IOException {
8410            long value = 0;
8411            final int end = offset + maxChars;
8412            for (int i = offset; i < end; i++) {
8413                final byte b = data[i];
8414                // Numeric fields in tar can terminate with either NUL or SPC
8415                if (b == 0 || b == ' ') break;
8416                if (b < '0' || b > ('0' + radix - 1)) {
8417                    throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
8418                }
8419                value = radix * value + (b - '0');
8420            }
8421            return value;
8422        }
8423
8424        String extractString(byte[] data, int offset, int maxChars) throws IOException {
8425            final int end = offset + maxChars;
8426            int eos = offset;
8427            // tar string fields terminate early with a NUL
8428            while (eos < end && data[eos] != 0) eos++;
8429            return new String(data, offset, eos-offset, "US-ASCII");
8430        }
8431
8432        void sendStartRestore() {
8433            if (mObserver != null) {
8434                try {
8435                    mObserver.onStartRestore();
8436                } catch (RemoteException e) {
8437                    Slog.w(TAG, "full restore observer went away: startRestore");
8438                    mObserver = null;
8439                }
8440            }
8441        }
8442
8443        void sendOnRestorePackage(String name) {
8444            if (mObserver != null) {
8445                try {
8446                    // TODO: use a more user-friendly name string
8447                    mObserver.onRestorePackage(name);
8448                } catch (RemoteException e) {
8449                    Slog.w(TAG, "full restore observer went away: restorePackage");
8450                    mObserver = null;
8451                }
8452            }
8453        }
8454
8455        void sendEndRestore() {
8456            if (mObserver != null) {
8457                try {
8458                    mObserver.onEndRestore();
8459                } catch (RemoteException e) {
8460                    Slog.w(TAG, "full restore observer went away: endRestore");
8461                    mObserver = null;
8462                }
8463            }
8464        }
8465    }
8466
8467    // ----- Restore handling -----
8468
8469    // Old style: directly match the stored vs on device signature blocks
8470    static boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
8471        if (target == null) {
8472            return false;
8473        }
8474
8475        // If the target resides on the system partition, we allow it to restore
8476        // data from the like-named package in a restore set even if the signatures
8477        // do not match.  (Unlike general applications, those flashed to the system
8478        // partition will be signed with the device's platform certificate, so on
8479        // different phones the same system app will have different signatures.)
8480        if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8481            if (MORE_DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
8482            return true;
8483        }
8484
8485        // Allow unsigned apps, but not signed on one device and unsigned on the other
8486        // !!! TODO: is this the right policy?
8487        Signature[] deviceSigs = target.signatures;
8488        if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
8489                + " device=" + deviceSigs);
8490        if ((storedSigs == null || storedSigs.length == 0)
8491                && (deviceSigs == null || deviceSigs.length == 0)) {
8492            return true;
8493        }
8494        if (storedSigs == null || deviceSigs == null) {
8495            return false;
8496        }
8497
8498        // !!! TODO: this demands that every stored signature match one
8499        // that is present on device, and does not demand the converse.
8500        // Is this this right policy?
8501        int nStored = storedSigs.length;
8502        int nDevice = deviceSigs.length;
8503
8504        for (int i=0; i < nStored; i++) {
8505            boolean match = false;
8506            for (int j=0; j < nDevice; j++) {
8507                if (storedSigs[i].equals(deviceSigs[j])) {
8508                    match = true;
8509                    break;
8510                }
8511            }
8512            if (!match) {
8513                return false;
8514            }
8515        }
8516        return true;
8517    }
8518
8519    // Used by both incremental and full restore
8520    void restoreWidgetData(String packageName, byte[] widgetData) {
8521        // Apply the restored widget state and generate the ID update for the app
8522        // TODO: http://b/22388012
8523        if (MORE_DEBUG) {
8524            Slog.i(TAG, "Incorporating restored widget data");
8525        }
8526        AppWidgetBackupBridge.restoreWidgetState(packageName, widgetData, UserHandle.USER_SYSTEM);
8527    }
8528
8529    // *****************************
8530    // NEW UNIFIED RESTORE IMPLEMENTATION
8531    // *****************************
8532
8533    // states of the unified-restore state machine
8534    enum UnifiedRestoreState {
8535        INITIAL,
8536        RUNNING_QUEUE,
8537        RESTORE_KEYVALUE,
8538        RESTORE_FULL,
8539        RESTORE_FINISHED,
8540        FINAL
8541    }
8542
8543    class PerformUnifiedRestoreTask implements BackupRestoreTask {
8544        // Transport we're working with to do the restore
8545        private IBackupTransport mTransport;
8546
8547        // Where per-transport saved state goes
8548        File mStateDir;
8549
8550        // Restore observer; may be null
8551        private IRestoreObserver mObserver;
8552
8553        // BackuoManagerMonitor; may be null
8554        private IBackupManagerMonitor mMonitor;
8555
8556        // Token identifying the dataset to the transport
8557        private long mToken;
8558
8559        // When this is a restore-during-install, this is the token identifying the
8560        // operation to the Package Manager, and we must ensure that we let it know
8561        // when we're finished.
8562        private int mPmToken;
8563
8564        // When this is restore-during-install, we need to tell the package manager
8565        // whether we actually launched the app, because this affects notifications
8566        // around externally-visible state transitions.
8567        private boolean mDidLaunch;
8568
8569        // Is this a whole-system restore, i.e. are we establishing a new ancestral
8570        // dataset to base future restore-at-install operations from?
8571        private boolean mIsSystemRestore;
8572
8573        // If this is a single-package restore, what package are we interested in?
8574        private PackageInfo mTargetPackage;
8575
8576        // In all cases, the calculated list of packages that we are trying to restore
8577        private List<PackageInfo> mAcceptSet;
8578
8579        // Our bookkeeping about the ancestral dataset
8580        private PackageManagerBackupAgent mPmAgent;
8581
8582        // Currently-bound backup agent for restore + restoreFinished purposes
8583        private IBackupAgent mAgent;
8584
8585        // What sort of restore we're doing now
8586        private RestoreDescription mRestoreDescription;
8587
8588        // The package we're currently restoring
8589        private PackageInfo mCurrentPackage;
8590
8591        // Widget-related data handled as part of this restore operation
8592        private byte[] mWidgetData;
8593
8594        // Number of apps restored in this pass
8595        private int mCount;
8596
8597        // When did we start?
8598        private long mStartRealtime;
8599
8600        // State machine progress
8601        private UnifiedRestoreState mState;
8602
8603        // How are things going?
8604        private int mStatus;
8605
8606        // Done?
8607        private boolean mFinished;
8608
8609        // Key/value: bookkeeping about staged data and files for agent access
8610        private File mBackupDataName;
8611        private File mStageName;
8612        private File mSavedStateName;
8613        private File mNewStateName;
8614        ParcelFileDescriptor mBackupData;
8615        ParcelFileDescriptor mNewState;
8616
8617        private final int mEphemeralOpToken;
8618
8619        // Invariant: mWakelock is already held, and this task is responsible for
8620        // releasing it at the end of the restore operation.
8621        PerformUnifiedRestoreTask(IBackupTransport transport, IRestoreObserver observer,
8622                IBackupManagerMonitor monitor, long restoreSetToken, PackageInfo targetPackage,
8623                int pmToken, boolean isFullSystemRestore, String[] filterSet) {
8624            mEphemeralOpToken = generateRandomIntegerToken();
8625            mState = UnifiedRestoreState.INITIAL;
8626            mStartRealtime = SystemClock.elapsedRealtime();
8627
8628            mTransport = transport;
8629            mObserver = observer;
8630            mMonitor = monitor;
8631            mToken = restoreSetToken;
8632            mPmToken = pmToken;
8633            mTargetPackage = targetPackage;
8634            mIsSystemRestore = isFullSystemRestore;
8635            mFinished = false;
8636            mDidLaunch = false;
8637
8638            if (targetPackage != null) {
8639                // Single package restore
8640                mAcceptSet = new ArrayList<PackageInfo>();
8641                mAcceptSet.add(targetPackage);
8642            } else {
8643                // Everything possible, or a target set
8644                if (filterSet == null) {
8645                    // We want everything and a pony
8646                    List<PackageInfo> apps =
8647                            PackageManagerBackupAgent.getStorableApplications(mPackageManager);
8648                    filterSet = packagesToNames(apps);
8649                    if (DEBUG) {
8650                        Slog.i(TAG, "Full restore; asking about " + filterSet.length + " apps");
8651                    }
8652                }
8653
8654                mAcceptSet = new ArrayList<PackageInfo>(filterSet.length);
8655
8656                // Pro tem, we insist on moving the settings provider package to last place.
8657                // Keep track of whether it's in the list, and bump it down if so.  We also
8658                // want to do the system package itself first if it's called for.
8659                boolean hasSystem = false;
8660                boolean hasSettings = false;
8661                for (int i = 0; i < filterSet.length; i++) {
8662                    try {
8663                        PackageInfo info = mPackageManager.getPackageInfo(filterSet[i], 0);
8664                        if ("android".equals(info.packageName)) {
8665                            hasSystem = true;
8666                            continue;
8667                        }
8668                        if (SETTINGS_PACKAGE.equals(info.packageName)) {
8669                            hasSettings = true;
8670                            continue;
8671                        }
8672
8673                        if (appIsEligibleForBackup(info.applicationInfo, mPackageManager)) {
8674                            mAcceptSet.add(info);
8675                        }
8676                    } catch (NameNotFoundException e) {
8677                        // requested package name doesn't exist; ignore it
8678                    }
8679                }
8680                if (hasSystem) {
8681                    try {
8682                        mAcceptSet.add(0, mPackageManager.getPackageInfo("android", 0));
8683                    } catch (NameNotFoundException e) {
8684                        // won't happen; we know a priori that it's valid
8685                    }
8686                }
8687                if (hasSettings) {
8688                    try {
8689                        mAcceptSet.add(mPackageManager.getPackageInfo(SETTINGS_PACKAGE, 0));
8690                    } catch (NameNotFoundException e) {
8691                        // this one is always valid too
8692                    }
8693                }
8694            }
8695
8696            if (MORE_DEBUG) {
8697                Slog.v(TAG, "Restore; accept set size is " + mAcceptSet.size());
8698                for (PackageInfo info : mAcceptSet) {
8699                    Slog.v(TAG, "   " + info.packageName);
8700                }
8701            }
8702        }
8703
8704        private String[] packagesToNames(List<PackageInfo> apps) {
8705            final int N = apps.size();
8706            String[] names = new String[N];
8707            for (int i = 0; i < N; i++) {
8708                names[i] = apps.get(i).packageName;
8709            }
8710            return names;
8711        }
8712
8713        // Execute one tick of whatever state machine the task implements
8714        @Override
8715        public void execute() {
8716            if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step " + mState);
8717            switch (mState) {
8718                case INITIAL:
8719                    startRestore();
8720                    break;
8721
8722                case RUNNING_QUEUE:
8723                    dispatchNextRestore();
8724                    break;
8725
8726                case RESTORE_KEYVALUE:
8727                    restoreKeyValue();
8728                    break;
8729
8730                case RESTORE_FULL:
8731                    restoreFull();
8732                    break;
8733
8734                case RESTORE_FINISHED:
8735                    restoreFinished();
8736                    break;
8737
8738                case FINAL:
8739                    if (!mFinished) finalizeRestore();
8740                    else {
8741                        Slog.e(TAG, "Duplicate finish");
8742                    }
8743                    mFinished = true;
8744                    break;
8745            }
8746        }
8747
8748        /*
8749         * SKETCH OF OPERATION
8750         *
8751         * create one of these PerformUnifiedRestoreTask objects, telling it which
8752         * dataset & transport to address, and then parameters within the restore
8753         * operation: single target package vs many, etc.
8754         *
8755         * 1. transport.startRestore(token, list-of-packages).  If we need @pm@  it is
8756         * always placed first and the settings provider always placed last [for now].
8757         *
8758         * 1a [if we needed @pm@ then nextRestorePackage() and restore the PMBA inline]
8759         *
8760         *   [ state change => RUNNING_QUEUE ]
8761         *
8762         * NOW ITERATE:
8763         *
8764         * { 3. t.nextRestorePackage()
8765         *   4. does the metadata for this package allow us to restore it?
8766         *      does the on-disk app permit us to restore it? [re-check allowBackup etc]
8767         *   5. is this a key/value dataset?  => key/value agent restore
8768         *       [ state change => RESTORE_KEYVALUE ]
8769         *       5a. spin up agent
8770         *       5b. t.getRestoreData() to stage it properly
8771         *       5c. call into agent to perform restore
8772         *       5d. tear down agent
8773         *       [ state change => RUNNING_QUEUE ]
8774         *
8775         *   6. else it's a stream dataset:
8776         *       [ state change => RESTORE_FULL ]
8777         *       6a. instantiate the engine for a stream restore: engine handles agent lifecycles
8778         *       6b. spin off engine runner on separate thread
8779         *       6c. ITERATE getNextFullRestoreDataChunk() and copy data to engine runner socket
8780         *       [ state change => RUNNING_QUEUE ]
8781         * }
8782         *
8783         *   [ state change => FINAL ]
8784         *
8785         * 7. t.finishRestore(), release wakelock, etc.
8786         *
8787         *
8788         */
8789
8790        // state INITIAL : set up for the restore and read the metadata if necessary
8791        private  void startRestore() {
8792            sendStartRestore(mAcceptSet.size());
8793
8794            // If we're starting a full-system restore, set up to begin widget ID remapping
8795            if (mIsSystemRestore) {
8796                // TODO: http://b/22388012
8797                AppWidgetBackupBridge.restoreStarting(UserHandle.USER_SYSTEM);
8798            }
8799
8800            try {
8801                String transportDir = mTransport.transportDirName();
8802                mStateDir = new File(mBaseStateDir, transportDir);
8803
8804                // Fetch the current metadata from the dataset first
8805                PackageInfo pmPackage = new PackageInfo();
8806                pmPackage.packageName = PACKAGE_MANAGER_SENTINEL;
8807                mAcceptSet.add(0, pmPackage);
8808
8809                PackageInfo[] packages = mAcceptSet.toArray(new PackageInfo[0]);
8810                mStatus = mTransport.startRestore(mToken, packages);
8811                if (mStatus != BackupTransport.TRANSPORT_OK) {
8812                    Slog.e(TAG, "Transport error " + mStatus + "; no restore possible");
8813                    mStatus = BackupTransport.TRANSPORT_ERROR;
8814                    executeNextState(UnifiedRestoreState.FINAL);
8815                    return;
8816                }
8817
8818                RestoreDescription desc = mTransport.nextRestorePackage();
8819                if (desc == null) {
8820                    Slog.e(TAG, "No restore metadata available; halting");
8821                    mMonitor = monitorEvent(mMonitor,
8822                            BackupManagerMonitor.LOG_EVENT_ID_NO_RESTORE_METADATA_AVAILABLE,
8823                            mCurrentPackage,
8824                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
8825                    mStatus = BackupTransport.TRANSPORT_ERROR;
8826                    executeNextState(UnifiedRestoreState.FINAL);
8827                    return;
8828                }
8829                if (!PACKAGE_MANAGER_SENTINEL.equals(desc.getPackageName())) {
8830                    Slog.e(TAG, "Required package metadata but got "
8831                            + desc.getPackageName());
8832                    mMonitor = monitorEvent(mMonitor,
8833                            BackupManagerMonitor.LOG_EVENT_ID_NO_PM_METADATA_RECEIVED,
8834                            mCurrentPackage,
8835                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
8836                    mStatus = BackupTransport.TRANSPORT_ERROR;
8837                    executeNextState(UnifiedRestoreState.FINAL);
8838                    return;
8839                }
8840
8841                // Pull the Package Manager metadata from the restore set first
8842                mCurrentPackage = new PackageInfo();
8843                mCurrentPackage.packageName = PACKAGE_MANAGER_SENTINEL;
8844                mPmAgent = makeMetadataAgent(null);
8845                mAgent = IBackupAgent.Stub.asInterface(mPmAgent.onBind());
8846                if (MORE_DEBUG) {
8847                    Slog.v(TAG, "initiating restore for PMBA");
8848                }
8849                initiateOneRestore(mCurrentPackage, 0);
8850                // The PM agent called operationComplete() already, because our invocation
8851                // of it is process-local and therefore synchronous.  That means that the
8852                // next-state message (RUNNING_QUEUE) is already enqueued.  Only if we're
8853                // unable to proceed with running the queue do we remove that pending
8854                // message and jump straight to the FINAL state.  Because this was
8855                // synchronous we also know that we should cancel the pending timeout
8856                // message.
8857                mBackupHandler.removeMessages(MSG_RESTORE_OPERATION_TIMEOUT);
8858
8859                // Verify that the backup set includes metadata.  If not, we can't do
8860                // signature/version verification etc, so we simply do not proceed with
8861                // the restore operation.
8862                if (!mPmAgent.hasMetadata()) {
8863                    Slog.e(TAG, "PM agent has no metadata, so not restoring");
8864                    mMonitor = monitorEvent(mMonitor,
8865                            BackupManagerMonitor.LOG_EVENT_ID_PM_AGENT_HAS_NO_METADATA,
8866                            mCurrentPackage,
8867                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
8868                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
8869                            PACKAGE_MANAGER_SENTINEL,
8870                            "Package manager restore metadata missing");
8871                    mStatus = BackupTransport.TRANSPORT_ERROR;
8872                    mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
8873                    executeNextState(UnifiedRestoreState.FINAL);
8874                    return;
8875                }
8876
8877                // Success; cache the metadata and continue as expected with the
8878                // next state already enqueued
8879
8880            } catch (Exception e) {
8881                // If we lost the transport at any time, halt
8882                Slog.e(TAG, "Unable to contact transport for restore: " + e.getMessage());
8883                mMonitor = monitorEvent(mMonitor,
8884                        BackupManagerMonitor.LOG_EVENT_ID_LOST_TRANSPORT,
8885                        null,
8886                        BackupManagerMonitor.LOG_EVENT_CATEGORY_TRANSPORT, null);
8887                mStatus = BackupTransport.TRANSPORT_ERROR;
8888                mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
8889                executeNextState(UnifiedRestoreState.FINAL);
8890                return;
8891            }
8892        }
8893
8894        // state RUNNING_QUEUE : figure out what the next thing to be restored is,
8895        // and fire the appropriate next step
8896        private void dispatchNextRestore() {
8897            UnifiedRestoreState nextState = UnifiedRestoreState.FINAL;
8898            try {
8899                mRestoreDescription = mTransport.nextRestorePackage();
8900                final String pkgName = (mRestoreDescription != null)
8901                        ? mRestoreDescription.getPackageName() : null;
8902                if (pkgName == null) {
8903                    Slog.e(TAG, "Failure getting next package name");
8904                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
8905                    nextState = UnifiedRestoreState.FINAL;
8906                    return;
8907                } else if (mRestoreDescription == RestoreDescription.NO_MORE_PACKAGES) {
8908                    // Yay we've reached the end cleanly
8909                    if (DEBUG) {
8910                        Slog.v(TAG, "No more packages; finishing restore");
8911                    }
8912                    int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
8913                    EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
8914                    nextState = UnifiedRestoreState.FINAL;
8915                    return;
8916                }
8917
8918                if (DEBUG) {
8919                    Slog.i(TAG, "Next restore package: " + mRestoreDescription);
8920                }
8921                sendOnRestorePackage(pkgName);
8922
8923                Metadata metaInfo = mPmAgent.getRestoredMetadata(pkgName);
8924                if (metaInfo == null) {
8925                    Slog.e(TAG, "No metadata for " + pkgName);
8926                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, pkgName,
8927                            "Package metadata missing");
8928                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
8929                    return;
8930                }
8931
8932                try {
8933                    mCurrentPackage = mPackageManager.getPackageInfo(
8934                            pkgName, PackageManager.GET_SIGNATURES);
8935                } catch (NameNotFoundException e) {
8936                    // Whoops, we thought we could restore this package but it
8937                    // turns out not to be present.  Skip it.
8938                    Slog.e(TAG, "Package not present: " + pkgName);
8939                    mMonitor = monitorEvent(mMonitor,
8940                            BackupManagerMonitor.LOG_EVENT_ID_PACKAGE_NOT_PRESENT,
8941                            mCurrentPackage,
8942                            BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
8943                            null);
8944                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, pkgName,
8945                            "Package missing on device");
8946                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
8947                    return;
8948                }
8949
8950                if (metaInfo.versionCode > mCurrentPackage.versionCode) {
8951                    // Data is from a "newer" version of the app than we have currently
8952                    // installed.  If the app has not declared that it is prepared to
8953                    // handle this case, we do not attempt the restore.
8954                    if ((mCurrentPackage.applicationInfo.flags
8955                            & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
8956                        String message = "Source version " + metaInfo.versionCode
8957                                + " > installed version " + mCurrentPackage.versionCode;
8958                        Slog.w(TAG, "Package " + pkgName + ": " + message);
8959                        Bundle monitoringExtras = putMonitoringExtra(null,
8960                                BackupManagerMonitor.EXTRA_LOG_RESTORE_VERSION,
8961                                metaInfo.versionCode);
8962                        monitoringExtras = putMonitoringExtra(monitoringExtras,
8963                                BackupManagerMonitor.EXTRA_LOG_RESTORE_ANYWAY, false);
8964                        mMonitor = monitorEvent(mMonitor,
8965                                BackupManagerMonitor.LOG_EVENT_ID_RESTORE_VERSION_HIGHER,
8966                                mCurrentPackage,
8967                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
8968                                monitoringExtras);
8969                        EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
8970                                pkgName, message);
8971                        nextState = UnifiedRestoreState.RUNNING_QUEUE;
8972                        return;
8973                    } else {
8974                        if (DEBUG) Slog.v(TAG, "Source version " + metaInfo.versionCode
8975                                + " > installed version " + mCurrentPackage.versionCode
8976                                + " but restoreAnyVersion");
8977                        Bundle monitoringExtras = putMonitoringExtra(null,
8978                                BackupManagerMonitor.EXTRA_LOG_RESTORE_VERSION,
8979                                metaInfo.versionCode);
8980                        monitoringExtras = putMonitoringExtra(monitoringExtras,
8981                                BackupManagerMonitor.EXTRA_LOG_RESTORE_ANYWAY, true);
8982                        mMonitor = monitorEvent(mMonitor,
8983                                BackupManagerMonitor.LOG_EVENT_ID_RESTORE_VERSION_HIGHER,
8984                                mCurrentPackage,
8985                                BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY,
8986                                monitoringExtras);
8987                    }
8988                }
8989
8990                if (MORE_DEBUG) Slog.v(TAG, "Package " + pkgName
8991                        + " restore version [" + metaInfo.versionCode
8992                        + "] is compatible with installed version ["
8993                        + mCurrentPackage.versionCode + "]");
8994
8995                // Reset per-package preconditions and fire the appropriate next state
8996                mWidgetData = null;
8997                final int type = mRestoreDescription.getDataType();
8998                if (type == RestoreDescription.TYPE_KEY_VALUE) {
8999                    nextState = UnifiedRestoreState.RESTORE_KEYVALUE;
9000                } else if (type == RestoreDescription.TYPE_FULL_STREAM) {
9001                    nextState = UnifiedRestoreState.RESTORE_FULL;
9002                } else {
9003                    // Unknown restore type; ignore this package and move on
9004                    Slog.e(TAG, "Unrecognized restore type " + type);
9005                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
9006                    return;
9007                }
9008            } catch (Exception e) {
9009                Slog.e(TAG, "Can't get next restore target from transport; halting: "
9010                        + e.getMessage());
9011                EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
9012                nextState = UnifiedRestoreState.FINAL;
9013                return;
9014            } finally {
9015                executeNextState(nextState);
9016            }
9017        }
9018
9019        // state RESTORE_KEYVALUE : restore one package via key/value API set
9020        private void restoreKeyValue() {
9021            // Initiating the restore will pass responsibility for the state machine's
9022            // progress to the agent callback, so we do not always execute the
9023            // next state here.
9024            final String packageName = mCurrentPackage.packageName;
9025            // Validate some semantic requirements that apply in this way
9026            // only to the key/value restore API flow
9027            if (mCurrentPackage.applicationInfo.backupAgentName == null
9028                    || "".equals(mCurrentPackage.applicationInfo.backupAgentName)) {
9029                if (MORE_DEBUG) {
9030                    Slog.i(TAG, "Data exists for package " + packageName
9031                            + " but app has no agent; skipping");
9032                }
9033                mMonitor = monitorEvent(mMonitor,
9034                        BackupManagerMonitor.LOG_EVENT_ID_APP_HAS_NO_AGENT, mCurrentPackage,
9035                        BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT, null);
9036                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
9037                        "Package has no agent");
9038                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9039                return;
9040            }
9041
9042            Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
9043            if (!BackupUtils.signaturesMatch(metaInfo.sigHashes, mCurrentPackage)) {
9044                Slog.w(TAG, "Signature mismatch restoring " + packageName);
9045                mMonitor = monitorEvent(mMonitor,
9046                        BackupManagerMonitor.LOG_EVENT_ID_SIGNATURE_MISMATCH, mCurrentPackage,
9047                        BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
9048                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
9049                        "Signature mismatch");
9050                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9051                return;
9052            }
9053
9054            // Good to go!  Set up and bind the agent...
9055            mAgent = bindToAgentSynchronous(
9056                    mCurrentPackage.applicationInfo,
9057                    ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL);
9058            if (mAgent == null) {
9059                Slog.w(TAG, "Can't find backup agent for " + packageName);
9060                mMonitor = monitorEvent(mMonitor,
9061                        BackupManagerMonitor.LOG_EVENT_ID_CANT_FIND_AGENT, mCurrentPackage,
9062                        BackupManagerMonitor.LOG_EVENT_CATEGORY_BACKUP_MANAGER_POLICY, null);
9063                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
9064                        "Restore agent missing");
9065                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9066                return;
9067            }
9068
9069            // Whatever happens next, we've launched the target app now; remember that.
9070            mDidLaunch = true;
9071
9072            // And then finally start the restore on this agent
9073            try {
9074                initiateOneRestore(mCurrentPackage, metaInfo.versionCode);
9075                ++mCount;
9076            } catch (Exception e) {
9077                Slog.e(TAG, "Error when attempting restore: " + e.toString());
9078                keyValueAgentErrorCleanup();
9079                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9080            }
9081        }
9082
9083        // Guts of a key/value restore operation
9084        void initiateOneRestore(PackageInfo app, int appVersionCode) {
9085            final String packageName = app.packageName;
9086
9087            if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
9088
9089            // !!! TODO: get the dirs from the transport
9090            mBackupDataName = new File(mDataDir, packageName + ".restore");
9091            mStageName = new File(mDataDir, packageName + ".stage");
9092            mNewStateName = new File(mStateDir, packageName + ".new");
9093            mSavedStateName = new File(mStateDir, packageName);
9094
9095            // don't stage the 'android' package where the wallpaper data lives.  this is
9096            // an optimization: we know there's no widget data hosted/published by that
9097            // package, and this way we avoid doing a spurious copy of MB-sized wallpaper
9098            // data following the download.
9099            boolean staging = !packageName.equals("android");
9100            ParcelFileDescriptor stage;
9101            File downloadFile = (staging) ? mStageName : mBackupDataName;
9102
9103            try {
9104                // Run the transport's restore pass
9105                stage = ParcelFileDescriptor.open(downloadFile,
9106                        ParcelFileDescriptor.MODE_READ_WRITE |
9107                        ParcelFileDescriptor.MODE_CREATE |
9108                        ParcelFileDescriptor.MODE_TRUNCATE);
9109
9110                if (mTransport.getRestoreData(stage) != BackupTransport.TRANSPORT_OK) {
9111                    // Transport-level failure, so we wind everything up and
9112                    // terminate the restore operation.
9113                    Slog.e(TAG, "Error getting restore data for " + packageName);
9114                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
9115                    stage.close();
9116                    downloadFile.delete();
9117                    executeNextState(UnifiedRestoreState.FINAL);
9118                    return;
9119                }
9120
9121                // We have the data from the transport. Now we extract and strip
9122                // any per-package metadata (typically widget-related information)
9123                // if appropriate
9124                if (staging) {
9125                    stage.close();
9126                    stage = ParcelFileDescriptor.open(downloadFile,
9127                            ParcelFileDescriptor.MODE_READ_ONLY);
9128
9129                    mBackupData = ParcelFileDescriptor.open(mBackupDataName,
9130                            ParcelFileDescriptor.MODE_READ_WRITE |
9131                            ParcelFileDescriptor.MODE_CREATE |
9132                            ParcelFileDescriptor.MODE_TRUNCATE);
9133
9134                    BackupDataInput in = new BackupDataInput(stage.getFileDescriptor());
9135                    BackupDataOutput out = new BackupDataOutput(mBackupData.getFileDescriptor());
9136                    byte[] buffer = new byte[8192]; // will grow when needed
9137                    while (in.readNextHeader()) {
9138                        final String key = in.getKey();
9139                        final int size = in.getDataSize();
9140
9141                        // is this a special key?
9142                        if (key.equals(KEY_WIDGET_STATE)) {
9143                            if (DEBUG) {
9144                                Slog.i(TAG, "Restoring widget state for " + packageName);
9145                            }
9146                            mWidgetData = new byte[size];
9147                            in.readEntityData(mWidgetData, 0, size);
9148                        } else {
9149                            if (size > buffer.length) {
9150                                buffer = new byte[size];
9151                            }
9152                            in.readEntityData(buffer, 0, size);
9153                            out.writeEntityHeader(key, size);
9154                            out.writeEntityData(buffer, size);
9155                        }
9156                    }
9157
9158                    mBackupData.close();
9159                }
9160
9161                // Okay, we have the data.  Now have the agent do the restore.
9162                stage.close();
9163
9164                mBackupData = ParcelFileDescriptor.open(mBackupDataName,
9165                        ParcelFileDescriptor.MODE_READ_ONLY);
9166
9167                mNewState = ParcelFileDescriptor.open(mNewStateName,
9168                        ParcelFileDescriptor.MODE_READ_WRITE |
9169                        ParcelFileDescriptor.MODE_CREATE |
9170                        ParcelFileDescriptor.MODE_TRUNCATE);
9171
9172                // Kick off the restore, checking for hung agents.  The timeout or
9173                // the operationComplete() callback will schedule the next step,
9174                // so we do not do that here.
9175                prepareOperationTimeout(mEphemeralOpToken, TIMEOUT_RESTORE_INTERVAL,
9176                        this, OP_TYPE_RESTORE_WAIT);
9177                mAgent.doRestore(mBackupData, appVersionCode, mNewState,
9178                        mEphemeralOpToken, mBackupManagerBinder);
9179            } catch (Exception e) {
9180                Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
9181                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
9182                        packageName, e.toString());
9183                keyValueAgentErrorCleanup();    // clears any pending timeout messages as well
9184
9185                // After a restore failure we go back to running the queue.  If there
9186                // are no more packages to be restored that will be handled by the
9187                // next step.
9188                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9189            }
9190        }
9191
9192        // state RESTORE_FULL : restore one package via streaming engine
9193        private void restoreFull() {
9194            // None of this can run on the work looper here, so we spin asynchronous
9195            // work like this:
9196            //
9197            //   StreamFeederThread: read data from mTransport.getNextFullRestoreDataChunk()
9198            //                       write it into the pipe to the engine
9199            //   EngineThread: FullRestoreEngine thread communicating with the target app
9200            //
9201            // When finished, StreamFeederThread executes next state as appropriate on the
9202            // backup looper, and the overall unified restore task resumes
9203            try {
9204                StreamFeederThread feeder = new StreamFeederThread();
9205                if (MORE_DEBUG) {
9206                    Slog.i(TAG, "Spinning threads for stream restore of "
9207                            + mCurrentPackage.packageName);
9208                }
9209                new Thread(feeder, "unified-stream-feeder").start();
9210
9211                // At this point the feeder is responsible for advancing the restore
9212                // state, so we're done here.
9213            } catch (IOException e) {
9214                // Unable to instantiate the feeder thread -- we need to bail on the
9215                // current target.  We haven't asked the transport for data yet, though,
9216                // so we can do that simply by going back to running the restore queue.
9217                Slog.e(TAG, "Unable to construct pipes for stream restore!");
9218                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9219            }
9220        }
9221
9222        // state RESTORE_FINISHED : provide the "no more data" signpost callback at the end
9223        private void restoreFinished() {
9224            if (DEBUG) {
9225                Slog.d(TAG, "restoreFinished packageName=" + mCurrentPackage.packageName);
9226            }
9227            try {
9228                prepareOperationTimeout(mEphemeralOpToken, TIMEOUT_RESTORE_FINISHED_INTERVAL, this,
9229                        OP_TYPE_RESTORE_WAIT);
9230                mAgent.doRestoreFinished(mEphemeralOpToken, mBackupManagerBinder);
9231                // If we get this far, the callback or timeout will schedule the
9232                // next restore state, so we're done
9233            } catch (Exception e) {
9234                final String packageName = mCurrentPackage.packageName;
9235                Slog.e(TAG, "Unable to finalize restore of " + packageName);
9236                EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
9237                        packageName, e.toString());
9238                keyValueAgentErrorCleanup();
9239                executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9240            }
9241        }
9242
9243        class StreamFeederThread extends RestoreEngine implements Runnable, BackupRestoreTask {
9244            final String TAG = "StreamFeederThread";
9245            FullRestoreEngine mEngine;
9246            EngineThread mEngineThread;
9247
9248            // pipe through which we read data from the transport. [0] read, [1] write
9249            ParcelFileDescriptor[] mTransportPipes;
9250
9251            // pipe through which the engine will read data.  [0] read, [1] write
9252            ParcelFileDescriptor[] mEnginePipes;
9253
9254            private final int mEphemeralOpToken;
9255
9256            public StreamFeederThread() throws IOException {
9257                mEphemeralOpToken = generateRandomIntegerToken();
9258                mTransportPipes = ParcelFileDescriptor.createPipe();
9259                mEnginePipes = ParcelFileDescriptor.createPipe();
9260                setRunning(true);
9261            }
9262
9263            @Override
9264            public void run() {
9265                UnifiedRestoreState nextState = UnifiedRestoreState.RUNNING_QUEUE;
9266                int status = BackupTransport.TRANSPORT_OK;
9267
9268                EventLog.writeEvent(EventLogTags.FULL_RESTORE_PACKAGE,
9269                        mCurrentPackage.packageName);
9270
9271                mEngine = new FullRestoreEngine(this, null, mMonitor, mCurrentPackage, false, false, mEphemeralOpToken);
9272                mEngineThread = new EngineThread(mEngine, mEnginePipes[0]);
9273
9274                ParcelFileDescriptor eWriteEnd = mEnginePipes[1];
9275                ParcelFileDescriptor tReadEnd = mTransportPipes[0];
9276                ParcelFileDescriptor tWriteEnd = mTransportPipes[1];
9277
9278                int bufferSize = 32 * 1024;
9279                byte[] buffer = new byte[bufferSize];
9280                FileOutputStream engineOut = new FileOutputStream(eWriteEnd.getFileDescriptor());
9281                FileInputStream transportIn = new FileInputStream(tReadEnd.getFileDescriptor());
9282
9283                // spin up the engine and start moving data to it
9284                new Thread(mEngineThread, "unified-restore-engine").start();
9285
9286                try {
9287                    while (status == BackupTransport.TRANSPORT_OK) {
9288                        // have the transport write some of the restoring data to us
9289                        int result = mTransport.getNextFullRestoreDataChunk(tWriteEnd);
9290                        if (result > 0) {
9291                            // The transport wrote this many bytes of restore data to the
9292                            // pipe, so pass it along to the engine.
9293                            if (MORE_DEBUG) {
9294                                Slog.v(TAG, "  <- transport provided chunk size " + result);
9295                            }
9296                            if (result > bufferSize) {
9297                                bufferSize = result;
9298                                buffer = new byte[bufferSize];
9299                            }
9300                            int toCopy = result;
9301                            while (toCopy > 0) {
9302                                int n = transportIn.read(buffer, 0, toCopy);
9303                                engineOut.write(buffer, 0, n);
9304                                toCopy -= n;
9305                                if (MORE_DEBUG) {
9306                                    Slog.v(TAG, "  -> wrote " + n + " to engine, left=" + toCopy);
9307                                }
9308                            }
9309                        } else if (result == BackupTransport.NO_MORE_DATA) {
9310                            // Clean finish.  Wind up and we're done!
9311                            if (MORE_DEBUG) {
9312                                Slog.i(TAG, "Got clean full-restore EOF for "
9313                                        + mCurrentPackage.packageName);
9314                            }
9315                            status = BackupTransport.TRANSPORT_OK;
9316                            break;
9317                        } else {
9318                            // Transport reported some sort of failure; the fall-through
9319                            // handling will deal properly with that.
9320                            Slog.e(TAG, "Error " + result + " streaming restore for "
9321                                    + mCurrentPackage.packageName);
9322                            EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
9323                            status = result;
9324                        }
9325                    }
9326                    if (MORE_DEBUG) Slog.v(TAG, "Done copying to engine, falling through");
9327                } catch (IOException e) {
9328                    // We lost our ability to communicate via the pipes.  That's worrying
9329                    // but potentially recoverable; abandon this package's restore but
9330                    // carry on with the next restore target.
9331                    Slog.e(TAG, "Unable to route data for restore");
9332                    EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
9333                            mCurrentPackage.packageName, "I/O error on pipes");
9334                    status = BackupTransport.AGENT_ERROR;
9335                } catch (Exception e) {
9336                    // The transport threw; terminate the whole operation.  Closing
9337                    // the sockets will wake up the engine and it will then tidy up the
9338                    // remote end.
9339                    Slog.e(TAG, "Transport failed during restore: " + e.getMessage());
9340                    EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
9341                    status = BackupTransport.TRANSPORT_ERROR;
9342                } finally {
9343                    // Close the transport pipes and *our* end of the engine pipe,
9344                    // but leave the engine thread's end open so that it properly
9345                    // hits EOF and winds up its operations.
9346                    IoUtils.closeQuietly(mEnginePipes[1]);
9347                    IoUtils.closeQuietly(mTransportPipes[0]);
9348                    IoUtils.closeQuietly(mTransportPipes[1]);
9349
9350                    // Don't proceed until the engine has wound up operations
9351                    mEngineThread.waitForResult();
9352
9353                    // Now we're really done with this one too
9354                    IoUtils.closeQuietly(mEnginePipes[0]);
9355
9356                    // In all cases we want to remember whether we launched
9357                    // the target app as part of our work so far.
9358                    mDidLaunch = (mEngine.getAgent() != null);
9359
9360                    // If we hit a transport-level error, we are done with everything;
9361                    // if we hit an agent error we just go back to running the queue.
9362                    if (status == BackupTransport.TRANSPORT_OK) {
9363                        // Clean finish means we issue the restore-finished callback
9364                        nextState = UnifiedRestoreState.RESTORE_FINISHED;
9365
9366                        // the engine bound the target's agent, so recover that binding
9367                        // to use for the callback.
9368                        mAgent = mEngine.getAgent();
9369
9370                        // and the restored widget data, if any
9371                        mWidgetData = mEngine.getWidgetData();
9372                    } else {
9373                        // Something went wrong somewhere.  Whether it was at the transport
9374                        // level is immaterial; we need to tell the transport to bail
9375                        try {
9376                            mTransport.abortFullRestore();
9377                        } catch (Exception e) {
9378                            // transport itself is dead; make sure we handle this as a
9379                            // fatal error
9380                            Slog.e(TAG, "Transport threw from abortFullRestore: " + e.getMessage());
9381                            status = BackupTransport.TRANSPORT_ERROR;
9382                        }
9383
9384                        // We also need to wipe the current target's data, as it's probably
9385                        // in an incoherent state.
9386                        clearApplicationDataSynchronous(mCurrentPackage.packageName);
9387
9388                        // Schedule the next state based on the nature of our failure
9389                        if (status == BackupTransport.TRANSPORT_ERROR) {
9390                            nextState = UnifiedRestoreState.FINAL;
9391                        } else {
9392                            nextState = UnifiedRestoreState.RUNNING_QUEUE;
9393                        }
9394                    }
9395                    executeNextState(nextState);
9396                    setRunning(false);
9397                }
9398            }
9399
9400            // BackupRestoreTask interface, specifically for timeout handling
9401
9402            @Override
9403            public void execute() { /* intentionally empty */ }
9404
9405            @Override
9406            public void operationComplete(long result) { /* intentionally empty */ }
9407
9408            // The app has timed out handling a restoring file
9409            @Override
9410            public void handleCancel(boolean cancelAll) {
9411                removeOperation(mEphemeralOpToken);
9412                if (DEBUG) {
9413                    Slog.w(TAG, "Full-data restore target timed out; shutting down");
9414                }
9415
9416                mMonitor = monitorEvent(mMonitor,
9417                        BackupManagerMonitor.LOG_EVENT_ID_FULL_RESTORE_TIMEOUT,
9418                        mCurrentPackage, BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT, null);
9419                mEngineThread.handleTimeout();
9420
9421                IoUtils.closeQuietly(mEnginePipes[1]);
9422                mEnginePipes[1] = null;
9423                IoUtils.closeQuietly(mEnginePipes[0]);
9424                mEnginePipes[0] = null;
9425            }
9426        }
9427
9428        class EngineThread implements Runnable {
9429            FullRestoreEngine mEngine;
9430            FileInputStream mEngineStream;
9431
9432            EngineThread(FullRestoreEngine engine, ParcelFileDescriptor engineSocket) {
9433                mEngine = engine;
9434                engine.setRunning(true);
9435                // We *do* want this FileInputStream to own the underlying fd, so that
9436                // when we are finished with it, it closes this end of the pipe in a way
9437                // that signals its other end.
9438                mEngineStream = new FileInputStream(engineSocket.getFileDescriptor(), true);
9439            }
9440
9441            public boolean isRunning() {
9442                return mEngine.isRunning();
9443            }
9444
9445            public int waitForResult() {
9446                return mEngine.waitForResult();
9447            }
9448
9449            @Override
9450            public void run() {
9451                try {
9452                    while (mEngine.isRunning()) {
9453                        // Tell it to be sure to leave the agent instance up after finishing
9454                        mEngine.restoreOneFile(mEngineStream, false);
9455                    }
9456                } finally {
9457                    // Because mEngineStream adopted its underlying FD, this also
9458                    // closes this end of the pipe.
9459                    IoUtils.closeQuietly(mEngineStream);
9460                }
9461            }
9462
9463            public void handleTimeout() {
9464                IoUtils.closeQuietly(mEngineStream);
9465                mEngine.handleTimeout();
9466            }
9467        }
9468
9469        // state FINAL : tear everything down and we're done.
9470        private void finalizeRestore() {
9471            if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
9472
9473            try {
9474                mTransport.finishRestore();
9475            } catch (Exception e) {
9476                Slog.e(TAG, "Error finishing restore", e);
9477            }
9478
9479            // Tell the observer we're done
9480            if (mObserver != null) {
9481                try {
9482                    mObserver.restoreFinished(mStatus);
9483                } catch (RemoteException e) {
9484                    Slog.d(TAG, "Restore observer died at restoreFinished");
9485                }
9486            }
9487
9488            // Clear any ongoing session timeout.
9489            mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
9490
9491            // If we have a PM token, we must under all circumstances be sure to
9492            // handshake when we've finished.
9493            if (mPmToken > 0) {
9494                if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
9495                try {
9496                    mPackageManagerBinder.finishPackageInstall(mPmToken, mDidLaunch);
9497                } catch (RemoteException e) { /* can't happen */ }
9498            } else {
9499                // We were invoked via an active restore session, not by the Package
9500                // Manager, so start up the session timeout again.
9501                mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_SESSION_TIMEOUT,
9502                        TIMEOUT_RESTORE_INTERVAL);
9503            }
9504
9505            // Kick off any work that may be needed regarding app widget restores
9506            // TODO: http://b/22388012
9507            AppWidgetBackupBridge.restoreFinished(UserHandle.USER_SYSTEM);
9508
9509            // If this was a full-system restore, record the ancestral
9510            // dataset information
9511            if (mIsSystemRestore && mPmAgent != null) {
9512                mAncestralPackages = mPmAgent.getRestoredPackages();
9513                mAncestralToken = mToken;
9514                writeRestoreTokens();
9515            }
9516
9517            // done; we can finally release the wakelock and be legitimately done.
9518            Slog.i(TAG, "Restore complete.");
9519
9520            synchronized (mPendingRestores) {
9521                if (mPendingRestores.size() > 0) {
9522                    if (DEBUG) {
9523                        Slog.d(TAG, "Starting next pending restore.");
9524                    }
9525                    PerformUnifiedRestoreTask task = mPendingRestores.remove();
9526                    mBackupHandler.sendMessage(
9527                            mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, task));
9528
9529                } else {
9530                    mIsRestoreInProgress = false;
9531                    if (MORE_DEBUG) {
9532                        Slog.d(TAG, "No pending restores.");
9533                    }
9534                }
9535            }
9536
9537            mWakelock.release();
9538        }
9539
9540        void keyValueAgentErrorCleanup() {
9541            // If the agent fails restore, it might have put the app's data
9542            // into an incoherent state.  For consistency we wipe its data
9543            // again in this case before continuing with normal teardown
9544            clearApplicationDataSynchronous(mCurrentPackage.packageName);
9545            keyValueAgentCleanup();
9546        }
9547
9548        // TODO: clean up naming; this is now used at finish by both k/v and stream restores
9549        void keyValueAgentCleanup() {
9550            mBackupDataName.delete();
9551            mStageName.delete();
9552            try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
9553            try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
9554            mBackupData = mNewState = null;
9555
9556            // if everything went okay, remember the recorded state now
9557            //
9558            // !!! TODO: the restored data could be migrated on the server
9559            // side into the current dataset.  In that case the new state file
9560            // we just created would reflect the data already extant in the
9561            // backend, so there'd be nothing more to do.  Until that happens,
9562            // however, we need to make sure that we record the data to the
9563            // current backend dataset.  (Yes, this means shipping the data over
9564            // the wire in both directions.  That's bad, but consistency comes
9565            // first, then efficiency.)  Once we introduce server-side data
9566            // migration to the newly-restored device's dataset, we will change
9567            // the following from a discard of the newly-written state to the
9568            // "correct" operation of renaming into the canonical state blob.
9569            mNewStateName.delete();                      // TODO: remove; see above comment
9570            //mNewStateName.renameTo(mSavedStateName);   // TODO: replace with this
9571
9572            // If this wasn't the PM pseudopackage, tear down the agent side
9573            if (mCurrentPackage.applicationInfo != null) {
9574                // unbind and tidy up even on timeout or failure
9575                try {
9576                    mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
9577
9578                    // The agent was probably running with a stub Application object,
9579                    // which isn't a valid run mode for the main app logic.  Shut
9580                    // down the app so that next time it's launched, it gets the
9581                    // usual full initialization.  Note that this is only done for
9582                    // full-system restores: when a single app has requested a restore,
9583                    // it is explicitly not killed following that operation.
9584                    //
9585                    // We execute this kill when these conditions hold:
9586                    //    1. it's not a system-uid process,
9587                    //    2. the app did not request its own restore (mTargetPackage == null), and either
9588                    //    3a. the app is a full-data target (TYPE_FULL_STREAM) or
9589                    //     b. the app does not state android:killAfterRestore="false" in its manifest
9590                    final int appFlags = mCurrentPackage.applicationInfo.flags;
9591                    final boolean killAfterRestore =
9592                            (mCurrentPackage.applicationInfo.uid >= Process.FIRST_APPLICATION_UID)
9593                            && ((mRestoreDescription.getDataType() == RestoreDescription.TYPE_FULL_STREAM)
9594                                    || ((appFlags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0));
9595
9596                    if (mTargetPackage == null && killAfterRestore) {
9597                        if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
9598                                + mCurrentPackage.applicationInfo.processName);
9599                        mActivityManager.killApplicationProcess(
9600                                mCurrentPackage.applicationInfo.processName,
9601                                mCurrentPackage.applicationInfo.uid);
9602                    }
9603                } catch (RemoteException e) {
9604                    // can't happen; we run in the same process as the activity manager
9605                }
9606            }
9607
9608            // The caller is responsible for reestablishing the state machine; our
9609            // responsibility here is to clear the decks for whatever comes next.
9610            mBackupHandler.removeMessages(MSG_RESTORE_OPERATION_TIMEOUT, this);
9611        }
9612
9613        @Override
9614        public void operationComplete(long unusedResult) {
9615            removeOperation(mEphemeralOpToken);
9616            if (MORE_DEBUG) {
9617                Slog.i(TAG, "operationComplete() during restore: target="
9618                        + mCurrentPackage.packageName
9619                        + " state=" + mState);
9620            }
9621
9622            final UnifiedRestoreState nextState;
9623            switch (mState) {
9624                case INITIAL:
9625                    // We've just (manually) restored the PMBA.  It doesn't need the
9626                    // additional restore-finished callback so we bypass that and go
9627                    // directly to running the queue.
9628                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
9629                    break;
9630
9631                case RESTORE_KEYVALUE:
9632                case RESTORE_FULL: {
9633                    // Okay, we've just heard back from the agent that it's done with
9634                    // the restore itself.  We now have to send the same agent its
9635                    // doRestoreFinished() callback, so roll into that state.
9636                    nextState = UnifiedRestoreState.RESTORE_FINISHED;
9637                    break;
9638                }
9639
9640                case RESTORE_FINISHED: {
9641                    // Okay, we're done with this package.  Tidy up and go on to the next
9642                    // app in the queue.
9643                    int size = (int) mBackupDataName.length();
9644                    EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE,
9645                            mCurrentPackage.packageName, size);
9646
9647                    // Just go back to running the restore queue
9648                    keyValueAgentCleanup();
9649
9650                    // If there was widget state associated with this app, get the OS to
9651                    // incorporate it into current bookeeping and then pass that along to
9652                    // the app as part of the restore-time work.
9653                    if (mWidgetData != null) {
9654                        restoreWidgetData(mCurrentPackage.packageName, mWidgetData);
9655                    }
9656
9657                    nextState = UnifiedRestoreState.RUNNING_QUEUE;
9658                    break;
9659                }
9660
9661                default: {
9662                    // Some kind of horrible semantic error; we're in an unexpected state.
9663                    // Back off hard and wind up.
9664                    Slog.e(TAG, "Unexpected restore callback into state " + mState);
9665                    keyValueAgentErrorCleanup();
9666                    nextState = UnifiedRestoreState.FINAL;
9667                    break;
9668                }
9669            }
9670
9671            executeNextState(nextState);
9672        }
9673
9674        // A call to agent.doRestore() or agent.doRestoreFinished() has timed out
9675        @Override
9676        public void handleCancel(boolean cancelAll) {
9677            removeOperation(mEphemeralOpToken);
9678            Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
9679            mMonitor = monitorEvent(mMonitor,
9680                    BackupManagerMonitor.LOG_EVENT_ID_KEY_VALUE_RESTORE_TIMEOUT,
9681                    mCurrentPackage, BackupManagerMonitor.LOG_EVENT_CATEGORY_AGENT, null);
9682            EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
9683                    mCurrentPackage.packageName, "restore timeout");
9684            // Handle like an agent that threw on invocation: wipe it and go on to the next
9685            keyValueAgentErrorCleanup();
9686            executeNextState(UnifiedRestoreState.RUNNING_QUEUE);
9687        }
9688
9689        void executeNextState(UnifiedRestoreState nextState) {
9690            if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
9691                    + this + " nextState=" + nextState);
9692            mState = nextState;
9693            Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
9694            mBackupHandler.sendMessage(msg);
9695        }
9696
9697        // restore observer support
9698        void sendStartRestore(int numPackages) {
9699            if (mObserver != null) {
9700                try {
9701                    mObserver.restoreStarting(numPackages);
9702                } catch (RemoteException e) {
9703                    Slog.w(TAG, "Restore observer went away: startRestore");
9704                    mObserver = null;
9705                }
9706            }
9707        }
9708
9709        void sendOnRestorePackage(String name) {
9710            if (mObserver != null) {
9711                if (mObserver != null) {
9712                    try {
9713                        mObserver.onUpdate(mCount, name);
9714                    } catch (RemoteException e) {
9715                        Slog.d(TAG, "Restore observer died in onUpdate");
9716                        mObserver = null;
9717                    }
9718                }
9719            }
9720        }
9721
9722        void sendEndRestore() {
9723            if (mObserver != null) {
9724                try {
9725                    mObserver.restoreFinished(mStatus);
9726                } catch (RemoteException e) {
9727                    Slog.w(TAG, "Restore observer went away: endRestore");
9728                    mObserver = null;
9729                }
9730            }
9731        }
9732    }
9733
9734    class PerformClearTask implements Runnable {
9735        IBackupTransport mTransport;
9736        PackageInfo mPackage;
9737
9738        PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
9739            mTransport = transport;
9740            mPackage = packageInfo;
9741        }
9742
9743        public void run() {
9744            try {
9745                // Clear the on-device backup state to ensure a full backup next time
9746                File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
9747                File stateFile = new File(stateDir, mPackage.packageName);
9748                stateFile.delete();
9749
9750                // Tell the transport to remove all the persistent storage for the app
9751                // TODO - need to handle failures
9752                mTransport.clearBackupData(mPackage);
9753            } catch (Exception e) {
9754                Slog.e(TAG, "Transport threw clearing data for " + mPackage + ": " + e.getMessage());
9755            } finally {
9756                try {
9757                    // TODO - need to handle failures
9758                    mTransport.finishBackup();
9759                } catch (Exception e) {
9760                    // Nothing we can do here, alas
9761                    Slog.e(TAG, "Unable to mark clear operation finished: " + e.getMessage());
9762                }
9763
9764                // Last but not least, release the cpu
9765                mWakelock.release();
9766            }
9767        }
9768    }
9769
9770    class PerformInitializeTask implements Runnable {
9771        HashSet<String> mQueue;
9772
9773        PerformInitializeTask(HashSet<String> transportNames) {
9774            mQueue = transportNames;
9775        }
9776
9777        public void run() {
9778            try {
9779                for (String transportName : mQueue) {
9780                    IBackupTransport transport =
9781                            mTransportManager.getTransportBinder(transportName);
9782                    if (transport == null) {
9783                        Slog.e(TAG, "Requested init for " + transportName + " but not found");
9784                        continue;
9785                    }
9786
9787                    Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
9788                    EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
9789                    long startRealtime = SystemClock.elapsedRealtime();
9790                    int status = transport.initializeDevice();
9791
9792                    if (status == BackupTransport.TRANSPORT_OK) {
9793                        status = transport.finishBackup();
9794                    }
9795
9796                    // Okay, the wipe really happened.  Clean up our local bookkeeping.
9797                    if (status == BackupTransport.TRANSPORT_OK) {
9798                        Slog.i(TAG, "Device init successful");
9799                        int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
9800                        EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
9801                        resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
9802                        EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
9803                        synchronized (mQueueLock) {
9804                            recordInitPendingLocked(false, transportName);
9805                        }
9806                    } else {
9807                        // If this didn't work, requeue this one and try again
9808                        // after a suitable interval
9809                        Slog.e(TAG, "Transport error in initializeDevice()");
9810                        EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
9811                        synchronized (mQueueLock) {
9812                            recordInitPendingLocked(true, transportName);
9813                        }
9814                        // do this via another alarm to make sure of the wakelock states
9815                        long delay = transport.requestBackupTime();
9816                        Slog.w(TAG, "Init failed on " + transportName + " resched in " + delay);
9817                        mAlarmManager.set(AlarmManager.RTC_WAKEUP,
9818                                System.currentTimeMillis() + delay, mRunInitIntent);
9819                    }
9820                }
9821            } catch (Exception e) {
9822                Slog.e(TAG, "Unexpected error performing init", e);
9823            } finally {
9824                // Done; release the wakelock
9825                mWakelock.release();
9826            }
9827        }
9828    }
9829
9830    private void dataChangedImpl(String packageName) {
9831        HashSet<String> targets = dataChangedTargets(packageName);
9832        dataChangedImpl(packageName, targets);
9833    }
9834
9835    private void dataChangedImpl(String packageName, HashSet<String> targets) {
9836        // Record that we need a backup pass for the caller.  Since multiple callers
9837        // may share a uid, we need to note all candidates within that uid and schedule
9838        // a backup pass for each of them.
9839        if (targets == null) {
9840            Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
9841                   + " uid=" + Binder.getCallingUid());
9842            return;
9843        }
9844
9845        synchronized (mQueueLock) {
9846            // Note that this client has made data changes that need to be backed up
9847            if (targets.contains(packageName)) {
9848                // Add the caller to the set of pending backups.  If there is
9849                // one already there, then overwrite it, but no harm done.
9850                BackupRequest req = new BackupRequest(packageName);
9851                if (mPendingBackups.put(packageName, req) == null) {
9852                    if (MORE_DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
9853
9854                    // Journal this request in case of crash.  The put()
9855                    // operation returned null when this package was not already
9856                    // in the set; we want to avoid touching the disk redundantly.
9857                    writeToJournalLocked(packageName);
9858                }
9859            }
9860        }
9861
9862        // ...and schedule a backup pass if necessary
9863        KeyValueBackupJob.schedule(mContext);
9864    }
9865
9866    // Note: packageName is currently unused, but may be in the future
9867    private HashSet<String> dataChangedTargets(String packageName) {
9868        // If the caller does not hold the BACKUP permission, it can only request a
9869        // backup of its own data.
9870        if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
9871                Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
9872            synchronized (mBackupParticipants) {
9873                return mBackupParticipants.get(Binder.getCallingUid());
9874            }
9875        }
9876
9877        // a caller with full permission can ask to back up any participating app
9878        HashSet<String> targets = new HashSet<String>();
9879        if (PACKAGE_MANAGER_SENTINEL.equals(packageName)) {
9880            targets.add(PACKAGE_MANAGER_SENTINEL);
9881        } else {
9882            synchronized (mBackupParticipants) {
9883                int N = mBackupParticipants.size();
9884                for (int i = 0; i < N; i++) {
9885                    HashSet<String> s = mBackupParticipants.valueAt(i);
9886                    if (s != null) {
9887                        targets.addAll(s);
9888                    }
9889                }
9890            }
9891        }
9892        return targets;
9893    }
9894
9895    private void writeToJournalLocked(String str) {
9896        RandomAccessFile out = null;
9897        try {
9898            if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
9899            out = new RandomAccessFile(mJournal, "rws");
9900            out.seek(out.length());
9901            out.writeUTF(str);
9902        } catch (IOException e) {
9903            Slog.e(TAG, "Can't write " + str + " to backup journal", e);
9904            mJournal = null;
9905        } finally {
9906            try { if (out != null) out.close(); } catch (IOException e) {}
9907        }
9908    }
9909
9910    // ----- IBackupManager binder interface -----
9911
9912    @Override
9913    public void dataChanged(final String packageName) {
9914        final int callingUserHandle = UserHandle.getCallingUserId();
9915        if (callingUserHandle != UserHandle.USER_SYSTEM) {
9916            // TODO: http://b/22388012
9917            // App is running under a non-owner user profile.  For now, we do not back
9918            // up data from secondary user profiles.
9919            // TODO: backups for all user profiles although don't add backup for profiles
9920            // without adding admin control in DevicePolicyManager.
9921            if (MORE_DEBUG) {
9922                Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user "
9923                        + callingUserHandle);
9924            }
9925            return;
9926        }
9927
9928        final HashSet<String> targets = dataChangedTargets(packageName);
9929        if (targets == null) {
9930            Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
9931                   + " uid=" + Binder.getCallingUid());
9932            return;
9933        }
9934
9935        mBackupHandler.post(new Runnable() {
9936                public void run() {
9937                    dataChangedImpl(packageName, targets);
9938                }
9939            });
9940    }
9941
9942    // Clear the given package's backup data from the current transport
9943    @Override
9944    public void clearBackupData(String transportName, String packageName) {
9945        if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName + " on " + transportName);
9946        PackageInfo info;
9947        try {
9948            info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
9949        } catch (NameNotFoundException e) {
9950            Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
9951            return;
9952        }
9953
9954        // If the caller does not hold the BACKUP permission, it can only request a
9955        // wipe of its own backed-up data.
9956        HashSet<String> apps;
9957        if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
9958                Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
9959            apps = mBackupParticipants.get(Binder.getCallingUid());
9960        } else {
9961            // a caller with full permission can ask to back up any participating app
9962            // !!! TODO: allow data-clear of ANY app?
9963            if (MORE_DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
9964            apps = new HashSet<String>();
9965            int N = mBackupParticipants.size();
9966            for (int i = 0; i < N; i++) {
9967                HashSet<String> s = mBackupParticipants.valueAt(i);
9968                if (s != null) {
9969                    apps.addAll(s);
9970                }
9971            }
9972        }
9973
9974        // Is the given app an available participant?
9975        if (apps.contains(packageName)) {
9976            // found it; fire off the clear request
9977            if (MORE_DEBUG) Slog.v(TAG, "Found the app - running clear process");
9978            mBackupHandler.removeMessages(MSG_RETRY_CLEAR);
9979            synchronized (mQueueLock) {
9980                final IBackupTransport transport =
9981                        mTransportManager.getTransportBinder(transportName);
9982                if (transport == null) {
9983                    // transport is currently unavailable -- make sure to retry
9984                    Message msg = mBackupHandler.obtainMessage(MSG_RETRY_CLEAR,
9985                            new ClearRetryParams(transportName, packageName));
9986                    mBackupHandler.sendMessageDelayed(msg, TRANSPORT_RETRY_INTERVAL);
9987                    return;
9988                }
9989                long oldId = Binder.clearCallingIdentity();
9990                mWakelock.acquire();
9991                Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
9992                        new ClearParams(transport, info));
9993                mBackupHandler.sendMessage(msg);
9994                Binder.restoreCallingIdentity(oldId);
9995            }
9996        }
9997    }
9998
9999    // Run a backup pass immediately for any applications that have declared
10000    // that they have pending updates.
10001    @Override
10002    public void backupNow() {
10003        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
10004
10005        final PowerSaveState result =
10006                mPowerManager.getPowerSaveState(ServiceType.KEYVALUE_BACKUP);
10007        if (result.batterySaverEnabled) {
10008            if (DEBUG) Slog.v(TAG, "Not running backup while in battery save mode");
10009            KeyValueBackupJob.schedule(mContext);   // try again in several hours
10010        } else {
10011            if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
10012            synchronized (mQueueLock) {
10013                // Fire the intent that kicks off the whole shebang...
10014                try {
10015                    mRunBackupIntent.send();
10016                } catch (PendingIntent.CanceledException e) {
10017                    // should never happen
10018                    Slog.e(TAG, "run-backup intent cancelled!");
10019                }
10020
10021                // ...and cancel any pending scheduled job, because we've just superseded it
10022                KeyValueBackupJob.cancel(mContext);
10023            }
10024        }
10025    }
10026
10027    boolean deviceIsProvisioned() {
10028        final ContentResolver resolver = mContext.getContentResolver();
10029        return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
10030    }
10031
10032    // Run a backup pass for the given packages, writing the resulting data stream
10033    // to the supplied file descriptor.  This method is synchronous and does not return
10034    // to the caller until the backup has been completed.
10035    //
10036    // This is the variant used by 'adb backup'; it requires on-screen confirmation
10037    // by the user because it can be used to offload data over untrusted USB.
10038    @Override
10039    public void adbBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeObbs,
10040            boolean includeShared, boolean doWidgets, boolean doAllApps, boolean includeSystem,
10041            boolean compress, boolean doKeyValue, String[] pkgList) {
10042        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "adbBackup");
10043
10044        final int callingUserHandle = UserHandle.getCallingUserId();
10045        // TODO: http://b/22388012
10046        if (callingUserHandle != UserHandle.USER_SYSTEM) {
10047            throw new IllegalStateException("Backup supported only for the device owner");
10048        }
10049
10050        // Validate
10051        if (!doAllApps) {
10052            if (!includeShared) {
10053                // If we're backing up shared data (sdcard or equivalent), then we can run
10054                // without any supplied app names.  Otherwise, we'd be doing no work, so
10055                // report the error.
10056                if (pkgList == null || pkgList.length == 0) {
10057                    throw new IllegalArgumentException(
10058                            "Backup requested but neither shared nor any apps named");
10059                }
10060            }
10061        }
10062
10063        long oldId = Binder.clearCallingIdentity();
10064        try {
10065            // Doesn't make sense to do a full backup prior to setup
10066            if (!deviceIsProvisioned()) {
10067                Slog.i(TAG, "Backup not supported before setup");
10068                return;
10069            }
10070
10071            if (DEBUG) Slog.v(TAG, "Requesting backup: apks=" + includeApks + " obb=" + includeObbs
10072                    + " shared=" + includeShared + " all=" + doAllApps + " system="
10073                    + includeSystem + " includekeyvalue=" + doKeyValue + " pkgs=" + pkgList);
10074            Slog.i(TAG, "Beginning adb backup...");
10075
10076            AdbBackupParams params = new AdbBackupParams(fd, includeApks, includeObbs,
10077                    includeShared, doWidgets, doAllApps, includeSystem, compress, doKeyValue,
10078                    pkgList);
10079            final int token = generateRandomIntegerToken();
10080            synchronized (mAdbBackupRestoreConfirmations) {
10081                mAdbBackupRestoreConfirmations.put(token, params);
10082            }
10083
10084            // start up the confirmation UI
10085            if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
10086            if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
10087                Slog.e(TAG, "Unable to launch backup confirmation UI");
10088                mAdbBackupRestoreConfirmations.delete(token);
10089                return;
10090            }
10091
10092            // make sure the screen is lit for the user interaction
10093            mPowerManager.userActivity(SystemClock.uptimeMillis(),
10094                    PowerManager.USER_ACTIVITY_EVENT_OTHER,
10095                    0);
10096
10097            // start the confirmation countdown
10098            startConfirmationTimeout(token, params);
10099
10100            // wait for the backup to be performed
10101            if (DEBUG) Slog.d(TAG, "Waiting for backup completion...");
10102            waitForCompletion(params);
10103        } finally {
10104            try {
10105                fd.close();
10106            } catch (IOException e) {
10107                // just eat it
10108            }
10109            Binder.restoreCallingIdentity(oldId);
10110            Slog.d(TAG, "Adb backup processing complete.");
10111        }
10112    }
10113
10114    @Override
10115    public void fullTransportBackup(String[] pkgNames) {
10116        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
10117                "fullTransportBackup");
10118
10119        final int callingUserHandle = UserHandle.getCallingUserId();
10120        // TODO: http://b/22388012
10121        if (callingUserHandle != UserHandle.USER_SYSTEM) {
10122            throw new IllegalStateException("Restore supported only for the device owner");
10123        }
10124
10125        if (!fullBackupAllowable(mTransportManager.getCurrentTransportBinder())) {
10126            Slog.i(TAG, "Full backup not currently possible -- key/value backup not yet run?");
10127        } else {
10128            if (DEBUG) {
10129                Slog.d(TAG, "fullTransportBackup()");
10130            }
10131
10132            final long oldId = Binder.clearCallingIdentity();
10133            try {
10134                CountDownLatch latch = new CountDownLatch(1);
10135                PerformFullTransportBackupTask task = new PerformFullTransportBackupTask(null,
10136                        pkgNames, false, null, latch, null, null, false /* userInitiated */);
10137                // Acquiring wakelock for PerformFullTransportBackupTask before its start.
10138                mWakelock.acquire();
10139                (new Thread(task, "full-transport-master")).start();
10140                do {
10141                    try {
10142                        latch.await();
10143                        break;
10144                    } catch (InterruptedException e) {
10145                        // Just go back to waiting for the latch to indicate completion
10146                    }
10147                } while (true);
10148
10149                // We just ran a backup on these packages, so kick them to the end of the queue
10150                final long now = System.currentTimeMillis();
10151                for (String pkg : pkgNames) {
10152                    enqueueFullBackup(pkg, now);
10153                }
10154            } finally {
10155                Binder.restoreCallingIdentity(oldId);
10156            }
10157        }
10158
10159        if (DEBUG) {
10160            Slog.d(TAG, "Done with full transport backup.");
10161        }
10162    }
10163
10164    @Override
10165    public void adbRestore(ParcelFileDescriptor fd) {
10166        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "adbRestore");
10167
10168        final int callingUserHandle = UserHandle.getCallingUserId();
10169        // TODO: http://b/22388012
10170        if (callingUserHandle != UserHandle.USER_SYSTEM) {
10171            throw new IllegalStateException("Restore supported only for the device owner");
10172        }
10173
10174        long oldId = Binder.clearCallingIdentity();
10175
10176        try {
10177            // Check whether the device has been provisioned -- we don't handle
10178            // full restores prior to completing the setup process.
10179            if (!deviceIsProvisioned()) {
10180                Slog.i(TAG, "Full restore not permitted before setup");
10181                return;
10182            }
10183
10184            Slog.i(TAG, "Beginning restore...");
10185
10186            AdbRestoreParams params = new AdbRestoreParams(fd);
10187            final int token = generateRandomIntegerToken();
10188            synchronized (mAdbBackupRestoreConfirmations) {
10189                mAdbBackupRestoreConfirmations.put(token, params);
10190            }
10191
10192            // start up the confirmation UI
10193            if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
10194            if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
10195                Slog.e(TAG, "Unable to launch restore confirmation");
10196                mAdbBackupRestoreConfirmations.delete(token);
10197                return;
10198            }
10199
10200            // make sure the screen is lit for the user interaction
10201            mPowerManager.userActivity(SystemClock.uptimeMillis(),
10202                    PowerManager.USER_ACTIVITY_EVENT_OTHER,
10203                    0);
10204
10205            // start the confirmation countdown
10206            startConfirmationTimeout(token, params);
10207
10208            // wait for the restore to be performed
10209            if (DEBUG) Slog.d(TAG, "Waiting for restore completion...");
10210            waitForCompletion(params);
10211        } finally {
10212            try {
10213                fd.close();
10214            } catch (IOException e) {
10215                Slog.w(TAG, "Error trying to close fd after adb restore: " + e);
10216            }
10217            Binder.restoreCallingIdentity(oldId);
10218            Slog.i(TAG, "adb restore processing complete.");
10219        }
10220    }
10221
10222    boolean startConfirmationUi(int token, String action) {
10223        try {
10224            Intent confIntent = new Intent(action);
10225            confIntent.setClassName("com.android.backupconfirm",
10226                    "com.android.backupconfirm.BackupRestoreConfirmation");
10227            confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
10228            confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
10229            mContext.startActivityAsUser(confIntent, UserHandle.SYSTEM);
10230        } catch (ActivityNotFoundException e) {
10231            return false;
10232        }
10233        return true;
10234    }
10235
10236    void startConfirmationTimeout(int token, AdbParams params) {
10237        if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
10238                + TIMEOUT_FULL_CONFIRMATION + " millis");
10239        Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
10240                token, 0, params);
10241        mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
10242    }
10243
10244    void waitForCompletion(AdbParams params) {
10245        synchronized (params.latch) {
10246            while (params.latch.get() == false) {
10247                try {
10248                    params.latch.wait();
10249                } catch (InterruptedException e) { /* never interrupted */ }
10250            }
10251        }
10252    }
10253
10254    void signalAdbBackupRestoreCompletion(AdbParams params) {
10255        synchronized (params.latch) {
10256            params.latch.set(true);
10257            params.latch.notifyAll();
10258        }
10259    }
10260
10261    // Confirm that the previously-requested full backup/restore operation can proceed.  This
10262    // is used to require a user-facing disclosure about the operation.
10263    @Override
10264    public void acknowledgeAdbBackupOrRestore(int token, boolean allow,
10265            String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
10266        if (DEBUG) Slog.d(TAG, "acknowledgeAdbBackupOrRestore : token=" + token
10267                + " allow=" + allow);
10268
10269        // TODO: possibly require not just this signature-only permission, but even
10270        // require that the specific designated confirmation-UI app uid is the caller?
10271        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeAdbBackupOrRestore");
10272
10273        long oldId = Binder.clearCallingIdentity();
10274        try {
10275
10276            AdbParams params;
10277            synchronized (mAdbBackupRestoreConfirmations) {
10278                params = mAdbBackupRestoreConfirmations.get(token);
10279                if (params != null) {
10280                    mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
10281                    mAdbBackupRestoreConfirmations.delete(token);
10282
10283                    if (allow) {
10284                        final int verb = params instanceof AdbBackupParams
10285                                ? MSG_RUN_ADB_BACKUP
10286                                : MSG_RUN_ADB_RESTORE;
10287
10288                        params.observer = observer;
10289                        params.curPassword = curPassword;
10290
10291                        params.encryptPassword = encPpassword;
10292
10293                        if (MORE_DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
10294                        mWakelock.acquire();
10295                        Message msg = mBackupHandler.obtainMessage(verb, params);
10296                        mBackupHandler.sendMessage(msg);
10297                    } else {
10298                        Slog.w(TAG, "User rejected full backup/restore operation");
10299                        // indicate completion without having actually transferred any data
10300                        signalAdbBackupRestoreCompletion(params);
10301                    }
10302                } else {
10303                    Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
10304                }
10305            }
10306        } finally {
10307            Binder.restoreCallingIdentity(oldId);
10308        }
10309    }
10310
10311    private static boolean backupSettingMigrated(int userId) {
10312        File base = new File(Environment.getDataDirectory(), "backup");
10313        File enableFile = new File(base, BACKUP_ENABLE_FILE);
10314        return enableFile.exists();
10315    }
10316
10317    private static boolean readBackupEnableState(int userId) {
10318        File base = new File(Environment.getDataDirectory(), "backup");
10319        File enableFile = new File(base, BACKUP_ENABLE_FILE);
10320        if (enableFile.exists()) {
10321            try (FileInputStream fin = new FileInputStream(enableFile)) {
10322                int state = fin.read();
10323                return state != 0;
10324            } catch (IOException e) {
10325                // can't read the file; fall through to assume disabled
10326                Slog.e(TAG, "Cannot read enable state; assuming disabled");
10327            }
10328        } else {
10329            if (DEBUG) {
10330                Slog.i(TAG, "isBackupEnabled() => false due to absent settings file");
10331            }
10332        }
10333        return false;
10334    }
10335
10336    private static void writeBackupEnableState(boolean enable, int userId) {
10337        File base = new File(Environment.getDataDirectory(), "backup");
10338        File enableFile = new File(base, BACKUP_ENABLE_FILE);
10339        File stage = new File(base, BACKUP_ENABLE_FILE + "-stage");
10340        FileOutputStream fout = null;
10341        try {
10342            fout = new FileOutputStream(stage);
10343            fout.write(enable ? 1 : 0);
10344            fout.close();
10345            stage.renameTo(enableFile);
10346            // will be synced immediately by the try-with-resources call to close()
10347        } catch (IOException|RuntimeException e) {
10348            // Whoops; looks like we're doomed.  Roll everything out, disabled,
10349            // including the legacy state.
10350            Slog.e(TAG, "Unable to record backup enable state; reverting to disabled: "
10351                    + e.getMessage());
10352
10353            final ContentResolver r = sInstance.mContext.getContentResolver();
10354            Settings.Secure.putStringForUser(r,
10355                    Settings.Secure.BACKUP_ENABLED, null, userId);
10356            enableFile.delete();
10357            stage.delete();
10358        } finally {
10359            IoUtils.closeQuietly(fout);
10360        }
10361    }
10362
10363    // Enable/disable backups
10364    @Override
10365    public void setBackupEnabled(boolean enable) {
10366        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10367                "setBackupEnabled");
10368
10369        Slog.i(TAG, "Backup enabled => " + enable);
10370
10371        long oldId = Binder.clearCallingIdentity();
10372        try {
10373            boolean wasEnabled = mEnabled;
10374            synchronized (this) {
10375                writeBackupEnableState(enable, UserHandle.USER_SYSTEM);
10376                mEnabled = enable;
10377            }
10378
10379            synchronized (mQueueLock) {
10380                if (enable && !wasEnabled && mProvisioned) {
10381                    // if we've just been enabled, start scheduling backup passes
10382                    KeyValueBackupJob.schedule(mContext);
10383                    scheduleNextFullBackupJob(0);
10384                } else if (!enable) {
10385                    // No longer enabled, so stop running backups
10386                    if (MORE_DEBUG) Slog.i(TAG, "Opting out of backup");
10387
10388                    KeyValueBackupJob.cancel(mContext);
10389
10390                    // This also constitutes an opt-out, so we wipe any data for
10391                    // this device from the backend.  We start that process with
10392                    // an alarm in order to guarantee wakelock states.
10393                    if (wasEnabled && mProvisioned) {
10394                        // NOTE: we currently flush every registered transport, not just
10395                        // the currently-active one.
10396                        String[] allTransports = mTransportManager.getBoundTransportNames();
10397                        // build the set of transports for which we are posting an init
10398                        for (String transport : allTransports) {
10399                            recordInitPendingLocked(true, transport);
10400                        }
10401                        mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
10402                                mRunInitIntent);
10403                    }
10404                }
10405            }
10406        } finally {
10407            Binder.restoreCallingIdentity(oldId);
10408        }
10409    }
10410
10411    // Enable/disable automatic restore of app data at install time
10412    @Override
10413    public void setAutoRestore(boolean doAutoRestore) {
10414        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10415                "setAutoRestore");
10416
10417        Slog.i(TAG, "Auto restore => " + doAutoRestore);
10418
10419        final long oldId = Binder.clearCallingIdentity();
10420        try {
10421            synchronized (this) {
10422                Settings.Secure.putInt(mContext.getContentResolver(),
10423                        Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
10424                mAutoRestore = doAutoRestore;
10425            }
10426        } finally {
10427            Binder.restoreCallingIdentity(oldId);
10428        }
10429    }
10430
10431    // Mark the backup service as having been provisioned
10432    @Override
10433    public void setBackupProvisioned(boolean available) {
10434        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10435                "setBackupProvisioned");
10436        /*
10437         * This is now a no-op; provisioning is simply the device's own setup state.
10438         */
10439    }
10440
10441    // Report whether the backup mechanism is currently enabled
10442    @Override
10443    public boolean isBackupEnabled() {
10444        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
10445        return mEnabled;    // no need to synchronize just to read it
10446    }
10447
10448    // Report the name of the currently active transport
10449    @Override
10450    public String getCurrentTransport() {
10451        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10452                "getCurrentTransport");
10453        String currentTransport = mTransportManager.getCurrentTransportName();
10454        if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + currentTransport);
10455        return currentTransport;
10456    }
10457
10458    // Report all known, available backup transports
10459    @Override
10460    public String[] listAllTransports() {
10461        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
10462
10463        return mTransportManager.getBoundTransportNames();
10464    }
10465
10466    @Override
10467    public ComponentName[] listAllTransportComponents() {
10468        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10469                "listAllTransportComponents");
10470        return mTransportManager.getAllTransportCompenents();
10471    }
10472
10473    @Override
10474    public String[] getTransportWhitelist() {
10475        // No permission check, intentionally.
10476        Set<ComponentName> whitelistedComponents = mTransportManager.getTransportWhitelist();
10477        String[] whitelistedTransports = new String[whitelistedComponents.size()];
10478        int i = 0;
10479        for (ComponentName component : whitelistedComponents) {
10480            whitelistedTransports[i] = component.flattenToShortString();
10481            i++;
10482        }
10483        return whitelistedTransports;
10484    }
10485
10486    // Select which transport to use for the next backup operation.
10487    @Override
10488    public String selectBackupTransport(String transport) {
10489        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10490                "selectBackupTransport");
10491
10492        final long oldId = Binder.clearCallingIdentity();
10493        try {
10494            String prevTransport = mTransportManager.selectTransport(transport);
10495            updateStateForTransport(transport);
10496            Slog.v(TAG, "selectBackupTransport() set " + mTransportManager.getCurrentTransportName()
10497                    + " returning " + prevTransport);
10498            return prevTransport;
10499        } finally {
10500            Binder.restoreCallingIdentity(oldId);
10501        }
10502    }
10503
10504    @Override
10505    public void selectBackupTransportAsync(final ComponentName transport,
10506            final ISelectBackupTransportCallback listener) {
10507        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10508                "selectBackupTransportAsync");
10509
10510        final long oldId = Binder.clearCallingIdentity();
10511
10512        Slog.v(TAG, "selectBackupTransportAsync() called with transport " +
10513                transport.flattenToShortString());
10514
10515        mTransportManager.ensureTransportReady(transport, new SelectBackupTransportCallback() {
10516            @Override
10517            public void onSuccess(String transportName) {
10518                mTransportManager.selectTransport(transportName);
10519                updateStateForTransport(mTransportManager.getCurrentTransportName());
10520                Slog.v(TAG, "Transport successfully selected: " + transport.flattenToShortString());
10521                try {
10522                    listener.onSuccess(transportName);
10523                } catch (RemoteException e) {
10524                    // Nothing to do here.
10525                }
10526            }
10527
10528            @Override
10529            public void onFailure(int reason) {
10530                Slog.v(TAG, "Failed to select transport: " + transport.flattenToShortString());
10531                try {
10532                    listener.onFailure(reason);
10533                } catch (RemoteException e) {
10534                    // Nothing to do here.
10535                }
10536            }
10537        });
10538
10539        Binder.restoreCallingIdentity(oldId);
10540    }
10541
10542    private void updateStateForTransport(String newTransportName) {
10543        // Publish the name change
10544        Settings.Secure.putString(mContext.getContentResolver(),
10545                Settings.Secure.BACKUP_TRANSPORT, newTransportName);
10546
10547        // And update our current-dataset bookkeeping
10548        IBackupTransport transport = mTransportManager.getTransportBinder(newTransportName);
10549        if (transport != null) {
10550            try {
10551                mCurrentToken = transport.getCurrentRestoreSet();
10552            } catch (Exception e) {
10553                // Oops.  We can't know the current dataset token, so reset and figure it out
10554                // when we do the next k/v backup operation on this transport.
10555                mCurrentToken = 0;
10556            }
10557        } else {
10558            // The named transport isn't bound at this particular moment, so we can't
10559            // know yet what its current dataset token is.  Reset as above.
10560            mCurrentToken = 0;
10561        }
10562    }
10563
10564    // Supply the configuration Intent for the given transport.  If the name is not one
10565    // of the available transports, or if the transport does not supply any configuration
10566    // UI, the method returns null.
10567    @Override
10568    public Intent getConfigurationIntent(String transportName) {
10569        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10570                "getConfigurationIntent");
10571
10572        final IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
10573        if (transport != null) {
10574            try {
10575                final Intent intent = transport.configurationIntent();
10576                if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
10577                        + intent);
10578                return intent;
10579            } catch (Exception e) {
10580                /* fall through to return null */
10581                Slog.e(TAG, "Unable to get configuration intent from transport: " + e.getMessage());
10582            }
10583        }
10584
10585        return null;
10586    }
10587
10588    // Supply the configuration summary string for the given transport.  If the name is
10589    // not one of the available transports, or if the transport does not supply any
10590    // summary / destination string, the method can return null.
10591    //
10592    // This string is used VERBATIM as the summary text of the relevant Settings item!
10593    @Override
10594    public String getDestinationString(String transportName) {
10595        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10596                "getDestinationString");
10597
10598        final IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
10599        if (transport != null) {
10600            try {
10601                final String text = transport.currentDestinationString();
10602                if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
10603                return text;
10604            } catch (Exception e) {
10605                /* fall through to return null */
10606                Slog.e(TAG, "Unable to get string from transport: " + e.getMessage());
10607            }
10608        }
10609
10610        return null;
10611    }
10612
10613    // Supply the manage-data intent for the given transport.
10614    @Override
10615    public Intent getDataManagementIntent(String transportName) {
10616        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10617                "getDataManagementIntent");
10618
10619        final IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
10620        if (transport != null) {
10621            try {
10622                final Intent intent = transport.dataManagementIntent();
10623                if (MORE_DEBUG) Slog.d(TAG, "getDataManagementIntent() returning intent "
10624                        + intent);
10625                return intent;
10626            } catch (Exception e) {
10627                /* fall through to return null */
10628                Slog.e(TAG, "Unable to get management intent from transport: " + e.getMessage());
10629            }
10630        }
10631
10632        return null;
10633    }
10634
10635    // Supply the menu label for affordances that fire the manage-data intent
10636    // for the given transport.
10637    @Override
10638    public String getDataManagementLabel(String transportName) {
10639        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10640                "getDataManagementLabel");
10641
10642        final IBackupTransport transport = mTransportManager.getTransportBinder(transportName);
10643        if (transport != null) {
10644            try {
10645                final String text = transport.dataManagementLabel();
10646                if (MORE_DEBUG) Slog.d(TAG, "getDataManagementLabel() returning " + text);
10647                return text;
10648            } catch (Exception e) {
10649                /* fall through to return null */
10650                Slog.e(TAG, "Unable to get management label from transport: " + e.getMessage());
10651            }
10652        }
10653
10654        return null;
10655    }
10656
10657    // Callback: a requested backup agent has been instantiated.  This should only
10658    // be called from the Activity Manager.
10659    @Override
10660    public void agentConnected(String packageName, IBinder agentBinder) {
10661        synchronized(mAgentConnectLock) {
10662            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
10663                Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
10664                IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
10665                mConnectedAgent = agent;
10666                mConnecting = false;
10667            } else {
10668                Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
10669                        + " claiming agent connected");
10670            }
10671            mAgentConnectLock.notifyAll();
10672        }
10673    }
10674
10675    // Callback: a backup agent has failed to come up, or has unexpectedly quit.
10676    // If the agent failed to come up in the first place, the agentBinder argument
10677    // will be null.  This should only be called from the Activity Manager.
10678    @Override
10679    public void agentDisconnected(String packageName) {
10680        // TODO: handle backup being interrupted
10681        synchronized(mAgentConnectLock) {
10682            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
10683                mConnectedAgent = null;
10684                mConnecting = false;
10685            } else {
10686                Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
10687                        + " claiming agent disconnected");
10688            }
10689            mAgentConnectLock.notifyAll();
10690        }
10691    }
10692
10693    // An application being installed will need a restore pass, then the Package Manager
10694    // will need to be told when the restore is finished.
10695    @Override
10696    public void restoreAtInstall(String packageName, int token) {
10697        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
10698            Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
10699                    + " attemping install-time restore");
10700            return;
10701        }
10702
10703        boolean skip = false;
10704
10705        long restoreSet = getAvailableRestoreToken(packageName);
10706        if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
10707                + " token=" + Integer.toHexString(token)
10708                + " restoreSet=" + Long.toHexString(restoreSet));
10709        if (restoreSet == 0) {
10710            if (MORE_DEBUG) Slog.i(TAG, "No restore set");
10711            skip = true;
10712        }
10713
10714        // Do we have a transport to fetch data for us?
10715        IBackupTransport transport = mTransportManager.getCurrentTransportBinder();
10716        if (transport == null) {
10717            if (DEBUG) Slog.w(TAG, "No transport");
10718            skip = true;
10719        }
10720
10721        if (!mAutoRestore) {
10722            if (DEBUG) {
10723                Slog.w(TAG, "Non-restorable state: auto=" + mAutoRestore);
10724            }
10725            skip = true;
10726        }
10727
10728        if (!skip) {
10729            try {
10730                // okay, we're going to attempt a restore of this package from this restore set.
10731                // The eventual message back into the Package Manager to run the post-install
10732                // steps for 'token' will be issued from the restore handling code.
10733
10734                // This can throw and so *must* happen before the wakelock is acquired
10735                String dirName = transport.transportDirName();
10736
10737                mWakelock.acquire();
10738                if (MORE_DEBUG) {
10739                    Slog.d(TAG, "Restore at install of " + packageName);
10740                }
10741                Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
10742                msg.obj = new RestoreParams(transport, dirName, null, null,
10743                        restoreSet, packageName, token);
10744                mBackupHandler.sendMessage(msg);
10745            } catch (Exception e) {
10746                // Calling into the transport broke; back off and proceed with the installation.
10747                Slog.e(TAG, "Unable to contact transport: " + e.getMessage());
10748                skip = true;
10749            }
10750        }
10751
10752        if (skip) {
10753            // Auto-restore disabled or no way to attempt a restore; just tell the Package
10754            // Manager to proceed with the post-install handling for this package.
10755            if (DEBUG) Slog.v(TAG, "Finishing install immediately");
10756            try {
10757                mPackageManagerBinder.finishPackageInstall(token, false);
10758            } catch (RemoteException e) { /* can't happen */ }
10759        }
10760    }
10761
10762    // Hand off a restore session
10763    @Override
10764    public IRestoreSession beginRestoreSession(String packageName, String transport) {
10765        if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
10766                + " transport=" + transport);
10767
10768        boolean needPermission = true;
10769        if (transport == null) {
10770            transport = mTransportManager.getCurrentTransportName();
10771
10772            if (packageName != null) {
10773                PackageInfo app = null;
10774                try {
10775                    app = mPackageManager.getPackageInfo(packageName, 0);
10776                } catch (NameNotFoundException nnf) {
10777                    Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
10778                    throw new IllegalArgumentException("Package " + packageName + " not found");
10779                }
10780
10781                if (app.applicationInfo.uid == Binder.getCallingUid()) {
10782                    // So: using the current active transport, and the caller has asked
10783                    // that its own package will be restored.  In this narrow use case
10784                    // we do not require the caller to hold the permission.
10785                    needPermission = false;
10786                }
10787            }
10788        }
10789
10790        if (needPermission) {
10791            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10792                    "beginRestoreSession");
10793        } else {
10794            if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
10795        }
10796
10797        synchronized(this) {
10798            if (mActiveRestoreSession != null) {
10799                Slog.i(TAG, "Restore session requested but one already active");
10800                return null;
10801            }
10802            if (mBackupRunning) {
10803                Slog.i(TAG, "Restore session requested but currently running backups");
10804                return null;
10805            }
10806            mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
10807            mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_SESSION_TIMEOUT,
10808                    TIMEOUT_RESTORE_INTERVAL);
10809        }
10810        return mActiveRestoreSession;
10811    }
10812
10813    void clearRestoreSession(ActiveRestoreSession currentSession) {
10814        synchronized(this) {
10815            if (currentSession != mActiveRestoreSession) {
10816                Slog.e(TAG, "ending non-current restore session");
10817            } else {
10818                if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
10819                mActiveRestoreSession = null;
10820                mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
10821            }
10822        }
10823    }
10824
10825    // Note that a currently-active backup agent has notified us that it has
10826    // completed the given outstanding asynchronous backup/restore operation.
10827    @Override
10828    public void opComplete(int token, long result) {
10829        if (MORE_DEBUG) {
10830            Slog.v(TAG, "opComplete: " + Integer.toHexString(token) + " result=" + result);
10831        }
10832        Operation op = null;
10833        synchronized (mCurrentOpLock) {
10834            op = mCurrentOperations.get(token);
10835            if (op != null) {
10836                if (op.state == OP_TIMEOUT) {
10837                    // The operation already timed out, and this is a late response.  Tidy up
10838                    // and ignore it; we've already dealt with the timeout.
10839                    op = null;
10840                    mCurrentOperations.delete(token);
10841                } else if (op.state == OP_ACKNOWLEDGED) {
10842                    if (DEBUG) {
10843                        Slog.w(TAG, "Received duplicate ack for token=" +
10844                                Integer.toHexString(token));
10845                    }
10846                    op = null;
10847                    mCurrentOperations.remove(token);
10848                } else if (op.state == OP_PENDING) {
10849                    // Can't delete op from mCurrentOperations. waitUntilOperationComplete can be
10850                    // called after we we receive this call.
10851                    op.state = OP_ACKNOWLEDGED;
10852                }
10853            }
10854            mCurrentOpLock.notifyAll();
10855        }
10856
10857        // The completion callback, if any, is invoked on the handler
10858        if (op != null && op.callback != null) {
10859            Pair<BackupRestoreTask, Long> callbackAndResult = Pair.create(op.callback, result);
10860            Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, callbackAndResult);
10861            mBackupHandler.sendMessage(msg);
10862        }
10863    }
10864
10865    @Override
10866    public boolean isAppEligibleForBackup(String packageName) {
10867        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10868                "isAppEligibleForBackup");
10869        try {
10870            PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName,
10871                    PackageManager.GET_SIGNATURES);
10872            if (!appIsEligibleForBackup(packageInfo.applicationInfo, mPackageManager) ||
10873                    appIsStopped(packageInfo.applicationInfo)) {
10874                return false;
10875            }
10876            IBackupTransport transport = mTransportManager.getCurrentTransportBinder();
10877            if (transport != null) {
10878                try {
10879                    return transport.isAppEligibleForBackup(packageInfo,
10880                        appGetsFullBackup(packageInfo));
10881                } catch (Exception e) {
10882                    Slog.e(TAG, "Unable to ask about eligibility: " + e.getMessage());
10883                }
10884            }
10885            // If transport is not present we couldn't tell that the package is not eligible.
10886            return true;
10887        } catch (NameNotFoundException e) {
10888            return false;
10889        }
10890    }
10891
10892    // ----- Restore session -----
10893
10894    class ActiveRestoreSession extends IRestoreSession.Stub {
10895        private static final String TAG = "RestoreSession";
10896
10897        private String mPackageName;
10898        private IBackupTransport mRestoreTransport = null;
10899        RestoreSet[] mRestoreSets = null;
10900        boolean mEnded = false;
10901        boolean mTimedOut = false;
10902
10903        ActiveRestoreSession(String packageName, String transport) {
10904            mPackageName = packageName;
10905            mRestoreTransport = mTransportManager.getTransportBinder(transport);
10906        }
10907
10908        public void markTimedOut() {
10909            mTimedOut = true;
10910        }
10911
10912        // --- Binder interface ---
10913        public synchronized int getAvailableRestoreSets(IRestoreObserver observer,
10914                IBackupManagerMonitor monitor) {
10915            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10916                    "getAvailableRestoreSets");
10917            if (observer == null) {
10918                throw new IllegalArgumentException("Observer must not be null");
10919            }
10920
10921            if (mEnded) {
10922                throw new IllegalStateException("Restore session already ended");
10923            }
10924
10925            if (mTimedOut) {
10926                Slog.i(TAG, "Session already timed out");
10927                return -1;
10928            }
10929
10930            long oldId = Binder.clearCallingIdentity();
10931            try {
10932                if (mRestoreTransport == null) {
10933                    Slog.w(TAG, "Null transport getting restore sets");
10934                    return -1;
10935                }
10936
10937                // We know we're doing legit work now, so halt the timeout
10938                // until we're done.  It gets started again when the result
10939                // comes in.
10940                mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
10941
10942                // spin off the transport request to our service thread
10943                mWakelock.acquire();
10944                Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
10945                        new RestoreGetSetsParams(mRestoreTransport, this, observer,
10946                                monitor));
10947                mBackupHandler.sendMessage(msg);
10948                return 0;
10949            } catch (Exception e) {
10950                Slog.e(TAG, "Error in getAvailableRestoreSets", e);
10951                return -1;
10952            } finally {
10953                Binder.restoreCallingIdentity(oldId);
10954            }
10955        }
10956
10957        public synchronized int restoreAll(long token, IRestoreObserver observer,
10958                IBackupManagerMonitor monitor) {
10959            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
10960                    "performRestore");
10961
10962            if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
10963                    + " observer=" + observer);
10964
10965            if (mEnded) {
10966                throw new IllegalStateException("Restore session already ended");
10967            }
10968
10969            if (mTimedOut) {
10970                Slog.i(TAG, "Session already timed out");
10971                return -1;
10972            }
10973
10974            if (mRestoreTransport == null || mRestoreSets == null) {
10975                Slog.e(TAG, "Ignoring restoreAll() with no restore set");
10976                return -1;
10977            }
10978
10979            if (mPackageName != null) {
10980                Slog.e(TAG, "Ignoring restoreAll() on single-package session");
10981                return -1;
10982            }
10983
10984            String dirName;
10985            try {
10986                dirName = mRestoreTransport.transportDirName();
10987            } catch (Exception e) {
10988                // Transport went AWOL; fail.
10989                Slog.e(TAG, "Unable to get transport dir for restore: " + e.getMessage());
10990                return -1;
10991            }
10992
10993            synchronized (mQueueLock) {
10994                for (int i = 0; i < mRestoreSets.length; i++) {
10995                    if (token == mRestoreSets[i].token) {
10996                        // Real work, so stop the session timeout until we finalize the restore
10997                        mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
10998
10999                        long oldId = Binder.clearCallingIdentity();
11000                        mWakelock.acquire();
11001                        if (MORE_DEBUG) {
11002                            Slog.d(TAG, "restoreAll() kicking off");
11003                        }
11004                        Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
11005                        msg.obj = new RestoreParams(mRestoreTransport, dirName,
11006                                observer, monitor, token);
11007                        mBackupHandler.sendMessage(msg);
11008                        Binder.restoreCallingIdentity(oldId);
11009                        return 0;
11010                    }
11011                }
11012            }
11013
11014            Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
11015            return -1;
11016        }
11017
11018        // Restores of more than a single package are treated as 'system' restores
11019        public synchronized int restoreSome(long token, IRestoreObserver observer,
11020                IBackupManagerMonitor monitor, String[] packages) {
11021            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
11022                    "performRestore");
11023
11024            if (DEBUG) {
11025                StringBuilder b = new StringBuilder(128);
11026                b.append("restoreSome token=");
11027                b.append(Long.toHexString(token));
11028                b.append(" observer=");
11029                b.append(observer.toString());
11030                b.append(" monitor=");
11031                if (monitor == null) {
11032                    b.append("null");
11033                } else {
11034                    b.append(monitor.toString());
11035                }
11036                b.append(" packages=");
11037                if (packages == null) {
11038                    b.append("null");
11039                } else {
11040                    b.append('{');
11041                    boolean first = true;
11042                    for (String s : packages) {
11043                        if (!first) {
11044                            b.append(", ");
11045                        } else first = false;
11046                        b.append(s);
11047                    }
11048                    b.append('}');
11049                }
11050                Slog.d(TAG, b.toString());
11051            }
11052
11053            if (mEnded) {
11054                throw new IllegalStateException("Restore session already ended");
11055            }
11056
11057            if (mTimedOut) {
11058                Slog.i(TAG, "Session already timed out");
11059                return -1;
11060            }
11061
11062            if (mRestoreTransport == null || mRestoreSets == null) {
11063                Slog.e(TAG, "Ignoring restoreAll() with no restore set");
11064                return -1;
11065            }
11066
11067            if (mPackageName != null) {
11068                Slog.e(TAG, "Ignoring restoreAll() on single-package session");
11069                return -1;
11070            }
11071
11072            String dirName;
11073            try {
11074                dirName = mRestoreTransport.transportDirName();
11075            } catch (Exception e) {
11076                // Transport went AWOL; fail.
11077                Slog.e(TAG, "Unable to get transport name for restoreSome: " + e.getMessage());
11078                return -1;
11079            }
11080
11081            synchronized (mQueueLock) {
11082                for (int i = 0; i < mRestoreSets.length; i++) {
11083                    if (token == mRestoreSets[i].token) {
11084                        // Stop the session timeout until we finalize the restore
11085                        mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
11086
11087                        long oldId = Binder.clearCallingIdentity();
11088                        mWakelock.acquire();
11089                        if (MORE_DEBUG) {
11090                            Slog.d(TAG, "restoreSome() of " + packages.length + " packages");
11091                        }
11092                        Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
11093                        msg.obj = new RestoreParams(mRestoreTransport, dirName, observer, monitor,
11094                                token, packages, packages.length > 1);
11095                        mBackupHandler.sendMessage(msg);
11096                        Binder.restoreCallingIdentity(oldId);
11097                        return 0;
11098                    }
11099                }
11100            }
11101
11102            Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
11103            return -1;
11104        }
11105
11106        public synchronized int restorePackage(String packageName, IRestoreObserver observer,
11107                IBackupManagerMonitor monitor) {
11108            if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer
11109                    + "monitor=" + monitor);
11110
11111            if (mEnded) {
11112                throw new IllegalStateException("Restore session already ended");
11113            }
11114
11115            if (mTimedOut) {
11116                Slog.i(TAG, "Session already timed out");
11117                return -1;
11118            }
11119
11120            if (mPackageName != null) {
11121                if (! mPackageName.equals(packageName)) {
11122                    Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
11123                            + " on session for package " + mPackageName);
11124                    return -1;
11125                }
11126            }
11127
11128            PackageInfo app = null;
11129            try {
11130                app = mPackageManager.getPackageInfo(packageName, 0);
11131            } catch (NameNotFoundException nnf) {
11132                Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
11133                return -1;
11134            }
11135
11136            // If the caller is not privileged and is not coming from the target
11137            // app's uid, throw a permission exception back to the caller.
11138            int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
11139                    Binder.getCallingPid(), Binder.getCallingUid());
11140            if ((perm == PackageManager.PERMISSION_DENIED) &&
11141                    (app.applicationInfo.uid != Binder.getCallingUid())) {
11142                Slog.w(TAG, "restorePackage: bad packageName=" + packageName
11143                        + " or calling uid=" + Binder.getCallingUid());
11144                throw new SecurityException("No permission to restore other packages");
11145            }
11146
11147            // So far so good; we're allowed to try to restore this package.
11148            long oldId = Binder.clearCallingIdentity();
11149            try {
11150                // Check whether there is data for it in the current dataset, falling back
11151                // to the ancestral dataset if not.
11152                long token = getAvailableRestoreToken(packageName);
11153                if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName
11154                        + " token=" + Long.toHexString(token));
11155
11156                // If we didn't come up with a place to look -- no ancestral dataset and
11157                // the app has never been backed up from this device -- there's nothing
11158                // to do but return failure.
11159                if (token == 0) {
11160                    if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
11161                    return -1;
11162                }
11163
11164                String dirName;
11165                try {
11166                    dirName = mRestoreTransport.transportDirName();
11167                } catch (Exception e) {
11168                    // Transport went AWOL; fail.
11169                    Slog.e(TAG, "Unable to get transport dir for restorePackage: " + e.getMessage());
11170                    return -1;
11171                }
11172
11173                // Stop the session timeout until we finalize the restore
11174                mBackupHandler.removeMessages(MSG_RESTORE_SESSION_TIMEOUT);
11175
11176                // Ready to go:  enqueue the restore request and claim success
11177                mWakelock.acquire();
11178                if (MORE_DEBUG) {
11179                    Slog.d(TAG, "restorePackage() : " + packageName);
11180                }
11181                Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
11182                msg.obj = new RestoreParams(mRestoreTransport, dirName, observer, monitor,
11183                        token, app);
11184                mBackupHandler.sendMessage(msg);
11185            } finally {
11186                Binder.restoreCallingIdentity(oldId);
11187            }
11188            return 0;
11189        }
11190
11191        // Posted to the handler to tear down a restore session in a cleanly synchronized way
11192        class EndRestoreRunnable implements Runnable {
11193            BackupManagerService mBackupManager;
11194            ActiveRestoreSession mSession;
11195
11196            EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
11197                mBackupManager = manager;
11198                mSession = session;
11199            }
11200
11201            public void run() {
11202                // clean up the session's bookkeeping
11203                synchronized (mSession) {
11204                    mSession.mRestoreTransport = null;
11205                    mSession.mEnded = true;
11206                }
11207
11208                // clean up the BackupManagerImpl side of the bookkeeping
11209                // and cancel any pending timeout message
11210                mBackupManager.clearRestoreSession(mSession);
11211            }
11212        }
11213
11214        public synchronized void endRestoreSession() {
11215            if (DEBUG) Slog.d(TAG, "endRestoreSession");
11216
11217            if (mTimedOut) {
11218                Slog.i(TAG, "Session already timed out");
11219                return;
11220            }
11221
11222            if (mEnded) {
11223                throw new IllegalStateException("Restore session already ended");
11224            }
11225
11226            mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
11227        }
11228    }
11229
11230    @Override
11231    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11232        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
11233
11234        long identityToken = Binder.clearCallingIdentity();
11235        try {
11236            if (args != null) {
11237                for (String arg : args) {
11238                    if ("-h".equals(arg)) {
11239                        pw.println("'dumpsys backup' optional arguments:");
11240                        pw.println("  -h       : this help text");
11241                        pw.println("  a[gents] : dump information about defined backup agents");
11242                        return;
11243                    } else if ("agents".startsWith(arg)) {
11244                        dumpAgents(pw);
11245                        return;
11246                    }
11247                }
11248            }
11249            dumpInternal(pw);
11250        } finally {
11251            Binder.restoreCallingIdentity(identityToken);
11252        }
11253    }
11254
11255    private void dumpAgents(PrintWriter pw) {
11256        List<PackageInfo> agentPackages = allAgentPackages();
11257        pw.println("Defined backup agents:");
11258        for (PackageInfo pkg : agentPackages) {
11259            pw.print("  ");
11260            pw.print(pkg.packageName); pw.println(':');
11261            pw.print("      "); pw.println(pkg.applicationInfo.backupAgentName);
11262        }
11263    }
11264
11265    private void dumpInternal(PrintWriter pw) {
11266        synchronized (mQueueLock) {
11267            pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
11268                    + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
11269                    + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
11270            pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
11271            if (mBackupRunning) pw.println("Backup currently running");
11272            pw.println("Last backup pass started: " + mLastBackupPass
11273                    + " (now = " + System.currentTimeMillis() + ')');
11274            pw.println("  next scheduled: " + KeyValueBackupJob.nextScheduled());
11275
11276            pw.println("Transport whitelist:");
11277            for (ComponentName transport : mTransportManager.getTransportWhitelist()) {
11278                pw.print("    ");
11279                pw.println(transport.flattenToShortString());
11280            }
11281
11282            pw.println("Available transports:");
11283            final String[] transports = listAllTransports();
11284            if (transports != null) {
11285                for (String t : listAllTransports()) {
11286                    pw.println((t.equals(mTransportManager.getCurrentTransportName()) ? "  * " : "    ") + t);
11287                    try {
11288                        IBackupTransport transport = mTransportManager.getTransportBinder(t);
11289                        File dir = new File(mBaseStateDir, transport.transportDirName());
11290                        pw.println("       destination: " + transport.currentDestinationString());
11291                        pw.println("       intent: " + transport.configurationIntent());
11292                        for (File f : dir.listFiles()) {
11293                            pw.println("       " + f.getName() + " - " + f.length() + " state bytes");
11294                        }
11295                    } catch (Exception e) {
11296                        Slog.e(TAG, "Error in transport", e);
11297                        pw.println("        Error: " + e);
11298                    }
11299                }
11300            }
11301
11302            pw.println("Pending init: " + mPendingInits.size());
11303            for (String s : mPendingInits) {
11304                pw.println("    " + s);
11305            }
11306
11307            if (DEBUG_BACKUP_TRACE) {
11308                synchronized (mBackupTrace) {
11309                    if (!mBackupTrace.isEmpty()) {
11310                        pw.println("Most recent backup trace:");
11311                        for (String s : mBackupTrace) {
11312                            pw.println("   " + s);
11313                        }
11314                    }
11315                }
11316            }
11317
11318            pw.print("Ancestral: "); pw.println(Long.toHexString(mAncestralToken));
11319            pw.print("Current:   "); pw.println(Long.toHexString(mCurrentToken));
11320
11321            int N = mBackupParticipants.size();
11322            pw.println("Participants:");
11323            for (int i=0; i<N; i++) {
11324                int uid = mBackupParticipants.keyAt(i);
11325                pw.print("  uid: ");
11326                pw.println(uid);
11327                HashSet<String> participants = mBackupParticipants.valueAt(i);
11328                for (String app: participants) {
11329                    pw.println("    " + app);
11330                }
11331            }
11332
11333            pw.println("Ancestral packages: "
11334                    + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
11335            if (mAncestralPackages != null) {
11336                for (String pkg : mAncestralPackages) {
11337                    pw.println("    " + pkg);
11338                }
11339            }
11340
11341            pw.println("Ever backed up: " + mEverStoredApps.size());
11342            for (String pkg : mEverStoredApps) {
11343                pw.println("    " + pkg);
11344            }
11345
11346            pw.println("Pending key/value backup: " + mPendingBackups.size());
11347            for (BackupRequest req : mPendingBackups.values()) {
11348                pw.println("    " + req);
11349            }
11350
11351            pw.println("Full backup queue:" + mFullBackupQueue.size());
11352            for (FullBackupEntry entry : mFullBackupQueue) {
11353                pw.print("    "); pw.print(entry.lastBackup);
11354                pw.print(" : "); pw.println(entry.packageName);
11355            }
11356        }
11357    }
11358
11359    private static void sendBackupOnUpdate(IBackupObserver observer, String packageName,
11360            BackupProgress progress) {
11361        if (observer != null) {
11362            try {
11363                observer.onUpdate(packageName, progress);
11364            } catch (RemoteException e) {
11365                if (DEBUG) {
11366                    Slog.w(TAG, "Backup observer went away: onUpdate");
11367                }
11368            }
11369        }
11370    }
11371
11372    private static void sendBackupOnPackageResult(IBackupObserver observer, String packageName,
11373            int status) {
11374        if (observer != null) {
11375            try {
11376                observer.onResult(packageName, status);
11377            } catch (RemoteException e) {
11378                if (DEBUG) {
11379                    Slog.w(TAG, "Backup observer went away: onResult");
11380                }
11381            }
11382        }
11383    }
11384
11385    private static void sendBackupFinished(IBackupObserver observer, int status) {
11386        if (observer != null) {
11387            try {
11388                observer.backupFinished(status);
11389            } catch (RemoteException e) {
11390                if (DEBUG) {
11391                    Slog.w(TAG, "Backup observer went away: backupFinished");
11392                }
11393            }
11394        }
11395    }
11396
11397    private Bundle putMonitoringExtra(Bundle extras, String key, String value) {
11398        if (extras == null) {
11399            extras = new Bundle();
11400        }
11401        extras.putString(key, value);
11402        return extras;
11403    }
11404
11405    private Bundle putMonitoringExtra(Bundle extras, String key, int value) {
11406        if (extras == null) {
11407            extras = new Bundle();
11408        }
11409        extras.putInt(key, value);
11410        return extras;
11411    }
11412
11413    private Bundle putMonitoringExtra(Bundle extras, String key, long value) {
11414        if (extras == null) {
11415            extras = new Bundle();
11416        }
11417        extras.putLong(key, value);
11418        return extras;
11419    }
11420
11421
11422    private Bundle putMonitoringExtra(Bundle extras, String key, boolean value) {
11423        if (extras == null) {
11424            extras = new Bundle();
11425        }
11426        extras.putBoolean(key, value);
11427        return extras;
11428    }
11429
11430    private static IBackupManagerMonitor monitorEvent(IBackupManagerMonitor monitor, int id,
11431            PackageInfo pkg, int category, Bundle extras) {
11432        if (monitor != null) {
11433            try {
11434                Bundle bundle = new Bundle();
11435                bundle.putInt(BackupManagerMonitor.EXTRA_LOG_EVENT_ID, id);
11436                bundle.putInt(BackupManagerMonitor.EXTRA_LOG_EVENT_CATEGORY, category);
11437                if (pkg != null) {
11438                    bundle.putString(EXTRA_LOG_EVENT_PACKAGE_NAME,
11439                            pkg.packageName);
11440                    bundle.putInt(BackupManagerMonitor.EXTRA_LOG_EVENT_PACKAGE_VERSION,
11441                            pkg.versionCode);
11442                }
11443                if (extras != null) {
11444                    bundle.putAll(extras);
11445                }
11446                monitor.onEvent(bundle);
11447                return monitor;
11448            } catch(RemoteException e) {
11449                if (DEBUG) {
11450                    Slog.w(TAG, "backup manager monitor went away");
11451                }
11452            }
11453        }
11454        return null;
11455    }
11456
11457    @Override
11458    public IBackupManager getBackupManagerBinder() {
11459        return mBackupManagerBinder;
11460    }
11461
11462}
11463