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