OSDN Git Service

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