blob: 2e3d6dd44937f8bd3b73f175295e0b9e8d1e5b89 [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070021import android.app.AppGlobals;
Christopher Tate181fafa2009-05-14 11:12:14 -070022import android.app.IActivityManager;
23import android.app.IApplicationThread;
24import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070025import android.app.PendingIntent;
Christopher Tate79ec80d2011-06-24 14:58:49 -070026import android.app.backup.BackupAgent;
Christopher Tate4a627c72011-04-01 14:43:32 -070027import android.app.backup.BackupDataOutput;
28import android.app.backup.FullBackup;
Jason parksa3cdaa52011-01-13 14:15:43 -060029import android.app.backup.RestoreSet;
Christopher Tate45281862010-03-05 15:46:30 -080030import android.app.backup.IBackupManager;
Christopher Tate4a627c72011-04-01 14:43:32 -070031import android.app.backup.IFullBackupRestoreObserver;
Christopher Tate45281862010-03-05 15:46:30 -080032import android.app.backup.IRestoreObserver;
33import android.app.backup.IRestoreSession;
Christopher Tate4a627c72011-04-01 14:43:32 -070034import android.content.ActivityNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070035import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070036import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070037import android.content.Context;
38import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070039import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070040import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070041import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070042import android.content.pm.IPackageDataObserver;
Christopher Tatea858cb02011-06-03 12:27:51 -070043import android.content.pm.IPackageDeleteObserver;
Christopher Tate75a99702011-05-18 16:28:19 -070044import android.content.pm.IPackageInstallObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080045import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070046import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070047import android.content.pm.PackageManager;
Jason parks1125d782011-01-12 09:47:26 -060048import android.content.pm.Signature;
Jason parksa3cdaa52011-01-13 14:15:43 -060049import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070050import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.os.Binder;
Christopher Tate75a99702011-05-18 16:28:19 -070052import android.os.Build;
Christopher Tate3799bc22009-05-06 16:13:56 -070053import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070054import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070055import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080056import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070057import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080058import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070059import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070060import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070061import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070062import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070063import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070064import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070065import android.os.WorkSource;
Oscar Montemayora8529f62009-11-18 10:14:20 -080066import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070067import android.util.EventLog;
Christopher Tate79ec80d2011-06-24 14:58:49 -070068import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080069import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070070import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080071import android.util.SparseIntArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070072import android.util.StringBuilderPrinter;
73
Jason parksa3cdaa52011-01-13 14:15:43 -060074import com.android.internal.backup.BackupConstants;
75import com.android.internal.backup.IBackupTransport;
76import com.android.internal.backup.LocalTransport;
77import com.android.server.PackageManagerBackupAgent.Metadata;
78
Christopher Tate2efd2db2011-07-19 16:32:49 -070079import java.io.BufferedInputStream;
80import java.io.BufferedOutputStream;
81import java.io.ByteArrayOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -070082import java.io.DataInputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070083import java.io.DataOutputStream;
Christopher Tatecde87f42009-06-12 12:55:53 -070084import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070085import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070086import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070087import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080088import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070089import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070090import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070091import java.io.InputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070092import java.io.OutputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070093import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070094import java.io.RandomAccessFile;
Christopher Tate2efd2db2011-07-19 16:32:49 -070095import java.security.InvalidAlgorithmParameterException;
96import java.security.InvalidKeyException;
97import java.security.Key;
98import java.security.NoSuchAlgorithmException;
99import java.security.SecureRandom;
100import java.security.spec.InvalidKeySpecException;
101import java.security.spec.KeySpec;
Christopher Tate75a99702011-05-18 16:28:19 -0700102import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -0400103import java.util.ArrayList;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700104import java.util.Arrays;
Christopher Tate75a99702011-05-18 16:28:19 -0700105import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -0400106import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -0700107import java.util.HashSet;
108import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -0700109import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -0700110import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800111import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -0700112import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate7926a692011-07-11 11:31:57 -0700113import java.util.zip.Deflater;
114import java.util.zip.DeflaterOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -0700115import java.util.zip.InflaterInputStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700116
Christopher Tate2efd2db2011-07-19 16:32:49 -0700117import javax.crypto.BadPaddingException;
118import javax.crypto.Cipher;
119import javax.crypto.CipherInputStream;
120import javax.crypto.CipherOutputStream;
121import javax.crypto.IllegalBlockSizeException;
122import javax.crypto.NoSuchPaddingException;
123import javax.crypto.SecretKey;
124import javax.crypto.SecretKeyFactory;
125import javax.crypto.spec.IvParameterSpec;
126import javax.crypto.spec.PBEKeySpec;
127import javax.crypto.spec.SecretKeySpec;
128
Christopher Tate487529a2009-04-29 14:03:25 -0700129class BackupManagerService extends IBackupManager.Stub {
130 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -0700131 private static final boolean DEBUG = true;
Christopher Tatec58efa62011-08-01 19:20:14 -0700132 private static final boolean MORE_DEBUG = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700133
134 // Name and current contents version of the full-backup manifest file
135 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
136 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700137 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
138 static final int BACKUP_FILE_VERSION = 1;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700139 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
Christopher Tateaa088442009-06-16 18:25:46 -0700140
Christopher Tate49401dd2009-07-01 12:34:29 -0700141 // How often we perform a backup pass. Privileged external callers can
142 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700143 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700144
Dan Egnorc1c49c02009-10-30 17:35:39 -0700145 // Random variation in backup scheduling time to avoid server load spikes
146 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
147
Christopher Tate8031a3d2009-07-06 16:36:05 -0700148 // The amount of time between the initial provisioning of the device and
149 // the first backup pass.
150 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
151
Christopher Tate45281862010-03-05 15:46:30 -0800152 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
153 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
154 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700155 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700156 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700157 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700158 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700159 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700160 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
161 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800162 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700163 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
164 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700165
166 // Timeout interval for deciding that a bind or clear-data has taken too long
167 static final long TIMEOUT_INTERVAL = 10 * 1000;
168
Christopher Tate44a27902010-01-27 17:15:49 -0800169 // Timeout intervals for agent backup & restore operations
170 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700171 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700172 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800173 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
174
Christopher Tate2efd2db2011-07-19 16:32:49 -0700175 // User confirmation timeout for a full backup/restore operation. It's this long in
176 // order to give them time to enter the backup password.
177 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700178
Christopher Tate487529a2009-04-29 14:03:25 -0700179 private Context mContext;
180 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800181 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700182 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700183 private PowerManager mPowerManager;
184 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800185 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700186
Christopher Tate73e02522009-07-15 14:18:26 -0700187 boolean mEnabled; // access to this is synchronized on 'this'
188 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800189 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700190 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800191 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
192 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700193 PendingIntent mRunBackupIntent, mRunInitIntent;
194 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700195 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700196 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700197 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700198 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700199 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700200 public ApplicationInfo appInfo;
Christopher Tateaa088442009-06-16 18:25:46 -0700201
Christopher Tate4a627c72011-04-01 14:43:32 -0700202 BackupRequest(ApplicationInfo app) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700203 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700204 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700205
206 public String toString() {
Christopher Tate4a627c72011-04-01 14:43:32 -0700207 return "BackupRequest{app=" + appInfo + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700208 }
Christopher Tate46758122009-05-06 11:22:00 -0700209 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800210 // Backups that we haven't started yet. Keys are package names.
211 HashMap<String,BackupRequest> mPendingBackups
212 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700213
214 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700215 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700216
217 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700218 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700219
Christopher Tate043dadc2009-06-02 16:11:00 -0700220 // The thread performing the sequence of queued backups binds to each app's agent
221 // in succession. Bind notifications are asynchronously delivered through the
222 // Activity Manager; use this lock object to signal when a requested binding has
223 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700224 final Object mAgentConnectLock = new Object();
225 IBackupAgent mConnectedAgent;
226 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700227 volatile long mLastBackupPass;
228 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700229
Christopher Tate55f931a2009-09-29 17:17:34 -0700230 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700231 final Object mClearDataLock = new Object();
232 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700233
Christopher Tate91717492009-06-26 21:07:13 -0700234 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700235 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700236 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700237 String mCurrentTransport;
238 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800239 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700240
Christopher Tate2d449afe2010-03-29 19:14:24 -0700241 class RestoreGetSetsParams {
242 public IBackupTransport transport;
243 public ActiveRestoreSession session;
244 public IRestoreObserver observer;
245
246 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
247 IRestoreObserver _observer) {
248 transport = _transport;
249 session = _session;
250 observer = _observer;
251 }
252 }
253
Christopher Tate73e02522009-07-15 14:18:26 -0700254 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700255 public IBackupTransport transport;
256 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700257 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800258 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800259 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700260 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700261 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800262
263 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700264 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800265 transport = _transport;
266 observer = _obs;
267 token = _token;
268 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800269 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700270 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700271 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800272 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700273
Chris Tate249345b2010-10-29 12:57:04 -0700274 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
275 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700276 transport = _transport;
277 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700278 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800279 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800280 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700281 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700282 filterSet = null;
283 }
284
285 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
286 String[] _filterSet, boolean _needFullBackup) {
287 transport = _transport;
288 observer = _obs;
289 token = _token;
290 pkgInfo = null;
291 pmToken = 0;
292 needFullBackup = _needFullBackup;
293 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700294 }
295 }
296
Christopher Tate73e02522009-07-15 14:18:26 -0700297 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700298 public IBackupTransport transport;
299 public PackageInfo packageInfo;
300
301 ClearParams(IBackupTransport _transport, PackageInfo _info) {
302 transport = _transport;
303 packageInfo = _info;
304 }
305 }
306
Christopher Tate4a627c72011-04-01 14:43:32 -0700307 class FullParams {
308 public ParcelFileDescriptor fd;
309 public final AtomicBoolean latch;
310 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700311 public String curPassword; // filled in by the confirmation step
312 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700313
314 FullParams() {
315 latch = new AtomicBoolean(false);
316 }
317 }
318
319 class FullBackupParams extends FullParams {
320 public boolean includeApks;
321 public boolean includeShared;
322 public boolean allApps;
323 public String[] packages;
324
325 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
326 boolean doAllApps, String[] pkgList) {
327 fd = output;
328 includeApks = saveApks;
329 includeShared = saveShared;
330 allApps = doAllApps;
331 packages = pkgList;
332 }
333 }
334
335 class FullRestoreParams extends FullParams {
336 FullRestoreParams(ParcelFileDescriptor input) {
337 fd = input;
338 }
339 }
340
Christopher Tate44a27902010-01-27 17:15:49 -0800341 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
342 // token is the index of the entry in the pending-operations list.
343 static final int OP_PENDING = 0;
344 static final int OP_ACKNOWLEDGED = 1;
345 static final int OP_TIMEOUT = -1;
346
347 final SparseIntArray mCurrentOperations = new SparseIntArray();
348 final Object mCurrentOpLock = new Object();
349 final Random mTokenGenerator = new Random();
350
Christopher Tate4a627c72011-04-01 14:43:32 -0700351 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
352
Christopher Tate5cb400b2009-06-25 16:03:14 -0700353 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700354 File mBaseStateDir;
355 File mDataDir;
356 File mJournalDir;
357 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700358
Christopher Tate2efd2db2011-07-19 16:32:49 -0700359 // Backup password, if any, and the file where it's saved. What is stored is not the
360 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
361 // persisted) salt. Validation is performed by running the challenge text through the
362 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
363 // the saved hash string, then the challenge text matches the originally supplied
364 // password text.
365 private final SecureRandom mRng = new SecureRandom();
366 private String mPasswordHash;
367 private File mPasswordHashFile;
368 private byte[] mPasswordSalt;
369
370 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
371 static final int PBKDF2_HASH_ROUNDS = 10000;
372 static final int PBKDF2_KEY_SIZE = 256; // bits
373 static final int PBKDF2_SALT_SIZE = 512; // bits
374 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
375
Christopher Tate84725812010-02-04 15:52:40 -0800376 // Keep a log of all the apps we've ever backed up, and what the
377 // dataset tokens are for both the current backup dataset and
378 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700379 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700380 HashSet<String> mEverStoredApps = new HashSet<String>();
381
Christopher Tateb49ceb32010-02-08 16:22:24 -0800382 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800383 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800384 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800385 long mAncestralToken = 0;
386 long mCurrentToken = 0;
387
Christopher Tate4cc86e12009-09-21 19:36:51 -0700388 // Persistently track the need to do a full init
389 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
390 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700391
Christopher Tate4a627c72011-04-01 14:43:32 -0700392 // Utility: build a new random integer token
393 int generateToken() {
394 int token;
395 do {
396 synchronized (mTokenGenerator) {
397 token = mTokenGenerator.nextInt();
398 }
399 } while (token < 0);
400 return token;
401 }
402
Christopher Tate44a27902010-01-27 17:15:49 -0800403 // ----- Asynchronous backup/restore handler thread -----
404
405 private class BackupHandler extends Handler {
406 public BackupHandler(Looper looper) {
407 super(looper);
408 }
409
410 public void handleMessage(Message msg) {
411
412 switch (msg.what) {
413 case MSG_RUN_BACKUP:
414 {
415 mLastBackupPass = System.currentTimeMillis();
416 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
417
418 IBackupTransport transport = getTransport(mCurrentTransport);
419 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800420 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800421 mWakelock.release();
422 break;
423 }
424
425 // snapshot the pending-backup set and work on that
426 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800427 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800428 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800429 // Do we have any work to do? Construct the work queue
430 // then release the synchronization lock to actually run
431 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800432 if (mPendingBackups.size() > 0) {
433 for (BackupRequest b: mPendingBackups.values()) {
434 queue.add(b);
435 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800436 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800437 mPendingBackups.clear();
438
439 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800440 mJournal = null;
441
Christopher Tate44a27902010-01-27 17:15:49 -0800442 }
443 }
Christopher Tatec61da312010-02-05 10:41:27 -0800444
445 if (queue.size() > 0) {
446 // At this point, we have started a new journal file, and the old
447 // file identity is being passed to the backup processing thread.
448 // When it completes successfully, that old journal file will be
449 // deleted. If we crash prior to that, the old journal is parsed
450 // at next boot and the journaled requests fulfilled.
451 (new PerformBackupTask(transport, queue, oldJournal)).run();
452 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800453 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800454 mWakelock.release();
455 }
Christopher Tate44a27902010-01-27 17:15:49 -0800456 break;
457 }
458
459 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700460 {
461 FullBackupParams params = (FullBackupParams)msg.obj;
462 (new PerformFullBackupTask(params.fd, params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700463 params.includeShared, params.curPassword, params.encryptPassword,
464 params.allApps, params.packages, params.latch)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800465 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700466 }
Christopher Tate44a27902010-01-27 17:15:49 -0800467
468 case MSG_RUN_RESTORE:
469 {
470 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800471 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800472 (new PerformRestoreTask(params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700473 params.token, params.pkgInfo, params.pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -0700474 params.needFullBackup, params.filterSet)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800475 break;
476 }
477
Christopher Tate75a99702011-05-18 16:28:19 -0700478 case MSG_RUN_FULL_RESTORE:
479 {
480 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tate728a1c42011-07-28 18:03:03 -0700481 (new PerformFullRestoreTask(params.fd, params.curPassword, params.encryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -0700482 params.observer, params.latch)).run();
Christopher Tate75a99702011-05-18 16:28:19 -0700483 break;
484 }
485
Christopher Tate44a27902010-01-27 17:15:49 -0800486 case MSG_RUN_CLEAR:
487 {
488 ClearParams params = (ClearParams)msg.obj;
489 (new PerformClearTask(params.transport, params.packageInfo)).run();
490 break;
491 }
492
493 case MSG_RUN_INITIALIZE:
494 {
495 HashSet<String> queue;
496
497 // Snapshot the pending-init queue and work on that
498 synchronized (mQueueLock) {
499 queue = new HashSet<String>(mPendingInits);
500 mPendingInits.clear();
501 }
502
503 (new PerformInitializeTask(queue)).run();
504 break;
505 }
506
Christopher Tate2d449afe2010-03-29 19:14:24 -0700507 case MSG_RUN_GET_RESTORE_SETS:
508 {
509 // Like other async operations, this is entered with the wakelock held
510 RestoreSet[] sets = null;
511 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
512 try {
513 sets = params.transport.getAvailableRestoreSets();
514 // cache the result in the active session
515 synchronized (params.session) {
516 params.session.mRestoreSets = sets;
517 }
518 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
519 } catch (Exception e) {
520 Slog.e(TAG, "Error from transport getting set list");
521 } finally {
522 if (params.observer != null) {
523 try {
524 params.observer.restoreSetsAvailable(sets);
525 } catch (RemoteException re) {
526 Slog.e(TAG, "Unable to report listing to observer");
527 } catch (Exception e) {
528 Slog.e(TAG, "Restore observer threw", e);
529 }
530 }
531
Christopher Tate2a935092011-03-03 17:30:32 -0800532 // Done: reset the session timeout clock
533 removeMessages(MSG_RESTORE_TIMEOUT);
534 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
535
Christopher Tate2d449afe2010-03-29 19:14:24 -0700536 mWakelock.release();
537 }
538 break;
539 }
540
Christopher Tate44a27902010-01-27 17:15:49 -0800541 case MSG_TIMEOUT:
542 {
543 synchronized (mCurrentOpLock) {
544 final int token = msg.arg1;
545 int state = mCurrentOperations.get(token, OP_TIMEOUT);
546 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800547 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800548 mCurrentOperations.put(token, OP_TIMEOUT);
549 }
550 mCurrentOpLock.notifyAll();
551 }
552 break;
553 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800554
555 case MSG_RESTORE_TIMEOUT:
556 {
557 synchronized (BackupManagerService.this) {
558 if (mActiveRestoreSession != null) {
559 // Client app left the restore session dangling. We know that it
560 // can't be in the middle of an actual restore operation because
561 // those are executed serially on this same handler thread. Clean
562 // up now.
563 Slog.w(TAG, "Restore session timed out; aborting");
564 post(mActiveRestoreSession.new EndRestoreRunnable(
565 BackupManagerService.this, mActiveRestoreSession));
566 }
567 }
568 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700569
570 case MSG_FULL_CONFIRMATION_TIMEOUT:
571 {
572 synchronized (mFullConfirmations) {
573 FullParams params = mFullConfirmations.get(msg.arg1);
574 if (params != null) {
575 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
576
577 // Release the waiter; timeout == completion
578 signalFullBackupRestoreCompletion(params);
579
580 // Remove the token from the set
581 mFullConfirmations.delete(msg.arg1);
582
583 // Report a timeout to the observer, if any
584 if (params.observer != null) {
585 try {
586 params.observer.onTimeout();
587 } catch (RemoteException e) {
588 /* don't care if the app has gone away */
589 }
590 }
591 } else {
592 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
593 }
594 }
595 break;
596 }
Christopher Tate44a27902010-01-27 17:15:49 -0800597 }
598 }
599 }
600
601 // ----- Main service implementation -----
602
Christopher Tate487529a2009-04-29 14:03:25 -0700603 public BackupManagerService(Context context) {
604 mContext = context;
605 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700606 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700607 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700608
Christopher Tateb6787f22009-07-02 17:40:45 -0700609 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
610 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
611
Christopher Tate44a27902010-01-27 17:15:49 -0800612 mBackupManagerBinder = asInterface(asBinder());
613
614 // spin up the backup/restore handler thread
615 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
616 mHandlerThread.start();
617 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
618
Christopher Tate22b87872009-05-04 16:41:53 -0700619 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700620 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700621 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700622 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700623 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800624 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800625 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800626 // If Encrypted file systems is enabled or disabled, this call will return the
627 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600628 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800629 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700630 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700631
Christopher Tate2efd2db2011-07-19 16:32:49 -0700632 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
633 if (mPasswordHashFile.exists()) {
634 FileInputStream fin = null;
635 DataInputStream in = null;
636 try {
637 fin = new FileInputStream(mPasswordHashFile);
638 in = new DataInputStream(new BufferedInputStream(fin));
639 // integer length of the salt array, followed by the salt,
640 // then the hex pw hash string
641 int saltLen = in.readInt();
642 byte[] salt = new byte[saltLen];
643 in.readFully(salt);
644 mPasswordHash = in.readUTF();
645 mPasswordSalt = salt;
646 } catch (IOException e) {
647 Slog.e(TAG, "Unable to read saved backup pw hash");
648 } finally {
649 try {
650 if (in != null) in.close();
651 if (fin != null) fin.close();
652 } catch (IOException e) {
653 Slog.w(TAG, "Unable to close streams");
654 }
655 }
656 }
657
Christopher Tate4cc86e12009-09-21 19:36:51 -0700658 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700659 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700660 IntentFilter filter = new IntentFilter();
661 filter.addAction(RUN_BACKUP_ACTION);
662 context.registerReceiver(mRunBackupReceiver, filter,
663 android.Manifest.permission.BACKUP, null);
664
665 mRunInitReceiver = new RunInitializeReceiver();
666 filter = new IntentFilter();
667 filter.addAction(RUN_INITIALIZE_ACTION);
668 context.registerReceiver(mRunInitReceiver, filter,
669 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700670
671 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700672 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
673 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
674
Christopher Tate4cc86e12009-09-21 19:36:51 -0700675 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
676 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
677 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
678
Christopher Tatecde87f42009-06-12 12:55:53 -0700679 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700680 mJournalDir = new File(mBaseStateDir, "pending");
681 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700682 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700683
Christopher Tate73e02522009-07-15 14:18:26 -0700684 // Set up the various sorts of package tracking we do
685 initPackageTracking();
686
Christopher Tateabce4e82009-06-18 18:35:32 -0700687 // Build our mapping of uid to backup client services. This implicitly
688 // schedules a backup pass on the Package Manager metadata the first
689 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700690 synchronized (mBackupParticipants) {
691 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700692 }
693
Dan Egnor87a02bc2009-06-17 02:30:10 -0700694 // Set up our transport options and initialize the default transport
695 // TODO: Have transports register themselves somehow?
696 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700697 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700698 ComponentName localName = new ComponentName(context, LocalTransport.class);
699 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700700
Christopher Tate91717492009-06-26 21:07:13 -0700701 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700702 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
703 Settings.Secure.BACKUP_TRANSPORT);
704 if ("".equals(mCurrentTransport)) {
705 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700706 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800707 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700708
709 // Attach to the Google backup transport. When this comes up, it will set
710 // itself as the current transport because we explicitly reset mCurrentTransport
711 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700712 ComponentName transportComponent = new ComponentName("com.google.android.backup",
713 "com.google.android.backup.BackupTransportService");
714 try {
715 // If there's something out there that is supposed to be the Google
716 // backup transport, make sure it's legitimately part of the OS build
717 // and not an app lying about its package name.
718 ApplicationInfo info = mPackageManager.getApplicationInfo(
719 transportComponent.getPackageName(), 0);
720 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
721 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
722 Intent intent = new Intent().setComponent(transportComponent);
723 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
724 } else {
725 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
726 }
727 } catch (PackageManager.NameNotFoundException nnf) {
728 // No such package? No binding.
729 if (DEBUG) Slog.v(TAG, "Google transport not present");
730 }
Christopher Tateaa088442009-06-16 18:25:46 -0700731
Christopher Tatecde87f42009-06-12 12:55:53 -0700732 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700733 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700734 parseLeftoverJournals();
735
Christopher Tateb6787f22009-07-02 17:40:45 -0700736 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700737 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700738
739 // Start the backup passes going
740 setBackupEnabled(areEnabled);
741 }
742
743 private class RunBackupReceiver extends BroadcastReceiver {
744 public void onReceive(Context context, Intent intent) {
745 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700746 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700747 if (mPendingInits.size() > 0) {
748 // If there are pending init operations, we process those
749 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800750 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700751 try {
752 mAlarmManager.cancel(mRunInitIntent);
753 mRunInitIntent.send();
754 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800755 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700756 // can't really do more than bail here
757 }
758 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800759 // Don't run backups now if we're disabled or not yet
760 // fully set up.
761 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800762 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700763
764 // Acquire the wakelock and pass it to the backup thread. it will
765 // be released once backup concludes.
766 mWakelock.acquire();
767
768 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
769 mBackupHandler.sendMessage(msg);
770 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800771 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700772 }
773 }
774 }
775 }
776 }
777 }
778
779 private class RunInitializeReceiver extends BroadcastReceiver {
780 public void onReceive(Context context, Intent intent) {
781 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
782 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800783 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700784
785 // Acquire the wakelock and pass it to the init thread. it will
786 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700787 mWakelock.acquire();
788
Christopher Tate4cc86e12009-09-21 19:36:51 -0700789 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700790 mBackupHandler.sendMessage(msg);
791 }
792 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700793 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700794 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700795
Christopher Tate73e02522009-07-15 14:18:26 -0700796 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800797 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700798
Christopher Tate84725812010-02-04 15:52:40 -0800799 // Remember our ancestral dataset
800 mTokenFile = new File(mBaseStateDir, "ancestral");
801 try {
802 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800803 int version = tf.readInt();
804 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
805 mAncestralToken = tf.readLong();
806 mCurrentToken = tf.readLong();
807
808 int numPackages = tf.readInt();
809 if (numPackages >= 0) {
810 mAncestralPackages = new HashSet<String>();
811 for (int i = 0; i < numPackages; i++) {
812 String pkgName = tf.readUTF();
813 mAncestralPackages.add(pkgName);
814 }
815 }
816 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800817 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800818 } catch (FileNotFoundException fnf) {
819 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800820 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800821 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800822 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800823 }
824
Christopher Tatee97e8072009-07-15 16:45:50 -0700825 // Keep a log of what apps we've ever backed up. Because we might have
826 // rebooted in the middle of an operation that was removing something from
827 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700828 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700829 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700830
Christopher Tatee97e8072009-07-15 16:45:50 -0700831 // If we were in the middle of removing something from the ever-backed-up
832 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700833 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700834 if (tempProcessedFile.exists()) {
835 tempProcessedFile.delete();
836 }
837
Dan Egnor852f8e42009-09-30 11:20:45 -0700838 // If there are previous contents, parse them out then start a new
839 // file to continue the recordkeeping.
840 if (mEverStored.exists()) {
841 RandomAccessFile temp = null;
842 RandomAccessFile in = null;
843
844 try {
845 temp = new RandomAccessFile(tempProcessedFile, "rws");
846 in = new RandomAccessFile(mEverStored, "r");
847
848 while (true) {
849 PackageInfo info;
850 String pkg = in.readUTF();
851 try {
852 info = mPackageManager.getPackageInfo(pkg, 0);
853 mEverStoredApps.add(pkg);
854 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700855 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700856 } catch (NameNotFoundException e) {
857 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700858 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700859 }
860 }
861 } catch (EOFException e) {
862 // Once we've rewritten the backup history log, atomically replace the
863 // old one with the new one then reopen the file for continuing use.
864 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800865 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700866 }
867 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800868 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700869 } finally {
870 try { if (temp != null) temp.close(); } catch (IOException e) {}
871 try { if (in != null) in.close(); } catch (IOException e) {}
872 }
873 }
874
Christopher Tate73e02522009-07-15 14:18:26 -0700875 // Register for broadcasts about package install, etc., so we can
876 // update the provider list.
877 IntentFilter filter = new IntentFilter();
878 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
879 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
880 filter.addDataScheme("package");
881 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800882 // Register for events related to sdcard installation.
883 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800884 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
885 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800886 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700887 }
888
Christopher Tatecde87f42009-06-12 12:55:53 -0700889 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700890 for (File f : mJournalDir.listFiles()) {
891 if (mJournal == null || f.compareTo(mJournal) != 0) {
892 // This isn't the current journal, so it must be a leftover. Read
893 // out the package names mentioned there and schedule them for
894 // backup.
895 RandomAccessFile in = null;
896 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400897 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700898 in = new RandomAccessFile(f, "r");
899 while (true) {
900 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400901 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700902 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700903 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700904 } catch (EOFException e) {
905 // no more data; we're done
906 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800907 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700908 } finally {
909 // close/delete the file
910 try { if (in != null) in.close(); } catch (IOException e) {}
911 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700912 }
913 }
914 }
915 }
916
Christopher Tate2efd2db2011-07-19 16:32:49 -0700917 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
918 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
919 }
920
921 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
922 try {
923 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
924 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
925 return keyFactory.generateSecret(ks);
926 } catch (InvalidKeySpecException e) {
927 Slog.e(TAG, "Invalid key spec for PBKDF2!");
928 } catch (NoSuchAlgorithmException e) {
929 Slog.e(TAG, "PBKDF2 unavailable!");
930 }
931 return null;
932 }
933
934 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
935 SecretKey key = buildPasswordKey(pw, salt, rounds);
936 if (key != null) {
937 return byteArrayToHex(key.getEncoded());
938 }
939 return null;
940 }
941
942 private String byteArrayToHex(byte[] data) {
943 StringBuilder buf = new StringBuilder(data.length * 2);
944 for (int i = 0; i < data.length; i++) {
945 buf.append(Byte.toHexString(data[i], true));
946 }
947 return buf.toString();
948 }
949
950 private byte[] hexToByteArray(String digits) {
951 final int bytes = digits.length() / 2;
952 if (2*bytes != digits.length()) {
953 throw new IllegalArgumentException("Hex string must have an even number of digits");
954 }
955
956 byte[] result = new byte[bytes];
957 for (int i = 0; i < digits.length(); i += 2) {
958 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
959 }
960 return result;
961 }
962
963 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
964 char[] mkAsChar = new char[pwBytes.length];
965 for (int i = 0; i < pwBytes.length; i++) {
966 mkAsChar[i] = (char) pwBytes[i];
967 }
968
969 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
970 return checksum.getEncoded();
971 }
972
973 // Used for generating random salts or passwords
974 private byte[] randomBytes(int bits) {
975 byte[] array = new byte[bits / 8];
976 mRng.nextBytes(array);
977 return array;
978 }
979
980 // Backup password management
981 boolean passwordMatchesSaved(String candidatePw, int rounds) {
982 if (mPasswordHash == null) {
983 // no current password case -- require that 'currentPw' be null or empty
984 if (candidatePw == null || "".equals(candidatePw)) {
985 return true;
986 } // else the non-empty candidate does not match the empty stored pw
987 } else {
988 // hash the stated current pw and compare to the stored one
989 if (candidatePw != null && candidatePw.length() > 0) {
990 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
991 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
992 // candidate hash matches the stored hash -- the password matches
993 return true;
994 }
995 } // else the stored pw is nonempty but the candidate is empty; no match
996 }
997 return false;
998 }
999
1000 @Override
1001 public boolean setBackupPassword(String currentPw, String newPw) {
1002 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1003 "setBackupPassword");
1004
1005 // If the supplied pw doesn't hash to the the saved one, fail
1006 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1007 return false;
1008 }
1009
1010 // Clearing the password is okay
1011 if (newPw == null || newPw.isEmpty()) {
1012 if (mPasswordHashFile.exists()) {
1013 if (!mPasswordHashFile.delete()) {
1014 // Unable to delete the old pw file, so fail
1015 Slog.e(TAG, "Unable to clear backup password");
1016 return false;
1017 }
1018 }
1019 mPasswordHash = null;
1020 mPasswordSalt = null;
1021 return true;
1022 }
1023
1024 try {
1025 // Okay, build the hash of the new backup password
1026 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1027 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1028
1029 OutputStream pwf = null, buffer = null;
1030 DataOutputStream out = null;
1031 try {
1032 pwf = new FileOutputStream(mPasswordHashFile);
1033 buffer = new BufferedOutputStream(pwf);
1034 out = new DataOutputStream(buffer);
1035 // integer length of the salt array, followed by the salt,
1036 // then the hex pw hash string
1037 out.writeInt(salt.length);
1038 out.write(salt);
1039 out.writeUTF(newPwHash);
1040 out.flush();
1041 mPasswordHash = newPwHash;
1042 mPasswordSalt = salt;
1043 return true;
1044 } finally {
1045 if (out != null) out.close();
1046 if (buffer != null) buffer.close();
1047 if (pwf != null) pwf.close();
1048 }
1049 } catch (IOException e) {
1050 Slog.e(TAG, "Unable to set backup password");
1051 }
1052 return false;
1053 }
1054
1055 @Override
1056 public boolean hasBackupPassword() {
1057 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1058 "hasBackupPassword");
1059 return (mPasswordHash != null && mPasswordHash.length() > 0);
1060 }
1061
Christopher Tate4cc86e12009-09-21 19:36:51 -07001062 // Maintain persistent state around whether need to do an initialize operation.
1063 // Must be called with the queue lock held.
1064 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001065 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001066 + " on transport " + transportName);
1067 try {
1068 IBackupTransport transport = getTransport(transportName);
1069 String transportDirName = transport.transportDirName();
1070 File stateDir = new File(mBaseStateDir, transportDirName);
1071 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1072
1073 if (isPending) {
1074 // We need an init before we can proceed with sending backup data.
1075 // Record that with an entry in our set of pending inits, as well as
1076 // journaling it via creation of a sentinel file.
1077 mPendingInits.add(transportName);
1078 try {
1079 (new FileOutputStream(initPendingFile)).close();
1080 } catch (IOException ioe) {
1081 // Something is badly wrong with our permissions; just try to move on
1082 }
1083 } else {
1084 // No more initialization needed; wipe the journal and reset our state.
1085 initPendingFile.delete();
1086 mPendingInits.remove(transportName);
1087 }
1088 } catch (RemoteException e) {
1089 // can't happen; the transport is local
1090 }
1091 }
1092
Christopher Tated55e18a2009-09-21 10:12:59 -07001093 // Reset all of our bookkeeping, in response to having been told that
1094 // the backend data has been wiped [due to idle expiry, for example],
1095 // so we must re-upload all saved settings.
1096 void resetBackupState(File stateFileDir) {
1097 synchronized (mQueueLock) {
1098 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001099 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001100 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001101
Christopher Tate84725812010-02-04 15:52:40 -08001102 mCurrentToken = 0;
1103 writeRestoreTokens();
1104
Christopher Tated55e18a2009-09-21 10:12:59 -07001105 // Remove all the state files
1106 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001107 // ... but don't touch the needs-init sentinel
1108 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1109 sf.delete();
1110 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001111 }
Christopher Tate45597642011-04-04 16:59:21 -07001112 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001113
Christopher Tate45597642011-04-04 16:59:21 -07001114 // Enqueue a new backup of every participant
1115 int N = mBackupParticipants.size();
1116 for (int i=0; i<N; i++) {
1117 int uid = mBackupParticipants.keyAt(i);
1118 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1119 for (ApplicationInfo app: participants) {
1120 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -07001121 }
1122 }
1123 }
1124
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001125 // Add a transport to our set of available backends. If 'transport' is null, this
1126 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001127 private void registerTransport(String name, IBackupTransport transport) {
1128 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001129 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001130 if (transport != null) {
1131 mTransports.put(name, transport);
1132 } else {
1133 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001134 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001135 mCurrentTransport = null;
1136 }
1137 // Nothing further to do in the unregistration case
1138 return;
1139 }
Christopher Tate91717492009-06-26 21:07:13 -07001140 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001141
1142 // If the init sentinel file exists, we need to be sure to perform the init
1143 // as soon as practical. We also create the state directory at registration
1144 // time to ensure it's present from the outset.
1145 try {
1146 String transportName = transport.transportDirName();
1147 File stateDir = new File(mBaseStateDir, transportName);
1148 stateDir.mkdirs();
1149
1150 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1151 if (initSentinel.exists()) {
1152 synchronized (mQueueLock) {
1153 mPendingInits.add(transportName);
1154
1155 // TODO: pick a better starting time than now + 1 minute
1156 long delay = 1000 * 60; // one minute, in milliseconds
1157 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1158 System.currentTimeMillis() + delay, mRunInitIntent);
1159 }
1160 }
1161 } catch (RemoteException e) {
1162 // can't happen, the transport is local
1163 }
Christopher Tate91717492009-06-26 21:07:13 -07001164 }
1165
Christopher Tate3799bc22009-05-06 16:13:56 -07001166 // ----- Track installation/removal of packages -----
1167 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1168 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001169 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001170
Christopher Tate3799bc22009-05-06 16:13:56 -07001171 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001172 boolean replacing = false;
1173 boolean added = false;
1174 Bundle extras = intent.getExtras();
1175 String pkgList[] = null;
1176 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
1177 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1178 Uri uri = intent.getData();
1179 if (uri == null) {
1180 return;
1181 }
1182 String pkgName = uri.getSchemeSpecificPart();
1183 if (pkgName != null) {
1184 pkgList = new String[] { pkgName };
1185 }
1186 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1187 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001188 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001189 added = true;
1190 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001191 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001192 added = false;
1193 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1194 }
1195 if (pkgList == null || pkgList.length == 0) {
1196 return;
1197 }
1198 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001199 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001200 for (String pkgName : pkgList) {
1201 if (replacing) {
1202 // The package was just upgraded
1203 updatePackageParticipantsLocked(pkgName);
1204 } else {
1205 // The package was just added
1206 addPackageParticipantsLocked(pkgName);
1207 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001208 }
1209 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001210 } else {
1211 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001212 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1213 } else {
1214 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001215 for (String pkgName : pkgList) {
1216 removePackageParticipantsLocked(pkgName);
1217 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001218 }
1219 }
1220 }
1221 }
1222 };
1223
Dan Egnor87a02bc2009-06-17 02:30:10 -07001224 // ----- Track connection to GoogleBackupTransport service -----
1225 ServiceConnection mGoogleConnection = new ServiceConnection() {
1226 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001227 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001228 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001229 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001230 }
1231
1232 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001233 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001234 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001235 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001236 }
1237 };
1238
Christopher Tate181fafa2009-05-14 11:12:14 -07001239 // Add the backup agents in the given package to our set of known backup participants.
1240 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -07001241 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001242 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -08001243 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -07001244 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001245 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001246 }
1247
Christopher Tate181fafa2009-05-14 11:12:14 -07001248 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001249 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001250 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001251 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -07001252 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001253 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001254 + " uid=" + p.applicationInfo.uid
1255 + " killAfterRestore="
1256 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001257 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001258 }
1259 }
1260
Dan Egnorefe52642009-06-24 00:16:33 -07001261 for (PackageInfo pkg : targetPkgs) {
1262 if (packageName == null || pkg.packageName.equals(packageName)) {
1263 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001264 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001265 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001266 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001267 mBackupParticipants.put(uid, set);
1268 }
Dan Egnorefe52642009-06-24 00:16:33 -07001269 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001270
1271 // If we've never seen this app before, schedule a backup for it
1272 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001273 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001274 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001275 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001276 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001277 }
Christopher Tate487529a2009-04-29 14:03:25 -07001278 }
1279 }
1280
Christopher Tate6785dd82009-06-18 15:58:25 -07001281 // Remove the given package's entry from our known active set. If
1282 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001283 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001284 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001285 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001286 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001287 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001288 } else {
1289 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001290 List<PackageInfo> knownPackages = allAgentPackages();
1291 for (PackageInfo pkg : knownPackages) {
1292 allApps.add(pkg.packageName);
1293 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001294 }
1295 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001296 }
1297
Joe Onorato8ad02812009-05-13 01:41:44 -04001298 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001299 List<String> allPackageNames) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001300 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001301 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001302 + ") removing " + allPackageNames.size() + " entries");
1303 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001304 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001305 }
1306 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001307 for (String pkg : allPackageNames) {
1308 if (packageName == null || pkg.equals(packageName)) {
1309 int uid = -1;
1310 try {
1311 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1312 uid = info.applicationInfo.uid;
1313 } catch (NameNotFoundException e) {
1314 // we don't know this package name, so just skip it for now
1315 continue;
1316 }
1317
Christopher Tate181fafa2009-05-14 11:12:14 -07001318 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001319 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001320 // Find the existing entry with the same package name, and remove it.
1321 // We can't just remove(app) because the instances are different.
1322 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001323 if (entry.packageName.equals(pkg)) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001324 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001325 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001326 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001327 break;
1328 }
1329 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001330 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001331 mBackupParticipants.delete(uid);
1332 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001333 }
1334 }
1335 }
1336 }
1337
Christopher Tate181fafa2009-05-14 11:12:14 -07001338 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001339 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001340 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001341 int flags = PackageManager.GET_SIGNATURES;
1342 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1343 int N = packages.size();
1344 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001345 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001346 try {
1347 ApplicationInfo app = pkg.applicationInfo;
1348 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001349 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001350 packages.remove(a);
1351 }
1352 else {
1353 // we will need the shared library path, so look that up and store it here
1354 app = mPackageManager.getApplicationInfo(pkg.packageName,
1355 PackageManager.GET_SHARED_LIBRARY_FILES);
1356 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1357 }
1358 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001359 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001360 }
1361 }
Dan Egnorefe52642009-06-24 00:16:33 -07001362 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001363 }
Christopher Tateaa088442009-06-16 18:25:46 -07001364
Christopher Tate3799bc22009-05-06 16:13:56 -07001365 // Reset the given package's known backup participants. Unlike add/remove, the update
1366 // action cannot be passed a null package name.
1367 void updatePackageParticipantsLocked(String packageName) {
1368 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001369 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001370 return;
1371 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001372 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001373
1374 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001375 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001376 List<String> allAppNames = new ArrayList<String>();
1377 for (PackageInfo pkg : allApps) {
1378 allAppNames.add(pkg.packageName);
1379 }
1380 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001381 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001382 }
1383
Christopher Tate84725812010-02-04 15:52:40 -08001384 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001385 // backed up at least once
1386 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001387 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1388
1389 synchronized (mEverStoredApps) {
1390 if (!mEverStoredApps.add(packageName)) return;
1391
1392 RandomAccessFile out = null;
1393 try {
1394 out = new RandomAccessFile(mEverStored, "rws");
1395 out.seek(out.length());
1396 out.writeUTF(packageName);
1397 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001398 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001399 } finally {
1400 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001401 }
1402 }
1403 }
1404
Christopher Tatee97e8072009-07-15 16:45:50 -07001405 // Remove our awareness of having ever backed up the given package
1406 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001407 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1408 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001409
Dan Egnor852f8e42009-09-30 11:20:45 -07001410 synchronized (mEverStoredApps) {
1411 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1412 // we'll recognize on initialization time that the package no longer
1413 // exists and fix it up then.
1414 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1415 RandomAccessFile known = null;
1416 try {
1417 known = new RandomAccessFile(tempKnownFile, "rws");
1418 mEverStoredApps.remove(packageName);
1419 for (String s : mEverStoredApps) {
1420 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001421 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001422 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001423 known.close();
1424 known = null;
1425 if (!tempKnownFile.renameTo(mEverStored)) {
1426 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1427 }
1428 } catch (IOException e) {
1429 // Bad: we couldn't create the new copy. For safety's sake we
1430 // abandon the whole process and remove all what's-backed-up
1431 // state entirely, meaning we'll force a backup pass for every
1432 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001433 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001434 mEverStoredApps.clear();
1435 tempKnownFile.delete();
1436 mEverStored.delete();
1437 } finally {
1438 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001439 }
1440 }
1441 }
1442
Christopher Tateb49ceb32010-02-08 16:22:24 -08001443 // Persistently record the current and ancestral backup tokens as well
1444 // as the set of packages with data [supposedly] available in the
1445 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001446 void writeRestoreTokens() {
1447 try {
1448 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001449
1450 // First, the version number of this record, for futureproofing
1451 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1452
1453 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001454 af.writeLong(mAncestralToken);
1455 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001456
1457 // Now write the set of ancestral packages
1458 if (mAncestralPackages == null) {
1459 af.writeInt(-1);
1460 } else {
1461 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001462 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001463 for (String pkgName : mAncestralPackages) {
1464 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001465 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001466 }
1467 }
Christopher Tate84725812010-02-04 15:52:40 -08001468 af.close();
1469 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001470 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001471 }
1472 }
1473
Dan Egnor87a02bc2009-06-17 02:30:10 -07001474 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001475 private IBackupTransport getTransport(String transportName) {
1476 synchronized (mTransports) {
1477 IBackupTransport transport = mTransports.get(transportName);
1478 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001479 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001480 }
1481 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001482 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001483 }
1484
Christopher Tatedf01dea2009-06-09 20:45:02 -07001485 // fire off a backup agent, blocking until it attaches or times out
1486 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1487 IBackupAgent agent = null;
1488 synchronized(mAgentConnectLock) {
1489 mConnecting = true;
1490 mConnectedAgent = null;
1491 try {
1492 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001493 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001494
1495 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001496 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001497 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1498 while (mConnecting && mConnectedAgent == null
1499 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001500 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001501 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001502 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001503 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001504 return null;
1505 }
1506 }
1507
1508 // if we timed out with no connect, abort and move on
1509 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001510 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001511 return null;
1512 }
1513 agent = mConnectedAgent;
1514 }
1515 } catch (RemoteException e) {
1516 // can't happen
1517 }
1518 }
1519 return agent;
1520 }
1521
Christopher Tatec7b31e32009-06-10 15:49:30 -07001522 // clear an application's data, blocking until the operation completes or times out
1523 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001524 // Don't wipe packages marked allowClearUserData=false
1525 try {
1526 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1527 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001528 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001529 + packageName);
1530 return;
1531 }
1532 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001533 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001534 return;
1535 }
1536
Christopher Tatec7b31e32009-06-10 15:49:30 -07001537 ClearDataObserver observer = new ClearDataObserver();
1538
1539 synchronized(mClearDataLock) {
1540 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001541 try {
1542 mActivityManager.clearApplicationUserData(packageName, observer);
1543 } catch (RemoteException e) {
1544 // can't happen because the activity manager is in this process
1545 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001546
1547 // only wait 10 seconds for the clear data to happen
1548 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1549 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1550 try {
1551 mClearDataLock.wait(5000);
1552 } catch (InterruptedException e) {
1553 // won't happen, but still.
1554 mClearingData = false;
1555 }
1556 }
1557 }
1558 }
1559
1560 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001561 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001562 synchronized(mClearDataLock) {
1563 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001564 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001565 }
1566 }
1567 }
1568
Christopher Tate1bb69062010-02-19 17:02:12 -08001569 // Get the restore-set token for the best-available restore set for this package:
1570 // the active set if possible, else the ancestral one. Returns zero if none available.
1571 long getAvailableRestoreToken(String packageName) {
1572 long token = mAncestralToken;
1573 synchronized (mQueueLock) {
1574 if (mEverStoredApps.contains(packageName)) {
1575 token = mCurrentToken;
1576 }
1577 }
1578 return token;
1579 }
1580
Christopher Tate44a27902010-01-27 17:15:49 -08001581 // -----
1582 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1583 boolean waitUntilOperationComplete(int token) {
1584 int finalState = OP_PENDING;
1585 synchronized (mCurrentOpLock) {
1586 try {
1587 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1588 try {
1589 mCurrentOpLock.wait();
1590 } catch (InterruptedException e) {}
1591 }
1592 } catch (IndexOutOfBoundsException e) {
1593 // the operation has been mysteriously cleared from our
1594 // bookkeeping -- consider this a success and ignore it.
1595 }
1596 }
1597 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001598 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001599 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001600 return finalState == OP_ACKNOWLEDGED;
1601 }
1602
1603 void prepareOperationTimeout(int token, long interval) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001604 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001605 + " interval=" + interval);
Christopher Tate4a627c72011-04-01 14:43:32 -07001606 synchronized (mCurrentOpLock) {
1607 mCurrentOperations.put(token, OP_PENDING);
1608 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1609 mBackupHandler.sendMessageDelayed(msg, interval);
1610 }
Christopher Tate44a27902010-01-27 17:15:49 -08001611 }
1612
Christopher Tate043dadc2009-06-02 16:11:00 -07001613 // ----- Back up a set of applications via a worker thread -----
1614
Christopher Tate44a27902010-01-27 17:15:49 -08001615 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001616 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001617 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001618 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001619 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001620 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001621
Christopher Tate44a27902010-01-27 17:15:49 -08001622 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001623 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001624 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001625 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001626 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001627
1628 try {
1629 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1630 } catch (RemoteException e) {
1631 // can't happen; the transport is local
1632 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001633 }
1634
Christopher Tate043dadc2009-06-02 16:11:00 -07001635 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001636 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001637 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001638 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001639
Christopher Tate79588342009-06-30 16:11:49 -07001640 // Backups run at background priority
1641 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1642
Christopher Tate043dadc2009-06-02 16:11:00 -07001643 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001644 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001645
Dan Egnor852f8e42009-09-30 11:20:45 -07001646 // If we haven't stored package manager metadata yet, we must init the transport.
1647 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1648 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001649 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001650 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001651 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001652 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001653 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001654 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001655 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001656 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001657 }
Dan Egnor01445162009-09-21 17:04:05 -07001658 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001659
1660 // The package manager doesn't have a proper <application> etc, but since
1661 // it's running here in the system process we can just set up its agent
1662 // directly and use a synthetic BackupRequest. We always run this pass
1663 // because it's cheap and this way we guarantee that we don't get out of
1664 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001665 if (status == BackupConstants.TRANSPORT_OK) {
1666 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1667 mPackageManager, allAgentPackages());
Christopher Tate4a627c72011-04-01 14:43:32 -07001668 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo());
Dan Egnor01445162009-09-21 17:04:05 -07001669 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1670 status = processOneBackup(pmRequest,
1671 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1672 }
Christopher Tate90967f42009-09-20 15:28:33 -07001673
Dan Egnor01445162009-09-21 17:04:05 -07001674 if (status == BackupConstants.TRANSPORT_OK) {
1675 // Now run all the backups in our queue
1676 status = doQueuedBackups(mTransport);
1677 }
1678
1679 if (status == BackupConstants.TRANSPORT_OK) {
1680 // Tell the transport to finish everything it has buffered
1681 status = mTransport.finishBackup();
1682 if (status == BackupConstants.TRANSPORT_OK) {
1683 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001684 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001685 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001686 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001687 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001688 }
1689 }
1690
Dan Egnor01445162009-09-21 17:04:05 -07001691 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001692 // The backend reports that our dataset has been wiped. We need to
1693 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001694 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001695 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001696 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001697 }
1698 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001699 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001700 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001701 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001702 // If everything actually went through and this is the first time we've
1703 // done a backup, we can now record what the current backup dataset token
1704 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001705 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001706 try {
1707 mCurrentToken = mTransport.getCurrentRestoreSet();
1708 } catch (RemoteException e) { /* cannot happen */ }
1709 writeRestoreTokens();
1710 }
1711
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001712 // If things went wrong, we need to re-stage the apps we had expected
1713 // to be backing up in this pass. This journals the package names in
1714 // the current active pending-backup file, not in the we are holding
1715 // here in mJournal.
1716 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001717 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001718 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001719 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001720 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001721
1722 // We also want to reset the backup schedule based on whatever
1723 // the transport suggests by way of retry/backoff time.
1724 try {
1725 startBackupAlarmsLocked(mTransport.requestBackupTime());
1726 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001727 }
1728
1729 // Either backup was successful, in which case we of course do not need
1730 // this pass's journal any more; or it failed, in which case we just
1731 // re-enqueued all of these packages in the current active journal.
1732 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001733 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001734 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001735 }
1736
Christopher Tatec2af5d32010-02-02 15:18:58 -08001737 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001738 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001739 backupNow();
1740 }
1741
Dan Egnorbb9001c2009-07-27 12:20:13 -07001742 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001743 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001744 }
1745
Dan Egnor01445162009-09-21 17:04:05 -07001746 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001747 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001748 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001749
Christopher Tatec28083a2010-12-14 16:16:44 -08001750 // Verify that the requested app exists; it might be something that
1751 // requested a backup but was then uninstalled. The request was
1752 // journalled and rather than tamper with the journal it's safer
1753 // to sanity-check here.
1754 try {
1755 mPackageManager.getPackageInfo(request.appInfo.packageName, 0);
1756 } catch (NameNotFoundException e) {
1757 Slog.d(TAG, "Package does not exist; skipping");
1758 continue;
1759 }
1760
Christopher Tate043dadc2009-06-02 16:11:00 -07001761 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001762 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001763 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tate4a627c72011-04-01 14:43:32 -07001764 agent = bindToAgentSynchronous(request.appInfo,
1765 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001766 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001767 int result = processOneBackup(request, agent, transport);
1768 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001769 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001770 } catch (SecurityException ex) {
1771 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001772 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001773 } finally {
1774 try { // unbind even on timeout, just in case
1775 mActivityManager.unbindBackupAgent(request.appInfo);
1776 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001777 }
1778 }
Dan Egnor01445162009-09-21 17:04:05 -07001779
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001780 mWakelock.setWorkSource(null);
1781
Dan Egnor01445162009-09-21 17:04:05 -07001782 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001783 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001784
Dan Egnor01445162009-09-21 17:04:05 -07001785 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1786 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001787 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001788 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001789
Dan Egnorbb9001c2009-07-27 12:20:13 -07001790 File savedStateName = new File(mStateDir, packageName);
1791 File backupDataName = new File(mDataDir, packageName + ".data");
1792 File newStateName = new File(mStateDir, packageName + ".new");
1793
1794 ParcelFileDescriptor savedState = null;
1795 ParcelFileDescriptor backupData = null;
1796 ParcelFileDescriptor newState = null;
1797
1798 PackageInfo packInfo;
Christopher Tate4a627c72011-04-01 14:43:32 -07001799 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001800 try {
1801 // Look up the package info & signatures. This is first so that if it
1802 // throws an exception, there's no file setup yet that would need to
1803 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001804 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1805 // The metadata 'package' is synthetic
1806 packInfo = new PackageInfo();
1807 packInfo.packageName = packageName;
1808 } else {
1809 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001810 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001811 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001812
Christopher Tatec7b31e32009-06-10 15:49:30 -07001813 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001814 // the saved-state "file". This is by definition an incremental,
1815 // so we build a saved state file to pass.
1816 savedState = ParcelFileDescriptor.open(savedStateName,
1817 ParcelFileDescriptor.MODE_READ_ONLY |
1818 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001819
Dan Egnorbb9001c2009-07-27 12:20:13 -07001820 backupData = ParcelFileDescriptor.open(backupDataName,
1821 ParcelFileDescriptor.MODE_READ_WRITE |
1822 ParcelFileDescriptor.MODE_CREATE |
1823 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001824
Dan Egnorbb9001c2009-07-27 12:20:13 -07001825 newState = ParcelFileDescriptor.open(newStateName,
1826 ParcelFileDescriptor.MODE_READ_WRITE |
1827 ParcelFileDescriptor.MODE_CREATE |
1828 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001829
Christopher Tate44a27902010-01-27 17:15:49 -08001830 // Initiate the target's backup pass
1831 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07001832 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
Christopher Tate44a27902010-01-27 17:15:49 -08001833 boolean success = waitUntilOperationComplete(token);
1834
1835 if (!success) {
1836 // timeout -- bail out into the failed-transaction logic
1837 throw new RuntimeException("Backup timeout");
1838 }
1839
Dan Egnorbb9001c2009-07-27 12:20:13 -07001840 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001841 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001842 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001843 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001844 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001845 backupDataName.delete();
1846 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001847 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001848 } finally {
1849 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1850 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1851 try { if (newState != null) newState.close(); } catch (IOException e) {}
1852 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001853 synchronized (mCurrentOpLock) {
1854 mCurrentOperations.clear();
1855 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001856 }
1857
1858 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001859 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001860 try {
1861 int size = (int) backupDataName.length();
1862 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001863 if (result == BackupConstants.TRANSPORT_OK) {
1864 backupData = ParcelFileDescriptor.open(backupDataName,
1865 ParcelFileDescriptor.MODE_READ_ONLY);
1866 result = transport.performBackup(packInfo, backupData);
1867 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001868
Dan Egnor83861e72009-09-17 16:17:55 -07001869 // TODO - We call finishBackup() for each application backed up, because
1870 // we need to know now whether it succeeded or failed. Instead, we should
1871 // hold off on finishBackup() until the end, which implies holding off on
1872 // renaming *all* the output state files (see below) until that happens.
1873
Dan Egnor01445162009-09-21 17:04:05 -07001874 if (result == BackupConstants.TRANSPORT_OK) {
1875 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001876 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001877 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001878 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001879 }
1880
1881 // After successful transport, delete the now-stale data
1882 // and juggle the files so that next time we supply the agent
1883 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001884 if (result == BackupConstants.TRANSPORT_OK) {
1885 backupDataName.delete();
1886 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001887 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001888 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001889 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001890 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001891 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001892 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001893 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001894 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001895 } finally {
1896 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001897 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001898
Dan Egnor01445162009-09-21 17:04:05 -07001899 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001900 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001901 }
1902
Christopher Tatedf01dea2009-06-09 20:45:02 -07001903
Christopher Tate4a627c72011-04-01 14:43:32 -07001904 // ----- Full backup to a file/socket -----
1905
1906 class PerformFullBackupTask implements Runnable {
1907 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07001908 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07001909 IFullBackupRestoreObserver mObserver;
1910 boolean mIncludeApks;
1911 boolean mIncludeShared;
1912 boolean mAllApps;
1913 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07001914 String mCurrentPassword;
1915 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07001916 AtomicBoolean mLatchObject;
1917 File mFilesDir;
1918 File mManifestFile;
1919
Christopher Tate7926a692011-07-11 11:31:57 -07001920 class FullBackupRunner implements Runnable {
1921 PackageInfo mPackage;
1922 IBackupAgent mAgent;
1923 ParcelFileDescriptor mPipe;
1924 int mToken;
1925 boolean mSendApk;
1926
1927 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
1928 int token, boolean sendApk) throws IOException {
1929 mPackage = pack;
1930 mAgent = agent;
1931 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
1932 mToken = token;
1933 mSendApk = sendApk;
1934 }
1935
1936 @Override
1937 public void run() {
1938 try {
1939 BackupDataOutput output = new BackupDataOutput(
1940 mPipe.getFileDescriptor());
1941
Christopher Tatec58efa62011-08-01 19:20:14 -07001942 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
Christopher Tate7926a692011-07-11 11:31:57 -07001943 writeAppManifest(mPackage, mManifestFile, mSendApk);
1944 FullBackup.backupToTar(mPackage.packageName, null, null,
1945 mFilesDir.getAbsolutePath(),
1946 mManifestFile.getAbsolutePath(),
1947 output);
1948
1949 if (mSendApk) {
1950 writeApkToBackup(mPackage, output);
1951 }
1952
Christopher Tatec58efa62011-08-01 19:20:14 -07001953 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate7926a692011-07-11 11:31:57 -07001954 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL);
1955 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
1956 } catch (IOException e) {
1957 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
1958 } catch (RemoteException e) {
1959 Slog.e(TAG, "Remote agent vanished during full backup of "
1960 + mPackage.packageName);
1961 } finally {
1962 try {
1963 mPipe.close();
1964 } catch (IOException e) {}
1965 }
1966 }
1967 }
1968
Christopher Tate4a627c72011-04-01 14:43:32 -07001969 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07001970 boolean includeApks, boolean includeShared, String curPassword,
1971 String encryptPassword, boolean doAllApps, String[] packages,
1972 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07001973 mOutputFile = fd;
1974 mObserver = observer;
1975 mIncludeApks = includeApks;
1976 mIncludeShared = includeShared;
1977 mAllApps = doAllApps;
1978 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07001979 mCurrentPassword = curPassword;
1980 // when backing up, if there is a current backup password, we require that
1981 // the user use a nonempty encryption password as well. if one is supplied
1982 // in the UI we use that, but if the UI was left empty we fall back to the
1983 // current backup password (which was supplied by the user as well).
1984 if (encryptPassword == null || "".equals(encryptPassword)) {
1985 mEncryptPassword = curPassword;
1986 } else {
1987 mEncryptPassword = encryptPassword;
1988 }
Christopher Tate4a627c72011-04-01 14:43:32 -07001989 mLatchObject = latch;
1990
1991 mFilesDir = new File("/data/system");
1992 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
1993 }
1994
1995 @Override
1996 public void run() {
1997 final List<PackageInfo> packagesToBackup;
1998
Christopher Tateb0628bf2011-06-02 15:08:13 -07001999 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002000 sendStartBackup();
2001
2002 // doAllApps supersedes the package set if any
2003 if (mAllApps) {
2004 packagesToBackup = mPackageManager.getInstalledPackages(
2005 PackageManager.GET_SIGNATURES);
2006 } else {
2007 packagesToBackup = new ArrayList<PackageInfo>();
2008 for (String pkgName : mPackages) {
2009 try {
2010 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2011 PackageManager.GET_SIGNATURES));
2012 } catch (NameNotFoundException e) {
2013 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2014 }
2015 }
2016 }
2017
Christopher Tatea858cb02011-06-03 12:27:51 -07002018 // Cull any packages that have indicated that backups are not permitted.
2019 for (int i = 0; i < packagesToBackup.size(); ) {
2020 PackageInfo info = packagesToBackup.get(i);
2021 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
2022 packagesToBackup.remove(i);
2023 } else {
2024 i++;
2025 }
2026 }
2027
Christopher Tate7926a692011-07-11 11:31:57 -07002028 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002029 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002030
Christopher Tate4a627c72011-04-01 14:43:32 -07002031 PackageInfo pkg = null;
2032 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002033 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002034 boolean compressing = COMPRESS_FULL_BACKUPS;
2035 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002036
2037 // Write the global file header. All strings are UTF-8 encoded; lines end
2038 // with a '\n' byte. Actual backup data begins immediately following the
2039 // final '\n'.
2040 //
2041 // line 1: "ANDROID BACKUP"
2042 // line 2: backup file format version, currently "1"
2043 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002044 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2045 //
2046 // When line 4 is not "none", then additional header data follows:
2047 //
2048 // line 5: user password salt [hex]
2049 // line 6: master key checksum salt [hex]
2050 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2051 // line 8: IV of the user key [hex]
2052 // line 9: master key blob [hex]
2053 // IV of the master key, master key itself, master key checksum hash
2054 //
2055 // The master key checksum is the master key plus its checksum salt, run through
2056 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2057 // correct password for decrypting the archive: the master key decrypted from
2058 // the archive using the user-supplied password is also run through PBKDF2 in
2059 // this way, and if the result does not match the checksum as stored in the
2060 // archive, then we know that the user-supplied password does not match the
2061 // archive's.
2062 StringBuilder headerbuf = new StringBuilder(1024);
2063
Christopher Tate7bdb0962011-07-13 19:30:21 -07002064 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002065 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2066 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002067
2068 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002069 // Set up the encryption stage if appropriate, and emit the correct header
2070 if (encrypting) {
2071 // Verify that the given password matches the currently-active
2072 // backup password, if any
2073 if (hasBackupPassword()) {
Christopher Tate728a1c42011-07-28 18:03:03 -07002074 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002075 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2076 return;
2077 }
2078 }
2079
2080 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2081 } else {
2082 headerbuf.append("none\n");
2083 }
2084
Christopher Tate7bdb0962011-07-13 19:30:21 -07002085 byte[] header = headerbuf.toString().getBytes("UTF-8");
2086 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002087
2088 // Set up the compression stage feeding into the encryption stage (if any)
2089 if (compressing) {
2090 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2091 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2092 }
2093
2094 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002095 } catch (Exception e) {
2096 // Should never happen!
2097 Slog.e(TAG, "Unable to emit archive header", e);
2098 return;
2099 }
2100
Christopher Tateb0628bf2011-06-02 15:08:13 -07002101 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002102 int N = packagesToBackup.size();
2103 for (int i = 0; i < N; i++) {
2104 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002105 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002106 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002107
Christopher Tateb0628bf2011-06-02 15:08:13 -07002108 // Finally, shared storage if requested
2109 if (mIncludeShared) {
2110 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07002111 }
2112 } catch (RemoteException e) {
2113 Slog.e(TAG, "App died during full backup");
2114 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002115 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002116 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002117 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002118 mOutputFile.close();
2119 } catch (IOException e) {
2120 /* nothing we can do about this */
2121 }
2122 synchronized (mCurrentOpLock) {
2123 mCurrentOperations.clear();
2124 }
2125 synchronized (mLatchObject) {
2126 mLatchObject.set(true);
2127 mLatchObject.notifyAll();
2128 }
2129 sendEndBackup();
2130 mWakelock.release();
2131 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
2132 }
2133 }
2134
Christopher Tate2efd2db2011-07-19 16:32:49 -07002135 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2136 OutputStream ofstream) throws Exception {
2137 // User key will be used to encrypt the master key.
2138 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002139 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002140 PBKDF2_HASH_ROUNDS);
2141
2142 // the master key is random for each backup
2143 byte[] masterPw = new byte[256 / 8];
2144 mRng.nextBytes(masterPw);
2145 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2146
2147 // primary encryption of the datastream with the random key
2148 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2149 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2150 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2151 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2152
2153 // line 4: name of encryption algorithm
2154 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2155 headerbuf.append('\n');
2156 // line 5: user password salt [hex]
2157 headerbuf.append(byteArrayToHex(newUserSalt));
2158 headerbuf.append('\n');
2159 // line 6: master key checksum salt [hex]
2160 headerbuf.append(byteArrayToHex(checksumSalt));
2161 headerbuf.append('\n');
2162 // line 7: number of PBKDF2 rounds used [decimal]
2163 headerbuf.append(PBKDF2_HASH_ROUNDS);
2164 headerbuf.append('\n');
2165
2166 // line 8: IV of the user key [hex]
2167 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2168 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2169
2170 byte[] IV = mkC.getIV();
2171 headerbuf.append(byteArrayToHex(IV));
2172 headerbuf.append('\n');
2173
2174 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2175 // [byte] IV length = Niv
2176 // [array of Niv bytes] IV itself
2177 // [byte] master key length = Nmk
2178 // [array of Nmk bytes] master key itself
2179 // [byte] MK checksum hash length = Nck
2180 // [array of Nck bytes] master key checksum hash
2181 //
2182 // The checksum is the (master key + checksum salt), run through the
2183 // stated number of PBKDF2 rounds
2184 IV = c.getIV();
2185 byte[] mk = masterKeySpec.getEncoded();
2186 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2187 checksumSalt, PBKDF2_HASH_ROUNDS);
2188
2189 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2190 + checksum.length + 3);
2191 DataOutputStream mkOut = new DataOutputStream(blob);
2192 mkOut.writeByte(IV.length);
2193 mkOut.write(IV);
2194 mkOut.writeByte(mk.length);
2195 mkOut.write(mk);
2196 mkOut.writeByte(checksum.length);
2197 mkOut.write(checksum);
2198 mkOut.flush();
2199 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2200 headerbuf.append(byteArrayToHex(encryptedMk));
2201 headerbuf.append('\n');
2202
2203 return finalOutput;
2204 }
2205
2206 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002207 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002208 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2209
2210 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2211 IApplicationThread.BACKUP_MODE_FULL);
2212 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002213 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002214 try {
Christopher Tate7926a692011-07-11 11:31:57 -07002215 pipes = ParcelFileDescriptor.createPipe();
2216
Christopher Tateb0628bf2011-06-02 15:08:13 -07002217 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07002218 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07002219 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2220 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2221 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2222
2223 sendOnBackupPackage(pkg.packageName);
2224
Christopher Tate7926a692011-07-11 11:31:57 -07002225 final int token = generateToken();
2226 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
2227 token, sendApk);
2228 pipes[1].close(); // the runner has dup'd it
2229 pipes[1] = null;
2230 Thread t = new Thread(runner);
2231 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002232
Christopher Tate7926a692011-07-11 11:31:57 -07002233 // Now pull data from the app and stuff it into the compressor
2234 try {
2235 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2236 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002237
Christopher Tate7926a692011-07-11 11:31:57 -07002238 byte[] buffer = new byte[16 * 1024];
2239 int chunkTotal;
2240 while ((chunkTotal = in.readInt()) > 0) {
2241 while (chunkTotal > 0) {
2242 int toRead = (chunkTotal > buffer.length)
2243 ? buffer.length : chunkTotal;
2244 int nRead = in.read(buffer, 0, toRead);
2245 out.write(buffer, 0, nRead);
2246 chunkTotal -= nRead;
2247 }
2248 }
2249 } catch (IOException e) {
2250 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002251 }
2252
Christopher Tateb0628bf2011-06-02 15:08:13 -07002253 if (!waitUntilOperationComplete(token)) {
2254 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2255 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002256 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002257 }
Christopher Tate7926a692011-07-11 11:31:57 -07002258
Christopher Tateb0628bf2011-06-02 15:08:13 -07002259 } catch (IOException e) {
2260 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002261 } finally {
2262 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002263 // flush after every package
2264 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002265 if (pipes != null) {
2266 if (pipes[0] != null) pipes[0].close();
2267 if (pipes[1] != null) pipes[1].close();
2268 }
Christopher Tate7926a692011-07-11 11:31:57 -07002269 } catch (IOException e) {
2270 Slog.w(TAG, "Error bringing down backup stack");
2271 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002272 }
2273 } else {
2274 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2275 }
2276 tearDown(pkg);
2277 }
2278
Christopher Tate79ec80d2011-06-24 14:58:49 -07002279 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2280 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2281 final String appSourceDir = pkg.applicationInfo.sourceDir;
2282 final String apkDir = new File(appSourceDir).getParent();
2283 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2284 apkDir, appSourceDir, output);
2285
2286 // Save associated .obb content if it exists and we did save the apk
2287 // check for .obb and save those too
2288 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2289 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002290 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002291 File[] obbFiles = obbDir.listFiles();
2292 if (obbFiles != null) {
2293 final String obbDirName = obbDir.getAbsolutePath();
2294 for (File obb : obbFiles) {
2295 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2296 obbDirName, obb.getAbsolutePath(), output);
2297 }
2298 }
2299 }
2300 }
2301
Christopher Tateb0628bf2011-06-02 15:08:13 -07002302 private void backupSharedStorage() throws RemoteException {
2303 PackageInfo pkg = null;
2304 try {
2305 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
2306 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2307 IApplicationThread.BACKUP_MODE_FULL);
2308 if (agent != null) {
2309 sendOnBackupPackage("Shared storage");
2310
2311 final int token = generateToken();
2312 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002313 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002314 if (!waitUntilOperationComplete(token)) {
2315 Slog.e(TAG, "Full backup failed on shared storage");
2316 } else {
2317 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
2318 }
2319 } else {
2320 Slog.e(TAG, "Could not bind to shared storage backup agent");
2321 }
2322 } catch (NameNotFoundException e) {
2323 Slog.e(TAG, "Shared storage backup package not found");
2324 } finally {
2325 tearDown(pkg);
2326 }
2327 }
2328
Christopher Tate4a627c72011-04-01 14:43:32 -07002329 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2330 throws IOException {
2331 // Manifest format. All data are strings ending in LF:
2332 // BACKUP_MANIFEST_VERSION, currently 1
2333 //
2334 // Version 1:
2335 // package name
2336 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002337 // platform versionCode
2338 // getInstallerPackageName() for this package (maybe empty)
2339 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002340 // number of signatures == N
2341 // N*: signature byte array in ascii format per Signature.toCharsString()
2342 StringBuilder builder = new StringBuilder(4096);
2343 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2344
2345 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2346 printer.println(pkg.packageName);
2347 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002348 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2349
2350 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2351 printer.println((installerName != null) ? installerName : "");
2352
Christopher Tate4a627c72011-04-01 14:43:32 -07002353 printer.println(withApk ? "1" : "0");
2354 if (pkg.signatures == null) {
2355 printer.println("0");
2356 } else {
2357 printer.println(Integer.toString(pkg.signatures.length));
2358 for (Signature sig : pkg.signatures) {
2359 printer.println(sig.toCharsString());
2360 }
2361 }
2362
2363 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002364 outstream.write(builder.toString().getBytes());
2365 outstream.close();
2366 }
2367
2368 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002369 if (pkg != null) {
2370 final ApplicationInfo app = pkg.applicationInfo;
2371 if (app != null) {
2372 try {
2373 // unbind and tidy up even on timeout or failure, just in case
2374 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002375
Christopher Tateb0628bf2011-06-02 15:08:13 -07002376 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002377 if (app.uid != Process.SYSTEM_UID
2378 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002379 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002380 mActivityManager.killApplicationProcess(app.processName, app.uid);
2381 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002382 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002383 }
2384 } catch (RemoteException e) {
2385 Slog.d(TAG, "Lost app trying to shut down");
2386 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002387 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002388 }
2389 }
2390
2391 // wrappers for observer use
2392 void sendStartBackup() {
2393 if (mObserver != null) {
2394 try {
2395 mObserver.onStartBackup();
2396 } catch (RemoteException e) {
2397 Slog.w(TAG, "full backup observer went away: startBackup");
2398 mObserver = null;
2399 }
2400 }
2401 }
2402
2403 void sendOnBackupPackage(String name) {
2404 if (mObserver != null) {
2405 try {
2406 // TODO: use a more user-friendly name string
2407 mObserver.onBackupPackage(name);
2408 } catch (RemoteException e) {
2409 Slog.w(TAG, "full backup observer went away: backupPackage");
2410 mObserver = null;
2411 }
2412 }
2413 }
2414
2415 void sendEndBackup() {
2416 if (mObserver != null) {
2417 try {
2418 mObserver.onEndBackup();
2419 } catch (RemoteException e) {
2420 Slog.w(TAG, "full backup observer went away: endBackup");
2421 mObserver = null;
2422 }
2423 }
2424 }
2425 }
2426
2427
Christopher Tate75a99702011-05-18 16:28:19 -07002428 // ----- Full restore from a file/socket -----
2429
2430 // Description of a file in the restore datastream
2431 static class FileMetadata {
2432 String packageName; // name of the owning app
2433 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002434 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002435 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2436 String path; // subpath within the semantic domain
2437 long mode; // e.g. 0666 (actually int)
2438 long mtime; // last mod time, UTC time_t (actually int)
2439 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002440
2441 @Override
2442 public String toString() {
2443 StringBuilder sb = new StringBuilder(128);
2444 sb.append("FileMetadata{");
2445 sb.append(packageName); sb.append(',');
2446 sb.append(type); sb.append(',');
2447 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2448 sb.append(size);
2449 sb.append('}');
2450 return sb.toString();
2451 }
Christopher Tate75a99702011-05-18 16:28:19 -07002452 }
2453
2454 enum RestorePolicy {
2455 IGNORE,
2456 ACCEPT,
2457 ACCEPT_IF_APK
2458 }
2459
2460 class PerformFullRestoreTask implements Runnable {
2461 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002462 String mCurrentPassword;
2463 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002464 IFullBackupRestoreObserver mObserver;
2465 AtomicBoolean mLatchObject;
2466 IBackupAgent mAgent;
2467 String mAgentPackage;
2468 ApplicationInfo mTargetApp;
2469 ParcelFileDescriptor[] mPipes = null;
2470
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002471 long mBytes;
2472
Christopher Tate75a99702011-05-18 16:28:19 -07002473 // possible handling states for a given package in the restore dataset
2474 final HashMap<String, RestorePolicy> mPackagePolicies
2475 = new HashMap<String, RestorePolicy>();
2476
2477 // installer package names for each encountered app, derived from the manifests
2478 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2479
2480 // Signatures for a given package found in its manifest file
2481 final HashMap<String, Signature[]> mManifestSignatures
2482 = new HashMap<String, Signature[]>();
2483
2484 // Packages we've already wiped data on when restoring their first file
2485 final HashSet<String> mClearedPackages = new HashSet<String>();
2486
Christopher Tate728a1c42011-07-28 18:03:03 -07002487 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002488 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002489 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002490 mCurrentPassword = curPassword;
2491 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002492 mObserver = observer;
2493 mLatchObject = latch;
2494 mAgent = null;
2495 mAgentPackage = null;
2496 mTargetApp = null;
2497
2498 // Which packages we've already wiped data on. We prepopulate this
2499 // with a whitelist of packages known to be unclearable.
2500 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002501 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002502
Christopher Tate75a99702011-05-18 16:28:19 -07002503 }
2504
2505 class RestoreFileRunnable implements Runnable {
2506 IBackupAgent mAgent;
2507 FileMetadata mInfo;
2508 ParcelFileDescriptor mSocket;
2509 int mToken;
2510
2511 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2512 ParcelFileDescriptor socket, int token) throws IOException {
2513 mAgent = agent;
2514 mInfo = info;
2515 mToken = token;
2516
2517 // This class is used strictly for process-local binder invocations. The
2518 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2519 // do not automatically get a 'dup'ed descriptor that we can can continue
2520 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2521 // before proceeding to do the restore.
2522 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2523 }
2524
2525 @Override
2526 public void run() {
2527 try {
2528 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2529 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2530 mToken, mBackupManagerBinder);
2531 } catch (RemoteException e) {
2532 // never happens; this is used strictly for local binder calls
2533 }
2534 }
2535 }
2536
2537 @Override
2538 public void run() {
2539 Slog.i(TAG, "--- Performing full-dataset restore ---");
2540 sendStartRestore();
2541
Christopher Tateb0628bf2011-06-02 15:08:13 -07002542 // Are we able to restore shared-storage data?
2543 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2544 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2545 }
2546
Christopher Tate2efd2db2011-07-19 16:32:49 -07002547 FileInputStream rawInStream = null;
2548 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002549 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002550 if (hasBackupPassword()) {
2551 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2552 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2553 return;
2554 }
2555 }
2556
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002557 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002558 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002559 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2560 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002561
2562 // First, parse out the unencrypted/uncompressed header
2563 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002564 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002565 final InputStream in;
2566
2567 boolean okay = false;
2568 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2569 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002570 rawDataIn.readFully(streamHeader);
2571 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2572 if (Arrays.equals(magicBytes, streamHeader)) {
2573 // okay, header looks good. now parse out the rest of the fields.
2574 String s = readHeaderLine(rawInStream);
2575 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2576 // okay, it's a version we recognize
2577 s = readHeaderLine(rawInStream);
2578 compressed = (Integer.parseInt(s) != 0);
2579 s = readHeaderLine(rawInStream);
2580 if (s.equals("none")) {
2581 // no more header to parse; we're good to go
2582 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07002583 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002584 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
2585 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07002586 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002587 }
2588 } else Slog.w(TAG, "Archive is encrypted but no password given");
2589 } else Slog.w(TAG, "Wrong header version: " + s);
2590 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002591
2592 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002593 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002594 return;
2595 }
2596
2597 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07002598 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07002599
2600 boolean didRestore;
2601 do {
Christopher Tate7926a692011-07-11 11:31:57 -07002602 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07002603 } while (didRestore);
2604
Christopher Tatec58efa62011-08-01 19:20:14 -07002605 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002606 } catch (IOException e) {
2607 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07002608 } finally {
2609 tearDownPipes();
2610 tearDownAgent(mTargetApp);
2611
2612 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002613 if (rawDataIn != null) rawDataIn.close();
2614 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07002615 mInputFile.close();
2616 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002617 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002618 /* nothing we can do about this */
2619 }
2620 synchronized (mCurrentOpLock) {
2621 mCurrentOperations.clear();
2622 }
2623 synchronized (mLatchObject) {
2624 mLatchObject.set(true);
2625 mLatchObject.notifyAll();
2626 }
2627 sendEndRestore();
2628 mWakelock.release();
Christopher Tatec58efa62011-08-01 19:20:14 -07002629 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07002630 }
2631 }
2632
Christopher Tate7bdb0962011-07-13 19:30:21 -07002633 String readHeaderLine(InputStream in) throws IOException {
2634 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002635 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002636 while ((c = in.read()) >= 0) {
2637 if (c == '\n') break; // consume and discard the newlines
2638 buffer.append((char)c);
2639 }
2640 return buffer.toString();
2641 }
2642
Christopher Tate2efd2db2011-07-19 16:32:49 -07002643 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
2644 InputStream result = null;
2645 try {
2646 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
2647
2648 String userSaltHex = readHeaderLine(rawInStream); // 5
2649 byte[] userSalt = hexToByteArray(userSaltHex);
2650
2651 String ckSaltHex = readHeaderLine(rawInStream); // 6
2652 byte[] ckSalt = hexToByteArray(ckSaltHex);
2653
2654 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
2655 String userIvHex = readHeaderLine(rawInStream); // 8
2656
2657 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
2658
2659 // decrypt the master key blob
2660 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07002661 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002662 rounds);
2663 byte[] IV = hexToByteArray(userIvHex);
2664 IvParameterSpec ivSpec = new IvParameterSpec(IV);
2665 c.init(Cipher.DECRYPT_MODE,
2666 new SecretKeySpec(userKey.getEncoded(), "AES"),
2667 ivSpec);
2668 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
2669 byte[] mkBlob = c.doFinal(mkCipher);
2670
2671 // first, the master key IV
2672 int offset = 0;
2673 int len = mkBlob[offset++];
2674 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
2675 offset += len;
2676 // then the master key itself
2677 len = mkBlob[offset++];
2678 byte[] mk = Arrays.copyOfRange(mkBlob,
2679 offset, offset + len);
2680 offset += len;
2681 // and finally the master key checksum hash
2682 len = mkBlob[offset++];
2683 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
2684 offset, offset + len);
2685
2686 // now validate the decrypted master key against the checksum
2687 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
2688 if (Arrays.equals(calculatedCk, mkChecksum)) {
2689 ivSpec = new IvParameterSpec(IV);
2690 c.init(Cipher.DECRYPT_MODE,
2691 new SecretKeySpec(mk, "AES"),
2692 ivSpec);
2693 // Only if all of the above worked properly will 'result' be assigned
2694 result = new CipherInputStream(rawInStream, c);
2695 } else Slog.w(TAG, "Incorrect password");
2696 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
2697 } catch (InvalidAlgorithmParameterException e) {
2698 Slog.e(TAG, "Needed parameter spec unavailable!", e);
2699 } catch (BadPaddingException e) {
2700 // This case frequently occurs when the wrong password is used to decrypt
2701 // the master key. Use the identical "incorrect password" log text as is
2702 // used in the checksum failure log in order to avoid providing additional
2703 // information to an attacker.
2704 Slog.w(TAG, "Incorrect password");
2705 } catch (IllegalBlockSizeException e) {
2706 Slog.w(TAG, "Invalid block size in master key");
2707 } catch (NoSuchAlgorithmException e) {
2708 Slog.e(TAG, "Needed decryption algorithm unavailable!");
2709 } catch (NoSuchPaddingException e) {
2710 Slog.e(TAG, "Needed padding mechanism unavailable!");
2711 } catch (InvalidKeyException e) {
2712 Slog.w(TAG, "Illegal password; aborting");
2713 } catch (NumberFormatException e) {
2714 Slog.w(TAG, "Can't parse restore data header");
2715 } catch (IOException e) {
2716 Slog.w(TAG, "Can't read input header");
2717 }
2718
2719 return result;
2720 }
2721
Christopher Tate75a99702011-05-18 16:28:19 -07002722 boolean restoreOneFile(InputStream instream, byte[] buffer) {
2723 FileMetadata info;
2724 try {
2725 info = readTarHeaders(instream);
2726 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002727 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07002728 dumpFileMetadata(info);
2729 }
2730
2731 final String pkg = info.packageName;
2732 if (!pkg.equals(mAgentPackage)) {
2733 // okay, change in package; set up our various
2734 // bookkeeping if we haven't seen it yet
2735 if (!mPackagePolicies.containsKey(pkg)) {
2736 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2737 }
2738
2739 // Clean up the previous agent relationship if necessary,
2740 // and let the observer know we're considering a new app.
2741 if (mAgent != null) {
2742 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
2743 tearDownPipes();
2744 tearDownAgent(mTargetApp);
2745 mTargetApp = null;
2746 mAgentPackage = null;
2747 }
2748 }
2749
2750 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
2751 mPackagePolicies.put(pkg, readAppManifest(info, instream));
2752 mPackageInstallers.put(pkg, info.installerPackageName);
2753 // We've read only the manifest content itself at this point,
2754 // so consume the footer before looping around to the next
2755 // input file
2756 skipTarPadding(info.size, instream);
2757 sendOnRestorePackage(pkg);
2758 } else {
2759 // Non-manifest, so it's actual file data. Is this a package
2760 // we're ignoring?
2761 boolean okay = true;
2762 RestorePolicy policy = mPackagePolicies.get(pkg);
2763 switch (policy) {
2764 case IGNORE:
2765 okay = false;
2766 break;
2767
2768 case ACCEPT_IF_APK:
2769 // If we're in accept-if-apk state, then the first file we
2770 // see MUST be the apk.
2771 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2772 if (DEBUG) Slog.d(TAG, "APK file; installing");
2773 // Try to install the app.
2774 String installerName = mPackageInstallers.get(pkg);
2775 okay = installApk(info, installerName, instream);
2776 // good to go; promote to ACCEPT
2777 mPackagePolicies.put(pkg, (okay)
2778 ? RestorePolicy.ACCEPT
2779 : RestorePolicy.IGNORE);
2780 // At this point we've consumed this file entry
2781 // ourselves, so just strip the tar footer and
2782 // go on to the next file in the input stream
2783 skipTarPadding(info.size, instream);
2784 return true;
2785 } else {
2786 // File data before (or without) the apk. We can't
2787 // handle it coherently in this case so ignore it.
2788 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2789 okay = false;
2790 }
2791 break;
2792
2793 case ACCEPT:
2794 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2795 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
2796 // we can take the data without the apk, so we
2797 // *want* to do so. skip the apk by declaring this
2798 // one file not-okay without changing the restore
2799 // policy for the package.
2800 okay = false;
2801 }
2802 break;
2803
2804 default:
2805 // Something has gone dreadfully wrong when determining
2806 // the restore policy from the manifest. Ignore the
2807 // rest of this package's data.
2808 Slog.e(TAG, "Invalid policy from manifest");
2809 okay = false;
2810 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2811 break;
2812 }
2813
2814 // If the policy is satisfied, go ahead and set up to pipe the
2815 // data to the agent.
2816 if (DEBUG && okay && mAgent != null) {
2817 Slog.i(TAG, "Reusing existing agent instance");
2818 }
2819 if (okay && mAgent == null) {
2820 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
2821
2822 try {
2823 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
2824
2825 // If we haven't sent any data to this app yet, we probably
2826 // need to clear it first. Check that.
2827 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002828 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07002829 // responsible for coherently managing a full
2830 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07002831 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07002832 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
2833 clearApplicationDataSynchronous(pkg);
2834 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002835 if (DEBUG) Slog.d(TAG, "backup agent ("
2836 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07002837 }
2838 mClearedPackages.add(pkg);
2839 } else {
2840 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
2841 }
2842
2843 // All set; now set up the IPC and launch the agent
2844 setUpPipes();
2845 mAgent = bindToAgentSynchronous(mTargetApp,
2846 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
2847 mAgentPackage = pkg;
2848 } catch (IOException e) {
2849 // fall through to error handling
2850 } catch (NameNotFoundException e) {
2851 // fall through to error handling
2852 }
2853
2854 if (mAgent == null) {
2855 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
2856 okay = false;
2857 tearDownPipes();
2858 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2859 }
2860 }
2861
2862 // Sanity check: make sure we never give data to the wrong app. This
2863 // should never happen but a little paranoia here won't go amiss.
2864 if (okay && !pkg.equals(mAgentPackage)) {
2865 Slog.e(TAG, "Restoring data for " + pkg
2866 + " but agent is for " + mAgentPackage);
2867 okay = false;
2868 }
2869
2870 // At this point we have an agent ready to handle the full
2871 // restore data as well as a pipe for sending data to
2872 // that agent. Tell the agent to start reading from the
2873 // pipe.
2874 if (okay) {
2875 boolean agentSuccess = true;
2876 long toCopy = info.size;
2877 final int token = generateToken();
2878 try {
2879 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
2880 + info.path);
2881 prepareOperationTimeout(token,
2882 TIMEOUT_FULL_BACKUP_INTERVAL);
2883 // fire up the app's agent listening on the socket. If
2884 // the agent is running in the system process we can't
2885 // just invoke it asynchronously, so we provide a thread
2886 // for it here.
2887 if (mTargetApp.processName.equals("system")) {
2888 Slog.d(TAG, "system process agent - spinning a thread");
2889 RestoreFileRunnable runner = new RestoreFileRunnable(
2890 mAgent, info, mPipes[0], token);
2891 new Thread(runner).start();
2892 } else {
2893 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
2894 info.domain, info.path, info.mode, info.mtime,
2895 token, mBackupManagerBinder);
2896 }
2897 } catch (IOException e) {
2898 // couldn't dup the socket for a process-local restore
2899 Slog.d(TAG, "Couldn't establish restore");
2900 agentSuccess = false;
2901 okay = false;
2902 } catch (RemoteException e) {
2903 // whoops, remote agent went away. We'll eat the content
2904 // ourselves, then, and not copy it over.
2905 Slog.e(TAG, "Agent crashed during full restore");
2906 agentSuccess = false;
2907 okay = false;
2908 }
2909
2910 // Copy over the data if the agent is still good
2911 if (okay) {
2912 boolean pipeOkay = true;
2913 FileOutputStream pipe = new FileOutputStream(
2914 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07002915 while (toCopy > 0) {
2916 int toRead = (toCopy > buffer.length)
2917 ? buffer.length : (int)toCopy;
2918 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002919 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002920 if (nRead <= 0) break;
2921 toCopy -= nRead;
2922
2923 // send it to the output pipe as long as things
2924 // are still good
2925 if (pipeOkay) {
2926 try {
2927 pipe.write(buffer, 0, nRead);
2928 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002929 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002930 pipeOkay = false;
2931 }
2932 }
2933 }
2934
2935 // done sending that file! Now we just need to consume
2936 // the delta from info.size to the end of block.
2937 skipTarPadding(info.size, instream);
2938
2939 // and now that we've sent it all, wait for the remote
2940 // side to acknowledge receipt
2941 agentSuccess = waitUntilOperationComplete(token);
2942 }
2943
2944 // okay, if the remote end failed at any point, deal with
2945 // it by ignoring the rest of the restore on it
2946 if (!agentSuccess) {
2947 mBackupHandler.removeMessages(MSG_TIMEOUT);
2948 tearDownPipes();
2949 tearDownAgent(mTargetApp);
2950 mAgent = null;
2951 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2952 }
2953 }
2954
2955 // Problems setting up the agent communication, or an already-
2956 // ignored package: skip to the next tar stream entry by
2957 // reading and discarding this file.
2958 if (!okay) {
2959 if (DEBUG) Slog.d(TAG, "[discarding file content]");
2960 long bytesToConsume = (info.size + 511) & ~511;
2961 while (bytesToConsume > 0) {
2962 int toRead = (bytesToConsume > buffer.length)
2963 ? buffer.length : (int)bytesToConsume;
2964 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002965 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002966 if (nRead <= 0) break;
2967 bytesToConsume -= nRead;
2968 }
2969 }
2970 }
2971 }
2972 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002973 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002974 // treat as EOF
2975 info = null;
2976 }
2977
2978 return (info != null);
2979 }
2980
2981 void setUpPipes() throws IOException {
2982 mPipes = ParcelFileDescriptor.createPipe();
2983 }
2984
2985 void tearDownPipes() {
2986 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002987 try {
2988 mPipes[0].close();
2989 mPipes[0] = null;
2990 mPipes[1].close();
2991 mPipes[1] = null;
2992 } catch (IOException e) {
2993 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002994 }
2995 mPipes = null;
2996 }
2997 }
2998
2999 void tearDownAgent(ApplicationInfo app) {
3000 if (mAgent != null) {
3001 try {
3002 // unbind and tidy up even on timeout or failure, just in case
3003 mActivityManager.unbindBackupAgent(app);
3004
3005 // The agent was running with a stub Application object, so shut it down.
3006 // !!! We hardcode the confirmation UI's package name here rather than use a
3007 // manifest flag! TODO something less direct.
3008 if (app.uid != Process.SYSTEM_UID
3009 && !app.packageName.equals("com.android.backupconfirm")) {
3010 if (DEBUG) Slog.d(TAG, "Killing host process");
3011 mActivityManager.killApplicationProcess(app.processName, app.uid);
3012 } else {
3013 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3014 }
3015 } catch (RemoteException e) {
3016 Slog.d(TAG, "Lost app trying to shut down");
3017 }
3018 mAgent = null;
3019 }
3020 }
3021
3022 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3023 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003024 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003025 int mResult;
3026
3027 public void reset() {
3028 synchronized (mDone) {
3029 mDone.set(false);
3030 }
3031 }
3032
3033 public void waitForCompletion() {
3034 synchronized (mDone) {
3035 while (mDone.get() == false) {
3036 try {
3037 mDone.wait();
3038 } catch (InterruptedException e) { }
3039 }
3040 }
3041 }
3042
3043 int getResult() {
3044 return mResult;
3045 }
3046
3047 @Override
3048 public void packageInstalled(String packageName, int returnCode)
3049 throws RemoteException {
3050 synchronized (mDone) {
3051 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003052 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003053 mDone.set(true);
3054 mDone.notifyAll();
3055 }
3056 }
3057 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003058
3059 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3060 final AtomicBoolean mDone = new AtomicBoolean();
3061 int mResult;
3062
3063 public void reset() {
3064 synchronized (mDone) {
3065 mDone.set(false);
3066 }
3067 }
3068
3069 public void waitForCompletion() {
3070 synchronized (mDone) {
3071 while (mDone.get() == false) {
3072 try {
3073 mDone.wait();
3074 } catch (InterruptedException e) { }
3075 }
3076 }
3077 }
3078
3079 @Override
3080 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3081 synchronized (mDone) {
3082 mResult = returnCode;
3083 mDone.set(true);
3084 mDone.notifyAll();
3085 }
3086 }
3087 }
3088
Christopher Tate75a99702011-05-18 16:28:19 -07003089 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003090 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003091
3092 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3093 boolean okay = true;
3094
3095 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3096
3097 // The file content is an .apk file. Copy it out to a staging location and
3098 // attempt to install it.
3099 File apkFile = new File(mDataDir, info.packageName);
3100 try {
3101 FileOutputStream apkStream = new FileOutputStream(apkFile);
3102 byte[] buffer = new byte[32 * 1024];
3103 long size = info.size;
3104 while (size > 0) {
3105 long toRead = (buffer.length < size) ? buffer.length : size;
3106 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003107 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003108 apkStream.write(buffer, 0, didRead);
3109 size -= didRead;
3110 }
3111 apkStream.close();
3112
3113 // make sure the installer can read it
3114 apkFile.setReadable(true, false);
3115
3116 // Now install it
3117 Uri packageUri = Uri.fromFile(apkFile);
3118 mInstallObserver.reset();
3119 mPackageManager.installPackage(packageUri, mInstallObserver,
3120 PackageManager.INSTALL_REPLACE_EXISTING, installerPackage);
3121 mInstallObserver.waitForCompletion();
3122
3123 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3124 // The only time we continue to accept install of data even if the
3125 // apk install failed is if we had already determined that we could
3126 // accept the data regardless.
3127 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3128 okay = false;
3129 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003130 } else {
3131 // Okay, the install succeeded. Make sure it was the right app.
3132 boolean uninstall = false;
3133 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3134 Slog.w(TAG, "Restore stream claimed to include apk for "
3135 + info.packageName + " but apk was really "
3136 + mInstallObserver.mPackageName);
3137 // delete the package we just put in place; it might be fraudulent
3138 okay = false;
3139 uninstall = true;
3140 } else {
3141 try {
3142 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3143 PackageManager.GET_SIGNATURES);
3144 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3145 Slog.w(TAG, "Restore stream contains apk of package "
3146 + info.packageName + " but it disallows backup/restore");
3147 okay = false;
3148 } else {
3149 // So far so good -- do the signatures match the manifest?
3150 Signature[] sigs = mManifestSignatures.get(info.packageName);
3151 if (!signaturesMatch(sigs, pkg)) {
3152 Slog.w(TAG, "Installed app " + info.packageName
3153 + " signatures do not match restore manifest");
3154 okay = false;
3155 uninstall = true;
3156 }
3157 }
3158 } catch (NameNotFoundException e) {
3159 Slog.w(TAG, "Install of package " + info.packageName
3160 + " succeeded but now not found");
3161 okay = false;
3162 }
3163 }
3164
3165 // If we're not okay at this point, we need to delete the package
3166 // that we just installed.
3167 if (uninstall) {
3168 mDeleteObserver.reset();
3169 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3170 mDeleteObserver, 0);
3171 mDeleteObserver.waitForCompletion();
3172 }
Christopher Tate75a99702011-05-18 16:28:19 -07003173 }
3174 } catch (IOException e) {
3175 Slog.e(TAG, "Unable to transcribe restored apk for install");
3176 okay = false;
3177 } finally {
3178 apkFile.delete();
3179 }
3180
3181 return okay;
3182 }
3183
3184 // Given an actual file content size, consume the post-content padding mandated
3185 // by the tar format.
3186 void skipTarPadding(long size, InputStream instream) throws IOException {
3187 long partial = (size + 512) % 512;
3188 if (partial > 0) {
3189 byte[] buffer = new byte[512];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003190 int nRead = instream.read(buffer, 0, 512 - (int)partial);
3191 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003192 }
3193 }
3194
3195 // Returns a policy constant; takes a buffer arg to reduce memory churn
3196 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3197 throws IOException {
3198 // Fail on suspiciously large manifest files
3199 if (info.size > 64 * 1024) {
3200 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3201 }
3202 byte[] buffer = new byte[(int) info.size];
3203 int nRead = 0;
3204 while (nRead < info.size) {
3205 nRead += instream.read(buffer, nRead, (int)info.size - nRead);
3206 }
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003207 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003208
3209 RestorePolicy policy = RestorePolicy.IGNORE;
3210 String[] str = new String[1];
3211 int offset = 0;
3212
3213 try {
3214 offset = extractLine(buffer, offset, str);
3215 int version = Integer.parseInt(str[0]);
3216 if (version == BACKUP_MANIFEST_VERSION) {
3217 offset = extractLine(buffer, offset, str);
3218 String manifestPackage = str[0];
3219 // TODO: handle <original-package>
3220 if (manifestPackage.equals(info.packageName)) {
3221 offset = extractLine(buffer, offset, str);
3222 version = Integer.parseInt(str[0]); // app version
3223 offset = extractLine(buffer, offset, str);
3224 int platformVersion = Integer.parseInt(str[0]);
3225 offset = extractLine(buffer, offset, str);
3226 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3227 offset = extractLine(buffer, offset, str);
3228 boolean hasApk = str[0].equals("1");
3229 offset = extractLine(buffer, offset, str);
3230 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003231 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003232 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003233 for (int i = 0; i < numSigs; i++) {
3234 offset = extractLine(buffer, offset, str);
3235 sigs[i] = new Signature(str[0]);
3236 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003237 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003238
3239 // Okay, got the manifest info we need...
3240 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003241 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3242 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003243 // Fall through to IGNORE if the app explicitly disallows backup
3244 final int flags = pkgInfo.applicationInfo.flags;
3245 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3246 // Verify signatures against any installed version; if they
3247 // don't match, then we fall though and ignore the data. The
3248 // signatureMatch() method explicitly ignores the signature
3249 // check for packages installed on the system partition, because
3250 // such packages are signed with the platform cert instead of
3251 // the app developer's cert, so they're different on every
3252 // device.
3253 if (signaturesMatch(sigs, pkgInfo)) {
3254 if (pkgInfo.versionCode >= version) {
3255 Slog.i(TAG, "Sig + version match; taking data");
3256 policy = RestorePolicy.ACCEPT;
3257 } else {
3258 // The data is from a newer version of the app than
3259 // is presently installed. That means we can only
3260 // use it if the matching apk is also supplied.
3261 Slog.d(TAG, "Data version " + version
3262 + " is newer than installed version "
3263 + pkgInfo.versionCode + " - requiring apk");
3264 policy = RestorePolicy.ACCEPT_IF_APK;
3265 }
Christopher Tate75a99702011-05-18 16:28:19 -07003266 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003267 Slog.w(TAG, "Restore manifest signatures do not match "
3268 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003269 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003270 } else {
3271 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3272 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003273 }
3274 } catch (NameNotFoundException e) {
3275 // Okay, the target app isn't installed. We can process
3276 // the restore properly only if the dataset provides the
3277 // apk file and we can successfully install it.
3278 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3279 + " not installed; requiring apk in dataset");
3280 policy = RestorePolicy.ACCEPT_IF_APK;
3281 }
3282
3283 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3284 Slog.i(TAG, "Cannot restore package " + info.packageName
3285 + " without the matching .apk");
3286 }
3287 } else {
3288 Slog.i(TAG, "Missing signature on backed-up package "
3289 + info.packageName);
3290 }
3291 } else {
3292 Slog.i(TAG, "Expected package " + info.packageName
3293 + " but restore manifest claims " + manifestPackage);
3294 }
3295 } else {
3296 Slog.i(TAG, "Unknown restore manifest version " + version
3297 + " for package " + info.packageName);
3298 }
3299 } catch (NumberFormatException e) {
3300 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
3301 }
3302
3303 return policy;
3304 }
3305
3306 // Builds a line from a byte buffer starting at 'offset', and returns
3307 // the index of the next unconsumed data in the buffer.
3308 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3309 final int end = buffer.length;
3310 if (offset >= end) throw new IOException("Incomplete data");
3311
3312 int pos;
3313 for (pos = offset; pos < end; pos++) {
3314 byte c = buffer[pos];
3315 // at LF we declare end of line, and return the next char as the
3316 // starting point for the next time through
3317 if (c == '\n') {
3318 break;
3319 }
3320 }
3321 outStr[0] = new String(buffer, offset, pos - offset);
3322 pos++; // may be pointing an extra byte past the end but that's okay
3323 return pos;
3324 }
3325
3326 void dumpFileMetadata(FileMetadata info) {
3327 if (DEBUG) {
3328 StringBuilder b = new StringBuilder(128);
3329
3330 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003331 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003332 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3333 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3334 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3335 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3336 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3337 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3338 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3339 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3340 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3341 b.append(String.format(" %9d ", info.size));
3342
3343 Date stamp = new Date(info.mtime);
3344 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3345
3346 b.append(info.packageName);
3347 b.append(" :: ");
3348 b.append(info.domain);
3349 b.append(" :: ");
3350 b.append(info.path);
3351
3352 Slog.i(TAG, b.toString());
3353 }
3354 }
3355 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3356 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3357 byte[] block = new byte[512];
3358 FileMetadata info = null;
3359
3360 boolean gotHeader = readTarHeader(instream, block);
3361 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003362 try {
3363 // okay, presume we're okay, and extract the various metadata
3364 info = new FileMetadata();
3365 info.size = extractRadix(block, 124, 12, 8);
3366 info.mtime = extractRadix(block, 136, 12, 8);
3367 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003368
Christopher Tate2efd2db2011-07-19 16:32:49 -07003369 info.path = extractString(block, 345, 155); // prefix
3370 String path = extractString(block, 0, 100);
3371 if (path.length() > 0) {
3372 if (info.path.length() > 0) info.path += '/';
3373 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003374 }
Christopher Tate75a99702011-05-18 16:28:19 -07003375
Christopher Tate2efd2db2011-07-19 16:32:49 -07003376 // tar link indicator field: 1 byte at offset 156 in the header.
3377 int typeChar = block[156];
3378 if (typeChar == 'x') {
3379 // pax extended header, so we need to read that
3380 gotHeader = readPaxExtendedHeader(instream, info);
3381 if (gotHeader) {
3382 // and after a pax extended header comes another real header -- read
3383 // that to find the real file type
3384 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003385 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003386 if (!gotHeader) throw new IOException("Bad or missing pax header");
3387
3388 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003389 }
Christopher Tate75a99702011-05-18 16:28:19 -07003390
Christopher Tate2efd2db2011-07-19 16:32:49 -07003391 switch (typeChar) {
3392 case '0': info.type = BackupAgent.TYPE_FILE; break;
3393 case '5': {
3394 info.type = BackupAgent.TYPE_DIRECTORY;
3395 if (info.size != 0) {
3396 Slog.w(TAG, "Directory entry with nonzero size in header");
3397 info.size = 0;
3398 }
3399 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003400 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003401 case 0: {
3402 // presume EOF
3403 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3404 return null;
3405 }
3406 default: {
3407 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3408 throw new IOException("Unknown entity type " + typeChar);
3409 }
Christopher Tate75a99702011-05-18 16:28:19 -07003410 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003411
3412 // Parse out the path
3413 //
3414 // first: apps/shared/unrecognized
3415 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3416 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3417 // File in shared storage. !!! TODO: implement this.
3418 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
3419 info.packageName = "com.android.sharedstoragebackup";
3420 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3421 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3422 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3423 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3424 // App content! Parse out the package name and domain
3425
3426 // strip the apps/ prefix
3427 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3428
3429 // extract the package name
3430 int slash = info.path.indexOf('/');
3431 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3432 info.packageName = info.path.substring(0, slash);
3433 info.path = info.path.substring(slash+1);
3434
3435 // if it's a manifest we're done, otherwise parse out the domains
3436 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3437 slash = info.path.indexOf('/');
3438 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3439 info.domain = info.path.substring(0, slash);
3440 // validate that it's one of the domains we understand
3441 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3442 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3443 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3444 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3445 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3446 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3447 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3448 throw new IOException("Unrecognized domain " + info.domain);
3449 }
3450
3451 info.path = info.path.substring(slash + 1);
3452 }
3453 }
3454 } catch (IOException e) {
3455 if (DEBUG) {
3456 Slog.e(TAG, "Parse error in header. Hexdump:");
3457 HEXLOG(block);
3458 }
3459 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003460 }
3461 }
3462 return info;
3463 }
3464
Christopher Tate2efd2db2011-07-19 16:32:49 -07003465 private void HEXLOG(byte[] block) {
3466 int offset = 0;
3467 int todo = block.length;
3468 StringBuilder buf = new StringBuilder(64);
3469 while (todo > 0) {
3470 buf.append(String.format("%04x ", offset));
3471 int numThisLine = (todo > 16) ? 16 : todo;
3472 for (int i = 0; i < numThisLine; i++) {
3473 buf.append(String.format("%02x ", block[offset+i]));
3474 }
3475 Slog.i("hexdump", buf.toString());
3476 buf.setLength(0);
3477 todo -= numThisLine;
3478 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003479 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003480 }
3481
3482 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3483 int totalRead = 0;
3484 while (totalRead < 512) {
3485 int nRead = instream.read(block, totalRead, 512 - totalRead);
3486 if (nRead >= 0) {
3487 mBytes += nRead;
3488 totalRead += nRead;
3489 } else {
3490 if (totalRead == 0) {
3491 // EOF instead of a new header; we're done
3492 break;
3493 }
3494 throw new IOException("Unable to read full block header, t=" + totalRead);
3495 }
3496 }
3497 return (totalRead == 512);
Christopher Tate75a99702011-05-18 16:28:19 -07003498 }
3499
3500 // overwrites 'info' fields based on the pax extended header
3501 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3502 throws IOException {
3503 // We should never see a pax extended header larger than this
3504 if (info.size > 32*1024) {
3505 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3506 + " - aborting");
3507 throw new IOException("Sanity failure: pax header size " + info.size);
3508 }
3509
3510 // read whole blocks, not just the content size
3511 int numBlocks = (int)((info.size + 511) >> 9);
3512 byte[] data = new byte[numBlocks * 512];
3513 int nRead = instream.read(data);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003514 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003515 if (nRead != data.length) {
3516 return false;
3517 }
3518
3519 final int contentSize = (int) info.size;
3520 int offset = 0;
3521 do {
3522 // extract the line at 'offset'
3523 int eol = offset+1;
3524 while (eol < contentSize && data[eol] != ' ') eol++;
3525 if (eol >= contentSize) {
3526 // error: we just hit EOD looking for the end of the size field
3527 throw new IOException("Invalid pax data");
3528 }
3529 // eol points to the space between the count and the key
3530 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3531 int key = eol + 1; // start of key=value
3532 eol = offset + linelen - 1; // trailing LF
3533 int value;
3534 for (value = key+1; data[value] != '=' && value <= eol; value++);
3535 if (value > eol) {
3536 throw new IOException("Invalid pax declaration");
3537 }
3538
3539 // pax requires that key/value strings be in UTF-8
3540 String keyStr = new String(data, key, value-key, "UTF-8");
3541 // -1 to strip the trailing LF
3542 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3543
3544 if ("path".equals(keyStr)) {
3545 info.path = valStr;
3546 } else if ("size".equals(keyStr)) {
3547 info.size = Long.parseLong(valStr);
3548 } else {
3549 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3550 }
3551
3552 offset += linelen;
3553 } while (offset < contentSize);
3554
3555 return true;
3556 }
3557
3558 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3559 throws IOException {
3560 long value = 0;
3561 final int end = offset + maxChars;
3562 for (int i = offset; i < end; i++) {
3563 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003564 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003565 if (b == 0 || b == ' ') break;
3566 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003567 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07003568 }
3569 value = radix * value + (b - '0');
3570 }
3571 return value;
3572 }
3573
3574 String extractString(byte[] data, int offset, int maxChars) throws IOException {
3575 final int end = offset + maxChars;
3576 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003577 // tar string fields terminate early with a NUL
3578 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07003579 return new String(data, offset, eos-offset, "US-ASCII");
3580 }
3581
3582 void sendStartRestore() {
3583 if (mObserver != null) {
3584 try {
3585 mObserver.onStartRestore();
3586 } catch (RemoteException e) {
3587 Slog.w(TAG, "full restore observer went away: startRestore");
3588 mObserver = null;
3589 }
3590 }
3591 }
3592
3593 void sendOnRestorePackage(String name) {
3594 if (mObserver != null) {
3595 try {
3596 // TODO: use a more user-friendly name string
3597 mObserver.onRestorePackage(name);
3598 } catch (RemoteException e) {
3599 Slog.w(TAG, "full restore observer went away: restorePackage");
3600 mObserver = null;
3601 }
3602 }
3603 }
3604
3605 void sendEndRestore() {
3606 if (mObserver != null) {
3607 try {
3608 mObserver.onEndRestore();
3609 } catch (RemoteException e) {
3610 Slog.w(TAG, "full restore observer went away: endRestore");
3611 mObserver = null;
3612 }
3613 }
3614 }
3615 }
3616
Christopher Tatedf01dea2009-06-09 20:45:02 -07003617 // ----- Restore handling -----
3618
Christopher Tate78dd4a72009-11-04 11:49:08 -08003619 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
3620 // If the target resides on the system partition, we allow it to restore
3621 // data from the like-named package in a restore set even if the signatures
3622 // do not match. (Unlike general applications, those flashed to the system
3623 // partition will be signed with the device's platform certificate, so on
3624 // different phones the same system app will have different signatures.)
3625 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003626 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08003627 return true;
3628 }
3629
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003630 // Allow unsigned apps, but not signed on one device and unsigned on the other
3631 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08003632 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07003633 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07003634 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003635 if ((storedSigs == null || storedSigs.length == 0)
3636 && (deviceSigs == null || deviceSigs.length == 0)) {
3637 return true;
3638 }
3639 if (storedSigs == null || deviceSigs == null) {
3640 return false;
3641 }
3642
Christopher Tateabce4e82009-06-18 18:35:32 -07003643 // !!! TODO: this demands that every stored signature match one
3644 // that is present on device, and does not demand the converse.
3645 // Is this this right policy?
3646 int nStored = storedSigs.length;
3647 int nDevice = deviceSigs.length;
3648
3649 for (int i=0; i < nStored; i++) {
3650 boolean match = false;
3651 for (int j=0; j < nDevice; j++) {
3652 if (storedSigs[i].equals(deviceSigs[j])) {
3653 match = true;
3654 break;
3655 }
3656 }
3657 if (!match) {
3658 return false;
3659 }
3660 }
3661 return true;
3662 }
3663
Christopher Tate44a27902010-01-27 17:15:49 -08003664 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003665 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003666 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003667 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003668 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003669 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003670 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003671 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07003672 private HashSet<String> mFilterSet;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003673
Christopher Tate5cbbf562009-06-22 16:44:51 -07003674 class RestoreRequest {
3675 public PackageInfo app;
3676 public int storedAppVersion;
3677
3678 RestoreRequest(PackageInfo _app, int _version) {
3679 app = _app;
3680 storedAppVersion = _version;
3681 }
3682 }
3683
Christopher Tate44a27902010-01-27 17:15:49 -08003684 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07003685 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07003686 boolean needFullBackup, String[] filterSet) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003687 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003688 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003689 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08003690 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08003691 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003692 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003693
Christopher Tate284f1bb2011-07-07 14:31:18 -07003694 if (filterSet != null) {
3695 mFilterSet = new HashSet<String>();
3696 for (String pkg : filterSet) {
3697 mFilterSet.add(pkg);
3698 }
3699 } else {
3700 mFilterSet = null;
3701 }
3702
Christopher Tate5cb400b2009-06-25 16:03:14 -07003703 try {
3704 mStateDir = new File(mBaseStateDir, transport.transportDirName());
3705 } catch (RemoteException e) {
3706 // can't happen; the transport is local
3707 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003708 }
3709
Christopher Tatedf01dea2009-06-09 20:45:02 -07003710 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003711 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003712 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08003713 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate284f1bb2011-07-07 14:31:18 -07003714 + " mTargetPackage=" + mTargetPackage + " mFilterSet=" + mFilterSet
3715 + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003716
Christopher Tateb49ceb32010-02-08 16:22:24 -08003717 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003718 int error = -1; // assume error
3719
Dan Egnorefe52642009-06-24 00:16:33 -07003720 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07003721 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003722 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003723 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07003724
Dan Egnorefe52642009-06-24 00:16:33 -07003725 // Get the list of all packages which have backup enabled.
3726 // (Include the Package Manager metadata pseudo-package first.)
3727 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
3728 PackageInfo omPackage = new PackageInfo();
3729 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
3730 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003731
Dan Egnorefe52642009-06-24 00:16:33 -07003732 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003733 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07003734 // if there's a filter set, strip out anything that isn't
3735 // present before proceeding
3736 if (mFilterSet != null) {
3737 for (int i = agentPackages.size() - 1; i >= 0; i--) {
3738 final PackageInfo pkg = agentPackages.get(i);
3739 if (! mFilterSet.contains(pkg.packageName)) {
3740 agentPackages.remove(i);
3741 }
3742 }
3743 if (DEBUG) {
3744 Slog.i(TAG, "Post-filter package set for restore:");
3745 for (PackageInfo p : agentPackages) {
3746 Slog.i(TAG, " " + p);
3747 }
3748 }
3749 }
Christopher Tate84725812010-02-04 15:52:40 -08003750 restorePackages.addAll(agentPackages);
3751 } else {
3752 // Just one package to attempt restore of
3753 restorePackages.add(mTargetPackage);
3754 }
Dan Egnorefe52642009-06-24 00:16:33 -07003755
Christopher Tate7d562ec2009-06-25 18:03:43 -07003756 // let the observer know that we're running
3757 if (mObserver != null) {
3758 try {
3759 // !!! TODO: get an actual count from the transport after
3760 // its startRestore() runs?
3761 mObserver.restoreStarting(restorePackages.size());
3762 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003763 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003764 mObserver = null;
3765 }
3766 }
3767
Dan Egnor01445162009-09-21 17:04:05 -07003768 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
3769 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003770 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003771 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003772 return;
3773 }
3774
3775 String packageName = mTransport.nextRestorePackage();
3776 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003777 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003778 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003779 return;
3780 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003781 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003782 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003783 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07003784 return;
3785 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003786 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07003787 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003788 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003789 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003790 return;
3791 }
3792
3793 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08003794 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07003795 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07003796 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
3797 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07003798
Christopher Tate8c032472009-07-02 14:28:47 -07003799 // Verify that the backup set includes metadata. If not, we can't do
3800 // signature/version verification etc, so we simply do not proceed with
3801 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07003802 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003803 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003804 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003805 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07003806 return;
3807 }
3808
Christopher Tate7d562ec2009-06-25 18:03:43 -07003809 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07003810 for (;;) {
3811 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003812
Dan Egnorefe52642009-06-24 00:16:33 -07003813 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003814 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003815 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003816 return;
3817 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003818 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07003819 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003820 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003821
Christopher Tate7d562ec2009-06-25 18:03:43 -07003822 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07003823 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07003824 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07003825 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003826 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003827 mObserver = null;
3828 }
3829 }
3830
Dan Egnorefe52642009-06-24 00:16:33 -07003831 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
3832 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003833 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003834 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003835 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003836 continue;
3837 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003838
Dan Egnorbb9001c2009-07-27 12:20:13 -07003839 PackageInfo packageInfo;
3840 try {
3841 int flags = PackageManager.GET_SIGNATURES;
3842 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
3843 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003844 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003845 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003846 "Package missing on device");
3847 continue;
3848 }
3849
Dan Egnorefe52642009-06-24 00:16:33 -07003850 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08003851 // Data is from a "newer" version of the app than we have currently
3852 // installed. If the app has not declared that it is prepared to
3853 // handle this case, we do not attempt the restore.
3854 if ((packageInfo.applicationInfo.flags
3855 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
3856 String message = "Version " + metaInfo.versionCode
3857 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003858 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08003859 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
3860 packageName, message);
3861 continue;
3862 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003863 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08003864 + " > installed " + packageInfo.versionCode
3865 + " but restoreAnyVersion");
3866 }
Dan Egnorefe52642009-06-24 00:16:33 -07003867 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003868
Christopher Tate78dd4a72009-11-04 11:49:08 -08003869 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003870 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003871 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003872 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07003873 continue;
3874 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003875
Joe Onorato8a9b2202010-02-26 18:56:32 -08003876 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07003877 + " restore version [" + metaInfo.versionCode
3878 + "] is compatible with installed version ["
3879 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07003880
Christopher Tate3de55bc2010-03-12 17:28:08 -08003881 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07003882 IBackupAgent agent = bindToAgentSynchronous(
3883 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08003884 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07003885 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003886 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003887 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003888 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003889 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003890 }
3891
Christopher Tate5e1ab332009-09-01 20:32:49 -07003892 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07003893 try {
Chris Tate249345b2010-10-29 12:57:04 -07003894 processOneRestore(packageInfo, metaInfo.versionCode, agent,
3895 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003896 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07003897 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003898 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07003899 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07003900
3901 // The agent was probably running with a stub Application object,
3902 // which isn't a valid run mode for the main app logic. Shut
3903 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08003904 // usual full initialization. Note that this is only done for
3905 // full-system restores: when a single app has requested a restore,
3906 // it is explicitly not killed following that operation.
3907 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07003908 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003909 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003910 + packageInfo.applicationInfo.processName);
3911 mActivityManager.killApplicationProcess(
3912 packageInfo.applicationInfo.processName,
3913 packageInfo.applicationInfo.uid);
3914 }
Dan Egnorefe52642009-06-24 00:16:33 -07003915 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003916 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003917
3918 // if we get this far, report success to the observer
3919 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07003920 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003921 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003922 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003923 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003924 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003925 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003926
Dan Egnorefe52642009-06-24 00:16:33 -07003927 try {
3928 mTransport.finishRestore();
3929 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003930 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003931 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003932
3933 if (mObserver != null) {
3934 try {
3935 mObserver.restoreFinished(error);
3936 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003937 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003938 }
3939 }
Christopher Tateb6787f22009-07-02 17:40:45 -07003940
Christopher Tate84725812010-02-04 15:52:40 -08003941 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08003942 // ancestral dataset, as well as the set of apps that are possibly
3943 // restoreable from the dataset
3944 if (mTargetPackage == null && pmAgent != null) {
3945 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003946 mAncestralToken = mToken;
3947 writeRestoreTokens();
3948 }
3949
Christopher Tate1bb69062010-02-19 17:02:12 -08003950 // We must under all circumstances tell the Package Manager to
3951 // proceed with install notifications if it's waiting for us.
3952 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003953 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08003954 try {
3955 mPackageManagerBinder.finishPackageInstall(mPmToken);
3956 } catch (RemoteException e) { /* can't happen */ }
3957 }
3958
Christopher Tate73a3cb32010-12-13 18:27:26 -08003959 // Furthermore we need to reset the session timeout clock
3960 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
3961 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
3962 TIMEOUT_RESTORE_INTERVAL);
3963
Christopher Tateb6787f22009-07-02 17:40:45 -07003964 // done; we can finally release the wakelock
3965 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07003966 }
3967 }
3968
Dan Egnorefe52642009-06-24 00:16:33 -07003969 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07003970 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
3971 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003972 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07003973 final String packageName = app.packageName;
3974
Joe Onorato8a9b2202010-02-26 18:56:32 -08003975 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04003976
Christopher Tatec7b31e32009-06-10 15:49:30 -07003977 // !!! TODO: get the dirs from the transport
3978 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003979 File newStateName = new File(mStateDir, packageName + ".new");
3980 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07003981
Dan Egnorbb9001c2009-07-27 12:20:13 -07003982 ParcelFileDescriptor backupData = null;
3983 ParcelFileDescriptor newState = null;
3984
Christopher Tate4a627c72011-04-01 14:43:32 -07003985 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003986 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07003987 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07003988 backupData = ParcelFileDescriptor.open(backupDataName,
3989 ParcelFileDescriptor.MODE_READ_WRITE |
3990 ParcelFileDescriptor.MODE_CREATE |
3991 ParcelFileDescriptor.MODE_TRUNCATE);
3992
Dan Egnor01445162009-09-21 17:04:05 -07003993 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003994 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003995 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003996 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07003997 }
3998
3999 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07004000 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07004001 backupData = ParcelFileDescriptor.open(backupDataName,
4002 ParcelFileDescriptor.MODE_READ_ONLY);
4003
Dan Egnorbb9001c2009-07-27 12:20:13 -07004004 newState = ParcelFileDescriptor.open(newStateName,
4005 ParcelFileDescriptor.MODE_READ_WRITE |
4006 ParcelFileDescriptor.MODE_CREATE |
4007 ParcelFileDescriptor.MODE_TRUNCATE);
4008
Christopher Tate44a27902010-01-27 17:15:49 -08004009 // Kick off the restore, checking for hung agents
4010 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
4011 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
4012 boolean success = waitUntilOperationComplete(token);
4013
4014 if (!success) {
4015 throw new RuntimeException("restore timeout");
4016 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004017
4018 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07004019 //
4020 // !!! TODO: the restored data should be migrated on the server
4021 // side into the current dataset. In that case the new state file
4022 // we just created would reflect the data already extant in the
4023 // backend, so there'd be nothing more to do. Until that happens,
4024 // however, we need to make sure that we record the data to the
4025 // current backend dataset. (Yes, this means shipping the data over
4026 // the wire in both directions. That's bad, but consistency comes
4027 // first, then efficiency.) Once we introduce server-side data
4028 // migration to the newly-restored device's dataset, we will change
4029 // the following from a discard of the newly-written state to the
4030 // "correct" operation of renaming into the canonical state blob.
4031 newStateName.delete(); // TODO: remove; see above comment
4032 //newStateName.renameTo(savedStateName); // TODO: replace with this
4033
Dan Egnorbb9001c2009-07-27 12:20:13 -07004034 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004035 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004036 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004037 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004038 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07004039
Christopher Tate96733042009-07-20 14:49:13 -07004040 // If the agent fails restore, it might have put the app's data
4041 // into an incoherent state. For consistency we wipe its data
4042 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07004043 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07004044 } finally {
4045 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004046 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
4047 try { if (newState != null) newState.close(); } catch (IOException e) {}
4048 backupData = newState = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07004049 synchronized (mCurrentOperations) {
4050 mCurrentOperations.delete(token);
4051 }
Chris Tate249345b2010-10-29 12:57:04 -07004052
4053 // If we know a priori that we'll need to perform a full post-restore backup
4054 // pass, clear the new state file data. This means we're discarding work that
4055 // was just done by the app's agent, but this way the agent doesn't need to
4056 // take any special action based on global device state.
4057 if (needFullBackup) {
4058 newStateName.delete();
4059 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004060 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004061 }
4062 }
4063
Christopher Tate44a27902010-01-27 17:15:49 -08004064 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004065 IBackupTransport mTransport;
4066 PackageInfo mPackage;
4067
Christopher Tate44a27902010-01-27 17:15:49 -08004068 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004069 mTransport = transport;
4070 mPackage = packageInfo;
4071 }
4072
Christopher Tateee0e78a2009-07-02 11:17:03 -07004073 public void run() {
4074 try {
4075 // Clear the on-device backup state to ensure a full backup next time
4076 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4077 File stateFile = new File(stateDir, mPackage.packageName);
4078 stateFile.delete();
4079
4080 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004081 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004082 mTransport.clearBackupData(mPackage);
4083 } catch (RemoteException e) {
4084 // can't happen; the transport is local
4085 } finally {
4086 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004087 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004088 mTransport.finishBackup();
4089 } catch (RemoteException e) {
4090 // can't happen; the transport is local
4091 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004092
4093 // Last but not least, release the cpu
4094 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004095 }
4096 }
4097 }
4098
Christopher Tate44a27902010-01-27 17:15:49 -08004099 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004100 HashSet<String> mQueue;
4101
Christopher Tate44a27902010-01-27 17:15:49 -08004102 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004103 mQueue = transportNames;
4104 }
4105
Christopher Tate4cc86e12009-09-21 19:36:51 -07004106 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004107 try {
4108 for (String transportName : mQueue) {
4109 IBackupTransport transport = getTransport(transportName);
4110 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004111 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004112 continue;
4113 }
4114
Joe Onorato8a9b2202010-02-26 18:56:32 -08004115 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004116 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004117 long startRealtime = SystemClock.elapsedRealtime();
4118 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004119
Christopher Tate4cc86e12009-09-21 19:36:51 -07004120 if (status == BackupConstants.TRANSPORT_OK) {
4121 status = transport.finishBackup();
4122 }
4123
4124 // Okay, the wipe really happened. Clean up our local bookkeeping.
4125 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004126 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004127 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004128 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004129 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004130 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004131 synchronized (mQueueLock) {
4132 recordInitPendingLocked(false, transportName);
4133 }
Dan Egnor726247c2009-09-29 19:12:31 -07004134 } else {
4135 // If this didn't work, requeue this one and try again
4136 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004137 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004138 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004139 synchronized (mQueueLock) {
4140 recordInitPendingLocked(true, transportName);
4141 }
4142 // do this via another alarm to make sure of the wakelock states
4143 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004144 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004145 + transportName + " resched in " + delay);
4146 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4147 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004148 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004149 }
4150 } catch (RemoteException e) {
4151 // can't happen; the transports are local
4152 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004153 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004154 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004155 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004156 mWakelock.release();
4157 }
4158 }
4159 }
4160
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004161 private void dataChangedImpl(String packageName) {
4162 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4163 dataChangedImpl(packageName, targets);
4164 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004165
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004166 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004167 // Record that we need a backup pass for the caller. Since multiple callers
4168 // may share a uid, we need to note all candidates within that uid and schedule
4169 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004170 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004171
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004172 if (targets == null) {
4173 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4174 + " uid=" + Binder.getCallingUid());
4175 return;
4176 }
4177
4178 synchronized (mQueueLock) {
4179 // Note that this client has made data changes that need to be backed up
4180 for (ApplicationInfo app : targets) {
4181 // validate the caller-supplied package name against the known set of
4182 // packages associated with this uid
4183 if (app.packageName.equals(packageName)) {
4184 // Add the caller to the set of pending backups. If there is
4185 // one already there, then overwrite it, but no harm done.
Christopher Tate4a627c72011-04-01 14:43:32 -07004186 BackupRequest req = new BackupRequest(app);
Christopher Tatec28083a2010-12-14 16:16:44 -08004187 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004188 // Journal this request in case of crash. The put()
4189 // operation returned null when this package was not already
4190 // in the set; we want to avoid touching the disk redundantly.
4191 writeToJournalLocked(packageName);
4192
Christopher Tatec58efa62011-08-01 19:20:14 -07004193 if (MORE_DEBUG) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004194 int numKeys = mPendingBackups.size();
4195 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4196 for (BackupRequest b : mPendingBackups.values()) {
4197 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
4198 }
4199 }
4200 }
4201 }
4202 }
4203 }
4204 }
4205
4206 // Note: packageName is currently unused, but may be in the future
4207 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004208 // If the caller does not hold the BACKUP permission, it can only request a
4209 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004210 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004211 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004212 synchronized (mBackupParticipants) {
4213 return mBackupParticipants.get(Binder.getCallingUid());
4214 }
4215 }
4216
4217 // a caller with full permission can ask to back up any participating app
4218 // !!! TODO: allow backup of ANY app?
4219 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4220 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004221 int N = mBackupParticipants.size();
4222 for (int i = 0; i < N; i++) {
4223 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4224 if (s != null) {
4225 targets.addAll(s);
4226 }
4227 }
4228 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004229 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004230 }
Christopher Tate46758122009-05-06 11:22:00 -07004231
Christopher Tatecde87f42009-06-12 12:55:53 -07004232 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004233 RandomAccessFile out = null;
4234 try {
4235 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4236 out = new RandomAccessFile(mJournal, "rws");
4237 out.seek(out.length());
4238 out.writeUTF(str);
4239 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004240 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004241 mJournal = null;
4242 } finally {
4243 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004244 }
4245 }
4246
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004247 // ----- IBackupManager binder interface -----
4248
4249 public void dataChanged(final String packageName) {
4250 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4251 if (targets == null) {
4252 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4253 + " uid=" + Binder.getCallingUid());
4254 return;
4255 }
4256
4257 mBackupHandler.post(new Runnable() {
4258 public void run() {
4259 dataChangedImpl(packageName, targets);
4260 }
4261 });
4262 }
4263
Christopher Tateee0e78a2009-07-02 11:17:03 -07004264 // Clear the given package's backup data from the current transport
4265 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004266 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004267 PackageInfo info;
4268 try {
4269 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4270 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004271 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004272 return;
4273 }
4274
4275 // If the caller does not hold the BACKUP permission, it can only request a
4276 // wipe of its own backed-up data.
4277 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004278 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004279 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4280 apps = mBackupParticipants.get(Binder.getCallingUid());
4281 } else {
4282 // a caller with full permission can ask to back up any participating app
4283 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004284 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004285 apps = new HashSet<ApplicationInfo>();
4286 int N = mBackupParticipants.size();
4287 for (int i = 0; i < N; i++) {
4288 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4289 if (s != null) {
4290 apps.addAll(s);
4291 }
4292 }
4293 }
4294
4295 // now find the given package in the set of candidate apps
4296 for (ApplicationInfo app : apps) {
4297 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004298 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004299 // found it; fire off the clear request
4300 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004301 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004302 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004303 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4304 new ClearParams(getTransport(mCurrentTransport), info));
4305 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004306 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004307 }
4308 break;
4309 }
4310 }
4311 }
4312
Christopher Tateace7f092009-06-15 18:07:25 -07004313 // Run a backup pass immediately for any applications that have declared
4314 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004315 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004316 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004317
Joe Onorato8a9b2202010-02-26 18:56:32 -08004318 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004319 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004320 // Because the alarms we are using can jitter, and we want an *immediate*
4321 // backup pass to happen, we restart the timer beginning with "next time,"
4322 // then manually fire the backup trigger intent ourselves.
4323 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004324 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004325 mRunBackupIntent.send();
4326 } catch (PendingIntent.CanceledException e) {
4327 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004328 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004329 }
Christopher Tate46758122009-05-06 11:22:00 -07004330 }
4331 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004332
Christopher Tate4a627c72011-04-01 14:43:32 -07004333 // Run a *full* backup pass for the given package, writing the resulting data stream
4334 // to the supplied file descriptor. This method is synchronous and does not return
4335 // to the caller until the backup has been completed.
4336 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
4337 boolean doAllApps, String[] pkgList) {
4338 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4339
4340 // Validate
4341 if (!doAllApps) {
4342 if (!includeShared) {
4343 // If we're backing up shared data (sdcard or equivalent), then we can run
4344 // without any supplied app names. Otherwise, we'd be doing no work, so
4345 // report the error.
4346 if (pkgList == null || pkgList.length == 0) {
4347 throw new IllegalArgumentException(
4348 "Backup requested but neither shared nor any apps named");
4349 }
4350 }
4351 }
4352
4353 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4354 + " shared=" + includeShared + " all=" + doAllApps
4355 + " pkgs=" + pkgList);
4356
4357 long oldId = Binder.clearCallingIdentity();
4358 try {
4359 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
4360 doAllApps, pkgList);
4361 final int token = generateToken();
4362 synchronized (mFullConfirmations) {
4363 mFullConfirmations.put(token, params);
4364 }
4365
Christopher Tate75a99702011-05-18 16:28:19 -07004366 // start up the confirmation UI
4367 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4368 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4369 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004370 mFullConfirmations.delete(token);
4371 return;
4372 }
Christopher Tate75a99702011-05-18 16:28:19 -07004373
4374 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004375 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4376
4377 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07004378 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004379
4380 // wait for the backup to be performed
4381 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
4382 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004383 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07004384 try {
4385 fd.close();
4386 } catch (IOException e) {
4387 // just eat it
4388 }
Christopher Tate75a99702011-05-18 16:28:19 -07004389 Binder.restoreCallingIdentity(oldId);
Christopher Tate4a627c72011-04-01 14:43:32 -07004390 }
Christopher Tatec58efa62011-08-01 19:20:14 -07004391 if (MORE_DEBUG) Slog.d(TAG, "Full backup done; returning to caller");
Christopher Tate75a99702011-05-18 16:28:19 -07004392 }
4393
4394 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004395 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07004396 Slog.i(TAG, "Beginning full restore...");
4397
4398 long oldId = Binder.clearCallingIdentity();
4399
4400 try {
4401 FullRestoreParams params = new FullRestoreParams(fd);
4402 final int token = generateToken();
4403 synchronized (mFullConfirmations) {
4404 mFullConfirmations.put(token, params);
4405 }
4406
4407 // start up the confirmation UI
4408 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
4409 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
4410 Slog.e(TAG, "Unable to launch full restore confirmation");
4411 mFullConfirmations.delete(token);
4412 return;
4413 }
4414
4415 // make sure the screen is lit for the user interaction
4416 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4417
4418 // start the confirmation countdown
4419 startConfirmationTimeout(token, params);
4420
4421 // wait for the restore to be performed
4422 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
4423 waitForCompletion(params);
4424 } finally {
4425 try {
4426 fd.close();
4427 } catch (IOException e) {
4428 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
4429 }
4430 Binder.restoreCallingIdentity(oldId);
4431 Slog.i(TAG, "Full restore completed");
4432 }
4433 }
4434
4435 boolean startConfirmationUi(int token, String action) {
4436 try {
4437 Intent confIntent = new Intent(action);
4438 confIntent.setClassName("com.android.backupconfirm",
4439 "com.android.backupconfirm.BackupRestoreConfirmation");
4440 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
4441 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4442 mContext.startActivity(confIntent);
4443 } catch (ActivityNotFoundException e) {
4444 return false;
4445 }
4446 return true;
4447 }
4448
4449 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07004450 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07004451 + TIMEOUT_FULL_CONFIRMATION + " millis");
4452 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
4453 token, 0, params);
4454 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07004455 }
4456
4457 void waitForCompletion(FullParams params) {
4458 synchronized (params.latch) {
4459 while (params.latch.get() == false) {
4460 try {
4461 params.latch.wait();
4462 } catch (InterruptedException e) { /* never interrupted */ }
4463 }
4464 }
4465 }
4466
4467 void signalFullBackupRestoreCompletion(FullParams params) {
4468 synchronized (params.latch) {
4469 params.latch.set(true);
4470 params.latch.notifyAll();
4471 }
4472 }
4473
4474 // Confirm that the previously-requested full backup/restore operation can proceed. This
4475 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07004476 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07004477 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07004478 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004479 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
4480 + " allow=" + allow);
4481
4482 // TODO: possibly require not just this signature-only permission, but even
4483 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07004484 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07004485
4486 long oldId = Binder.clearCallingIdentity();
4487 try {
4488
4489 FullParams params;
4490 synchronized (mFullConfirmations) {
4491 params = mFullConfirmations.get(token);
4492 if (params != null) {
4493 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
4494 mFullConfirmations.delete(token);
4495
4496 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004497 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07004498 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07004499 : MSG_RUN_FULL_RESTORE;
4500
Christopher Tate728a1c42011-07-28 18:03:03 -07004501 params.observer = observer;
4502 params.curPassword = curPassword;
4503 params.encryptPassword = encPpassword;
4504
Christopher Tate75a99702011-05-18 16:28:19 -07004505 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07004506 mWakelock.acquire();
4507 Message msg = mBackupHandler.obtainMessage(verb, params);
4508 mBackupHandler.sendMessage(msg);
4509 } else {
4510 Slog.w(TAG, "User rejected full backup/restore operation");
4511 // indicate completion without having actually transferred any data
4512 signalFullBackupRestoreCompletion(params);
4513 }
4514 } else {
4515 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
4516 }
4517 }
4518 } finally {
4519 Binder.restoreCallingIdentity(oldId);
4520 }
4521 }
4522
Christopher Tate8031a3d2009-07-06 16:36:05 -07004523 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07004524 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004525 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004526 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004527
Joe Onorato8a9b2202010-02-26 18:56:32 -08004528 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004529
Christopher Tate6ef58a12009-06-29 14:56:28 -07004530 boolean wasEnabled = mEnabled;
4531 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07004532 Settings.Secure.putInt(mContext.getContentResolver(),
4533 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07004534 mEnabled = enable;
4535 }
4536
Christopher Tate49401dd2009-07-01 12:34:29 -07004537 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07004538 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07004539 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07004540 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07004541 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004542 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004543 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004544
Christopher Tateb6787f22009-07-02 17:40:45 -07004545 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004546
4547 // This also constitutes an opt-out, so we wipe any data for
4548 // this device from the backend. We start that process with
4549 // an alarm in order to guarantee wakelock states.
4550 if (wasEnabled && mProvisioned) {
4551 // NOTE: we currently flush every registered transport, not just
4552 // the currently-active one.
4553 HashSet<String> allTransports;
4554 synchronized (mTransports) {
4555 allTransports = new HashSet<String>(mTransports.keySet());
4556 }
4557 // build the set of transports for which we are posting an init
4558 for (String transport : allTransports) {
4559 recordInitPendingLocked(true, transport);
4560 }
4561 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
4562 mRunInitIntent);
4563 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004564 }
4565 }
Christopher Tate49401dd2009-07-01 12:34:29 -07004566 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004567
Christopher Tatecce9da52010-02-03 15:11:15 -08004568 // Enable/disable automatic restore of app data at install time
4569 public void setAutoRestore(boolean doAutoRestore) {
4570 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004571 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08004572
Joe Onorato8a9b2202010-02-26 18:56:32 -08004573 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08004574
4575 synchronized (this) {
4576 Settings.Secure.putInt(mContext.getContentResolver(),
4577 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
4578 mAutoRestore = doAutoRestore;
4579 }
4580 }
4581
Christopher Tate8031a3d2009-07-06 16:36:05 -07004582 // Mark the backup service as having been provisioned
4583 public void setBackupProvisioned(boolean available) {
4584 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4585 "setBackupProvisioned");
4586
4587 boolean wasProvisioned = mProvisioned;
4588 synchronized (this) {
4589 Settings.Secure.putInt(mContext.getContentResolver(),
4590 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
4591 mProvisioned = available;
4592 }
4593
4594 synchronized (mQueueLock) {
4595 if (available && !wasProvisioned && mEnabled) {
4596 // we're now good to go, so start the backup alarms
4597 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
4598 } else if (!available) {
4599 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004600 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07004601 mAlarmManager.cancel(mRunBackupIntent);
4602 }
4603 }
4604 }
4605
4606 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07004607 // We used to use setInexactRepeating(), but that may be linked to
4608 // backups running at :00 more often than not, creating load spikes.
4609 // Schedule at an exact time for now, and also add a bit of "fuzz".
4610
4611 Random random = new Random();
4612 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
4613 random.nextInt(FUZZ_MILLIS);
4614 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
4615 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07004616 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07004617 }
4618
Christopher Tate6ef58a12009-06-29 14:56:28 -07004619 // Report whether the backup mechanism is currently enabled
4620 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04004621 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004622 return mEnabled; // no need to synchronize just to read it
4623 }
4624
Christopher Tate91717492009-06-26 21:07:13 -07004625 // Report the name of the currently active transport
4626 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04004627 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004628 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07004629 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07004630 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07004631 }
4632
Christopher Tate91717492009-06-26 21:07:13 -07004633 // Report all known, available backup transports
4634 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07004635 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07004636
Christopher Tate91717492009-06-26 21:07:13 -07004637 String[] list = null;
4638 ArrayList<String> known = new ArrayList<String>();
4639 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
4640 if (entry.getValue() != null) {
4641 known.add(entry.getKey());
4642 }
4643 }
4644
4645 if (known.size() > 0) {
4646 list = new String[known.size()];
4647 known.toArray(list);
4648 }
4649 return list;
4650 }
4651
4652 // Select which transport to use for the next backup operation. If the given
4653 // name is not one of the available transports, no action is taken and the method
4654 // returns null.
4655 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04004656 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07004657
4658 synchronized (mTransports) {
4659 String prevTransport = null;
4660 if (mTransports.get(transport) != null) {
4661 prevTransport = mCurrentTransport;
4662 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07004663 Settings.Secure.putString(mContext.getContentResolver(),
4664 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004665 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07004666 + " returning " + prevTransport);
4667 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004668 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07004669 }
4670 return prevTransport;
4671 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004672 }
4673
Christopher Tatef5e1c292010-12-08 18:40:26 -08004674 // Supply the configuration Intent for the given transport. If the name is not one
4675 // of the available transports, or if the transport does not supply any configuration
4676 // UI, the method returns null.
4677 public Intent getConfigurationIntent(String transportName) {
4678 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4679 "getConfigurationIntent");
4680
4681 synchronized (mTransports) {
4682 final IBackupTransport transport = mTransports.get(transportName);
4683 if (transport != null) {
4684 try {
4685 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07004686 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08004687 + intent);
4688 return intent;
4689 } catch (RemoteException e) {
4690 /* fall through to return null */
4691 }
4692 }
4693 }
4694
4695 return null;
4696 }
4697
4698 // Supply the configuration summary string for the given transport. If the name is
4699 // not one of the available transports, or if the transport does not supply any
4700 // summary / destination string, the method can return null.
4701 //
4702 // This string is used VERBATIM as the summary text of the relevant Settings item!
4703 public String getDestinationString(String transportName) {
4704 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004705 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08004706
4707 synchronized (mTransports) {
4708 final IBackupTransport transport = mTransports.get(transportName);
4709 if (transport != null) {
4710 try {
4711 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07004712 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08004713 return text;
4714 } catch (RemoteException e) {
4715 /* fall through to return null */
4716 }
4717 }
4718 }
4719
4720 return null;
4721 }
4722
Christopher Tate043dadc2009-06-02 16:11:00 -07004723 // Callback: a requested backup agent has been instantiated. This should only
4724 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004725 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07004726 synchronized(mAgentConnectLock) {
4727 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004728 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07004729 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
4730 mConnectedAgent = agent;
4731 mConnecting = false;
4732 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004733 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004734 + " claiming agent connected");
4735 }
4736 mAgentConnectLock.notifyAll();
4737 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004738 }
4739
4740 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
4741 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07004742 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004743 public void agentDisconnected(String packageName) {
4744 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07004745 synchronized(mAgentConnectLock) {
4746 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
4747 mConnectedAgent = null;
4748 mConnecting = false;
4749 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004750 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004751 + " claiming agent disconnected");
4752 }
4753 mAgentConnectLock.notifyAll();
4754 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004755 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004756
Christopher Tate1bb69062010-02-19 17:02:12 -08004757 // An application being installed will need a restore pass, then the Package Manager
4758 // will need to be told when the restore is finished.
4759 public void restoreAtInstall(String packageName, int token) {
4760 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004761 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08004762 + " attemping install-time restore");
4763 return;
4764 }
4765
4766 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004767 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08004768 + " token=" + Integer.toHexString(token));
4769
Christopher Tatef0872722010-02-25 15:22:48 -08004770 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08004771 // okay, we're going to attempt a restore of this package from this restore set.
4772 // The eventual message back into the Package Manager to run the post-install
4773 // steps for 'token' will be issued from the restore handling code.
4774
4775 // We can use a synthetic PackageInfo here because:
4776 // 1. We know it's valid, since the Package Manager supplied the name
4777 // 2. Only the packageName field will be used by the restore code
4778 PackageInfo pkg = new PackageInfo();
4779 pkg.packageName = packageName;
4780
4781 mWakelock.acquire();
4782 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
4783 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07004784 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08004785 mBackupHandler.sendMessage(msg);
4786 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08004787 // Auto-restore disabled or no way to attempt a restore; just tell the Package
4788 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004789 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08004790 try {
4791 mPackageManagerBinder.finishPackageInstall(token);
4792 } catch (RemoteException e) { /* can't happen */ }
4793 }
4794 }
4795
Christopher Tate8c850b72009-06-07 19:33:20 -07004796 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08004797 public IRestoreSession beginRestoreSession(String packageName, String transport) {
4798 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
4799 + " transport=" + transport);
4800
4801 boolean needPermission = true;
4802 if (transport == null) {
4803 transport = mCurrentTransport;
4804
4805 if (packageName != null) {
4806 PackageInfo app = null;
4807 try {
4808 app = mPackageManager.getPackageInfo(packageName, 0);
4809 } catch (NameNotFoundException nnf) {
4810 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
4811 throw new IllegalArgumentException("Package " + packageName + " not found");
4812 }
4813
4814 if (app.applicationInfo.uid == Binder.getCallingUid()) {
4815 // So: using the current active transport, and the caller has asked
4816 // that its own package will be restored. In this narrow use case
4817 // we do not require the caller to hold the permission.
4818 needPermission = false;
4819 }
4820 }
4821 }
4822
4823 if (needPermission) {
4824 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4825 "beginRestoreSession");
4826 } else {
4827 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
4828 }
Christopher Tatef68eb502009-06-16 11:02:01 -07004829
4830 synchronized(this) {
4831 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004832 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07004833 return null;
4834 }
Chris Tate44ab8452010-11-16 15:10:49 -08004835 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08004836 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07004837 }
4838 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07004839 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004840
Christopher Tate73a3cb32010-12-13 18:27:26 -08004841 void clearRestoreSession(ActiveRestoreSession currentSession) {
4842 synchronized(this) {
4843 if (currentSession != mActiveRestoreSession) {
4844 Slog.e(TAG, "ending non-current restore session");
4845 } else {
4846 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
4847 mActiveRestoreSession = null;
4848 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4849 }
4850 }
4851 }
4852
Christopher Tate44a27902010-01-27 17:15:49 -08004853 // Note that a currently-active backup agent has notified us that it has
4854 // completed the given outstanding asynchronous backup/restore operation.
4855 public void opComplete(int token) {
4856 synchronized (mCurrentOpLock) {
Christopher Tatec58efa62011-08-01 19:20:14 -07004857 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08004858 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
4859 mCurrentOpLock.notifyAll();
4860 }
4861 }
4862
Christopher Tate9b3905c2009-06-08 15:24:01 -07004863 // ----- Restore session -----
4864
Christopher Tate80202c82010-01-25 19:37:47 -08004865 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07004866 private static final String TAG = "RestoreSession";
4867
Chris Tate44ab8452010-11-16 15:10:49 -08004868 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004869 private IBackupTransport mRestoreTransport = null;
4870 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08004871 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004872
Chris Tate44ab8452010-11-16 15:10:49 -08004873 ActiveRestoreSession(String packageName, String transport) {
4874 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07004875 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07004876 }
4877
4878 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07004879 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04004880 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004881 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004882 if (observer == null) {
4883 throw new IllegalArgumentException("Observer must not be null");
4884 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004885
Christopher Tate73a3cb32010-12-13 18:27:26 -08004886 if (mEnded) {
4887 throw new IllegalStateException("Restore session already ended");
4888 }
4889
Christopher Tate1bb69062010-02-19 17:02:12 -08004890 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07004891 try {
Christopher Tate43383042009-07-13 15:17:13 -07004892 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004893 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004894 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07004895 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07004896 // spin off the transport request to our service thread
4897 mWakelock.acquire();
4898 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
4899 new RestoreGetSetsParams(mRestoreTransport, this, observer));
4900 mBackupHandler.sendMessage(msg);
4901 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07004902 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004903 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07004904 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08004905 } finally {
4906 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07004907 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07004908 }
4909
Christopher Tate84725812010-02-04 15:52:40 -08004910 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07004911 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4912 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004913
Chris Tate44ab8452010-11-16 15:10:49 -08004914 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07004915 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004916
Christopher Tate73a3cb32010-12-13 18:27:26 -08004917 if (mEnded) {
4918 throw new IllegalStateException("Restore session already ended");
4919 }
4920
Dan Egnor0084da52009-07-29 12:57:16 -07004921 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08004922 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
4923 return -1;
4924 }
4925
4926 if (mPackageName != null) {
4927 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07004928 return -1;
4929 }
4930
Christopher Tate21ab6a52009-09-24 18:01:46 -07004931 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004932 for (int i = 0; i < mRestoreSets.length; i++) {
4933 if (token == mRestoreSets[i].token) {
4934 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07004935 mWakelock.acquire();
4936 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07004937 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07004938 mBackupHandler.sendMessage(msg);
4939 Binder.restoreCallingIdentity(oldId);
4940 return 0;
4941 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004942 }
4943 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07004944
Joe Onorato8a9b2202010-02-26 18:56:32 -08004945 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07004946 return -1;
4947 }
4948
Christopher Tate284f1bb2011-07-07 14:31:18 -07004949 public synchronized int restoreSome(long token, IRestoreObserver observer,
4950 String[] packages) {
4951 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4952 "performRestore");
4953
4954 if (DEBUG) {
4955 StringBuilder b = new StringBuilder(128);
4956 b.append("restoreSome token=");
4957 b.append(Long.toHexString(token));
4958 b.append(" observer=");
4959 b.append(observer.toString());
4960 b.append(" packages=");
4961 if (packages == null) {
4962 b.append("null");
4963 } else {
4964 b.append('{');
4965 boolean first = true;
4966 for (String s : packages) {
4967 if (!first) {
4968 b.append(", ");
4969 } else first = false;
4970 b.append(s);
4971 }
4972 b.append('}');
4973 }
4974 Slog.d(TAG, b.toString());
4975 }
4976
4977 if (mEnded) {
4978 throw new IllegalStateException("Restore session already ended");
4979 }
4980
4981 if (mRestoreTransport == null || mRestoreSets == null) {
4982 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
4983 return -1;
4984 }
4985
4986 if (mPackageName != null) {
4987 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
4988 return -1;
4989 }
4990
4991 synchronized (mQueueLock) {
4992 for (int i = 0; i < mRestoreSets.length; i++) {
4993 if (token == mRestoreSets[i].token) {
4994 long oldId = Binder.clearCallingIdentity();
4995 mWakelock.acquire();
4996 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
4997 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
4998 packages, true);
4999 mBackupHandler.sendMessage(msg);
5000 Binder.restoreCallingIdentity(oldId);
5001 return 0;
5002 }
5003 }
5004 }
5005
5006 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5007 return -1;
5008 }
5009
Christopher Tate84725812010-02-04 15:52:40 -08005010 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005011 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005012
Christopher Tate73a3cb32010-12-13 18:27:26 -08005013 if (mEnded) {
5014 throw new IllegalStateException("Restore session already ended");
5015 }
5016
Chris Tate44ab8452010-11-16 15:10:49 -08005017 if (mPackageName != null) {
5018 if (! mPackageName.equals(packageName)) {
5019 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5020 + " on session for package " + mPackageName);
5021 return -1;
5022 }
5023 }
5024
Christopher Tate84725812010-02-04 15:52:40 -08005025 PackageInfo app = null;
5026 try {
5027 app = mPackageManager.getPackageInfo(packageName, 0);
5028 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005029 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005030 return -1;
5031 }
5032
5033 // If the caller is not privileged and is not coming from the target
5034 // app's uid, throw a permission exception back to the caller.
5035 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5036 Binder.getCallingPid(), Binder.getCallingUid());
5037 if ((perm == PackageManager.PERMISSION_DENIED) &&
5038 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005039 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005040 + " or calling uid=" + Binder.getCallingUid());
5041 throw new SecurityException("No permission to restore other packages");
5042 }
5043
Christopher Tate7d411a32010-02-26 11:27:08 -08005044 // If the package has no backup agent, we obviously cannot proceed
5045 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005046 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005047 return -1;
5048 }
5049
Christopher Tate84725812010-02-04 15:52:40 -08005050 // So far so good; we're allowed to try to restore this package. Now
5051 // check whether there is data for it in the current dataset, falling back
5052 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005053 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005054
5055 // If we didn't come up with a place to look -- no ancestral dataset and
5056 // the app has never been backed up from this device -- there's nothing
5057 // to do but return failure.
5058 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005059 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005060 return -1;
5061 }
5062
5063 // Ready to go: enqueue the restore request and claim success
5064 long oldId = Binder.clearCallingIdentity();
5065 mWakelock.acquire();
5066 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005067 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005068 mBackupHandler.sendMessage(msg);
5069 Binder.restoreCallingIdentity(oldId);
5070 return 0;
5071 }
5072
Christopher Tate73a3cb32010-12-13 18:27:26 -08005073 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5074 class EndRestoreRunnable implements Runnable {
5075 BackupManagerService mBackupManager;
5076 ActiveRestoreSession mSession;
5077
5078 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5079 mBackupManager = manager;
5080 mSession = session;
5081 }
5082
5083 public void run() {
5084 // clean up the session's bookkeeping
5085 synchronized (mSession) {
5086 try {
5087 if (mSession.mRestoreTransport != null) {
5088 mSession.mRestoreTransport.finishRestore();
5089 }
5090 } catch (Exception e) {
5091 Slog.e(TAG, "Error in finishRestore", e);
5092 } finally {
5093 mSession.mRestoreTransport = null;
5094 mSession.mEnded = true;
5095 }
5096 }
5097
5098 // clean up the BackupManagerService side of the bookkeeping
5099 // and cancel any pending timeout message
5100 mBackupManager.clearRestoreSession(mSession);
5101 }
5102 }
5103
Dan Egnor0084da52009-07-29 12:57:16 -07005104 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005105 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005106
Christopher Tate73a3cb32010-12-13 18:27:26 -08005107 if (mEnded) {
5108 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005109 }
5110
Christopher Tate73a3cb32010-12-13 18:27:26 -08005111 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005112 }
5113 }
5114
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005115 @Override
5116 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005117 long identityToken = Binder.clearCallingIdentity();
5118 try {
5119 dumpInternal(pw);
5120 } finally {
5121 Binder.restoreCallingIdentity(identityToken);
5122 }
5123 }
5124
5125 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005126 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005127 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005128 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005129 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005130 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07005131 pw.println("Last backup pass: " + mLastBackupPass
5132 + " (now = " + System.currentTimeMillis() + ')');
5133 pw.println(" next scheduled: " + mNextBackupPass);
5134
Christopher Tate91717492009-06-26 21:07:13 -07005135 pw.println("Available transports:");
5136 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005137 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5138 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005139 IBackupTransport transport = getTransport(t);
5140 File dir = new File(mBaseStateDir, transport.transportDirName());
5141 pw.println(" destination: " + transport.currentDestinationString());
5142 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005143 for (File f : dir.listFiles()) {
5144 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5145 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005146 } catch (Exception e) {
5147 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005148 pw.println(" Error: " + e);
5149 }
Christopher Tate91717492009-06-26 21:07:13 -07005150 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005151
5152 pw.println("Pending init: " + mPendingInits.size());
5153 for (String s : mPendingInits) {
5154 pw.println(" " + s);
5155 }
5156
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005157 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005158 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005159 for (int i=0; i<N; i++) {
5160 int uid = mBackupParticipants.keyAt(i);
5161 pw.print(" uid: ");
5162 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005163 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5164 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005165 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005166 }
5167 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005168
Christopher Tateb49ceb32010-02-08 16:22:24 -08005169 pw.println("Ancestral packages: "
5170 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005171 if (mAncestralPackages != null) {
5172 for (String pkg : mAncestralPackages) {
5173 pw.println(" " + pkg);
5174 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005175 }
5176
Christopher Tate73e02522009-07-15 14:18:26 -07005177 pw.println("Ever backed up: " + mEverStoredApps.size());
5178 for (String pkg : mEverStoredApps) {
5179 pw.println(" " + pkg);
5180 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005181
5182 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005183 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005184 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005185 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005186 }
5187 }
Christopher Tate487529a2009-04-29 14:03:25 -07005188}