BackupManagerService.java revision cce476034388383a6006555a225e2170f3b4dcd9
1/* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.backup; 18 19import android.app.ActivityManagerNative; 20import android.app.AlarmManager; 21import android.app.AppGlobals; 22import android.app.IActivityManager; 23import android.app.IApplicationThread; 24import android.app.IBackupAgent; 25import android.app.PendingIntent; 26import android.app.backup.BackupAgent; 27import android.app.backup.BackupDataInput; 28import android.app.backup.BackupDataOutput; 29import android.app.backup.BackupTransport; 30import android.app.backup.FullBackup; 31import android.app.backup.RestoreDescription; 32import android.app.backup.RestoreSet; 33import android.app.backup.IBackupManager; 34import android.app.backup.IFullBackupRestoreObserver; 35import android.app.backup.IRestoreObserver; 36import android.app.backup.IRestoreSession; 37import android.app.job.JobParameters; 38import android.content.ActivityNotFoundException; 39import android.content.BroadcastReceiver; 40import android.content.ComponentName; 41import android.content.ContentResolver; 42import android.content.Context; 43import android.content.Intent; 44import android.content.IntentFilter; 45import android.content.ServiceConnection; 46import android.content.pm.ApplicationInfo; 47import android.content.pm.IPackageDataObserver; 48import android.content.pm.IPackageDeleteObserver; 49import android.content.pm.IPackageInstallObserver; 50import android.content.pm.IPackageManager; 51import android.content.pm.PackageInfo; 52import android.content.pm.PackageManager; 53import android.content.pm.ResolveInfo; 54import android.content.pm.ServiceInfo; 55import android.content.pm.Signature; 56import android.content.pm.PackageManager.NameNotFoundException; 57import android.database.ContentObserver; 58import android.net.Uri; 59import android.os.Binder; 60import android.os.Build; 61import android.os.Bundle; 62import android.os.Environment; 63import android.os.Handler; 64import android.os.HandlerThread; 65import android.os.IBinder; 66import android.os.Looper; 67import android.os.Message; 68import android.os.ParcelFileDescriptor; 69import android.os.PowerManager; 70import android.os.Process; 71import android.os.RemoteException; 72import android.os.SELinux; 73import android.os.ServiceManager; 74import android.os.SystemClock; 75import android.os.UserHandle; 76import android.os.WorkSource; 77import android.os.Environment.UserEnvironment; 78import android.os.storage.IMountService; 79import android.provider.Settings; 80import android.system.ErrnoException; 81import android.system.Os; 82import android.util.AtomicFile; 83import android.util.EventLog; 84import android.util.Log; 85import android.util.Slog; 86import android.util.SparseArray; 87import android.util.StringBuilderPrinter; 88 89import com.android.internal.backup.IBackupTransport; 90import com.android.internal.backup.IObbBackupService; 91import com.android.server.AppWidgetBackupBridge; 92import com.android.server.EventLogTags; 93import com.android.server.SystemService; 94import com.android.server.backup.PackageManagerBackupAgent.Metadata; 95 96import java.io.BufferedInputStream; 97import java.io.BufferedOutputStream; 98import java.io.ByteArrayInputStream; 99import java.io.ByteArrayOutputStream; 100import java.io.DataInputStream; 101import java.io.DataOutputStream; 102import java.io.EOFException; 103import java.io.File; 104import java.io.FileDescriptor; 105import java.io.FileInputStream; 106import java.io.FileNotFoundException; 107import java.io.FileOutputStream; 108import java.io.IOException; 109import java.io.InputStream; 110import java.io.OutputStream; 111import java.io.PrintWriter; 112import java.io.RandomAccessFile; 113import java.security.InvalidAlgorithmParameterException; 114import java.security.InvalidKeyException; 115import java.security.Key; 116import java.security.MessageDigest; 117import java.security.NoSuchAlgorithmException; 118import java.security.SecureRandom; 119import java.security.spec.InvalidKeySpecException; 120import java.security.spec.KeySpec; 121import java.text.SimpleDateFormat; 122import java.util.ArrayList; 123import java.util.Arrays; 124import java.util.Collections; 125import java.util.Date; 126import java.util.HashMap; 127import java.util.HashSet; 128import java.util.Iterator; 129import java.util.List; 130import java.util.Map; 131import java.util.Map.Entry; 132import java.util.Random; 133import java.util.Set; 134import java.util.TreeMap; 135import java.util.concurrent.atomic.AtomicBoolean; 136import java.util.concurrent.atomic.AtomicInteger; 137import java.util.zip.Deflater; 138import java.util.zip.DeflaterOutputStream; 139import java.util.zip.InflaterInputStream; 140 141import javax.crypto.BadPaddingException; 142import javax.crypto.Cipher; 143import javax.crypto.CipherInputStream; 144import javax.crypto.CipherOutputStream; 145import javax.crypto.IllegalBlockSizeException; 146import javax.crypto.NoSuchPaddingException; 147import javax.crypto.SecretKey; 148import javax.crypto.SecretKeyFactory; 149import javax.crypto.spec.IvParameterSpec; 150import javax.crypto.spec.PBEKeySpec; 151import javax.crypto.spec.SecretKeySpec; 152 153import libcore.io.IoUtils; 154 155public class BackupManagerService extends IBackupManager.Stub { 156 157 private static final String TAG = "BackupManagerService"; 158 private static final boolean DEBUG = true; 159 private static final boolean MORE_DEBUG = false; 160 private static final boolean DEBUG_SCHEDULING = MORE_DEBUG || true; 161 162 // System-private key used for backing up an app's widget state. Must 163 // begin with U+FFxx by convention (we reserve all keys starting 164 // with U+FF00 or higher for system use). 165 static final String KEY_WIDGET_STATE = "\uffed\uffedwidget"; 166 167 // Historical and current algorithm names 168 static final String PBKDF_CURRENT = "PBKDF2WithHmacSHA1"; 169 static final String PBKDF_FALLBACK = "PBKDF2WithHmacSHA1And8bit"; 170 171 // Name and current contents version of the full-backup manifest file 172 // 173 // Manifest version history: 174 // 175 // 1 : initial release 176 static final String BACKUP_MANIFEST_FILENAME = "_manifest"; 177 static final int BACKUP_MANIFEST_VERSION = 1; 178 179 // External archive format version history: 180 // 181 // 1 : initial release 182 // 2 : no format change per se; version bump to facilitate PBKDF2 version skew detection 183 // 3 : introduced "_meta" metadata file; no other format change per se 184 static final int BACKUP_FILE_VERSION = 3; 185 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n"; 186 static final int BACKUP_PW_FILE_VERSION = 2; 187 static final String BACKUP_METADATA_FILENAME = "_meta"; 188 static final int BACKUP_METADATA_VERSION = 1; 189 static final int BACKUP_WIDGET_METADATA_TOKEN = 0x01FFED01; 190 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production 191 192 static final String SETTINGS_PACKAGE = "com.android.providers.settings"; 193 static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup"; 194 static final String SERVICE_ACTION_TRANSPORT_HOST = "android.backup.TRANSPORT_HOST"; 195 196 // How often we perform a backup pass. Privileged external callers can 197 // trigger an immediate pass. 198 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR; 199 200 // Random variation in backup scheduling time to avoid server load spikes 201 private static final int FUZZ_MILLIS = 5 * 60 * 1000; 202 203 // The amount of time between the initial provisioning of the device and 204 // the first backup pass. 205 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR; 206 207 // Retry interval for clear/init when the transport is unavailable 208 private static final long TRANSPORT_RETRY_INTERVAL = 1 * AlarmManager.INTERVAL_HOUR; 209 210 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN"; 211 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT"; 212 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR"; 213 private static final int MSG_RUN_BACKUP = 1; 214 private static final int MSG_RUN_ADB_BACKUP = 2; 215 private static final int MSG_RUN_RESTORE = 3; 216 private static final int MSG_RUN_CLEAR = 4; 217 private static final int MSG_RUN_INITIALIZE = 5; 218 private static final int MSG_RUN_GET_RESTORE_SETS = 6; 219 private static final int MSG_TIMEOUT = 7; 220 private static final int MSG_RESTORE_TIMEOUT = 8; 221 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9; 222 private static final int MSG_RUN_ADB_RESTORE = 10; 223 private static final int MSG_RETRY_INIT = 11; 224 private static final int MSG_RETRY_CLEAR = 12; 225 private static final int MSG_WIDGET_BROADCAST = 13; 226 private static final int MSG_RUN_FULL_TRANSPORT_BACKUP = 14; 227 228 // backup task state machine tick 229 static final int MSG_BACKUP_RESTORE_STEP = 20; 230 static final int MSG_OP_COMPLETE = 21; 231 232 // Timeout interval for deciding that a bind or clear-data has taken too long 233 static final long TIMEOUT_INTERVAL = 10 * 1000; 234 235 // Timeout intervals for agent backup & restore operations 236 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000; 237 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000; 238 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000; 239 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000; 240 static final long TIMEOUT_RESTORE_FINISHED_INTERVAL = 30 * 1000; 241 242 // User confirmation timeout for a full backup/restore operation. It's this long in 243 // order to give them time to enter the backup password. 244 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000; 245 246 // How long between attempts to perform a full-data backup of any given app 247 static final long MIN_FULL_BACKUP_INTERVAL = 1000 * 60 * 60 * 24; // one day 248 249 Context mContext; 250 private PackageManager mPackageManager; 251 IPackageManager mPackageManagerBinder; 252 private IActivityManager mActivityManager; 253 private PowerManager mPowerManager; 254 private AlarmManager mAlarmManager; 255 private IMountService mMountService; 256 IBackupManager mBackupManagerBinder; 257 258 boolean mEnabled; // access to this is synchronized on 'this' 259 boolean mProvisioned; 260 boolean mAutoRestore; 261 PowerManager.WakeLock mWakelock; 262 HandlerThread mHandlerThread; 263 BackupHandler mBackupHandler; 264 PendingIntent mRunBackupIntent, mRunInitIntent; 265 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver; 266 // map UIDs to the set of participating packages under that UID 267 final SparseArray<HashSet<String>> mBackupParticipants 268 = new SparseArray<HashSet<String>>(); 269 // set of backup services that have pending changes 270 class BackupRequest { 271 public String packageName; 272 273 BackupRequest(String pkgName) { 274 packageName = pkgName; 275 } 276 277 public String toString() { 278 return "BackupRequest{pkg=" + packageName + "}"; 279 } 280 } 281 // Backups that we haven't started yet. Keys are package names. 282 HashMap<String,BackupRequest> mPendingBackups 283 = new HashMap<String,BackupRequest>(); 284 285 // Pseudoname that we use for the Package Manager metadata "package" 286 static final String PACKAGE_MANAGER_SENTINEL = "@pm@"; 287 288 // locking around the pending-backup management 289 final Object mQueueLock = new Object(); 290 291 // The thread performing the sequence of queued backups binds to each app's agent 292 // in succession. Bind notifications are asynchronously delivered through the 293 // Activity Manager; use this lock object to signal when a requested binding has 294 // completed. 295 final Object mAgentConnectLock = new Object(); 296 IBackupAgent mConnectedAgent; 297 volatile boolean mBackupRunning; 298 volatile boolean mConnecting; 299 volatile long mLastBackupPass; 300 volatile long mNextBackupPass; 301 302 // For debugging, we maintain a progress trace of operations during backup 303 static final boolean DEBUG_BACKUP_TRACE = true; 304 final List<String> mBackupTrace = new ArrayList<String>(); 305 306 // A similar synchronization mechanism around clearing apps' data for restore 307 final Object mClearDataLock = new Object(); 308 volatile boolean mClearingData; 309 310 // Transport bookkeeping 311 final HashMap<String,String> mTransportNames 312 = new HashMap<String,String>(); // component name -> registration name 313 final HashMap<String,IBackupTransport> mTransports 314 = new HashMap<String,IBackupTransport>(); // registration name -> binder 315 final ArrayList<TransportConnection> mTransportConnections 316 = new ArrayList<TransportConnection>(); 317 String mCurrentTransport; 318 ActiveRestoreSession mActiveRestoreSession; 319 320 // Watch the device provisioning operation during setup 321 ContentObserver mProvisionedObserver; 322 323 static BackupManagerService sInstance; 324 static BackupManagerService getInstance() { 325 // Always constructed during system bringup, so no need to lazy-init 326 return sInstance; 327 } 328 329 public static final class Lifecycle extends SystemService { 330 331 public Lifecycle(Context context) { 332 super(context); 333 sInstance = new BackupManagerService(context); 334 } 335 336 @Override 337 public void onStart() { 338 publishBinderService(Context.BACKUP_SERVICE, sInstance); 339 } 340 341 @Override 342 public void onBootPhase(int phase) { 343 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) { 344 ContentResolver r = sInstance.mContext.getContentResolver(); 345 boolean areEnabled = Settings.Secure.getInt(r, 346 Settings.Secure.BACKUP_ENABLED, 0) != 0; 347 sInstance.setBackupEnabled(areEnabled); 348 } 349 } 350 } 351 352 class ProvisionedObserver extends ContentObserver { 353 public ProvisionedObserver(Handler handler) { 354 super(handler); 355 } 356 357 public void onChange(boolean selfChange) { 358 final boolean wasProvisioned = mProvisioned; 359 final boolean isProvisioned = deviceIsProvisioned(); 360 // latch: never unprovision 361 mProvisioned = wasProvisioned || isProvisioned; 362 if (MORE_DEBUG) { 363 Slog.d(TAG, "Provisioning change: was=" + wasProvisioned 364 + " is=" + isProvisioned + " now=" + mProvisioned); 365 } 366 367 synchronized (mQueueLock) { 368 if (mProvisioned && !wasProvisioned && mEnabled) { 369 // we're now good to go, so start the backup alarms 370 if (MORE_DEBUG) Slog.d(TAG, "Now provisioned, so starting backups"); 371 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL); 372 } 373 } 374 } 375 } 376 377 class RestoreGetSetsParams { 378 public IBackupTransport transport; 379 public ActiveRestoreSession session; 380 public IRestoreObserver observer; 381 382 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session, 383 IRestoreObserver _observer) { 384 transport = _transport; 385 session = _session; 386 observer = _observer; 387 } 388 } 389 390 class RestoreParams { 391 public IBackupTransport transport; 392 public String dirName; 393 public IRestoreObserver observer; 394 public long token; 395 public PackageInfo pkgInfo; 396 public int pmToken; // in post-install restore, the PM's token for this transaction 397 public boolean isSystemRestore; 398 public String[] filterSet; 399 400 // Restore a single package 401 RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs, 402 long _token, PackageInfo _pkg, int _pmToken) { 403 transport = _transport; 404 dirName = _dirName; 405 observer = _obs; 406 token = _token; 407 pkgInfo = _pkg; 408 pmToken = _pmToken; 409 isSystemRestore = false; 410 filterSet = null; 411 } 412 413 // Restore everything possible. This is the form that Setup Wizard or similar 414 // restore UXes use. 415 RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs, 416 long _token) { 417 transport = _transport; 418 dirName = _dirName; 419 observer = _obs; 420 token = _token; 421 pkgInfo = null; 422 pmToken = 0; 423 isSystemRestore = true; 424 filterSet = null; 425 } 426 427 // Restore some set of packages. Leave this one up to the caller to specify 428 // whether it's to be considered a system-level restore. 429 RestoreParams(IBackupTransport _transport, String _dirName, IRestoreObserver _obs, 430 long _token, String[] _filterSet, boolean _isSystemRestore) { 431 transport = _transport; 432 dirName = _dirName; 433 observer = _obs; 434 token = _token; 435 pkgInfo = null; 436 pmToken = 0; 437 isSystemRestore = _isSystemRestore; 438 filterSet = _filterSet; 439 } 440 } 441 442 class ClearParams { 443 public IBackupTransport transport; 444 public PackageInfo packageInfo; 445 446 ClearParams(IBackupTransport _transport, PackageInfo _info) { 447 transport = _transport; 448 packageInfo = _info; 449 } 450 } 451 452 class ClearRetryParams { 453 public String transportName; 454 public String packageName; 455 456 ClearRetryParams(String transport, String pkg) { 457 transportName = transport; 458 packageName = pkg; 459 } 460 } 461 462 class FullParams { 463 public ParcelFileDescriptor fd; 464 public final AtomicBoolean latch; 465 public IFullBackupRestoreObserver observer; 466 public String curPassword; // filled in by the confirmation step 467 public String encryptPassword; 468 469 FullParams() { 470 latch = new AtomicBoolean(false); 471 } 472 } 473 474 class FullBackupParams extends FullParams { 475 public boolean includeApks; 476 public boolean includeObbs; 477 public boolean includeShared; 478 public boolean doWidgets; 479 public boolean allApps; 480 public boolean includeSystem; 481 public boolean doCompress; 482 public String[] packages; 483 484 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveObbs, 485 boolean saveShared, boolean alsoWidgets, boolean doAllApps, boolean doSystem, 486 boolean compress, String[] pkgList) { 487 fd = output; 488 includeApks = saveApks; 489 includeObbs = saveObbs; 490 includeShared = saveShared; 491 doWidgets = alsoWidgets; 492 allApps = doAllApps; 493 includeSystem = doSystem; 494 doCompress = compress; 495 packages = pkgList; 496 } 497 } 498 499 class FullRestoreParams extends FullParams { 500 FullRestoreParams(ParcelFileDescriptor input) { 501 fd = input; 502 } 503 } 504 505 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation 506 // token is the index of the entry in the pending-operations list. 507 static final int OP_PENDING = 0; 508 static final int OP_ACKNOWLEDGED = 1; 509 static final int OP_TIMEOUT = -1; 510 511 class Operation { 512 public int state; 513 public BackupRestoreTask callback; 514 515 Operation(int initialState, BackupRestoreTask callbackObj) { 516 state = initialState; 517 callback = callbackObj; 518 } 519 } 520 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>(); 521 final Object mCurrentOpLock = new Object(); 522 final Random mTokenGenerator = new Random(); 523 524 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>(); 525 526 // Where we keep our journal files and other bookkeeping 527 File mBaseStateDir; 528 File mDataDir; 529 File mJournalDir; 530 File mJournal; 531 532 // Backup password, if any, and the file where it's saved. What is stored is not the 533 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but 534 // persisted) salt. Validation is performed by running the challenge text through the 535 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches 536 // the saved hash string, then the challenge text matches the originally supplied 537 // password text. 538 private final SecureRandom mRng = new SecureRandom(); 539 private String mPasswordHash; 540 private File mPasswordHashFile; 541 private int mPasswordVersion; 542 private File mPasswordVersionFile; 543 private byte[] mPasswordSalt; 544 545 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys 546 static final int PBKDF2_HASH_ROUNDS = 10000; 547 static final int PBKDF2_KEY_SIZE = 256; // bits 548 static final int PBKDF2_SALT_SIZE = 512; // bits 549 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256"; 550 551 // Keep a log of all the apps we've ever backed up, and what the 552 // dataset tokens are for both the current backup dataset and 553 // the ancestral dataset. 554 private File mEverStored; 555 HashSet<String> mEverStoredApps = new HashSet<String>(); 556 557 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes 558 File mTokenFile; 559 Set<String> mAncestralPackages = null; 560 long mAncestralToken = 0; 561 long mCurrentToken = 0; 562 563 // Persistently track the need to do a full init 564 static final String INIT_SENTINEL_FILE_NAME = "_need_init_"; 565 HashSet<String> mPendingInits = new HashSet<String>(); // transport names 566 567 // Round-robin queue for scheduling full backup passes 568 static final int SCHEDULE_FILE_VERSION = 1; // current version of the schedule file 569 class FullBackupEntry implements Comparable<FullBackupEntry> { 570 String packageName; 571 long lastBackup; 572 573 FullBackupEntry(String pkg, long when) { 574 packageName = pkg; 575 lastBackup = when; 576 } 577 578 @Override 579 public int compareTo(FullBackupEntry other) { 580 if (lastBackup < other.lastBackup) return -1; 581 else if (lastBackup > other.lastBackup) return 1; 582 else return 0; 583 } 584 } 585 586 File mFullBackupScheduleFile; 587 // If we're running a schedule-driven full backup, this is the task instance doing it 588 PerformFullTransportBackupTask mRunningFullBackupTask; // inside mQueueLock 589 ArrayList<FullBackupEntry> mFullBackupQueue; // inside mQueueLock 590 591 // Utility: build a new random integer token 592 int generateToken() { 593 int token; 594 do { 595 synchronized (mTokenGenerator) { 596 token = mTokenGenerator.nextInt(); 597 } 598 } while (token < 0); 599 return token; 600 } 601 602 // High level policy: apps are ineligible for backup if certain conditions apply 603 public static boolean appIsEligibleForBackup(ApplicationInfo app) { 604 // 1. their manifest states android:allowBackup="false" 605 if ((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) { 606 return false; 607 } 608 609 // 2. they run as a system-level uid but do not supply their own backup agent 610 if ((app.uid < Process.FIRST_APPLICATION_UID) && (app.backupAgentName == null)) { 611 return false; 612 } 613 614 // 3. it is the special shared-storage backup package used for 'adb backup' 615 if (app.packageName.equals(BackupManagerService.SHARED_BACKUP_AGENT_PACKAGE)) { 616 return false; 617 } 618 619 return true; 620 } 621 622 /* does *not* check overall backup eligibility policy! */ 623 public static boolean appGetsFullBackup(PackageInfo pkg) { 624 if (pkg.applicationInfo.backupAgentName != null) { 625 // If it has an agent, it gets full backups only if it says so 626 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FULL_BACKUP_ONLY) != 0; 627 } 628 629 // No agent means we do full backups for it 630 return true; 631 } 632 633 // ----- Asynchronous backup/restore handler thread ----- 634 635 private class BackupHandler extends Handler { 636 public BackupHandler(Looper looper) { 637 super(looper); 638 } 639 640 public void handleMessage(Message msg) { 641 642 switch (msg.what) { 643 case MSG_RUN_BACKUP: 644 { 645 mLastBackupPass = System.currentTimeMillis(); 646 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL; 647 648 IBackupTransport transport = getTransport(mCurrentTransport); 649 if (transport == null) { 650 Slog.v(TAG, "Backup requested but no transport available"); 651 synchronized (mQueueLock) { 652 mBackupRunning = false; 653 } 654 mWakelock.release(); 655 break; 656 } 657 658 // snapshot the pending-backup set and work on that 659 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>(); 660 File oldJournal = mJournal; 661 synchronized (mQueueLock) { 662 // Do we have any work to do? Construct the work queue 663 // then release the synchronization lock to actually run 664 // the backup. 665 if (mPendingBackups.size() > 0) { 666 for (BackupRequest b: mPendingBackups.values()) { 667 queue.add(b); 668 } 669 if (DEBUG) Slog.v(TAG, "clearing pending backups"); 670 mPendingBackups.clear(); 671 672 // Start a new backup-queue journal file too 673 mJournal = null; 674 675 } 676 } 677 678 // At this point, we have started a new journal file, and the old 679 // file identity is being passed to the backup processing task. 680 // When it completes successfully, that old journal file will be 681 // deleted. If we crash prior to that, the old journal is parsed 682 // at next boot and the journaled requests fulfilled. 683 boolean staged = true; 684 if (queue.size() > 0) { 685 // Spin up a backup state sequence and set it running 686 try { 687 String dirName = transport.transportDirName(); 688 PerformBackupTask pbt = new PerformBackupTask(transport, dirName, 689 queue, oldJournal); 690 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt); 691 sendMessage(pbtMessage); 692 } catch (RemoteException e) { 693 // unable to ask the transport its dir name -- transient failure, since 694 // the above check succeeded. Try again next time. 695 Slog.e(TAG, "Transport became unavailable attempting backup"); 696 staged = false; 697 } 698 } else { 699 Slog.v(TAG, "Backup requested but nothing pending"); 700 staged = false; 701 } 702 703 if (!staged) { 704 // if we didn't actually hand off the wakelock, rewind until next time 705 synchronized (mQueueLock) { 706 mBackupRunning = false; 707 } 708 mWakelock.release(); 709 } 710 break; 711 } 712 713 case MSG_BACKUP_RESTORE_STEP: 714 { 715 try { 716 BackupRestoreTask task = (BackupRestoreTask) msg.obj; 717 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing"); 718 task.execute(); 719 } catch (ClassCastException e) { 720 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj); 721 } 722 break; 723 } 724 725 case MSG_OP_COMPLETE: 726 { 727 try { 728 BackupRestoreTask task = (BackupRestoreTask) msg.obj; 729 task.operationComplete(); 730 } catch (ClassCastException e) { 731 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj); 732 } 733 break; 734 } 735 736 case MSG_RUN_ADB_BACKUP: 737 { 738 // TODO: refactor full backup to be a looper-based state machine 739 // similar to normal backup/restore. 740 FullBackupParams params = (FullBackupParams)msg.obj; 741 PerformAdbBackupTask task = new PerformAdbBackupTask(params.fd, 742 params.observer, params.includeApks, params.includeObbs, 743 params.includeShared, params.doWidgets, 744 params.curPassword, params.encryptPassword, 745 params.allApps, params.includeSystem, params.doCompress, 746 params.packages, params.latch); 747 (new Thread(task, "adb-backup")).start(); 748 break; 749 } 750 751 case MSG_RUN_FULL_TRANSPORT_BACKUP: 752 { 753 PerformFullTransportBackupTask task = (PerformFullTransportBackupTask) msg.obj; 754 (new Thread(task, "transport-backup")).start(); 755 break; 756 } 757 758 case MSG_RUN_RESTORE: 759 { 760 RestoreParams params = (RestoreParams)msg.obj; 761 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer); 762 BackupRestoreTask task = new PerformUnifiedRestoreTask(params.transport, 763 params.observer, params.token, params.pkgInfo, params.pmToken, 764 params.isSystemRestore, params.filterSet); 765 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task); 766 sendMessage(restoreMsg); 767 break; 768 } 769 770 case MSG_RUN_ADB_RESTORE: 771 { 772 // TODO: refactor full restore to be a looper-based state machine 773 // similar to normal backup/restore. 774 FullRestoreParams params = (FullRestoreParams)msg.obj; 775 PerformAdbRestoreTask task = new PerformAdbRestoreTask(params.fd, 776 params.curPassword, params.encryptPassword, 777 params.observer, params.latch); 778 (new Thread(task, "adb-restore")).start(); 779 break; 780 } 781 782 case MSG_RUN_CLEAR: 783 { 784 ClearParams params = (ClearParams)msg.obj; 785 (new PerformClearTask(params.transport, params.packageInfo)).run(); 786 break; 787 } 788 789 case MSG_RETRY_CLEAR: 790 { 791 // reenqueues if the transport remains unavailable 792 ClearRetryParams params = (ClearRetryParams)msg.obj; 793 clearBackupData(params.transportName, params.packageName); 794 break; 795 } 796 797 case MSG_RUN_INITIALIZE: 798 { 799 HashSet<String> queue; 800 801 // Snapshot the pending-init queue and work on that 802 synchronized (mQueueLock) { 803 queue = new HashSet<String>(mPendingInits); 804 mPendingInits.clear(); 805 } 806 807 (new PerformInitializeTask(queue)).run(); 808 break; 809 } 810 811 case MSG_RETRY_INIT: 812 { 813 synchronized (mQueueLock) { 814 recordInitPendingLocked(msg.arg1 != 0, (String)msg.obj); 815 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 816 mRunInitIntent); 817 } 818 break; 819 } 820 821 case MSG_RUN_GET_RESTORE_SETS: 822 { 823 // Like other async operations, this is entered with the wakelock held 824 RestoreSet[] sets = null; 825 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj; 826 try { 827 sets = params.transport.getAvailableRestoreSets(); 828 // cache the result in the active session 829 synchronized (params.session) { 830 params.session.mRestoreSets = sets; 831 } 832 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE); 833 } catch (Exception e) { 834 Slog.e(TAG, "Error from transport getting set list"); 835 } finally { 836 if (params.observer != null) { 837 try { 838 params.observer.restoreSetsAvailable(sets); 839 } catch (RemoteException re) { 840 Slog.e(TAG, "Unable to report listing to observer"); 841 } catch (Exception e) { 842 Slog.e(TAG, "Restore observer threw", e); 843 } 844 } 845 846 // Done: reset the session timeout clock 847 removeMessages(MSG_RESTORE_TIMEOUT); 848 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL); 849 850 mWakelock.release(); 851 } 852 break; 853 } 854 855 case MSG_TIMEOUT: 856 { 857 handleTimeout(msg.arg1, msg.obj); 858 break; 859 } 860 861 case MSG_RESTORE_TIMEOUT: 862 { 863 synchronized (BackupManagerService.this) { 864 if (mActiveRestoreSession != null) { 865 // Client app left the restore session dangling. We know that it 866 // can't be in the middle of an actual restore operation because 867 // the timeout is suspended while a restore is in progress. Clean 868 // up now. 869 Slog.w(TAG, "Restore session timed out; aborting"); 870 post(mActiveRestoreSession.new EndRestoreRunnable( 871 BackupManagerService.this, mActiveRestoreSession)); 872 } 873 } 874 } 875 876 case MSG_FULL_CONFIRMATION_TIMEOUT: 877 { 878 synchronized (mFullConfirmations) { 879 FullParams params = mFullConfirmations.get(msg.arg1); 880 if (params != null) { 881 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation"); 882 883 // Release the waiter; timeout == completion 884 signalFullBackupRestoreCompletion(params); 885 886 // Remove the token from the set 887 mFullConfirmations.delete(msg.arg1); 888 889 // Report a timeout to the observer, if any 890 if (params.observer != null) { 891 try { 892 params.observer.onTimeout(); 893 } catch (RemoteException e) { 894 /* don't care if the app has gone away */ 895 } 896 } 897 } else { 898 Slog.d(TAG, "couldn't find params for token " + msg.arg1); 899 } 900 } 901 break; 902 } 903 904 case MSG_WIDGET_BROADCAST: 905 { 906 final Intent intent = (Intent) msg.obj; 907 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER); 908 break; 909 } 910 } 911 } 912 } 913 914 // ----- Debug-only backup operation trace ----- 915 void addBackupTrace(String s) { 916 if (DEBUG_BACKUP_TRACE) { 917 synchronized (mBackupTrace) { 918 mBackupTrace.add(s); 919 } 920 } 921 } 922 923 void clearBackupTrace() { 924 if (DEBUG_BACKUP_TRACE) { 925 synchronized (mBackupTrace) { 926 mBackupTrace.clear(); 927 } 928 } 929 } 930 931 // ----- Main service implementation ----- 932 933 public BackupManagerService(Context context) { 934 mContext = context; 935 mPackageManager = context.getPackageManager(); 936 mPackageManagerBinder = AppGlobals.getPackageManager(); 937 mActivityManager = ActivityManagerNative.getDefault(); 938 939 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 940 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 941 mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount")); 942 943 mBackupManagerBinder = asInterface(asBinder()); 944 945 // spin up the backup/restore handler thread 946 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND); 947 mHandlerThread.start(); 948 mBackupHandler = new BackupHandler(mHandlerThread.getLooper()); 949 950 // Set up our bookkeeping 951 final ContentResolver resolver = context.getContentResolver(); 952 mProvisioned = Settings.Global.getInt(resolver, 953 Settings.Global.DEVICE_PROVISIONED, 0) != 0; 954 mAutoRestore = Settings.Secure.getInt(resolver, 955 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0; 956 957 mProvisionedObserver = new ProvisionedObserver(mBackupHandler); 958 resolver.registerContentObserver( 959 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), 960 false, mProvisionedObserver); 961 962 // If Encrypted file systems is enabled or disabled, this call will return the 963 // correct directory. 964 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup"); 965 mBaseStateDir.mkdirs(); 966 if (!SELinux.restorecon(mBaseStateDir)) { 967 Slog.e(TAG, "SELinux restorecon failed on " + mBaseStateDir); 968 } 969 mDataDir = Environment.getDownloadCacheDirectory(); 970 971 mPasswordVersion = 1; // unless we hear otherwise 972 mPasswordVersionFile = new File(mBaseStateDir, "pwversion"); 973 if (mPasswordVersionFile.exists()) { 974 FileInputStream fin = null; 975 DataInputStream in = null; 976 try { 977 fin = new FileInputStream(mPasswordVersionFile); 978 in = new DataInputStream(fin); 979 mPasswordVersion = in.readInt(); 980 } catch (IOException e) { 981 Slog.e(TAG, "Unable to read backup pw version"); 982 } finally { 983 try { 984 if (in != null) in.close(); 985 if (fin != null) fin.close(); 986 } catch (IOException e) { 987 Slog.w(TAG, "Error closing pw version files"); 988 } 989 } 990 } 991 992 mPasswordHashFile = new File(mBaseStateDir, "pwhash"); 993 if (mPasswordHashFile.exists()) { 994 FileInputStream fin = null; 995 DataInputStream in = null; 996 try { 997 fin = new FileInputStream(mPasswordHashFile); 998 in = new DataInputStream(new BufferedInputStream(fin)); 999 // integer length of the salt array, followed by the salt, 1000 // then the hex pw hash string 1001 int saltLen = in.readInt(); 1002 byte[] salt = new byte[saltLen]; 1003 in.readFully(salt); 1004 mPasswordHash = in.readUTF(); 1005 mPasswordSalt = salt; 1006 } catch (IOException e) { 1007 Slog.e(TAG, "Unable to read saved backup pw hash"); 1008 } finally { 1009 try { 1010 if (in != null) in.close(); 1011 if (fin != null) fin.close(); 1012 } catch (IOException e) { 1013 Slog.w(TAG, "Unable to close streams"); 1014 } 1015 } 1016 } 1017 1018 // Alarm receivers for scheduled backups & initialization operations 1019 mRunBackupReceiver = new RunBackupReceiver(); 1020 IntentFilter filter = new IntentFilter(); 1021 filter.addAction(RUN_BACKUP_ACTION); 1022 context.registerReceiver(mRunBackupReceiver, filter, 1023 android.Manifest.permission.BACKUP, null); 1024 1025 mRunInitReceiver = new RunInitializeReceiver(); 1026 filter = new IntentFilter(); 1027 filter.addAction(RUN_INITIALIZE_ACTION); 1028 context.registerReceiver(mRunInitReceiver, filter, 1029 android.Manifest.permission.BACKUP, null); 1030 1031 Intent backupIntent = new Intent(RUN_BACKUP_ACTION); 1032 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 1033 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0); 1034 1035 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION); 1036 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 1037 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0); 1038 1039 // Set up the backup-request journaling 1040 mJournalDir = new File(mBaseStateDir, "pending"); 1041 mJournalDir.mkdirs(); // creates mBaseStateDir along the way 1042 mJournal = null; // will be created on first use 1043 1044 // Set up the various sorts of package tracking we do 1045 mFullBackupScheduleFile = new File(mBaseStateDir, "fb-schedule"); 1046 initPackageTracking(); 1047 1048 // Build our mapping of uid to backup client services. This implicitly 1049 // schedules a backup pass on the Package Manager metadata the first 1050 // time anything needs to be backed up. 1051 synchronized (mBackupParticipants) { 1052 addPackageParticipantsLocked(null); 1053 } 1054 1055 // Set up our transport options and initialize the default transport 1056 // TODO: Don't create transports that we don't need to? 1057 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(), 1058 Settings.Secure.BACKUP_TRANSPORT); 1059 if ("".equals(mCurrentTransport)) { 1060 mCurrentTransport = null; 1061 } 1062 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport); 1063 1064 // Find transport hosts and bind to their services 1065 Intent transportServiceIntent = new Intent(SERVICE_ACTION_TRANSPORT_HOST); 1066 List<ResolveInfo> hosts = mPackageManager.queryIntentServicesAsUser( 1067 transportServiceIntent, 0, UserHandle.USER_OWNER); 1068 if (DEBUG) { 1069 Slog.v(TAG, "Found transports: " + ((hosts == null) ? "null" : hosts.size())); 1070 } 1071 if (hosts != null) { 1072 if (MORE_DEBUG) { 1073 for (int i = 0; i < hosts.size(); i++) { 1074 ServiceInfo info = hosts.get(i).serviceInfo; 1075 Slog.v(TAG, " " + info.packageName + "/" + info.name); 1076 } 1077 } 1078 for (int i = 0; i < hosts.size(); i++) { 1079 try { 1080 ServiceInfo info = hosts.get(i).serviceInfo; 1081 PackageInfo packInfo = mPackageManager.getPackageInfo(info.packageName, 0); 1082 if ((packInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 1083 ComponentName svcName = new ComponentName(info.packageName, info.name); 1084 if (DEBUG) { 1085 Slog.i(TAG, "Binding to transport host " + svcName); 1086 } 1087 Intent intent = new Intent(transportServiceIntent); 1088 intent.setComponent(svcName); 1089 TransportConnection connection = new TransportConnection(); 1090 mTransportConnections.add(connection); 1091 context.bindServiceAsUser(intent, 1092 connection, Context.BIND_AUTO_CREATE, 1093 UserHandle.OWNER); 1094 } else { 1095 Slog.w(TAG, "Transport package not privileged: " + info.packageName); 1096 } 1097 } catch (Exception e) { 1098 Slog.e(TAG, "Problem resolving transport service: " + e.getMessage()); 1099 } 1100 } 1101 } 1102 1103 // Now that we know about valid backup participants, parse any 1104 // leftover journal files into the pending backup set 1105 parseLeftoverJournals(); 1106 1107 // Power management 1108 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*"); 1109 } 1110 1111 private class RunBackupReceiver extends BroadcastReceiver { 1112 public void onReceive(Context context, Intent intent) { 1113 if (RUN_BACKUP_ACTION.equals(intent.getAction())) { 1114 synchronized (mQueueLock) { 1115 if (mPendingInits.size() > 0) { 1116 // If there are pending init operations, we process those 1117 // and then settle into the usual periodic backup schedule. 1118 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup"); 1119 try { 1120 mAlarmManager.cancel(mRunInitIntent); 1121 mRunInitIntent.send(); 1122 } catch (PendingIntent.CanceledException ce) { 1123 Slog.e(TAG, "Run init intent cancelled"); 1124 // can't really do more than bail here 1125 } 1126 } else { 1127 // Don't run backups now if we're disabled or not yet 1128 // fully set up. 1129 if (mEnabled && mProvisioned) { 1130 if (!mBackupRunning) { 1131 if (DEBUG) Slog.v(TAG, "Running a backup pass"); 1132 1133 // Acquire the wakelock and pass it to the backup thread. it will 1134 // be released once backup concludes. 1135 mBackupRunning = true; 1136 mWakelock.acquire(); 1137 1138 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP); 1139 mBackupHandler.sendMessage(msg); 1140 } else { 1141 Slog.i(TAG, "Backup time but one already running"); 1142 } 1143 } else { 1144 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned); 1145 } 1146 } 1147 } 1148 } 1149 } 1150 } 1151 1152 private class RunInitializeReceiver extends BroadcastReceiver { 1153 public void onReceive(Context context, Intent intent) { 1154 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) { 1155 synchronized (mQueueLock) { 1156 if (DEBUG) Slog.v(TAG, "Running a device init"); 1157 1158 // Acquire the wakelock and pass it to the init thread. it will 1159 // be released once init concludes. 1160 mWakelock.acquire(); 1161 1162 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE); 1163 mBackupHandler.sendMessage(msg); 1164 } 1165 } 1166 } 1167 } 1168 1169 private void initPackageTracking() { 1170 if (MORE_DEBUG) Slog.v(TAG, "` tracking"); 1171 1172 // Remember our ancestral dataset 1173 mTokenFile = new File(mBaseStateDir, "ancestral"); 1174 try { 1175 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r"); 1176 int version = tf.readInt(); 1177 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) { 1178 mAncestralToken = tf.readLong(); 1179 mCurrentToken = tf.readLong(); 1180 1181 int numPackages = tf.readInt(); 1182 if (numPackages >= 0) { 1183 mAncestralPackages = new HashSet<String>(); 1184 for (int i = 0; i < numPackages; i++) { 1185 String pkgName = tf.readUTF(); 1186 mAncestralPackages.add(pkgName); 1187 } 1188 } 1189 } 1190 tf.close(); 1191 } catch (FileNotFoundException fnf) { 1192 // Probably innocuous 1193 Slog.v(TAG, "No ancestral data"); 1194 } catch (IOException e) { 1195 Slog.w(TAG, "Unable to read token file", e); 1196 } 1197 1198 // Keep a log of what apps we've ever backed up. Because we might have 1199 // rebooted in the middle of an operation that was removing something from 1200 // this log, we sanity-check its contents here and reconstruct it. 1201 mEverStored = new File(mBaseStateDir, "processed"); 1202 File tempProcessedFile = new File(mBaseStateDir, "processed.new"); 1203 1204 // If we were in the middle of removing something from the ever-backed-up 1205 // file, there might be a transient "processed.new" file still present. 1206 // Ignore it -- we'll validate "processed" against the current package set. 1207 if (tempProcessedFile.exists()) { 1208 tempProcessedFile.delete(); 1209 } 1210 1211 // If there are previous contents, parse them out then start a new 1212 // file to continue the recordkeeping. 1213 if (mEverStored.exists()) { 1214 RandomAccessFile temp = null; 1215 RandomAccessFile in = null; 1216 1217 try { 1218 temp = new RandomAccessFile(tempProcessedFile, "rws"); 1219 in = new RandomAccessFile(mEverStored, "r"); 1220 1221 while (true) { 1222 PackageInfo info; 1223 String pkg = in.readUTF(); 1224 try { 1225 info = mPackageManager.getPackageInfo(pkg, 0); 1226 mEverStoredApps.add(pkg); 1227 temp.writeUTF(pkg); 1228 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg); 1229 } catch (NameNotFoundException e) { 1230 // nope, this package was uninstalled; don't include it 1231 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg); 1232 } 1233 } 1234 } catch (EOFException e) { 1235 // Once we've rewritten the backup history log, atomically replace the 1236 // old one with the new one then reopen the file for continuing use. 1237 if (!tempProcessedFile.renameTo(mEverStored)) { 1238 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored); 1239 } 1240 } catch (IOException e) { 1241 Slog.e(TAG, "Error in processed file", e); 1242 } finally { 1243 try { if (temp != null) temp.close(); } catch (IOException e) {} 1244 try { if (in != null) in.close(); } catch (IOException e) {} 1245 } 1246 } 1247 1248 // Resume the full-data backup queue 1249 mFullBackupQueue = readFullBackupSchedule(); 1250 1251 // Register for broadcasts about package install, etc., so we can 1252 // update the provider list. 1253 IntentFilter filter = new IntentFilter(); 1254 filter.addAction(Intent.ACTION_PACKAGE_ADDED); 1255 filter.addAction(Intent.ACTION_PACKAGE_REMOVED); 1256 filter.addDataScheme("package"); 1257 mContext.registerReceiver(mBroadcastReceiver, filter); 1258 // Register for events related to sdcard installation. 1259 IntentFilter sdFilter = new IntentFilter(); 1260 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE); 1261 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE); 1262 mContext.registerReceiver(mBroadcastReceiver, sdFilter); 1263 } 1264 1265 private ArrayList<FullBackupEntry> readFullBackupSchedule() { 1266 ArrayList<FullBackupEntry> schedule = null; 1267 synchronized (mQueueLock) { 1268 if (mFullBackupScheduleFile.exists()) { 1269 try { 1270 FileInputStream fstream = new FileInputStream(mFullBackupScheduleFile); 1271 BufferedInputStream bufStream = new BufferedInputStream(fstream); 1272 DataInputStream in = new DataInputStream(bufStream); 1273 1274 int version = in.readInt(); 1275 if (version != SCHEDULE_FILE_VERSION) { 1276 Slog.e(TAG, "Unknown backup schedule version " + version); 1277 return null; 1278 } 1279 1280 int N = in.readInt(); 1281 schedule = new ArrayList<FullBackupEntry>(N); 1282 for (int i = 0; i < N; i++) { 1283 String pkgName = in.readUTF(); 1284 long lastBackup = in.readLong(); 1285 schedule.add(new FullBackupEntry(pkgName, lastBackup)); 1286 } 1287 Collections.sort(schedule); 1288 } catch (Exception e) { 1289 Slog.e(TAG, "Unable to read backup schedule", e); 1290 mFullBackupScheduleFile.delete(); 1291 schedule = null; 1292 } 1293 } 1294 1295 if (schedule == null) { 1296 // no prior queue record, or unable to read it. Set up the queue 1297 // from scratch. 1298 List<PackageInfo> apps = 1299 PackageManagerBackupAgent.getStorableApplications(mPackageManager); 1300 final int N = apps.size(); 1301 schedule = new ArrayList<FullBackupEntry>(N); 1302 for (int i = 0; i < N; i++) { 1303 PackageInfo info = apps.get(i); 1304 if (appGetsFullBackup(info)) { 1305 schedule.add(new FullBackupEntry(info.packageName, 0)); 1306 } 1307 } 1308 writeFullBackupScheduleAsync(); 1309 } 1310 } 1311 return schedule; 1312 } 1313 1314 Runnable mFullBackupScheduleWriter = new Runnable() { 1315 @Override public void run() { 1316 synchronized (mQueueLock) { 1317 try { 1318 ByteArrayOutputStream bufStream = new ByteArrayOutputStream(4096); 1319 DataOutputStream bufOut = new DataOutputStream(bufStream); 1320 bufOut.writeInt(SCHEDULE_FILE_VERSION); 1321 1322 // version 1: 1323 // 1324 // [int] # of packages in the queue = N 1325 // N * { 1326 // [utf8] package name 1327 // [long] last backup time for this package 1328 // } 1329 int N = mFullBackupQueue.size(); 1330 bufOut.writeInt(N); 1331 1332 for (int i = 0; i < N; i++) { 1333 FullBackupEntry entry = mFullBackupQueue.get(i); 1334 bufOut.writeUTF(entry.packageName); 1335 bufOut.writeLong(entry.lastBackup); 1336 } 1337 bufOut.flush(); 1338 1339 AtomicFile af = new AtomicFile(mFullBackupScheduleFile); 1340 FileOutputStream out = af.startWrite(); 1341 out.write(bufStream.toByteArray()); 1342 af.finishWrite(out); 1343 } catch (Exception e) { 1344 Slog.e(TAG, "Unable to write backup schedule!", e); 1345 } 1346 } 1347 } 1348 }; 1349 1350 private void writeFullBackupScheduleAsync() { 1351 mBackupHandler.removeCallbacks(mFullBackupScheduleWriter); 1352 mBackupHandler.post(mFullBackupScheduleWriter); 1353 } 1354 1355 private void parseLeftoverJournals() { 1356 for (File f : mJournalDir.listFiles()) { 1357 if (mJournal == null || f.compareTo(mJournal) != 0) { 1358 // This isn't the current journal, so it must be a leftover. Read 1359 // out the package names mentioned there and schedule them for 1360 // backup. 1361 RandomAccessFile in = null; 1362 try { 1363 Slog.i(TAG, "Found stale backup journal, scheduling"); 1364 in = new RandomAccessFile(f, "r"); 1365 while (true) { 1366 String packageName = in.readUTF(); 1367 if (MORE_DEBUG) Slog.i(TAG, " " + packageName); 1368 dataChangedImpl(packageName); 1369 } 1370 } catch (EOFException e) { 1371 // no more data; we're done 1372 } catch (Exception e) { 1373 Slog.e(TAG, "Can't read " + f, e); 1374 } finally { 1375 // close/delete the file 1376 try { if (in != null) in.close(); } catch (IOException e) {} 1377 f.delete(); 1378 } 1379 } 1380 } 1381 } 1382 1383 private SecretKey buildPasswordKey(String algorithm, String pw, byte[] salt, int rounds) { 1384 return buildCharArrayKey(algorithm, pw.toCharArray(), salt, rounds); 1385 } 1386 1387 private SecretKey buildCharArrayKey(String algorithm, char[] pwArray, byte[] salt, int rounds) { 1388 try { 1389 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm); 1390 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE); 1391 return keyFactory.generateSecret(ks); 1392 } catch (InvalidKeySpecException e) { 1393 Slog.e(TAG, "Invalid key spec for PBKDF2!"); 1394 } catch (NoSuchAlgorithmException e) { 1395 Slog.e(TAG, "PBKDF2 unavailable!"); 1396 } 1397 return null; 1398 } 1399 1400 private String buildPasswordHash(String algorithm, String pw, byte[] salt, int rounds) { 1401 SecretKey key = buildPasswordKey(algorithm, pw, salt, rounds); 1402 if (key != null) { 1403 return byteArrayToHex(key.getEncoded()); 1404 } 1405 return null; 1406 } 1407 1408 private String byteArrayToHex(byte[] data) { 1409 StringBuilder buf = new StringBuilder(data.length * 2); 1410 for (int i = 0; i < data.length; i++) { 1411 buf.append(Byte.toHexString(data[i], true)); 1412 } 1413 return buf.toString(); 1414 } 1415 1416 private byte[] hexToByteArray(String digits) { 1417 final int bytes = digits.length() / 2; 1418 if (2*bytes != digits.length()) { 1419 throw new IllegalArgumentException("Hex string must have an even number of digits"); 1420 } 1421 1422 byte[] result = new byte[bytes]; 1423 for (int i = 0; i < digits.length(); i += 2) { 1424 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16); 1425 } 1426 return result; 1427 } 1428 1429 private byte[] makeKeyChecksum(String algorithm, byte[] pwBytes, byte[] salt, int rounds) { 1430 char[] mkAsChar = new char[pwBytes.length]; 1431 for (int i = 0; i < pwBytes.length; i++) { 1432 mkAsChar[i] = (char) pwBytes[i]; 1433 } 1434 1435 Key checksum = buildCharArrayKey(algorithm, mkAsChar, salt, rounds); 1436 return checksum.getEncoded(); 1437 } 1438 1439 // Used for generating random salts or passwords 1440 private byte[] randomBytes(int bits) { 1441 byte[] array = new byte[bits / 8]; 1442 mRng.nextBytes(array); 1443 return array; 1444 } 1445 1446 // Backup password management 1447 boolean passwordMatchesSaved(String algorithm, String candidatePw, int rounds) { 1448 // First, on an encrypted device we require matching the device pw 1449 final boolean isEncrypted; 1450 try { 1451 isEncrypted = (mMountService.getEncryptionState() != 1452 IMountService.ENCRYPTION_STATE_NONE); 1453 if (isEncrypted) { 1454 if (DEBUG) { 1455 Slog.i(TAG, "Device encrypted; verifying against device data pw"); 1456 } 1457 // 0 means the password validated 1458 // -2 means device not encrypted 1459 // Any other result is either password failure or an error condition, 1460 // so we refuse the match 1461 final int result = mMountService.verifyEncryptionPassword(candidatePw); 1462 if (result == 0) { 1463 if (MORE_DEBUG) Slog.d(TAG, "Pw verifies"); 1464 return true; 1465 } else if (result != -2) { 1466 if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch"); 1467 return false; 1468 } else { 1469 // ...else the device is supposedly not encrypted. HOWEVER, the 1470 // query about the encryption state said that the device *is* 1471 // encrypted, so ... we may have a problem. Log it and refuse 1472 // the backup. 1473 Slog.e(TAG, "verified encryption state mismatch against query; no match allowed"); 1474 return false; 1475 } 1476 } 1477 } catch (Exception e) { 1478 // Something went wrong talking to the mount service. This is very bad; 1479 // assume that we fail password validation. 1480 return false; 1481 } 1482 1483 if (mPasswordHash == null) { 1484 // no current password case -- require that 'currentPw' be null or empty 1485 if (candidatePw == null || "".equals(candidatePw)) { 1486 return true; 1487 } // else the non-empty candidate does not match the empty stored pw 1488 } else { 1489 // hash the stated current pw and compare to the stored one 1490 if (candidatePw != null && candidatePw.length() > 0) { 1491 String currentPwHash = buildPasswordHash(algorithm, candidatePw, mPasswordSalt, rounds); 1492 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) { 1493 // candidate hash matches the stored hash -- the password matches 1494 return true; 1495 } 1496 } // else the stored pw is nonempty but the candidate is empty; no match 1497 } 1498 return false; 1499 } 1500 1501 @Override 1502 public boolean setBackupPassword(String currentPw, String newPw) { 1503 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 1504 "setBackupPassword"); 1505 1506 // When processing v1 passwords we may need to try two different PBKDF2 checksum regimes 1507 final boolean pbkdf2Fallback = (mPasswordVersion < BACKUP_PW_FILE_VERSION); 1508 1509 // If the supplied pw doesn't hash to the the saved one, fail. The password 1510 // might be caught in the legacy crypto mismatch; verify that too. 1511 if (!passwordMatchesSaved(PBKDF_CURRENT, currentPw, PBKDF2_HASH_ROUNDS) 1512 && !(pbkdf2Fallback && passwordMatchesSaved(PBKDF_FALLBACK, 1513 currentPw, PBKDF2_HASH_ROUNDS))) { 1514 return false; 1515 } 1516 1517 // Snap up to current on the pw file version 1518 mPasswordVersion = BACKUP_PW_FILE_VERSION; 1519 FileOutputStream pwFout = null; 1520 DataOutputStream pwOut = null; 1521 try { 1522 pwFout = new FileOutputStream(mPasswordVersionFile); 1523 pwOut = new DataOutputStream(pwFout); 1524 pwOut.writeInt(mPasswordVersion); 1525 } catch (IOException e) { 1526 Slog.e(TAG, "Unable to write backup pw version; password not changed"); 1527 return false; 1528 } finally { 1529 try { 1530 if (pwOut != null) pwOut.close(); 1531 if (pwFout != null) pwFout.close(); 1532 } catch (IOException e) { 1533 Slog.w(TAG, "Unable to close pw version record"); 1534 } 1535 } 1536 1537 // Clearing the password is okay 1538 if (newPw == null || newPw.isEmpty()) { 1539 if (mPasswordHashFile.exists()) { 1540 if (!mPasswordHashFile.delete()) { 1541 // Unable to delete the old pw file, so fail 1542 Slog.e(TAG, "Unable to clear backup password"); 1543 return false; 1544 } 1545 } 1546 mPasswordHash = null; 1547 mPasswordSalt = null; 1548 return true; 1549 } 1550 1551 try { 1552 // Okay, build the hash of the new backup password 1553 byte[] salt = randomBytes(PBKDF2_SALT_SIZE); 1554 String newPwHash = buildPasswordHash(PBKDF_CURRENT, newPw, salt, PBKDF2_HASH_ROUNDS); 1555 1556 OutputStream pwf = null, buffer = null; 1557 DataOutputStream out = null; 1558 try { 1559 pwf = new FileOutputStream(mPasswordHashFile); 1560 buffer = new BufferedOutputStream(pwf); 1561 out = new DataOutputStream(buffer); 1562 // integer length of the salt array, followed by the salt, 1563 // then the hex pw hash string 1564 out.writeInt(salt.length); 1565 out.write(salt); 1566 out.writeUTF(newPwHash); 1567 out.flush(); 1568 mPasswordHash = newPwHash; 1569 mPasswordSalt = salt; 1570 return true; 1571 } finally { 1572 if (out != null) out.close(); 1573 if (buffer != null) buffer.close(); 1574 if (pwf != null) pwf.close(); 1575 } 1576 } catch (IOException e) { 1577 Slog.e(TAG, "Unable to set backup password"); 1578 } 1579 return false; 1580 } 1581 1582 @Override 1583 public boolean hasBackupPassword() { 1584 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 1585 "hasBackupPassword"); 1586 1587 try { 1588 return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE) 1589 || (mPasswordHash != null && mPasswordHash.length() > 0); 1590 } catch (Exception e) { 1591 // If we can't talk to the mount service we have a serious problem; fail 1592 // "secure" i.e. assuming that we require a password 1593 return true; 1594 } 1595 } 1596 1597 private boolean backupPasswordMatches(String currentPw) { 1598 if (hasBackupPassword()) { 1599 final boolean pbkdf2Fallback = (mPasswordVersion < BACKUP_PW_FILE_VERSION); 1600 if (!passwordMatchesSaved(PBKDF_CURRENT, currentPw, PBKDF2_HASH_ROUNDS) 1601 && !(pbkdf2Fallback && passwordMatchesSaved(PBKDF_FALLBACK, 1602 currentPw, PBKDF2_HASH_ROUNDS))) { 1603 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting"); 1604 return false; 1605 } 1606 } 1607 return true; 1608 } 1609 1610 // Maintain persistent state around whether need to do an initialize operation. 1611 // Must be called with the queue lock held. 1612 void recordInitPendingLocked(boolean isPending, String transportName) { 1613 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending 1614 + " on transport " + transportName); 1615 mBackupHandler.removeMessages(MSG_RETRY_INIT); 1616 1617 try { 1618 IBackupTransport transport = getTransport(transportName); 1619 if (transport != null) { 1620 String transportDirName = transport.transportDirName(); 1621 File stateDir = new File(mBaseStateDir, transportDirName); 1622 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME); 1623 1624 if (isPending) { 1625 // We need an init before we can proceed with sending backup data. 1626 // Record that with an entry in our set of pending inits, as well as 1627 // journaling it via creation of a sentinel file. 1628 mPendingInits.add(transportName); 1629 try { 1630 (new FileOutputStream(initPendingFile)).close(); 1631 } catch (IOException ioe) { 1632 // Something is badly wrong with our permissions; just try to move on 1633 } 1634 } else { 1635 // No more initialization needed; wipe the journal and reset our state. 1636 initPendingFile.delete(); 1637 mPendingInits.remove(transportName); 1638 } 1639 return; // done; don't fall through to the error case 1640 } 1641 } catch (RemoteException e) { 1642 // transport threw when asked its name; fall through to the lookup-failed case 1643 } 1644 1645 // The named transport doesn't exist or threw. This operation is 1646 // important, so we record the need for a an init and post a message 1647 // to retry the init later. 1648 if (isPending) { 1649 mPendingInits.add(transportName); 1650 mBackupHandler.sendMessageDelayed( 1651 mBackupHandler.obtainMessage(MSG_RETRY_INIT, 1652 (isPending ? 1 : 0), 1653 0, 1654 transportName), 1655 TRANSPORT_RETRY_INTERVAL); 1656 } 1657 } 1658 1659 // Reset all of our bookkeeping, in response to having been told that 1660 // the backend data has been wiped [due to idle expiry, for example], 1661 // so we must re-upload all saved settings. 1662 void resetBackupState(File stateFileDir) { 1663 synchronized (mQueueLock) { 1664 // Wipe the "what we've ever backed up" tracking 1665 mEverStoredApps.clear(); 1666 mEverStored.delete(); 1667 1668 mCurrentToken = 0; 1669 writeRestoreTokens(); 1670 1671 // Remove all the state files 1672 for (File sf : stateFileDir.listFiles()) { 1673 // ... but don't touch the needs-init sentinel 1674 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) { 1675 sf.delete(); 1676 } 1677 } 1678 } 1679 1680 // Enqueue a new backup of every participant 1681 synchronized (mBackupParticipants) { 1682 final int N = mBackupParticipants.size(); 1683 for (int i=0; i<N; i++) { 1684 HashSet<String> participants = mBackupParticipants.valueAt(i); 1685 if (participants != null) { 1686 for (String packageName : participants) { 1687 dataChangedImpl(packageName); 1688 } 1689 } 1690 } 1691 } 1692 } 1693 1694 // Add a transport to our set of available backends. If 'transport' is null, this 1695 // is an unregistration, and the transport's entry is removed from our bookkeeping. 1696 private void registerTransport(String name, String component, IBackupTransport transport) { 1697 synchronized (mTransports) { 1698 if (DEBUG) Slog.v(TAG, "Registering transport " 1699 + component + "::" + name + " = " + transport); 1700 if (transport != null) { 1701 mTransports.put(name, transport); 1702 mTransportNames.put(component, name); 1703 } else { 1704 mTransports.remove(mTransportNames.get(component)); 1705 mTransportNames.remove(component); 1706 // Nothing further to do in the unregistration case 1707 return; 1708 } 1709 } 1710 1711 // If the init sentinel file exists, we need to be sure to perform the init 1712 // as soon as practical. We also create the state directory at registration 1713 // time to ensure it's present from the outset. 1714 try { 1715 String transportName = transport.transportDirName(); 1716 File stateDir = new File(mBaseStateDir, transportName); 1717 stateDir.mkdirs(); 1718 1719 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME); 1720 if (initSentinel.exists()) { 1721 synchronized (mQueueLock) { 1722 mPendingInits.add(transportName); 1723 1724 // TODO: pick a better starting time than now + 1 minute 1725 long delay = 1000 * 60; // one minute, in milliseconds 1726 mAlarmManager.set(AlarmManager.RTC_WAKEUP, 1727 System.currentTimeMillis() + delay, mRunInitIntent); 1728 } 1729 } 1730 } catch (RemoteException e) { 1731 // the transport threw when asked its file naming prefs; declare it invalid 1732 Slog.e(TAG, "Unable to register transport as " + name); 1733 mTransportNames.remove(component); 1734 mTransports.remove(name); 1735 } 1736 } 1737 1738 // ----- Track installation/removal of packages ----- 1739 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { 1740 public void onReceive(Context context, Intent intent) { 1741 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent); 1742 1743 String action = intent.getAction(); 1744 boolean replacing = false; 1745 boolean added = false; 1746 Bundle extras = intent.getExtras(); 1747 String pkgList[] = null; 1748 if (Intent.ACTION_PACKAGE_ADDED.equals(action) || 1749 Intent.ACTION_PACKAGE_REMOVED.equals(action)) { 1750 Uri uri = intent.getData(); 1751 if (uri == null) { 1752 return; 1753 } 1754 String pkgName = uri.getSchemeSpecificPart(); 1755 if (pkgName != null) { 1756 pkgList = new String[] { pkgName }; 1757 } 1758 added = Intent.ACTION_PACKAGE_ADDED.equals(action); 1759 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false); 1760 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { 1761 added = true; 1762 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 1763 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { 1764 added = false; 1765 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 1766 } 1767 1768 if (pkgList == null || pkgList.length == 0) { 1769 return; 1770 } 1771 1772 final int uid = extras.getInt(Intent.EXTRA_UID); 1773 if (added) { 1774 synchronized (mBackupParticipants) { 1775 if (replacing) { 1776 // This is the package-replaced case; we just remove the entry 1777 // under the old uid and fall through to re-add. 1778 removePackageParticipantsLocked(pkgList, uid); 1779 } 1780 addPackageParticipantsLocked(pkgList); 1781 } 1782 // If they're full-backup candidates, add them there instead 1783 for (String packageName : pkgList) { 1784 try { 1785 PackageInfo app = mPackageManager.getPackageInfo(packageName, 0); 1786 long now = System.currentTimeMillis(); 1787 if (appGetsFullBackup(app)) { 1788 enqueueFullBackup(packageName, now); 1789 scheduleNextFullBackupJob(); 1790 } 1791 } catch (NameNotFoundException e) { 1792 // doesn't really exist; ignore it 1793 if (DEBUG) { 1794 Slog.i(TAG, "Can't resolve new app " + packageName); 1795 } 1796 } 1797 } 1798 } else { 1799 if (replacing) { 1800 // The package is being updated. We'll receive a PACKAGE_ADDED shortly. 1801 } else { 1802 synchronized (mBackupParticipants) { 1803 removePackageParticipantsLocked(pkgList, uid); 1804 } 1805 } 1806 } 1807 } 1808 }; 1809 1810 // ----- Track connection to transports service ----- 1811 class TransportConnection implements ServiceConnection { 1812 @Override 1813 public void onServiceConnected(ComponentName component, IBinder service) { 1814 if (DEBUG) Slog.v(TAG, "Connected to transport " + component); 1815 try { 1816 IBackupTransport transport = IBackupTransport.Stub.asInterface(service); 1817 registerTransport(transport.name(), component.flattenToShortString(), transport); 1818 } catch (RemoteException e) { 1819 Slog.e(TAG, "Unable to register transport " + component); 1820 } 1821 } 1822 1823 @Override 1824 public void onServiceDisconnected(ComponentName component) { 1825 if (DEBUG) Slog.v(TAG, "Disconnected from transport " + component); 1826 registerTransport(null, component.flattenToShortString(), null); 1827 } 1828 }; 1829 1830 // Add the backup agents in the given packages to our set of known backup participants. 1831 // If 'packageNames' is null, adds all backup agents in the whole system. 1832 void addPackageParticipantsLocked(String[] packageNames) { 1833 // Look for apps that define the android:backupAgent attribute 1834 List<PackageInfo> targetApps = allAgentPackages(); 1835 if (packageNames != null) { 1836 if (MORE_DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length); 1837 for (String packageName : packageNames) { 1838 addPackageParticipantsLockedInner(packageName, targetApps); 1839 } 1840 } else { 1841 if (MORE_DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all"); 1842 addPackageParticipantsLockedInner(null, targetApps); 1843 } 1844 } 1845 1846 private void addPackageParticipantsLockedInner(String packageName, 1847 List<PackageInfo> targetPkgs) { 1848 if (MORE_DEBUG) { 1849 Slog.v(TAG, "Examining " + packageName + " for backup agent"); 1850 } 1851 1852 for (PackageInfo pkg : targetPkgs) { 1853 if (packageName == null || pkg.packageName.equals(packageName)) { 1854 int uid = pkg.applicationInfo.uid; 1855 HashSet<String> set = mBackupParticipants.get(uid); 1856 if (set == null) { 1857 set = new HashSet<String>(); 1858 mBackupParticipants.put(uid, set); 1859 } 1860 set.add(pkg.packageName); 1861 if (MORE_DEBUG) Slog.v(TAG, "Agent found; added"); 1862 1863 // Schedule a backup for it on general principles 1864 if (MORE_DEBUG) Slog.i(TAG, "Scheduling backup for new app " + pkg.packageName); 1865 dataChangedImpl(pkg.packageName); 1866 } 1867 } 1868 } 1869 1870 // Remove the given packages' entries from our known active set. 1871 void removePackageParticipantsLocked(String[] packageNames, int oldUid) { 1872 if (packageNames == null) { 1873 Slog.w(TAG, "removePackageParticipants with null list"); 1874 return; 1875 } 1876 1877 if (MORE_DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: uid=" + oldUid 1878 + " #" + packageNames.length); 1879 for (String pkg : packageNames) { 1880 // Known previous UID, so we know which package set to check 1881 HashSet<String> set = mBackupParticipants.get(oldUid); 1882 if (set != null && set.contains(pkg)) { 1883 removePackageFromSetLocked(set, pkg); 1884 if (set.isEmpty()) { 1885 if (MORE_DEBUG) Slog.v(TAG, " last one of this uid; purging set"); 1886 mBackupParticipants.remove(oldUid); 1887 } 1888 } 1889 } 1890 } 1891 1892 private void removePackageFromSetLocked(final HashSet<String> set, 1893 final String packageName) { 1894 if (set.contains(packageName)) { 1895 // Found it. Remove this one package from the bookkeeping, and 1896 // if it's the last participating app under this uid we drop the 1897 // (now-empty) set as well. 1898 // Note that we deliberately leave it 'known' in the "ever backed up" 1899 // bookkeeping so that its current-dataset data will be retrieved 1900 // if the app is subsequently reinstalled 1901 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + packageName); 1902 set.remove(packageName); 1903 mPendingBackups.remove(packageName); 1904 } 1905 } 1906 1907 // Returns the set of all applications that define an android:backupAgent attribute 1908 List<PackageInfo> allAgentPackages() { 1909 // !!! TODO: cache this and regenerate only when necessary 1910 int flags = PackageManager.GET_SIGNATURES; 1911 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags); 1912 int N = packages.size(); 1913 for (int a = N-1; a >= 0; a--) { 1914 PackageInfo pkg = packages.get(a); 1915 try { 1916 ApplicationInfo app = pkg.applicationInfo; 1917 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) 1918 || app.backupAgentName == null) { 1919 packages.remove(a); 1920 } 1921 else { 1922 // we will need the shared library path, so look that up and store it here. 1923 // This is used implicitly when we pass the PackageInfo object off to 1924 // the Activity Manager to launch the app for backup/restore purposes. 1925 app = mPackageManager.getApplicationInfo(pkg.packageName, 1926 PackageManager.GET_SHARED_LIBRARY_FILES); 1927 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles; 1928 } 1929 } catch (NameNotFoundException e) { 1930 packages.remove(a); 1931 } 1932 } 1933 return packages; 1934 } 1935 1936 // Called from the backup task: record that the given app has been successfully 1937 // backed up at least once 1938 void logBackupComplete(String packageName) { 1939 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return; 1940 1941 synchronized (mEverStoredApps) { 1942 if (!mEverStoredApps.add(packageName)) return; 1943 1944 RandomAccessFile out = null; 1945 try { 1946 out = new RandomAccessFile(mEverStored, "rws"); 1947 out.seek(out.length()); 1948 out.writeUTF(packageName); 1949 } catch (IOException e) { 1950 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored); 1951 } finally { 1952 try { if (out != null) out.close(); } catch (IOException e) {} 1953 } 1954 } 1955 } 1956 1957 // Remove our awareness of having ever backed up the given package 1958 void removeEverBackedUp(String packageName) { 1959 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName); 1960 if (MORE_DEBUG) Slog.v(TAG, "New set:"); 1961 1962 synchronized (mEverStoredApps) { 1963 // Rewrite the file and rename to overwrite. If we reboot in the middle, 1964 // we'll recognize on initialization time that the package no longer 1965 // exists and fix it up then. 1966 File tempKnownFile = new File(mBaseStateDir, "processed.new"); 1967 RandomAccessFile known = null; 1968 try { 1969 known = new RandomAccessFile(tempKnownFile, "rws"); 1970 mEverStoredApps.remove(packageName); 1971 for (String s : mEverStoredApps) { 1972 known.writeUTF(s); 1973 if (MORE_DEBUG) Slog.v(TAG, " " + s); 1974 } 1975 known.close(); 1976 known = null; 1977 if (!tempKnownFile.renameTo(mEverStored)) { 1978 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored); 1979 } 1980 } catch (IOException e) { 1981 // Bad: we couldn't create the new copy. For safety's sake we 1982 // abandon the whole process and remove all what's-backed-up 1983 // state entirely, meaning we'll force a backup pass for every 1984 // participant on the next boot or [re]install. 1985 Slog.w(TAG, "Error rewriting " + mEverStored, e); 1986 mEverStoredApps.clear(); 1987 tempKnownFile.delete(); 1988 mEverStored.delete(); 1989 } finally { 1990 try { if (known != null) known.close(); } catch (IOException e) {} 1991 } 1992 } 1993 } 1994 1995 // Persistently record the current and ancestral backup tokens as well 1996 // as the set of packages with data [supposedly] available in the 1997 // ancestral dataset. 1998 void writeRestoreTokens() { 1999 try { 2000 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd"); 2001 2002 // First, the version number of this record, for futureproofing 2003 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION); 2004 2005 // Write the ancestral and current tokens 2006 af.writeLong(mAncestralToken); 2007 af.writeLong(mCurrentToken); 2008 2009 // Now write the set of ancestral packages 2010 if (mAncestralPackages == null) { 2011 af.writeInt(-1); 2012 } else { 2013 af.writeInt(mAncestralPackages.size()); 2014 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size()); 2015 for (String pkgName : mAncestralPackages) { 2016 af.writeUTF(pkgName); 2017 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName); 2018 } 2019 } 2020 af.close(); 2021 } catch (IOException e) { 2022 Slog.w(TAG, "Unable to write token file:", e); 2023 } 2024 } 2025 2026 // Return the given transport 2027 private IBackupTransport getTransport(String transportName) { 2028 synchronized (mTransports) { 2029 IBackupTransport transport = mTransports.get(transportName); 2030 if (transport == null) { 2031 Slog.w(TAG, "Requested unavailable transport: " + transportName); 2032 } 2033 return transport; 2034 } 2035 } 2036 2037 // fire off a backup agent, blocking until it attaches or times out 2038 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) { 2039 IBackupAgent agent = null; 2040 synchronized(mAgentConnectLock) { 2041 mConnecting = true; 2042 mConnectedAgent = null; 2043 try { 2044 if (mActivityManager.bindBackupAgent(app, mode)) { 2045 Slog.d(TAG, "awaiting agent for " + app); 2046 2047 // success; wait for the agent to arrive 2048 // only wait 10 seconds for the bind to happen 2049 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL; 2050 while (mConnecting && mConnectedAgent == null 2051 && (System.currentTimeMillis() < timeoutMark)) { 2052 try { 2053 mAgentConnectLock.wait(5000); 2054 } catch (InterruptedException e) { 2055 // just bail 2056 if (DEBUG) Slog.w(TAG, "Interrupted: " + e); 2057 mActivityManager.clearPendingBackup(); 2058 return null; 2059 } 2060 } 2061 2062 // if we timed out with no connect, abort and move on 2063 if (mConnecting == true) { 2064 Slog.w(TAG, "Timeout waiting for agent " + app); 2065 mActivityManager.clearPendingBackup(); 2066 return null; 2067 } 2068 if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent); 2069 agent = mConnectedAgent; 2070 } 2071 } catch (RemoteException e) { 2072 // can't happen - ActivityManager is local 2073 } 2074 } 2075 return agent; 2076 } 2077 2078 // clear an application's data, blocking until the operation completes or times out 2079 void clearApplicationDataSynchronous(String packageName) { 2080 // Don't wipe packages marked allowClearUserData=false 2081 try { 2082 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0); 2083 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) { 2084 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping " 2085 + packageName); 2086 return; 2087 } 2088 } catch (NameNotFoundException e) { 2089 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found"); 2090 return; 2091 } 2092 2093 ClearDataObserver observer = new ClearDataObserver(); 2094 2095 synchronized(mClearDataLock) { 2096 mClearingData = true; 2097 try { 2098 mActivityManager.clearApplicationUserData(packageName, observer, 0); 2099 } catch (RemoteException e) { 2100 // can't happen because the activity manager is in this process 2101 } 2102 2103 // only wait 10 seconds for the clear data to happen 2104 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL; 2105 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) { 2106 try { 2107 mClearDataLock.wait(5000); 2108 } catch (InterruptedException e) { 2109 // won't happen, but still. 2110 mClearingData = false; 2111 } 2112 } 2113 } 2114 } 2115 2116 class ClearDataObserver extends IPackageDataObserver.Stub { 2117 public void onRemoveCompleted(String packageName, boolean succeeded) { 2118 synchronized(mClearDataLock) { 2119 mClearingData = false; 2120 mClearDataLock.notifyAll(); 2121 } 2122 } 2123 } 2124 2125 // Get the restore-set token for the best-available restore set for this package: 2126 // the active set if possible, else the ancestral one. Returns zero if none available. 2127 long getAvailableRestoreToken(String packageName) { 2128 long token = mAncestralToken; 2129 synchronized (mQueueLock) { 2130 if (mEverStoredApps.contains(packageName)) { 2131 token = mCurrentToken; 2132 } 2133 } 2134 return token; 2135 } 2136 2137 // ----- 2138 // Interface and methods used by the asynchronous-with-timeout backup/restore operations 2139 2140 interface BackupRestoreTask { 2141 // Execute one tick of whatever state machine the task implements 2142 void execute(); 2143 2144 // An operation that wanted a callback has completed 2145 void operationComplete(); 2146 2147 // An operation that wanted a callback has timed out 2148 void handleTimeout(); 2149 } 2150 2151 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) { 2152 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token) 2153 + " interval=" + interval); 2154 synchronized (mCurrentOpLock) { 2155 mCurrentOperations.put(token, new Operation(OP_PENDING, callback)); 2156 2157 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback); 2158 mBackupHandler.sendMessageDelayed(msg, interval); 2159 } 2160 } 2161 2162 // synchronous waiter case 2163 boolean waitUntilOperationComplete(int token) { 2164 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for " 2165 + Integer.toHexString(token)); 2166 int finalState = OP_PENDING; 2167 Operation op = null; 2168 synchronized (mCurrentOpLock) { 2169 while (true) { 2170 op = mCurrentOperations.get(token); 2171 if (op == null) { 2172 // mysterious disappearance: treat as success with no callback 2173 break; 2174 } else { 2175 if (op.state == OP_PENDING) { 2176 try { 2177 mCurrentOpLock.wait(); 2178 } catch (InterruptedException e) {} 2179 // When the wait is notified we loop around and recheck the current state 2180 } else { 2181 // No longer pending; we're done 2182 finalState = op.state; 2183 break; 2184 } 2185 } 2186 } 2187 } 2188 2189 mBackupHandler.removeMessages(MSG_TIMEOUT); 2190 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token) 2191 + " complete: finalState=" + finalState); 2192 return finalState == OP_ACKNOWLEDGED; 2193 } 2194 2195 void handleTimeout(int token, Object obj) { 2196 // Notify any synchronous waiters 2197 Operation op = null; 2198 synchronized (mCurrentOpLock) { 2199 op = mCurrentOperations.get(token); 2200 if (MORE_DEBUG) { 2201 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token) 2202 + " but no op found"); 2203 } 2204 int state = (op != null) ? op.state : OP_TIMEOUT; 2205 if (state == OP_PENDING) { 2206 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token)); 2207 op.state = OP_TIMEOUT; 2208 mCurrentOperations.put(token, op); 2209 } 2210 mCurrentOpLock.notifyAll(); 2211 } 2212 2213 // If there's a TimeoutHandler for this event, call it 2214 if (op != null && op.callback != null) { 2215 op.callback.handleTimeout(); 2216 } 2217 } 2218 2219 // ----- Back up a set of applications via a worker thread ----- 2220 2221 enum BackupState { 2222 INITIAL, 2223 RUNNING_QUEUE, 2224 FINAL 2225 } 2226 2227 class PerformBackupTask implements BackupRestoreTask { 2228 private static final String TAG = "PerformBackupTask"; 2229 2230 IBackupTransport mTransport; 2231 ArrayList<BackupRequest> mQueue; 2232 ArrayList<BackupRequest> mOriginalQueue; 2233 File mStateDir; 2234 File mJournal; 2235 BackupState mCurrentState; 2236 2237 // carried information about the current in-flight operation 2238 IBackupAgent mAgentBinder; 2239 PackageInfo mCurrentPackage; 2240 File mSavedStateName; 2241 File mBackupDataName; 2242 File mNewStateName; 2243 ParcelFileDescriptor mSavedState; 2244 ParcelFileDescriptor mBackupData; 2245 ParcelFileDescriptor mNewState; 2246 int mStatus; 2247 boolean mFinished; 2248 2249 public PerformBackupTask(IBackupTransport transport, String dirName, 2250 ArrayList<BackupRequest> queue, File journal) { 2251 mTransport = transport; 2252 mOriginalQueue = queue; 2253 mJournal = journal; 2254 2255 mStateDir = new File(mBaseStateDir, dirName); 2256 2257 mCurrentState = BackupState.INITIAL; 2258 mFinished = false; 2259 2260 addBackupTrace("STATE => INITIAL"); 2261 } 2262 2263 // Main entry point: perform one chunk of work, updating the state as appropriate 2264 // and reposting the next chunk to the primary backup handler thread. 2265 @Override 2266 public void execute() { 2267 switch (mCurrentState) { 2268 case INITIAL: 2269 beginBackup(); 2270 break; 2271 2272 case RUNNING_QUEUE: 2273 invokeNextAgent(); 2274 break; 2275 2276 case FINAL: 2277 if (!mFinished) finalizeBackup(); 2278 else { 2279 Slog.e(TAG, "Duplicate finish"); 2280 } 2281 mFinished = true; 2282 break; 2283 } 2284 } 2285 2286 // We're starting a backup pass. Initialize the transport and send 2287 // the PM metadata blob if we haven't already. 2288 void beginBackup() { 2289 if (DEBUG_BACKUP_TRACE) { 2290 clearBackupTrace(); 2291 StringBuilder b = new StringBuilder(256); 2292 b.append("beginBackup: ["); 2293 for (BackupRequest req : mOriginalQueue) { 2294 b.append(' '); 2295 b.append(req.packageName); 2296 } 2297 b.append(" ]"); 2298 addBackupTrace(b.toString()); 2299 } 2300 2301 mAgentBinder = null; 2302 mStatus = BackupTransport.TRANSPORT_OK; 2303 2304 // Sanity check: if the queue is empty we have no work to do. 2305 if (mOriginalQueue.isEmpty()) { 2306 Slog.w(TAG, "Backup begun with an empty queue - nothing to do."); 2307 addBackupTrace("queue empty at begin"); 2308 executeNextState(BackupState.FINAL); 2309 return; 2310 } 2311 2312 // We need to retain the original queue contents in case of transport 2313 // failure, but we want a working copy that we can manipulate along 2314 // the way. 2315 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone(); 2316 2317 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets"); 2318 2319 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL); 2320 try { 2321 final String transportName = mTransport.transportDirName(); 2322 EventLog.writeEvent(EventLogTags.BACKUP_START, transportName); 2323 2324 // If we haven't stored package manager metadata yet, we must init the transport. 2325 if (mStatus == BackupTransport.TRANSPORT_OK && pmState.length() <= 0) { 2326 Slog.i(TAG, "Initializing (wiping) backup state and transport storage"); 2327 addBackupTrace("initializing transport " + transportName); 2328 resetBackupState(mStateDir); // Just to make sure. 2329 mStatus = mTransport.initializeDevice(); 2330 2331 addBackupTrace("transport.initializeDevice() == " + mStatus); 2332 if (mStatus == BackupTransport.TRANSPORT_OK) { 2333 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE); 2334 } else { 2335 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)"); 2336 Slog.e(TAG, "Transport error in initializeDevice()"); 2337 } 2338 } 2339 2340 // The package manager doesn't have a proper <application> etc, but since 2341 // it's running here in the system process we can just set up its agent 2342 // directly and use a synthetic BackupRequest. We always run this pass 2343 // because it's cheap and this way we guarantee that we don't get out of 2344 // step even if we're selecting among various transports at run time. 2345 if (mStatus == BackupTransport.TRANSPORT_OK) { 2346 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent( 2347 mPackageManager); 2348 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL, 2349 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport); 2350 addBackupTrace("PMBA invoke: " + mStatus); 2351 } 2352 2353 if (mStatus == BackupTransport.TRANSPORT_NOT_INITIALIZED) { 2354 // The backend reports that our dataset has been wiped. Note this in 2355 // the event log; the no-success code below will reset the backup 2356 // state as well. 2357 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName()); 2358 } 2359 } catch (Exception e) { 2360 Slog.e(TAG, "Error in backup thread", e); 2361 addBackupTrace("Exception in backup thread: " + e); 2362 mStatus = BackupTransport.TRANSPORT_ERROR; 2363 } finally { 2364 // If we've succeeded so far, invokeAgentForBackup() will have run the PM 2365 // metadata and its completion/timeout callback will continue the state 2366 // machine chain. If it failed that won't happen; we handle that now. 2367 addBackupTrace("exiting prelim: " + mStatus); 2368 if (mStatus != BackupTransport.TRANSPORT_OK) { 2369 // if things went wrong at this point, we need to 2370 // restage everything and try again later. 2371 resetBackupState(mStateDir); // Just to make sure. 2372 executeNextState(BackupState.FINAL); 2373 } 2374 } 2375 } 2376 2377 // Transport has been initialized and the PM metadata submitted successfully 2378 // if that was warranted. Now we process the single next thing in the queue. 2379 void invokeNextAgent() { 2380 mStatus = BackupTransport.TRANSPORT_OK; 2381 addBackupTrace("invoke q=" + mQueue.size()); 2382 2383 // Sanity check that we have work to do. If not, skip to the end where 2384 // we reestablish the wakelock invariants etc. 2385 if (mQueue.isEmpty()) { 2386 if (DEBUG) Slog.i(TAG, "queue now empty"); 2387 executeNextState(BackupState.FINAL); 2388 return; 2389 } 2390 2391 // pop the entry we're going to process on this step 2392 BackupRequest request = mQueue.get(0); 2393 mQueue.remove(0); 2394 2395 Slog.d(TAG, "starting agent for backup of " + request); 2396 addBackupTrace("launch agent for " + request.packageName); 2397 2398 // Verify that the requested app exists; it might be something that 2399 // requested a backup but was then uninstalled. The request was 2400 // journalled and rather than tamper with the journal it's safer 2401 // to sanity-check here. This also gives us the classname of the 2402 // package's backup agent. 2403 try { 2404 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName, 2405 PackageManager.GET_SIGNATURES); 2406 if (mCurrentPackage.applicationInfo.backupAgentName == null) { 2407 // The manifest has changed but we had a stale backup request pending. 2408 // This won't happen again because the app won't be requesting further 2409 // backups. 2410 Slog.i(TAG, "Package " + request.packageName 2411 + " no longer supports backup; skipping"); 2412 addBackupTrace("skipping - no agent, completion is noop"); 2413 executeNextState(BackupState.RUNNING_QUEUE); 2414 return; 2415 } 2416 2417 if ((mCurrentPackage.applicationInfo.flags & ApplicationInfo.FLAG_STOPPED) != 0) { 2418 // The app has been force-stopped or cleared or just installed, 2419 // and not yet launched out of that state, so just as it won't 2420 // receive broadcasts, we won't run it for backup. 2421 addBackupTrace("skipping - stopped"); 2422 executeNextState(BackupState.RUNNING_QUEUE); 2423 return; 2424 } 2425 2426 IBackupAgent agent = null; 2427 try { 2428 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid)); 2429 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo, 2430 IApplicationThread.BACKUP_MODE_INCREMENTAL); 2431 addBackupTrace("agent bound; a? = " + (agent != null)); 2432 if (agent != null) { 2433 mAgentBinder = agent; 2434 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport); 2435 // at this point we'll either get a completion callback from the 2436 // agent, or a timeout message on the main handler. either way, we're 2437 // done here as long as we're successful so far. 2438 } else { 2439 // Timeout waiting for the agent 2440 mStatus = BackupTransport.AGENT_ERROR; 2441 } 2442 } catch (SecurityException ex) { 2443 // Try for the next one. 2444 Slog.d(TAG, "error in bind/backup", ex); 2445 mStatus = BackupTransport.AGENT_ERROR; 2446 addBackupTrace("agent SE"); 2447 } 2448 } catch (NameNotFoundException e) { 2449 Slog.d(TAG, "Package does not exist; skipping"); 2450 addBackupTrace("no such package"); 2451 mStatus = BackupTransport.AGENT_UNKNOWN; 2452 } finally { 2453 mWakelock.setWorkSource(null); 2454 2455 // If there was an agent error, no timeout/completion handling will occur. 2456 // That means we need to direct to the next state ourselves. 2457 if (mStatus != BackupTransport.TRANSPORT_OK) { 2458 BackupState nextState = BackupState.RUNNING_QUEUE; 2459 mAgentBinder = null; 2460 2461 // An agent-level failure means we reenqueue this one agent for 2462 // a later retry, but otherwise proceed normally. 2463 if (mStatus == BackupTransport.AGENT_ERROR) { 2464 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName 2465 + " - restaging"); 2466 dataChangedImpl(request.packageName); 2467 mStatus = BackupTransport.TRANSPORT_OK; 2468 if (mQueue.isEmpty()) nextState = BackupState.FINAL; 2469 } else if (mStatus == BackupTransport.AGENT_UNKNOWN) { 2470 // Failed lookup of the app, so we couldn't bring up an agent, but 2471 // we're otherwise fine. Just drop it and go on to the next as usual. 2472 mStatus = BackupTransport.TRANSPORT_OK; 2473 } else { 2474 // Transport-level failure means we reenqueue everything 2475 revertAndEndBackup(); 2476 nextState = BackupState.FINAL; 2477 } 2478 2479 executeNextState(nextState); 2480 } else { 2481 // success case 2482 addBackupTrace("expecting completion/timeout callback"); 2483 } 2484 } 2485 } 2486 2487 void finalizeBackup() { 2488 addBackupTrace("finishing"); 2489 2490 // Either backup was successful, in which case we of course do not need 2491 // this pass's journal any more; or it failed, in which case we just 2492 // re-enqueued all of these packages in the current active journal. 2493 // Either way, we no longer need this pass's journal. 2494 if (mJournal != null && !mJournal.delete()) { 2495 Slog.e(TAG, "Unable to remove backup journal file " + mJournal); 2496 } 2497 2498 // If everything actually went through and this is the first time we've 2499 // done a backup, we can now record what the current backup dataset token 2500 // is. 2501 if ((mCurrentToken == 0) && (mStatus == BackupTransport.TRANSPORT_OK)) { 2502 addBackupTrace("success; recording token"); 2503 try { 2504 mCurrentToken = mTransport.getCurrentRestoreSet(); 2505 writeRestoreTokens(); 2506 } catch (RemoteException e) { 2507 // nothing for it at this point, unfortunately, but this will be 2508 // recorded the next time we fully succeed. 2509 addBackupTrace("transport threw returning token"); 2510 } 2511 } 2512 2513 // Set up the next backup pass - at this point we can set mBackupRunning 2514 // to false to allow another pass to fire, because we're done with the 2515 // state machine sequence and the wakelock is refcounted. 2516 synchronized (mQueueLock) { 2517 mBackupRunning = false; 2518 if (mStatus == BackupTransport.TRANSPORT_NOT_INITIALIZED) { 2519 // Make sure we back up everything and perform the one-time init 2520 clearMetadata(); 2521 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning"); 2522 addBackupTrace("init required; rerunning"); 2523 backupNow(); 2524 } 2525 } 2526 2527 // Only once we're entirely finished do we release the wakelock 2528 clearBackupTrace(); 2529 Slog.i(BackupManagerService.TAG, "Backup pass finished."); 2530 mWakelock.release(); 2531 } 2532 2533 // Remove the PM metadata state. This will generate an init on the next pass. 2534 void clearMetadata() { 2535 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL); 2536 if (pmState.exists()) pmState.delete(); 2537 } 2538 2539 // Invoke an agent's doBackup() and start a timeout message spinning on the main 2540 // handler in case it doesn't get back to us. 2541 int invokeAgentForBackup(String packageName, IBackupAgent agent, 2542 IBackupTransport transport) { 2543 if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName); 2544 addBackupTrace("invoking " + packageName); 2545 2546 mSavedStateName = new File(mStateDir, packageName); 2547 mBackupDataName = new File(mDataDir, packageName + ".data"); 2548 mNewStateName = new File(mStateDir, packageName + ".new"); 2549 if (MORE_DEBUG) Slog.d(TAG, "data file: " + mBackupDataName); 2550 2551 mSavedState = null; 2552 mBackupData = null; 2553 mNewState = null; 2554 2555 final int token = generateToken(); 2556 try { 2557 // Look up the package info & signatures. This is first so that if it 2558 // throws an exception, there's no file setup yet that would need to 2559 // be unraveled. 2560 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) { 2561 // The metadata 'package' is synthetic; construct one and make 2562 // sure our global state is pointed at it 2563 mCurrentPackage = new PackageInfo(); 2564 mCurrentPackage.packageName = packageName; 2565 } 2566 2567 // In a full backup, we pass a null ParcelFileDescriptor as 2568 // the saved-state "file". This is by definition an incremental, 2569 // so we build a saved state file to pass. 2570 mSavedState = ParcelFileDescriptor.open(mSavedStateName, 2571 ParcelFileDescriptor.MODE_READ_ONLY | 2572 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary 2573 2574 mBackupData = ParcelFileDescriptor.open(mBackupDataName, 2575 ParcelFileDescriptor.MODE_READ_WRITE | 2576 ParcelFileDescriptor.MODE_CREATE | 2577 ParcelFileDescriptor.MODE_TRUNCATE); 2578 2579 if (!SELinux.restorecon(mBackupDataName)) { 2580 Slog.e(TAG, "SELinux restorecon failed on " + mBackupDataName); 2581 } 2582 2583 mNewState = ParcelFileDescriptor.open(mNewStateName, 2584 ParcelFileDescriptor.MODE_READ_WRITE | 2585 ParcelFileDescriptor.MODE_CREATE | 2586 ParcelFileDescriptor.MODE_TRUNCATE); 2587 2588 // Initiate the target's backup pass 2589 addBackupTrace("setting timeout"); 2590 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this); 2591 addBackupTrace("calling agent doBackup()"); 2592 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder); 2593 } catch (Exception e) { 2594 Slog.e(TAG, "Error invoking for backup on " + packageName); 2595 addBackupTrace("exception: " + e); 2596 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, 2597 e.toString()); 2598 agentErrorCleanup(); 2599 return BackupTransport.AGENT_ERROR; 2600 } 2601 2602 // At this point the agent is off and running. The next thing to happen will 2603 // either be a callback from the agent, at which point we'll process its data 2604 // for transport, or a timeout. Either way the next phase will happen in 2605 // response to the TimeoutHandler interface callbacks. 2606 addBackupTrace("invoke success"); 2607 return BackupTransport.TRANSPORT_OK; 2608 } 2609 2610 public void failAgent(IBackupAgent agent, String message) { 2611 try { 2612 agent.fail(message); 2613 } catch (Exception e) { 2614 Slog.w(TAG, "Error conveying failure to " + mCurrentPackage.packageName); 2615 } 2616 } 2617 2618 @Override 2619 public void operationComplete() { 2620 // Okay, the agent successfully reported back to us! 2621 final String pkgName = mCurrentPackage.packageName; 2622 final long filepos = mBackupDataName.length(); 2623 FileDescriptor fd = mBackupData.getFileDescriptor(); 2624 try { 2625 // If it's a 3rd party app, see whether they wrote any protected keys 2626 // and complain mightily if they are attempting shenanigans. 2627 if (mCurrentPackage.applicationInfo != null && 2628 (mCurrentPackage.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) { 2629 ParcelFileDescriptor readFd = ParcelFileDescriptor.open(mBackupDataName, 2630 ParcelFileDescriptor.MODE_READ_ONLY); 2631 BackupDataInput in = new BackupDataInput(readFd.getFileDescriptor()); 2632 try { 2633 while (in.readNextHeader()) { 2634 final String key = in.getKey(); 2635 if (key != null && key.charAt(0) >= 0xff00) { 2636 // Not okay: crash them and bail. 2637 failAgent(mAgentBinder, "Illegal backup key: " + key); 2638 addBackupTrace("illegal key " + key + " from " + pkgName); 2639 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, pkgName, 2640 "bad key"); 2641 mBackupHandler.removeMessages(MSG_TIMEOUT); 2642 agentErrorCleanup(); 2643 // agentErrorCleanup() implicitly executes next state properly 2644 return; 2645 } 2646 in.skipEntityData(); 2647 } 2648 } finally { 2649 if (readFd != null) { 2650 readFd.close(); 2651 } 2652 } 2653 } 2654 2655 // Piggyback the widget state payload, if any 2656 BackupDataOutput out = new BackupDataOutput(fd); 2657 byte[] widgetState = AppWidgetBackupBridge.getWidgetState(pkgName, 2658 UserHandle.USER_OWNER); 2659 if (widgetState != null) { 2660 out.writeEntityHeader(KEY_WIDGET_STATE, widgetState.length); 2661 out.writeEntityData(widgetState, widgetState.length); 2662 } else { 2663 // No widget state for this app, but push a 'delete' operation for it 2664 // in case they're trying to play games with the payload. 2665 out.writeEntityHeader(KEY_WIDGET_STATE, -1); 2666 } 2667 } catch (IOException e) { 2668 // Hard disk error; recovery/failure policy TBD. For now roll back, 2669 // but we may want to consider this a transport-level failure (i.e. 2670 // we're in such a bad state that we can't contemplate doing backup 2671 // operations any more during this pass). 2672 Slog.w(TAG, "Unable to save widget state for " + pkgName); 2673 try { 2674 Os.ftruncate(fd, filepos); 2675 } catch (ErrnoException ee) { 2676 Slog.w(TAG, "Unable to roll back!"); 2677 } 2678 } 2679 2680 // Spin the data off to the transport and proceed with the next stage. 2681 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for " 2682 + pkgName); 2683 mBackupHandler.removeMessages(MSG_TIMEOUT); 2684 clearAgentState(); 2685 addBackupTrace("operation complete"); 2686 2687 ParcelFileDescriptor backupData = null; 2688 mStatus = BackupTransport.TRANSPORT_OK; 2689 try { 2690 int size = (int) mBackupDataName.length(); 2691 if (size > 0) { 2692 if (mStatus == BackupTransport.TRANSPORT_OK) { 2693 backupData = ParcelFileDescriptor.open(mBackupDataName, 2694 ParcelFileDescriptor.MODE_READ_ONLY); 2695 addBackupTrace("sending data to transport"); 2696 mStatus = mTransport.performBackup(mCurrentPackage, backupData); 2697 } 2698 2699 // TODO - We call finishBackup() for each application backed up, because 2700 // we need to know now whether it succeeded or failed. Instead, we should 2701 // hold off on finishBackup() until the end, which implies holding off on 2702 // renaming *all* the output state files (see below) until that happens. 2703 2704 addBackupTrace("data delivered: " + mStatus); 2705 if (mStatus == BackupTransport.TRANSPORT_OK) { 2706 addBackupTrace("finishing op on transport"); 2707 mStatus = mTransport.finishBackup(); 2708 addBackupTrace("finished: " + mStatus); 2709 } 2710 } else { 2711 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport"); 2712 addBackupTrace("no data to send"); 2713 } 2714 2715 // After successful transport, delete the now-stale data 2716 // and juggle the files so that next time we supply the agent 2717 // with the new state file it just created. 2718 if (mStatus == BackupTransport.TRANSPORT_OK) { 2719 mBackupDataName.delete(); 2720 mNewStateName.renameTo(mSavedStateName); 2721 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, pkgName, size); 2722 logBackupComplete(pkgName); 2723 } else { 2724 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, pkgName); 2725 } 2726 } catch (Exception e) { 2727 Slog.e(TAG, "Transport error backing up " + pkgName, e); 2728 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, pkgName); 2729 mStatus = BackupTransport.TRANSPORT_ERROR; 2730 } finally { 2731 try { if (backupData != null) backupData.close(); } catch (IOException e) {} 2732 } 2733 2734 // If we encountered an error here it's a transport-level failure. That 2735 // means we need to halt everything and reschedule everything for next time. 2736 final BackupState nextState; 2737 if (mStatus != BackupTransport.TRANSPORT_OK) { 2738 revertAndEndBackup(); 2739 nextState = BackupState.FINAL; 2740 } else { 2741 // Success! Proceed with the next app if any, otherwise we're done. 2742 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE; 2743 } 2744 2745 executeNextState(nextState); 2746 } 2747 2748 @Override 2749 public void handleTimeout() { 2750 // Whoops, the current agent timed out running doBackup(). Tidy up and restage 2751 // it for the next time we run a backup pass. 2752 // !!! TODO: keep track of failure counts per agent, and blacklist those which 2753 // fail repeatedly (i.e. have proved themselves to be buggy). 2754 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName); 2755 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName, 2756 "timeout"); 2757 addBackupTrace("timeout of " + mCurrentPackage.packageName); 2758 agentErrorCleanup(); 2759 dataChangedImpl(mCurrentPackage.packageName); 2760 } 2761 2762 void revertAndEndBackup() { 2763 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything"); 2764 addBackupTrace("transport error; reverting"); 2765 for (BackupRequest request : mOriginalQueue) { 2766 dataChangedImpl(request.packageName); 2767 } 2768 // We also want to reset the backup schedule based on whatever 2769 // the transport suggests by way of retry/backoff time. 2770 restartBackupAlarm(); 2771 } 2772 2773 void agentErrorCleanup() { 2774 mBackupDataName.delete(); 2775 mNewStateName.delete(); 2776 clearAgentState(); 2777 2778 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE); 2779 } 2780 2781 // Cleanup common to both success and failure cases 2782 void clearAgentState() { 2783 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {} 2784 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {} 2785 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {} 2786 mSavedState = mBackupData = mNewState = null; 2787 synchronized (mCurrentOpLock) { 2788 mCurrentOperations.clear(); 2789 } 2790 2791 // If this was a pseudopackage there's no associated Activity Manager state 2792 if (mCurrentPackage.applicationInfo != null) { 2793 addBackupTrace("unbinding " + mCurrentPackage.packageName); 2794 try { // unbind even on timeout, just in case 2795 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo); 2796 } catch (RemoteException e) { /* can't happen; activity manager is local */ } 2797 } 2798 } 2799 2800 void restartBackupAlarm() { 2801 addBackupTrace("setting backup trigger"); 2802 synchronized (mQueueLock) { 2803 try { 2804 startBackupAlarmsLocked(mTransport.requestBackupTime()); 2805 } catch (RemoteException e) { /* cannot happen */ } 2806 } 2807 } 2808 2809 void executeNextState(BackupState nextState) { 2810 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on " 2811 + this + " nextState=" + nextState); 2812 addBackupTrace("executeNextState => " + nextState); 2813 mCurrentState = nextState; 2814 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this); 2815 mBackupHandler.sendMessage(msg); 2816 } 2817 } 2818 2819 2820 // ----- Full backup/restore to a file/socket ----- 2821 2822 class FullBackupObbConnection implements ServiceConnection { 2823 volatile IObbBackupService mService; 2824 2825 FullBackupObbConnection() { 2826 mService = null; 2827 } 2828 2829 public void establish() { 2830 if (DEBUG) Slog.i(TAG, "Initiating bind of OBB service on " + this); 2831 Intent obbIntent = new Intent().setComponent(new ComponentName( 2832 "com.android.sharedstoragebackup", 2833 "com.android.sharedstoragebackup.ObbBackupService")); 2834 BackupManagerService.this.mContext.bindService( 2835 obbIntent, this, Context.BIND_AUTO_CREATE); 2836 } 2837 2838 public void tearDown() { 2839 BackupManagerService.this.mContext.unbindService(this); 2840 } 2841 2842 public boolean backupObbs(PackageInfo pkg, OutputStream out) { 2843 boolean success = false; 2844 waitForConnection(); 2845 2846 ParcelFileDescriptor[] pipes = null; 2847 try { 2848 pipes = ParcelFileDescriptor.createPipe(); 2849 int token = generateToken(); 2850 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null); 2851 mService.backupObbs(pkg.packageName, pipes[1], token, mBackupManagerBinder); 2852 routeSocketDataToOutput(pipes[0], out); 2853 success = waitUntilOperationComplete(token); 2854 } catch (Exception e) { 2855 Slog.w(TAG, "Unable to back up OBBs for " + pkg, e); 2856 } finally { 2857 try { 2858 out.flush(); 2859 if (pipes != null) { 2860 if (pipes[0] != null) pipes[0].close(); 2861 if (pipes[1] != null) pipes[1].close(); 2862 } 2863 } catch (IOException e) { 2864 Slog.w(TAG, "I/O error closing down OBB backup", e); 2865 } 2866 } 2867 return success; 2868 } 2869 2870 public void restoreObbFile(String pkgName, ParcelFileDescriptor data, 2871 long fileSize, int type, String path, long mode, long mtime, 2872 int token, IBackupManager callbackBinder) { 2873 waitForConnection(); 2874 2875 try { 2876 mService.restoreObbFile(pkgName, data, fileSize, type, path, mode, mtime, 2877 token, callbackBinder); 2878 } catch (Exception e) { 2879 Slog.w(TAG, "Unable to restore OBBs for " + pkgName, e); 2880 } 2881 } 2882 2883 private void waitForConnection() { 2884 synchronized (this) { 2885 while (mService == null) { 2886 if (DEBUG) Slog.i(TAG, "...waiting for OBB service binding..."); 2887 try { 2888 this.wait(); 2889 } catch (InterruptedException e) { /* never interrupted */ } 2890 } 2891 if (DEBUG) Slog.i(TAG, "Connected to OBB service; continuing"); 2892 } 2893 } 2894 2895 @Override 2896 public void onServiceConnected(ComponentName name, IBinder service) { 2897 synchronized (this) { 2898 mService = IObbBackupService.Stub.asInterface(service); 2899 if (DEBUG) Slog.i(TAG, "OBB service connection " + mService 2900 + " connected on " + this); 2901 this.notifyAll(); 2902 } 2903 } 2904 2905 @Override 2906 public void onServiceDisconnected(ComponentName name) { 2907 synchronized (this) { 2908 mService = null; 2909 if (DEBUG) Slog.i(TAG, "OBB service connection disconnected on " + this); 2910 this.notifyAll(); 2911 } 2912 } 2913 2914 } 2915 2916 private void routeSocketDataToOutput(ParcelFileDescriptor inPipe, OutputStream out) 2917 throws IOException { 2918 FileInputStream raw = new FileInputStream(inPipe.getFileDescriptor()); 2919 DataInputStream in = new DataInputStream(raw); 2920 2921 byte[] buffer = new byte[32 * 1024]; 2922 int chunkTotal; 2923 while ((chunkTotal = in.readInt()) > 0) { 2924 while (chunkTotal > 0) { 2925 int toRead = (chunkTotal > buffer.length) ? buffer.length : chunkTotal; 2926 int nRead = in.read(buffer, 0, toRead); 2927 out.write(buffer, 0, nRead); 2928 chunkTotal -= nRead; 2929 } 2930 } 2931 } 2932 2933 // Core logic for performing one package's full backup, gathering the tarball from the 2934 // application and emitting it to the designated OutputStream. 2935 class FullBackupEngine { 2936 OutputStream mOutput; 2937 IFullBackupRestoreObserver mObserver; 2938 File mFilesDir; 2939 File mManifestFile; 2940 File mMetadataFile; 2941 boolean mIncludeApks; 2942 2943 class FullBackupRunner implements Runnable { 2944 PackageInfo mPackage; 2945 byte[] mWidgetData; 2946 IBackupAgent mAgent; 2947 ParcelFileDescriptor mPipe; 2948 int mToken; 2949 boolean mSendApk; 2950 boolean mWriteManifest; 2951 2952 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe, 2953 int token, boolean sendApk, boolean writeManifest, byte[] widgetData) 2954 throws IOException { 2955 mPackage = pack; 2956 mWidgetData = widgetData; 2957 mAgent = agent; 2958 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor()); 2959 mToken = token; 2960 mSendApk = sendApk; 2961 mWriteManifest = writeManifest; 2962 } 2963 2964 @Override 2965 public void run() { 2966 try { 2967 BackupDataOutput output = new BackupDataOutput( 2968 mPipe.getFileDescriptor()); 2969 2970 if (mWriteManifest) { 2971 final boolean writeWidgetData = mWidgetData != null; 2972 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName); 2973 writeAppManifest(mPackage, mManifestFile, mSendApk, writeWidgetData); 2974 FullBackup.backupToTar(mPackage.packageName, null, null, 2975 mFilesDir.getAbsolutePath(), 2976 mManifestFile.getAbsolutePath(), 2977 output); 2978 mManifestFile.delete(); 2979 2980 // We only need to write a metadata file if we have widget data to stash 2981 if (writeWidgetData) { 2982 writeMetadata(mPackage, mMetadataFile, mWidgetData); 2983 FullBackup.backupToTar(mPackage.packageName, null, null, 2984 mFilesDir.getAbsolutePath(), 2985 mMetadataFile.getAbsolutePath(), 2986 output); 2987 mMetadataFile.delete(); 2988 } 2989 } 2990 2991 if (mSendApk) { 2992 writeApkToBackup(mPackage, output); 2993 } 2994 2995 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName); 2996 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null); 2997 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder); 2998 } catch (IOException e) { 2999 Slog.e(TAG, "Error running full backup for " + mPackage.packageName); 3000 } catch (RemoteException e) { 3001 Slog.e(TAG, "Remote agent vanished during full backup of " 3002 + mPackage.packageName); 3003 } finally { 3004 try { 3005 mPipe.close(); 3006 } catch (IOException e) {} 3007 } 3008 } 3009 } 3010 3011 FullBackupEngine(OutputStream output, String packageName, boolean alsoApks) { 3012 mOutput = output; 3013 mIncludeApks = alsoApks; 3014 mFilesDir = new File("/data/system"); 3015 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME); 3016 mMetadataFile = new File(mFilesDir, BACKUP_METADATA_FILENAME); 3017 } 3018 3019 3020 public int backupOnePackage(PackageInfo pkg) throws RemoteException { 3021 int result = BackupTransport.TRANSPORT_OK; 3022 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName); 3023 3024 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo, 3025 IApplicationThread.BACKUP_MODE_FULL); 3026 if (agent != null) { 3027 ParcelFileDescriptor[] pipes = null; 3028 try { 3029 pipes = ParcelFileDescriptor.createPipe(); 3030 3031 ApplicationInfo app = pkg.applicationInfo; 3032 final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE); 3033 final boolean sendApk = mIncludeApks 3034 && !isSharedStorage 3035 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0) 3036 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 || 3037 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0); 3038 3039 byte[] widgetBlob = AppWidgetBackupBridge.getWidgetState(pkg.packageName, 3040 UserHandle.USER_OWNER); 3041 3042 final int token = generateToken(); 3043 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1], 3044 token, sendApk, !isSharedStorage, widgetBlob); 3045 pipes[1].close(); // the runner has dup'd it 3046 pipes[1] = null; 3047 Thread t = new Thread(runner, "app-data-runner"); 3048 t.start(); 3049 3050 // Now pull data from the app and stuff it into the output 3051 try { 3052 routeSocketDataToOutput(pipes[0], mOutput); 3053 } catch (IOException e) { 3054 Slog.i(TAG, "Caught exception reading from agent", e); 3055 result = BackupTransport.AGENT_ERROR; 3056 } 3057 3058 if (!waitUntilOperationComplete(token)) { 3059 Slog.e(TAG, "Full backup failed on package " + pkg.packageName); 3060 result = BackupTransport.AGENT_ERROR; 3061 } else { 3062 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName); 3063 } 3064 3065 } catch (IOException e) { 3066 Slog.e(TAG, "Error backing up " + pkg.packageName, e); 3067 result = BackupTransport.AGENT_ERROR; 3068 } finally { 3069 try { 3070 // flush after every package 3071 mOutput.flush(); 3072 if (pipes != null) { 3073 if (pipes[0] != null) pipes[0].close(); 3074 if (pipes[1] != null) pipes[1].close(); 3075 } 3076 } catch (IOException e) { 3077 Slog.w(TAG, "Error bringing down backup stack"); 3078 result = BackupTransport.TRANSPORT_ERROR; 3079 } 3080 } 3081 } else { 3082 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName); 3083 result = BackupTransport.AGENT_ERROR; 3084 } 3085 tearDown(pkg); 3086 return result; 3087 } 3088 3089 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) { 3090 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here 3091 // TODO: handle backing up split APKs 3092 final String appSourceDir = pkg.applicationInfo.getBaseCodePath(); 3093 final String apkDir = new File(appSourceDir).getParent(); 3094 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null, 3095 apkDir, appSourceDir, output); 3096 3097 // TODO: migrate this to SharedStorageBackup, since AID_SYSTEM 3098 // doesn't have access to external storage. 3099 3100 // Save associated .obb content if it exists and we did save the apk 3101 // check for .obb and save those too 3102 final UserEnvironment userEnv = new UserEnvironment(UserHandle.USER_OWNER); 3103 final File obbDir = userEnv.buildExternalStorageAppObbDirs(pkg.packageName)[0]; 3104 if (obbDir != null) { 3105 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath()); 3106 File[] obbFiles = obbDir.listFiles(); 3107 if (obbFiles != null) { 3108 final String obbDirName = obbDir.getAbsolutePath(); 3109 for (File obb : obbFiles) { 3110 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null, 3111 obbDirName, obb.getAbsolutePath(), output); 3112 } 3113 } 3114 } 3115 } 3116 3117 private void writeAppManifest(PackageInfo pkg, File manifestFile, 3118 boolean withApk, boolean withWidgets) throws IOException { 3119 // Manifest format. All data are strings ending in LF: 3120 // BACKUP_MANIFEST_VERSION, currently 1 3121 // 3122 // Version 1: 3123 // package name 3124 // package's versionCode 3125 // platform versionCode 3126 // getInstallerPackageName() for this package (maybe empty) 3127 // boolean: "1" if archive includes .apk; any other string means not 3128 // number of signatures == N 3129 // N*: signature byte array in ascii format per Signature.toCharsString() 3130 StringBuilder builder = new StringBuilder(4096); 3131 StringBuilderPrinter printer = new StringBuilderPrinter(builder); 3132 3133 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION)); 3134 printer.println(pkg.packageName); 3135 printer.println(Integer.toString(pkg.versionCode)); 3136 printer.println(Integer.toString(Build.VERSION.SDK_INT)); 3137 3138 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName); 3139 printer.println((installerName != null) ? installerName : ""); 3140 3141 printer.println(withApk ? "1" : "0"); 3142 if (pkg.signatures == null) { 3143 printer.println("0"); 3144 } else { 3145 printer.println(Integer.toString(pkg.signatures.length)); 3146 for (Signature sig : pkg.signatures) { 3147 printer.println(sig.toCharsString()); 3148 } 3149 } 3150 3151 FileOutputStream outstream = new FileOutputStream(manifestFile); 3152 outstream.write(builder.toString().getBytes()); 3153 outstream.close(); 3154 3155 // We want the manifest block in the archive stream to be idempotent: 3156 // each time we generate a backup stream for the app, we want the manifest 3157 // block to be identical. The underlying tar mechanism sees it as a file, 3158 // though, and will propagate its mtime, causing the tar header to vary. 3159 // Avoid this problem by pinning the mtime to zero. 3160 manifestFile.setLastModified(0); 3161 } 3162 3163 // Widget metadata format. All header entries are strings ending in LF: 3164 // 3165 // Version 1 header: 3166 // BACKUP_METADATA_VERSION, currently "1" 3167 // package name 3168 // 3169 // File data (all integers are binary in network byte order) 3170 // *N: 4 : integer token identifying which metadata blob 3171 // 4 : integer size of this blob = N 3172 // N : raw bytes of this metadata blob 3173 // 3174 // Currently understood blobs (always in network byte order): 3175 // 3176 // widgets : metadata token = 0x01FFED01 (BACKUP_WIDGET_METADATA_TOKEN) 3177 // 3178 // Unrecognized blobs are *ignored*, not errors. 3179 private void writeMetadata(PackageInfo pkg, File destination, byte[] widgetData) 3180 throws IOException { 3181 StringBuilder b = new StringBuilder(512); 3182 StringBuilderPrinter printer = new StringBuilderPrinter(b); 3183 printer.println(Integer.toString(BACKUP_METADATA_VERSION)); 3184 printer.println(pkg.packageName); 3185 3186 FileOutputStream fout = new FileOutputStream(destination); 3187 BufferedOutputStream bout = new BufferedOutputStream(fout); 3188 DataOutputStream out = new DataOutputStream(bout); 3189 bout.write(b.toString().getBytes()); // bypassing DataOutputStream 3190 3191 if (widgetData != null && widgetData.length > 0) { 3192 out.writeInt(BACKUP_WIDGET_METADATA_TOKEN); 3193 out.writeInt(widgetData.length); 3194 out.write(widgetData); 3195 } 3196 bout.flush(); 3197 out.close(); 3198 3199 // As with the manifest file, guarantee idempotence of the archive metadata 3200 // for the widget block by using a fixed mtime on the transient file. 3201 destination.setLastModified(0); 3202 } 3203 3204 private void tearDown(PackageInfo pkg) { 3205 if (pkg != null) { 3206 final ApplicationInfo app = pkg.applicationInfo; 3207 if (app != null) { 3208 try { 3209 // unbind and tidy up even on timeout or failure, just in case 3210 mActivityManager.unbindBackupAgent(app); 3211 3212 // The agent was running with a stub Application object, so shut it down. 3213 if (app.uid != Process.SYSTEM_UID 3214 && app.uid != Process.PHONE_UID) { 3215 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process"); 3216 mActivityManager.killApplicationProcess(app.processName, app.uid); 3217 } else { 3218 if (MORE_DEBUG) Slog.d(TAG, "Not killing after backup: " + app.processName); 3219 } 3220 } catch (RemoteException e) { 3221 Slog.d(TAG, "Lost app trying to shut down"); 3222 } 3223 } 3224 } 3225 } 3226 } 3227 3228 // Generic driver skeleton for full backup operations 3229 abstract class FullBackupTask implements Runnable { 3230 IFullBackupRestoreObserver mObserver; 3231 3232 FullBackupTask(IFullBackupRestoreObserver observer) { 3233 mObserver = observer; 3234 } 3235 3236 // wrappers for observer use 3237 final void sendStartBackup() { 3238 if (mObserver != null) { 3239 try { 3240 mObserver.onStartBackup(); 3241 } catch (RemoteException e) { 3242 Slog.w(TAG, "full backup observer went away: startBackup"); 3243 mObserver = null; 3244 } 3245 } 3246 } 3247 3248 final void sendOnBackupPackage(String name) { 3249 if (mObserver != null) { 3250 try { 3251 // TODO: use a more user-friendly name string 3252 mObserver.onBackupPackage(name); 3253 } catch (RemoteException e) { 3254 Slog.w(TAG, "full backup observer went away: backupPackage"); 3255 mObserver = null; 3256 } 3257 } 3258 } 3259 3260 final void sendEndBackup() { 3261 if (mObserver != null) { 3262 try { 3263 mObserver.onEndBackup(); 3264 } catch (RemoteException e) { 3265 Slog.w(TAG, "full backup observer went away: endBackup"); 3266 mObserver = null; 3267 } 3268 } 3269 } 3270 } 3271 3272 // Full backup task variant used for adb backup 3273 class PerformAdbBackupTask extends FullBackupTask { 3274 FullBackupEngine mBackupEngine; 3275 final AtomicBoolean mLatch; 3276 3277 ParcelFileDescriptor mOutputFile; 3278 DeflaterOutputStream mDeflater; 3279 boolean mIncludeApks; 3280 boolean mIncludeObbs; 3281 boolean mIncludeShared; 3282 boolean mDoWidgets; 3283 boolean mAllApps; 3284 boolean mIncludeSystem; 3285 boolean mCompress; 3286 ArrayList<String> mPackages; 3287 String mCurrentPassword; 3288 String mEncryptPassword; 3289 3290 PerformAdbBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer, 3291 boolean includeApks, boolean includeObbs, boolean includeShared, 3292 boolean doWidgets, String curPassword, String encryptPassword, boolean doAllApps, 3293 boolean doSystem, boolean doCompress, String[] packages, AtomicBoolean latch) { 3294 super(observer); 3295 mLatch = latch; 3296 3297 mOutputFile = fd; 3298 mIncludeApks = includeApks; 3299 mIncludeObbs = includeObbs; 3300 mIncludeShared = includeShared; 3301 mDoWidgets = doWidgets; 3302 mAllApps = doAllApps; 3303 mIncludeSystem = doSystem; 3304 mPackages = (packages == null) 3305 ? new ArrayList<String>() 3306 : new ArrayList<String>(Arrays.asList(packages)); 3307 mCurrentPassword = curPassword; 3308 // when backing up, if there is a current backup password, we require that 3309 // the user use a nonempty encryption password as well. if one is supplied 3310 // in the UI we use that, but if the UI was left empty we fall back to the 3311 // current backup password (which was supplied by the user as well). 3312 if (encryptPassword == null || "".equals(encryptPassword)) { 3313 mEncryptPassword = curPassword; 3314 } else { 3315 mEncryptPassword = encryptPassword; 3316 } 3317 mCompress = doCompress; 3318 } 3319 3320 void addPackagesToSet(TreeMap<String, PackageInfo> set, List<String> pkgNames) { 3321 for (String pkgName : pkgNames) { 3322 if (!set.containsKey(pkgName)) { 3323 try { 3324 PackageInfo info = mPackageManager.getPackageInfo(pkgName, 3325 PackageManager.GET_SIGNATURES); 3326 set.put(pkgName, info); 3327 } catch (NameNotFoundException e) { 3328 Slog.w(TAG, "Unknown package " + pkgName + ", skipping"); 3329 } 3330 } 3331 } 3332 } 3333 3334 private OutputStream emitAesBackupHeader(StringBuilder headerbuf, 3335 OutputStream ofstream) throws Exception { 3336 // User key will be used to encrypt the master key. 3337 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE); 3338 SecretKey userKey = buildPasswordKey(PBKDF_CURRENT, mEncryptPassword, newUserSalt, 3339 PBKDF2_HASH_ROUNDS); 3340 3341 // the master key is random for each backup 3342 byte[] masterPw = new byte[256 / 8]; 3343 mRng.nextBytes(masterPw); 3344 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE); 3345 3346 // primary encryption of the datastream with the random key 3347 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding"); 3348 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES"); 3349 c.init(Cipher.ENCRYPT_MODE, masterKeySpec); 3350 OutputStream finalOutput = new CipherOutputStream(ofstream, c); 3351 3352 // line 4: name of encryption algorithm 3353 headerbuf.append(ENCRYPTION_ALGORITHM_NAME); 3354 headerbuf.append('\n'); 3355 // line 5: user password salt [hex] 3356 headerbuf.append(byteArrayToHex(newUserSalt)); 3357 headerbuf.append('\n'); 3358 // line 6: master key checksum salt [hex] 3359 headerbuf.append(byteArrayToHex(checksumSalt)); 3360 headerbuf.append('\n'); 3361 // line 7: number of PBKDF2 rounds used [decimal] 3362 headerbuf.append(PBKDF2_HASH_ROUNDS); 3363 headerbuf.append('\n'); 3364 3365 // line 8: IV of the user key [hex] 3366 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding"); 3367 mkC.init(Cipher.ENCRYPT_MODE, userKey); 3368 3369 byte[] IV = mkC.getIV(); 3370 headerbuf.append(byteArrayToHex(IV)); 3371 headerbuf.append('\n'); 3372 3373 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format: 3374 // [byte] IV length = Niv 3375 // [array of Niv bytes] IV itself 3376 // [byte] master key length = Nmk 3377 // [array of Nmk bytes] master key itself 3378 // [byte] MK checksum hash length = Nck 3379 // [array of Nck bytes] master key checksum hash 3380 // 3381 // The checksum is the (master key + checksum salt), run through the 3382 // stated number of PBKDF2 rounds 3383 IV = c.getIV(); 3384 byte[] mk = masterKeySpec.getEncoded(); 3385 byte[] checksum = makeKeyChecksum(PBKDF_CURRENT, masterKeySpec.getEncoded(), 3386 checksumSalt, PBKDF2_HASH_ROUNDS); 3387 3388 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length 3389 + checksum.length + 3); 3390 DataOutputStream mkOut = new DataOutputStream(blob); 3391 mkOut.writeByte(IV.length); 3392 mkOut.write(IV); 3393 mkOut.writeByte(mk.length); 3394 mkOut.write(mk); 3395 mkOut.writeByte(checksum.length); 3396 mkOut.write(checksum); 3397 mkOut.flush(); 3398 byte[] encryptedMk = mkC.doFinal(blob.toByteArray()); 3399 headerbuf.append(byteArrayToHex(encryptedMk)); 3400 headerbuf.append('\n'); 3401 3402 return finalOutput; 3403 } 3404 3405 private void finalizeBackup(OutputStream out) { 3406 try { 3407 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes. 3408 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled 3409 out.write(eof); 3410 } catch (IOException e) { 3411 Slog.w(TAG, "Error attempting to finalize backup stream"); 3412 } 3413 } 3414 3415 @Override 3416 public void run() { 3417 Slog.i(TAG, "--- Performing full-dataset adb backup ---"); 3418 3419 TreeMap<String, PackageInfo> packagesToBackup = new TreeMap<String, PackageInfo>(); 3420 FullBackupObbConnection obbConnection = new FullBackupObbConnection(); 3421 obbConnection.establish(); // we'll want this later 3422 3423 sendStartBackup(); 3424 3425 // doAllApps supersedes the package set if any 3426 if (mAllApps) { 3427 List<PackageInfo> allPackages = mPackageManager.getInstalledPackages( 3428 PackageManager.GET_SIGNATURES); 3429 for (int i = 0; i < allPackages.size(); i++) { 3430 PackageInfo pkg = allPackages.get(i); 3431 // Exclude system apps if we've been asked to do so 3432 if (mIncludeSystem == true 3433 || ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3434 packagesToBackup.put(pkg.packageName, pkg); 3435 } 3436 } 3437 } 3438 3439 // If we're doing widget state as well, ensure that we have all the involved 3440 // host & provider packages in the set 3441 if (mDoWidgets) { 3442 List<String> pkgs = 3443 AppWidgetBackupBridge.getWidgetParticipants(UserHandle.USER_OWNER); 3444 if (pkgs != null) { 3445 if (MORE_DEBUG) { 3446 Slog.i(TAG, "Adding widget participants to backup set:"); 3447 StringBuilder sb = new StringBuilder(128); 3448 sb.append(" "); 3449 for (String s : pkgs) { 3450 sb.append(' '); 3451 sb.append(s); 3452 } 3453 Slog.i(TAG, sb.toString()); 3454 } 3455 addPackagesToSet(packagesToBackup, pkgs); 3456 } 3457 } 3458 3459 // Now process the command line argument packages, if any. Note that explicitly- 3460 // named system-partition packages will be included even if includeSystem was 3461 // set to false. 3462 if (mPackages != null) { 3463 addPackagesToSet(packagesToBackup, mPackages); 3464 } 3465 3466 // Now we cull any inapplicable / inappropriate packages from the set. This 3467 // includes the special shared-storage agent package; we handle that one 3468 // explicitly at the end of the backup pass. 3469 Iterator<Entry<String, PackageInfo>> iter = packagesToBackup.entrySet().iterator(); 3470 while (iter.hasNext()) { 3471 PackageInfo pkg = iter.next().getValue(); 3472 if (!appIsEligibleForBackup(pkg.applicationInfo)) { 3473 iter.remove(); 3474 } 3475 } 3476 3477 // flatten the set of packages now so we can explicitly control the ordering 3478 ArrayList<PackageInfo> backupQueue = 3479 new ArrayList<PackageInfo>(packagesToBackup.values()); 3480 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor()); 3481 OutputStream out = null; 3482 3483 PackageInfo pkg = null; 3484 try { 3485 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0); 3486 OutputStream finalOutput = ofstream; 3487 3488 // Verify that the given password matches the currently-active 3489 // backup password, if any 3490 if (!backupPasswordMatches(mCurrentPassword)) { 3491 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting"); 3492 return; 3493 } 3494 3495 // Write the global file header. All strings are UTF-8 encoded; lines end 3496 // with a '\n' byte. Actual backup data begins immediately following the 3497 // final '\n'. 3498 // 3499 // line 1: "ANDROID BACKUP" 3500 // line 2: backup file format version, currently "2" 3501 // line 3: compressed? "0" if not compressed, "1" if compressed. 3502 // line 4: name of encryption algorithm [currently only "none" or "AES-256"] 3503 // 3504 // When line 4 is not "none", then additional header data follows: 3505 // 3506 // line 5: user password salt [hex] 3507 // line 6: master key checksum salt [hex] 3508 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal] 3509 // line 8: IV of the user key [hex] 3510 // line 9: master key blob [hex] 3511 // IV of the master key, master key itself, master key checksum hash 3512 // 3513 // The master key checksum is the master key plus its checksum salt, run through 3514 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the 3515 // correct password for decrypting the archive: the master key decrypted from 3516 // the archive using the user-supplied password is also run through PBKDF2 in 3517 // this way, and if the result does not match the checksum as stored in the 3518 // archive, then we know that the user-supplied password does not match the 3519 // archive's. 3520 StringBuilder headerbuf = new StringBuilder(1024); 3521 3522 headerbuf.append(BACKUP_FILE_HEADER_MAGIC); 3523 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n 3524 headerbuf.append(mCompress ? "\n1\n" : "\n0\n"); 3525 3526 try { 3527 // Set up the encryption stage if appropriate, and emit the correct header 3528 if (encrypting) { 3529 finalOutput = emitAesBackupHeader(headerbuf, finalOutput); 3530 } else { 3531 headerbuf.append("none\n"); 3532 } 3533 3534 byte[] header = headerbuf.toString().getBytes("UTF-8"); 3535 ofstream.write(header); 3536 3537 // Set up the compression stage feeding into the encryption stage (if any) 3538 if (mCompress) { 3539 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION); 3540 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true); 3541 } 3542 3543 out = finalOutput; 3544 } catch (Exception e) { 3545 // Should never happen! 3546 Slog.e(TAG, "Unable to emit archive header", e); 3547 return; 3548 } 3549 3550 // Shared storage if requested 3551 if (mIncludeShared) { 3552 try { 3553 pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0); 3554 backupQueue.add(pkg); 3555 } catch (NameNotFoundException e) { 3556 Slog.e(TAG, "Unable to find shared-storage backup handler"); 3557 } 3558 } 3559 3560 // Now actually run the constructed backup sequence 3561 int N = backupQueue.size(); 3562 for (int i = 0; i < N; i++) { 3563 pkg = backupQueue.get(i); 3564 final boolean isSharedStorage = 3565 pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE); 3566 3567 mBackupEngine = new FullBackupEngine(out, pkg.packageName, mIncludeApks); 3568 sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName); 3569 mBackupEngine.backupOnePackage(pkg); 3570 3571 // after the app's agent runs to handle its private filesystem 3572 // contents, back up any OBB content it has on its behalf. 3573 if (mIncludeObbs) { 3574 boolean obbOkay = obbConnection.backupObbs(pkg, out); 3575 if (!obbOkay) { 3576 throw new RuntimeException("Failure writing OBB stack for " + pkg); 3577 } 3578 } 3579 } 3580 3581 // Done! 3582 finalizeBackup(out); 3583 } catch (RemoteException e) { 3584 Slog.e(TAG, "App died during full backup"); 3585 } catch (Exception e) { 3586 Slog.e(TAG, "Internal exception during full backup", e); 3587 } finally { 3588 try { 3589 if (out != null) out.close(); 3590 mOutputFile.close(); 3591 } catch (IOException e) { 3592 /* nothing we can do about this */ 3593 } 3594 synchronized (mCurrentOpLock) { 3595 mCurrentOperations.clear(); 3596 } 3597 synchronized (mLatch) { 3598 mLatch.set(true); 3599 mLatch.notifyAll(); 3600 } 3601 sendEndBackup(); 3602 obbConnection.tearDown(); 3603 if (DEBUG) Slog.d(TAG, "Full backup pass complete."); 3604 mWakelock.release(); 3605 } 3606 } 3607 } 3608 3609 // Full backup task extension used for transport-oriented operation 3610 class PerformFullTransportBackupTask extends FullBackupTask { 3611 static final String TAG = "PFTBT"; 3612 ArrayList<PackageInfo> mPackages; 3613 boolean mUpdateSchedule; 3614 AtomicBoolean mLatch; 3615 AtomicBoolean mKeepRunning; // signal from job scheduler 3616 FullBackupJob mJob; // if a scheduled job needs to be finished afterwards 3617 3618 PerformFullTransportBackupTask(IFullBackupRestoreObserver observer, 3619 String[] whichPackages, boolean updateSchedule, 3620 FullBackupJob runningJob, AtomicBoolean latch) { 3621 super(observer); 3622 mUpdateSchedule = updateSchedule; 3623 mLatch = latch; 3624 mKeepRunning = new AtomicBoolean(true); 3625 mJob = runningJob; 3626 mPackages = new ArrayList<PackageInfo>(whichPackages.length); 3627 3628 for (String pkg : whichPackages) { 3629 try { 3630 PackageInfo info = mPackageManager.getPackageInfo(pkg, 3631 PackageManager.GET_SIGNATURES); 3632 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0 3633 || pkg.equals(SHARED_BACKUP_AGENT_PACKAGE)) { 3634 // Cull any packages that have indicated that backups are not permitted, 3635 // as well as any explicit mention of the 'special' shared-storage agent 3636 // package (we handle that one at the end). 3637 if (MORE_DEBUG) { 3638 Slog.d(TAG, "Ignoring opted-out package " + pkg); 3639 } 3640 continue; 3641 } else if ((info.applicationInfo.uid < Process.FIRST_APPLICATION_UID) 3642 && (info.applicationInfo.backupAgentName == null)) { 3643 // Cull any packages that run as system-domain uids but do not define their 3644 // own backup agents 3645 if (MORE_DEBUG) { 3646 Slog.d(TAG, "Ignoring non-agent system package " + pkg); 3647 } 3648 continue; 3649 } 3650 mPackages.add(info); 3651 } catch (NameNotFoundException e) { 3652 Slog.i(TAG, "Requested package " + pkg + " not found; ignoring"); 3653 } 3654 } 3655 } 3656 3657 public void setRunning(boolean running) { 3658 mKeepRunning.set(running); 3659 } 3660 3661 @Override 3662 public void run() { 3663 // data from the app, passed to us for bridging to the transport 3664 ParcelFileDescriptor[] enginePipes = null; 3665 3666 // Pipe through which we write data to the transport 3667 ParcelFileDescriptor[] transportPipes = null; 3668 3669 PackageInfo currentPackage; 3670 3671 try { 3672 IBackupTransport transport = getTransport(mCurrentTransport); 3673 if (transport == null) { 3674 Slog.w(TAG, "Transport not present; full data backup not performed"); 3675 return; 3676 } 3677 3678 // Set up to send data to the transport 3679 final int N = mPackages.size(); 3680 for (int i = 0; i < N; i++) { 3681 currentPackage = mPackages.get(i); 3682 if (DEBUG) { 3683 Slog.i(TAG, "Initiating full-data transport backup of " 3684 + currentPackage.packageName); 3685 } 3686 transportPipes = ParcelFileDescriptor.createPipe(); 3687 3688 // Tell the transport the data's coming 3689 int result = transport.performFullBackup(currentPackage, 3690 transportPipes[0]); 3691 if (result == BackupTransport.TRANSPORT_OK) { 3692 // The transport has its own copy of the read end of the pipe, 3693 // so close ours now 3694 transportPipes[0].close(); 3695 transportPipes[0] = null; 3696 3697 // Now set up the backup engine / data source end of things 3698 enginePipes = ParcelFileDescriptor.createPipe(); 3699 AtomicBoolean runnerLatch = new AtomicBoolean(false); 3700 SinglePackageBackupRunner backupRunner = 3701 new SinglePackageBackupRunner(enginePipes[1], currentPackage, 3702 runnerLatch); 3703 // The runner dup'd the pipe half, so we close it here 3704 enginePipes[1].close(); 3705 enginePipes[1] = null; 3706 3707 // Spin off the runner to fetch the app's data and pipe it 3708 // into the engine pipes 3709 (new Thread(backupRunner, "package-backup-bridge")).start(); 3710 3711 // Read data off the engine pipe and pass it to the transport 3712 // pipe until we hit EOD on the input stream. 3713 FileInputStream in = new FileInputStream( 3714 enginePipes[0].getFileDescriptor()); 3715 FileOutputStream out = new FileOutputStream( 3716 transportPipes[1].getFileDescriptor()); 3717 byte[] buffer = new byte[8192]; 3718 int nRead = 0; 3719 do { 3720 if (!mKeepRunning.get()) { 3721 if (DEBUG_SCHEDULING) { 3722 Slog.i(TAG, "Full backup task told to stop"); 3723 } 3724 break; 3725 } 3726 nRead = in.read(buffer); 3727 if (nRead > 0) { 3728 out.write(buffer, 0, nRead); 3729 result = transport.sendBackupData(nRead); 3730 } 3731 } while (nRead > 0 && result == BackupTransport.TRANSPORT_OK); 3732 3733 int finishResult; 3734 3735 if (!mKeepRunning.get()) { 3736 result = BackupTransport.TRANSPORT_ERROR; 3737 // TODO: tell the transport to abort the backup 3738 Slog.w(TAG, "TODO: tell transport to halt & roll back"); 3739 } 3740 3741 // In all cases we need to give the transport its finish callback 3742 finishResult = transport.finishBackup(); 3743 3744 if (MORE_DEBUG) { 3745 Slog.i(TAG, "Done trying to send backup data: result=" 3746 + result + " finishResult=" + finishResult); 3747 } 3748 3749 // If we were otherwise in a good state, now interpret the final 3750 // result based on what finishBackup() returned. If we're in a 3751 // failure case already, preserve that result and ignore whatever 3752 // finishBackup() reported. 3753 if (result == BackupTransport.TRANSPORT_OK) { 3754 result = finishResult; 3755 } 3756 3757 if (result != BackupTransport.TRANSPORT_OK) { 3758 Slog.e(TAG, "Error " + result 3759 + " backing up " + currentPackage.packageName); 3760 } 3761 } 3762 3763 // Roll this package to the end of the backup queue if we're 3764 // in a queue-driven mode (regardless of success/failure) 3765 if (mUpdateSchedule) { 3766 enqueueFullBackup(currentPackage.packageName, 3767 System.currentTimeMillis()); 3768 } 3769 3770 if (result == BackupTransport.TRANSPORT_PACKAGE_REJECTED) { 3771 if (DEBUG) { 3772 Slog.i(TAG, "Transport rejected backup of " 3773 + currentPackage.packageName 3774 + ", skipping"); 3775 } 3776 // do nothing, clean up, and continue looping 3777 } else if (result != BackupTransport.TRANSPORT_OK) { 3778 if (DEBUG) { 3779 Slog.i(TAG, "Transport failed; aborting backup: " + result); 3780 return; 3781 } 3782 } 3783 cleanUpPipes(transportPipes); 3784 cleanUpPipes(enginePipes); 3785 currentPackage = null; 3786 } 3787 3788 if (DEBUG) { 3789 Slog.i(TAG, "Full backup completed."); 3790 } 3791 } catch (Exception e) { 3792 Slog.w(TAG, "Exception trying full transport backup", e); 3793 } finally { 3794 cleanUpPipes(transportPipes); 3795 cleanUpPipes(enginePipes); 3796 3797 if (mJob != null) { 3798 mJob.finishBackupPass(); 3799 } 3800 3801 synchronized (mQueueLock) { 3802 mRunningFullBackupTask = null; 3803 } 3804 3805 synchronized (mLatch) { 3806 mLatch.set(true); 3807 mLatch.notifyAll(); 3808 } 3809 3810 // Now that we're actually done with schedule-driven work, reschedule 3811 // the next pass based on the new queue state. 3812 if (mUpdateSchedule) { 3813 scheduleNextFullBackupJob(); 3814 } 3815 } 3816 } 3817 3818 void cleanUpPipes(ParcelFileDescriptor[] pipes) { 3819 if (pipes != null) { 3820 if (pipes[0] != null) { 3821 ParcelFileDescriptor fd = pipes[0]; 3822 pipes[0] = null; 3823 try { 3824 fd.close(); 3825 } catch (IOException e) { 3826 Slog.w(TAG, "Unable to close pipe!"); 3827 } 3828 } 3829 if (pipes[1] != null) { 3830 ParcelFileDescriptor fd = pipes[1]; 3831 pipes[1] = null; 3832 try { 3833 fd.close(); 3834 } catch (IOException e) { 3835 Slog.w(TAG, "Unable to close pipe!"); 3836 } 3837 } 3838 } 3839 } 3840 3841 // Run the backup and pipe it back to the given socket -- expects to run on 3842 // a standalone thread. The runner owns this half of the pipe, and closes 3843 // it to indicate EOD to the other end. 3844 class SinglePackageBackupRunner implements Runnable { 3845 final ParcelFileDescriptor mOutput; 3846 final PackageInfo mTarget; 3847 final AtomicBoolean mLatch; 3848 3849 SinglePackageBackupRunner(ParcelFileDescriptor output, PackageInfo target, 3850 AtomicBoolean latch) throws IOException { 3851 int oldfd = output.getFd(); 3852 mOutput = ParcelFileDescriptor.dup(output.getFileDescriptor()); 3853 mTarget = target; 3854 mLatch = latch; 3855 } 3856 3857 @Override 3858 public void run() { 3859 try { 3860 FileOutputStream out = new FileOutputStream(mOutput.getFileDescriptor()); 3861 FullBackupEngine engine = new FullBackupEngine(out, mTarget.packageName, false); 3862 engine.backupOnePackage(mTarget); 3863 } catch (Exception e) { 3864 Slog.e(TAG, "Exception during full package backup of " + mTarget); 3865 } finally { 3866 synchronized (mLatch) { 3867 mLatch.set(true); 3868 mLatch.notifyAll(); 3869 } 3870 try { 3871 mOutput.close(); 3872 } catch (IOException e) { 3873 Slog.w(TAG, "Error closing transport pipe in runner"); 3874 } 3875 } 3876 } 3877 3878 } 3879 } 3880 3881 // ----- Full-data backup scheduling ----- 3882 3883 /** 3884 * Schedule a job to tell us when it's a good time to run a full backup 3885 */ 3886 void scheduleNextFullBackupJob() { 3887 synchronized (mQueueLock) { 3888 if (mFullBackupQueue.size() > 0) { 3889 // schedule the next job at the point in the future when the least-recently 3890 // backed up app comes due for backup again; or immediately if it's already 3891 // due. 3892 long upcomingLastBackup = mFullBackupQueue.get(0).lastBackup; 3893 long timeSinceLast = System.currentTimeMillis() - upcomingLastBackup; 3894 final long latency = (timeSinceLast < MIN_FULL_BACKUP_INTERVAL) 3895 ? (MIN_FULL_BACKUP_INTERVAL - timeSinceLast) : 0; 3896 Runnable r = new Runnable() { 3897 @Override public void run() { 3898 FullBackupJob.schedule(mContext, latency); 3899 } 3900 }; 3901 mBackupHandler.postDelayed(r, 2500); 3902 } else { 3903 if (DEBUG_SCHEDULING) { 3904 Slog.i(TAG, "Full backup queue empty; not scheduling"); 3905 } 3906 } 3907 } 3908 } 3909 3910 /** 3911 * Enqueue full backup for the given app, with a note about when it last ran. 3912 */ 3913 void enqueueFullBackup(String packageName, long lastBackedUp) { 3914 FullBackupEntry newEntry = new FullBackupEntry(packageName, lastBackedUp); 3915 synchronized (mQueueLock) { 3916 int N = mFullBackupQueue.size(); 3917 // First, sanity check that we aren't adding a duplicate. Slow but 3918 // straightforward; we'll have at most on the order of a few hundred 3919 // items in this list. 3920 for (int i = N-1; i >= 0; i--) { 3921 final FullBackupEntry e = mFullBackupQueue.get(i); 3922 if (packageName.equals(e.packageName)) { 3923 if (DEBUG) { 3924 Slog.w(TAG, "Removing schedule queue dupe of " + packageName); 3925 } 3926 mFullBackupQueue.remove(i); 3927 } 3928 } 3929 3930 // This is also slow but easy for modest numbers of apps: work backwards 3931 // from the end of the queue until we find an item whose last backup 3932 // time was before this one, then insert this new entry after it. 3933 int which; 3934 for (which = mFullBackupQueue.size() - 1; which >= 0; which--) { 3935 final FullBackupEntry entry = mFullBackupQueue.get(which); 3936 if (entry.lastBackup <= lastBackedUp) { 3937 mFullBackupQueue.add(which + 1, newEntry); 3938 break; 3939 } 3940 } 3941 if (which < 0) { 3942 // this one is earlier than any existing one, so prepend 3943 mFullBackupQueue.add(0, newEntry); 3944 } 3945 } 3946 writeFullBackupScheduleAsync(); 3947 } 3948 3949 /** 3950 * Conditions are right for a full backup operation, so run one. The model we use is 3951 * to perform one app backup per scheduled job execution, and to reschedule the job 3952 * with zero latency as long as conditions remain right and we still have work to do. 3953 * 3954 * @return Whether ongoing work will continue. The return value here will be passed 3955 * along as the return value to the scheduled job's onStartJob() callback. 3956 */ 3957 boolean beginFullBackup(FullBackupJob scheduledJob) { 3958 long now = System.currentTimeMillis(); 3959 FullBackupEntry entry = null; 3960 3961 if (DEBUG_SCHEDULING) { 3962 Slog.i(TAG, "Beginning scheduled full backup operation"); 3963 } 3964 3965 // Great; we're able to run full backup jobs now. See if we have any work to do. 3966 synchronized (mQueueLock) { 3967 if (mRunningFullBackupTask != null) { 3968 Slog.e(TAG, "Backup triggered but one already/still running!"); 3969 return false; 3970 } 3971 3972 if (mFullBackupQueue.size() == 0) { 3973 // no work to do so just bow out 3974 if (DEBUG) { 3975 Slog.i(TAG, "Backup queue empty; doing nothing"); 3976 } 3977 return false; 3978 } 3979 3980 entry = mFullBackupQueue.get(0); 3981 long timeSinceRun = now - entry.lastBackup; 3982 if (timeSinceRun < MIN_FULL_BACKUP_INTERVAL) { 3983 // It's too early to back up the next thing in the queue, so bow out 3984 if (MORE_DEBUG) { 3985 Slog.i(TAG, "Device ready but too early to back up next app"); 3986 } 3987 final long latency = MIN_FULL_BACKUP_INTERVAL - timeSinceRun; 3988 mBackupHandler.post(new Runnable() { 3989 @Override public void run() { 3990 FullBackupJob.schedule(mContext, latency); 3991 } 3992 }); 3993 return false; 3994 } 3995 3996 // Okay, the top thing is runnable now. Pop it off and get going. 3997 mFullBackupQueue.remove(0); 3998 AtomicBoolean latch = new AtomicBoolean(false); 3999 String[] pkg = new String[] {entry.packageName}; 4000 mRunningFullBackupTask = new PerformFullTransportBackupTask(null, pkg, true, 4001 scheduledJob, latch); 4002 (new Thread(mRunningFullBackupTask)).start(); 4003 } 4004 4005 return true; 4006 } 4007 4008 // The job scheduler says our constraints don't hold any more, 4009 // so tear down any ongoing backup task right away. 4010 void endFullBackup() { 4011 synchronized (mQueueLock) { 4012 if (mRunningFullBackupTask != null) { 4013 if (DEBUG_SCHEDULING) { 4014 Slog.i(TAG, "Telling running backup to stop"); 4015 } 4016 mRunningFullBackupTask.setRunning(false); 4017 } 4018 } 4019 } 4020 4021 // ----- Restore infrastructure ----- 4022 4023 abstract class RestoreEngine { 4024 static final String TAG = "RestoreEngine"; 4025 4026 public static final int SUCCESS = 0; 4027 public static final int TARGET_FAILURE = -2; 4028 public static final int TRANSPORT_FAILURE = -3; 4029 4030 private AtomicBoolean mRunning = new AtomicBoolean(false); 4031 private AtomicInteger mResult = new AtomicInteger(SUCCESS); 4032 4033 public boolean isRunning() { 4034 return mRunning.get(); 4035 } 4036 4037 public void setRunning(boolean stillRunning) { 4038 synchronized (mRunning) { 4039 mRunning.set(stillRunning); 4040 mRunning.notifyAll(); 4041 } 4042 } 4043 4044 public int waitForResult() { 4045 synchronized (mRunning) { 4046 while (isRunning()) { 4047 try { 4048 mRunning.wait(); 4049 } catch (InterruptedException e) {} 4050 } 4051 } 4052 return getResult(); 4053 } 4054 4055 public int getResult() { 4056 return mResult.get(); 4057 } 4058 4059 public void setResult(int result) { 4060 mResult.set(result); 4061 } 4062 4063 // TODO: abstract restore state and APIs 4064 } 4065 4066 // ----- Full restore from a file/socket ----- 4067 4068 // Description of a file in the restore datastream 4069 static class FileMetadata { 4070 String packageName; // name of the owning app 4071 String installerPackageName; // name of the market-type app that installed the owner 4072 int type; // e.g. BackupAgent.TYPE_DIRECTORY 4073 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN 4074 String path; // subpath within the semantic domain 4075 long mode; // e.g. 0666 (actually int) 4076 long mtime; // last mod time, UTC time_t (actually int) 4077 long size; // bytes of content 4078 4079 @Override 4080 public String toString() { 4081 StringBuilder sb = new StringBuilder(128); 4082 sb.append("FileMetadata{"); 4083 sb.append(packageName); sb.append(','); 4084 sb.append(type); sb.append(','); 4085 sb.append(domain); sb.append(':'); sb.append(path); sb.append(','); 4086 sb.append(size); 4087 sb.append('}'); 4088 return sb.toString(); 4089 } 4090 } 4091 4092 enum RestorePolicy { 4093 IGNORE, 4094 ACCEPT, 4095 ACCEPT_IF_APK 4096 } 4097 4098 // Full restore engine, used by both adb restore and transport-based full restore 4099 class FullRestoreEngine extends RestoreEngine { 4100 // Dedicated observer, if any 4101 IFullBackupRestoreObserver mObserver; 4102 4103 // Where we're delivering the file data as we go 4104 IBackupAgent mAgent; 4105 4106 // Are we permitted to only deliver a specific package's metadata? 4107 PackageInfo mOnlyPackage; 4108 4109 boolean mAllowApks; 4110 boolean mAllowObbs; 4111 4112 // Which package are we currently handling data for? 4113 String mAgentPackage; 4114 4115 // Info for working with the target app process 4116 ApplicationInfo mTargetApp; 4117 4118 // Machinery for restoring OBBs 4119 FullBackupObbConnection mObbConnection = null; 4120 4121 // possible handling states for a given package in the restore dataset 4122 final HashMap<String, RestorePolicy> mPackagePolicies 4123 = new HashMap<String, RestorePolicy>(); 4124 4125 // installer package names for each encountered app, derived from the manifests 4126 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>(); 4127 4128 // Signatures for a given package found in its manifest file 4129 final HashMap<String, Signature[]> mManifestSignatures 4130 = new HashMap<String, Signature[]>(); 4131 4132 // Packages we've already wiped data on when restoring their first file 4133 final HashSet<String> mClearedPackages = new HashSet<String>(); 4134 4135 // How much data have we moved? 4136 long mBytes; 4137 4138 // Working buffer 4139 byte[] mBuffer; 4140 4141 // Pipes for moving data 4142 ParcelFileDescriptor[] mPipes = null; 4143 4144 // Widget blob to be restored out-of-band 4145 byte[] mWidgetData = null; 4146 4147 // Runner that can be placed in a separate thread to do in-process 4148 // invocations of the full restore API asynchronously 4149 class RestoreFileRunnable implements Runnable { 4150 IBackupAgent mAgent; 4151 FileMetadata mInfo; 4152 ParcelFileDescriptor mSocket; 4153 int mToken; 4154 4155 RestoreFileRunnable(IBackupAgent agent, FileMetadata info, 4156 ParcelFileDescriptor socket, int token) throws IOException { 4157 mAgent = agent; 4158 mInfo = info; 4159 mToken = token; 4160 4161 // This class is used strictly for process-local binder invocations. The 4162 // semantics of ParcelFileDescriptor differ in this case; in particular, we 4163 // do not automatically get a 'dup'ed descriptor that we can can continue 4164 // to use asynchronously from the caller. So, we make sure to dup it ourselves 4165 // before proceeding to do the restore. 4166 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor()); 4167 } 4168 4169 @Override 4170 public void run() { 4171 try { 4172 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type, 4173 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime, 4174 mToken, mBackupManagerBinder); 4175 } catch (RemoteException e) { 4176 // never happens; this is used strictly for local binder calls 4177 } 4178 } 4179 } 4180 4181 public FullRestoreEngine(IFullBackupRestoreObserver observer, PackageInfo onlyPackage, 4182 boolean allowApks, boolean allowObbs) { 4183 mObserver = observer; 4184 mOnlyPackage = onlyPackage; 4185 mAllowApks = allowApks; 4186 mAllowObbs = allowObbs; 4187 mBuffer = new byte[32 * 1024]; 4188 mBytes = 0; 4189 } 4190 4191 public boolean restoreOneFile(InputStream instream) { 4192 if (!isRunning()) { 4193 Slog.w(TAG, "Restore engine used after halting"); 4194 return false; 4195 } 4196 4197 FileMetadata info; 4198 try { 4199 if (MORE_DEBUG) { 4200 Slog.v(TAG, "Reading tar header for restoring file"); 4201 } 4202 info = readTarHeaders(instream); 4203 if (info != null) { 4204 if (MORE_DEBUG) { 4205 dumpFileMetadata(info); 4206 } 4207 4208 final String pkg = info.packageName; 4209 if (!pkg.equals(mAgentPackage)) { 4210 // In the single-package case, it's a semantic error to expect 4211 // one app's data but see a different app's on the wire 4212 if (mOnlyPackage != null) { 4213 if (!pkg.equals(mOnlyPackage.packageName)) { 4214 Slog.w(TAG, "Expected data for " + mOnlyPackage 4215 + " but saw " + pkg); 4216 setResult(RestoreEngine.TRANSPORT_FAILURE); 4217 setRunning(false); 4218 return false; 4219 } 4220 } 4221 4222 // okay, change in package; set up our various 4223 // bookkeeping if we haven't seen it yet 4224 if (!mPackagePolicies.containsKey(pkg)) { 4225 mPackagePolicies.put(pkg, RestorePolicy.IGNORE); 4226 } 4227 4228 // Clean up the previous agent relationship if necessary, 4229 // and let the observer know we're considering a new app. 4230 if (mAgent != null) { 4231 if (DEBUG) Slog.d(TAG, "Saw new package; finalizing old one"); 4232 // Now we're really done 4233 tearDownPipes(); 4234 tearDownAgent(mTargetApp); 4235 mTargetApp = null; 4236 mAgentPackage = null; 4237 } 4238 } 4239 4240 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) { 4241 mPackagePolicies.put(pkg, readAppManifest(info, instream)); 4242 mPackageInstallers.put(pkg, info.installerPackageName); 4243 // We've read only the manifest content itself at this point, 4244 // so consume the footer before looping around to the next 4245 // input file 4246 skipTarPadding(info.size, instream); 4247 sendOnRestorePackage(pkg); 4248 } else if (info.path.equals(BACKUP_METADATA_FILENAME)) { 4249 // Metadata blobs! 4250 readMetadata(info, instream); 4251 } else { 4252 // Non-manifest, so it's actual file data. Is this a package 4253 // we're ignoring? 4254 boolean okay = true; 4255 RestorePolicy policy = mPackagePolicies.get(pkg); 4256 switch (policy) { 4257 case IGNORE: 4258 okay = false; 4259 break; 4260 4261 case ACCEPT_IF_APK: 4262 // If we're in accept-if-apk state, then the first file we 4263 // see MUST be the apk. 4264 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) { 4265 if (DEBUG) Slog.d(TAG, "APK file; installing"); 4266 // Try to install the app. 4267 String installerName = mPackageInstallers.get(pkg); 4268 okay = installApk(info, installerName, instream); 4269 // good to go; promote to ACCEPT 4270 mPackagePolicies.put(pkg, (okay) 4271 ? RestorePolicy.ACCEPT 4272 : RestorePolicy.IGNORE); 4273 // At this point we've consumed this file entry 4274 // ourselves, so just strip the tar footer and 4275 // go on to the next file in the input stream 4276 skipTarPadding(info.size, instream); 4277 return true; 4278 } else { 4279 // File data before (or without) the apk. We can't 4280 // handle it coherently in this case so ignore it. 4281 mPackagePolicies.put(pkg, RestorePolicy.IGNORE); 4282 okay = false; 4283 } 4284 break; 4285 4286 case ACCEPT: 4287 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) { 4288 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT"); 4289 // we can take the data without the apk, so we 4290 // *want* to do so. skip the apk by declaring this 4291 // one file not-okay without changing the restore 4292 // policy for the package. 4293 okay = false; 4294 } 4295 break; 4296 4297 default: 4298 // Something has gone dreadfully wrong when determining 4299 // the restore policy from the manifest. Ignore the 4300 // rest of this package's data. 4301 Slog.e(TAG, "Invalid policy from manifest"); 4302 okay = false; 4303 mPackagePolicies.put(pkg, RestorePolicy.IGNORE); 4304 break; 4305 } 4306 4307 // Is it a *file* we need to drop? 4308 if (!isRestorableFile(info)) { 4309 okay = false; 4310 } 4311 4312 // If the policy is satisfied, go ahead and set up to pipe the 4313 // data to the agent. 4314 if (DEBUG && okay && mAgent != null) { 4315 Slog.i(TAG, "Reusing existing agent instance"); 4316 } 4317 if (okay && mAgent == null) { 4318 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg); 4319 4320 try { 4321 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0); 4322 4323 // If we haven't sent any data to this app yet, we probably 4324 // need to clear it first. Check that. 4325 if (!mClearedPackages.contains(pkg)) { 4326 // apps with their own backup agents are 4327 // responsible for coherently managing a full 4328 // restore. 4329 if (mTargetApp.backupAgentName == null) { 4330 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore"); 4331 clearApplicationDataSynchronous(pkg); 4332 } else { 4333 if (DEBUG) Slog.d(TAG, "backup agent (" 4334 + mTargetApp.backupAgentName + ") => no clear"); 4335 } 4336 mClearedPackages.add(pkg); 4337 } else { 4338 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required"); 4339 } 4340 4341 // All set; now set up the IPC and launch the agent 4342 setUpPipes(); 4343 mAgent = bindToAgentSynchronous(mTargetApp, 4344 IApplicationThread.BACKUP_MODE_RESTORE_FULL); 4345 mAgentPackage = pkg; 4346 } catch (IOException e) { 4347 // fall through to error handling 4348 } catch (NameNotFoundException e) { 4349 // fall through to error handling 4350 } 4351 4352 if (mAgent == null) { 4353 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg); 4354 okay = false; 4355 tearDownPipes(); 4356 mPackagePolicies.put(pkg, RestorePolicy.IGNORE); 4357 } 4358 } 4359 4360 // Sanity check: make sure we never give data to the wrong app. This 4361 // should never happen but a little paranoia here won't go amiss. 4362 if (okay && !pkg.equals(mAgentPackage)) { 4363 Slog.e(TAG, "Restoring data for " + pkg 4364 + " but agent is for " + mAgentPackage); 4365 okay = false; 4366 } 4367 4368 // At this point we have an agent ready to handle the full 4369 // restore data as well as a pipe for sending data to 4370 // that agent. Tell the agent to start reading from the 4371 // pipe. 4372 if (okay) { 4373 boolean agentSuccess = true; 4374 long toCopy = info.size; 4375 final int token = generateToken(); 4376 try { 4377 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null); 4378 if (info.domain.equals(FullBackup.OBB_TREE_TOKEN)) { 4379 if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg 4380 + " : " + info.path); 4381 mObbConnection.restoreObbFile(pkg, mPipes[0], 4382 info.size, info.type, info.path, info.mode, 4383 info.mtime, token, mBackupManagerBinder); 4384 } else { 4385 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file " 4386 + info.path); 4387 // fire up the app's agent listening on the socket. If 4388 // the agent is running in the system process we can't 4389 // just invoke it asynchronously, so we provide a thread 4390 // for it here. 4391 if (mTargetApp.processName.equals("system")) { 4392 Slog.d(TAG, "system process agent - spinning a thread"); 4393 RestoreFileRunnable runner = new RestoreFileRunnable( 4394 mAgent, info, mPipes[0], token); 4395 new Thread(runner, "restore-sys-runner").start(); 4396 } else { 4397 mAgent.doRestoreFile(mPipes[0], info.size, info.type, 4398 info.domain, info.path, info.mode, info.mtime, 4399 token, mBackupManagerBinder); 4400 } 4401 } 4402 } catch (IOException e) { 4403 // couldn't dup the socket for a process-local restore 4404 Slog.d(TAG, "Couldn't establish restore"); 4405 agentSuccess = false; 4406 okay = false; 4407 } catch (RemoteException e) { 4408 // whoops, remote entity went away. We'll eat the content 4409 // ourselves, then, and not copy it over. 4410 Slog.e(TAG, "Agent crashed during full restore"); 4411 agentSuccess = false; 4412 okay = false; 4413 } 4414 4415 // Copy over the data if the agent is still good 4416 if (okay) { 4417 if (MORE_DEBUG) { 4418 Slog.v(TAG, " copying to restore agent: " 4419 + toCopy + " bytes"); 4420 } 4421 boolean pipeOkay = true; 4422 FileOutputStream pipe = new FileOutputStream( 4423 mPipes[1].getFileDescriptor()); 4424 while (toCopy > 0) { 4425 int toRead = (toCopy > mBuffer.length) 4426 ? mBuffer.length : (int)toCopy; 4427 int nRead = instream.read(mBuffer, 0, toRead); 4428 if (nRead >= 0) mBytes += nRead; 4429 if (nRead <= 0) break; 4430 toCopy -= nRead; 4431 4432 // send it to the output pipe as long as things 4433 // are still good 4434 if (pipeOkay) { 4435 try { 4436 pipe.write(mBuffer, 0, nRead); 4437 } catch (IOException e) { 4438 Slog.e(TAG, "Failed to write to restore pipe", e); 4439 pipeOkay = false; 4440 } 4441 } 4442 } 4443 4444 // done sending that file! Now we just need to consume 4445 // the delta from info.size to the end of block. 4446 skipTarPadding(info.size, instream); 4447 4448 // and now that we've sent it all, wait for the remote 4449 // side to acknowledge receipt 4450 agentSuccess = waitUntilOperationComplete(token); 4451 } 4452 4453 // okay, if the remote end failed at any point, deal with 4454 // it by ignoring the rest of the restore on it 4455 if (!agentSuccess) { 4456 if (DEBUG) { 4457 Slog.i(TAG, "Agent failure; ending restore"); 4458 } 4459 mBackupHandler.removeMessages(MSG_TIMEOUT); 4460 tearDownPipes(); 4461 tearDownAgent(mTargetApp); 4462 mAgent = null; 4463 mPackagePolicies.put(pkg, RestorePolicy.IGNORE); 4464 4465 // If this was a single-package restore, we halt immediately 4466 // with an agent error under these circumstances 4467 if (mOnlyPackage != null) { 4468 setResult(RestoreEngine.TARGET_FAILURE); 4469 setRunning(false); 4470 return false; 4471 } 4472 } 4473 } 4474 4475 // Problems setting up the agent communication, an explicitly 4476 // dropped file, or an already-ignored package: skip to the 4477 // next stream entry by reading and discarding this file. 4478 if (!okay) { 4479 if (DEBUG) Slog.d(TAG, "[discarding file content]"); 4480 long bytesToConsume = (info.size + 511) & ~511; 4481 while (bytesToConsume > 0) { 4482 int toRead = (bytesToConsume > mBuffer.length) 4483 ? mBuffer.length : (int)bytesToConsume; 4484 long nRead = instream.read(mBuffer, 0, toRead); 4485 if (nRead >= 0) mBytes += nRead; 4486 if (nRead <= 0) break; 4487 bytesToConsume -= nRead; 4488 } 4489 } 4490 } 4491 } 4492 } catch (IOException e) { 4493 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e); 4494 setResult(RestoreEngine.TRANSPORT_FAILURE); 4495 info = null; 4496 } 4497 4498 // If we got here we're either running smoothly or we've finished 4499 if (info == null) { 4500 if (MORE_DEBUG) { 4501 Slog.i(TAG, "No [more] data for this package; tearing down"); 4502 } 4503 tearDownPipes(); 4504 tearDownAgent(mTargetApp); 4505 setRunning(false); 4506 } 4507 return (info != null); 4508 } 4509 4510 void setUpPipes() throws IOException { 4511 mPipes = ParcelFileDescriptor.createPipe(); 4512 } 4513 4514 void tearDownPipes() { 4515 if (mPipes != null) { 4516 try { 4517 mPipes[0].close(); 4518 mPipes[0] = null; 4519 mPipes[1].close(); 4520 mPipes[1] = null; 4521 } catch (IOException e) { 4522 Slog.w(TAG, "Couldn't close agent pipes", e); 4523 } 4524 mPipes = null; 4525 } 4526 } 4527 4528 void tearDownAgent(ApplicationInfo app) { 4529 if (mAgent != null) { 4530 try { 4531 // unbind and tidy up even on timeout or failure, just in case 4532 mActivityManager.unbindBackupAgent(app); 4533 4534 // The agent was running with a stub Application object, so shut it down. 4535 // !!! We hardcode the confirmation UI's package name here rather than use a 4536 // manifest flag! TODO something less direct. 4537 if (app.uid != Process.SYSTEM_UID 4538 && !app.packageName.equals("com.android.backupconfirm")) { 4539 if (DEBUG) Slog.d(TAG, "Killing host process"); 4540 mActivityManager.killApplicationProcess(app.processName, app.uid); 4541 } else { 4542 if (DEBUG) Slog.d(TAG, "Not killing after full restore"); 4543 } 4544 } catch (RemoteException e) { 4545 Slog.d(TAG, "Lost app trying to shut down"); 4546 } 4547 mAgent = null; 4548 } 4549 } 4550 4551 class RestoreInstallObserver extends IPackageInstallObserver.Stub { 4552 final AtomicBoolean mDone = new AtomicBoolean(); 4553 String mPackageName; 4554 int mResult; 4555 4556 public void reset() { 4557 synchronized (mDone) { 4558 mDone.set(false); 4559 } 4560 } 4561 4562 public void waitForCompletion() { 4563 synchronized (mDone) { 4564 while (mDone.get() == false) { 4565 try { 4566 mDone.wait(); 4567 } catch (InterruptedException e) { } 4568 } 4569 } 4570 } 4571 4572 int getResult() { 4573 return mResult; 4574 } 4575 4576 @Override 4577 public void packageInstalled(String packageName, int returnCode) 4578 throws RemoteException { 4579 synchronized (mDone) { 4580 mResult = returnCode; 4581 mPackageName = packageName; 4582 mDone.set(true); 4583 mDone.notifyAll(); 4584 } 4585 } 4586 } 4587 4588 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub { 4589 final AtomicBoolean mDone = new AtomicBoolean(); 4590 int mResult; 4591 4592 public void reset() { 4593 synchronized (mDone) { 4594 mDone.set(false); 4595 } 4596 } 4597 4598 public void waitForCompletion() { 4599 synchronized (mDone) { 4600 while (mDone.get() == false) { 4601 try { 4602 mDone.wait(); 4603 } catch (InterruptedException e) { } 4604 } 4605 } 4606 } 4607 4608 @Override 4609 public void packageDeleted(String packageName, int returnCode) throws RemoteException { 4610 synchronized (mDone) { 4611 mResult = returnCode; 4612 mDone.set(true); 4613 mDone.notifyAll(); 4614 } 4615 } 4616 } 4617 4618 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver(); 4619 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver(); 4620 4621 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) { 4622 boolean okay = true; 4623 4624 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName); 4625 4626 // The file content is an .apk file. Copy it out to a staging location and 4627 // attempt to install it. 4628 File apkFile = new File(mDataDir, info.packageName); 4629 try { 4630 FileOutputStream apkStream = new FileOutputStream(apkFile); 4631 byte[] buffer = new byte[32 * 1024]; 4632 long size = info.size; 4633 while (size > 0) { 4634 long toRead = (buffer.length < size) ? buffer.length : size; 4635 int didRead = instream.read(buffer, 0, (int)toRead); 4636 if (didRead >= 0) mBytes += didRead; 4637 apkStream.write(buffer, 0, didRead); 4638 size -= didRead; 4639 } 4640 apkStream.close(); 4641 4642 // make sure the installer can read it 4643 apkFile.setReadable(true, false); 4644 4645 // Now install it 4646 Uri packageUri = Uri.fromFile(apkFile); 4647 mInstallObserver.reset(); 4648 mPackageManager.installPackage(packageUri, mInstallObserver, 4649 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB, 4650 installerPackage); 4651 mInstallObserver.waitForCompletion(); 4652 4653 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) { 4654 // The only time we continue to accept install of data even if the 4655 // apk install failed is if we had already determined that we could 4656 // accept the data regardless. 4657 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) { 4658 okay = false; 4659 } 4660 } else { 4661 // Okay, the install succeeded. Make sure it was the right app. 4662 boolean uninstall = false; 4663 if (!mInstallObserver.mPackageName.equals(info.packageName)) { 4664 Slog.w(TAG, "Restore stream claimed to include apk for " 4665 + info.packageName + " but apk was really " 4666 + mInstallObserver.mPackageName); 4667 // delete the package we just put in place; it might be fraudulent 4668 okay = false; 4669 uninstall = true; 4670 } else { 4671 try { 4672 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName, 4673 PackageManager.GET_SIGNATURES); 4674 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) { 4675 Slog.w(TAG, "Restore stream contains apk of package " 4676 + info.packageName + " but it disallows backup/restore"); 4677 okay = false; 4678 } else { 4679 // So far so good -- do the signatures match the manifest? 4680 Signature[] sigs = mManifestSignatures.get(info.packageName); 4681 if (signaturesMatch(sigs, pkg)) { 4682 // If this is a system-uid app without a declared backup agent, 4683 // don't restore any of the file data. 4684 if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID) 4685 && (pkg.applicationInfo.backupAgentName == null)) { 4686 Slog.w(TAG, "Installed app " + info.packageName 4687 + " has restricted uid and no agent"); 4688 okay = false; 4689 } 4690 } else { 4691 Slog.w(TAG, "Installed app " + info.packageName 4692 + " signatures do not match restore manifest"); 4693 okay = false; 4694 uninstall = true; 4695 } 4696 } 4697 } catch (NameNotFoundException e) { 4698 Slog.w(TAG, "Install of package " + info.packageName 4699 + " succeeded but now not found"); 4700 okay = false; 4701 } 4702 } 4703 4704 // If we're not okay at this point, we need to delete the package 4705 // that we just installed. 4706 if (uninstall) { 4707 mDeleteObserver.reset(); 4708 mPackageManager.deletePackage(mInstallObserver.mPackageName, 4709 mDeleteObserver, 0); 4710 mDeleteObserver.waitForCompletion(); 4711 } 4712 } 4713 } catch (IOException e) { 4714 Slog.e(TAG, "Unable to transcribe restored apk for install"); 4715 okay = false; 4716 } finally { 4717 apkFile.delete(); 4718 } 4719 4720 return okay; 4721 } 4722 4723 // Given an actual file content size, consume the post-content padding mandated 4724 // by the tar format. 4725 void skipTarPadding(long size, InputStream instream) throws IOException { 4726 long partial = (size + 512) % 512; 4727 if (partial > 0) { 4728 final int needed = 512 - (int)partial; 4729 if (MORE_DEBUG) { 4730 Slog.i(TAG, "Skipping tar padding: " + needed + " bytes"); 4731 } 4732 byte[] buffer = new byte[needed]; 4733 if (readExactly(instream, buffer, 0, needed) == needed) { 4734 mBytes += needed; 4735 } else throw new IOException("Unexpected EOF in padding"); 4736 } 4737 } 4738 4739 // Read a widget metadata file, returning the restored blob 4740 void readMetadata(FileMetadata info, InputStream instream) throws IOException { 4741 // Fail on suspiciously large widget dump files 4742 if (info.size > 64 * 1024) { 4743 throw new IOException("Metadata too big; corrupt? size=" + info.size); 4744 } 4745 4746 byte[] buffer = new byte[(int) info.size]; 4747 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) { 4748 mBytes += info.size; 4749 } else throw new IOException("Unexpected EOF in widget data"); 4750 4751 String[] str = new String[1]; 4752 int offset = extractLine(buffer, 0, str); 4753 int version = Integer.parseInt(str[0]); 4754 if (version == BACKUP_MANIFEST_VERSION) { 4755 offset = extractLine(buffer, offset, str); 4756 final String pkg = str[0]; 4757 if (info.packageName.equals(pkg)) { 4758 // Data checks out -- the rest of the buffer is a concatenation of 4759 // binary blobs as described in the comment at writeAppWidgetData() 4760 ByteArrayInputStream bin = new ByteArrayInputStream(buffer, 4761 offset, buffer.length - offset); 4762 DataInputStream in = new DataInputStream(bin); 4763 while (bin.available() > 0) { 4764 int token = in.readInt(); 4765 int size = in.readInt(); 4766 if (size > 64 * 1024) { 4767 throw new IOException("Datum " 4768 + Integer.toHexString(token) 4769 + " too big; corrupt? size=" + info.size); 4770 } 4771 switch (token) { 4772 case BACKUP_WIDGET_METADATA_TOKEN: 4773 { 4774 if (MORE_DEBUG) { 4775 Slog.i(TAG, "Got widget metadata for " + info.packageName); 4776 } 4777 mWidgetData = new byte[size]; 4778 in.read(mWidgetData); 4779 break; 4780 } 4781 default: 4782 { 4783 if (DEBUG) { 4784 Slog.i(TAG, "Ignoring metadata blob " 4785 + Integer.toHexString(token) 4786 + " for " + info.packageName); 4787 } 4788 in.skipBytes(size); 4789 break; 4790 } 4791 } 4792 } 4793 } else { 4794 Slog.w(TAG, "Metadata mismatch: package " + info.packageName 4795 + " but widget data for " + pkg); 4796 } 4797 } else { 4798 Slog.w(TAG, "Unsupported metadata version " + version); 4799 } 4800 } 4801 4802 // Returns a policy constant 4803 RestorePolicy readAppManifest(FileMetadata info, InputStream instream) 4804 throws IOException { 4805 // Fail on suspiciously large manifest files 4806 if (info.size > 64 * 1024) { 4807 throw new IOException("Restore manifest too big; corrupt? size=" + info.size); 4808 } 4809 4810 byte[] buffer = new byte[(int) info.size]; 4811 if (MORE_DEBUG) { 4812 Slog.i(TAG, " readAppManifest() looking for " + info.size + " bytes, " 4813 + mBytes + " already consumed"); 4814 } 4815 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) { 4816 mBytes += info.size; 4817 } else throw new IOException("Unexpected EOF in manifest"); 4818 4819 RestorePolicy policy = RestorePolicy.IGNORE; 4820 String[] str = new String[1]; 4821 int offset = 0; 4822 4823 try { 4824 offset = extractLine(buffer, offset, str); 4825 int version = Integer.parseInt(str[0]); 4826 if (version == BACKUP_MANIFEST_VERSION) { 4827 offset = extractLine(buffer, offset, str); 4828 String manifestPackage = str[0]; 4829 // TODO: handle <original-package> 4830 if (manifestPackage.equals(info.packageName)) { 4831 offset = extractLine(buffer, offset, str); 4832 version = Integer.parseInt(str[0]); // app version 4833 offset = extractLine(buffer, offset, str); 4834 int platformVersion = Integer.parseInt(str[0]); 4835 offset = extractLine(buffer, offset, str); 4836 info.installerPackageName = (str[0].length() > 0) ? str[0] : null; 4837 offset = extractLine(buffer, offset, str); 4838 boolean hasApk = str[0].equals("1"); 4839 offset = extractLine(buffer, offset, str); 4840 int numSigs = Integer.parseInt(str[0]); 4841 if (numSigs > 0) { 4842 Signature[] sigs = new Signature[numSigs]; 4843 for (int i = 0; i < numSigs; i++) { 4844 offset = extractLine(buffer, offset, str); 4845 sigs[i] = new Signature(str[0]); 4846 } 4847 mManifestSignatures.put(info.packageName, sigs); 4848 4849 // Okay, got the manifest info we need... 4850 try { 4851 PackageInfo pkgInfo = mPackageManager.getPackageInfo( 4852 info.packageName, PackageManager.GET_SIGNATURES); 4853 // Fall through to IGNORE if the app explicitly disallows backup 4854 final int flags = pkgInfo.applicationInfo.flags; 4855 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) { 4856 // Restore system-uid-space packages only if they have 4857 // defined a custom backup agent 4858 if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID) 4859 || (pkgInfo.applicationInfo.backupAgentName != null)) { 4860 // Verify signatures against any installed version; if they 4861 // don't match, then we fall though and ignore the data. The 4862 // signatureMatch() method explicitly ignores the signature 4863 // check for packages installed on the system partition, because 4864 // such packages are signed with the platform cert instead of 4865 // the app developer's cert, so they're different on every 4866 // device. 4867 if (signaturesMatch(sigs, pkgInfo)) { 4868 if (pkgInfo.versionCode >= version) { 4869 Slog.i(TAG, "Sig + version match; taking data"); 4870 policy = RestorePolicy.ACCEPT; 4871 } else { 4872 // The data is from a newer version of the app than 4873 // is presently installed. That means we can only 4874 // use it if the matching apk is also supplied. 4875 if (mAllowApks) { 4876 Slog.i(TAG, "Data version " + version 4877 + " is newer than installed version " 4878 + pkgInfo.versionCode 4879 + " - requiring apk"); 4880 policy = RestorePolicy.ACCEPT_IF_APK; 4881 } else { 4882 Slog.i(TAG, "Data requires newer version " 4883 + version + "; ignoring"); 4884 policy = RestorePolicy.IGNORE; 4885 } 4886 } 4887 } else { 4888 Slog.w(TAG, "Restore manifest signatures do not match " 4889 + "installed application for " + info.packageName); 4890 } 4891 } else { 4892 Slog.w(TAG, "Package " + info.packageName 4893 + " is system level with no agent"); 4894 } 4895 } else { 4896 if (DEBUG) Slog.i(TAG, "Restore manifest from " 4897 + info.packageName + " but allowBackup=false"); 4898 } 4899 } catch (NameNotFoundException e) { 4900 // Okay, the target app isn't installed. We can process 4901 // the restore properly only if the dataset provides the 4902 // apk file and we can successfully install it. 4903 if (mAllowApks) { 4904 if (DEBUG) Slog.i(TAG, "Package " + info.packageName 4905 + " not installed; requiring apk in dataset"); 4906 policy = RestorePolicy.ACCEPT_IF_APK; 4907 } else { 4908 policy = RestorePolicy.IGNORE; 4909 } 4910 } 4911 4912 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) { 4913 Slog.i(TAG, "Cannot restore package " + info.packageName 4914 + " without the matching .apk"); 4915 } 4916 } else { 4917 Slog.i(TAG, "Missing signature on backed-up package " 4918 + info.packageName); 4919 } 4920 } else { 4921 Slog.i(TAG, "Expected package " + info.packageName 4922 + " but restore manifest claims " + manifestPackage); 4923 } 4924 } else { 4925 Slog.i(TAG, "Unknown restore manifest version " + version 4926 + " for package " + info.packageName); 4927 } 4928 } catch (NumberFormatException e) { 4929 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName); 4930 } catch (IllegalArgumentException e) { 4931 Slog.w(TAG, e.getMessage()); 4932 } 4933 4934 return policy; 4935 } 4936 4937 // Builds a line from a byte buffer starting at 'offset', and returns 4938 // the index of the next unconsumed data in the buffer. 4939 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException { 4940 final int end = buffer.length; 4941 if (offset >= end) throw new IOException("Incomplete data"); 4942 4943 int pos; 4944 for (pos = offset; pos < end; pos++) { 4945 byte c = buffer[pos]; 4946 // at LF we declare end of line, and return the next char as the 4947 // starting point for the next time through 4948 if (c == '\n') { 4949 break; 4950 } 4951 } 4952 outStr[0] = new String(buffer, offset, pos - offset); 4953 pos++; // may be pointing an extra byte past the end but that's okay 4954 return pos; 4955 } 4956 4957 void dumpFileMetadata(FileMetadata info) { 4958 if (DEBUG) { 4959 StringBuilder b = new StringBuilder(128); 4960 4961 // mode string 4962 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-'); 4963 b.append(((info.mode & 0400) != 0) ? 'r' : '-'); 4964 b.append(((info.mode & 0200) != 0) ? 'w' : '-'); 4965 b.append(((info.mode & 0100) != 0) ? 'x' : '-'); 4966 b.append(((info.mode & 0040) != 0) ? 'r' : '-'); 4967 b.append(((info.mode & 0020) != 0) ? 'w' : '-'); 4968 b.append(((info.mode & 0010) != 0) ? 'x' : '-'); 4969 b.append(((info.mode & 0004) != 0) ? 'r' : '-'); 4970 b.append(((info.mode & 0002) != 0) ? 'w' : '-'); 4971 b.append(((info.mode & 0001) != 0) ? 'x' : '-'); 4972 b.append(String.format(" %9d ", info.size)); 4973 4974 Date stamp = new Date(info.mtime); 4975 b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp)); 4976 4977 b.append(info.packageName); 4978 b.append(" :: "); 4979 b.append(info.domain); 4980 b.append(" :: "); 4981 b.append(info.path); 4982 4983 Slog.i(TAG, b.toString()); 4984 } 4985 } 4986 4987 // Consume a tar file header block [sequence] and accumulate the relevant metadata 4988 FileMetadata readTarHeaders(InputStream instream) throws IOException { 4989 byte[] block = new byte[512]; 4990 FileMetadata info = null; 4991 4992 boolean gotHeader = readTarHeader(instream, block); 4993 if (gotHeader) { 4994 try { 4995 // okay, presume we're okay, and extract the various metadata 4996 info = new FileMetadata(); 4997 info.size = extractRadix(block, 124, 12, 8); 4998 info.mtime = extractRadix(block, 136, 12, 8); 4999 info.mode = extractRadix(block, 100, 8, 8); 5000 5001 info.path = extractString(block, 345, 155); // prefix 5002 String path = extractString(block, 0, 100); 5003 if (path.length() > 0) { 5004 if (info.path.length() > 0) info.path += '/'; 5005 info.path += path; 5006 } 5007 5008 // tar link indicator field: 1 byte at offset 156 in the header. 5009 int typeChar = block[156]; 5010 if (typeChar == 'x') { 5011 // pax extended header, so we need to read that 5012 gotHeader = readPaxExtendedHeader(instream, info); 5013 if (gotHeader) { 5014 // and after a pax extended header comes another real header -- read 5015 // that to find the real file type 5016 gotHeader = readTarHeader(instream, block); 5017 } 5018 if (!gotHeader) throw new IOException("Bad or missing pax header"); 5019 5020 typeChar = block[156]; 5021 } 5022 5023 switch (typeChar) { 5024 case '0': info.type = BackupAgent.TYPE_FILE; break; 5025 case '5': { 5026 info.type = BackupAgent.TYPE_DIRECTORY; 5027 if (info.size != 0) { 5028 Slog.w(TAG, "Directory entry with nonzero size in header"); 5029 info.size = 0; 5030 } 5031 break; 5032 } 5033 case 0: { 5034 // presume EOF 5035 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info); 5036 return null; 5037 } 5038 default: { 5039 Slog.e(TAG, "Unknown tar entity type: " + typeChar); 5040 throw new IOException("Unknown entity type " + typeChar); 5041 } 5042 } 5043 5044 // Parse out the path 5045 // 5046 // first: apps/shared/unrecognized 5047 if (FullBackup.SHARED_PREFIX.regionMatches(0, 5048 info.path, 0, FullBackup.SHARED_PREFIX.length())) { 5049 // File in shared storage. !!! TODO: implement this. 5050 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length()); 5051 info.packageName = SHARED_BACKUP_AGENT_PACKAGE; 5052 info.domain = FullBackup.SHARED_STORAGE_TOKEN; 5053 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path); 5054 } else if (FullBackup.APPS_PREFIX.regionMatches(0, 5055 info.path, 0, FullBackup.APPS_PREFIX.length())) { 5056 // App content! Parse out the package name and domain 5057 5058 // strip the apps/ prefix 5059 info.path = info.path.substring(FullBackup.APPS_PREFIX.length()); 5060 5061 // extract the package name 5062 int slash = info.path.indexOf('/'); 5063 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path); 5064 info.packageName = info.path.substring(0, slash); 5065 info.path = info.path.substring(slash+1); 5066 5067 // if it's a manifest we're done, otherwise parse out the domains 5068 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) { 5069 slash = info.path.indexOf('/'); 5070 if (slash < 0) { 5071 throw new IOException("Illegal semantic path in non-manifest " 5072 + info.path); 5073 } 5074 info.domain = info.path.substring(0, slash); 5075 info.path = info.path.substring(slash + 1); 5076 } 5077 } 5078 } catch (IOException e) { 5079 if (DEBUG) { 5080 Slog.e(TAG, "Parse error in header: " + e.getMessage()); 5081 HEXLOG(block); 5082 } 5083 throw e; 5084 } 5085 } 5086 return info; 5087 } 5088 5089 private boolean isRestorableFile(FileMetadata info) { 5090 if (FullBackup.CACHE_TREE_TOKEN.equals(info.domain)) { 5091 if (MORE_DEBUG) { 5092 Slog.i(TAG, "Dropping cache file path " + info.path); 5093 } 5094 return false; 5095 } 5096 5097 if (FullBackup.ROOT_TREE_TOKEN.equals(info.domain)) { 5098 // It's possible this is "no-backup" dir contents in an archive stream 5099 // produced on a device running a version of the OS that predates that 5100 // API. Respect the no-backup intention and don't let the data get to 5101 // the app. 5102 if (info.path.startsWith("no_backup/")) { 5103 if (MORE_DEBUG) { 5104 Slog.i(TAG, "Dropping no_backup file path " + info.path); 5105 } 5106 return false; 5107 } 5108 } 5109 5110 // The path needs to be canonical 5111 if (info.path.contains("..") || info.path.contains("//")) { 5112 if (MORE_DEBUG) { 5113 Slog.w(TAG, "Dropping invalid path " + info.path); 5114 } 5115 return false; 5116 } 5117 5118 // Otherwise we think this file is good to go 5119 return true; 5120 } 5121 5122 private void HEXLOG(byte[] block) { 5123 int offset = 0; 5124 int todo = block.length; 5125 StringBuilder buf = new StringBuilder(64); 5126 while (todo > 0) { 5127 buf.append(String.format("%04x ", offset)); 5128 int numThisLine = (todo > 16) ? 16 : todo; 5129 for (int i = 0; i < numThisLine; i++) { 5130 buf.append(String.format("%02x ", block[offset+i])); 5131 } 5132 Slog.i("hexdump", buf.toString()); 5133 buf.setLength(0); 5134 todo -= numThisLine; 5135 offset += numThisLine; 5136 } 5137 } 5138 5139 // Read exactly the given number of bytes into a buffer at the stated offset. 5140 // Returns false if EOF is encountered before the requested number of bytes 5141 // could be read. 5142 int readExactly(InputStream in, byte[] buffer, int offset, int size) 5143 throws IOException { 5144 if (size <= 0) throw new IllegalArgumentException("size must be > 0"); 5145if (MORE_DEBUG) Slog.i(TAG, " ... readExactly(" + size + ") called"); 5146 int soFar = 0; 5147 while (soFar < size) { 5148 int nRead = in.read(buffer, offset + soFar, size - soFar); 5149 if (nRead <= 0) { 5150 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar); 5151 break; 5152 } 5153 soFar += nRead; 5154if (MORE_DEBUG) Slog.v(TAG, " + got " + nRead + "; now wanting " + (size - soFar)); 5155 } 5156 return soFar; 5157 } 5158 5159 boolean readTarHeader(InputStream instream, byte[] block) throws IOException { 5160 final int got = readExactly(instream, block, 0, 512); 5161 if (got == 0) return false; // Clean EOF 5162 if (got < 512) throw new IOException("Unable to read full block header"); 5163 mBytes += 512; 5164 return true; 5165 } 5166 5167 // overwrites 'info' fields based on the pax extended header 5168 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info) 5169 throws IOException { 5170 // We should never see a pax extended header larger than this 5171 if (info.size > 32*1024) { 5172 Slog.w(TAG, "Suspiciously large pax header size " + info.size 5173 + " - aborting"); 5174 throw new IOException("Sanity failure: pax header size " + info.size); 5175 } 5176 5177 // read whole blocks, not just the content size 5178 int numBlocks = (int)((info.size + 511) >> 9); 5179 byte[] data = new byte[numBlocks * 512]; 5180 if (readExactly(instream, data, 0, data.length) < data.length) { 5181 throw new IOException("Unable to read full pax header"); 5182 } 5183 mBytes += data.length; 5184 5185 final int contentSize = (int) info.size; 5186 int offset = 0; 5187 do { 5188 // extract the line at 'offset' 5189 int eol = offset+1; 5190 while (eol < contentSize && data[eol] != ' ') eol++; 5191 if (eol >= contentSize) { 5192 // error: we just hit EOD looking for the end of the size field 5193 throw new IOException("Invalid pax data"); 5194 } 5195 // eol points to the space between the count and the key 5196 int linelen = (int) extractRadix(data, offset, eol - offset, 10); 5197 int key = eol + 1; // start of key=value 5198 eol = offset + linelen - 1; // trailing LF 5199 int value; 5200 for (value = key+1; data[value] != '=' && value <= eol; value++); 5201 if (value > eol) { 5202 throw new IOException("Invalid pax declaration"); 5203 } 5204 5205 // pax requires that key/value strings be in UTF-8 5206 String keyStr = new String(data, key, value-key, "UTF-8"); 5207 // -1 to strip the trailing LF 5208 String valStr = new String(data, value+1, eol-value-1, "UTF-8"); 5209 5210 if ("path".equals(keyStr)) { 5211 info.path = valStr; 5212 } else if ("size".equals(keyStr)) { 5213 info.size = Long.parseLong(valStr); 5214 } else { 5215 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key); 5216 } 5217 5218 offset += linelen; 5219 } while (offset < contentSize); 5220 5221 return true; 5222 } 5223 5224 long extractRadix(byte[] data, int offset, int maxChars, int radix) 5225 throws IOException { 5226 long value = 0; 5227 final int end = offset + maxChars; 5228 for (int i = offset; i < end; i++) { 5229 final byte b = data[i]; 5230 // Numeric fields in tar can terminate with either NUL or SPC 5231 if (b == 0 || b == ' ') break; 5232 if (b < '0' || b > ('0' + radix - 1)) { 5233 throw new IOException("Invalid number in header: '" + (char)b 5234 + "' for radix " + radix); 5235 } 5236 value = radix * value + (b - '0'); 5237 } 5238 return value; 5239 } 5240 5241 String extractString(byte[] data, int offset, int maxChars) throws IOException { 5242 final int end = offset + maxChars; 5243 int eos = offset; 5244 // tar string fields terminate early with a NUL 5245 while (eos < end && data[eos] != 0) eos++; 5246 return new String(data, offset, eos-offset, "US-ASCII"); 5247 } 5248 5249 void sendStartRestore() { 5250 if (mObserver != null) { 5251 try { 5252 mObserver.onStartRestore(); 5253 } catch (RemoteException e) { 5254 Slog.w(TAG, "full restore observer went away: startRestore"); 5255 mObserver = null; 5256 } 5257 } 5258 } 5259 5260 void sendOnRestorePackage(String name) { 5261 if (mObserver != null) { 5262 try { 5263 // TODO: use a more user-friendly name string 5264 mObserver.onRestorePackage(name); 5265 } catch (RemoteException e) { 5266 Slog.w(TAG, "full restore observer went away: restorePackage"); 5267 mObserver = null; 5268 } 5269 } 5270 } 5271 5272 void sendEndRestore() { 5273 if (mObserver != null) { 5274 try { 5275 mObserver.onEndRestore(); 5276 } catch (RemoteException e) { 5277 Slog.w(TAG, "full restore observer went away: endRestore"); 5278 mObserver = null; 5279 } 5280 } 5281 } 5282 } 5283 5284 // ***** end new engine class *** 5285 5286 class PerformAdbRestoreTask implements Runnable { 5287 ParcelFileDescriptor mInputFile; 5288 String mCurrentPassword; 5289 String mDecryptPassword; 5290 IFullBackupRestoreObserver mObserver; 5291 AtomicBoolean mLatchObject; 5292 IBackupAgent mAgent; 5293 String mAgentPackage; 5294 ApplicationInfo mTargetApp; 5295 FullBackupObbConnection mObbConnection = null; 5296 ParcelFileDescriptor[] mPipes = null; 5297 byte[] mWidgetData = null; 5298 5299 long mBytes; 5300 5301 // possible handling states for a given package in the restore dataset 5302 final HashMap<String, RestorePolicy> mPackagePolicies 5303 = new HashMap<String, RestorePolicy>(); 5304 5305 // installer package names for each encountered app, derived from the manifests 5306 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>(); 5307 5308 // Signatures for a given package found in its manifest file 5309 final HashMap<String, Signature[]> mManifestSignatures 5310 = new HashMap<String, Signature[]>(); 5311 5312 // Packages we've already wiped data on when restoring their first file 5313 final HashSet<String> mClearedPackages = new HashSet<String>(); 5314 5315 PerformAdbRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword, 5316 IFullBackupRestoreObserver observer, AtomicBoolean latch) { 5317 mInputFile = fd; 5318 mCurrentPassword = curPassword; 5319 mDecryptPassword = decryptPassword; 5320 mObserver = observer; 5321 mLatchObject = latch; 5322 mAgent = null; 5323 mAgentPackage = null; 5324 mTargetApp = null; 5325 mObbConnection = new FullBackupObbConnection(); 5326 5327 // Which packages we've already wiped data on. We prepopulate this 5328 // with a whitelist of packages known to be unclearable. 5329 mClearedPackages.add("android"); 5330 mClearedPackages.add(SETTINGS_PACKAGE); 5331 } 5332 5333 class RestoreFileRunnable implements Runnable { 5334 IBackupAgent mAgent; 5335 FileMetadata mInfo; 5336 ParcelFileDescriptor mSocket; 5337 int mToken; 5338 5339 RestoreFileRunnable(IBackupAgent agent, FileMetadata info, 5340 ParcelFileDescriptor socket, int token) throws IOException { 5341 mAgent = agent; 5342 mInfo = info; 5343 mToken = token; 5344 5345 // This class is used strictly for process-local binder invocations. The 5346 // semantics of ParcelFileDescriptor differ in this case; in particular, we 5347 // do not automatically get a 'dup'ed descriptor that we can can continue 5348 // to use asynchronously from the caller. So, we make sure to dup it ourselves 5349 // before proceeding to do the restore. 5350 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor()); 5351 } 5352 5353 @Override 5354 public void run() { 5355 try { 5356 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type, 5357 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime, 5358 mToken, mBackupManagerBinder); 5359 } catch (RemoteException e) { 5360 // never happens; this is used strictly for local binder calls 5361 } 5362 } 5363 } 5364 5365 @Override 5366 public void run() { 5367 Slog.i(TAG, "--- Performing full-dataset restore ---"); 5368 mObbConnection.establish(); 5369 sendStartRestore(); 5370 5371 // Are we able to restore shared-storage data? 5372 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 5373 mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT); 5374 } 5375 5376 FileInputStream rawInStream = null; 5377 DataInputStream rawDataIn = null; 5378 try { 5379 if (!backupPasswordMatches(mCurrentPassword)) { 5380 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting"); 5381 return; 5382 } 5383 5384 mBytes = 0; 5385 byte[] buffer = new byte[32 * 1024]; 5386 rawInStream = new FileInputStream(mInputFile.getFileDescriptor()); 5387 rawDataIn = new DataInputStream(rawInStream); 5388 5389 // First, parse out the unencrypted/uncompressed header 5390 boolean compressed = false; 5391 InputStream preCompressStream = rawInStream; 5392 final InputStream in; 5393 5394 boolean okay = false; 5395 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length(); 5396 byte[] streamHeader = new byte[headerLen]; 5397 rawDataIn.readFully(streamHeader); 5398 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8"); 5399 if (Arrays.equals(magicBytes, streamHeader)) { 5400 // okay, header looks good. now parse out the rest of the fields. 5401 String s = readHeaderLine(rawInStream); 5402 final int archiveVersion = Integer.parseInt(s); 5403 if (archiveVersion <= BACKUP_FILE_VERSION) { 5404 // okay, it's a version we recognize. if it's version 1, we may need 5405 // to try two different PBKDF2 regimes to compare checksums. 5406 final boolean pbkdf2Fallback = (archiveVersion == 1); 5407 5408 s = readHeaderLine(rawInStream); 5409 compressed = (Integer.parseInt(s) != 0); 5410 s = readHeaderLine(rawInStream); 5411 if (s.equals("none")) { 5412 // no more header to parse; we're good to go 5413 okay = true; 5414 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) { 5415 preCompressStream = decodeAesHeaderAndInitialize(s, pbkdf2Fallback, 5416 rawInStream); 5417 if (preCompressStream != null) { 5418 okay = true; 5419 } 5420 } else Slog.w(TAG, "Archive is encrypted but no password given"); 5421 } else Slog.w(TAG, "Wrong header version: " + s); 5422 } else Slog.w(TAG, "Didn't read the right header magic"); 5423 5424 if (!okay) { 5425 Slog.w(TAG, "Invalid restore data; aborting."); 5426 return; 5427 } 5428 5429 // okay, use the right stream layer based on compression 5430 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream; 5431 5432 boolean didRestore; 5433 do { 5434 didRestore = restoreOneFile(in, buffer); 5435 } while (didRestore); 5436 5437 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes); 5438 } catch (IOException e) { 5439 Slog.e(TAG, "Unable to read restore input"); 5440 } finally { 5441 tearDownPipes(); 5442 tearDownAgent(mTargetApp); 5443 5444 try { 5445 if (rawDataIn != null) rawDataIn.close(); 5446 if (rawInStream != null) rawInStream.close(); 5447 mInputFile.close(); 5448 } catch (IOException e) { 5449 Slog.w(TAG, "Close of restore data pipe threw", e); 5450 /* nothing we can do about this */ 5451 } 5452 synchronized (mCurrentOpLock) { 5453 mCurrentOperations.clear(); 5454 } 5455 synchronized (mLatchObject) { 5456 mLatchObject.set(true); 5457 mLatchObject.notifyAll(); 5458 } 5459 mObbConnection.tearDown(); 5460 sendEndRestore(); 5461 Slog.d(TAG, "Full restore pass complete."); 5462 mWakelock.release(); 5463 } 5464 } 5465 5466 String readHeaderLine(InputStream in) throws IOException { 5467 int c; 5468 StringBuilder buffer = new StringBuilder(80); 5469 while ((c = in.read()) >= 0) { 5470 if (c == '\n') break; // consume and discard the newlines 5471 buffer.append((char)c); 5472 } 5473 return buffer.toString(); 5474 } 5475 5476 InputStream attemptMasterKeyDecryption(String algorithm, byte[] userSalt, byte[] ckSalt, 5477 int rounds, String userIvHex, String masterKeyBlobHex, InputStream rawInStream, 5478 boolean doLog) { 5479 InputStream result = null; 5480 5481 try { 5482 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding"); 5483 SecretKey userKey = buildPasswordKey(algorithm, mDecryptPassword, userSalt, 5484 rounds); 5485 byte[] IV = hexToByteArray(userIvHex); 5486 IvParameterSpec ivSpec = new IvParameterSpec(IV); 5487 c.init(Cipher.DECRYPT_MODE, 5488 new SecretKeySpec(userKey.getEncoded(), "AES"), 5489 ivSpec); 5490 byte[] mkCipher = hexToByteArray(masterKeyBlobHex); 5491 byte[] mkBlob = c.doFinal(mkCipher); 5492 5493 // first, the master key IV 5494 int offset = 0; 5495 int len = mkBlob[offset++]; 5496 IV = Arrays.copyOfRange(mkBlob, offset, offset + len); 5497 offset += len; 5498 // then the master key itself 5499 len = mkBlob[offset++]; 5500 byte[] mk = Arrays.copyOfRange(mkBlob, 5501 offset, offset + len); 5502 offset += len; 5503 // and finally the master key checksum hash 5504 len = mkBlob[offset++]; 5505 byte[] mkChecksum = Arrays.copyOfRange(mkBlob, 5506 offset, offset + len); 5507 5508 // now validate the decrypted master key against the checksum 5509 byte[] calculatedCk = makeKeyChecksum(algorithm, mk, ckSalt, rounds); 5510 if (Arrays.equals(calculatedCk, mkChecksum)) { 5511 ivSpec = new IvParameterSpec(IV); 5512 c.init(Cipher.DECRYPT_MODE, 5513 new SecretKeySpec(mk, "AES"), 5514 ivSpec); 5515 // Only if all of the above worked properly will 'result' be assigned 5516 result = new CipherInputStream(rawInStream, c); 5517 } else if (doLog) Slog.w(TAG, "Incorrect password"); 5518 } catch (InvalidAlgorithmParameterException e) { 5519 if (doLog) Slog.e(TAG, "Needed parameter spec unavailable!", e); 5520 } catch (BadPaddingException e) { 5521 // This case frequently occurs when the wrong password is used to decrypt 5522 // the master key. Use the identical "incorrect password" log text as is 5523 // used in the checksum failure log in order to avoid providing additional 5524 // information to an attacker. 5525 if (doLog) Slog.w(TAG, "Incorrect password"); 5526 } catch (IllegalBlockSizeException e) { 5527 if (doLog) Slog.w(TAG, "Invalid block size in master key"); 5528 } catch (NoSuchAlgorithmException e) { 5529 if (doLog) Slog.e(TAG, "Needed decryption algorithm unavailable!"); 5530 } catch (NoSuchPaddingException e) { 5531 if (doLog) Slog.e(TAG, "Needed padding mechanism unavailable!"); 5532 } catch (InvalidKeyException e) { 5533 if (doLog) Slog.w(TAG, "Illegal password; aborting"); 5534 } 5535 5536 return result; 5537 } 5538 5539 InputStream decodeAesHeaderAndInitialize(String encryptionName, boolean pbkdf2Fallback, 5540 InputStream rawInStream) { 5541 InputStream result = null; 5542 try { 5543 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) { 5544 5545 String userSaltHex = readHeaderLine(rawInStream); // 5 5546 byte[] userSalt = hexToByteArray(userSaltHex); 5547 5548 String ckSaltHex = readHeaderLine(rawInStream); // 6 5549 byte[] ckSalt = hexToByteArray(ckSaltHex); 5550 5551 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7 5552 String userIvHex = readHeaderLine(rawInStream); // 8 5553 5554 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9 5555 5556 // decrypt the master key blob 5557 result = attemptMasterKeyDecryption(PBKDF_CURRENT, userSalt, ckSalt, 5558 rounds, userIvHex, masterKeyBlobHex, rawInStream, false); 5559 if (result == null && pbkdf2Fallback) { 5560 result = attemptMasterKeyDecryption(PBKDF_FALLBACK, userSalt, ckSalt, 5561 rounds, userIvHex, masterKeyBlobHex, rawInStream, true); 5562 } 5563 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName); 5564 } catch (NumberFormatException e) { 5565 Slog.w(TAG, "Can't parse restore data header"); 5566 } catch (IOException e) { 5567 Slog.w(TAG, "Can't read input header"); 5568 } 5569 5570 return result; 5571 } 5572 5573 boolean restoreOneFile(InputStream instream, byte[] buffer) { 5574 FileMetadata info; 5575 try { 5576 info = readTarHeaders(instream); 5577 if (info != null) { 5578 if (MORE_DEBUG) { 5579 dumpFileMetadata(info); 5580 } 5581 5582 final String pkg = info.packageName; 5583 if (!pkg.equals(mAgentPackage)) { 5584 // okay, change in package; set up our various 5585 // bookkeeping if we haven't seen it yet 5586 if (!mPackagePolicies.containsKey(pkg)) { 5587 mPackagePolicies.put(pkg, RestorePolicy.IGNORE); 5588 } 5589 5590 // Clean up the previous agent relationship if necessary, 5591 // and let the observer know we're considering a new app. 5592 if (mAgent != null) { 5593 if (DEBUG) Slog.d(TAG, "Saw new package; finalizing old one"); 5594 // Now we're really done 5595 tearDownPipes(); 5596 tearDownAgent(mTargetApp); 5597 mTargetApp = null; 5598 mAgentPackage = null; 5599 } 5600 } 5601 5602 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) { 5603 mPackagePolicies.put(pkg, readAppManifest(info, instream)); 5604 mPackageInstallers.put(pkg, info.installerPackageName); 5605 // We've read only the manifest content itself at this point, 5606 // so consume the footer before looping around to the next 5607 // input file 5608 skipTarPadding(info.size, instream); 5609 sendOnRestorePackage(pkg); 5610 } else if (info.path.equals(BACKUP_METADATA_FILENAME)) { 5611 // Metadata blobs! 5612 readMetadata(info, instream); 5613 } else { 5614 // Non-manifest, so it's actual file data. Is this a package 5615 // we're ignoring? 5616 boolean okay = true; 5617 RestorePolicy policy = mPackagePolicies.get(pkg); 5618 switch (policy) { 5619 case IGNORE: 5620 okay = false; 5621 break; 5622 5623 case ACCEPT_IF_APK: 5624 // If we're in accept-if-apk state, then the first file we 5625 // see MUST be the apk. 5626 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) { 5627 if (DEBUG) Slog.d(TAG, "APK file; installing"); 5628 // Try to install the app. 5629 String installerName = mPackageInstallers.get(pkg); 5630 okay = installApk(info, installerName, instream); 5631 // good to go; promote to ACCEPT 5632 mPackagePolicies.put(pkg, (okay) 5633 ? RestorePolicy.ACCEPT 5634 : RestorePolicy.IGNORE); 5635 // At this point we've consumed this file entry 5636 // ourselves, so just strip the tar footer and 5637 // go on to the next file in the input stream 5638 skipTarPadding(info.size, instream); 5639 return true; 5640 } else { 5641 // File data before (or without) the apk. We can't 5642 // handle it coherently in this case so ignore it. 5643 mPackagePolicies.put(pkg, RestorePolicy.IGNORE); 5644 okay = false; 5645 } 5646 break; 5647 5648 case ACCEPT: 5649 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) { 5650 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT"); 5651 // we can take the data without the apk, so we 5652 // *want* to do so. skip the apk by declaring this 5653 // one file not-okay without changing the restore 5654 // policy for the package. 5655 okay = false; 5656 } 5657 break; 5658 5659 default: 5660 // Something has gone dreadfully wrong when determining 5661 // the restore policy from the manifest. Ignore the 5662 // rest of this package's data. 5663 Slog.e(TAG, "Invalid policy from manifest"); 5664 okay = false; 5665 mPackagePolicies.put(pkg, RestorePolicy.IGNORE); 5666 break; 5667 } 5668 5669 // The path needs to be canonical 5670 if (info.path.contains("..") || info.path.contains("//")) { 5671 if (MORE_DEBUG) { 5672 Slog.w(TAG, "Dropping invalid path " + info.path); 5673 } 5674 okay = false; 5675 } 5676 5677 // If the policy is satisfied, go ahead and set up to pipe the 5678 // data to the agent. 5679 if (DEBUG && okay && mAgent != null) { 5680 Slog.i(TAG, "Reusing existing agent instance"); 5681 } 5682 if (okay && mAgent == null) { 5683 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg); 5684 5685 try { 5686 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0); 5687 5688 // If we haven't sent any data to this app yet, we probably 5689 // need to clear it first. Check that. 5690 if (!mClearedPackages.contains(pkg)) { 5691 // apps with their own backup agents are 5692 // responsible for coherently managing a full 5693 // restore. 5694 if (mTargetApp.backupAgentName == null) { 5695 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore"); 5696 clearApplicationDataSynchronous(pkg); 5697 } else { 5698 if (DEBUG) Slog.d(TAG, "backup agent (" 5699 + mTargetApp.backupAgentName + ") => no clear"); 5700 } 5701 mClearedPackages.add(pkg); 5702 } else { 5703 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required"); 5704 } 5705 5706 // All set; now set up the IPC and launch the agent 5707 setUpPipes(); 5708 mAgent = bindToAgentSynchronous(mTargetApp, 5709 IApplicationThread.BACKUP_MODE_RESTORE_FULL); 5710 mAgentPackage = pkg; 5711 } catch (IOException e) { 5712 // fall through to error handling 5713 } catch (NameNotFoundException e) { 5714 // fall through to error handling 5715 } 5716 5717 if (mAgent == null) { 5718 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg); 5719 okay = false; 5720 tearDownPipes(); 5721 mPackagePolicies.put(pkg, RestorePolicy.IGNORE); 5722 } 5723 } 5724 5725 // Sanity check: make sure we never give data to the wrong app. This 5726 // should never happen but a little paranoia here won't go amiss. 5727 if (okay && !pkg.equals(mAgentPackage)) { 5728 Slog.e(TAG, "Restoring data for " + pkg 5729 + " but agent is for " + mAgentPackage); 5730 okay = false; 5731 } 5732 5733 // At this point we have an agent ready to handle the full 5734 // restore data as well as a pipe for sending data to 5735 // that agent. Tell the agent to start reading from the 5736 // pipe. 5737 if (okay) { 5738 boolean agentSuccess = true; 5739 long toCopy = info.size; 5740 final int token = generateToken(); 5741 try { 5742 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null); 5743 if (info.domain.equals(FullBackup.OBB_TREE_TOKEN)) { 5744 if (DEBUG) Slog.d(TAG, "Restoring OBB file for " + pkg 5745 + " : " + info.path); 5746 mObbConnection.restoreObbFile(pkg, mPipes[0], 5747 info.size, info.type, info.path, info.mode, 5748 info.mtime, token, mBackupManagerBinder); 5749 } else { 5750 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file " 5751 + info.path); 5752 // fire up the app's agent listening on the socket. If 5753 // the agent is running in the system process we can't 5754 // just invoke it asynchronously, so we provide a thread 5755 // for it here. 5756 if (mTargetApp.processName.equals("system")) { 5757 Slog.d(TAG, "system process agent - spinning a thread"); 5758 RestoreFileRunnable runner = new RestoreFileRunnable( 5759 mAgent, info, mPipes[0], token); 5760 new Thread(runner, "restore-sys-runner").start(); 5761 } else { 5762 mAgent.doRestoreFile(mPipes[0], info.size, info.type, 5763 info.domain, info.path, info.mode, info.mtime, 5764 token, mBackupManagerBinder); 5765 } 5766 } 5767 } catch (IOException e) { 5768 // couldn't dup the socket for a process-local restore 5769 Slog.d(TAG, "Couldn't establish restore"); 5770 agentSuccess = false; 5771 okay = false; 5772 } catch (RemoteException e) { 5773 // whoops, remote entity went away. We'll eat the content 5774 // ourselves, then, and not copy it over. 5775 Slog.e(TAG, "Agent crashed during full restore"); 5776 agentSuccess = false; 5777 okay = false; 5778 } 5779 5780 // Copy over the data if the agent is still good 5781 if (okay) { 5782 boolean pipeOkay = true; 5783 FileOutputStream pipe = new FileOutputStream( 5784 mPipes[1].getFileDescriptor()); 5785 while (toCopy > 0) { 5786 int toRead = (toCopy > buffer.length) 5787 ? buffer.length : (int)toCopy; 5788 int nRead = instream.read(buffer, 0, toRead); 5789 if (nRead >= 0) mBytes += nRead; 5790 if (nRead <= 0) break; 5791 toCopy -= nRead; 5792 5793 // send it to the output pipe as long as things 5794 // are still good 5795 if (pipeOkay) { 5796 try { 5797 pipe.write(buffer, 0, nRead); 5798 } catch (IOException e) { 5799 Slog.e(TAG, "Failed to write to restore pipe", e); 5800 pipeOkay = false; 5801 } 5802 } 5803 } 5804 5805 // done sending that file! Now we just need to consume 5806 // the delta from info.size to the end of block. 5807 skipTarPadding(info.size, instream); 5808 5809 // and now that we've sent it all, wait for the remote 5810 // side to acknowledge receipt 5811 agentSuccess = waitUntilOperationComplete(token); 5812 } 5813 5814 // okay, if the remote end failed at any point, deal with 5815 // it by ignoring the rest of the restore on it 5816 if (!agentSuccess) { 5817 mBackupHandler.removeMessages(MSG_TIMEOUT); 5818 tearDownPipes(); 5819 tearDownAgent(mTargetApp); 5820 mAgent = null; 5821 mPackagePolicies.put(pkg, RestorePolicy.IGNORE); 5822 } 5823 } 5824 5825 // Problems setting up the agent communication, or an already- 5826 // ignored package: skip to the next tar stream entry by 5827 // reading and discarding this file. 5828 if (!okay) { 5829 if (DEBUG) Slog.d(TAG, "[discarding file content]"); 5830 long bytesToConsume = (info.size + 511) & ~511; 5831 while (bytesToConsume > 0) { 5832 int toRead = (bytesToConsume > buffer.length) 5833 ? buffer.length : (int)bytesToConsume; 5834 long nRead = instream.read(buffer, 0, toRead); 5835 if (nRead >= 0) mBytes += nRead; 5836 if (nRead <= 0) break; 5837 bytesToConsume -= nRead; 5838 } 5839 } 5840 } 5841 } 5842 } catch (IOException e) { 5843 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e); 5844 // treat as EOF 5845 info = null; 5846 } 5847 5848 return (info != null); 5849 } 5850 5851 void setUpPipes() throws IOException { 5852 mPipes = ParcelFileDescriptor.createPipe(); 5853 } 5854 5855 void tearDownPipes() { 5856 if (mPipes != null) { 5857 try { 5858 mPipes[0].close(); 5859 mPipes[0] = null; 5860 mPipes[1].close(); 5861 mPipes[1] = null; 5862 } catch (IOException e) { 5863 Slog.w(TAG, "Couldn't close agent pipes", e); 5864 } 5865 mPipes = null; 5866 } 5867 } 5868 5869 void tearDownAgent(ApplicationInfo app) { 5870 if (mAgent != null) { 5871 try { 5872 // unbind and tidy up even on timeout or failure, just in case 5873 mActivityManager.unbindBackupAgent(app); 5874 5875 // The agent was running with a stub Application object, so shut it down. 5876 // !!! We hardcode the confirmation UI's package name here rather than use a 5877 // manifest flag! TODO something less direct. 5878 if (app.uid != Process.SYSTEM_UID 5879 && !app.packageName.equals("com.android.backupconfirm")) { 5880 if (DEBUG) Slog.d(TAG, "Killing host process"); 5881 mActivityManager.killApplicationProcess(app.processName, app.uid); 5882 } else { 5883 if (DEBUG) Slog.d(TAG, "Not killing after full restore"); 5884 } 5885 } catch (RemoteException e) { 5886 Slog.d(TAG, "Lost app trying to shut down"); 5887 } 5888 mAgent = null; 5889 } 5890 } 5891 5892 class RestoreInstallObserver extends IPackageInstallObserver.Stub { 5893 final AtomicBoolean mDone = new AtomicBoolean(); 5894 String mPackageName; 5895 int mResult; 5896 5897 public void reset() { 5898 synchronized (mDone) { 5899 mDone.set(false); 5900 } 5901 } 5902 5903 public void waitForCompletion() { 5904 synchronized (mDone) { 5905 while (mDone.get() == false) { 5906 try { 5907 mDone.wait(); 5908 } catch (InterruptedException e) { } 5909 } 5910 } 5911 } 5912 5913 int getResult() { 5914 return mResult; 5915 } 5916 5917 @Override 5918 public void packageInstalled(String packageName, int returnCode) 5919 throws RemoteException { 5920 synchronized (mDone) { 5921 mResult = returnCode; 5922 mPackageName = packageName; 5923 mDone.set(true); 5924 mDone.notifyAll(); 5925 } 5926 } 5927 } 5928 5929 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub { 5930 final AtomicBoolean mDone = new AtomicBoolean(); 5931 int mResult; 5932 5933 public void reset() { 5934 synchronized (mDone) { 5935 mDone.set(false); 5936 } 5937 } 5938 5939 public void waitForCompletion() { 5940 synchronized (mDone) { 5941 while (mDone.get() == false) { 5942 try { 5943 mDone.wait(); 5944 } catch (InterruptedException e) { } 5945 } 5946 } 5947 } 5948 5949 @Override 5950 public void packageDeleted(String packageName, int returnCode) throws RemoteException { 5951 synchronized (mDone) { 5952 mResult = returnCode; 5953 mDone.set(true); 5954 mDone.notifyAll(); 5955 } 5956 } 5957 } 5958 5959 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver(); 5960 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver(); 5961 5962 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) { 5963 boolean okay = true; 5964 5965 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName); 5966 5967 // The file content is an .apk file. Copy it out to a staging location and 5968 // attempt to install it. 5969 File apkFile = new File(mDataDir, info.packageName); 5970 try { 5971 FileOutputStream apkStream = new FileOutputStream(apkFile); 5972 byte[] buffer = new byte[32 * 1024]; 5973 long size = info.size; 5974 while (size > 0) { 5975 long toRead = (buffer.length < size) ? buffer.length : size; 5976 int didRead = instream.read(buffer, 0, (int)toRead); 5977 if (didRead >= 0) mBytes += didRead; 5978 apkStream.write(buffer, 0, didRead); 5979 size -= didRead; 5980 } 5981 apkStream.close(); 5982 5983 // make sure the installer can read it 5984 apkFile.setReadable(true, false); 5985 5986 // Now install it 5987 Uri packageUri = Uri.fromFile(apkFile); 5988 mInstallObserver.reset(); 5989 mPackageManager.installPackage(packageUri, mInstallObserver, 5990 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB, 5991 installerPackage); 5992 mInstallObserver.waitForCompletion(); 5993 5994 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) { 5995 // The only time we continue to accept install of data even if the 5996 // apk install failed is if we had already determined that we could 5997 // accept the data regardless. 5998 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) { 5999 okay = false; 6000 } 6001 } else { 6002 // Okay, the install succeeded. Make sure it was the right app. 6003 boolean uninstall = false; 6004 if (!mInstallObserver.mPackageName.equals(info.packageName)) { 6005 Slog.w(TAG, "Restore stream claimed to include apk for " 6006 + info.packageName + " but apk was really " 6007 + mInstallObserver.mPackageName); 6008 // delete the package we just put in place; it might be fraudulent 6009 okay = false; 6010 uninstall = true; 6011 } else { 6012 try { 6013 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName, 6014 PackageManager.GET_SIGNATURES); 6015 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) { 6016 Slog.w(TAG, "Restore stream contains apk of package " 6017 + info.packageName + " but it disallows backup/restore"); 6018 okay = false; 6019 } else { 6020 // So far so good -- do the signatures match the manifest? 6021 Signature[] sigs = mManifestSignatures.get(info.packageName); 6022 if (signaturesMatch(sigs, pkg)) { 6023 // If this is a system-uid app without a declared backup agent, 6024 // don't restore any of the file data. 6025 if ((pkg.applicationInfo.uid < Process.FIRST_APPLICATION_UID) 6026 && (pkg.applicationInfo.backupAgentName == null)) { 6027 Slog.w(TAG, "Installed app " + info.packageName 6028 + " has restricted uid and no agent"); 6029 okay = false; 6030 } 6031 } else { 6032 Slog.w(TAG, "Installed app " + info.packageName 6033 + " signatures do not match restore manifest"); 6034 okay = false; 6035 uninstall = true; 6036 } 6037 } 6038 } catch (NameNotFoundException e) { 6039 Slog.w(TAG, "Install of package " + info.packageName 6040 + " succeeded but now not found"); 6041 okay = false; 6042 } 6043 } 6044 6045 // If we're not okay at this point, we need to delete the package 6046 // that we just installed. 6047 if (uninstall) { 6048 mDeleteObserver.reset(); 6049 mPackageManager.deletePackage(mInstallObserver.mPackageName, 6050 mDeleteObserver, 0); 6051 mDeleteObserver.waitForCompletion(); 6052 } 6053 } 6054 } catch (IOException e) { 6055 Slog.e(TAG, "Unable to transcribe restored apk for install"); 6056 okay = false; 6057 } finally { 6058 apkFile.delete(); 6059 } 6060 6061 return okay; 6062 } 6063 6064 // Given an actual file content size, consume the post-content padding mandated 6065 // by the tar format. 6066 void skipTarPadding(long size, InputStream instream) throws IOException { 6067 long partial = (size + 512) % 512; 6068 if (partial > 0) { 6069 final int needed = 512 - (int)partial; 6070 byte[] buffer = new byte[needed]; 6071 if (readExactly(instream, buffer, 0, needed) == needed) { 6072 mBytes += needed; 6073 } else throw new IOException("Unexpected EOF in padding"); 6074 } 6075 } 6076 6077 // Read a widget metadata file, returning the restored blob 6078 void readMetadata(FileMetadata info, InputStream instream) throws IOException { 6079 // Fail on suspiciously large widget dump files 6080 if (info.size > 64 * 1024) { 6081 throw new IOException("Metadata too big; corrupt? size=" + info.size); 6082 } 6083 6084 byte[] buffer = new byte[(int) info.size]; 6085 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) { 6086 mBytes += info.size; 6087 } else throw new IOException("Unexpected EOF in widget data"); 6088 6089 String[] str = new String[1]; 6090 int offset = extractLine(buffer, 0, str); 6091 int version = Integer.parseInt(str[0]); 6092 if (version == BACKUP_MANIFEST_VERSION) { 6093 offset = extractLine(buffer, offset, str); 6094 final String pkg = str[0]; 6095 if (info.packageName.equals(pkg)) { 6096 // Data checks out -- the rest of the buffer is a concatenation of 6097 // binary blobs as described in the comment at writeAppWidgetData() 6098 ByteArrayInputStream bin = new ByteArrayInputStream(buffer, 6099 offset, buffer.length - offset); 6100 DataInputStream in = new DataInputStream(bin); 6101 while (bin.available() > 0) { 6102 int token = in.readInt(); 6103 int size = in.readInt(); 6104 if (size > 64 * 1024) { 6105 throw new IOException("Datum " 6106 + Integer.toHexString(token) 6107 + " too big; corrupt? size=" + info.size); 6108 } 6109 switch (token) { 6110 case BACKUP_WIDGET_METADATA_TOKEN: 6111 { 6112 if (MORE_DEBUG) { 6113 Slog.i(TAG, "Got widget metadata for " + info.packageName); 6114 } 6115 mWidgetData = new byte[size]; 6116 in.read(mWidgetData); 6117 break; 6118 } 6119 default: 6120 { 6121 if (DEBUG) { 6122 Slog.i(TAG, "Ignoring metadata blob " 6123 + Integer.toHexString(token) 6124 + " for " + info.packageName); 6125 } 6126 in.skipBytes(size); 6127 break; 6128 } 6129 } 6130 } 6131 } else { 6132 Slog.w(TAG, "Metadata mismatch: package " + info.packageName 6133 + " but widget data for " + pkg); 6134 } 6135 } else { 6136 Slog.w(TAG, "Unsupported metadata version " + version); 6137 } 6138 } 6139 6140 // Returns a policy constant; takes a buffer arg to reduce memory churn 6141 RestorePolicy readAppManifest(FileMetadata info, InputStream instream) 6142 throws IOException { 6143 // Fail on suspiciously large manifest files 6144 if (info.size > 64 * 1024) { 6145 throw new IOException("Restore manifest too big; corrupt? size=" + info.size); 6146 } 6147 6148 byte[] buffer = new byte[(int) info.size]; 6149 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) { 6150 mBytes += info.size; 6151 } else throw new IOException("Unexpected EOF in manifest"); 6152 6153 RestorePolicy policy = RestorePolicy.IGNORE; 6154 String[] str = new String[1]; 6155 int offset = 0; 6156 6157 try { 6158 offset = extractLine(buffer, offset, str); 6159 int version = Integer.parseInt(str[0]); 6160 if (version == BACKUP_MANIFEST_VERSION) { 6161 offset = extractLine(buffer, offset, str); 6162 String manifestPackage = str[0]; 6163 // TODO: handle <original-package> 6164 if (manifestPackage.equals(info.packageName)) { 6165 offset = extractLine(buffer, offset, str); 6166 version = Integer.parseInt(str[0]); // app version 6167 offset = extractLine(buffer, offset, str); 6168 int platformVersion = Integer.parseInt(str[0]); 6169 offset = extractLine(buffer, offset, str); 6170 info.installerPackageName = (str[0].length() > 0) ? str[0] : null; 6171 offset = extractLine(buffer, offset, str); 6172 boolean hasApk = str[0].equals("1"); 6173 offset = extractLine(buffer, offset, str); 6174 int numSigs = Integer.parseInt(str[0]); 6175 if (numSigs > 0) { 6176 Signature[] sigs = new Signature[numSigs]; 6177 for (int i = 0; i < numSigs; i++) { 6178 offset = extractLine(buffer, offset, str); 6179 sigs[i] = new Signature(str[0]); 6180 } 6181 mManifestSignatures.put(info.packageName, sigs); 6182 6183 // Okay, got the manifest info we need... 6184 try { 6185 PackageInfo pkgInfo = mPackageManager.getPackageInfo( 6186 info.packageName, PackageManager.GET_SIGNATURES); 6187 // Fall through to IGNORE if the app explicitly disallows backup 6188 final int flags = pkgInfo.applicationInfo.flags; 6189 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) { 6190 // Restore system-uid-space packages only if they have 6191 // defined a custom backup agent 6192 if ((pkgInfo.applicationInfo.uid >= Process.FIRST_APPLICATION_UID) 6193 || (pkgInfo.applicationInfo.backupAgentName != null)) { 6194 // Verify signatures against any installed version; if they 6195 // don't match, then we fall though and ignore the data. The 6196 // signatureMatch() method explicitly ignores the signature 6197 // check for packages installed on the system partition, because 6198 // such packages are signed with the platform cert instead of 6199 // the app developer's cert, so they're different on every 6200 // device. 6201 if (signaturesMatch(sigs, pkgInfo)) { 6202 if (pkgInfo.versionCode >= version) { 6203 Slog.i(TAG, "Sig + version match; taking data"); 6204 policy = RestorePolicy.ACCEPT; 6205 } else { 6206 // The data is from a newer version of the app than 6207 // is presently installed. That means we can only 6208 // use it if the matching apk is also supplied. 6209 Slog.d(TAG, "Data version " + version 6210 + " is newer than installed version " 6211 + pkgInfo.versionCode + " - requiring apk"); 6212 policy = RestorePolicy.ACCEPT_IF_APK; 6213 } 6214 } else { 6215 Slog.w(TAG, "Restore manifest signatures do not match " 6216 + "installed application for " + info.packageName); 6217 } 6218 } else { 6219 Slog.w(TAG, "Package " + info.packageName 6220 + " is system level with no agent"); 6221 } 6222 } else { 6223 if (DEBUG) Slog.i(TAG, "Restore manifest from " 6224 + info.packageName + " but allowBackup=false"); 6225 } 6226 } catch (NameNotFoundException e) { 6227 // Okay, the target app isn't installed. We can process 6228 // the restore properly only if the dataset provides the 6229 // apk file and we can successfully install it. 6230 if (DEBUG) Slog.i(TAG, "Package " + info.packageName 6231 + " not installed; requiring apk in dataset"); 6232 policy = RestorePolicy.ACCEPT_IF_APK; 6233 } 6234 6235 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) { 6236 Slog.i(TAG, "Cannot restore package " + info.packageName 6237 + " without the matching .apk"); 6238 } 6239 } else { 6240 Slog.i(TAG, "Missing signature on backed-up package " 6241 + info.packageName); 6242 } 6243 } else { 6244 Slog.i(TAG, "Expected package " + info.packageName 6245 + " but restore manifest claims " + manifestPackage); 6246 } 6247 } else { 6248 Slog.i(TAG, "Unknown restore manifest version " + version 6249 + " for package " + info.packageName); 6250 } 6251 } catch (NumberFormatException e) { 6252 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName); 6253 } catch (IllegalArgumentException e) { 6254 Slog.w(TAG, e.getMessage()); 6255 } 6256 6257 return policy; 6258 } 6259 6260 // Builds a line from a byte buffer starting at 'offset', and returns 6261 // the index of the next unconsumed data in the buffer. 6262 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException { 6263 final int end = buffer.length; 6264 if (offset >= end) throw new IOException("Incomplete data"); 6265 6266 int pos; 6267 for (pos = offset; pos < end; pos++) { 6268 byte c = buffer[pos]; 6269 // at LF we declare end of line, and return the next char as the 6270 // starting point for the next time through 6271 if (c == '\n') { 6272 break; 6273 } 6274 } 6275 outStr[0] = new String(buffer, offset, pos - offset); 6276 pos++; // may be pointing an extra byte past the end but that's okay 6277 return pos; 6278 } 6279 6280 void dumpFileMetadata(FileMetadata info) { 6281 if (DEBUG) { 6282 StringBuilder b = new StringBuilder(128); 6283 6284 // mode string 6285 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-'); 6286 b.append(((info.mode & 0400) != 0) ? 'r' : '-'); 6287 b.append(((info.mode & 0200) != 0) ? 'w' : '-'); 6288 b.append(((info.mode & 0100) != 0) ? 'x' : '-'); 6289 b.append(((info.mode & 0040) != 0) ? 'r' : '-'); 6290 b.append(((info.mode & 0020) != 0) ? 'w' : '-'); 6291 b.append(((info.mode & 0010) != 0) ? 'x' : '-'); 6292 b.append(((info.mode & 0004) != 0) ? 'r' : '-'); 6293 b.append(((info.mode & 0002) != 0) ? 'w' : '-'); 6294 b.append(((info.mode & 0001) != 0) ? 'x' : '-'); 6295 b.append(String.format(" %9d ", info.size)); 6296 6297 Date stamp = new Date(info.mtime); 6298 b.append(new SimpleDateFormat("MMM dd HH:mm:ss ").format(stamp)); 6299 6300 b.append(info.packageName); 6301 b.append(" :: "); 6302 b.append(info.domain); 6303 b.append(" :: "); 6304 b.append(info.path); 6305 6306 Slog.i(TAG, b.toString()); 6307 } 6308 } 6309 // Consume a tar file header block [sequence] and accumulate the relevant metadata 6310 FileMetadata readTarHeaders(InputStream instream) throws IOException { 6311 byte[] block = new byte[512]; 6312 FileMetadata info = null; 6313 6314 boolean gotHeader = readTarHeader(instream, block); 6315 if (gotHeader) { 6316 try { 6317 // okay, presume we're okay, and extract the various metadata 6318 info = new FileMetadata(); 6319 info.size = extractRadix(block, 124, 12, 8); 6320 info.mtime = extractRadix(block, 136, 12, 8); 6321 info.mode = extractRadix(block, 100, 8, 8); 6322 6323 info.path = extractString(block, 345, 155); // prefix 6324 String path = extractString(block, 0, 100); 6325 if (path.length() > 0) { 6326 if (info.path.length() > 0) info.path += '/'; 6327 info.path += path; 6328 } 6329 6330 // tar link indicator field: 1 byte at offset 156 in the header. 6331 int typeChar = block[156]; 6332 if (typeChar == 'x') { 6333 // pax extended header, so we need to read that 6334 gotHeader = readPaxExtendedHeader(instream, info); 6335 if (gotHeader) { 6336 // and after a pax extended header comes another real header -- read 6337 // that to find the real file type 6338 gotHeader = readTarHeader(instream, block); 6339 } 6340 if (!gotHeader) throw new IOException("Bad or missing pax header"); 6341 6342 typeChar = block[156]; 6343 } 6344 6345 switch (typeChar) { 6346 case '0': info.type = BackupAgent.TYPE_FILE; break; 6347 case '5': { 6348 info.type = BackupAgent.TYPE_DIRECTORY; 6349 if (info.size != 0) { 6350 Slog.w(TAG, "Directory entry with nonzero size in header"); 6351 info.size = 0; 6352 } 6353 break; 6354 } 6355 case 0: { 6356 // presume EOF 6357 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info); 6358 return null; 6359 } 6360 default: { 6361 Slog.e(TAG, "Unknown tar entity type: " + typeChar); 6362 throw new IOException("Unknown entity type " + typeChar); 6363 } 6364 } 6365 6366 // Parse out the path 6367 // 6368 // first: apps/shared/unrecognized 6369 if (FullBackup.SHARED_PREFIX.regionMatches(0, 6370 info.path, 0, FullBackup.SHARED_PREFIX.length())) { 6371 // File in shared storage. !!! TODO: implement this. 6372 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length()); 6373 info.packageName = SHARED_BACKUP_AGENT_PACKAGE; 6374 info.domain = FullBackup.SHARED_STORAGE_TOKEN; 6375 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path); 6376 } else if (FullBackup.APPS_PREFIX.regionMatches(0, 6377 info.path, 0, FullBackup.APPS_PREFIX.length())) { 6378 // App content! Parse out the package name and domain 6379 6380 // strip the apps/ prefix 6381 info.path = info.path.substring(FullBackup.APPS_PREFIX.length()); 6382 6383 // extract the package name 6384 int slash = info.path.indexOf('/'); 6385 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path); 6386 info.packageName = info.path.substring(0, slash); 6387 info.path = info.path.substring(slash+1); 6388 6389 // if it's a manifest we're done, otherwise parse out the domains 6390 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) { 6391 slash = info.path.indexOf('/'); 6392 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path); 6393 info.domain = info.path.substring(0, slash); 6394 info.path = info.path.substring(slash + 1); 6395 } 6396 } 6397 } catch (IOException e) { 6398 if (DEBUG) { 6399 Slog.e(TAG, "Parse error in header: " + e.getMessage()); 6400 HEXLOG(block); 6401 } 6402 throw e; 6403 } 6404 } 6405 return info; 6406 } 6407 6408 private void HEXLOG(byte[] block) { 6409 int offset = 0; 6410 int todo = block.length; 6411 StringBuilder buf = new StringBuilder(64); 6412 while (todo > 0) { 6413 buf.append(String.format("%04x ", offset)); 6414 int numThisLine = (todo > 16) ? 16 : todo; 6415 for (int i = 0; i < numThisLine; i++) { 6416 buf.append(String.format("%02x ", block[offset+i])); 6417 } 6418 Slog.i("hexdump", buf.toString()); 6419 buf.setLength(0); 6420 todo -= numThisLine; 6421 offset += numThisLine; 6422 } 6423 } 6424 6425 // Read exactly the given number of bytes into a buffer at the stated offset. 6426 // Returns false if EOF is encountered before the requested number of bytes 6427 // could be read. 6428 int readExactly(InputStream in, byte[] buffer, int offset, int size) 6429 throws IOException { 6430 if (size <= 0) throw new IllegalArgumentException("size must be > 0"); 6431 6432 int soFar = 0; 6433 while (soFar < size) { 6434 int nRead = in.read(buffer, offset + soFar, size - soFar); 6435 if (nRead <= 0) { 6436 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar); 6437 break; 6438 } 6439 soFar += nRead; 6440 } 6441 return soFar; 6442 } 6443 6444 boolean readTarHeader(InputStream instream, byte[] block) throws IOException { 6445 final int got = readExactly(instream, block, 0, 512); 6446 if (got == 0) return false; // Clean EOF 6447 if (got < 512) throw new IOException("Unable to read full block header"); 6448 mBytes += 512; 6449 return true; 6450 } 6451 6452 // overwrites 'info' fields based on the pax extended header 6453 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info) 6454 throws IOException { 6455 // We should never see a pax extended header larger than this 6456 if (info.size > 32*1024) { 6457 Slog.w(TAG, "Suspiciously large pax header size " + info.size 6458 + " - aborting"); 6459 throw new IOException("Sanity failure: pax header size " + info.size); 6460 } 6461 6462 // read whole blocks, not just the content size 6463 int numBlocks = (int)((info.size + 511) >> 9); 6464 byte[] data = new byte[numBlocks * 512]; 6465 if (readExactly(instream, data, 0, data.length) < data.length) { 6466 throw new IOException("Unable to read full pax header"); 6467 } 6468 mBytes += data.length; 6469 6470 final int contentSize = (int) info.size; 6471 int offset = 0; 6472 do { 6473 // extract the line at 'offset' 6474 int eol = offset+1; 6475 while (eol < contentSize && data[eol] != ' ') eol++; 6476 if (eol >= contentSize) { 6477 // error: we just hit EOD looking for the end of the size field 6478 throw new IOException("Invalid pax data"); 6479 } 6480 // eol points to the space between the count and the key 6481 int linelen = (int) extractRadix(data, offset, eol - offset, 10); 6482 int key = eol + 1; // start of key=value 6483 eol = offset + linelen - 1; // trailing LF 6484 int value; 6485 for (value = key+1; data[value] != '=' && value <= eol; value++); 6486 if (value > eol) { 6487 throw new IOException("Invalid pax declaration"); 6488 } 6489 6490 // pax requires that key/value strings be in UTF-8 6491 String keyStr = new String(data, key, value-key, "UTF-8"); 6492 // -1 to strip the trailing LF 6493 String valStr = new String(data, value+1, eol-value-1, "UTF-8"); 6494 6495 if ("path".equals(keyStr)) { 6496 info.path = valStr; 6497 } else if ("size".equals(keyStr)) { 6498 info.size = Long.parseLong(valStr); 6499 } else { 6500 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key); 6501 } 6502 6503 offset += linelen; 6504 } while (offset < contentSize); 6505 6506 return true; 6507 } 6508 6509 long extractRadix(byte[] data, int offset, int maxChars, int radix) 6510 throws IOException { 6511 long value = 0; 6512 final int end = offset + maxChars; 6513 for (int i = offset; i < end; i++) { 6514 final byte b = data[i]; 6515 // Numeric fields in tar can terminate with either NUL or SPC 6516 if (b == 0 || b == ' ') break; 6517 if (b < '0' || b > ('0' + radix - 1)) { 6518 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix); 6519 } 6520 value = radix * value + (b - '0'); 6521 } 6522 return value; 6523 } 6524 6525 String extractString(byte[] data, int offset, int maxChars) throws IOException { 6526 final int end = offset + maxChars; 6527 int eos = offset; 6528 // tar string fields terminate early with a NUL 6529 while (eos < end && data[eos] != 0) eos++; 6530 return new String(data, offset, eos-offset, "US-ASCII"); 6531 } 6532 6533 void sendStartRestore() { 6534 if (mObserver != null) { 6535 try { 6536 mObserver.onStartRestore(); 6537 } catch (RemoteException e) { 6538 Slog.w(TAG, "full restore observer went away: startRestore"); 6539 mObserver = null; 6540 } 6541 } 6542 } 6543 6544 void sendOnRestorePackage(String name) { 6545 if (mObserver != null) { 6546 try { 6547 // TODO: use a more user-friendly name string 6548 mObserver.onRestorePackage(name); 6549 } catch (RemoteException e) { 6550 Slog.w(TAG, "full restore observer went away: restorePackage"); 6551 mObserver = null; 6552 } 6553 } 6554 } 6555 6556 void sendEndRestore() { 6557 if (mObserver != null) { 6558 try { 6559 mObserver.onEndRestore(); 6560 } catch (RemoteException e) { 6561 Slog.w(TAG, "full restore observer went away: endRestore"); 6562 mObserver = null; 6563 } 6564 } 6565 } 6566 } 6567 6568 // ----- Restore handling ----- 6569 6570 // new style: we only store the SHA-1 hashes of each sig, not the full block 6571 static boolean signaturesMatch(ArrayList<byte[]> storedSigHashes, PackageInfo target) { 6572 if (target == null) { 6573 return false; 6574 } 6575 6576 // If the target resides on the system partition, we allow it to restore 6577 // data from the like-named package in a restore set even if the signatures 6578 // do not match. (Unlike general applications, those flashed to the system 6579 // partition will be signed with the device's platform certificate, so on 6580 // different phones the same system app will have different signatures.) 6581 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 6582 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check"); 6583 return true; 6584 } 6585 6586 // Allow unsigned apps, but not signed on one device and unsigned on the other 6587 // !!! TODO: is this the right policy? 6588 Signature[] deviceSigs = target.signatures; 6589 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigHashes 6590 + " device=" + deviceSigs); 6591 if ((storedSigHashes == null || storedSigHashes.size() == 0) 6592 && (deviceSigs == null || deviceSigs.length == 0)) { 6593 return true; 6594 } 6595 if (storedSigHashes == null || deviceSigs == null) { 6596 return false; 6597 } 6598 6599 // !!! TODO: this demands that every stored signature match one 6600 // that is present on device, and does not demand the converse. 6601 // Is this this right policy? 6602 final int nStored = storedSigHashes.size(); 6603 final int nDevice = deviceSigs.length; 6604 6605 // hash each on-device signature 6606 ArrayList<byte[]> deviceHashes = new ArrayList<byte[]>(nDevice); 6607 for (int i = 0; i < nDevice; i++) { 6608 deviceHashes.add(hashSignature(deviceSigs[i])); 6609 } 6610 6611 // now ensure that each stored sig (hash) matches an on-device sig (hash) 6612 for (int n = 0; n < nStored; n++) { 6613 boolean match = false; 6614 final byte[] storedHash = storedSigHashes.get(n); 6615 for (int i = 0; i < nDevice; i++) { 6616 if (Arrays.equals(storedHash, deviceHashes.get(i))) { 6617 match = true; 6618 break; 6619 } 6620 } 6621 // match is false when no on-device sig matched one of the stored ones 6622 if (!match) { 6623 return false; 6624 } 6625 } 6626 6627 return true; 6628 } 6629 6630 static byte[] hashSignature(Signature sig) { 6631 try { 6632 MessageDigest digest = MessageDigest.getInstance("SHA-256"); 6633 digest.update(sig.toByteArray()); 6634 return digest.digest(); 6635 } catch (NoSuchAlgorithmException e) { 6636 Slog.w(TAG, "No SHA-256 algorithm found!"); 6637 } 6638 return null; 6639 } 6640 6641 // Old style: directly match the stored vs on device signature blocks 6642 static boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) { 6643 if (target == null) { 6644 return false; 6645 } 6646 6647 // If the target resides on the system partition, we allow it to restore 6648 // data from the like-named package in a restore set even if the signatures 6649 // do not match. (Unlike general applications, those flashed to the system 6650 // partition will be signed with the device's platform certificate, so on 6651 // different phones the same system app will have different signatures.) 6652 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 6653 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check"); 6654 return true; 6655 } 6656 6657 // Allow unsigned apps, but not signed on one device and unsigned on the other 6658 // !!! TODO: is this the right policy? 6659 Signature[] deviceSigs = target.signatures; 6660 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs 6661 + " device=" + deviceSigs); 6662 if ((storedSigs == null || storedSigs.length == 0) 6663 && (deviceSigs == null || deviceSigs.length == 0)) { 6664 return true; 6665 } 6666 if (storedSigs == null || deviceSigs == null) { 6667 return false; 6668 } 6669 6670 // !!! TODO: this demands that every stored signature match one 6671 // that is present on device, and does not demand the converse. 6672 // Is this this right policy? 6673 int nStored = storedSigs.length; 6674 int nDevice = deviceSigs.length; 6675 6676 for (int i=0; i < nStored; i++) { 6677 boolean match = false; 6678 for (int j=0; j < nDevice; j++) { 6679 if (storedSigs[i].equals(deviceSigs[j])) { 6680 match = true; 6681 break; 6682 } 6683 } 6684 if (!match) { 6685 return false; 6686 } 6687 } 6688 return true; 6689 } 6690 6691 // Used by both incremental and full restore 6692 void restoreWidgetData(String packageName, byte[] widgetData) { 6693 // Apply the restored widget state and generate the ID update for the app 6694 AppWidgetBackupBridge.restoreWidgetState(packageName, widgetData, UserHandle.USER_OWNER); 6695 } 6696 6697 // ***************************** 6698 // NEW UNIFIED RESTORE IMPLEMENTATION 6699 // ***************************** 6700 6701 // states of the unified-restore state machine 6702 enum UnifiedRestoreState { 6703 INITIAL, 6704 RUNNING_QUEUE, 6705 RESTORE_KEYVALUE, 6706 RESTORE_FULL, 6707 RESTORE_FINISHED, 6708 FINAL 6709 } 6710 6711 class PerformUnifiedRestoreTask implements BackupRestoreTask { 6712 // Transport we're working with to do the restore 6713 private IBackupTransport mTransport; 6714 6715 // Where per-transport saved state goes 6716 File mStateDir; 6717 6718 // Restore observer; may be null 6719 private IRestoreObserver mObserver; 6720 6721 // Token identifying the dataset to the transport 6722 private long mToken; 6723 6724 // When this is a restore-during-install, this is the token identifying the 6725 // operation to the Package Manager, and we must ensure that we let it know 6726 // when we're finished. 6727 private int mPmToken; 6728 6729 // Is this a whole-system restore, i.e. are we establishing a new ancestral 6730 // dataset to base future restore-at-install operations from? 6731 private boolean mIsSystemRestore; 6732 6733 // If this is a single-package restore, what package are we interested in? 6734 private PackageInfo mTargetPackage; 6735 6736 // In all cases, the calculated list of packages that we are trying to restore 6737 private List<PackageInfo> mAcceptSet; 6738 6739 // Our bookkeeping about the ancestral dataset 6740 private PackageManagerBackupAgent mPmAgent; 6741 6742 // Currently-bound backup agent for restore + restoreFinished purposes 6743 private IBackupAgent mAgent; 6744 6745 // What sort of restore we're doing now 6746 private RestoreDescription mRestoreDescription; 6747 6748 // The package we're currently restoring 6749 private PackageInfo mCurrentPackage; 6750 6751 // Widget-related data handled as part of this restore operation 6752 private byte[] mWidgetData; 6753 6754 // Number of apps restored in this pass 6755 private int mCount; 6756 6757 // When did we start? 6758 private long mStartRealtime; 6759 6760 // State machine progress 6761 private UnifiedRestoreState mState; 6762 6763 // How are things going? 6764 private int mStatus; 6765 6766 // Done? 6767 private boolean mFinished; 6768 6769 // Key/value: bookkeeping about staged data and files for agent access 6770 private File mBackupDataName; 6771 private File mStageName; 6772 private File mSavedStateName; 6773 private File mNewStateName; 6774 ParcelFileDescriptor mBackupData; 6775 ParcelFileDescriptor mNewState; 6776 6777 // Invariant: mWakelock is already held, and this task is responsible for 6778 // releasing it at the end of the restore operation. 6779 PerformUnifiedRestoreTask(IBackupTransport transport, IRestoreObserver observer, 6780 long restoreSetToken, PackageInfo targetPackage, int pmToken, 6781 boolean isFullSystemRestore, String[] filterSet) { 6782 mState = UnifiedRestoreState.INITIAL; 6783 mStartRealtime = SystemClock.elapsedRealtime(); 6784 6785 mTransport = transport; 6786 mObserver = observer; 6787 mToken = restoreSetToken; 6788 mPmToken = pmToken; 6789 mTargetPackage = targetPackage; 6790 mIsSystemRestore = isFullSystemRestore; 6791 mFinished = false; 6792 6793 if (targetPackage != null) { 6794 // Single package restore 6795 mAcceptSet = new ArrayList<PackageInfo>(); 6796 mAcceptSet.add(targetPackage); 6797 } else { 6798 // Everything possible, or a target set 6799 if (filterSet == null) { 6800 // We want everything and a pony 6801 List<PackageInfo> apps = 6802 PackageManagerBackupAgent.getStorableApplications(mPackageManager); 6803 filterSet = packagesToNames(apps); 6804 if (DEBUG) { 6805 Slog.i(TAG, "Full restore; asking for " + filterSet.length + " apps"); 6806 } 6807 } 6808 6809 mAcceptSet = new ArrayList<PackageInfo>(filterSet.length); 6810 6811 // Pro tem, we insist on moving the settings provider package to last place. 6812 // Keep track of whether it's in the list, and bump it down if so. We also 6813 // want to do the system package itself first if it's called for. 6814 boolean hasSystem = false; 6815 boolean hasSettings = false; 6816 for (int i = 0; i < filterSet.length; i++) { 6817 try { 6818 PackageInfo info = mPackageManager.getPackageInfo(filterSet[i], 0); 6819 if ("android".equals(info.packageName)) { 6820 hasSystem = true; 6821 continue; 6822 } 6823 if (SETTINGS_PACKAGE.equals(info.packageName)) { 6824 hasSettings = true; 6825 continue; 6826 } 6827 6828 if (appIsEligibleForBackup(info.applicationInfo)) { 6829 mAcceptSet.add(info); 6830 } 6831 } catch (NameNotFoundException e) { 6832 // requested package name doesn't exist; ignore it 6833 } 6834 } 6835 if (hasSystem) { 6836 try { 6837 mAcceptSet.add(0, mPackageManager.getPackageInfo("android", 0)); 6838 } catch (NameNotFoundException e) { 6839 // won't happen; we know a priori that it's valid 6840 } 6841 } 6842 if (hasSettings) { 6843 try { 6844 mAcceptSet.add(mPackageManager.getPackageInfo(SETTINGS_PACKAGE, 0)); 6845 } catch (NameNotFoundException e) { 6846 // this one is always valid too 6847 } 6848 } 6849 } 6850 6851 if (MORE_DEBUG) { 6852 Slog.v(TAG, "Restore; accept set size is " + mAcceptSet.size()); 6853 for (PackageInfo info : mAcceptSet) { 6854 Slog.v(TAG, " " + info.packageName); 6855 } 6856 } 6857 } 6858 6859 private String[] packagesToNames(List<PackageInfo> apps) { 6860 final int N = apps.size(); 6861 String[] names = new String[N]; 6862 for (int i = 0; i < N; i++) { 6863 names[i] = apps.get(i).packageName; 6864 } 6865 return names; 6866 } 6867 6868 // Execute one tick of whatever state machine the task implements 6869 @Override 6870 public void execute() { 6871 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step " + mState); 6872 switch (mState) { 6873 case INITIAL: 6874 startRestore(); 6875 break; 6876 6877 case RUNNING_QUEUE: 6878 dispatchNextRestore(); 6879 break; 6880 6881 case RESTORE_KEYVALUE: 6882 restoreKeyValue(); 6883 break; 6884 6885 case RESTORE_FULL: 6886 restoreFull(); 6887 break; 6888 6889 case RESTORE_FINISHED: 6890 restoreFinished(); 6891 break; 6892 6893 case FINAL: 6894 if (!mFinished) finalizeRestore(); 6895 else { 6896 Slog.e(TAG, "Duplicate finish"); 6897 } 6898 mFinished = true; 6899 break; 6900 } 6901 } 6902 6903 /* 6904 * SKETCH OF OPERATION 6905 * 6906 * create one of these PerformUnifiedRestoreTask objects, telling it which 6907 * dataset & transport to address, and then parameters within the restore 6908 * operation: single target package vs many, etc. 6909 * 6910 * 1. transport.startRestore(token, list-of-packages). If we need @pm@ it is 6911 * always placed first and the settings provider always placed last [for now]. 6912 * 6913 * 1a [if we needed @pm@ then nextRestorePackage() and restore the PMBA inline] 6914 * 6915 * [ state change => RUNNING_QUEUE ] 6916 * 6917 * NOW ITERATE: 6918 * 6919 * { 3. t.nextRestorePackage() 6920 * 4. does the metadata for this package allow us to restore it? 6921 * does the on-disk app permit us to restore it? [re-check allowBackup etc] 6922 * 5. is this a key/value dataset? => key/value agent restore 6923 * [ state change => RESTORE_KEYVALUE ] 6924 * 5a. spin up agent 6925 * 5b. t.getRestoreData() to stage it properly 6926 * 5c. call into agent to perform restore 6927 * 5d. tear down agent 6928 * [ state change => RUNNING_QUEUE ] 6929 * 6930 * 6. else it's a stream dataset: 6931 * [ state change => RESTORE_FULL ] 6932 * 6a. instantiate the engine for a stream restore: engine handles agent lifecycles 6933 * 6b. spin off engine runner on separate thread 6934 * 6c. ITERATE getNextFullRestoreDataChunk() and copy data to engine runner socket 6935 * [ state change => RUNNING_QUEUE ] 6936 * } 6937 * 6938 * [ state change => FINAL ] 6939 * 6940 * 7. t.finishRestore(), release wakelock, etc. 6941 * 6942 * 6943 */ 6944 6945 // state INITIAL : set up for the restore and read the metadata if necessary 6946 private void startRestore() { 6947 sendStartRestore(mAcceptSet.size()); 6948 6949 try { 6950 String transportDir = mTransport.transportDirName(); 6951 mStateDir = new File(mBaseStateDir, transportDir); 6952 6953 // Fetch the current metadata from the dataset first 6954 PackageInfo pmPackage = new PackageInfo(); 6955 pmPackage.packageName = PACKAGE_MANAGER_SENTINEL; 6956 mAcceptSet.add(0, pmPackage); 6957 6958 PackageInfo[] packages = mAcceptSet.toArray(new PackageInfo[0]); 6959 mStatus = mTransport.startRestore(mToken, packages); 6960 if (mStatus != BackupTransport.TRANSPORT_OK) { 6961 Slog.e(TAG, "Transport error " + mStatus + "; no restore possible"); 6962 mStatus = BackupTransport.TRANSPORT_ERROR; 6963 executeNextState(UnifiedRestoreState.FINAL); 6964 return; 6965 } 6966 6967 RestoreDescription desc = mTransport.nextRestorePackage(); 6968 if (desc == null) { 6969 Slog.e(TAG, "No restore metadata available; halting"); 6970 mStatus = BackupTransport.TRANSPORT_ERROR; 6971 executeNextState(UnifiedRestoreState.FINAL); 6972 return; 6973 } 6974 if (!PACKAGE_MANAGER_SENTINEL.equals(desc.getPackageName())) { 6975 Slog.e(TAG, "Required metadata but got " + desc.getPackageName()); 6976 mStatus = BackupTransport.TRANSPORT_ERROR; 6977 executeNextState(UnifiedRestoreState.FINAL); 6978 return; 6979 } 6980 6981 // Pull the Package Manager metadata from the restore set first 6982 mCurrentPackage = new PackageInfo(); 6983 mCurrentPackage.packageName = PACKAGE_MANAGER_SENTINEL; 6984 mPmAgent = new PackageManagerBackupAgent(mPackageManager, null); 6985 mAgent = IBackupAgent.Stub.asInterface(mPmAgent.onBind()); 6986 if (MORE_DEBUG) { 6987 Slog.v(TAG, "initiating restore for PMBA"); 6988 } 6989 initiateOneRestore(mCurrentPackage, 0); 6990 // The PM agent called operationComplete() already, because our invocation 6991 // of it is process-local and therefore synchronous. That means that the 6992 // next-state message (RUNNING_QUEUE) is already enqueued. Only if we're 6993 // unable to proceed with running the queue do we remove that pending 6994 // message and jump straight to the FINAL state. 6995 6996 // Verify that the backup set includes metadata. If not, we can't do 6997 // signature/version verification etc, so we simply do not proceed with 6998 // the restore operation. 6999 if (!mPmAgent.hasMetadata()) { 7000 Slog.e(TAG, "No restore metadata available, so not restoring"); 7001 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, 7002 PACKAGE_MANAGER_SENTINEL, 7003 "Package manager restore metadata missing"); 7004 mStatus = BackupTransport.TRANSPORT_ERROR; 7005 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this); 7006 executeNextState(UnifiedRestoreState.FINAL); 7007 return; 7008 } 7009 7010 // Success; cache the metadata and continue as expected with the 7011 // next state already enqueued 7012 7013 } catch (RemoteException e) { 7014 // If we lost the transport at any time, halt 7015 Slog.e(TAG, "Unable to contact transport for restore"); 7016 mStatus = BackupTransport.TRANSPORT_ERROR; 7017 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this); 7018 executeNextState(UnifiedRestoreState.FINAL); 7019 return; 7020 } 7021 } 7022 7023 // state RUNNING_QUEUE : figure out what the next thing to be restored is, 7024 // and fire the appropriate next step 7025 private void dispatchNextRestore() { 7026 UnifiedRestoreState nextState = UnifiedRestoreState.FINAL; 7027 try { 7028 mRestoreDescription = mTransport.nextRestorePackage(); 7029 final String pkgName = (mRestoreDescription != null) 7030 ? mRestoreDescription.getPackageName() : null; 7031 if (pkgName == null) { 7032 Slog.e(TAG, "Failure getting next package name"); 7033 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE); 7034 nextState = UnifiedRestoreState.FINAL; 7035 return; 7036 } else if (mRestoreDescription == RestoreDescription.NO_MORE_PACKAGES) { 7037 // Yay we've reached the end cleanly 7038 if (DEBUG) { 7039 Slog.v(TAG, "No more packages; finishing restore"); 7040 } 7041 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime); 7042 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis); 7043 nextState = UnifiedRestoreState.FINAL; 7044 return; 7045 } 7046 7047 if (DEBUG) { 7048 Slog.i(TAG, "Next restore package: " + mRestoreDescription); 7049 } 7050 sendOnRestorePackage(pkgName); 7051 7052 Metadata metaInfo = mPmAgent.getRestoredMetadata(pkgName); 7053 if (metaInfo == null) { 7054 Slog.e(TAG, "No metadata for " + pkgName); 7055 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, pkgName, 7056 "Package metadata missing"); 7057 nextState = UnifiedRestoreState.RUNNING_QUEUE; 7058 return; 7059 } 7060 7061 try { 7062 mCurrentPackage = mPackageManager.getPackageInfo( 7063 pkgName, PackageManager.GET_SIGNATURES); 7064 } catch (NameNotFoundException e) { 7065 // Whoops, we thought we could restore this package but it 7066 // turns out not to be present. Skip it. 7067 Slog.e(TAG, "Package not present: " + pkgName); 7068 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, pkgName, 7069 "Package missing on device"); 7070 nextState = UnifiedRestoreState.RUNNING_QUEUE; 7071 return; 7072 } 7073 7074 if (metaInfo.versionCode > mCurrentPackage.versionCode) { 7075 // Data is from a "newer" version of the app than we have currently 7076 // installed. If the app has not declared that it is prepared to 7077 // handle this case, we do not attempt the restore. 7078 if ((mCurrentPackage.applicationInfo.flags 7079 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) { 7080 String message = "Version " + metaInfo.versionCode 7081 + " > installed version " + mCurrentPackage.versionCode; 7082 Slog.w(TAG, "Package " + pkgName + ": " + message); 7083 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, 7084 pkgName, message); 7085 nextState = UnifiedRestoreState.RUNNING_QUEUE; 7086 return; 7087 } else { 7088 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode 7089 + " > installed " + mCurrentPackage.versionCode 7090 + " but restoreAnyVersion"); 7091 } 7092 } 7093 7094 if (DEBUG) Slog.v(TAG, "Package " + pkgName 7095 + " restore version [" + metaInfo.versionCode 7096 + "] is compatible with installed version [" 7097 + mCurrentPackage.versionCode + "]"); 7098 7099 // Reset per-package preconditions and fire the appropriate next state 7100 mWidgetData = null; 7101 final int type = mRestoreDescription.getDataType(); 7102 if (type == RestoreDescription.TYPE_KEY_VALUE) { 7103 nextState = UnifiedRestoreState.RESTORE_KEYVALUE; 7104 } else if (type == RestoreDescription.TYPE_FULL_STREAM) { 7105 nextState = UnifiedRestoreState.RESTORE_FULL; 7106 } else { 7107 // Unknown restore type; ignore this package and move on 7108 Slog.e(TAG, "Unrecognized restore type " + type); 7109 nextState = UnifiedRestoreState.RUNNING_QUEUE; 7110 return; 7111 } 7112 } catch (RemoteException e) { 7113 Slog.e(TAG, "Can't get next target from transport; ending restore"); 7114 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE); 7115 nextState = UnifiedRestoreState.FINAL; 7116 return; 7117 } finally { 7118 executeNextState(nextState); 7119 } 7120 } 7121 7122 // state RESTORE_KEYVALUE : restore one package via key/value API set 7123 private void restoreKeyValue() { 7124 // Initiating the restore will pass responsibility for the state machine's 7125 // progress to the agent callback, so we do not always execute the 7126 // next state here. 7127 final String packageName = mCurrentPackage.packageName; 7128 // Validate some semantic requirements that apply in this way 7129 // only to the key/value restore API flow 7130 if (mCurrentPackage.applicationInfo.backupAgentName == null 7131 || "".equals(mCurrentPackage.applicationInfo.backupAgentName)) { 7132 if (DEBUG) { 7133 Slog.i(TAG, "Data exists for package " + packageName 7134 + " but app has no agent; skipping"); 7135 } 7136 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, 7137 "Package has no agent"); 7138 executeNextState(UnifiedRestoreState.RUNNING_QUEUE); 7139 return; 7140 } 7141 7142 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName); 7143 if (!signaturesMatch(metaInfo.sigHashes, mCurrentPackage)) { 7144 Slog.w(TAG, "Signature mismatch restoring " + packageName); 7145 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, 7146 "Signature mismatch"); 7147 executeNextState(UnifiedRestoreState.RUNNING_QUEUE); 7148 return; 7149 } 7150 7151 // Good to go! Set up and bind the agent... 7152 mAgent = bindToAgentSynchronous( 7153 mCurrentPackage.applicationInfo, 7154 IApplicationThread.BACKUP_MODE_INCREMENTAL); 7155 if (mAgent == null) { 7156 Slog.w(TAG, "Can't find backup agent for " + packageName); 7157 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, 7158 "Restore agent missing"); 7159 executeNextState(UnifiedRestoreState.RUNNING_QUEUE); 7160 return; 7161 } 7162 7163 // And then finally start the restore on this agent 7164 try { 7165 initiateOneRestore(mCurrentPackage, metaInfo.versionCode); 7166 ++mCount; 7167 } catch (Exception e) { 7168 Slog.e(TAG, "Error when attempting restore: " + e.toString()); 7169 keyValueAgentErrorCleanup(); 7170 executeNextState(UnifiedRestoreState.RUNNING_QUEUE); 7171 } 7172 } 7173 7174 // Guts of a key/value restore operation 7175 void initiateOneRestore(PackageInfo app, int appVersionCode) { 7176 final String packageName = app.packageName; 7177 7178 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName); 7179 7180 // !!! TODO: get the dirs from the transport 7181 mBackupDataName = new File(mDataDir, packageName + ".restore"); 7182 mStageName = new File(mDataDir, packageName + ".stage"); 7183 mNewStateName = new File(mStateDir, packageName + ".new"); 7184 mSavedStateName = new File(mStateDir, packageName); 7185 7186 // don't stage the 'android' package where the wallpaper data lives. this is 7187 // an optimization: we know there's no widget data hosted/published by that 7188 // package, and this way we avoid doing a spurious copy of MB-sized wallpaper 7189 // data following the download. 7190 boolean staging = !packageName.equals("android"); 7191 ParcelFileDescriptor stage; 7192 File downloadFile = (staging) ? mStageName : mBackupDataName; 7193 7194 final int token = generateToken(); 7195 try { 7196 // Run the transport's restore pass 7197 stage = ParcelFileDescriptor.open(downloadFile, 7198 ParcelFileDescriptor.MODE_READ_WRITE | 7199 ParcelFileDescriptor.MODE_CREATE | 7200 ParcelFileDescriptor.MODE_TRUNCATE); 7201 7202 if (!SELinux.restorecon(mBackupDataName)) { 7203 Slog.e(TAG, "SElinux restorecon failed for " + downloadFile); 7204 } 7205 7206 if (mTransport.getRestoreData(stage) != BackupTransport.TRANSPORT_OK) { 7207 // Transport-level failure, so we wind everything up and 7208 // terminate the restore operation. 7209 Slog.e(TAG, "Error getting restore data for " + packageName); 7210 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE); 7211 stage.close(); 7212 downloadFile.delete(); 7213 executeNextState(UnifiedRestoreState.FINAL); 7214 return; 7215 } 7216 7217 // We have the data from the transport. Now we extract and strip 7218 // any per-package metadata (typically widget-related information) 7219 // if appropriate 7220 if (staging) { 7221 stage.close(); 7222 stage = ParcelFileDescriptor.open(downloadFile, 7223 ParcelFileDescriptor.MODE_READ_ONLY); 7224 7225 mBackupData = ParcelFileDescriptor.open(mBackupDataName, 7226 ParcelFileDescriptor.MODE_READ_WRITE | 7227 ParcelFileDescriptor.MODE_CREATE | 7228 ParcelFileDescriptor.MODE_TRUNCATE); 7229 7230 BackupDataInput in = new BackupDataInput(stage.getFileDescriptor()); 7231 BackupDataOutput out = new BackupDataOutput(mBackupData.getFileDescriptor()); 7232 byte[] buffer = new byte[8192]; // will grow when needed 7233 while (in.readNextHeader()) { 7234 final String key = in.getKey(); 7235 final int size = in.getDataSize(); 7236 7237 // is this a special key? 7238 if (key.equals(KEY_WIDGET_STATE)) { 7239 if (DEBUG) { 7240 Slog.i(TAG, "Restoring widget state for " + packageName); 7241 } 7242 mWidgetData = new byte[size]; 7243 in.readEntityData(mWidgetData, 0, size); 7244 } else { 7245 if (size > buffer.length) { 7246 buffer = new byte[size]; 7247 } 7248 in.readEntityData(buffer, 0, size); 7249 out.writeEntityHeader(key, size); 7250 out.writeEntityData(buffer, size); 7251 } 7252 } 7253 7254 mBackupData.close(); 7255 } 7256 7257 // Okay, we have the data. Now have the agent do the restore. 7258 stage.close(); 7259 mBackupData = ParcelFileDescriptor.open(mBackupDataName, 7260 ParcelFileDescriptor.MODE_READ_ONLY); 7261 7262 mNewState = ParcelFileDescriptor.open(mNewStateName, 7263 ParcelFileDescriptor.MODE_READ_WRITE | 7264 ParcelFileDescriptor.MODE_CREATE | 7265 ParcelFileDescriptor.MODE_TRUNCATE); 7266 7267 // Kick off the restore, checking for hung agents. The timeout or 7268 // the operationComplete() callback will schedule the next step, 7269 // so we do not do that here. 7270 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this); 7271 mAgent.doRestore(mBackupData, appVersionCode, mNewState, 7272 token, mBackupManagerBinder); 7273 } catch (Exception e) { 7274 Slog.e(TAG, "Unable to call app for restore: " + packageName, e); 7275 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, 7276 packageName, e.toString()); 7277 keyValueAgentErrorCleanup(); // clears any pending timeout messages as well 7278 7279 // After a restore failure we go back to running the queue. If there 7280 // are no more packages to be restored that will be handled by the 7281 // next step. 7282 executeNextState(UnifiedRestoreState.RUNNING_QUEUE); 7283 } 7284 } 7285 7286 // state RESTORE_FULL : restore one package via streaming engine 7287 private void restoreFull() { 7288 // None of this can run on the work looper here, so we spin asynchronous 7289 // work like this: 7290 // 7291 // StreamFeederThread: read data from mTransport.getNextFullRestoreDataChunk() 7292 // write it into the pipe to the engine 7293 // EngineThread: FullRestoreEngine thread communicating with the target app 7294 // 7295 // When finished, StreamFeederThread executes next state as appropriate on the 7296 // backup looper, and the overall unified restore task resumes 7297 try { 7298 StreamFeederThread feeder = new StreamFeederThread(); 7299 if (DEBUG) { 7300 Slog.i(TAG, "Spinning threads for stream restore of " 7301 + mCurrentPackage.packageName); 7302 } 7303 new Thread(feeder, "unified-stream-feeder").start(); 7304 7305 // At this point the feeder is responsible for advancing the restore 7306 // state, so we're done here. 7307 } catch (IOException e) { 7308 // Unable to instantiate the feeder thread -- we need to bail on the 7309 // current target. We haven't asked the transport for data yet, though, 7310 // so we can do that simply by going back to running the restore queue. 7311 Slog.e(TAG, "Unable to construct pipes for stream restore!"); 7312 executeNextState(UnifiedRestoreState.RUNNING_QUEUE); 7313 } 7314 } 7315 7316 // state RESTORE_FINISHED : provide the "no more data" signpost callback at the end 7317 private void restoreFinished() { 7318 try { 7319 final int token = generateToken(); 7320 prepareOperationTimeout(token, TIMEOUT_RESTORE_FINISHED_INTERVAL, this); 7321 mAgent.doRestoreFinished(token, mBackupManagerBinder); 7322 // If we get this far, the callback or timeout will schedule the 7323 // next restore state, so we're done 7324 } catch (Exception e) { 7325 Slog.e(TAG, "Unable to finalize restore of " + mCurrentPackage.packageName); 7326 executeNextState(UnifiedRestoreState.FINAL); 7327 } 7328 } 7329 7330 class StreamFeederThread extends RestoreEngine implements Runnable { 7331 final String TAG = "StreamFeederThread"; 7332 FullRestoreEngine mEngine; 7333 7334 // pipe through which we read data from the transport. [0] read, [1] write 7335 ParcelFileDescriptor[] mTransportPipes; 7336 7337 // pipe through which the engine will read data. [0] read, [1] write 7338 ParcelFileDescriptor[] mEnginePipes; 7339 7340 public StreamFeederThread() throws IOException { 7341 mTransportPipes = ParcelFileDescriptor.createPipe(); 7342 mEnginePipes = ParcelFileDescriptor.createPipe(); 7343 setRunning(true); 7344 } 7345 7346 @Override 7347 public void run() { 7348 UnifiedRestoreState nextState = UnifiedRestoreState.RUNNING_QUEUE; 7349 int status = BackupTransport.TRANSPORT_OK; 7350 7351 mEngine = new FullRestoreEngine(null, mCurrentPackage, false, false); 7352 EngineThread eThread = new EngineThread(mEngine, mEnginePipes[0]); 7353 7354 ParcelFileDescriptor eWriteEnd = mEnginePipes[1]; 7355 ParcelFileDescriptor tReadEnd = mTransportPipes[0]; 7356 ParcelFileDescriptor tWriteEnd = mTransportPipes[1]; 7357 7358 int bufferSize = 32 * 1024; 7359 byte[] buffer = new byte[bufferSize]; 7360 FileOutputStream engineOut = new FileOutputStream(eWriteEnd.getFileDescriptor()); 7361 FileInputStream transportIn = new FileInputStream(tReadEnd.getFileDescriptor()); 7362 7363 // spin up the engine and start moving data to it 7364 new Thread(eThread, "unified-restore-engine").start(); 7365 7366 try { 7367 while (status == BackupTransport.TRANSPORT_OK) { 7368 // have the transport write some of the restoring data to us 7369 int result = mTransport.getNextFullRestoreDataChunk(tWriteEnd); 7370 if (result > 0) { 7371 // The transport wrote this many bytes of restore data to the 7372 // pipe, so pass it along to the engine. 7373 if (MORE_DEBUG) { 7374 Slog.v(TAG, " <- transport provided chunk size " + result); 7375 } 7376 if (result > bufferSize) { 7377 bufferSize = result; 7378 buffer = new byte[bufferSize]; 7379 } 7380 int toCopy = result; 7381 while (toCopy > 0) { 7382 int n = transportIn.read(buffer, 0, toCopy); 7383 engineOut.write(buffer, 0, n); 7384 toCopy -= n; 7385 if (MORE_DEBUG) { 7386 Slog.v(TAG, " -> wrote " + n + " to engine, left=" + toCopy); 7387 } 7388 } 7389 } else if (result == BackupTransport.NO_MORE_DATA) { 7390 // Clean finish. Wind up and we're done! 7391 if (MORE_DEBUG) { 7392 Slog.i(TAG, "Got clean full-restore EOF for " 7393 + mCurrentPackage.packageName); 7394 } 7395 status = BackupTransport.TRANSPORT_OK; 7396 break; 7397 } else { 7398 // Transport reported some sort of failure; the fall-through 7399 // handling will deal properly with that. 7400 Slog.e(TAG, "Error " + result + " streaming restore for " 7401 + mCurrentPackage.packageName); 7402 status = result; 7403 } 7404 } 7405 if (MORE_DEBUG) Slog.v(TAG, "Done copying to engine, falling through"); 7406 } catch (IOException e) { 7407 // We lost our ability to communicate via the pipes. That's worrying 7408 // but potentially recoverable; abandon this package's restore but 7409 // carry on with the next restore target. 7410 Slog.e(TAG, "Unable to route data for restore"); 7411 status = BackupTransport.AGENT_ERROR; 7412 } catch (RemoteException e) { 7413 // The transport went away; terminate the whole operation. Closing 7414 // the sockets will wake up the engine and it will then tidy up the 7415 // remote end. 7416 Slog.e(TAG, "Transport failed during restore"); 7417 status = BackupTransport.TRANSPORT_ERROR; 7418 } finally { 7419 // Close the transport pipes and *our* end of the engine pipe, 7420 // but leave the engine thread's end open so that it properly 7421 // hits EOF and winds up its operations. 7422 IoUtils.closeQuietly(mEnginePipes[1]); 7423 IoUtils.closeQuietly(mTransportPipes[0]); 7424 IoUtils.closeQuietly(mTransportPipes[1]); 7425 7426 // Don't proceed until the engine has torn down the agent etc 7427 eThread.waitForResult(); 7428 7429 if (MORE_DEBUG) { 7430 Slog.i(TAG, "engine thread finished; proceeding"); 7431 } 7432 7433 // Now we're really done with this one too 7434 IoUtils.closeQuietly(mEnginePipes[0]); 7435 7436 // If we hit a transport-level error, we are done with everything; 7437 // if we hit an agent error we just go back to running the queue. 7438 if (status == BackupTransport.TRANSPORT_OK) { 7439 // Clean finish, so just carry on 7440 nextState = UnifiedRestoreState.RUNNING_QUEUE; 7441 } else { 7442 // Something went wrong somewhere. Whether it was at the transport 7443 // level is immaterial; we need to tell the transport to bail 7444 try { 7445 mTransport.abortFullRestore(); 7446 } catch (RemoteException e) { 7447 // transport itself is dead; make sure we handle this as a 7448 // fatal error 7449 status = BackupTransport.TRANSPORT_ERROR; 7450 } 7451 7452 // We also need to wipe the current target's data, as it's probably 7453 // in an incoherent state. 7454 clearApplicationDataSynchronous(mCurrentPackage.packageName); 7455 7456 // Schedule the next state based on the nature of our failure 7457 if (status == BackupTransport.TRANSPORT_ERROR) { 7458 nextState = UnifiedRestoreState.FINAL; 7459 } else { 7460 nextState = UnifiedRestoreState.RUNNING_QUEUE; 7461 } 7462 } 7463 executeNextState(nextState); 7464 setRunning(false); 7465 } 7466 } 7467 7468 } 7469 7470 class EngineThread implements Runnable { 7471 FullRestoreEngine mEngine; 7472 FileInputStream mEngineStream; 7473 7474 EngineThread(FullRestoreEngine engine, ParcelFileDescriptor engineSocket) { 7475 mEngine = engine; 7476 engine.setRunning(true); 7477 mEngineStream = new FileInputStream(engineSocket.getFileDescriptor()); 7478 } 7479 7480 public boolean isRunning() { 7481 return mEngine.isRunning(); 7482 } 7483 7484 public int waitForResult() { 7485 return mEngine.waitForResult(); 7486 } 7487 7488 @Override 7489 public void run() { 7490 while (mEngine.isRunning()) { 7491 mEngine.restoreOneFile(mEngineStream); 7492 } 7493 } 7494 } 7495 7496 // state FINAL : tear everything down and we're done. 7497 private void finalizeRestore() { 7498 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver); 7499 7500 try { 7501 mTransport.finishRestore(); 7502 } catch (Exception e) { 7503 Slog.e(TAG, "Error finishing restore", e); 7504 } 7505 7506 // Tell the observer we're done 7507 if (mObserver != null) { 7508 try { 7509 mObserver.restoreFinished(mStatus); 7510 } catch (RemoteException e) { 7511 Slog.d(TAG, "Restore observer died at restoreFinished"); 7512 } 7513 } 7514 7515 // If we have a PM token, we must under all circumstances be sure to 7516 // handshake when we've finished. 7517 if (mPmToken > 0) { 7518 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken); 7519 try { 7520 mPackageManagerBinder.finishPackageInstall(mPmToken); 7521 } catch (RemoteException e) { /* can't happen */ } 7522 } 7523 7524 // Kick off any work that may be needed regarding app widget restores 7525 AppWidgetBackupBridge.restoreFinished(UserHandle.USER_OWNER); 7526 7527 // If this was a full-system restore, record the ancestral 7528 // dataset information 7529 if (mIsSystemRestore) { 7530 mAncestralPackages = mPmAgent.getRestoredPackages(); 7531 mAncestralToken = mToken; 7532 writeRestoreTokens(); 7533 } 7534 7535 // Furthermore we need to reset the session timeout clock 7536 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT); 7537 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, 7538 TIMEOUT_RESTORE_INTERVAL); 7539 7540 // done; we can finally release the wakelock and be legitimately done. 7541 Slog.i(TAG, "Restore complete."); 7542 mWakelock.release(); 7543 } 7544 7545 void keyValueAgentErrorCleanup() { 7546 // If the agent fails restore, it might have put the app's data 7547 // into an incoherent state. For consistency we wipe its data 7548 // again in this case before continuing with normal teardown 7549 clearApplicationDataSynchronous(mCurrentPackage.packageName); 7550 keyValueAgentCleanup(); 7551 } 7552 7553 void keyValueAgentCleanup() { 7554 mBackupDataName.delete(); 7555 mStageName.delete(); 7556 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {} 7557 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {} 7558 mBackupData = mNewState = null; 7559 7560 // if everything went okay, remember the recorded state now 7561 // 7562 // !!! TODO: the restored data could be migrated on the server 7563 // side into the current dataset. In that case the new state file 7564 // we just created would reflect the data already extant in the 7565 // backend, so there'd be nothing more to do. Until that happens, 7566 // however, we need to make sure that we record the data to the 7567 // current backend dataset. (Yes, this means shipping the data over 7568 // the wire in both directions. That's bad, but consistency comes 7569 // first, then efficiency.) Once we introduce server-side data 7570 // migration to the newly-restored device's dataset, we will change 7571 // the following from a discard of the newly-written state to the 7572 // "correct" operation of renaming into the canonical state blob. 7573 mNewStateName.delete(); // TODO: remove; see above comment 7574 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this 7575 7576 // If this wasn't the PM pseudopackage, tear down the agent side 7577 if (mCurrentPackage.applicationInfo != null) { 7578 // unbind and tidy up even on timeout or failure 7579 try { 7580 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo); 7581 7582 // The agent was probably running with a stub Application object, 7583 // which isn't a valid run mode for the main app logic. Shut 7584 // down the app so that next time it's launched, it gets the 7585 // usual full initialization. Note that this is only done for 7586 // full-system restores: when a single app has requested a restore, 7587 // it is explicitly not killed following that operation. 7588 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags 7589 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) { 7590 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of " 7591 + mCurrentPackage.applicationInfo.processName); 7592 mActivityManager.killApplicationProcess( 7593 mCurrentPackage.applicationInfo.processName, 7594 mCurrentPackage.applicationInfo.uid); 7595 } 7596 } catch (RemoteException e) { 7597 // can't happen; we run in the same process as the activity manager 7598 } 7599 } 7600 7601 // The caller is responsible for reestablishing the state machine; our 7602 // responsibility here is to clear the decks for whatever comes next. 7603 mBackupHandler.removeMessages(MSG_TIMEOUT, this); 7604 synchronized (mCurrentOpLock) { 7605 mCurrentOperations.clear(); 7606 } 7607 } 7608 7609 @Override 7610 public void operationComplete() { 7611 if (MORE_DEBUG) { 7612 Slog.i(TAG, "operationComplete() during restore: target=" 7613 + mCurrentPackage.packageName 7614 + " state=" + mState); 7615 } 7616 7617 final UnifiedRestoreState nextState; 7618 switch (mState) { 7619 case INITIAL: 7620 // We've just (manually) restored the PMBA. It doesn't need the 7621 // additional restore-finished callback so we bypass that and go 7622 // directly to running the queue. 7623 nextState = UnifiedRestoreState.RUNNING_QUEUE; 7624 break; 7625 7626 case RESTORE_KEYVALUE: 7627 case RESTORE_FULL: { 7628 // Okay, we've just heard back from the agent that it's done with 7629 // the restore itself. We now have to send the same agent its 7630 // doRestoreFinished() callback, so roll into that state. 7631 nextState = UnifiedRestoreState.RESTORE_FINISHED; 7632 break; 7633 } 7634 7635 case RESTORE_FINISHED: { 7636 // Okay, we're done with this package. Tidy up and go on to the next 7637 // app in the queue. 7638 int size = (int) mBackupDataName.length(); 7639 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, 7640 mCurrentPackage.packageName, size); 7641 7642 // Just go back to running the restore queue 7643 keyValueAgentCleanup(); 7644 7645 // If there was widget state associated with this app, get the OS to 7646 // incorporate it into current bookeeping and then pass that along to 7647 // the app as part of the restore-time work. 7648 if (mWidgetData != null) { 7649 restoreWidgetData(mCurrentPackage.packageName, mWidgetData); 7650 } 7651 7652 nextState = UnifiedRestoreState.RUNNING_QUEUE; 7653 break; 7654 } 7655 7656 default: { 7657 // Some kind of horrible semantic error; we're in an unexpected state. 7658 // Back off hard and wind up. 7659 Slog.e(TAG, "Unexpected restore callback into state " + mState); 7660 keyValueAgentErrorCleanup(); 7661 nextState = UnifiedRestoreState.FINAL; 7662 break; 7663 } 7664 } 7665 7666 executeNextState(nextState); 7667 } 7668 7669 // A call to agent.doRestore() or agent.doRestoreFinished() has timed out 7670 @Override 7671 public void handleTimeout() { 7672 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName); 7673 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, 7674 mCurrentPackage.packageName, "restore timeout"); 7675 // Handle like an agent that threw on invocation: wipe it and go on to the next 7676 keyValueAgentErrorCleanup(); 7677 executeNextState(UnifiedRestoreState.RUNNING_QUEUE); 7678 } 7679 7680 void executeNextState(UnifiedRestoreState nextState) { 7681 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on " 7682 + this + " nextState=" + nextState); 7683 mState = nextState; 7684 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this); 7685 mBackupHandler.sendMessage(msg); 7686 } 7687 7688 // restore observer support 7689 void sendStartRestore(int numPackages) { 7690 if (mObserver != null) { 7691 try { 7692 mObserver.restoreStarting(numPackages); 7693 } catch (RemoteException e) { 7694 Slog.w(TAG, "Restore observer went away: startRestore"); 7695 mObserver = null; 7696 } 7697 } 7698 } 7699 7700 void sendOnRestorePackage(String name) { 7701 if (mObserver != null) { 7702 if (mObserver != null) { 7703 try { 7704 mObserver.onUpdate(mCount, name); 7705 } catch (RemoteException e) { 7706 Slog.d(TAG, "Restore observer died in onUpdate"); 7707 mObserver = null; 7708 } 7709 } 7710 } 7711 } 7712 7713 void sendEndRestore() { 7714 if (mObserver != null) { 7715 try { 7716 mObserver.restoreFinished(mStatus); 7717 } catch (RemoteException e) { 7718 Slog.w(TAG, "Restore observer went away: endRestore"); 7719 mObserver = null; 7720 } 7721 } 7722 } 7723 } 7724 7725 class PerformClearTask implements Runnable { 7726 IBackupTransport mTransport; 7727 PackageInfo mPackage; 7728 7729 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) { 7730 mTransport = transport; 7731 mPackage = packageInfo; 7732 } 7733 7734 public void run() { 7735 try { 7736 // Clear the on-device backup state to ensure a full backup next time 7737 File stateDir = new File(mBaseStateDir, mTransport.transportDirName()); 7738 File stateFile = new File(stateDir, mPackage.packageName); 7739 stateFile.delete(); 7740 7741 // Tell the transport to remove all the persistent storage for the app 7742 // TODO - need to handle failures 7743 mTransport.clearBackupData(mPackage); 7744 } catch (RemoteException e) { 7745 // can't happen; the transport is local 7746 } catch (Exception e) { 7747 Slog.e(TAG, "Transport threw attempting to clear data for " + mPackage); 7748 } finally { 7749 try { 7750 // TODO - need to handle failures 7751 mTransport.finishBackup(); 7752 } catch (RemoteException e) { 7753 // can't happen; the transport is local 7754 } 7755 7756 // Last but not least, release the cpu 7757 mWakelock.release(); 7758 } 7759 } 7760 } 7761 7762 class PerformInitializeTask implements Runnable { 7763 HashSet<String> mQueue; 7764 7765 PerformInitializeTask(HashSet<String> transportNames) { 7766 mQueue = transportNames; 7767 } 7768 7769 public void run() { 7770 try { 7771 for (String transportName : mQueue) { 7772 IBackupTransport transport = getTransport(transportName); 7773 if (transport == null) { 7774 Slog.e(TAG, "Requested init for " + transportName + " but not found"); 7775 continue; 7776 } 7777 7778 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName); 7779 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName()); 7780 long startRealtime = SystemClock.elapsedRealtime(); 7781 int status = transport.initializeDevice(); 7782 7783 if (status == BackupTransport.TRANSPORT_OK) { 7784 status = transport.finishBackup(); 7785 } 7786 7787 // Okay, the wipe really happened. Clean up our local bookkeeping. 7788 if (status == BackupTransport.TRANSPORT_OK) { 7789 Slog.i(TAG, "Device init successful"); 7790 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime); 7791 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE); 7792 resetBackupState(new File(mBaseStateDir, transport.transportDirName())); 7793 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis); 7794 synchronized (mQueueLock) { 7795 recordInitPendingLocked(false, transportName); 7796 } 7797 } else { 7798 // If this didn't work, requeue this one and try again 7799 // after a suitable interval 7800 Slog.e(TAG, "Transport error in initializeDevice()"); 7801 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)"); 7802 synchronized (mQueueLock) { 7803 recordInitPendingLocked(true, transportName); 7804 } 7805 // do this via another alarm to make sure of the wakelock states 7806 long delay = transport.requestBackupTime(); 7807 if (DEBUG) Slog.w(TAG, "init failed on " 7808 + transportName + " resched in " + delay); 7809 mAlarmManager.set(AlarmManager.RTC_WAKEUP, 7810 System.currentTimeMillis() + delay, mRunInitIntent); 7811 } 7812 } 7813 } catch (RemoteException e) { 7814 // can't happen; the transports are local 7815 } catch (Exception e) { 7816 Slog.e(TAG, "Unexpected error performing init", e); 7817 } finally { 7818 // Done; release the wakelock 7819 mWakelock.release(); 7820 } 7821 } 7822 } 7823 7824 private void dataChangedImpl(String packageName) { 7825 HashSet<String> targets = dataChangedTargets(packageName); 7826 dataChangedImpl(packageName, targets); 7827 } 7828 7829 private void dataChangedImpl(String packageName, HashSet<String> targets) { 7830 // Record that we need a backup pass for the caller. Since multiple callers 7831 // may share a uid, we need to note all candidates within that uid and schedule 7832 // a backup pass for each of them. 7833 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName); 7834 7835 if (targets == null) { 7836 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'" 7837 + " uid=" + Binder.getCallingUid()); 7838 return; 7839 } 7840 7841 synchronized (mQueueLock) { 7842 // Note that this client has made data changes that need to be backed up 7843 if (targets.contains(packageName)) { 7844 // Add the caller to the set of pending backups. If there is 7845 // one already there, then overwrite it, but no harm done. 7846 BackupRequest req = new BackupRequest(packageName); 7847 if (mPendingBackups.put(packageName, req) == null) { 7848 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName); 7849 7850 // Journal this request in case of crash. The put() 7851 // operation returned null when this package was not already 7852 // in the set; we want to avoid touching the disk redundantly. 7853 writeToJournalLocked(packageName); 7854 7855 if (MORE_DEBUG) { 7856 int numKeys = mPendingBackups.size(); 7857 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:"); 7858 for (BackupRequest b : mPendingBackups.values()) { 7859 Slog.d(TAG, " + " + b); 7860 } 7861 } 7862 } 7863 } 7864 } 7865 } 7866 7867 // Note: packageName is currently unused, but may be in the future 7868 private HashSet<String> dataChangedTargets(String packageName) { 7869 // If the caller does not hold the BACKUP permission, it can only request a 7870 // backup of its own data. 7871 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(), 7872 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) { 7873 synchronized (mBackupParticipants) { 7874 return mBackupParticipants.get(Binder.getCallingUid()); 7875 } 7876 } 7877 7878 // a caller with full permission can ask to back up any participating app 7879 // !!! TODO: allow backup of ANY app? 7880 HashSet<String> targets = new HashSet<String>(); 7881 synchronized (mBackupParticipants) { 7882 int N = mBackupParticipants.size(); 7883 for (int i = 0; i < N; i++) { 7884 HashSet<String> s = mBackupParticipants.valueAt(i); 7885 if (s != null) { 7886 targets.addAll(s); 7887 } 7888 } 7889 } 7890 return targets; 7891 } 7892 7893 private void writeToJournalLocked(String str) { 7894 RandomAccessFile out = null; 7895 try { 7896 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir); 7897 out = new RandomAccessFile(mJournal, "rws"); 7898 out.seek(out.length()); 7899 out.writeUTF(str); 7900 } catch (IOException e) { 7901 Slog.e(TAG, "Can't write " + str + " to backup journal", e); 7902 mJournal = null; 7903 } finally { 7904 try { if (out != null) out.close(); } catch (IOException e) {} 7905 } 7906 } 7907 7908 // ----- IBackupManager binder interface ----- 7909 7910 public void dataChanged(final String packageName) { 7911 final int callingUserHandle = UserHandle.getCallingUserId(); 7912 if (callingUserHandle != UserHandle.USER_OWNER) { 7913 // App is running under a non-owner user profile. For now, we do not back 7914 // up data from secondary user profiles. 7915 // TODO: backups for all user profiles. 7916 if (MORE_DEBUG) { 7917 Slog.v(TAG, "dataChanged(" + packageName + ") ignored because it's user " 7918 + callingUserHandle); 7919 } 7920 return; 7921 } 7922 7923 final HashSet<String> targets = dataChangedTargets(packageName); 7924 if (targets == null) { 7925 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'" 7926 + " uid=" + Binder.getCallingUid()); 7927 return; 7928 } 7929 7930 mBackupHandler.post(new Runnable() { 7931 public void run() { 7932 dataChangedImpl(packageName, targets); 7933 } 7934 }); 7935 } 7936 7937 // Clear the given package's backup data from the current transport 7938 public void clearBackupData(String transportName, String packageName) { 7939 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName + " on " + transportName); 7940 PackageInfo info; 7941 try { 7942 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES); 7943 } catch (NameNotFoundException e) { 7944 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data"); 7945 return; 7946 } 7947 7948 // If the caller does not hold the BACKUP permission, it can only request a 7949 // wipe of its own backed-up data. 7950 HashSet<String> apps; 7951 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(), 7952 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) { 7953 apps = mBackupParticipants.get(Binder.getCallingUid()); 7954 } else { 7955 // a caller with full permission can ask to back up any participating app 7956 // !!! TODO: allow data-clear of ANY app? 7957 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps"); 7958 apps = new HashSet<String>(); 7959 int N = mBackupParticipants.size(); 7960 for (int i = 0; i < N; i++) { 7961 HashSet<String> s = mBackupParticipants.valueAt(i); 7962 if (s != null) { 7963 apps.addAll(s); 7964 } 7965 } 7966 } 7967 7968 // Is the given app an available participant? 7969 if (apps.contains(packageName)) { 7970 // found it; fire off the clear request 7971 if (DEBUG) Slog.v(TAG, "Found the app - running clear process"); 7972 mBackupHandler.removeMessages(MSG_RETRY_CLEAR); 7973 synchronized (mQueueLock) { 7974 final IBackupTransport transport = getTransport(transportName); 7975 if (transport == null) { 7976 // transport is currently unavailable -- make sure to retry 7977 Message msg = mBackupHandler.obtainMessage(MSG_RETRY_CLEAR, 7978 new ClearRetryParams(transportName, packageName)); 7979 mBackupHandler.sendMessageDelayed(msg, TRANSPORT_RETRY_INTERVAL); 7980 return; 7981 } 7982 long oldId = Binder.clearCallingIdentity(); 7983 mWakelock.acquire(); 7984 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR, 7985 new ClearParams(transport, info)); 7986 mBackupHandler.sendMessage(msg); 7987 Binder.restoreCallingIdentity(oldId); 7988 } 7989 } 7990 } 7991 7992 // Run a backup pass immediately for any applications that have declared 7993 // that they have pending updates. 7994 public void backupNow() { 7995 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow"); 7996 7997 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass"); 7998 synchronized (mQueueLock) { 7999 // Because the alarms we are using can jitter, and we want an *immediate* 8000 // backup pass to happen, we restart the timer beginning with "next time," 8001 // then manually fire the backup trigger intent ourselves. 8002 startBackupAlarmsLocked(BACKUP_INTERVAL); 8003 try { 8004 mRunBackupIntent.send(); 8005 } catch (PendingIntent.CanceledException e) { 8006 // should never happen 8007 Slog.e(TAG, "run-backup intent cancelled!"); 8008 } 8009 } 8010 } 8011 8012 boolean deviceIsProvisioned() { 8013 final ContentResolver resolver = mContext.getContentResolver(); 8014 return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0); 8015 } 8016 8017 // Run a *full* backup pass for the given packages, writing the resulting data stream 8018 // to the supplied file descriptor. This method is synchronous and does not return 8019 // to the caller until the backup has been completed. 8020 // 8021 // This is the variant used by 'adb backup'; it requires on-screen confirmation 8022 // by the user because it can be used to offload data over untrusted USB. 8023 @Override 8024 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, 8025 boolean includeObbs, boolean includeShared, boolean doWidgets, 8026 boolean doAllApps, boolean includeSystem, boolean compress, String[] pkgList) { 8027 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup"); 8028 8029 final int callingUserHandle = UserHandle.getCallingUserId(); 8030 if (callingUserHandle != UserHandle.USER_OWNER) { 8031 throw new IllegalStateException("Backup supported only for the device owner"); 8032 } 8033 8034 // Validate 8035 if (!doAllApps) { 8036 if (!includeShared) { 8037 // If we're backing up shared data (sdcard or equivalent), then we can run 8038 // without any supplied app names. Otherwise, we'd be doing no work, so 8039 // report the error. 8040 if (pkgList == null || pkgList.length == 0) { 8041 throw new IllegalArgumentException( 8042 "Backup requested but neither shared nor any apps named"); 8043 } 8044 } 8045 } 8046 8047 long oldId = Binder.clearCallingIdentity(); 8048 try { 8049 // Doesn't make sense to do a full backup prior to setup 8050 if (!deviceIsProvisioned()) { 8051 Slog.i(TAG, "Full backup not supported before setup"); 8052 return; 8053 } 8054 8055 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks 8056 + " obb=" + includeObbs + " shared=" + includeShared + " all=" + doAllApps 8057 + " pkgs=" + pkgList); 8058 Slog.i(TAG, "Beginning full backup..."); 8059 8060 FullBackupParams params = new FullBackupParams(fd, includeApks, includeObbs, 8061 includeShared, doWidgets, doAllApps, includeSystem, compress, pkgList); 8062 final int token = generateToken(); 8063 synchronized (mFullConfirmations) { 8064 mFullConfirmations.put(token, params); 8065 } 8066 8067 // start up the confirmation UI 8068 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token); 8069 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) { 8070 Slog.e(TAG, "Unable to launch full backup confirmation"); 8071 mFullConfirmations.delete(token); 8072 return; 8073 } 8074 8075 // make sure the screen is lit for the user interaction 8076 mPowerManager.userActivity(SystemClock.uptimeMillis(), false); 8077 8078 // start the confirmation countdown 8079 startConfirmationTimeout(token, params); 8080 8081 // wait for the backup to be performed 8082 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion..."); 8083 waitForCompletion(params); 8084 } finally { 8085 try { 8086 fd.close(); 8087 } catch (IOException e) { 8088 // just eat it 8089 } 8090 Binder.restoreCallingIdentity(oldId); 8091 Slog.d(TAG, "Full backup processing complete."); 8092 } 8093 } 8094 8095 @Override 8096 public void fullTransportBackup(String[] pkgNames) { 8097 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, 8098 "fullTransportBackup"); 8099 8100 final int callingUserHandle = UserHandle.getCallingUserId(); 8101 if (callingUserHandle != UserHandle.USER_OWNER) { 8102 throw new IllegalStateException("Restore supported only for the device owner"); 8103 } 8104 8105 if (DEBUG) { 8106 Slog.d(TAG, "fullTransportBackup()"); 8107 } 8108 8109 AtomicBoolean latch = new AtomicBoolean(false); 8110 PerformFullTransportBackupTask task = 8111 new PerformFullTransportBackupTask(null, pkgNames, false, null, latch); 8112 (new Thread(task, "full-transport-master")).start(); 8113 synchronized (latch) { 8114 try { 8115 while (latch.get() == false) { 8116 latch.wait(); 8117 } 8118 } catch (InterruptedException e) {} 8119 } 8120 if (DEBUG) { 8121 Slog.d(TAG, "Done with full transport backup."); 8122 } 8123 } 8124 8125 @Override 8126 public void fullRestore(ParcelFileDescriptor fd) { 8127 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore"); 8128 8129 final int callingUserHandle = UserHandle.getCallingUserId(); 8130 if (callingUserHandle != UserHandle.USER_OWNER) { 8131 throw new IllegalStateException("Restore supported only for the device owner"); 8132 } 8133 8134 long oldId = Binder.clearCallingIdentity(); 8135 8136 try { 8137 // Check whether the device has been provisioned -- we don't handle 8138 // full restores prior to completing the setup process. 8139 if (!deviceIsProvisioned()) { 8140 Slog.i(TAG, "Full restore not permitted before setup"); 8141 return; 8142 } 8143 8144 Slog.i(TAG, "Beginning full restore..."); 8145 8146 FullRestoreParams params = new FullRestoreParams(fd); 8147 final int token = generateToken(); 8148 synchronized (mFullConfirmations) { 8149 mFullConfirmations.put(token, params); 8150 } 8151 8152 // start up the confirmation UI 8153 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token); 8154 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) { 8155 Slog.e(TAG, "Unable to launch full restore confirmation"); 8156 mFullConfirmations.delete(token); 8157 return; 8158 } 8159 8160 // make sure the screen is lit for the user interaction 8161 mPowerManager.userActivity(SystemClock.uptimeMillis(), false); 8162 8163 // start the confirmation countdown 8164 startConfirmationTimeout(token, params); 8165 8166 // wait for the restore to be performed 8167 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion..."); 8168 waitForCompletion(params); 8169 } finally { 8170 try { 8171 fd.close(); 8172 } catch (IOException e) { 8173 Slog.w(TAG, "Error trying to close fd after full restore: " + e); 8174 } 8175 Binder.restoreCallingIdentity(oldId); 8176 Slog.i(TAG, "Full restore processing complete."); 8177 } 8178 } 8179 8180 boolean startConfirmationUi(int token, String action) { 8181 try { 8182 Intent confIntent = new Intent(action); 8183 confIntent.setClassName("com.android.backupconfirm", 8184 "com.android.backupconfirm.BackupRestoreConfirmation"); 8185 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token); 8186 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 8187 mContext.startActivity(confIntent); 8188 } catch (ActivityNotFoundException e) { 8189 return false; 8190 } 8191 return true; 8192 } 8193 8194 void startConfirmationTimeout(int token, FullParams params) { 8195 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after " 8196 + TIMEOUT_FULL_CONFIRMATION + " millis"); 8197 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT, 8198 token, 0, params); 8199 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION); 8200 } 8201 8202 void waitForCompletion(FullParams params) { 8203 synchronized (params.latch) { 8204 while (params.latch.get() == false) { 8205 try { 8206 params.latch.wait(); 8207 } catch (InterruptedException e) { /* never interrupted */ } 8208 } 8209 } 8210 } 8211 8212 void signalFullBackupRestoreCompletion(FullParams params) { 8213 synchronized (params.latch) { 8214 params.latch.set(true); 8215 params.latch.notifyAll(); 8216 } 8217 } 8218 8219 // Confirm that the previously-requested full backup/restore operation can proceed. This 8220 // is used to require a user-facing disclosure about the operation. 8221 @Override 8222 public void acknowledgeFullBackupOrRestore(int token, boolean allow, 8223 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) { 8224 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token 8225 + " allow=" + allow); 8226 8227 // TODO: possibly require not just this signature-only permission, but even 8228 // require that the specific designated confirmation-UI app uid is the caller? 8229 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore"); 8230 8231 long oldId = Binder.clearCallingIdentity(); 8232 try { 8233 8234 FullParams params; 8235 synchronized (mFullConfirmations) { 8236 params = mFullConfirmations.get(token); 8237 if (params != null) { 8238 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params); 8239 mFullConfirmations.delete(token); 8240 8241 if (allow) { 8242 final int verb = params instanceof FullBackupParams 8243 ? MSG_RUN_ADB_BACKUP 8244 : MSG_RUN_ADB_RESTORE; 8245 8246 params.observer = observer; 8247 params.curPassword = curPassword; 8248 8249 boolean isEncrypted; 8250 try { 8251 isEncrypted = (mMountService.getEncryptionState() != 8252 IMountService.ENCRYPTION_STATE_NONE); 8253 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password"); 8254 } catch (RemoteException e) { 8255 // couldn't contact the mount service; fail "safe" and assume encryption 8256 Slog.e(TAG, "Unable to contact mount service!"); 8257 isEncrypted = true; 8258 } 8259 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword; 8260 8261 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb); 8262 mWakelock.acquire(); 8263 Message msg = mBackupHandler.obtainMessage(verb, params); 8264 mBackupHandler.sendMessage(msg); 8265 } else { 8266 Slog.w(TAG, "User rejected full backup/restore operation"); 8267 // indicate completion without having actually transferred any data 8268 signalFullBackupRestoreCompletion(params); 8269 } 8270 } else { 8271 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token"); 8272 } 8273 } 8274 } finally { 8275 Binder.restoreCallingIdentity(oldId); 8276 } 8277 } 8278 8279 // Enable/disable the backup service 8280 @Override 8281 public void setBackupEnabled(boolean enable) { 8282 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 8283 "setBackupEnabled"); 8284 8285 Slog.i(TAG, "Backup enabled => " + enable); 8286 8287 long oldId = Binder.clearCallingIdentity(); 8288 try { 8289 boolean wasEnabled = mEnabled; 8290 synchronized (this) { 8291 Settings.Secure.putInt(mContext.getContentResolver(), 8292 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0); 8293 mEnabled = enable; 8294 } 8295 8296 synchronized (mQueueLock) { 8297 if (enable && !wasEnabled && mProvisioned) { 8298 // if we've just been enabled, start scheduling backup passes 8299 startBackupAlarmsLocked(BACKUP_INTERVAL); 8300 scheduleNextFullBackupJob(); 8301 } else if (!enable) { 8302 // No longer enabled, so stop running backups 8303 if (DEBUG) Slog.i(TAG, "Opting out of backup"); 8304 8305 mAlarmManager.cancel(mRunBackupIntent); 8306 8307 // This also constitutes an opt-out, so we wipe any data for 8308 // this device from the backend. We start that process with 8309 // an alarm in order to guarantee wakelock states. 8310 if (wasEnabled && mProvisioned) { 8311 // NOTE: we currently flush every registered transport, not just 8312 // the currently-active one. 8313 HashSet<String> allTransports; 8314 synchronized (mTransports) { 8315 allTransports = new HashSet<String>(mTransports.keySet()); 8316 } 8317 // build the set of transports for which we are posting an init 8318 for (String transport : allTransports) { 8319 recordInitPendingLocked(true, transport); 8320 } 8321 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 8322 mRunInitIntent); 8323 } 8324 } 8325 } 8326 } finally { 8327 Binder.restoreCallingIdentity(oldId); 8328 } 8329 } 8330 8331 // Enable/disable automatic restore of app data at install time 8332 public void setAutoRestore(boolean doAutoRestore) { 8333 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 8334 "setAutoRestore"); 8335 8336 Slog.i(TAG, "Auto restore => " + doAutoRestore); 8337 8338 synchronized (this) { 8339 Settings.Secure.putInt(mContext.getContentResolver(), 8340 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0); 8341 mAutoRestore = doAutoRestore; 8342 } 8343 } 8344 8345 // Mark the backup service as having been provisioned 8346 public void setBackupProvisioned(boolean available) { 8347 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 8348 "setBackupProvisioned"); 8349 /* 8350 * This is now a no-op; provisioning is simply the device's own setup state. 8351 */ 8352 } 8353 8354 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) { 8355 // We used to use setInexactRepeating(), but that may be linked to 8356 // backups running at :00 more often than not, creating load spikes. 8357 // Schedule at an exact time for now, and also add a bit of "fuzz". 8358 8359 Random random = new Random(); 8360 long when = System.currentTimeMillis() + delayBeforeFirstBackup + 8361 random.nextInt(FUZZ_MILLIS); 8362 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when, 8363 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent); 8364 mNextBackupPass = when; 8365 } 8366 8367 // Report whether the backup mechanism is currently enabled 8368 public boolean isBackupEnabled() { 8369 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled"); 8370 return mEnabled; // no need to synchronize just to read it 8371 } 8372 8373 // Report the name of the currently active transport 8374 public String getCurrentTransport() { 8375 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 8376 "getCurrentTransport"); 8377 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport); 8378 return mCurrentTransport; 8379 } 8380 8381 // Report all known, available backup transports 8382 public String[] listAllTransports() { 8383 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports"); 8384 8385 String[] list = null; 8386 ArrayList<String> known = new ArrayList<String>(); 8387 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) { 8388 if (entry.getValue() != null) { 8389 known.add(entry.getKey()); 8390 } 8391 } 8392 8393 if (known.size() > 0) { 8394 list = new String[known.size()]; 8395 known.toArray(list); 8396 } 8397 return list; 8398 } 8399 8400 // Select which transport to use for the next backup operation. If the given 8401 // name is not one of the available transports, no action is taken and the method 8402 // returns null. 8403 public String selectBackupTransport(String transport) { 8404 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport"); 8405 8406 synchronized (mTransports) { 8407 String prevTransport = null; 8408 if (mTransports.get(transport) != null) { 8409 prevTransport = mCurrentTransport; 8410 mCurrentTransport = transport; 8411 Settings.Secure.putString(mContext.getContentResolver(), 8412 Settings.Secure.BACKUP_TRANSPORT, transport); 8413 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport 8414 + " returning " + prevTransport); 8415 } else { 8416 Slog.w(TAG, "Attempt to select unavailable transport " + transport); 8417 } 8418 return prevTransport; 8419 } 8420 } 8421 8422 // Supply the configuration Intent for the given transport. If the name is not one 8423 // of the available transports, or if the transport does not supply any configuration 8424 // UI, the method returns null. 8425 public Intent getConfigurationIntent(String transportName) { 8426 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 8427 "getConfigurationIntent"); 8428 8429 synchronized (mTransports) { 8430 final IBackupTransport transport = mTransports.get(transportName); 8431 if (transport != null) { 8432 try { 8433 final Intent intent = transport.configurationIntent(); 8434 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent " 8435 + intent); 8436 return intent; 8437 } catch (RemoteException e) { 8438 /* fall through to return null */ 8439 } 8440 } 8441 } 8442 8443 return null; 8444 } 8445 8446 // Supply the configuration summary string for the given transport. If the name is 8447 // not one of the available transports, or if the transport does not supply any 8448 // summary / destination string, the method can return null. 8449 // 8450 // This string is used VERBATIM as the summary text of the relevant Settings item! 8451 public String getDestinationString(String transportName) { 8452 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 8453 "getDestinationString"); 8454 8455 synchronized (mTransports) { 8456 final IBackupTransport transport = mTransports.get(transportName); 8457 if (transport != null) { 8458 try { 8459 final String text = transport.currentDestinationString(); 8460 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text); 8461 return text; 8462 } catch (RemoteException e) { 8463 /* fall through to return null */ 8464 } 8465 } 8466 } 8467 8468 return null; 8469 } 8470 8471 // Supply the manage-data intent for the given transport. 8472 public Intent getDataManagementIntent(String transportName) { 8473 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 8474 "getDataManagementIntent"); 8475 8476 synchronized (mTransports) { 8477 final IBackupTransport transport = mTransports.get(transportName); 8478 if (transport != null) { 8479 try { 8480 final Intent intent = transport.dataManagementIntent(); 8481 if (MORE_DEBUG) Slog.d(TAG, "getDataManagementIntent() returning intent " 8482 + intent); 8483 return intent; 8484 } catch (RemoteException e) { 8485 /* fall through to return null */ 8486 } 8487 } 8488 } 8489 8490 return null; 8491 } 8492 8493 // Supply the menu label for affordances that fire the manage-data intent 8494 // for the given transport. 8495 public String getDataManagementLabel(String transportName) { 8496 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 8497 "getDataManagementLabel"); 8498 8499 synchronized (mTransports) { 8500 final IBackupTransport transport = mTransports.get(transportName); 8501 if (transport != null) { 8502 try { 8503 final String text = transport.dataManagementLabel(); 8504 if (MORE_DEBUG) Slog.d(TAG, "getDataManagementLabel() returning " + text); 8505 return text; 8506 } catch (RemoteException e) { 8507 /* fall through to return null */ 8508 } 8509 } 8510 } 8511 8512 return null; 8513 } 8514 8515 // Callback: a requested backup agent has been instantiated. This should only 8516 // be called from the Activity Manager. 8517 public void agentConnected(String packageName, IBinder agentBinder) { 8518 synchronized(mAgentConnectLock) { 8519 if (Binder.getCallingUid() == Process.SYSTEM_UID) { 8520 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder); 8521 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder); 8522 mConnectedAgent = agent; 8523 mConnecting = false; 8524 } else { 8525 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid() 8526 + " claiming agent connected"); 8527 } 8528 mAgentConnectLock.notifyAll(); 8529 } 8530 } 8531 8532 // Callback: a backup agent has failed to come up, or has unexpectedly quit. 8533 // If the agent failed to come up in the first place, the agentBinder argument 8534 // will be null. This should only be called from the Activity Manager. 8535 public void agentDisconnected(String packageName) { 8536 // TODO: handle backup being interrupted 8537 synchronized(mAgentConnectLock) { 8538 if (Binder.getCallingUid() == Process.SYSTEM_UID) { 8539 mConnectedAgent = null; 8540 mConnecting = false; 8541 } else { 8542 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid() 8543 + " claiming agent disconnected"); 8544 } 8545 mAgentConnectLock.notifyAll(); 8546 } 8547 } 8548 8549 // An application being installed will need a restore pass, then the Package Manager 8550 // will need to be told when the restore is finished. 8551 public void restoreAtInstall(String packageName, int token) { 8552 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 8553 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid() 8554 + " attemping install-time restore"); 8555 return; 8556 } 8557 8558 boolean skip = false; 8559 8560 long restoreSet = getAvailableRestoreToken(packageName); 8561 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName 8562 + " token=" + Integer.toHexString(token) 8563 + " restoreSet=" + Long.toHexString(restoreSet)); 8564 if (restoreSet == 0) { 8565 if (MORE_DEBUG) Slog.i(TAG, "No restore set"); 8566 skip = true; 8567 } 8568 8569 // Do we have a transport to fetch data for us? 8570 IBackupTransport transport = getTransport(mCurrentTransport); 8571 if (transport == null) { 8572 if (DEBUG) Slog.w(TAG, "No transport"); 8573 skip = true; 8574 } 8575 8576 if (!skip && mAutoRestore && mProvisioned) { 8577 try { 8578 // okay, we're going to attempt a restore of this package from this restore set. 8579 // The eventual message back into the Package Manager to run the post-install 8580 // steps for 'token' will be issued from the restore handling code. 8581 8582 // This can throw and so *must* happen before the wakelock is acquired 8583 String dirName = transport.transportDirName(); 8584 8585 // We can use a synthetic PackageInfo here because: 8586 // 1. We know it's valid, since the Package Manager supplied the name 8587 // 2. Only the packageName field will be used by the restore code 8588 PackageInfo pkg = new PackageInfo(); 8589 pkg.packageName = packageName; 8590 8591 mWakelock.acquire(); 8592 if (MORE_DEBUG) { 8593 Slog.d(TAG, "Restore at install of " + packageName); 8594 } 8595 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE); 8596 msg.obj = new RestoreParams(transport, dirName, null, 8597 restoreSet, pkg, token); 8598 mBackupHandler.sendMessage(msg); 8599 } catch (RemoteException e) { 8600 // Binding to the transport broke; back off and proceed with the installation. 8601 Slog.e(TAG, "Unable to contact transport"); 8602 skip = true; 8603 } 8604 } 8605 8606 if (skip) { 8607 // Auto-restore disabled or no way to attempt a restore; just tell the Package 8608 // Manager to proceed with the post-install handling for this package. 8609 if (DEBUG) Slog.v(TAG, "Skipping"); 8610 try { 8611 mPackageManagerBinder.finishPackageInstall(token); 8612 } catch (RemoteException e) { /* can't happen */ } 8613 } 8614 } 8615 8616 // Hand off a restore session 8617 public IRestoreSession beginRestoreSession(String packageName, String transport) { 8618 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName 8619 + " transport=" + transport); 8620 8621 boolean needPermission = true; 8622 if (transport == null) { 8623 transport = mCurrentTransport; 8624 8625 if (packageName != null) { 8626 PackageInfo app = null; 8627 try { 8628 app = mPackageManager.getPackageInfo(packageName, 0); 8629 } catch (NameNotFoundException nnf) { 8630 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName); 8631 throw new IllegalArgumentException("Package " + packageName + " not found"); 8632 } 8633 8634 if (app.applicationInfo.uid == Binder.getCallingUid()) { 8635 // So: using the current active transport, and the caller has asked 8636 // that its own package will be restored. In this narrow use case 8637 // we do not require the caller to hold the permission. 8638 needPermission = false; 8639 } 8640 } 8641 } 8642 8643 if (needPermission) { 8644 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 8645 "beginRestoreSession"); 8646 } else { 8647 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed"); 8648 } 8649 8650 synchronized(this) { 8651 if (mActiveRestoreSession != null) { 8652 Slog.d(TAG, "Restore session requested but one already active"); 8653 return null; 8654 } 8655 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport); 8656 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL); 8657 } 8658 return mActiveRestoreSession; 8659 } 8660 8661 void clearRestoreSession(ActiveRestoreSession currentSession) { 8662 synchronized(this) { 8663 if (currentSession != mActiveRestoreSession) { 8664 Slog.e(TAG, "ending non-current restore session"); 8665 } else { 8666 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout"); 8667 mActiveRestoreSession = null; 8668 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT); 8669 } 8670 } 8671 } 8672 8673 // Note that a currently-active backup agent has notified us that it has 8674 // completed the given outstanding asynchronous backup/restore operation. 8675 @Override 8676 public void opComplete(int token) { 8677 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token)); 8678 Operation op = null; 8679 synchronized (mCurrentOpLock) { 8680 op = mCurrentOperations.get(token); 8681 if (op != null) { 8682 op.state = OP_ACKNOWLEDGED; 8683 } 8684 mCurrentOpLock.notifyAll(); 8685 } 8686 8687 // The completion callback, if any, is invoked on the handler 8688 if (op != null && op.callback != null) { 8689 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback); 8690 mBackupHandler.sendMessage(msg); 8691 } 8692 } 8693 8694 // ----- Restore session ----- 8695 8696 class ActiveRestoreSession extends IRestoreSession.Stub { 8697 private static final String TAG = "RestoreSession"; 8698 8699 private String mPackageName; 8700 private IBackupTransport mRestoreTransport = null; 8701 RestoreSet[] mRestoreSets = null; 8702 boolean mEnded = false; 8703 8704 ActiveRestoreSession(String packageName, String transport) { 8705 mPackageName = packageName; 8706 mRestoreTransport = getTransport(transport); 8707 } 8708 8709 // --- Binder interface --- 8710 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) { 8711 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 8712 "getAvailableRestoreSets"); 8713 if (observer == null) { 8714 throw new IllegalArgumentException("Observer must not be null"); 8715 } 8716 8717 if (mEnded) { 8718 throw new IllegalStateException("Restore session already ended"); 8719 } 8720 8721 long oldId = Binder.clearCallingIdentity(); 8722 try { 8723 if (mRestoreTransport == null) { 8724 Slog.w(TAG, "Null transport getting restore sets"); 8725 return -1; 8726 } 8727 // spin off the transport request to our service thread 8728 mWakelock.acquire(); 8729 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS, 8730 new RestoreGetSetsParams(mRestoreTransport, this, observer)); 8731 mBackupHandler.sendMessage(msg); 8732 return 0; 8733 } catch (Exception e) { 8734 Slog.e(TAG, "Error in getAvailableRestoreSets", e); 8735 return -1; 8736 } finally { 8737 Binder.restoreCallingIdentity(oldId); 8738 } 8739 } 8740 8741 public synchronized int restoreAll(long token, IRestoreObserver observer) { 8742 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 8743 "performRestore"); 8744 8745 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token) 8746 + " observer=" + observer); 8747 8748 if (mEnded) { 8749 throw new IllegalStateException("Restore session already ended"); 8750 } 8751 8752 if (mRestoreTransport == null || mRestoreSets == null) { 8753 Slog.e(TAG, "Ignoring restoreAll() with no restore set"); 8754 return -1; 8755 } 8756 8757 if (mPackageName != null) { 8758 Slog.e(TAG, "Ignoring restoreAll() on single-package session"); 8759 return -1; 8760 } 8761 8762 String dirName; 8763 try { 8764 dirName = mRestoreTransport.transportDirName(); 8765 } catch (RemoteException e) { 8766 // Transport went AWOL; fail. 8767 Slog.e(TAG, "Unable to contact transport for restore"); 8768 return -1; 8769 } 8770 8771 synchronized (mQueueLock) { 8772 for (int i = 0; i < mRestoreSets.length; i++) { 8773 if (token == mRestoreSets[i].token) { 8774 long oldId = Binder.clearCallingIdentity(); 8775 mWakelock.acquire(); 8776 if (MORE_DEBUG) { 8777 Slog.d(TAG, "restoreAll() kicking off"); 8778 } 8779 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE); 8780 msg.obj = new RestoreParams(mRestoreTransport, dirName, 8781 observer, token); 8782 mBackupHandler.sendMessage(msg); 8783 Binder.restoreCallingIdentity(oldId); 8784 return 0; 8785 } 8786 } 8787 } 8788 8789 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found"); 8790 return -1; 8791 } 8792 8793 // Restores of more than a single package are treated as 'system' restores 8794 public synchronized int restoreSome(long token, IRestoreObserver observer, 8795 String[] packages) { 8796 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, 8797 "performRestore"); 8798 8799 if (DEBUG) { 8800 StringBuilder b = new StringBuilder(128); 8801 b.append("restoreSome token="); 8802 b.append(Long.toHexString(token)); 8803 b.append(" observer="); 8804 b.append(observer.toString()); 8805 b.append(" packages="); 8806 if (packages == null) { 8807 b.append("null"); 8808 } else { 8809 b.append('{'); 8810 boolean first = true; 8811 for (String s : packages) { 8812 if (!first) { 8813 b.append(", "); 8814 } else first = false; 8815 b.append(s); 8816 } 8817 b.append('}'); 8818 } 8819 Slog.d(TAG, b.toString()); 8820 } 8821 8822 if (mEnded) { 8823 throw new IllegalStateException("Restore session already ended"); 8824 } 8825 8826 if (mRestoreTransport == null || mRestoreSets == null) { 8827 Slog.e(TAG, "Ignoring restoreAll() with no restore set"); 8828 return -1; 8829 } 8830 8831 if (mPackageName != null) { 8832 Slog.e(TAG, "Ignoring restoreAll() on single-package session"); 8833 return -1; 8834 } 8835 8836 String dirName; 8837 try { 8838 dirName = mRestoreTransport.transportDirName(); 8839 } catch (RemoteException e) { 8840 // Transport went AWOL; fail. 8841 Slog.e(TAG, "Unable to contact transport for restore"); 8842 return -1; 8843 } 8844 8845 synchronized (mQueueLock) { 8846 for (int i = 0; i < mRestoreSets.length; i++) { 8847 if (token == mRestoreSets[i].token) { 8848 long oldId = Binder.clearCallingIdentity(); 8849 mWakelock.acquire(); 8850 if (MORE_DEBUG) { 8851 Slog.d(TAG, "restoreSome() of " + packages.length + " packages"); 8852 } 8853 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE); 8854 msg.obj = new RestoreParams(mRestoreTransport, dirName, observer, token, 8855 packages, packages.length > 1); 8856 mBackupHandler.sendMessage(msg); 8857 Binder.restoreCallingIdentity(oldId); 8858 return 0; 8859 } 8860 } 8861 } 8862 8863 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found"); 8864 return -1; 8865 } 8866 8867 public synchronized int restorePackage(String packageName, IRestoreObserver observer) { 8868 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer); 8869 8870 if (mEnded) { 8871 throw new IllegalStateException("Restore session already ended"); 8872 } 8873 8874 if (mPackageName != null) { 8875 if (! mPackageName.equals(packageName)) { 8876 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName 8877 + " on session for package " + mPackageName); 8878 return -1; 8879 } 8880 } 8881 8882 PackageInfo app = null; 8883 try { 8884 app = mPackageManager.getPackageInfo(packageName, 0); 8885 } catch (NameNotFoundException nnf) { 8886 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName); 8887 return -1; 8888 } 8889 8890 // If the caller is not privileged and is not coming from the target 8891 // app's uid, throw a permission exception back to the caller. 8892 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP, 8893 Binder.getCallingPid(), Binder.getCallingUid()); 8894 if ((perm == PackageManager.PERMISSION_DENIED) && 8895 (app.applicationInfo.uid != Binder.getCallingUid())) { 8896 Slog.w(TAG, "restorePackage: bad packageName=" + packageName 8897 + " or calling uid=" + Binder.getCallingUid()); 8898 throw new SecurityException("No permission to restore other packages"); 8899 } 8900 8901 // So far so good; we're allowed to try to restore this package. Now 8902 // check whether there is data for it in the current dataset, falling back 8903 // to the ancestral dataset if not. 8904 long token = getAvailableRestoreToken(packageName); 8905 8906 // If we didn't come up with a place to look -- no ancestral dataset and 8907 // the app has never been backed up from this device -- there's nothing 8908 // to do but return failure. 8909 if (token == 0) { 8910 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring"); 8911 return -1; 8912 } 8913 8914 String dirName; 8915 try { 8916 dirName = mRestoreTransport.transportDirName(); 8917 } catch (RemoteException e) { 8918 // Transport went AWOL; fail. 8919 Slog.e(TAG, "Unable to contact transport for restore"); 8920 return -1; 8921 } 8922 8923 // Ready to go: enqueue the restore request and claim success 8924 long oldId = Binder.clearCallingIdentity(); 8925 mWakelock.acquire(); 8926 if (MORE_DEBUG) { 8927 Slog.d(TAG, "restorePackage() : " + packageName); 8928 } 8929 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE); 8930 msg.obj = new RestoreParams(mRestoreTransport, dirName, 8931 observer, token, app, 0); 8932 mBackupHandler.sendMessage(msg); 8933 Binder.restoreCallingIdentity(oldId); 8934 return 0; 8935 } 8936 8937 // Posted to the handler to tear down a restore session in a cleanly synchronized way 8938 class EndRestoreRunnable implements Runnable { 8939 BackupManagerService mBackupManager; 8940 ActiveRestoreSession mSession; 8941 8942 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) { 8943 mBackupManager = manager; 8944 mSession = session; 8945 } 8946 8947 public void run() { 8948 // clean up the session's bookkeeping 8949 synchronized (mSession) { 8950 try { 8951 if (mSession.mRestoreTransport != null) { 8952 mSession.mRestoreTransport.finishRestore(); 8953 } 8954 } catch (Exception e) { 8955 Slog.e(TAG, "Error in finishRestore", e); 8956 } finally { 8957 mSession.mRestoreTransport = null; 8958 mSession.mEnded = true; 8959 } 8960 } 8961 8962 // clean up the BackupManagerImpl side of the bookkeeping 8963 // and cancel any pending timeout message 8964 mBackupManager.clearRestoreSession(mSession); 8965 } 8966 } 8967 8968 public synchronized void endRestoreSession() { 8969 if (DEBUG) Slog.d(TAG, "endRestoreSession"); 8970 8971 if (mEnded) { 8972 throw new IllegalStateException("Restore session already ended"); 8973 } 8974 8975 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this)); 8976 } 8977 } 8978 8979 @Override 8980 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 8981 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG); 8982 8983 long identityToken = Binder.clearCallingIdentity(); 8984 try { 8985 if (args != null) { 8986 for (String arg : args) { 8987 if ("-h".equals(arg)) { 8988 pw.println("'dumpsys backup' optional arguments:"); 8989 pw.println(" -h : this help text"); 8990 pw.println(" a[gents] : dump information about defined backup agents"); 8991 return; 8992 } else if ("agents".startsWith(arg)) { 8993 dumpAgents(pw); 8994 return; 8995 } 8996 } 8997 } 8998 dumpInternal(pw); 8999 } finally { 9000 Binder.restoreCallingIdentity(identityToken); 9001 } 9002 } 9003 9004 private void dumpAgents(PrintWriter pw) { 9005 List<PackageInfo> agentPackages = allAgentPackages(); 9006 pw.println("Defined backup agents:"); 9007 for (PackageInfo pkg : agentPackages) { 9008 pw.print(" "); 9009 pw.print(pkg.packageName); pw.println(':'); 9010 pw.print(" "); pw.println(pkg.applicationInfo.backupAgentName); 9011 } 9012 } 9013 9014 private void dumpInternal(PrintWriter pw) { 9015 synchronized (mQueueLock) { 9016 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled") 9017 + " / " + (!mProvisioned ? "not " : "") + "provisioned / " 9018 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init"); 9019 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled")); 9020 if (mBackupRunning) pw.println("Backup currently running"); 9021 pw.println("Last backup pass started: " + mLastBackupPass 9022 + " (now = " + System.currentTimeMillis() + ')'); 9023 pw.println(" next scheduled: " + mNextBackupPass); 9024 9025 pw.println("Available transports:"); 9026 for (String t : listAllTransports()) { 9027 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t); 9028 try { 9029 IBackupTransport transport = getTransport(t); 9030 File dir = new File(mBaseStateDir, transport.transportDirName()); 9031 pw.println(" destination: " + transport.currentDestinationString()); 9032 pw.println(" intent: " + transport.configurationIntent()); 9033 for (File f : dir.listFiles()) { 9034 pw.println(" " + f.getName() + " - " + f.length() + " state bytes"); 9035 } 9036 } catch (Exception e) { 9037 Slog.e(TAG, "Error in transport", e); 9038 pw.println(" Error: " + e); 9039 } 9040 } 9041 9042 pw.println("Pending init: " + mPendingInits.size()); 9043 for (String s : mPendingInits) { 9044 pw.println(" " + s); 9045 } 9046 9047 if (DEBUG_BACKUP_TRACE) { 9048 synchronized (mBackupTrace) { 9049 if (!mBackupTrace.isEmpty()) { 9050 pw.println("Most recent backup trace:"); 9051 for (String s : mBackupTrace) { 9052 pw.println(" " + s); 9053 } 9054 } 9055 } 9056 } 9057 9058 int N = mBackupParticipants.size(); 9059 pw.println("Participants:"); 9060 for (int i=0; i<N; i++) { 9061 int uid = mBackupParticipants.keyAt(i); 9062 pw.print(" uid: "); 9063 pw.println(uid); 9064 HashSet<String> participants = mBackupParticipants.valueAt(i); 9065 for (String app: participants) { 9066 pw.println(" " + app); 9067 } 9068 } 9069 9070 pw.println("Ancestral packages: " 9071 + (mAncestralPackages == null ? "none" : mAncestralPackages.size())); 9072 if (mAncestralPackages != null) { 9073 for (String pkg : mAncestralPackages) { 9074 pw.println(" " + pkg); 9075 } 9076 } 9077 9078 pw.println("Ever backed up: " + mEverStoredApps.size()); 9079 for (String pkg : mEverStoredApps) { 9080 pw.println(" " + pkg); 9081 } 9082 9083 pw.println("Pending key/value backup: " + mPendingBackups.size()); 9084 for (BackupRequest req : mPendingBackups.values()) { 9085 pw.println(" " + req); 9086 } 9087 9088 pw.println("Full backup queue:" + mFullBackupQueue.size()); 9089 for (FullBackupEntry entry : mFullBackupQueue) { 9090 pw.print(" "); pw.print(entry.lastBackup); 9091 pw.print(" : "); pw.println(entry.packageName); 9092 } 9093 } 9094 } 9095} 9096