blob: b3309e53969072b12f6bc96ad005892f003780ec [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
Christopher Tateeef4ae42011-08-05 13:15:53 -07002037 // Verify that the given password matches the currently-active
2038 // backup password, if any
2039 if (hasBackupPassword()) {
2040 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2041 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2042 return;
2043 }
2044 }
2045
Christopher Tate7bdb0962011-07-13 19:30:21 -07002046 // Write the global file header. All strings are UTF-8 encoded; lines end
2047 // with a '\n' byte. Actual backup data begins immediately following the
2048 // final '\n'.
2049 //
2050 // line 1: "ANDROID BACKUP"
2051 // line 2: backup file format version, currently "1"
2052 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002053 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2054 //
2055 // When line 4 is not "none", then additional header data follows:
2056 //
2057 // line 5: user password salt [hex]
2058 // line 6: master key checksum salt [hex]
2059 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2060 // line 8: IV of the user key [hex]
2061 // line 9: master key blob [hex]
2062 // IV of the master key, master key itself, master key checksum hash
2063 //
2064 // The master key checksum is the master key plus its checksum salt, run through
2065 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2066 // correct password for decrypting the archive: the master key decrypted from
2067 // the archive using the user-supplied password is also run through PBKDF2 in
2068 // this way, and if the result does not match the checksum as stored in the
2069 // archive, then we know that the user-supplied password does not match the
2070 // archive's.
2071 StringBuilder headerbuf = new StringBuilder(1024);
2072
Christopher Tate7bdb0962011-07-13 19:30:21 -07002073 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002074 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2075 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002076
2077 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002078 // Set up the encryption stage if appropriate, and emit the correct header
2079 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002080 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 Tate6853fcf2011-08-10 17:52:21 -07002108 // Shared storage if requested
Christopher Tateb0628bf2011-06-02 15:08:13 -07002109 if (mIncludeShared) {
2110 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07002111 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07002112
2113 // Done!
2114 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002115 } catch (RemoteException e) {
2116 Slog.e(TAG, "App died during full backup");
2117 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002118 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002119 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002120 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002121 mOutputFile.close();
2122 } catch (IOException e) {
2123 /* nothing we can do about this */
2124 }
2125 synchronized (mCurrentOpLock) {
2126 mCurrentOperations.clear();
2127 }
2128 synchronized (mLatchObject) {
2129 mLatchObject.set(true);
2130 mLatchObject.notifyAll();
2131 }
2132 sendEndBackup();
2133 mWakelock.release();
2134 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
2135 }
2136 }
2137
Christopher Tate2efd2db2011-07-19 16:32:49 -07002138 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2139 OutputStream ofstream) throws Exception {
2140 // User key will be used to encrypt the master key.
2141 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002142 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002143 PBKDF2_HASH_ROUNDS);
2144
2145 // the master key is random for each backup
2146 byte[] masterPw = new byte[256 / 8];
2147 mRng.nextBytes(masterPw);
2148 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2149
2150 // primary encryption of the datastream with the random key
2151 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2152 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2153 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2154 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2155
2156 // line 4: name of encryption algorithm
2157 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2158 headerbuf.append('\n');
2159 // line 5: user password salt [hex]
2160 headerbuf.append(byteArrayToHex(newUserSalt));
2161 headerbuf.append('\n');
2162 // line 6: master key checksum salt [hex]
2163 headerbuf.append(byteArrayToHex(checksumSalt));
2164 headerbuf.append('\n');
2165 // line 7: number of PBKDF2 rounds used [decimal]
2166 headerbuf.append(PBKDF2_HASH_ROUNDS);
2167 headerbuf.append('\n');
2168
2169 // line 8: IV of the user key [hex]
2170 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2171 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2172
2173 byte[] IV = mkC.getIV();
2174 headerbuf.append(byteArrayToHex(IV));
2175 headerbuf.append('\n');
2176
2177 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2178 // [byte] IV length = Niv
2179 // [array of Niv bytes] IV itself
2180 // [byte] master key length = Nmk
2181 // [array of Nmk bytes] master key itself
2182 // [byte] MK checksum hash length = Nck
2183 // [array of Nck bytes] master key checksum hash
2184 //
2185 // The checksum is the (master key + checksum salt), run through the
2186 // stated number of PBKDF2 rounds
2187 IV = c.getIV();
2188 byte[] mk = masterKeySpec.getEncoded();
2189 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2190 checksumSalt, PBKDF2_HASH_ROUNDS);
2191
2192 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2193 + checksum.length + 3);
2194 DataOutputStream mkOut = new DataOutputStream(blob);
2195 mkOut.writeByte(IV.length);
2196 mkOut.write(IV);
2197 mkOut.writeByte(mk.length);
2198 mkOut.write(mk);
2199 mkOut.writeByte(checksum.length);
2200 mkOut.write(checksum);
2201 mkOut.flush();
2202 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2203 headerbuf.append(byteArrayToHex(encryptedMk));
2204 headerbuf.append('\n');
2205
2206 return finalOutput;
2207 }
2208
2209 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002210 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002211 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2212
2213 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2214 IApplicationThread.BACKUP_MODE_FULL);
2215 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002216 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002217 try {
Christopher Tate7926a692011-07-11 11:31:57 -07002218 pipes = ParcelFileDescriptor.createPipe();
2219
Christopher Tateb0628bf2011-06-02 15:08:13 -07002220 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07002221 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07002222 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2223 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2224 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2225
2226 sendOnBackupPackage(pkg.packageName);
2227
Christopher Tate7926a692011-07-11 11:31:57 -07002228 final int token = generateToken();
2229 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
2230 token, sendApk);
2231 pipes[1].close(); // the runner has dup'd it
2232 pipes[1] = null;
2233 Thread t = new Thread(runner);
2234 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002235
Christopher Tate7926a692011-07-11 11:31:57 -07002236 // Now pull data from the app and stuff it into the compressor
2237 try {
2238 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2239 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002240
Christopher Tate7926a692011-07-11 11:31:57 -07002241 byte[] buffer = new byte[16 * 1024];
2242 int chunkTotal;
2243 while ((chunkTotal = in.readInt()) > 0) {
2244 while (chunkTotal > 0) {
2245 int toRead = (chunkTotal > buffer.length)
2246 ? buffer.length : chunkTotal;
2247 int nRead = in.read(buffer, 0, toRead);
2248 out.write(buffer, 0, nRead);
2249 chunkTotal -= nRead;
2250 }
2251 }
2252 } catch (IOException e) {
2253 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002254 }
2255
Christopher Tateb0628bf2011-06-02 15:08:13 -07002256 if (!waitUntilOperationComplete(token)) {
2257 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2258 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002259 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002260 }
Christopher Tate7926a692011-07-11 11:31:57 -07002261
Christopher Tateb0628bf2011-06-02 15:08:13 -07002262 } catch (IOException e) {
2263 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002264 } finally {
2265 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002266 // flush after every package
2267 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002268 if (pipes != null) {
2269 if (pipes[0] != null) pipes[0].close();
2270 if (pipes[1] != null) pipes[1].close();
2271 }
Christopher Tate7926a692011-07-11 11:31:57 -07002272 } catch (IOException e) {
2273 Slog.w(TAG, "Error bringing down backup stack");
2274 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002275 }
2276 } else {
2277 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2278 }
2279 tearDown(pkg);
2280 }
2281
Christopher Tate79ec80d2011-06-24 14:58:49 -07002282 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2283 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2284 final String appSourceDir = pkg.applicationInfo.sourceDir;
2285 final String apkDir = new File(appSourceDir).getParent();
2286 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2287 apkDir, appSourceDir, output);
2288
2289 // Save associated .obb content if it exists and we did save the apk
2290 // check for .obb and save those too
2291 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2292 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002293 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002294 File[] obbFiles = obbDir.listFiles();
2295 if (obbFiles != null) {
2296 final String obbDirName = obbDir.getAbsolutePath();
2297 for (File obb : obbFiles) {
2298 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2299 obbDirName, obb.getAbsolutePath(), output);
2300 }
2301 }
2302 }
2303 }
2304
Christopher Tateb0628bf2011-06-02 15:08:13 -07002305 private void backupSharedStorage() throws RemoteException {
2306 PackageInfo pkg = null;
2307 try {
2308 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
2309 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2310 IApplicationThread.BACKUP_MODE_FULL);
2311 if (agent != null) {
2312 sendOnBackupPackage("Shared storage");
2313
2314 final int token = generateToken();
2315 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002316 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002317 if (!waitUntilOperationComplete(token)) {
2318 Slog.e(TAG, "Full backup failed on shared storage");
2319 } else {
2320 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
2321 }
2322 } else {
2323 Slog.e(TAG, "Could not bind to shared storage backup agent");
2324 }
2325 } catch (NameNotFoundException e) {
2326 Slog.e(TAG, "Shared storage backup package not found");
2327 } finally {
2328 tearDown(pkg);
2329 }
2330 }
2331
Christopher Tate6853fcf2011-08-10 17:52:21 -07002332 private void finalizeBackup(OutputStream out) {
2333 try {
2334 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2335 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2336 out.write(eof);
2337 } catch (IOException e) {
2338 Slog.w(TAG, "Error attempting to finalize backup stream");
2339 }
2340 }
2341
Christopher Tate4a627c72011-04-01 14:43:32 -07002342 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2343 throws IOException {
2344 // Manifest format. All data are strings ending in LF:
2345 // BACKUP_MANIFEST_VERSION, currently 1
2346 //
2347 // Version 1:
2348 // package name
2349 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002350 // platform versionCode
2351 // getInstallerPackageName() for this package (maybe empty)
2352 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002353 // number of signatures == N
2354 // N*: signature byte array in ascii format per Signature.toCharsString()
2355 StringBuilder builder = new StringBuilder(4096);
2356 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2357
2358 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2359 printer.println(pkg.packageName);
2360 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002361 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2362
2363 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2364 printer.println((installerName != null) ? installerName : "");
2365
Christopher Tate4a627c72011-04-01 14:43:32 -07002366 printer.println(withApk ? "1" : "0");
2367 if (pkg.signatures == null) {
2368 printer.println("0");
2369 } else {
2370 printer.println(Integer.toString(pkg.signatures.length));
2371 for (Signature sig : pkg.signatures) {
2372 printer.println(sig.toCharsString());
2373 }
2374 }
2375
2376 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002377 outstream.write(builder.toString().getBytes());
2378 outstream.close();
2379 }
2380
2381 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002382 if (pkg != null) {
2383 final ApplicationInfo app = pkg.applicationInfo;
2384 if (app != null) {
2385 try {
2386 // unbind and tidy up even on timeout or failure, just in case
2387 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002388
Christopher Tateb0628bf2011-06-02 15:08:13 -07002389 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002390 if (app.uid != Process.SYSTEM_UID
2391 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002392 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002393 mActivityManager.killApplicationProcess(app.processName, app.uid);
2394 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002395 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002396 }
2397 } catch (RemoteException e) {
2398 Slog.d(TAG, "Lost app trying to shut down");
2399 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002400 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002401 }
2402 }
2403
2404 // wrappers for observer use
2405 void sendStartBackup() {
2406 if (mObserver != null) {
2407 try {
2408 mObserver.onStartBackup();
2409 } catch (RemoteException e) {
2410 Slog.w(TAG, "full backup observer went away: startBackup");
2411 mObserver = null;
2412 }
2413 }
2414 }
2415
2416 void sendOnBackupPackage(String name) {
2417 if (mObserver != null) {
2418 try {
2419 // TODO: use a more user-friendly name string
2420 mObserver.onBackupPackage(name);
2421 } catch (RemoteException e) {
2422 Slog.w(TAG, "full backup observer went away: backupPackage");
2423 mObserver = null;
2424 }
2425 }
2426 }
2427
2428 void sendEndBackup() {
2429 if (mObserver != null) {
2430 try {
2431 mObserver.onEndBackup();
2432 } catch (RemoteException e) {
2433 Slog.w(TAG, "full backup observer went away: endBackup");
2434 mObserver = null;
2435 }
2436 }
2437 }
2438 }
2439
2440
Christopher Tate75a99702011-05-18 16:28:19 -07002441 // ----- Full restore from a file/socket -----
2442
2443 // Description of a file in the restore datastream
2444 static class FileMetadata {
2445 String packageName; // name of the owning app
2446 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002447 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002448 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2449 String path; // subpath within the semantic domain
2450 long mode; // e.g. 0666 (actually int)
2451 long mtime; // last mod time, UTC time_t (actually int)
2452 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002453
2454 @Override
2455 public String toString() {
2456 StringBuilder sb = new StringBuilder(128);
2457 sb.append("FileMetadata{");
2458 sb.append(packageName); sb.append(',');
2459 sb.append(type); sb.append(',');
2460 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2461 sb.append(size);
2462 sb.append('}');
2463 return sb.toString();
2464 }
Christopher Tate75a99702011-05-18 16:28:19 -07002465 }
2466
2467 enum RestorePolicy {
2468 IGNORE,
2469 ACCEPT,
2470 ACCEPT_IF_APK
2471 }
2472
2473 class PerformFullRestoreTask implements Runnable {
2474 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002475 String mCurrentPassword;
2476 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002477 IFullBackupRestoreObserver mObserver;
2478 AtomicBoolean mLatchObject;
2479 IBackupAgent mAgent;
2480 String mAgentPackage;
2481 ApplicationInfo mTargetApp;
2482 ParcelFileDescriptor[] mPipes = null;
2483
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002484 long mBytes;
2485
Christopher Tate75a99702011-05-18 16:28:19 -07002486 // possible handling states for a given package in the restore dataset
2487 final HashMap<String, RestorePolicy> mPackagePolicies
2488 = new HashMap<String, RestorePolicy>();
2489
2490 // installer package names for each encountered app, derived from the manifests
2491 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2492
2493 // Signatures for a given package found in its manifest file
2494 final HashMap<String, Signature[]> mManifestSignatures
2495 = new HashMap<String, Signature[]>();
2496
2497 // Packages we've already wiped data on when restoring their first file
2498 final HashSet<String> mClearedPackages = new HashSet<String>();
2499
Christopher Tate728a1c42011-07-28 18:03:03 -07002500 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002501 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002502 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002503 mCurrentPassword = curPassword;
2504 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002505 mObserver = observer;
2506 mLatchObject = latch;
2507 mAgent = null;
2508 mAgentPackage = null;
2509 mTargetApp = null;
2510
2511 // Which packages we've already wiped data on. We prepopulate this
2512 // with a whitelist of packages known to be unclearable.
2513 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002514 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002515
Christopher Tate75a99702011-05-18 16:28:19 -07002516 }
2517
2518 class RestoreFileRunnable implements Runnable {
2519 IBackupAgent mAgent;
2520 FileMetadata mInfo;
2521 ParcelFileDescriptor mSocket;
2522 int mToken;
2523
2524 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2525 ParcelFileDescriptor socket, int token) throws IOException {
2526 mAgent = agent;
2527 mInfo = info;
2528 mToken = token;
2529
2530 // This class is used strictly for process-local binder invocations. The
2531 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2532 // do not automatically get a 'dup'ed descriptor that we can can continue
2533 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2534 // before proceeding to do the restore.
2535 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2536 }
2537
2538 @Override
2539 public void run() {
2540 try {
2541 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2542 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2543 mToken, mBackupManagerBinder);
2544 } catch (RemoteException e) {
2545 // never happens; this is used strictly for local binder calls
2546 }
2547 }
2548 }
2549
2550 @Override
2551 public void run() {
2552 Slog.i(TAG, "--- Performing full-dataset restore ---");
2553 sendStartRestore();
2554
Christopher Tateb0628bf2011-06-02 15:08:13 -07002555 // Are we able to restore shared-storage data?
2556 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2557 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2558 }
2559
Christopher Tate2efd2db2011-07-19 16:32:49 -07002560 FileInputStream rawInStream = null;
2561 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002562 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002563 if (hasBackupPassword()) {
2564 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2565 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2566 return;
2567 }
2568 }
2569
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002570 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002571 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002572 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2573 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002574
2575 // First, parse out the unencrypted/uncompressed header
2576 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002577 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002578 final InputStream in;
2579
2580 boolean okay = false;
2581 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2582 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002583 rawDataIn.readFully(streamHeader);
2584 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2585 if (Arrays.equals(magicBytes, streamHeader)) {
2586 // okay, header looks good. now parse out the rest of the fields.
2587 String s = readHeaderLine(rawInStream);
2588 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2589 // okay, it's a version we recognize
2590 s = readHeaderLine(rawInStream);
2591 compressed = (Integer.parseInt(s) != 0);
2592 s = readHeaderLine(rawInStream);
2593 if (s.equals("none")) {
2594 // no more header to parse; we're good to go
2595 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07002596 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002597 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
2598 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07002599 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002600 }
2601 } else Slog.w(TAG, "Archive is encrypted but no password given");
2602 } else Slog.w(TAG, "Wrong header version: " + s);
2603 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002604
2605 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002606 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002607 return;
2608 }
2609
2610 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07002611 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07002612
2613 boolean didRestore;
2614 do {
Christopher Tate7926a692011-07-11 11:31:57 -07002615 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07002616 } while (didRestore);
2617
Christopher Tatec58efa62011-08-01 19:20:14 -07002618 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002619 } catch (IOException e) {
2620 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07002621 } finally {
2622 tearDownPipes();
2623 tearDownAgent(mTargetApp);
2624
2625 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002626 if (rawDataIn != null) rawDataIn.close();
2627 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07002628 mInputFile.close();
2629 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002630 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002631 /* nothing we can do about this */
2632 }
2633 synchronized (mCurrentOpLock) {
2634 mCurrentOperations.clear();
2635 }
2636 synchronized (mLatchObject) {
2637 mLatchObject.set(true);
2638 mLatchObject.notifyAll();
2639 }
2640 sendEndRestore();
2641 mWakelock.release();
Christopher Tatec58efa62011-08-01 19:20:14 -07002642 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07002643 }
2644 }
2645
Christopher Tate7bdb0962011-07-13 19:30:21 -07002646 String readHeaderLine(InputStream in) throws IOException {
2647 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002648 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002649 while ((c = in.read()) >= 0) {
2650 if (c == '\n') break; // consume and discard the newlines
2651 buffer.append((char)c);
2652 }
2653 return buffer.toString();
2654 }
2655
Christopher Tate2efd2db2011-07-19 16:32:49 -07002656 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
2657 InputStream result = null;
2658 try {
2659 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
2660
2661 String userSaltHex = readHeaderLine(rawInStream); // 5
2662 byte[] userSalt = hexToByteArray(userSaltHex);
2663
2664 String ckSaltHex = readHeaderLine(rawInStream); // 6
2665 byte[] ckSalt = hexToByteArray(ckSaltHex);
2666
2667 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
2668 String userIvHex = readHeaderLine(rawInStream); // 8
2669
2670 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
2671
2672 // decrypt the master key blob
2673 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07002674 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002675 rounds);
2676 byte[] IV = hexToByteArray(userIvHex);
2677 IvParameterSpec ivSpec = new IvParameterSpec(IV);
2678 c.init(Cipher.DECRYPT_MODE,
2679 new SecretKeySpec(userKey.getEncoded(), "AES"),
2680 ivSpec);
2681 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
2682 byte[] mkBlob = c.doFinal(mkCipher);
2683
2684 // first, the master key IV
2685 int offset = 0;
2686 int len = mkBlob[offset++];
2687 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
2688 offset += len;
2689 // then the master key itself
2690 len = mkBlob[offset++];
2691 byte[] mk = Arrays.copyOfRange(mkBlob,
2692 offset, offset + len);
2693 offset += len;
2694 // and finally the master key checksum hash
2695 len = mkBlob[offset++];
2696 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
2697 offset, offset + len);
2698
2699 // now validate the decrypted master key against the checksum
2700 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
2701 if (Arrays.equals(calculatedCk, mkChecksum)) {
2702 ivSpec = new IvParameterSpec(IV);
2703 c.init(Cipher.DECRYPT_MODE,
2704 new SecretKeySpec(mk, "AES"),
2705 ivSpec);
2706 // Only if all of the above worked properly will 'result' be assigned
2707 result = new CipherInputStream(rawInStream, c);
2708 } else Slog.w(TAG, "Incorrect password");
2709 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
2710 } catch (InvalidAlgorithmParameterException e) {
2711 Slog.e(TAG, "Needed parameter spec unavailable!", e);
2712 } catch (BadPaddingException e) {
2713 // This case frequently occurs when the wrong password is used to decrypt
2714 // the master key. Use the identical "incorrect password" log text as is
2715 // used in the checksum failure log in order to avoid providing additional
2716 // information to an attacker.
2717 Slog.w(TAG, "Incorrect password");
2718 } catch (IllegalBlockSizeException e) {
2719 Slog.w(TAG, "Invalid block size in master key");
2720 } catch (NoSuchAlgorithmException e) {
2721 Slog.e(TAG, "Needed decryption algorithm unavailable!");
2722 } catch (NoSuchPaddingException e) {
2723 Slog.e(TAG, "Needed padding mechanism unavailable!");
2724 } catch (InvalidKeyException e) {
2725 Slog.w(TAG, "Illegal password; aborting");
2726 } catch (NumberFormatException e) {
2727 Slog.w(TAG, "Can't parse restore data header");
2728 } catch (IOException e) {
2729 Slog.w(TAG, "Can't read input header");
2730 }
2731
2732 return result;
2733 }
2734
Christopher Tate75a99702011-05-18 16:28:19 -07002735 boolean restoreOneFile(InputStream instream, byte[] buffer) {
2736 FileMetadata info;
2737 try {
2738 info = readTarHeaders(instream);
2739 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002740 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07002741 dumpFileMetadata(info);
2742 }
2743
2744 final String pkg = info.packageName;
2745 if (!pkg.equals(mAgentPackage)) {
2746 // okay, change in package; set up our various
2747 // bookkeeping if we haven't seen it yet
2748 if (!mPackagePolicies.containsKey(pkg)) {
2749 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2750 }
2751
2752 // Clean up the previous agent relationship if necessary,
2753 // and let the observer know we're considering a new app.
2754 if (mAgent != null) {
2755 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
2756 tearDownPipes();
2757 tearDownAgent(mTargetApp);
2758 mTargetApp = null;
2759 mAgentPackage = null;
2760 }
2761 }
2762
2763 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
2764 mPackagePolicies.put(pkg, readAppManifest(info, instream));
2765 mPackageInstallers.put(pkg, info.installerPackageName);
2766 // We've read only the manifest content itself at this point,
2767 // so consume the footer before looping around to the next
2768 // input file
2769 skipTarPadding(info.size, instream);
2770 sendOnRestorePackage(pkg);
2771 } else {
2772 // Non-manifest, so it's actual file data. Is this a package
2773 // we're ignoring?
2774 boolean okay = true;
2775 RestorePolicy policy = mPackagePolicies.get(pkg);
2776 switch (policy) {
2777 case IGNORE:
2778 okay = false;
2779 break;
2780
2781 case ACCEPT_IF_APK:
2782 // If we're in accept-if-apk state, then the first file we
2783 // see MUST be the apk.
2784 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2785 if (DEBUG) Slog.d(TAG, "APK file; installing");
2786 // Try to install the app.
2787 String installerName = mPackageInstallers.get(pkg);
2788 okay = installApk(info, installerName, instream);
2789 // good to go; promote to ACCEPT
2790 mPackagePolicies.put(pkg, (okay)
2791 ? RestorePolicy.ACCEPT
2792 : RestorePolicy.IGNORE);
2793 // At this point we've consumed this file entry
2794 // ourselves, so just strip the tar footer and
2795 // go on to the next file in the input stream
2796 skipTarPadding(info.size, instream);
2797 return true;
2798 } else {
2799 // File data before (or without) the apk. We can't
2800 // handle it coherently in this case so ignore it.
2801 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2802 okay = false;
2803 }
2804 break;
2805
2806 case ACCEPT:
2807 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2808 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
2809 // we can take the data without the apk, so we
2810 // *want* to do so. skip the apk by declaring this
2811 // one file not-okay without changing the restore
2812 // policy for the package.
2813 okay = false;
2814 }
2815 break;
2816
2817 default:
2818 // Something has gone dreadfully wrong when determining
2819 // the restore policy from the manifest. Ignore the
2820 // rest of this package's data.
2821 Slog.e(TAG, "Invalid policy from manifest");
2822 okay = false;
2823 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2824 break;
2825 }
2826
2827 // If the policy is satisfied, go ahead and set up to pipe the
2828 // data to the agent.
2829 if (DEBUG && okay && mAgent != null) {
2830 Slog.i(TAG, "Reusing existing agent instance");
2831 }
2832 if (okay && mAgent == null) {
2833 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
2834
2835 try {
2836 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
2837
2838 // If we haven't sent any data to this app yet, we probably
2839 // need to clear it first. Check that.
2840 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002841 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07002842 // responsible for coherently managing a full
2843 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07002844 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07002845 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
2846 clearApplicationDataSynchronous(pkg);
2847 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002848 if (DEBUG) Slog.d(TAG, "backup agent ("
2849 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07002850 }
2851 mClearedPackages.add(pkg);
2852 } else {
2853 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
2854 }
2855
2856 // All set; now set up the IPC and launch the agent
2857 setUpPipes();
2858 mAgent = bindToAgentSynchronous(mTargetApp,
2859 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
2860 mAgentPackage = pkg;
2861 } catch (IOException e) {
2862 // fall through to error handling
2863 } catch (NameNotFoundException e) {
2864 // fall through to error handling
2865 }
2866
2867 if (mAgent == null) {
2868 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
2869 okay = false;
2870 tearDownPipes();
2871 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2872 }
2873 }
2874
2875 // Sanity check: make sure we never give data to the wrong app. This
2876 // should never happen but a little paranoia here won't go amiss.
2877 if (okay && !pkg.equals(mAgentPackage)) {
2878 Slog.e(TAG, "Restoring data for " + pkg
2879 + " but agent is for " + mAgentPackage);
2880 okay = false;
2881 }
2882
2883 // At this point we have an agent ready to handle the full
2884 // restore data as well as a pipe for sending data to
2885 // that agent. Tell the agent to start reading from the
2886 // pipe.
2887 if (okay) {
2888 boolean agentSuccess = true;
2889 long toCopy = info.size;
2890 final int token = generateToken();
2891 try {
2892 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
2893 + info.path);
2894 prepareOperationTimeout(token,
2895 TIMEOUT_FULL_BACKUP_INTERVAL);
2896 // fire up the app's agent listening on the socket. If
2897 // the agent is running in the system process we can't
2898 // just invoke it asynchronously, so we provide a thread
2899 // for it here.
2900 if (mTargetApp.processName.equals("system")) {
2901 Slog.d(TAG, "system process agent - spinning a thread");
2902 RestoreFileRunnable runner = new RestoreFileRunnable(
2903 mAgent, info, mPipes[0], token);
2904 new Thread(runner).start();
2905 } else {
2906 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
2907 info.domain, info.path, info.mode, info.mtime,
2908 token, mBackupManagerBinder);
2909 }
2910 } catch (IOException e) {
2911 // couldn't dup the socket for a process-local restore
2912 Slog.d(TAG, "Couldn't establish restore");
2913 agentSuccess = false;
2914 okay = false;
2915 } catch (RemoteException e) {
2916 // whoops, remote agent went away. We'll eat the content
2917 // ourselves, then, and not copy it over.
2918 Slog.e(TAG, "Agent crashed during full restore");
2919 agentSuccess = false;
2920 okay = false;
2921 }
2922
2923 // Copy over the data if the agent is still good
2924 if (okay) {
2925 boolean pipeOkay = true;
2926 FileOutputStream pipe = new FileOutputStream(
2927 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07002928 while (toCopy > 0) {
2929 int toRead = (toCopy > buffer.length)
2930 ? buffer.length : (int)toCopy;
2931 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002932 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002933 if (nRead <= 0) break;
2934 toCopy -= nRead;
2935
2936 // send it to the output pipe as long as things
2937 // are still good
2938 if (pipeOkay) {
2939 try {
2940 pipe.write(buffer, 0, nRead);
2941 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002942 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002943 pipeOkay = false;
2944 }
2945 }
2946 }
2947
2948 // done sending that file! Now we just need to consume
2949 // the delta from info.size to the end of block.
2950 skipTarPadding(info.size, instream);
2951
2952 // and now that we've sent it all, wait for the remote
2953 // side to acknowledge receipt
2954 agentSuccess = waitUntilOperationComplete(token);
2955 }
2956
2957 // okay, if the remote end failed at any point, deal with
2958 // it by ignoring the rest of the restore on it
2959 if (!agentSuccess) {
2960 mBackupHandler.removeMessages(MSG_TIMEOUT);
2961 tearDownPipes();
2962 tearDownAgent(mTargetApp);
2963 mAgent = null;
2964 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2965 }
2966 }
2967
2968 // Problems setting up the agent communication, or an already-
2969 // ignored package: skip to the next tar stream entry by
2970 // reading and discarding this file.
2971 if (!okay) {
2972 if (DEBUG) Slog.d(TAG, "[discarding file content]");
2973 long bytesToConsume = (info.size + 511) & ~511;
2974 while (bytesToConsume > 0) {
2975 int toRead = (bytesToConsume > buffer.length)
2976 ? buffer.length : (int)bytesToConsume;
2977 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002978 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002979 if (nRead <= 0) break;
2980 bytesToConsume -= nRead;
2981 }
2982 }
2983 }
2984 }
2985 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002986 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002987 // treat as EOF
2988 info = null;
2989 }
2990
2991 return (info != null);
2992 }
2993
2994 void setUpPipes() throws IOException {
2995 mPipes = ParcelFileDescriptor.createPipe();
2996 }
2997
2998 void tearDownPipes() {
2999 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003000 try {
3001 mPipes[0].close();
3002 mPipes[0] = null;
3003 mPipes[1].close();
3004 mPipes[1] = null;
3005 } catch (IOException e) {
3006 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003007 }
3008 mPipes = null;
3009 }
3010 }
3011
3012 void tearDownAgent(ApplicationInfo app) {
3013 if (mAgent != null) {
3014 try {
3015 // unbind and tidy up even on timeout or failure, just in case
3016 mActivityManager.unbindBackupAgent(app);
3017
3018 // The agent was running with a stub Application object, so shut it down.
3019 // !!! We hardcode the confirmation UI's package name here rather than use a
3020 // manifest flag! TODO something less direct.
3021 if (app.uid != Process.SYSTEM_UID
3022 && !app.packageName.equals("com.android.backupconfirm")) {
3023 if (DEBUG) Slog.d(TAG, "Killing host process");
3024 mActivityManager.killApplicationProcess(app.processName, app.uid);
3025 } else {
3026 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3027 }
3028 } catch (RemoteException e) {
3029 Slog.d(TAG, "Lost app trying to shut down");
3030 }
3031 mAgent = null;
3032 }
3033 }
3034
3035 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3036 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003037 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003038 int mResult;
3039
3040 public void reset() {
3041 synchronized (mDone) {
3042 mDone.set(false);
3043 }
3044 }
3045
3046 public void waitForCompletion() {
3047 synchronized (mDone) {
3048 while (mDone.get() == false) {
3049 try {
3050 mDone.wait();
3051 } catch (InterruptedException e) { }
3052 }
3053 }
3054 }
3055
3056 int getResult() {
3057 return mResult;
3058 }
3059
3060 @Override
3061 public void packageInstalled(String packageName, int returnCode)
3062 throws RemoteException {
3063 synchronized (mDone) {
3064 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003065 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003066 mDone.set(true);
3067 mDone.notifyAll();
3068 }
3069 }
3070 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003071
3072 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3073 final AtomicBoolean mDone = new AtomicBoolean();
3074 int mResult;
3075
3076 public void reset() {
3077 synchronized (mDone) {
3078 mDone.set(false);
3079 }
3080 }
3081
3082 public void waitForCompletion() {
3083 synchronized (mDone) {
3084 while (mDone.get() == false) {
3085 try {
3086 mDone.wait();
3087 } catch (InterruptedException e) { }
3088 }
3089 }
3090 }
3091
3092 @Override
3093 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3094 synchronized (mDone) {
3095 mResult = returnCode;
3096 mDone.set(true);
3097 mDone.notifyAll();
3098 }
3099 }
3100 }
3101
Christopher Tate75a99702011-05-18 16:28:19 -07003102 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003103 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003104
3105 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3106 boolean okay = true;
3107
3108 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3109
3110 // The file content is an .apk file. Copy it out to a staging location and
3111 // attempt to install it.
3112 File apkFile = new File(mDataDir, info.packageName);
3113 try {
3114 FileOutputStream apkStream = new FileOutputStream(apkFile);
3115 byte[] buffer = new byte[32 * 1024];
3116 long size = info.size;
3117 while (size > 0) {
3118 long toRead = (buffer.length < size) ? buffer.length : size;
3119 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003120 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003121 apkStream.write(buffer, 0, didRead);
3122 size -= didRead;
3123 }
3124 apkStream.close();
3125
3126 // make sure the installer can read it
3127 apkFile.setReadable(true, false);
3128
3129 // Now install it
3130 Uri packageUri = Uri.fromFile(apkFile);
3131 mInstallObserver.reset();
3132 mPackageManager.installPackage(packageUri, mInstallObserver,
3133 PackageManager.INSTALL_REPLACE_EXISTING, installerPackage);
3134 mInstallObserver.waitForCompletion();
3135
3136 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3137 // The only time we continue to accept install of data even if the
3138 // apk install failed is if we had already determined that we could
3139 // accept the data regardless.
3140 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3141 okay = false;
3142 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003143 } else {
3144 // Okay, the install succeeded. Make sure it was the right app.
3145 boolean uninstall = false;
3146 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3147 Slog.w(TAG, "Restore stream claimed to include apk for "
3148 + info.packageName + " but apk was really "
3149 + mInstallObserver.mPackageName);
3150 // delete the package we just put in place; it might be fraudulent
3151 okay = false;
3152 uninstall = true;
3153 } else {
3154 try {
3155 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3156 PackageManager.GET_SIGNATURES);
3157 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3158 Slog.w(TAG, "Restore stream contains apk of package "
3159 + info.packageName + " but it disallows backup/restore");
3160 okay = false;
3161 } else {
3162 // So far so good -- do the signatures match the manifest?
3163 Signature[] sigs = mManifestSignatures.get(info.packageName);
3164 if (!signaturesMatch(sigs, pkg)) {
3165 Slog.w(TAG, "Installed app " + info.packageName
3166 + " signatures do not match restore manifest");
3167 okay = false;
3168 uninstall = true;
3169 }
3170 }
3171 } catch (NameNotFoundException e) {
3172 Slog.w(TAG, "Install of package " + info.packageName
3173 + " succeeded but now not found");
3174 okay = false;
3175 }
3176 }
3177
3178 // If we're not okay at this point, we need to delete the package
3179 // that we just installed.
3180 if (uninstall) {
3181 mDeleteObserver.reset();
3182 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3183 mDeleteObserver, 0);
3184 mDeleteObserver.waitForCompletion();
3185 }
Christopher Tate75a99702011-05-18 16:28:19 -07003186 }
3187 } catch (IOException e) {
3188 Slog.e(TAG, "Unable to transcribe restored apk for install");
3189 okay = false;
3190 } finally {
3191 apkFile.delete();
3192 }
3193
3194 return okay;
3195 }
3196
3197 // Given an actual file content size, consume the post-content padding mandated
3198 // by the tar format.
3199 void skipTarPadding(long size, InputStream instream) throws IOException {
3200 long partial = (size + 512) % 512;
3201 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003202 final int needed = 512 - (int)partial;
3203 byte[] buffer = new byte[needed];
3204 if (readExactly(instream, buffer, 0, needed) == needed) {
3205 mBytes += needed;
3206 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003207 }
3208 }
3209
3210 // Returns a policy constant; takes a buffer arg to reduce memory churn
3211 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3212 throws IOException {
3213 // Fail on suspiciously large manifest files
3214 if (info.size > 64 * 1024) {
3215 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3216 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003217
Christopher Tate75a99702011-05-18 16:28:19 -07003218 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003219 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3220 mBytes += info.size;
3221 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003222
3223 RestorePolicy policy = RestorePolicy.IGNORE;
3224 String[] str = new String[1];
3225 int offset = 0;
3226
3227 try {
3228 offset = extractLine(buffer, offset, str);
3229 int version = Integer.parseInt(str[0]);
3230 if (version == BACKUP_MANIFEST_VERSION) {
3231 offset = extractLine(buffer, offset, str);
3232 String manifestPackage = str[0];
3233 // TODO: handle <original-package>
3234 if (manifestPackage.equals(info.packageName)) {
3235 offset = extractLine(buffer, offset, str);
3236 version = Integer.parseInt(str[0]); // app version
3237 offset = extractLine(buffer, offset, str);
3238 int platformVersion = Integer.parseInt(str[0]);
3239 offset = extractLine(buffer, offset, str);
3240 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3241 offset = extractLine(buffer, offset, str);
3242 boolean hasApk = str[0].equals("1");
3243 offset = extractLine(buffer, offset, str);
3244 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003245 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003246 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003247 for (int i = 0; i < numSigs; i++) {
3248 offset = extractLine(buffer, offset, str);
3249 sigs[i] = new Signature(str[0]);
3250 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003251 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003252
3253 // Okay, got the manifest info we need...
3254 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003255 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3256 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003257 // Fall through to IGNORE if the app explicitly disallows backup
3258 final int flags = pkgInfo.applicationInfo.flags;
3259 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3260 // Verify signatures against any installed version; if they
3261 // don't match, then we fall though and ignore the data. The
3262 // signatureMatch() method explicitly ignores the signature
3263 // check for packages installed on the system partition, because
3264 // such packages are signed with the platform cert instead of
3265 // the app developer's cert, so they're different on every
3266 // device.
3267 if (signaturesMatch(sigs, pkgInfo)) {
3268 if (pkgInfo.versionCode >= version) {
3269 Slog.i(TAG, "Sig + version match; taking data");
3270 policy = RestorePolicy.ACCEPT;
3271 } else {
3272 // The data is from a newer version of the app than
3273 // is presently installed. That means we can only
3274 // use it if the matching apk is also supplied.
3275 Slog.d(TAG, "Data version " + version
3276 + " is newer than installed version "
3277 + pkgInfo.versionCode + " - requiring apk");
3278 policy = RestorePolicy.ACCEPT_IF_APK;
3279 }
Christopher Tate75a99702011-05-18 16:28:19 -07003280 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003281 Slog.w(TAG, "Restore manifest signatures do not match "
3282 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003283 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003284 } else {
3285 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3286 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003287 }
3288 } catch (NameNotFoundException e) {
3289 // Okay, the target app isn't installed. We can process
3290 // the restore properly only if the dataset provides the
3291 // apk file and we can successfully install it.
3292 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3293 + " not installed; requiring apk in dataset");
3294 policy = RestorePolicy.ACCEPT_IF_APK;
3295 }
3296
3297 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3298 Slog.i(TAG, "Cannot restore package " + info.packageName
3299 + " without the matching .apk");
3300 }
3301 } else {
3302 Slog.i(TAG, "Missing signature on backed-up package "
3303 + info.packageName);
3304 }
3305 } else {
3306 Slog.i(TAG, "Expected package " + info.packageName
3307 + " but restore manifest claims " + manifestPackage);
3308 }
3309 } else {
3310 Slog.i(TAG, "Unknown restore manifest version " + version
3311 + " for package " + info.packageName);
3312 }
3313 } catch (NumberFormatException e) {
3314 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003315 } catch (IllegalArgumentException e) {
3316 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003317 }
3318
3319 return policy;
3320 }
3321
3322 // Builds a line from a byte buffer starting at 'offset', and returns
3323 // the index of the next unconsumed data in the buffer.
3324 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3325 final int end = buffer.length;
3326 if (offset >= end) throw new IOException("Incomplete data");
3327
3328 int pos;
3329 for (pos = offset; pos < end; pos++) {
3330 byte c = buffer[pos];
3331 // at LF we declare end of line, and return the next char as the
3332 // starting point for the next time through
3333 if (c == '\n') {
3334 break;
3335 }
3336 }
3337 outStr[0] = new String(buffer, offset, pos - offset);
3338 pos++; // may be pointing an extra byte past the end but that's okay
3339 return pos;
3340 }
3341
3342 void dumpFileMetadata(FileMetadata info) {
3343 if (DEBUG) {
3344 StringBuilder b = new StringBuilder(128);
3345
3346 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003347 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003348 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3349 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3350 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3351 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3352 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3353 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3354 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3355 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3356 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3357 b.append(String.format(" %9d ", info.size));
3358
3359 Date stamp = new Date(info.mtime);
3360 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3361
3362 b.append(info.packageName);
3363 b.append(" :: ");
3364 b.append(info.domain);
3365 b.append(" :: ");
3366 b.append(info.path);
3367
3368 Slog.i(TAG, b.toString());
3369 }
3370 }
3371 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3372 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3373 byte[] block = new byte[512];
3374 FileMetadata info = null;
3375
3376 boolean gotHeader = readTarHeader(instream, block);
3377 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003378 try {
3379 // okay, presume we're okay, and extract the various metadata
3380 info = new FileMetadata();
3381 info.size = extractRadix(block, 124, 12, 8);
3382 info.mtime = extractRadix(block, 136, 12, 8);
3383 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003384
Christopher Tate2efd2db2011-07-19 16:32:49 -07003385 info.path = extractString(block, 345, 155); // prefix
3386 String path = extractString(block, 0, 100);
3387 if (path.length() > 0) {
3388 if (info.path.length() > 0) info.path += '/';
3389 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003390 }
Christopher Tate75a99702011-05-18 16:28:19 -07003391
Christopher Tate2efd2db2011-07-19 16:32:49 -07003392 // tar link indicator field: 1 byte at offset 156 in the header.
3393 int typeChar = block[156];
3394 if (typeChar == 'x') {
3395 // pax extended header, so we need to read that
3396 gotHeader = readPaxExtendedHeader(instream, info);
3397 if (gotHeader) {
3398 // and after a pax extended header comes another real header -- read
3399 // that to find the real file type
3400 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003401 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003402 if (!gotHeader) throw new IOException("Bad or missing pax header");
3403
3404 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003405 }
Christopher Tate75a99702011-05-18 16:28:19 -07003406
Christopher Tate2efd2db2011-07-19 16:32:49 -07003407 switch (typeChar) {
3408 case '0': info.type = BackupAgent.TYPE_FILE; break;
3409 case '5': {
3410 info.type = BackupAgent.TYPE_DIRECTORY;
3411 if (info.size != 0) {
3412 Slog.w(TAG, "Directory entry with nonzero size in header");
3413 info.size = 0;
3414 }
3415 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003416 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003417 case 0: {
3418 // presume EOF
3419 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3420 return null;
3421 }
3422 default: {
3423 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3424 throw new IOException("Unknown entity type " + typeChar);
3425 }
Christopher Tate75a99702011-05-18 16:28:19 -07003426 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003427
3428 // Parse out the path
3429 //
3430 // first: apps/shared/unrecognized
3431 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3432 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3433 // File in shared storage. !!! TODO: implement this.
3434 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
3435 info.packageName = "com.android.sharedstoragebackup";
3436 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3437 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3438 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3439 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3440 // App content! Parse out the package name and domain
3441
3442 // strip the apps/ prefix
3443 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3444
3445 // extract the package name
3446 int slash = info.path.indexOf('/');
3447 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3448 info.packageName = info.path.substring(0, slash);
3449 info.path = info.path.substring(slash+1);
3450
3451 // if it's a manifest we're done, otherwise parse out the domains
3452 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3453 slash = info.path.indexOf('/');
3454 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3455 info.domain = info.path.substring(0, slash);
3456 // validate that it's one of the domains we understand
3457 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3458 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3459 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3460 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3461 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3462 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3463 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3464 throw new IOException("Unrecognized domain " + info.domain);
3465 }
3466
3467 info.path = info.path.substring(slash + 1);
3468 }
3469 }
3470 } catch (IOException e) {
3471 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003472 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003473 HEXLOG(block);
3474 }
3475 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003476 }
3477 }
3478 return info;
3479 }
3480
Christopher Tate2efd2db2011-07-19 16:32:49 -07003481 private void HEXLOG(byte[] block) {
3482 int offset = 0;
3483 int todo = block.length;
3484 StringBuilder buf = new StringBuilder(64);
3485 while (todo > 0) {
3486 buf.append(String.format("%04x ", offset));
3487 int numThisLine = (todo > 16) ? 16 : todo;
3488 for (int i = 0; i < numThisLine; i++) {
3489 buf.append(String.format("%02x ", block[offset+i]));
3490 }
3491 Slog.i("hexdump", buf.toString());
3492 buf.setLength(0);
3493 todo -= numThisLine;
3494 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003495 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003496 }
3497
Christopher Tate6853fcf2011-08-10 17:52:21 -07003498 // Read exactly the given number of bytes into a buffer at the stated offset.
3499 // Returns false if EOF is encountered before the requested number of bytes
3500 // could be read.
3501 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3502 throws IOException {
3503 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3504
3505 int soFar = 0;
3506 while (soFar < size) {
3507 int nRead = in.read(buffer, offset + soFar, size - soFar);
3508 if (nRead <= 0) {
3509 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3510 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003511 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003512 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003513 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003514 return soFar;
3515 }
3516
3517 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3518 final int got = readExactly(instream, block, 0, 512);
3519 if (got == 0) return false; // Clean EOF
3520 if (got < 512) throw new IOException("Unable to read full block header");
3521 mBytes += 512;
3522 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003523 }
3524
3525 // overwrites 'info' fields based on the pax extended header
3526 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3527 throws IOException {
3528 // We should never see a pax extended header larger than this
3529 if (info.size > 32*1024) {
3530 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3531 + " - aborting");
3532 throw new IOException("Sanity failure: pax header size " + info.size);
3533 }
3534
3535 // read whole blocks, not just the content size
3536 int numBlocks = (int)((info.size + 511) >> 9);
3537 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003538 if (readExactly(instream, data, 0, data.length) < data.length) {
3539 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003540 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003541 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003542
3543 final int contentSize = (int) info.size;
3544 int offset = 0;
3545 do {
3546 // extract the line at 'offset'
3547 int eol = offset+1;
3548 while (eol < contentSize && data[eol] != ' ') eol++;
3549 if (eol >= contentSize) {
3550 // error: we just hit EOD looking for the end of the size field
3551 throw new IOException("Invalid pax data");
3552 }
3553 // eol points to the space between the count and the key
3554 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3555 int key = eol + 1; // start of key=value
3556 eol = offset + linelen - 1; // trailing LF
3557 int value;
3558 for (value = key+1; data[value] != '=' && value <= eol; value++);
3559 if (value > eol) {
3560 throw new IOException("Invalid pax declaration");
3561 }
3562
3563 // pax requires that key/value strings be in UTF-8
3564 String keyStr = new String(data, key, value-key, "UTF-8");
3565 // -1 to strip the trailing LF
3566 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3567
3568 if ("path".equals(keyStr)) {
3569 info.path = valStr;
3570 } else if ("size".equals(keyStr)) {
3571 info.size = Long.parseLong(valStr);
3572 } else {
3573 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3574 }
3575
3576 offset += linelen;
3577 } while (offset < contentSize);
3578
3579 return true;
3580 }
3581
3582 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3583 throws IOException {
3584 long value = 0;
3585 final int end = offset + maxChars;
3586 for (int i = offset; i < end; i++) {
3587 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003588 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003589 if (b == 0 || b == ' ') break;
3590 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003591 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07003592 }
3593 value = radix * value + (b - '0');
3594 }
3595 return value;
3596 }
3597
3598 String extractString(byte[] data, int offset, int maxChars) throws IOException {
3599 final int end = offset + maxChars;
3600 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003601 // tar string fields terminate early with a NUL
3602 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07003603 return new String(data, offset, eos-offset, "US-ASCII");
3604 }
3605
3606 void sendStartRestore() {
3607 if (mObserver != null) {
3608 try {
3609 mObserver.onStartRestore();
3610 } catch (RemoteException e) {
3611 Slog.w(TAG, "full restore observer went away: startRestore");
3612 mObserver = null;
3613 }
3614 }
3615 }
3616
3617 void sendOnRestorePackage(String name) {
3618 if (mObserver != null) {
3619 try {
3620 // TODO: use a more user-friendly name string
3621 mObserver.onRestorePackage(name);
3622 } catch (RemoteException e) {
3623 Slog.w(TAG, "full restore observer went away: restorePackage");
3624 mObserver = null;
3625 }
3626 }
3627 }
3628
3629 void sendEndRestore() {
3630 if (mObserver != null) {
3631 try {
3632 mObserver.onEndRestore();
3633 } catch (RemoteException e) {
3634 Slog.w(TAG, "full restore observer went away: endRestore");
3635 mObserver = null;
3636 }
3637 }
3638 }
3639 }
3640
Christopher Tatedf01dea2009-06-09 20:45:02 -07003641 // ----- Restore handling -----
3642
Christopher Tate78dd4a72009-11-04 11:49:08 -08003643 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
3644 // If the target resides on the system partition, we allow it to restore
3645 // data from the like-named package in a restore set even if the signatures
3646 // do not match. (Unlike general applications, those flashed to the system
3647 // partition will be signed with the device's platform certificate, so on
3648 // different phones the same system app will have different signatures.)
3649 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003650 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08003651 return true;
3652 }
3653
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003654 // Allow unsigned apps, but not signed on one device and unsigned on the other
3655 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08003656 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07003657 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07003658 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003659 if ((storedSigs == null || storedSigs.length == 0)
3660 && (deviceSigs == null || deviceSigs.length == 0)) {
3661 return true;
3662 }
3663 if (storedSigs == null || deviceSigs == null) {
3664 return false;
3665 }
3666
Christopher Tateabce4e82009-06-18 18:35:32 -07003667 // !!! TODO: this demands that every stored signature match one
3668 // that is present on device, and does not demand the converse.
3669 // Is this this right policy?
3670 int nStored = storedSigs.length;
3671 int nDevice = deviceSigs.length;
3672
3673 for (int i=0; i < nStored; i++) {
3674 boolean match = false;
3675 for (int j=0; j < nDevice; j++) {
3676 if (storedSigs[i].equals(deviceSigs[j])) {
3677 match = true;
3678 break;
3679 }
3680 }
3681 if (!match) {
3682 return false;
3683 }
3684 }
3685 return true;
3686 }
3687
Christopher Tate44a27902010-01-27 17:15:49 -08003688 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003689 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003690 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003691 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003692 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003693 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003694 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003695 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07003696 private HashSet<String> mFilterSet;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003697
Christopher Tate5cbbf562009-06-22 16:44:51 -07003698 class RestoreRequest {
3699 public PackageInfo app;
3700 public int storedAppVersion;
3701
3702 RestoreRequest(PackageInfo _app, int _version) {
3703 app = _app;
3704 storedAppVersion = _version;
3705 }
3706 }
3707
Christopher Tate44a27902010-01-27 17:15:49 -08003708 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07003709 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07003710 boolean needFullBackup, String[] filterSet) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003711 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003712 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003713 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08003714 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08003715 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003716 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003717
Christopher Tate284f1bb2011-07-07 14:31:18 -07003718 if (filterSet != null) {
3719 mFilterSet = new HashSet<String>();
3720 for (String pkg : filterSet) {
3721 mFilterSet.add(pkg);
3722 }
3723 } else {
3724 mFilterSet = null;
3725 }
3726
Christopher Tate5cb400b2009-06-25 16:03:14 -07003727 try {
3728 mStateDir = new File(mBaseStateDir, transport.transportDirName());
3729 } catch (RemoteException e) {
3730 // can't happen; the transport is local
3731 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003732 }
3733
Christopher Tatedf01dea2009-06-09 20:45:02 -07003734 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003735 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003736 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08003737 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate284f1bb2011-07-07 14:31:18 -07003738 + " mTargetPackage=" + mTargetPackage + " mFilterSet=" + mFilterSet
3739 + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003740
Christopher Tateb49ceb32010-02-08 16:22:24 -08003741 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003742 int error = -1; // assume error
3743
Dan Egnorefe52642009-06-24 00:16:33 -07003744 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07003745 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003746 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003747 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07003748
Dan Egnorefe52642009-06-24 00:16:33 -07003749 // Get the list of all packages which have backup enabled.
3750 // (Include the Package Manager metadata pseudo-package first.)
3751 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
3752 PackageInfo omPackage = new PackageInfo();
3753 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
3754 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003755
Dan Egnorefe52642009-06-24 00:16:33 -07003756 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003757 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07003758 // if there's a filter set, strip out anything that isn't
3759 // present before proceeding
3760 if (mFilterSet != null) {
3761 for (int i = agentPackages.size() - 1; i >= 0; i--) {
3762 final PackageInfo pkg = agentPackages.get(i);
3763 if (! mFilterSet.contains(pkg.packageName)) {
3764 agentPackages.remove(i);
3765 }
3766 }
3767 if (DEBUG) {
3768 Slog.i(TAG, "Post-filter package set for restore:");
3769 for (PackageInfo p : agentPackages) {
3770 Slog.i(TAG, " " + p);
3771 }
3772 }
3773 }
Christopher Tate84725812010-02-04 15:52:40 -08003774 restorePackages.addAll(agentPackages);
3775 } else {
3776 // Just one package to attempt restore of
3777 restorePackages.add(mTargetPackage);
3778 }
Dan Egnorefe52642009-06-24 00:16:33 -07003779
Christopher Tate7d562ec2009-06-25 18:03:43 -07003780 // let the observer know that we're running
3781 if (mObserver != null) {
3782 try {
3783 // !!! TODO: get an actual count from the transport after
3784 // its startRestore() runs?
3785 mObserver.restoreStarting(restorePackages.size());
3786 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003787 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003788 mObserver = null;
3789 }
3790 }
3791
Dan Egnor01445162009-09-21 17:04:05 -07003792 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
3793 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003794 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003795 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003796 return;
3797 }
3798
3799 String packageName = mTransport.nextRestorePackage();
3800 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003801 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003802 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003803 return;
3804 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003805 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003806 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003807 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07003808 return;
3809 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003810 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07003811 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003812 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003813 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003814 return;
3815 }
3816
3817 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08003818 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07003819 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07003820 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
3821 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07003822
Christopher Tate8c032472009-07-02 14:28:47 -07003823 // Verify that the backup set includes metadata. If not, we can't do
3824 // signature/version verification etc, so we simply do not proceed with
3825 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07003826 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003827 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003828 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003829 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07003830 return;
3831 }
3832
Christopher Tate7d562ec2009-06-25 18:03:43 -07003833 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07003834 for (;;) {
3835 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003836
Dan Egnorefe52642009-06-24 00:16:33 -07003837 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003838 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003839 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003840 return;
3841 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003842 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07003843 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003844 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003845
Christopher Tate7d562ec2009-06-25 18:03:43 -07003846 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07003847 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07003848 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07003849 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003850 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003851 mObserver = null;
3852 }
3853 }
3854
Dan Egnorefe52642009-06-24 00:16:33 -07003855 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
3856 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003857 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003858 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003859 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003860 continue;
3861 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003862
Dan Egnorbb9001c2009-07-27 12:20:13 -07003863 PackageInfo packageInfo;
3864 try {
3865 int flags = PackageManager.GET_SIGNATURES;
3866 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
3867 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003868 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003869 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003870 "Package missing on device");
3871 continue;
3872 }
3873
Dan Egnorefe52642009-06-24 00:16:33 -07003874 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08003875 // Data is from a "newer" version of the app than we have currently
3876 // installed. If the app has not declared that it is prepared to
3877 // handle this case, we do not attempt the restore.
3878 if ((packageInfo.applicationInfo.flags
3879 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
3880 String message = "Version " + metaInfo.versionCode
3881 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003882 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08003883 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
3884 packageName, message);
3885 continue;
3886 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003887 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08003888 + " > installed " + packageInfo.versionCode
3889 + " but restoreAnyVersion");
3890 }
Dan Egnorefe52642009-06-24 00:16:33 -07003891 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003892
Christopher Tate78dd4a72009-11-04 11:49:08 -08003893 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003894 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003895 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003896 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07003897 continue;
3898 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003899
Joe Onorato8a9b2202010-02-26 18:56:32 -08003900 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07003901 + " restore version [" + metaInfo.versionCode
3902 + "] is compatible with installed version ["
3903 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07003904
Christopher Tate3de55bc2010-03-12 17:28:08 -08003905 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07003906 IBackupAgent agent = bindToAgentSynchronous(
3907 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08003908 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07003909 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003910 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003911 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003912 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003913 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003914 }
3915
Christopher Tate5e1ab332009-09-01 20:32:49 -07003916 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07003917 try {
Chris Tate249345b2010-10-29 12:57:04 -07003918 processOneRestore(packageInfo, metaInfo.versionCode, agent,
3919 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003920 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07003921 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003922 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07003923 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07003924
3925 // The agent was probably running with a stub Application object,
3926 // which isn't a valid run mode for the main app logic. Shut
3927 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08003928 // usual full initialization. Note that this is only done for
3929 // full-system restores: when a single app has requested a restore,
3930 // it is explicitly not killed following that operation.
3931 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07003932 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003933 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003934 + packageInfo.applicationInfo.processName);
3935 mActivityManager.killApplicationProcess(
3936 packageInfo.applicationInfo.processName,
3937 packageInfo.applicationInfo.uid);
3938 }
Dan Egnorefe52642009-06-24 00:16:33 -07003939 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003940 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003941
3942 // if we get this far, report success to the observer
3943 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07003944 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003945 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003946 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003947 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003948 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003949 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003950
Dan Egnorefe52642009-06-24 00:16:33 -07003951 try {
3952 mTransport.finishRestore();
3953 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003954 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003955 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003956
3957 if (mObserver != null) {
3958 try {
3959 mObserver.restoreFinished(error);
3960 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003961 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003962 }
3963 }
Christopher Tateb6787f22009-07-02 17:40:45 -07003964
Christopher Tate84725812010-02-04 15:52:40 -08003965 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08003966 // ancestral dataset, as well as the set of apps that are possibly
3967 // restoreable from the dataset
3968 if (mTargetPackage == null && pmAgent != null) {
3969 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003970 mAncestralToken = mToken;
3971 writeRestoreTokens();
3972 }
3973
Christopher Tate1bb69062010-02-19 17:02:12 -08003974 // We must under all circumstances tell the Package Manager to
3975 // proceed with install notifications if it's waiting for us.
3976 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003977 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08003978 try {
3979 mPackageManagerBinder.finishPackageInstall(mPmToken);
3980 } catch (RemoteException e) { /* can't happen */ }
3981 }
3982
Christopher Tate73a3cb32010-12-13 18:27:26 -08003983 // Furthermore we need to reset the session timeout clock
3984 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
3985 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
3986 TIMEOUT_RESTORE_INTERVAL);
3987
Christopher Tateb6787f22009-07-02 17:40:45 -07003988 // done; we can finally release the wakelock
3989 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07003990 }
3991 }
3992
Dan Egnorefe52642009-06-24 00:16:33 -07003993 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07003994 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
3995 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003996 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07003997 final String packageName = app.packageName;
3998
Joe Onorato8a9b2202010-02-26 18:56:32 -08003999 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004000
Christopher Tatec7b31e32009-06-10 15:49:30 -07004001 // !!! TODO: get the dirs from the transport
4002 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07004003 File newStateName = new File(mStateDir, packageName + ".new");
4004 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004005
Dan Egnorbb9001c2009-07-27 12:20:13 -07004006 ParcelFileDescriptor backupData = null;
4007 ParcelFileDescriptor newState = null;
4008
Christopher Tate4a627c72011-04-01 14:43:32 -07004009 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004010 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004011 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07004012 backupData = ParcelFileDescriptor.open(backupDataName,
4013 ParcelFileDescriptor.MODE_READ_WRITE |
4014 ParcelFileDescriptor.MODE_CREATE |
4015 ParcelFileDescriptor.MODE_TRUNCATE);
4016
Dan Egnor01445162009-09-21 17:04:05 -07004017 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004018 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004019 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004020 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004021 }
4022
4023 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07004024 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07004025 backupData = ParcelFileDescriptor.open(backupDataName,
4026 ParcelFileDescriptor.MODE_READ_ONLY);
4027
Dan Egnorbb9001c2009-07-27 12:20:13 -07004028 newState = ParcelFileDescriptor.open(newStateName,
4029 ParcelFileDescriptor.MODE_READ_WRITE |
4030 ParcelFileDescriptor.MODE_CREATE |
4031 ParcelFileDescriptor.MODE_TRUNCATE);
4032
Christopher Tate44a27902010-01-27 17:15:49 -08004033 // Kick off the restore, checking for hung agents
4034 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
4035 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
4036 boolean success = waitUntilOperationComplete(token);
4037
4038 if (!success) {
4039 throw new RuntimeException("restore timeout");
4040 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004041
4042 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07004043 //
4044 // !!! TODO: the restored data should be migrated on the server
4045 // side into the current dataset. In that case the new state file
4046 // we just created would reflect the data already extant in the
4047 // backend, so there'd be nothing more to do. Until that happens,
4048 // however, we need to make sure that we record the data to the
4049 // current backend dataset. (Yes, this means shipping the data over
4050 // the wire in both directions. That's bad, but consistency comes
4051 // first, then efficiency.) Once we introduce server-side data
4052 // migration to the newly-restored device's dataset, we will change
4053 // the following from a discard of the newly-written state to the
4054 // "correct" operation of renaming into the canonical state blob.
4055 newStateName.delete(); // TODO: remove; see above comment
4056 //newStateName.renameTo(savedStateName); // TODO: replace with this
4057
Dan Egnorbb9001c2009-07-27 12:20:13 -07004058 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004059 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004060 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004061 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004062 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07004063
Christopher Tate96733042009-07-20 14:49:13 -07004064 // If the agent fails restore, it might have put the app's data
4065 // into an incoherent state. For consistency we wipe its data
4066 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07004067 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07004068 } finally {
4069 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004070 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
4071 try { if (newState != null) newState.close(); } catch (IOException e) {}
4072 backupData = newState = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07004073 synchronized (mCurrentOperations) {
4074 mCurrentOperations.delete(token);
4075 }
Chris Tate249345b2010-10-29 12:57:04 -07004076
4077 // If we know a priori that we'll need to perform a full post-restore backup
4078 // pass, clear the new state file data. This means we're discarding work that
4079 // was just done by the app's agent, but this way the agent doesn't need to
4080 // take any special action based on global device state.
4081 if (needFullBackup) {
4082 newStateName.delete();
4083 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004084 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004085 }
4086 }
4087
Christopher Tate44a27902010-01-27 17:15:49 -08004088 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004089 IBackupTransport mTransport;
4090 PackageInfo mPackage;
4091
Christopher Tate44a27902010-01-27 17:15:49 -08004092 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004093 mTransport = transport;
4094 mPackage = packageInfo;
4095 }
4096
Christopher Tateee0e78a2009-07-02 11:17:03 -07004097 public void run() {
4098 try {
4099 // Clear the on-device backup state to ensure a full backup next time
4100 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4101 File stateFile = new File(stateDir, mPackage.packageName);
4102 stateFile.delete();
4103
4104 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004105 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004106 mTransport.clearBackupData(mPackage);
4107 } catch (RemoteException e) {
4108 // can't happen; the transport is local
4109 } finally {
4110 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004111 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004112 mTransport.finishBackup();
4113 } catch (RemoteException e) {
4114 // can't happen; the transport is local
4115 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004116
4117 // Last but not least, release the cpu
4118 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004119 }
4120 }
4121 }
4122
Christopher Tate44a27902010-01-27 17:15:49 -08004123 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004124 HashSet<String> mQueue;
4125
Christopher Tate44a27902010-01-27 17:15:49 -08004126 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004127 mQueue = transportNames;
4128 }
4129
Christopher Tate4cc86e12009-09-21 19:36:51 -07004130 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004131 try {
4132 for (String transportName : mQueue) {
4133 IBackupTransport transport = getTransport(transportName);
4134 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004135 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004136 continue;
4137 }
4138
Joe Onorato8a9b2202010-02-26 18:56:32 -08004139 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004140 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004141 long startRealtime = SystemClock.elapsedRealtime();
4142 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004143
Christopher Tate4cc86e12009-09-21 19:36:51 -07004144 if (status == BackupConstants.TRANSPORT_OK) {
4145 status = transport.finishBackup();
4146 }
4147
4148 // Okay, the wipe really happened. Clean up our local bookkeeping.
4149 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004150 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004151 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004152 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004153 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004154 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004155 synchronized (mQueueLock) {
4156 recordInitPendingLocked(false, transportName);
4157 }
Dan Egnor726247c2009-09-29 19:12:31 -07004158 } else {
4159 // If this didn't work, requeue this one and try again
4160 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004161 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004162 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004163 synchronized (mQueueLock) {
4164 recordInitPendingLocked(true, transportName);
4165 }
4166 // do this via another alarm to make sure of the wakelock states
4167 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004168 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004169 + transportName + " resched in " + delay);
4170 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4171 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004172 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004173 }
4174 } catch (RemoteException e) {
4175 // can't happen; the transports are local
4176 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004177 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004178 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004179 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004180 mWakelock.release();
4181 }
4182 }
4183 }
4184
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004185 private void dataChangedImpl(String packageName) {
4186 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4187 dataChangedImpl(packageName, targets);
4188 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004189
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004190 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004191 // Record that we need a backup pass for the caller. Since multiple callers
4192 // may share a uid, we need to note all candidates within that uid and schedule
4193 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004194 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004195
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004196 if (targets == null) {
4197 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4198 + " uid=" + Binder.getCallingUid());
4199 return;
4200 }
4201
4202 synchronized (mQueueLock) {
4203 // Note that this client has made data changes that need to be backed up
4204 for (ApplicationInfo app : targets) {
4205 // validate the caller-supplied package name against the known set of
4206 // packages associated with this uid
4207 if (app.packageName.equals(packageName)) {
4208 // Add the caller to the set of pending backups. If there is
4209 // one already there, then overwrite it, but no harm done.
Christopher Tate4a627c72011-04-01 14:43:32 -07004210 BackupRequest req = new BackupRequest(app);
Christopher Tatec28083a2010-12-14 16:16:44 -08004211 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004212 // Journal this request in case of crash. The put()
4213 // operation returned null when this package was not already
4214 // in the set; we want to avoid touching the disk redundantly.
4215 writeToJournalLocked(packageName);
4216
Christopher Tatec58efa62011-08-01 19:20:14 -07004217 if (MORE_DEBUG) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004218 int numKeys = mPendingBackups.size();
4219 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4220 for (BackupRequest b : mPendingBackups.values()) {
4221 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
4222 }
4223 }
4224 }
4225 }
4226 }
4227 }
4228 }
4229
4230 // Note: packageName is currently unused, but may be in the future
4231 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004232 // If the caller does not hold the BACKUP permission, it can only request a
4233 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004234 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004235 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004236 synchronized (mBackupParticipants) {
4237 return mBackupParticipants.get(Binder.getCallingUid());
4238 }
4239 }
4240
4241 // a caller with full permission can ask to back up any participating app
4242 // !!! TODO: allow backup of ANY app?
4243 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4244 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004245 int N = mBackupParticipants.size();
4246 for (int i = 0; i < N; i++) {
4247 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4248 if (s != null) {
4249 targets.addAll(s);
4250 }
4251 }
4252 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004253 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004254 }
Christopher Tate46758122009-05-06 11:22:00 -07004255
Christopher Tatecde87f42009-06-12 12:55:53 -07004256 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004257 RandomAccessFile out = null;
4258 try {
4259 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4260 out = new RandomAccessFile(mJournal, "rws");
4261 out.seek(out.length());
4262 out.writeUTF(str);
4263 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004264 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004265 mJournal = null;
4266 } finally {
4267 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004268 }
4269 }
4270
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004271 // ----- IBackupManager binder interface -----
4272
4273 public void dataChanged(final String packageName) {
4274 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4275 if (targets == null) {
4276 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4277 + " uid=" + Binder.getCallingUid());
4278 return;
4279 }
4280
4281 mBackupHandler.post(new Runnable() {
4282 public void run() {
4283 dataChangedImpl(packageName, targets);
4284 }
4285 });
4286 }
4287
Christopher Tateee0e78a2009-07-02 11:17:03 -07004288 // Clear the given package's backup data from the current transport
4289 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004290 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004291 PackageInfo info;
4292 try {
4293 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4294 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004295 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004296 return;
4297 }
4298
4299 // If the caller does not hold the BACKUP permission, it can only request a
4300 // wipe of its own backed-up data.
4301 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004302 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004303 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4304 apps = mBackupParticipants.get(Binder.getCallingUid());
4305 } else {
4306 // a caller with full permission can ask to back up any participating app
4307 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004308 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004309 apps = new HashSet<ApplicationInfo>();
4310 int N = mBackupParticipants.size();
4311 for (int i = 0; i < N; i++) {
4312 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4313 if (s != null) {
4314 apps.addAll(s);
4315 }
4316 }
4317 }
4318
4319 // now find the given package in the set of candidate apps
4320 for (ApplicationInfo app : apps) {
4321 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004322 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004323 // found it; fire off the clear request
4324 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004325 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004326 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004327 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4328 new ClearParams(getTransport(mCurrentTransport), info));
4329 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004330 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004331 }
4332 break;
4333 }
4334 }
4335 }
4336
Christopher Tateace7f092009-06-15 18:07:25 -07004337 // Run a backup pass immediately for any applications that have declared
4338 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004339 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004340 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004341
Joe Onorato8a9b2202010-02-26 18:56:32 -08004342 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004343 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004344 // Because the alarms we are using can jitter, and we want an *immediate*
4345 // backup pass to happen, we restart the timer beginning with "next time,"
4346 // then manually fire the backup trigger intent ourselves.
4347 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004348 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004349 mRunBackupIntent.send();
4350 } catch (PendingIntent.CanceledException e) {
4351 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004352 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004353 }
Christopher Tate46758122009-05-06 11:22:00 -07004354 }
4355 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004356
Christopher Tate4a627c72011-04-01 14:43:32 -07004357 // Run a *full* backup pass for the given package, writing the resulting data stream
4358 // to the supplied file descriptor. This method is synchronous and does not return
4359 // to the caller until the backup has been completed.
4360 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
4361 boolean doAllApps, String[] pkgList) {
4362 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4363
4364 // Validate
4365 if (!doAllApps) {
4366 if (!includeShared) {
4367 // If we're backing up shared data (sdcard or equivalent), then we can run
4368 // without any supplied app names. Otherwise, we'd be doing no work, so
4369 // report the error.
4370 if (pkgList == null || pkgList.length == 0) {
4371 throw new IllegalArgumentException(
4372 "Backup requested but neither shared nor any apps named");
4373 }
4374 }
4375 }
4376
4377 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4378 + " shared=" + includeShared + " all=" + doAllApps
4379 + " pkgs=" + pkgList);
4380
4381 long oldId = Binder.clearCallingIdentity();
4382 try {
4383 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
4384 doAllApps, pkgList);
4385 final int token = generateToken();
4386 synchronized (mFullConfirmations) {
4387 mFullConfirmations.put(token, params);
4388 }
4389
Christopher Tate75a99702011-05-18 16:28:19 -07004390 // start up the confirmation UI
4391 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4392 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4393 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004394 mFullConfirmations.delete(token);
4395 return;
4396 }
Christopher Tate75a99702011-05-18 16:28:19 -07004397
4398 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004399 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4400
4401 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07004402 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004403
4404 // wait for the backup to be performed
4405 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
4406 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004407 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07004408 try {
4409 fd.close();
4410 } catch (IOException e) {
4411 // just eat it
4412 }
Christopher Tate75a99702011-05-18 16:28:19 -07004413 Binder.restoreCallingIdentity(oldId);
Christopher Tate4a627c72011-04-01 14:43:32 -07004414 }
Christopher Tatec58efa62011-08-01 19:20:14 -07004415 if (MORE_DEBUG) Slog.d(TAG, "Full backup done; returning to caller");
Christopher Tate75a99702011-05-18 16:28:19 -07004416 }
4417
4418 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004419 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07004420 Slog.i(TAG, "Beginning full restore...");
4421
4422 long oldId = Binder.clearCallingIdentity();
4423
4424 try {
4425 FullRestoreParams params = new FullRestoreParams(fd);
4426 final int token = generateToken();
4427 synchronized (mFullConfirmations) {
4428 mFullConfirmations.put(token, params);
4429 }
4430
4431 // start up the confirmation UI
4432 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
4433 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
4434 Slog.e(TAG, "Unable to launch full restore confirmation");
4435 mFullConfirmations.delete(token);
4436 return;
4437 }
4438
4439 // make sure the screen is lit for the user interaction
4440 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4441
4442 // start the confirmation countdown
4443 startConfirmationTimeout(token, params);
4444
4445 // wait for the restore to be performed
4446 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
4447 waitForCompletion(params);
4448 } finally {
4449 try {
4450 fd.close();
4451 } catch (IOException e) {
4452 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
4453 }
4454 Binder.restoreCallingIdentity(oldId);
4455 Slog.i(TAG, "Full restore completed");
4456 }
4457 }
4458
4459 boolean startConfirmationUi(int token, String action) {
4460 try {
4461 Intent confIntent = new Intent(action);
4462 confIntent.setClassName("com.android.backupconfirm",
4463 "com.android.backupconfirm.BackupRestoreConfirmation");
4464 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
4465 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4466 mContext.startActivity(confIntent);
4467 } catch (ActivityNotFoundException e) {
4468 return false;
4469 }
4470 return true;
4471 }
4472
4473 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07004474 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07004475 + TIMEOUT_FULL_CONFIRMATION + " millis");
4476 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
4477 token, 0, params);
4478 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07004479 }
4480
4481 void waitForCompletion(FullParams params) {
4482 synchronized (params.latch) {
4483 while (params.latch.get() == false) {
4484 try {
4485 params.latch.wait();
4486 } catch (InterruptedException e) { /* never interrupted */ }
4487 }
4488 }
4489 }
4490
4491 void signalFullBackupRestoreCompletion(FullParams params) {
4492 synchronized (params.latch) {
4493 params.latch.set(true);
4494 params.latch.notifyAll();
4495 }
4496 }
4497
4498 // Confirm that the previously-requested full backup/restore operation can proceed. This
4499 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07004500 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07004501 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07004502 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004503 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
4504 + " allow=" + allow);
4505
4506 // TODO: possibly require not just this signature-only permission, but even
4507 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07004508 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07004509
4510 long oldId = Binder.clearCallingIdentity();
4511 try {
4512
4513 FullParams params;
4514 synchronized (mFullConfirmations) {
4515 params = mFullConfirmations.get(token);
4516 if (params != null) {
4517 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
4518 mFullConfirmations.delete(token);
4519
4520 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004521 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07004522 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07004523 : MSG_RUN_FULL_RESTORE;
4524
Christopher Tate728a1c42011-07-28 18:03:03 -07004525 params.observer = observer;
4526 params.curPassword = curPassword;
4527 params.encryptPassword = encPpassword;
4528
Christopher Tate75a99702011-05-18 16:28:19 -07004529 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07004530 mWakelock.acquire();
4531 Message msg = mBackupHandler.obtainMessage(verb, params);
4532 mBackupHandler.sendMessage(msg);
4533 } else {
4534 Slog.w(TAG, "User rejected full backup/restore operation");
4535 // indicate completion without having actually transferred any data
4536 signalFullBackupRestoreCompletion(params);
4537 }
4538 } else {
4539 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
4540 }
4541 }
4542 } finally {
4543 Binder.restoreCallingIdentity(oldId);
4544 }
4545 }
4546
Christopher Tate8031a3d2009-07-06 16:36:05 -07004547 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07004548 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004549 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004550 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004551
Joe Onorato8a9b2202010-02-26 18:56:32 -08004552 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004553
Christopher Tate6ef58a12009-06-29 14:56:28 -07004554 boolean wasEnabled = mEnabled;
4555 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07004556 Settings.Secure.putInt(mContext.getContentResolver(),
4557 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07004558 mEnabled = enable;
4559 }
4560
Christopher Tate49401dd2009-07-01 12:34:29 -07004561 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07004562 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07004563 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07004564 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07004565 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004566 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004567 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004568
Christopher Tateb6787f22009-07-02 17:40:45 -07004569 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004570
4571 // This also constitutes an opt-out, so we wipe any data for
4572 // this device from the backend. We start that process with
4573 // an alarm in order to guarantee wakelock states.
4574 if (wasEnabled && mProvisioned) {
4575 // NOTE: we currently flush every registered transport, not just
4576 // the currently-active one.
4577 HashSet<String> allTransports;
4578 synchronized (mTransports) {
4579 allTransports = new HashSet<String>(mTransports.keySet());
4580 }
4581 // build the set of transports for which we are posting an init
4582 for (String transport : allTransports) {
4583 recordInitPendingLocked(true, transport);
4584 }
4585 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
4586 mRunInitIntent);
4587 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004588 }
4589 }
Christopher Tate49401dd2009-07-01 12:34:29 -07004590 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004591
Christopher Tatecce9da52010-02-03 15:11:15 -08004592 // Enable/disable automatic restore of app data at install time
4593 public void setAutoRestore(boolean doAutoRestore) {
4594 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004595 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08004596
Joe Onorato8a9b2202010-02-26 18:56:32 -08004597 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08004598
4599 synchronized (this) {
4600 Settings.Secure.putInt(mContext.getContentResolver(),
4601 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
4602 mAutoRestore = doAutoRestore;
4603 }
4604 }
4605
Christopher Tate8031a3d2009-07-06 16:36:05 -07004606 // Mark the backup service as having been provisioned
4607 public void setBackupProvisioned(boolean available) {
4608 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4609 "setBackupProvisioned");
4610
4611 boolean wasProvisioned = mProvisioned;
4612 synchronized (this) {
4613 Settings.Secure.putInt(mContext.getContentResolver(),
4614 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
4615 mProvisioned = available;
4616 }
4617
4618 synchronized (mQueueLock) {
4619 if (available && !wasProvisioned && mEnabled) {
4620 // we're now good to go, so start the backup alarms
4621 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
4622 } else if (!available) {
4623 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004624 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07004625 mAlarmManager.cancel(mRunBackupIntent);
4626 }
4627 }
4628 }
4629
4630 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07004631 // We used to use setInexactRepeating(), but that may be linked to
4632 // backups running at :00 more often than not, creating load spikes.
4633 // Schedule at an exact time for now, and also add a bit of "fuzz".
4634
4635 Random random = new Random();
4636 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
4637 random.nextInt(FUZZ_MILLIS);
4638 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
4639 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07004640 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07004641 }
4642
Christopher Tate6ef58a12009-06-29 14:56:28 -07004643 // Report whether the backup mechanism is currently enabled
4644 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04004645 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004646 return mEnabled; // no need to synchronize just to read it
4647 }
4648
Christopher Tate91717492009-06-26 21:07:13 -07004649 // Report the name of the currently active transport
4650 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04004651 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004652 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07004653 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07004654 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07004655 }
4656
Christopher Tate91717492009-06-26 21:07:13 -07004657 // Report all known, available backup transports
4658 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07004659 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07004660
Christopher Tate91717492009-06-26 21:07:13 -07004661 String[] list = null;
4662 ArrayList<String> known = new ArrayList<String>();
4663 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
4664 if (entry.getValue() != null) {
4665 known.add(entry.getKey());
4666 }
4667 }
4668
4669 if (known.size() > 0) {
4670 list = new String[known.size()];
4671 known.toArray(list);
4672 }
4673 return list;
4674 }
4675
4676 // Select which transport to use for the next backup operation. If the given
4677 // name is not one of the available transports, no action is taken and the method
4678 // returns null.
4679 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04004680 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07004681
4682 synchronized (mTransports) {
4683 String prevTransport = null;
4684 if (mTransports.get(transport) != null) {
4685 prevTransport = mCurrentTransport;
4686 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07004687 Settings.Secure.putString(mContext.getContentResolver(),
4688 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004689 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07004690 + " returning " + prevTransport);
4691 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004692 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07004693 }
4694 return prevTransport;
4695 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004696 }
4697
Christopher Tatef5e1c292010-12-08 18:40:26 -08004698 // Supply the configuration Intent for the given transport. If the name is not one
4699 // of the available transports, or if the transport does not supply any configuration
4700 // UI, the method returns null.
4701 public Intent getConfigurationIntent(String transportName) {
4702 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4703 "getConfigurationIntent");
4704
4705 synchronized (mTransports) {
4706 final IBackupTransport transport = mTransports.get(transportName);
4707 if (transport != null) {
4708 try {
4709 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07004710 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08004711 + intent);
4712 return intent;
4713 } catch (RemoteException e) {
4714 /* fall through to return null */
4715 }
4716 }
4717 }
4718
4719 return null;
4720 }
4721
4722 // Supply the configuration summary string for the given transport. If the name is
4723 // not one of the available transports, or if the transport does not supply any
4724 // summary / destination string, the method can return null.
4725 //
4726 // This string is used VERBATIM as the summary text of the relevant Settings item!
4727 public String getDestinationString(String transportName) {
4728 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004729 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08004730
4731 synchronized (mTransports) {
4732 final IBackupTransport transport = mTransports.get(transportName);
4733 if (transport != null) {
4734 try {
4735 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07004736 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08004737 return text;
4738 } catch (RemoteException e) {
4739 /* fall through to return null */
4740 }
4741 }
4742 }
4743
4744 return null;
4745 }
4746
Christopher Tate043dadc2009-06-02 16:11:00 -07004747 // Callback: a requested backup agent has been instantiated. This should only
4748 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004749 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07004750 synchronized(mAgentConnectLock) {
4751 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004752 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07004753 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
4754 mConnectedAgent = agent;
4755 mConnecting = false;
4756 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004757 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004758 + " claiming agent connected");
4759 }
4760 mAgentConnectLock.notifyAll();
4761 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004762 }
4763
4764 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
4765 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07004766 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004767 public void agentDisconnected(String packageName) {
4768 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07004769 synchronized(mAgentConnectLock) {
4770 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
4771 mConnectedAgent = null;
4772 mConnecting = false;
4773 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004774 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004775 + " claiming agent disconnected");
4776 }
4777 mAgentConnectLock.notifyAll();
4778 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004779 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004780
Christopher Tate1bb69062010-02-19 17:02:12 -08004781 // An application being installed will need a restore pass, then the Package Manager
4782 // will need to be told when the restore is finished.
4783 public void restoreAtInstall(String packageName, int token) {
4784 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004785 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08004786 + " attemping install-time restore");
4787 return;
4788 }
4789
4790 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004791 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08004792 + " token=" + Integer.toHexString(token));
4793
Christopher Tatef0872722010-02-25 15:22:48 -08004794 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08004795 // okay, we're going to attempt a restore of this package from this restore set.
4796 // The eventual message back into the Package Manager to run the post-install
4797 // steps for 'token' will be issued from the restore handling code.
4798
4799 // We can use a synthetic PackageInfo here because:
4800 // 1. We know it's valid, since the Package Manager supplied the name
4801 // 2. Only the packageName field will be used by the restore code
4802 PackageInfo pkg = new PackageInfo();
4803 pkg.packageName = packageName;
4804
4805 mWakelock.acquire();
4806 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
4807 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07004808 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08004809 mBackupHandler.sendMessage(msg);
4810 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08004811 // Auto-restore disabled or no way to attempt a restore; just tell the Package
4812 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004813 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08004814 try {
4815 mPackageManagerBinder.finishPackageInstall(token);
4816 } catch (RemoteException e) { /* can't happen */ }
4817 }
4818 }
4819
Christopher Tate8c850b72009-06-07 19:33:20 -07004820 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08004821 public IRestoreSession beginRestoreSession(String packageName, String transport) {
4822 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
4823 + " transport=" + transport);
4824
4825 boolean needPermission = true;
4826 if (transport == null) {
4827 transport = mCurrentTransport;
4828
4829 if (packageName != null) {
4830 PackageInfo app = null;
4831 try {
4832 app = mPackageManager.getPackageInfo(packageName, 0);
4833 } catch (NameNotFoundException nnf) {
4834 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
4835 throw new IllegalArgumentException("Package " + packageName + " not found");
4836 }
4837
4838 if (app.applicationInfo.uid == Binder.getCallingUid()) {
4839 // So: using the current active transport, and the caller has asked
4840 // that its own package will be restored. In this narrow use case
4841 // we do not require the caller to hold the permission.
4842 needPermission = false;
4843 }
4844 }
4845 }
4846
4847 if (needPermission) {
4848 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4849 "beginRestoreSession");
4850 } else {
4851 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
4852 }
Christopher Tatef68eb502009-06-16 11:02:01 -07004853
4854 synchronized(this) {
4855 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004856 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07004857 return null;
4858 }
Chris Tate44ab8452010-11-16 15:10:49 -08004859 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08004860 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07004861 }
4862 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07004863 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004864
Christopher Tate73a3cb32010-12-13 18:27:26 -08004865 void clearRestoreSession(ActiveRestoreSession currentSession) {
4866 synchronized(this) {
4867 if (currentSession != mActiveRestoreSession) {
4868 Slog.e(TAG, "ending non-current restore session");
4869 } else {
4870 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
4871 mActiveRestoreSession = null;
4872 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4873 }
4874 }
4875 }
4876
Christopher Tate44a27902010-01-27 17:15:49 -08004877 // Note that a currently-active backup agent has notified us that it has
4878 // completed the given outstanding asynchronous backup/restore operation.
4879 public void opComplete(int token) {
4880 synchronized (mCurrentOpLock) {
Christopher Tatec58efa62011-08-01 19:20:14 -07004881 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08004882 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
4883 mCurrentOpLock.notifyAll();
4884 }
4885 }
4886
Christopher Tate9b3905c2009-06-08 15:24:01 -07004887 // ----- Restore session -----
4888
Christopher Tate80202c82010-01-25 19:37:47 -08004889 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07004890 private static final String TAG = "RestoreSession";
4891
Chris Tate44ab8452010-11-16 15:10:49 -08004892 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004893 private IBackupTransport mRestoreTransport = null;
4894 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08004895 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004896
Chris Tate44ab8452010-11-16 15:10:49 -08004897 ActiveRestoreSession(String packageName, String transport) {
4898 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07004899 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07004900 }
4901
4902 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07004903 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04004904 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004905 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004906 if (observer == null) {
4907 throw new IllegalArgumentException("Observer must not be null");
4908 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004909
Christopher Tate73a3cb32010-12-13 18:27:26 -08004910 if (mEnded) {
4911 throw new IllegalStateException("Restore session already ended");
4912 }
4913
Christopher Tate1bb69062010-02-19 17:02:12 -08004914 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07004915 try {
Christopher Tate43383042009-07-13 15:17:13 -07004916 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004917 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004918 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07004919 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07004920 // spin off the transport request to our service thread
4921 mWakelock.acquire();
4922 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
4923 new RestoreGetSetsParams(mRestoreTransport, this, observer));
4924 mBackupHandler.sendMessage(msg);
4925 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07004926 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004927 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07004928 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08004929 } finally {
4930 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07004931 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07004932 }
4933
Christopher Tate84725812010-02-04 15:52:40 -08004934 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07004935 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4936 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004937
Chris Tate44ab8452010-11-16 15:10:49 -08004938 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07004939 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004940
Christopher Tate73a3cb32010-12-13 18:27:26 -08004941 if (mEnded) {
4942 throw new IllegalStateException("Restore session already ended");
4943 }
4944
Dan Egnor0084da52009-07-29 12:57:16 -07004945 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08004946 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
4947 return -1;
4948 }
4949
4950 if (mPackageName != null) {
4951 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07004952 return -1;
4953 }
4954
Christopher Tate21ab6a52009-09-24 18:01:46 -07004955 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004956 for (int i = 0; i < mRestoreSets.length; i++) {
4957 if (token == mRestoreSets[i].token) {
4958 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07004959 mWakelock.acquire();
4960 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07004961 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07004962 mBackupHandler.sendMessage(msg);
4963 Binder.restoreCallingIdentity(oldId);
4964 return 0;
4965 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004966 }
4967 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07004968
Joe Onorato8a9b2202010-02-26 18:56:32 -08004969 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07004970 return -1;
4971 }
4972
Christopher Tate284f1bb2011-07-07 14:31:18 -07004973 public synchronized int restoreSome(long token, IRestoreObserver observer,
4974 String[] packages) {
4975 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4976 "performRestore");
4977
4978 if (DEBUG) {
4979 StringBuilder b = new StringBuilder(128);
4980 b.append("restoreSome token=");
4981 b.append(Long.toHexString(token));
4982 b.append(" observer=");
4983 b.append(observer.toString());
4984 b.append(" packages=");
4985 if (packages == null) {
4986 b.append("null");
4987 } else {
4988 b.append('{');
4989 boolean first = true;
4990 for (String s : packages) {
4991 if (!first) {
4992 b.append(", ");
4993 } else first = false;
4994 b.append(s);
4995 }
4996 b.append('}');
4997 }
4998 Slog.d(TAG, b.toString());
4999 }
5000
5001 if (mEnded) {
5002 throw new IllegalStateException("Restore session already ended");
5003 }
5004
5005 if (mRestoreTransport == null || mRestoreSets == null) {
5006 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5007 return -1;
5008 }
5009
5010 if (mPackageName != null) {
5011 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5012 return -1;
5013 }
5014
5015 synchronized (mQueueLock) {
5016 for (int i = 0; i < mRestoreSets.length; i++) {
5017 if (token == mRestoreSets[i].token) {
5018 long oldId = Binder.clearCallingIdentity();
5019 mWakelock.acquire();
5020 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5021 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5022 packages, true);
5023 mBackupHandler.sendMessage(msg);
5024 Binder.restoreCallingIdentity(oldId);
5025 return 0;
5026 }
5027 }
5028 }
5029
5030 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5031 return -1;
5032 }
5033
Christopher Tate84725812010-02-04 15:52:40 -08005034 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005035 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005036
Christopher Tate73a3cb32010-12-13 18:27:26 -08005037 if (mEnded) {
5038 throw new IllegalStateException("Restore session already ended");
5039 }
5040
Chris Tate44ab8452010-11-16 15:10:49 -08005041 if (mPackageName != null) {
5042 if (! mPackageName.equals(packageName)) {
5043 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5044 + " on session for package " + mPackageName);
5045 return -1;
5046 }
5047 }
5048
Christopher Tate84725812010-02-04 15:52:40 -08005049 PackageInfo app = null;
5050 try {
5051 app = mPackageManager.getPackageInfo(packageName, 0);
5052 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005053 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005054 return -1;
5055 }
5056
5057 // If the caller is not privileged and is not coming from the target
5058 // app's uid, throw a permission exception back to the caller.
5059 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5060 Binder.getCallingPid(), Binder.getCallingUid());
5061 if ((perm == PackageManager.PERMISSION_DENIED) &&
5062 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005063 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005064 + " or calling uid=" + Binder.getCallingUid());
5065 throw new SecurityException("No permission to restore other packages");
5066 }
5067
Christopher Tate7d411a32010-02-26 11:27:08 -08005068 // If the package has no backup agent, we obviously cannot proceed
5069 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005070 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005071 return -1;
5072 }
5073
Christopher Tate84725812010-02-04 15:52:40 -08005074 // So far so good; we're allowed to try to restore this package. Now
5075 // check whether there is data for it in the current dataset, falling back
5076 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005077 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005078
5079 // If we didn't come up with a place to look -- no ancestral dataset and
5080 // the app has never been backed up from this device -- there's nothing
5081 // to do but return failure.
5082 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005083 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005084 return -1;
5085 }
5086
5087 // Ready to go: enqueue the restore request and claim success
5088 long oldId = Binder.clearCallingIdentity();
5089 mWakelock.acquire();
5090 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005091 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005092 mBackupHandler.sendMessage(msg);
5093 Binder.restoreCallingIdentity(oldId);
5094 return 0;
5095 }
5096
Christopher Tate73a3cb32010-12-13 18:27:26 -08005097 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5098 class EndRestoreRunnable implements Runnable {
5099 BackupManagerService mBackupManager;
5100 ActiveRestoreSession mSession;
5101
5102 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5103 mBackupManager = manager;
5104 mSession = session;
5105 }
5106
5107 public void run() {
5108 // clean up the session's bookkeeping
5109 synchronized (mSession) {
5110 try {
5111 if (mSession.mRestoreTransport != null) {
5112 mSession.mRestoreTransport.finishRestore();
5113 }
5114 } catch (Exception e) {
5115 Slog.e(TAG, "Error in finishRestore", e);
5116 } finally {
5117 mSession.mRestoreTransport = null;
5118 mSession.mEnded = true;
5119 }
5120 }
5121
5122 // clean up the BackupManagerService side of the bookkeeping
5123 // and cancel any pending timeout message
5124 mBackupManager.clearRestoreSession(mSession);
5125 }
5126 }
5127
Dan Egnor0084da52009-07-29 12:57:16 -07005128 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005129 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005130
Christopher Tate73a3cb32010-12-13 18:27:26 -08005131 if (mEnded) {
5132 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005133 }
5134
Christopher Tate73a3cb32010-12-13 18:27:26 -08005135 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005136 }
5137 }
5138
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005139 @Override
5140 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005141 long identityToken = Binder.clearCallingIdentity();
5142 try {
5143 dumpInternal(pw);
5144 } finally {
5145 Binder.restoreCallingIdentity(identityToken);
5146 }
5147 }
5148
5149 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005150 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005151 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005152 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005153 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005154 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07005155 pw.println("Last backup pass: " + mLastBackupPass
5156 + " (now = " + System.currentTimeMillis() + ')');
5157 pw.println(" next scheduled: " + mNextBackupPass);
5158
Christopher Tate91717492009-06-26 21:07:13 -07005159 pw.println("Available transports:");
5160 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005161 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5162 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005163 IBackupTransport transport = getTransport(t);
5164 File dir = new File(mBaseStateDir, transport.transportDirName());
5165 pw.println(" destination: " + transport.currentDestinationString());
5166 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005167 for (File f : dir.listFiles()) {
5168 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5169 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005170 } catch (Exception e) {
5171 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005172 pw.println(" Error: " + e);
5173 }
Christopher Tate91717492009-06-26 21:07:13 -07005174 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005175
5176 pw.println("Pending init: " + mPendingInits.size());
5177 for (String s : mPendingInits) {
5178 pw.println(" " + s);
5179 }
5180
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005181 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005182 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005183 for (int i=0; i<N; i++) {
5184 int uid = mBackupParticipants.keyAt(i);
5185 pw.print(" uid: ");
5186 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005187 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5188 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005189 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005190 }
5191 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005192
Christopher Tateb49ceb32010-02-08 16:22:24 -08005193 pw.println("Ancestral packages: "
5194 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005195 if (mAncestralPackages != null) {
5196 for (String pkg : mAncestralPackages) {
5197 pw.println(" " + pkg);
5198 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005199 }
5200
Christopher Tate73e02522009-07-15 14:18:26 -07005201 pw.println("Ever backed up: " + mEverStoredApps.size());
5202 for (String pkg : mEverStoredApps) {
5203 pw.println(" " + pkg);
5204 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005205
5206 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005207 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005208 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005209 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005210 }
5211 }
Christopher Tate487529a2009-04-29 14:03:25 -07005212}