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