blob: 0ac490d0468eaaed7caf96eb485932f2152e07ad [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 Tate8e294d42011-08-31 20:37:12 -0700132 private static final boolean MORE_DEBUG = true;
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
Christopher Tate8e294d42011-08-31 20:37:12 -0700166 // backup task state machine tick
167 static final int MSG_BACKUP_RESTORE_STEP = 20;
168 static final int MSG_OP_COMPLETE = 21;
169
Christopher Tatec7b31e32009-06-10 15:49:30 -0700170 // Timeout interval for deciding that a bind or clear-data has taken too long
171 static final long TIMEOUT_INTERVAL = 10 * 1000;
172
Christopher Tate44a27902010-01-27 17:15:49 -0800173 // Timeout intervals for agent backup & restore operations
174 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700175 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700176 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800177 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
178
Christopher Tate2efd2db2011-07-19 16:32:49 -0700179 // User confirmation timeout for a full backup/restore operation. It's this long in
180 // order to give them time to enter the backup password.
181 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700182
Christopher Tate487529a2009-04-29 14:03:25 -0700183 private Context mContext;
184 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800185 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700186 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700187 private PowerManager mPowerManager;
188 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800189 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700190
Christopher Tate73e02522009-07-15 14:18:26 -0700191 boolean mEnabled; // access to this is synchronized on 'this'
192 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800193 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700194 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800195 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
196 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700197 PendingIntent mRunBackupIntent, mRunInitIntent;
198 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700199 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700200 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700201 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700202 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700203 class BackupRequest {
Christopher Tatecc55f812011-08-16 16:06:53 -0700204 public String packageName;
Christopher Tateaa088442009-06-16 18:25:46 -0700205
Christopher Tatecc55f812011-08-16 16:06:53 -0700206 BackupRequest(String pkgName) {
207 packageName = pkgName;
Christopher Tate46758122009-05-06 11:22:00 -0700208 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700209
210 public String toString() {
Christopher Tatecc55f812011-08-16 16:06:53 -0700211 return "BackupRequest{pkg=" + packageName + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700212 }
Christopher Tate46758122009-05-06 11:22:00 -0700213 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800214 // Backups that we haven't started yet. Keys are package names.
215 HashMap<String,BackupRequest> mPendingBackups
216 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700217
218 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700219 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700220
221 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700222 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700223
Christopher Tate043dadc2009-06-02 16:11:00 -0700224 // The thread performing the sequence of queued backups binds to each app's agent
225 // in succession. Bind notifications are asynchronously delivered through the
226 // Activity Manager; use this lock object to signal when a requested binding has
227 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700228 final Object mAgentConnectLock = new Object();
229 IBackupAgent mConnectedAgent;
230 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700231 volatile long mLastBackupPass;
232 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700233
Christopher Tate55f931a2009-09-29 17:17:34 -0700234 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700235 final Object mClearDataLock = new Object();
236 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700237
Christopher Tate91717492009-06-26 21:07:13 -0700238 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700239 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700240 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700241 String mCurrentTransport;
242 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800243 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700244
Christopher Tate2d449afe2010-03-29 19:14:24 -0700245 class RestoreGetSetsParams {
246 public IBackupTransport transport;
247 public ActiveRestoreSession session;
248 public IRestoreObserver observer;
249
250 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
251 IRestoreObserver _observer) {
252 transport = _transport;
253 session = _session;
254 observer = _observer;
255 }
256 }
257
Christopher Tate73e02522009-07-15 14:18:26 -0700258 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700259 public IBackupTransport transport;
260 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700261 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800262 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800263 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700264 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700265 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800266
267 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700268 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800269 transport = _transport;
270 observer = _obs;
271 token = _token;
272 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800273 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700274 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700275 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800276 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700277
Chris Tate249345b2010-10-29 12:57:04 -0700278 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
279 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700280 transport = _transport;
281 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700282 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800283 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800284 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700285 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700286 filterSet = null;
287 }
288
289 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
290 String[] _filterSet, boolean _needFullBackup) {
291 transport = _transport;
292 observer = _obs;
293 token = _token;
294 pkgInfo = null;
295 pmToken = 0;
296 needFullBackup = _needFullBackup;
297 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700298 }
299 }
300
Christopher Tate73e02522009-07-15 14:18:26 -0700301 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700302 public IBackupTransport transport;
303 public PackageInfo packageInfo;
304
305 ClearParams(IBackupTransport _transport, PackageInfo _info) {
306 transport = _transport;
307 packageInfo = _info;
308 }
309 }
310
Christopher Tate4a627c72011-04-01 14:43:32 -0700311 class FullParams {
312 public ParcelFileDescriptor fd;
313 public final AtomicBoolean latch;
314 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700315 public String curPassword; // filled in by the confirmation step
316 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700317
318 FullParams() {
319 latch = new AtomicBoolean(false);
320 }
321 }
322
323 class FullBackupParams extends FullParams {
324 public boolean includeApks;
325 public boolean includeShared;
326 public boolean allApps;
327 public String[] packages;
328
329 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
330 boolean doAllApps, String[] pkgList) {
331 fd = output;
332 includeApks = saveApks;
333 includeShared = saveShared;
334 allApps = doAllApps;
335 packages = pkgList;
336 }
337 }
338
339 class FullRestoreParams extends FullParams {
340 FullRestoreParams(ParcelFileDescriptor input) {
341 fd = input;
342 }
343 }
344
Christopher Tate44a27902010-01-27 17:15:49 -0800345 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
346 // token is the index of the entry in the pending-operations list.
347 static final int OP_PENDING = 0;
348 static final int OP_ACKNOWLEDGED = 1;
349 static final int OP_TIMEOUT = -1;
350
Christopher Tate8e294d42011-08-31 20:37:12 -0700351 class Operation {
352 public int state;
353 public BackupRestoreTask callback;
354
355 Operation(int initialState, BackupRestoreTask callbackObj) {
356 state = initialState;
357 callback = callbackObj;
358 }
359 }
360 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
Christopher Tate44a27902010-01-27 17:15:49 -0800361 final Object mCurrentOpLock = new Object();
362 final Random mTokenGenerator = new Random();
363
Christopher Tate4a627c72011-04-01 14:43:32 -0700364 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
365
Christopher Tate5cb400b2009-06-25 16:03:14 -0700366 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700367 File mBaseStateDir;
368 File mDataDir;
369 File mJournalDir;
370 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700371
Christopher Tate2efd2db2011-07-19 16:32:49 -0700372 // Backup password, if any, and the file where it's saved. What is stored is not the
373 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
374 // persisted) salt. Validation is performed by running the challenge text through the
375 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
376 // the saved hash string, then the challenge text matches the originally supplied
377 // password text.
378 private final SecureRandom mRng = new SecureRandom();
379 private String mPasswordHash;
380 private File mPasswordHashFile;
381 private byte[] mPasswordSalt;
382
383 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
384 static final int PBKDF2_HASH_ROUNDS = 10000;
385 static final int PBKDF2_KEY_SIZE = 256; // bits
386 static final int PBKDF2_SALT_SIZE = 512; // bits
387 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
388
Christopher Tate84725812010-02-04 15:52:40 -0800389 // Keep a log of all the apps we've ever backed up, and what the
390 // dataset tokens are for both the current backup dataset and
391 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700392 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700393 HashSet<String> mEverStoredApps = new HashSet<String>();
394
Christopher Tateb49ceb32010-02-08 16:22:24 -0800395 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800396 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800397 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800398 long mAncestralToken = 0;
399 long mCurrentToken = 0;
400
Christopher Tate4cc86e12009-09-21 19:36:51 -0700401 // Persistently track the need to do a full init
402 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
403 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700404
Christopher Tate4a627c72011-04-01 14:43:32 -0700405 // Utility: build a new random integer token
406 int generateToken() {
407 int token;
408 do {
409 synchronized (mTokenGenerator) {
410 token = mTokenGenerator.nextInt();
411 }
412 } while (token < 0);
413 return token;
414 }
415
Christopher Tate44a27902010-01-27 17:15:49 -0800416 // ----- Asynchronous backup/restore handler thread -----
417
418 private class BackupHandler extends Handler {
419 public BackupHandler(Looper looper) {
420 super(looper);
421 }
422
423 public void handleMessage(Message msg) {
424
425 switch (msg.what) {
426 case MSG_RUN_BACKUP:
427 {
428 mLastBackupPass = System.currentTimeMillis();
429 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
430
431 IBackupTransport transport = getTransport(mCurrentTransport);
432 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800433 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800434 mWakelock.release();
435 break;
436 }
437
438 // snapshot the pending-backup set and work on that
439 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800440 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800441 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800442 // Do we have any work to do? Construct the work queue
443 // then release the synchronization lock to actually run
444 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800445 if (mPendingBackups.size() > 0) {
446 for (BackupRequest b: mPendingBackups.values()) {
447 queue.add(b);
448 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800449 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800450 mPendingBackups.clear();
451
452 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800453 mJournal = null;
454
Christopher Tate44a27902010-01-27 17:15:49 -0800455 }
456 }
Christopher Tatec61da312010-02-05 10:41:27 -0800457
Christopher Tate8e294d42011-08-31 20:37:12 -0700458 // At this point, we have started a new journal file, and the old
459 // file identity is being passed to the backup processing task.
460 // When it completes successfully, that old journal file will be
461 // deleted. If we crash prior to that, the old journal is parsed
462 // at next boot and the journaled requests fulfilled.
Christopher Tatec61da312010-02-05 10:41:27 -0800463 if (queue.size() > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -0700464 // Spin up a backup state sequence and set it running
465 PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
466 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
467 sendMessage(pbtMessage);
Christopher Tatec61da312010-02-05 10:41:27 -0800468 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800469 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800470 mWakelock.release();
471 }
Christopher Tate44a27902010-01-27 17:15:49 -0800472 break;
473 }
474
Christopher Tate8e294d42011-08-31 20:37:12 -0700475 case MSG_BACKUP_RESTORE_STEP:
476 {
477 try {
478 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
479 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
480 task.execute();
481 } catch (ClassCastException e) {
482 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
483 }
484 break;
485 }
486
487 case MSG_OP_COMPLETE:
488 {
489 try {
490 BackupRestoreTask obj = (BackupRestoreTask) msg.obj;
491 obj.operationComplete();
492 } catch (ClassCastException e) {
493 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
494 }
495 break;
496 }
497
Christopher Tate44a27902010-01-27 17:15:49 -0800498 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700499 {
500 FullBackupParams params = (FullBackupParams)msg.obj;
501 (new PerformFullBackupTask(params.fd, params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700502 params.includeShared, params.curPassword, params.encryptPassword,
503 params.allApps, params.packages, params.latch)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800504 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700505 }
Christopher Tate44a27902010-01-27 17:15:49 -0800506
507 case MSG_RUN_RESTORE:
508 {
509 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800510 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800511 (new PerformRestoreTask(params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700512 params.token, params.pkgInfo, params.pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -0700513 params.needFullBackup, params.filterSet)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800514 break;
515 }
516
Christopher Tate75a99702011-05-18 16:28:19 -0700517 case MSG_RUN_FULL_RESTORE:
518 {
519 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tate728a1c42011-07-28 18:03:03 -0700520 (new PerformFullRestoreTask(params.fd, params.curPassword, params.encryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -0700521 params.observer, params.latch)).run();
Christopher Tate75a99702011-05-18 16:28:19 -0700522 break;
523 }
524
Christopher Tate44a27902010-01-27 17:15:49 -0800525 case MSG_RUN_CLEAR:
526 {
527 ClearParams params = (ClearParams)msg.obj;
528 (new PerformClearTask(params.transport, params.packageInfo)).run();
529 break;
530 }
531
532 case MSG_RUN_INITIALIZE:
533 {
534 HashSet<String> queue;
535
536 // Snapshot the pending-init queue and work on that
537 synchronized (mQueueLock) {
538 queue = new HashSet<String>(mPendingInits);
539 mPendingInits.clear();
540 }
541
542 (new PerformInitializeTask(queue)).run();
543 break;
544 }
545
Christopher Tate2d449afe2010-03-29 19:14:24 -0700546 case MSG_RUN_GET_RESTORE_SETS:
547 {
548 // Like other async operations, this is entered with the wakelock held
549 RestoreSet[] sets = null;
550 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
551 try {
552 sets = params.transport.getAvailableRestoreSets();
553 // cache the result in the active session
554 synchronized (params.session) {
555 params.session.mRestoreSets = sets;
556 }
557 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
558 } catch (Exception e) {
559 Slog.e(TAG, "Error from transport getting set list");
560 } finally {
561 if (params.observer != null) {
562 try {
563 params.observer.restoreSetsAvailable(sets);
564 } catch (RemoteException re) {
565 Slog.e(TAG, "Unable to report listing to observer");
566 } catch (Exception e) {
567 Slog.e(TAG, "Restore observer threw", e);
568 }
569 }
570
Christopher Tate2a935092011-03-03 17:30:32 -0800571 // Done: reset the session timeout clock
572 removeMessages(MSG_RESTORE_TIMEOUT);
573 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
574
Christopher Tate2d449afe2010-03-29 19:14:24 -0700575 mWakelock.release();
576 }
577 break;
578 }
579
Christopher Tate44a27902010-01-27 17:15:49 -0800580 case MSG_TIMEOUT:
581 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700582 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800583 break;
584 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800585
586 case MSG_RESTORE_TIMEOUT:
587 {
588 synchronized (BackupManagerService.this) {
589 if (mActiveRestoreSession != null) {
590 // Client app left the restore session dangling. We know that it
591 // can't be in the middle of an actual restore operation because
592 // those are executed serially on this same handler thread. Clean
593 // up now.
594 Slog.w(TAG, "Restore session timed out; aborting");
595 post(mActiveRestoreSession.new EndRestoreRunnable(
596 BackupManagerService.this, mActiveRestoreSession));
597 }
598 }
599 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700600
601 case MSG_FULL_CONFIRMATION_TIMEOUT:
602 {
603 synchronized (mFullConfirmations) {
604 FullParams params = mFullConfirmations.get(msg.arg1);
605 if (params != null) {
606 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
607
608 // Release the waiter; timeout == completion
609 signalFullBackupRestoreCompletion(params);
610
611 // Remove the token from the set
612 mFullConfirmations.delete(msg.arg1);
613
614 // Report a timeout to the observer, if any
615 if (params.observer != null) {
616 try {
617 params.observer.onTimeout();
618 } catch (RemoteException e) {
619 /* don't care if the app has gone away */
620 }
621 }
622 } else {
623 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
624 }
625 }
626 break;
627 }
Christopher Tate44a27902010-01-27 17:15:49 -0800628 }
629 }
630 }
631
632 // ----- Main service implementation -----
633
Christopher Tate487529a2009-04-29 14:03:25 -0700634 public BackupManagerService(Context context) {
635 mContext = context;
636 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700637 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700638 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700639
Christopher Tateb6787f22009-07-02 17:40:45 -0700640 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
641 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
642
Christopher Tate44a27902010-01-27 17:15:49 -0800643 mBackupManagerBinder = asInterface(asBinder());
644
645 // spin up the backup/restore handler thread
646 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
647 mHandlerThread.start();
648 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
649
Christopher Tate22b87872009-05-04 16:41:53 -0700650 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700651 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700652 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700653 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700654 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800655 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800656 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800657 // If Encrypted file systems is enabled or disabled, this call will return the
658 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600659 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800660 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700661 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700662
Christopher Tate2efd2db2011-07-19 16:32:49 -0700663 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
664 if (mPasswordHashFile.exists()) {
665 FileInputStream fin = null;
666 DataInputStream in = null;
667 try {
668 fin = new FileInputStream(mPasswordHashFile);
669 in = new DataInputStream(new BufferedInputStream(fin));
670 // integer length of the salt array, followed by the salt,
671 // then the hex pw hash string
672 int saltLen = in.readInt();
673 byte[] salt = new byte[saltLen];
674 in.readFully(salt);
675 mPasswordHash = in.readUTF();
676 mPasswordSalt = salt;
677 } catch (IOException e) {
678 Slog.e(TAG, "Unable to read saved backup pw hash");
679 } finally {
680 try {
681 if (in != null) in.close();
682 if (fin != null) fin.close();
683 } catch (IOException e) {
684 Slog.w(TAG, "Unable to close streams");
685 }
686 }
687 }
688
Christopher Tate4cc86e12009-09-21 19:36:51 -0700689 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700690 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700691 IntentFilter filter = new IntentFilter();
692 filter.addAction(RUN_BACKUP_ACTION);
693 context.registerReceiver(mRunBackupReceiver, filter,
694 android.Manifest.permission.BACKUP, null);
695
696 mRunInitReceiver = new RunInitializeReceiver();
697 filter = new IntentFilter();
698 filter.addAction(RUN_INITIALIZE_ACTION);
699 context.registerReceiver(mRunInitReceiver, filter,
700 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700701
702 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700703 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
704 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
705
Christopher Tate4cc86e12009-09-21 19:36:51 -0700706 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
707 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
708 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
709
Christopher Tatecde87f42009-06-12 12:55:53 -0700710 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700711 mJournalDir = new File(mBaseStateDir, "pending");
712 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700713 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700714
Christopher Tate73e02522009-07-15 14:18:26 -0700715 // Set up the various sorts of package tracking we do
716 initPackageTracking();
717
Christopher Tateabce4e82009-06-18 18:35:32 -0700718 // Build our mapping of uid to backup client services. This implicitly
719 // schedules a backup pass on the Package Manager metadata the first
720 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700721 synchronized (mBackupParticipants) {
722 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700723 }
724
Dan Egnor87a02bc2009-06-17 02:30:10 -0700725 // Set up our transport options and initialize the default transport
726 // TODO: Have transports register themselves somehow?
727 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700728 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700729 ComponentName localName = new ComponentName(context, LocalTransport.class);
730 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700731
Christopher Tate91717492009-06-26 21:07:13 -0700732 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700733 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
734 Settings.Secure.BACKUP_TRANSPORT);
735 if ("".equals(mCurrentTransport)) {
736 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700737 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800738 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700739
740 // Attach to the Google backup transport. When this comes up, it will set
741 // itself as the current transport because we explicitly reset mCurrentTransport
742 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700743 ComponentName transportComponent = new ComponentName("com.google.android.backup",
744 "com.google.android.backup.BackupTransportService");
745 try {
746 // If there's something out there that is supposed to be the Google
747 // backup transport, make sure it's legitimately part of the OS build
748 // and not an app lying about its package name.
749 ApplicationInfo info = mPackageManager.getApplicationInfo(
750 transportComponent.getPackageName(), 0);
751 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
752 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
753 Intent intent = new Intent().setComponent(transportComponent);
754 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
755 } else {
756 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
757 }
758 } catch (PackageManager.NameNotFoundException nnf) {
759 // No such package? No binding.
760 if (DEBUG) Slog.v(TAG, "Google transport not present");
761 }
Christopher Tateaa088442009-06-16 18:25:46 -0700762
Christopher Tatecde87f42009-06-12 12:55:53 -0700763 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700764 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700765 parseLeftoverJournals();
766
Christopher Tateb6787f22009-07-02 17:40:45 -0700767 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700768 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700769
770 // Start the backup passes going
771 setBackupEnabled(areEnabled);
772 }
773
774 private class RunBackupReceiver extends BroadcastReceiver {
775 public void onReceive(Context context, Intent intent) {
776 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700777 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700778 if (mPendingInits.size() > 0) {
779 // If there are pending init operations, we process those
780 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800781 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700782 try {
783 mAlarmManager.cancel(mRunInitIntent);
784 mRunInitIntent.send();
785 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800786 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700787 // can't really do more than bail here
788 }
789 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800790 // Don't run backups now if we're disabled or not yet
791 // fully set up.
792 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800793 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700794
795 // Acquire the wakelock and pass it to the backup thread. it will
796 // be released once backup concludes.
797 mWakelock.acquire();
798
799 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
800 mBackupHandler.sendMessage(msg);
801 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800802 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700803 }
804 }
805 }
806 }
807 }
808 }
809
810 private class RunInitializeReceiver extends BroadcastReceiver {
811 public void onReceive(Context context, Intent intent) {
812 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
813 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800814 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700815
816 // Acquire the wakelock and pass it to the init thread. it will
817 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700818 mWakelock.acquire();
819
Christopher Tate4cc86e12009-09-21 19:36:51 -0700820 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700821 mBackupHandler.sendMessage(msg);
822 }
823 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700824 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700825 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700826
Christopher Tate73e02522009-07-15 14:18:26 -0700827 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800828 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700829
Christopher Tate84725812010-02-04 15:52:40 -0800830 // Remember our ancestral dataset
831 mTokenFile = new File(mBaseStateDir, "ancestral");
832 try {
833 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800834 int version = tf.readInt();
835 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
836 mAncestralToken = tf.readLong();
837 mCurrentToken = tf.readLong();
838
839 int numPackages = tf.readInt();
840 if (numPackages >= 0) {
841 mAncestralPackages = new HashSet<String>();
842 for (int i = 0; i < numPackages; i++) {
843 String pkgName = tf.readUTF();
844 mAncestralPackages.add(pkgName);
845 }
846 }
847 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800848 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800849 } catch (FileNotFoundException fnf) {
850 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800851 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800852 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800853 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800854 }
855
Christopher Tatee97e8072009-07-15 16:45:50 -0700856 // Keep a log of what apps we've ever backed up. Because we might have
857 // rebooted in the middle of an operation that was removing something from
858 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700859 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700860 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700861
Christopher Tatee97e8072009-07-15 16:45:50 -0700862 // If we were in the middle of removing something from the ever-backed-up
863 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700864 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700865 if (tempProcessedFile.exists()) {
866 tempProcessedFile.delete();
867 }
868
Dan Egnor852f8e42009-09-30 11:20:45 -0700869 // If there are previous contents, parse them out then start a new
870 // file to continue the recordkeeping.
871 if (mEverStored.exists()) {
872 RandomAccessFile temp = null;
873 RandomAccessFile in = null;
874
875 try {
876 temp = new RandomAccessFile(tempProcessedFile, "rws");
877 in = new RandomAccessFile(mEverStored, "r");
878
879 while (true) {
880 PackageInfo info;
881 String pkg = in.readUTF();
882 try {
883 info = mPackageManager.getPackageInfo(pkg, 0);
884 mEverStoredApps.add(pkg);
885 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700886 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700887 } catch (NameNotFoundException e) {
888 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700889 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700890 }
891 }
892 } catch (EOFException e) {
893 // Once we've rewritten the backup history log, atomically replace the
894 // old one with the new one then reopen the file for continuing use.
895 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800896 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700897 }
898 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800899 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700900 } finally {
901 try { if (temp != null) temp.close(); } catch (IOException e) {}
902 try { if (in != null) in.close(); } catch (IOException e) {}
903 }
904 }
905
Christopher Tate73e02522009-07-15 14:18:26 -0700906 // Register for broadcasts about package install, etc., so we can
907 // update the provider list.
908 IntentFilter filter = new IntentFilter();
909 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
910 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Christopher Tatecc55f812011-08-16 16:06:53 -0700911 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Christopher Tate73e02522009-07-15 14:18:26 -0700912 filter.addDataScheme("package");
913 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800914 // Register for events related to sdcard installation.
915 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800916 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
917 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800918 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700919 }
920
Christopher Tatecde87f42009-06-12 12:55:53 -0700921 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700922 for (File f : mJournalDir.listFiles()) {
923 if (mJournal == null || f.compareTo(mJournal) != 0) {
924 // This isn't the current journal, so it must be a leftover. Read
925 // out the package names mentioned there and schedule them for
926 // backup.
927 RandomAccessFile in = null;
928 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400929 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700930 in = new RandomAccessFile(f, "r");
931 while (true) {
932 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400933 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700934 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700935 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700936 } catch (EOFException e) {
937 // no more data; we're done
938 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800939 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700940 } finally {
941 // close/delete the file
942 try { if (in != null) in.close(); } catch (IOException e) {}
943 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700944 }
945 }
946 }
947 }
948
Christopher Tate2efd2db2011-07-19 16:32:49 -0700949 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
950 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
951 }
952
953 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
954 try {
955 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
956 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
957 return keyFactory.generateSecret(ks);
958 } catch (InvalidKeySpecException e) {
959 Slog.e(TAG, "Invalid key spec for PBKDF2!");
960 } catch (NoSuchAlgorithmException e) {
961 Slog.e(TAG, "PBKDF2 unavailable!");
962 }
963 return null;
964 }
965
966 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
967 SecretKey key = buildPasswordKey(pw, salt, rounds);
968 if (key != null) {
969 return byteArrayToHex(key.getEncoded());
970 }
971 return null;
972 }
973
974 private String byteArrayToHex(byte[] data) {
975 StringBuilder buf = new StringBuilder(data.length * 2);
976 for (int i = 0; i < data.length; i++) {
977 buf.append(Byte.toHexString(data[i], true));
978 }
979 return buf.toString();
980 }
981
982 private byte[] hexToByteArray(String digits) {
983 final int bytes = digits.length() / 2;
984 if (2*bytes != digits.length()) {
985 throw new IllegalArgumentException("Hex string must have an even number of digits");
986 }
987
988 byte[] result = new byte[bytes];
989 for (int i = 0; i < digits.length(); i += 2) {
990 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
991 }
992 return result;
993 }
994
995 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
996 char[] mkAsChar = new char[pwBytes.length];
997 for (int i = 0; i < pwBytes.length; i++) {
998 mkAsChar[i] = (char) pwBytes[i];
999 }
1000
1001 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1002 return checksum.getEncoded();
1003 }
1004
1005 // Used for generating random salts or passwords
1006 private byte[] randomBytes(int bits) {
1007 byte[] array = new byte[bits / 8];
1008 mRng.nextBytes(array);
1009 return array;
1010 }
1011
1012 // Backup password management
1013 boolean passwordMatchesSaved(String candidatePw, int rounds) {
1014 if (mPasswordHash == null) {
1015 // no current password case -- require that 'currentPw' be null or empty
1016 if (candidatePw == null || "".equals(candidatePw)) {
1017 return true;
1018 } // else the non-empty candidate does not match the empty stored pw
1019 } else {
1020 // hash the stated current pw and compare to the stored one
1021 if (candidatePw != null && candidatePw.length() > 0) {
1022 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1023 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1024 // candidate hash matches the stored hash -- the password matches
1025 return true;
1026 }
1027 } // else the stored pw is nonempty but the candidate is empty; no match
1028 }
1029 return false;
1030 }
1031
1032 @Override
1033 public boolean setBackupPassword(String currentPw, String newPw) {
1034 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1035 "setBackupPassword");
1036
1037 // If the supplied pw doesn't hash to the the saved one, fail
1038 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1039 return false;
1040 }
1041
1042 // Clearing the password is okay
1043 if (newPw == null || newPw.isEmpty()) {
1044 if (mPasswordHashFile.exists()) {
1045 if (!mPasswordHashFile.delete()) {
1046 // Unable to delete the old pw file, so fail
1047 Slog.e(TAG, "Unable to clear backup password");
1048 return false;
1049 }
1050 }
1051 mPasswordHash = null;
1052 mPasswordSalt = null;
1053 return true;
1054 }
1055
1056 try {
1057 // Okay, build the hash of the new backup password
1058 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1059 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1060
1061 OutputStream pwf = null, buffer = null;
1062 DataOutputStream out = null;
1063 try {
1064 pwf = new FileOutputStream(mPasswordHashFile);
1065 buffer = new BufferedOutputStream(pwf);
1066 out = new DataOutputStream(buffer);
1067 // integer length of the salt array, followed by the salt,
1068 // then the hex pw hash string
1069 out.writeInt(salt.length);
1070 out.write(salt);
1071 out.writeUTF(newPwHash);
1072 out.flush();
1073 mPasswordHash = newPwHash;
1074 mPasswordSalt = salt;
1075 return true;
1076 } finally {
1077 if (out != null) out.close();
1078 if (buffer != null) buffer.close();
1079 if (pwf != null) pwf.close();
1080 }
1081 } catch (IOException e) {
1082 Slog.e(TAG, "Unable to set backup password");
1083 }
1084 return false;
1085 }
1086
1087 @Override
1088 public boolean hasBackupPassword() {
1089 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1090 "hasBackupPassword");
1091 return (mPasswordHash != null && mPasswordHash.length() > 0);
1092 }
1093
Christopher Tate4cc86e12009-09-21 19:36:51 -07001094 // Maintain persistent state around whether need to do an initialize operation.
1095 // Must be called with the queue lock held.
1096 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001097 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001098 + " on transport " + transportName);
1099 try {
1100 IBackupTransport transport = getTransport(transportName);
1101 String transportDirName = transport.transportDirName();
1102 File stateDir = new File(mBaseStateDir, transportDirName);
1103 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1104
1105 if (isPending) {
1106 // We need an init before we can proceed with sending backup data.
1107 // Record that with an entry in our set of pending inits, as well as
1108 // journaling it via creation of a sentinel file.
1109 mPendingInits.add(transportName);
1110 try {
1111 (new FileOutputStream(initPendingFile)).close();
1112 } catch (IOException ioe) {
1113 // Something is badly wrong with our permissions; just try to move on
1114 }
1115 } else {
1116 // No more initialization needed; wipe the journal and reset our state.
1117 initPendingFile.delete();
1118 mPendingInits.remove(transportName);
1119 }
1120 } catch (RemoteException e) {
1121 // can't happen; the transport is local
1122 }
1123 }
1124
Christopher Tated55e18a2009-09-21 10:12:59 -07001125 // Reset all of our bookkeeping, in response to having been told that
1126 // the backend data has been wiped [due to idle expiry, for example],
1127 // so we must re-upload all saved settings.
1128 void resetBackupState(File stateFileDir) {
1129 synchronized (mQueueLock) {
1130 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001131 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001132 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001133
Christopher Tate84725812010-02-04 15:52:40 -08001134 mCurrentToken = 0;
1135 writeRestoreTokens();
1136
Christopher Tated55e18a2009-09-21 10:12:59 -07001137 // Remove all the state files
1138 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001139 // ... but don't touch the needs-init sentinel
1140 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1141 sf.delete();
1142 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001143 }
Christopher Tate45597642011-04-04 16:59:21 -07001144 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001145
Christopher Tate45597642011-04-04 16:59:21 -07001146 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001147 synchronized (mBackupParticipants) {
1148 int N = mBackupParticipants.size();
1149 for (int i=0; i<N; i++) {
1150 int uid = mBackupParticipants.keyAt(i);
1151 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1152 for (ApplicationInfo app: participants) {
1153 dataChangedImpl(app.packageName);
1154 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001155 }
1156 }
1157 }
1158
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001159 // Add a transport to our set of available backends. If 'transport' is null, this
1160 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001161 private void registerTransport(String name, IBackupTransport transport) {
1162 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001163 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001164 if (transport != null) {
1165 mTransports.put(name, transport);
1166 } else {
1167 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001168 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001169 mCurrentTransport = null;
1170 }
1171 // Nothing further to do in the unregistration case
1172 return;
1173 }
Christopher Tate91717492009-06-26 21:07:13 -07001174 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001175
1176 // If the init sentinel file exists, we need to be sure to perform the init
1177 // as soon as practical. We also create the state directory at registration
1178 // time to ensure it's present from the outset.
1179 try {
1180 String transportName = transport.transportDirName();
1181 File stateDir = new File(mBaseStateDir, transportName);
1182 stateDir.mkdirs();
1183
1184 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1185 if (initSentinel.exists()) {
1186 synchronized (mQueueLock) {
1187 mPendingInits.add(transportName);
1188
1189 // TODO: pick a better starting time than now + 1 minute
1190 long delay = 1000 * 60; // one minute, in milliseconds
1191 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1192 System.currentTimeMillis() + delay, mRunInitIntent);
1193 }
1194 }
1195 } catch (RemoteException e) {
1196 // can't happen, the transport is local
1197 }
Christopher Tate91717492009-06-26 21:07:13 -07001198 }
1199
Christopher Tate3799bc22009-05-06 16:13:56 -07001200 // ----- Track installation/removal of packages -----
1201 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1202 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001203 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001204
Christopher Tate3799bc22009-05-06 16:13:56 -07001205 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001206 boolean replacing = false;
1207 boolean added = false;
1208 Bundle extras = intent.getExtras();
1209 String pkgList[] = null;
1210 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatecc55f812011-08-16 16:06:53 -07001211 Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
1212 Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001213 Uri uri = intent.getData();
1214 if (uri == null) {
1215 return;
1216 }
1217 String pkgName = uri.getSchemeSpecificPart();
1218 if (pkgName != null) {
1219 pkgList = new String[] { pkgName };
1220 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001221 if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
1222 // use the existing "add with replacement" logic
1223 if (MORE_DEBUG) Slog.d(TAG, "PACKAGE_REPLACED, updating package " + pkgName);
1224 added = replacing = true;
1225 } else {
1226 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1227 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
1228 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001229 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001230 added = true;
1231 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001232 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001233 added = false;
1234 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1235 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001236
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001237 if (pkgList == null || pkgList.length == 0) {
1238 return;
1239 }
1240 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001241 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001242 for (String pkgName : pkgList) {
1243 if (replacing) {
1244 // The package was just upgraded
1245 updatePackageParticipantsLocked(pkgName);
1246 } else {
1247 // The package was just added
1248 addPackageParticipantsLocked(pkgName);
1249 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001250 }
1251 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001252 } else {
1253 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001254 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1255 } else {
1256 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001257 for (String pkgName : pkgList) {
1258 removePackageParticipantsLocked(pkgName);
1259 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001260 }
1261 }
1262 }
1263 }
1264 };
1265
Dan Egnor87a02bc2009-06-17 02:30:10 -07001266 // ----- Track connection to GoogleBackupTransport service -----
1267 ServiceConnection mGoogleConnection = new ServiceConnection() {
1268 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001269 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001270 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001271 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001272 }
1273
1274 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001275 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001276 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001277 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001278 }
1279 };
1280
Christopher Tate181fafa2009-05-14 11:12:14 -07001281 // Add the backup agents in the given package to our set of known backup participants.
1282 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -07001283 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001284 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -08001285 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -07001286 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001287 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001288 }
1289
Christopher Tate181fafa2009-05-14 11:12:14 -07001290 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001291 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001292 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001293 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -07001294 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001295 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001296 + " uid=" + p.applicationInfo.uid
1297 + " killAfterRestore="
1298 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001299 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001300 }
1301 }
1302
Dan Egnorefe52642009-06-24 00:16:33 -07001303 for (PackageInfo pkg : targetPkgs) {
1304 if (packageName == null || pkg.packageName.equals(packageName)) {
1305 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001306 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001307 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001308 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001309 mBackupParticipants.put(uid, set);
1310 }
Dan Egnorefe52642009-06-24 00:16:33 -07001311 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001312
1313 // If we've never seen this app before, schedule a backup for it
1314 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001315 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001316 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001317 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001318 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001319 }
Christopher Tate487529a2009-04-29 14:03:25 -07001320 }
1321 }
1322
Christopher Tate6785dd82009-06-18 15:58:25 -07001323 // Remove the given package's entry from our known active set. If
1324 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001325 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001326 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001327 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001328 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001329 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001330 } else {
1331 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001332 List<PackageInfo> knownPackages = allAgentPackages();
1333 for (PackageInfo pkg : knownPackages) {
1334 allApps.add(pkg.packageName);
1335 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001336 }
1337 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001338 }
1339
Joe Onorato8ad02812009-05-13 01:41:44 -04001340 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001341 List<String> allPackageNames) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001342 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001343 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001344 + ") removing " + allPackageNames.size() + " entries");
1345 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001346 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001347 }
1348 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001349 for (String pkg : allPackageNames) {
1350 if (packageName == null || pkg.equals(packageName)) {
1351 int uid = -1;
1352 try {
1353 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1354 uid = info.applicationInfo.uid;
1355 } catch (NameNotFoundException e) {
1356 // we don't know this package name, so just skip it for now
1357 continue;
1358 }
1359
Christopher Tate181fafa2009-05-14 11:12:14 -07001360 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001361 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001362 // Find the existing entry with the same package name, and remove it.
1363 // We can't just remove(app) because the instances are different.
1364 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001365 if (entry.packageName.equals(pkg)) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001366 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001367 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001368 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001369 break;
1370 }
1371 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001372 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001373 mBackupParticipants.delete(uid);
1374 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001375 }
1376 }
1377 }
1378 }
1379
Christopher Tate181fafa2009-05-14 11:12:14 -07001380 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001381 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001382 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001383 int flags = PackageManager.GET_SIGNATURES;
1384 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1385 int N = packages.size();
1386 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001387 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001388 try {
1389 ApplicationInfo app = pkg.applicationInfo;
1390 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001391 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001392 packages.remove(a);
1393 }
1394 else {
1395 // we will need the shared library path, so look that up and store it here
1396 app = mPackageManager.getApplicationInfo(pkg.packageName,
1397 PackageManager.GET_SHARED_LIBRARY_FILES);
1398 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1399 }
1400 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001401 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001402 }
1403 }
Dan Egnorefe52642009-06-24 00:16:33 -07001404 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001405 }
Christopher Tateaa088442009-06-16 18:25:46 -07001406
Christopher Tate3799bc22009-05-06 16:13:56 -07001407 // Reset the given package's known backup participants. Unlike add/remove, the update
1408 // action cannot be passed a null package name.
1409 void updatePackageParticipantsLocked(String packageName) {
1410 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001411 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001412 return;
1413 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001414 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001415
1416 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001417 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001418 List<String> allAppNames = new ArrayList<String>();
1419 for (PackageInfo pkg : allApps) {
1420 allAppNames.add(pkg.packageName);
1421 }
1422 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001423 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001424 }
1425
Christopher Tate84725812010-02-04 15:52:40 -08001426 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001427 // backed up at least once
1428 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001429 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1430
1431 synchronized (mEverStoredApps) {
1432 if (!mEverStoredApps.add(packageName)) return;
1433
1434 RandomAccessFile out = null;
1435 try {
1436 out = new RandomAccessFile(mEverStored, "rws");
1437 out.seek(out.length());
1438 out.writeUTF(packageName);
1439 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001440 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001441 } finally {
1442 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001443 }
1444 }
1445 }
1446
Christopher Tatee97e8072009-07-15 16:45:50 -07001447 // Remove our awareness of having ever backed up the given package
1448 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001449 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1450 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001451
Dan Egnor852f8e42009-09-30 11:20:45 -07001452 synchronized (mEverStoredApps) {
1453 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1454 // we'll recognize on initialization time that the package no longer
1455 // exists and fix it up then.
1456 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1457 RandomAccessFile known = null;
1458 try {
1459 known = new RandomAccessFile(tempKnownFile, "rws");
1460 mEverStoredApps.remove(packageName);
1461 for (String s : mEverStoredApps) {
1462 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001463 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001464 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001465 known.close();
1466 known = null;
1467 if (!tempKnownFile.renameTo(mEverStored)) {
1468 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1469 }
1470 } catch (IOException e) {
1471 // Bad: we couldn't create the new copy. For safety's sake we
1472 // abandon the whole process and remove all what's-backed-up
1473 // state entirely, meaning we'll force a backup pass for every
1474 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001475 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001476 mEverStoredApps.clear();
1477 tempKnownFile.delete();
1478 mEverStored.delete();
1479 } finally {
1480 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001481 }
1482 }
1483 }
1484
Christopher Tateb49ceb32010-02-08 16:22:24 -08001485 // Persistently record the current and ancestral backup tokens as well
1486 // as the set of packages with data [supposedly] available in the
1487 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001488 void writeRestoreTokens() {
1489 try {
1490 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001491
1492 // First, the version number of this record, for futureproofing
1493 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1494
1495 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001496 af.writeLong(mAncestralToken);
1497 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001498
1499 // Now write the set of ancestral packages
1500 if (mAncestralPackages == null) {
1501 af.writeInt(-1);
1502 } else {
1503 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001504 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001505 for (String pkgName : mAncestralPackages) {
1506 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001507 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001508 }
1509 }
Christopher Tate84725812010-02-04 15:52:40 -08001510 af.close();
1511 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001512 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001513 }
1514 }
1515
Dan Egnor87a02bc2009-06-17 02:30:10 -07001516 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001517 private IBackupTransport getTransport(String transportName) {
1518 synchronized (mTransports) {
1519 IBackupTransport transport = mTransports.get(transportName);
1520 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001521 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001522 }
1523 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001524 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001525 }
1526
Christopher Tatedf01dea2009-06-09 20:45:02 -07001527 // fire off a backup agent, blocking until it attaches or times out
1528 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1529 IBackupAgent agent = null;
1530 synchronized(mAgentConnectLock) {
1531 mConnecting = true;
1532 mConnectedAgent = null;
1533 try {
1534 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001535 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001536
1537 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001538 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001539 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1540 while (mConnecting && mConnectedAgent == null
1541 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001542 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001543 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001544 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001545 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001546 return null;
1547 }
1548 }
1549
1550 // if we timed out with no connect, abort and move on
1551 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001552 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001553 return null;
1554 }
1555 agent = mConnectedAgent;
1556 }
1557 } catch (RemoteException e) {
1558 // can't happen
1559 }
1560 }
1561 return agent;
1562 }
1563
Christopher Tatec7b31e32009-06-10 15:49:30 -07001564 // clear an application's data, blocking until the operation completes or times out
1565 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001566 // Don't wipe packages marked allowClearUserData=false
1567 try {
1568 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1569 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001570 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001571 + packageName);
1572 return;
1573 }
1574 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001575 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001576 return;
1577 }
1578
Christopher Tatec7b31e32009-06-10 15:49:30 -07001579 ClearDataObserver observer = new ClearDataObserver();
1580
1581 synchronized(mClearDataLock) {
1582 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001583 try {
1584 mActivityManager.clearApplicationUserData(packageName, observer);
1585 } catch (RemoteException e) {
1586 // can't happen because the activity manager is in this process
1587 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001588
1589 // only wait 10 seconds for the clear data to happen
1590 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1591 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1592 try {
1593 mClearDataLock.wait(5000);
1594 } catch (InterruptedException e) {
1595 // won't happen, but still.
1596 mClearingData = false;
1597 }
1598 }
1599 }
1600 }
1601
1602 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001603 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001604 synchronized(mClearDataLock) {
1605 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001606 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001607 }
1608 }
1609 }
1610
Christopher Tate1bb69062010-02-19 17:02:12 -08001611 // Get the restore-set token for the best-available restore set for this package:
1612 // the active set if possible, else the ancestral one. Returns zero if none available.
1613 long getAvailableRestoreToken(String packageName) {
1614 long token = mAncestralToken;
1615 synchronized (mQueueLock) {
1616 if (mEverStoredApps.contains(packageName)) {
1617 token = mCurrentToken;
1618 }
1619 }
1620 return token;
1621 }
1622
Christopher Tate44a27902010-01-27 17:15:49 -08001623 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001624 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1625
1626 interface BackupRestoreTask {
1627 // Execute one tick of whatever state machine the task implements
1628 void execute();
1629
1630 // An operation that wanted a callback has completed
1631 void operationComplete();
1632
1633 // An operation that wanted a callback has timed out
1634 void handleTimeout();
1635 }
1636
1637 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1638 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1639 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001640 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001641 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1642
1643 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1644 mBackupHandler.sendMessageDelayed(msg, interval);
1645 }
1646 }
1647
1648 // synchronous waiter case
1649 boolean waitUntilOperationComplete(int token) {
1650 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1651 + Integer.toHexString(token));
1652 int finalState = OP_PENDING;
1653 Operation op = null;
1654 synchronized (mCurrentOpLock) {
1655 while (true) {
1656 op = mCurrentOperations.get(token);
1657 if (op == null) {
1658 // mysterious disappearance: treat as success with no callback
1659 break;
1660 } else {
1661 if (op.state == OP_PENDING) {
1662 try {
1663 mCurrentOpLock.wait();
1664 } catch (InterruptedException e) {}
1665 // When the wait is notified we loop around and recheck the current state
1666 } else {
1667 // No longer pending; we're done
1668 finalState = op.state;
1669 break;
1670 }
Christopher Tate44a27902010-01-27 17:15:49 -08001671 }
Christopher Tate44a27902010-01-27 17:15:49 -08001672 }
1673 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001674
Christopher Tate44a27902010-01-27 17:15:49 -08001675 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001676 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001677 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001678 return finalState == OP_ACKNOWLEDGED;
1679 }
1680
Christopher Tate8e294d42011-08-31 20:37:12 -07001681 void handleTimeout(int token, Object obj) {
1682 // Notify any synchronous waiters
1683 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001684 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001685 op = mCurrentOperations.get(token);
1686 if (MORE_DEBUG) {
1687 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1688 + " but no op found");
1689 }
1690 int state = (op != null) ? op.state : OP_TIMEOUT;
1691 if (state == OP_PENDING) {
1692 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1693 op.state = OP_TIMEOUT;
1694 mCurrentOperations.put(token, op);
1695 }
1696 mCurrentOpLock.notifyAll();
1697 }
1698
1699 // If there's a TimeoutHandler for this event, call it
1700 if (op != null && op.callback != null) {
1701 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001702 }
Christopher Tate44a27902010-01-27 17:15:49 -08001703 }
1704
Christopher Tate043dadc2009-06-02 16:11:00 -07001705 // ----- Back up a set of applications via a worker thread -----
1706
Christopher Tate8e294d42011-08-31 20:37:12 -07001707 enum BackupState {
1708 INITIAL,
1709 RUNNING_QUEUE,
1710 FINAL
1711 }
1712
1713 class PerformBackupTask implements BackupRestoreTask {
1714 private static final String TAG = "PerformBackupTask";
1715
Christopher Tateaa088442009-06-16 18:25:46 -07001716 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001717 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001718 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001719 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001720 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001721 BackupState mCurrentState;
1722
1723 // carried information about the current in-flight operation
1724 PackageInfo mCurrentPackage;
1725 File mSavedStateName;
1726 File mBackupDataName;
1727 File mNewStateName;
1728 ParcelFileDescriptor mSavedState;
1729 ParcelFileDescriptor mBackupData;
1730 ParcelFileDescriptor mNewState;
1731 int mStatus;
1732 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001733
Christopher Tate44a27902010-01-27 17:15:49 -08001734 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001735 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001736 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001737 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001738 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001739
1740 try {
1741 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1742 } catch (RemoteException e) {
1743 // can't happen; the transport is local
1744 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001745
1746 mCurrentState = BackupState.INITIAL;
1747 mFinished = false;
Christopher Tate043dadc2009-06-02 16:11:00 -07001748 }
1749
Christopher Tate8e294d42011-08-31 20:37:12 -07001750 // Main entry point: perform one chunk of work, updating the state as appropriate
1751 // and reposting the next chunk to the primary backup handler thread.
1752 @Override
1753 public void execute() {
1754 switch (mCurrentState) {
1755 case INITIAL:
1756 beginBackup();
1757 break;
1758
1759 case RUNNING_QUEUE:
1760 invokeNextAgent();
1761 break;
1762
1763 case FINAL:
1764 if (!mFinished) finalizeBackup();
1765 else {
1766 Slog.e(TAG, "Duplicate finish");
1767 }
1768 break;
1769 }
1770 }
1771
1772 // We're starting a backup pass. Initialize the transport and send
1773 // the PM metadata blob if we haven't already.
1774 void beginBackup() {
1775 mStatus = BackupConstants.TRANSPORT_OK;
1776
1777 // Sanity check: if the queue is empty we have no work to do.
1778 if (mOriginalQueue.isEmpty()) {
1779 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
1780 return;
1781 }
1782
1783 // We need to retain the original queue contents in case of transport
1784 // failure, but we want a working copy that we can manipulate along
1785 // the way.
1786 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1787
Joe Onorato8a9b2202010-02-26 18:56:32 -08001788 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001789
Christopher Tate8e294d42011-08-31 20:37:12 -07001790 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001791 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001792 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001793
Dan Egnor852f8e42009-09-30 11:20:45 -07001794 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001795 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001796 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001797 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001798 mStatus = mTransport.initializeDevice();
1799 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001800 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001801 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001802 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001803 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001804 }
Dan Egnor01445162009-09-21 17:04:05 -07001805 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001806
1807 // The package manager doesn't have a proper <application> etc, but since
1808 // it's running here in the system process we can just set up its agent
1809 // directly and use a synthetic BackupRequest. We always run this pass
1810 // because it's cheap and this way we guarantee that we don't get out of
1811 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001812 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001813 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1814 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001815 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001816 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1817 }
Christopher Tate90967f42009-09-20 15:28:33 -07001818
Christopher Tate8e294d42011-08-31 20:37:12 -07001819 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1820 // The backend reports that our dataset has been wiped. Note this in
1821 // the event log; the no-success code below will reset the backup
1822 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001823 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001824 }
1825 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001826 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001827 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001828 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001829 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1830 // metadata and its completion/timeout callback will continue the state
1831 // machine chain. If it failed that won't happen; we handle that now.
1832 if (mStatus != BackupConstants.TRANSPORT_OK) {
1833 // if things went wrong at this point, we need to
1834 // restage everything and try again later.
1835 resetBackupState(mStateDir); // Just to make sure.
1836 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001837 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001838 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001839 }
1840
Christopher Tate8e294d42011-08-31 20:37:12 -07001841 // Transport has been initialized and the PM metadata submitted successfully
1842 // if that was warranted. Now we process the single next thing in the queue.
1843 void invokeNextAgent() {
1844 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001845
Christopher Tate8e294d42011-08-31 20:37:12 -07001846 // Sanity check that we have work to do. If not, skip to the end where
1847 // we reestablish the wakelock invariants etc.
1848 if (mQueue.isEmpty()) {
1849 Slog.e(TAG, "Running queue but it's empty!");
1850 executeNextState(BackupState.FINAL);
1851 return;
1852 }
1853
1854 // pop the entry we're going to process on this step
1855 BackupRequest request = mQueue.get(0);
1856 mQueue.remove(0);
1857
1858 Slog.d(TAG, "starting agent for backup of " + request);
1859
1860 // Verify that the requested app exists; it might be something that
1861 // requested a backup but was then uninstalled. The request was
1862 // journalled and rather than tamper with the journal it's safer
1863 // to sanity-check here. This also gives us the classname of the
1864 // package's backup agent.
1865 try {
1866 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1867 PackageManager.GET_SIGNATURES);
Christopher Tatec28083a2010-12-14 16:16:44 -08001868
Christopher Tate043dadc2009-06-02 16:11:00 -07001869 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001870 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001871 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1872 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001873 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001874 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001875 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
1876 // at this point we'll either get a completion callback from the
1877 // agent, or a timeout message on the main handler. either way, we're
1878 // done here as long as we're successful so far.
1879 } else {
1880 // Timeout waiting for the agent
1881 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07001882 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001883 } catch (SecurityException ex) {
1884 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001885 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07001886 mStatus = BackupConstants.AGENT_ERROR;
1887 }
1888 } catch (NameNotFoundException e) {
1889 Slog.d(TAG, "Package does not exist; skipping");
1890 } finally {
1891 mWakelock.setWorkSource(null);
1892
1893 // If there was an agent error, no timeout/completion handling will occur.
1894 // That means we need to deal with the next state ourselves.
1895 if (mStatus != BackupConstants.TRANSPORT_OK) {
1896 BackupState nextState = BackupState.RUNNING_QUEUE;
1897
1898 // An agent-level failure means we reenqueue this one agent for
1899 // a later retry, but otherwise proceed normally.
1900 if (mStatus == BackupConstants.AGENT_ERROR) {
1901 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
1902 + " - restaging");
1903 dataChangedImpl(request.packageName);
1904 mStatus = BackupConstants.TRANSPORT_OK;
1905 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
1906 } else if (mStatus != BackupConstants.TRANSPORT_OK) {
1907 // Transport-level failure means we reenqueue everything
1908 revertAndEndBackup();
1909 nextState = BackupState.FINAL;
1910 }
1911
1912 executeNextState(nextState);
Christopher Tate043dadc2009-06-02 16:11:00 -07001913 }
1914 }
1915 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001916
Christopher Tate8e294d42011-08-31 20:37:12 -07001917 void finalizeBackup() {
1918 // Either backup was successful, in which case we of course do not need
1919 // this pass's journal any more; or it failed, in which case we just
1920 // re-enqueued all of these packages in the current active journal.
1921 // Either way, we no longer need this pass's journal.
1922 if (mJournal != null && !mJournal.delete()) {
1923 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
1924 }
1925
1926 // If everything actually went through and this is the first time we've
1927 // done a backup, we can now record what the current backup dataset token
1928 // is.
1929 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
1930 try {
1931 mCurrentToken = mTransport.getCurrentRestoreSet();
1932 } catch (RemoteException e) {} // can't happen
1933 writeRestoreTokens();
1934 }
1935
1936 // Set up the next backup pass
1937 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1938 backupNow();
1939 }
1940
1941 // Only once we're entirely finished do we release the wakelock
1942 Slog.i(TAG, "Backup pass finished.");
1943 mWakelock.release();
1944 }
1945
1946 // Invoke an agent's doBackup() and start a timeout message spinning on the main
1947 // handler in case it doesn't get back to us.
1948 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07001949 IBackupTransport transport) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001950 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001951
Christopher Tate8e294d42011-08-31 20:37:12 -07001952 mSavedStateName = new File(mStateDir, packageName);
1953 mBackupDataName = new File(mDataDir, packageName + ".data");
1954 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001955
Christopher Tate8e294d42011-08-31 20:37:12 -07001956 mSavedState = null;
1957 mBackupData = null;
1958 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001959
Christopher Tate4a627c72011-04-01 14:43:32 -07001960 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001961 try {
1962 // Look up the package info & signatures. This is first so that if it
1963 // throws an exception, there's no file setup yet that would need to
1964 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001965 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001966 // The metadata 'package' is synthetic; construct one and make
1967 // sure our global state is pointed at it
1968 mCurrentPackage = new PackageInfo();
1969 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07001970 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001971
Christopher Tatec7b31e32009-06-10 15:49:30 -07001972 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001973 // the saved-state "file". This is by definition an incremental,
1974 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07001975 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07001976 ParcelFileDescriptor.MODE_READ_ONLY |
1977 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001978
Christopher Tate8e294d42011-08-31 20:37:12 -07001979 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001980 ParcelFileDescriptor.MODE_READ_WRITE |
1981 ParcelFileDescriptor.MODE_CREATE |
1982 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001983
Christopher Tate8e294d42011-08-31 20:37:12 -07001984 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001985 ParcelFileDescriptor.MODE_READ_WRITE |
1986 ParcelFileDescriptor.MODE_CREATE |
1987 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001988
Christopher Tate44a27902010-01-27 17:15:49 -08001989 // Initiate the target's backup pass
Christopher Tate8e294d42011-08-31 20:37:12 -07001990 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
1991 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001992 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001993 Slog.e(TAG, "Error invoking for backup on " + packageName);
1994 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
1995 e.toString());
1996 agentErrorCleanup();
1997 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001998 }
1999
Christopher Tate8e294d42011-08-31 20:37:12 -07002000 // At this point the agent is off and running. The next thing to happen will
2001 // either be a callback from the agent, at which point we'll process its data
2002 // for transport, or a timeout. Either way the next phase will happen in
2003 // response to the TimeoutHandler interface callbacks.
2004 return BackupConstants.TRANSPORT_OK;
2005 }
2006
2007 @Override
2008 public void operationComplete() {
2009 // Okay, the agent successfully reported back to us. Spin the data off to the
2010 // transport and proceed with the next stage.
2011 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2012 + mCurrentPackage.packageName);
2013 mBackupHandler.removeMessages(MSG_TIMEOUT);
2014 clearAgentState();
2015
2016 ParcelFileDescriptor backupData = null;
2017 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002018 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002019 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002020 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002021 if (mStatus == BackupConstants.TRANSPORT_OK) {
2022 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002023 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate8e294d42011-08-31 20:37:12 -07002024 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002025 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002026
Dan Egnor83861e72009-09-17 16:17:55 -07002027 // TODO - We call finishBackup() for each application backed up, because
2028 // we need to know now whether it succeeded or failed. Instead, we should
2029 // hold off on finishBackup() until the end, which implies holding off on
2030 // renaming *all* the output state files (see below) until that happens.
2031
Christopher Tate8e294d42011-08-31 20:37:12 -07002032 if (mStatus == BackupConstants.TRANSPORT_OK) {
2033 mStatus = mTransport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07002034 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002035 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002036 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002037 }
2038
2039 // After successful transport, delete the now-stale data
2040 // and juggle the files so that next time we supply the agent
2041 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002042 if (mStatus == BackupConstants.TRANSPORT_OK) {
2043 mBackupDataName.delete();
2044 mNewStateName.renameTo(mSavedStateName);
2045 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2046 mCurrentPackage.packageName, size);
2047 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002048 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002049 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2050 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002051 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002052 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002053 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2054 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2055 mCurrentPackage.packageName);
2056 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002057 } finally {
2058 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002059 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002060
Christopher Tate8e294d42011-08-31 20:37:12 -07002061 // If we encountered an error here it's a transport-level failure. That
2062 // means we need to halt everything and reschedule everything for next time.
2063 final BackupState nextState;
2064 if (mStatus != BackupConstants.TRANSPORT_OK) {
2065 revertAndEndBackup();
2066 nextState = BackupState.FINAL;
2067 } else {
2068 // Success! Proceed with the next app if any, otherwise we're done.
2069 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2070 }
2071
2072 executeNextState(nextState);
2073 }
2074
2075 @Override
2076 public void handleTimeout() {
2077 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2078 // it for the next time we run a backup pass.
2079 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2080 // fail repeatedly (i.e. have proved themselves to be buggy).
2081 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2082 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2083 "timeout");
2084 agentErrorCleanup();
2085 dataChangedImpl(mCurrentPackage.packageName);
2086 }
2087
2088 void revertAndEndBackup() {
2089 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
2090 for (BackupRequest request : mOriginalQueue) {
2091 dataChangedImpl(request.packageName);
2092 }
2093 // We also want to reset the backup schedule based on whatever
2094 // the transport suggests by way of retry/backoff time.
2095 restartBackupAlarm();
2096 }
2097
2098 void agentErrorCleanup() {
2099 mBackupDataName.delete();
2100 mNewStateName.delete();
2101 clearAgentState();
2102
2103 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2104 }
2105
2106 // Cleanup common to both success and failure cases
2107 void clearAgentState() {
2108 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2109 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2110 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2111 mSavedState = mBackupData = mNewState = null;
2112 synchronized (mCurrentOpLock) {
2113 mCurrentOperations.clear();
2114 }
2115
2116 // If this was a pseudopackage there's no associated Activity Manager state
2117 if (mCurrentPackage.applicationInfo != null) {
2118 try { // unbind even on timeout, just in case
2119 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2120 } catch (RemoteException e) {}
2121 }
2122 }
2123
2124 void restartBackupAlarm() {
2125 synchronized (mQueueLock) {
2126 try {
2127 startBackupAlarmsLocked(mTransport.requestBackupTime());
2128 } catch (RemoteException e) { /* cannot happen */ }
2129 }
2130 }
2131
2132 void executeNextState(BackupState nextState) {
2133 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2134 + this + " nextState=" + nextState);
2135 mCurrentState = nextState;
2136 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2137 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002138 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002139 }
2140
Christopher Tatedf01dea2009-06-09 20:45:02 -07002141
Christopher Tate4a627c72011-04-01 14:43:32 -07002142 // ----- Full backup to a file/socket -----
2143
2144 class PerformFullBackupTask implements Runnable {
2145 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002146 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002147 IFullBackupRestoreObserver mObserver;
2148 boolean mIncludeApks;
2149 boolean mIncludeShared;
2150 boolean mAllApps;
2151 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002152 String mCurrentPassword;
2153 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002154 AtomicBoolean mLatchObject;
2155 File mFilesDir;
2156 File mManifestFile;
2157
Christopher Tate7926a692011-07-11 11:31:57 -07002158 class FullBackupRunner implements Runnable {
2159 PackageInfo mPackage;
2160 IBackupAgent mAgent;
2161 ParcelFileDescriptor mPipe;
2162 int mToken;
2163 boolean mSendApk;
2164
2165 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
2166 int token, boolean sendApk) throws IOException {
2167 mPackage = pack;
2168 mAgent = agent;
2169 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2170 mToken = token;
2171 mSendApk = sendApk;
2172 }
2173
2174 @Override
2175 public void run() {
2176 try {
2177 BackupDataOutput output = new BackupDataOutput(
2178 mPipe.getFileDescriptor());
2179
Christopher Tatec58efa62011-08-01 19:20:14 -07002180 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
Christopher Tate7926a692011-07-11 11:31:57 -07002181 writeAppManifest(mPackage, mManifestFile, mSendApk);
2182 FullBackup.backupToTar(mPackage.packageName, null, null,
2183 mFilesDir.getAbsolutePath(),
2184 mManifestFile.getAbsolutePath(),
2185 output);
2186
2187 if (mSendApk) {
2188 writeApkToBackup(mPackage, output);
2189 }
2190
Christopher Tatec58efa62011-08-01 19:20:14 -07002191 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002192 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002193 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2194 } catch (IOException e) {
2195 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2196 } catch (RemoteException e) {
2197 Slog.e(TAG, "Remote agent vanished during full backup of "
2198 + mPackage.packageName);
2199 } finally {
2200 try {
2201 mPipe.close();
2202 } catch (IOException e) {}
2203 }
2204 }
2205 }
2206
Christopher Tate4a627c72011-04-01 14:43:32 -07002207 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002208 boolean includeApks, boolean includeShared, String curPassword,
2209 String encryptPassword, boolean doAllApps, String[] packages,
2210 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002211 mOutputFile = fd;
2212 mObserver = observer;
2213 mIncludeApks = includeApks;
2214 mIncludeShared = includeShared;
2215 mAllApps = doAllApps;
2216 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002217 mCurrentPassword = curPassword;
2218 // when backing up, if there is a current backup password, we require that
2219 // the user use a nonempty encryption password as well. if one is supplied
2220 // in the UI we use that, but if the UI was left empty we fall back to the
2221 // current backup password (which was supplied by the user as well).
2222 if (encryptPassword == null || "".equals(encryptPassword)) {
2223 mEncryptPassword = curPassword;
2224 } else {
2225 mEncryptPassword = encryptPassword;
2226 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002227 mLatchObject = latch;
2228
2229 mFilesDir = new File("/data/system");
2230 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2231 }
2232
2233 @Override
2234 public void run() {
2235 final List<PackageInfo> packagesToBackup;
2236
Christopher Tateb0628bf2011-06-02 15:08:13 -07002237 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002238 sendStartBackup();
2239
2240 // doAllApps supersedes the package set if any
2241 if (mAllApps) {
2242 packagesToBackup = mPackageManager.getInstalledPackages(
2243 PackageManager.GET_SIGNATURES);
2244 } else {
2245 packagesToBackup = new ArrayList<PackageInfo>();
2246 for (String pkgName : mPackages) {
2247 try {
2248 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2249 PackageManager.GET_SIGNATURES));
2250 } catch (NameNotFoundException e) {
2251 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2252 }
2253 }
2254 }
2255
Christopher Tatea858cb02011-06-03 12:27:51 -07002256 // Cull any packages that have indicated that backups are not permitted.
2257 for (int i = 0; i < packagesToBackup.size(); ) {
2258 PackageInfo info = packagesToBackup.get(i);
2259 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
2260 packagesToBackup.remove(i);
2261 } else {
2262 i++;
2263 }
2264 }
2265
Christopher Tate7926a692011-07-11 11:31:57 -07002266 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002267 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002268
Christopher Tate4a627c72011-04-01 14:43:32 -07002269 PackageInfo pkg = null;
2270 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002271 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002272 boolean compressing = COMPRESS_FULL_BACKUPS;
2273 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002274
Christopher Tateeef4ae42011-08-05 13:15:53 -07002275 // Verify that the given password matches the currently-active
2276 // backup password, if any
2277 if (hasBackupPassword()) {
2278 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2279 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2280 return;
2281 }
2282 }
2283
Christopher Tate7bdb0962011-07-13 19:30:21 -07002284 // Write the global file header. All strings are UTF-8 encoded; lines end
2285 // with a '\n' byte. Actual backup data begins immediately following the
2286 // final '\n'.
2287 //
2288 // line 1: "ANDROID BACKUP"
2289 // line 2: backup file format version, currently "1"
2290 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002291 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2292 //
2293 // When line 4 is not "none", then additional header data follows:
2294 //
2295 // line 5: user password salt [hex]
2296 // line 6: master key checksum salt [hex]
2297 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2298 // line 8: IV of the user key [hex]
2299 // line 9: master key blob [hex]
2300 // IV of the master key, master key itself, master key checksum hash
2301 //
2302 // The master key checksum is the master key plus its checksum salt, run through
2303 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2304 // correct password for decrypting the archive: the master key decrypted from
2305 // the archive using the user-supplied password is also run through PBKDF2 in
2306 // this way, and if the result does not match the checksum as stored in the
2307 // archive, then we know that the user-supplied password does not match the
2308 // archive's.
2309 StringBuilder headerbuf = new StringBuilder(1024);
2310
Christopher Tate7bdb0962011-07-13 19:30:21 -07002311 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002312 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2313 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002314
2315 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002316 // Set up the encryption stage if appropriate, and emit the correct header
2317 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002318 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2319 } else {
2320 headerbuf.append("none\n");
2321 }
2322
Christopher Tate7bdb0962011-07-13 19:30:21 -07002323 byte[] header = headerbuf.toString().getBytes("UTF-8");
2324 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002325
2326 // Set up the compression stage feeding into the encryption stage (if any)
2327 if (compressing) {
2328 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2329 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2330 }
2331
2332 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002333 } catch (Exception e) {
2334 // Should never happen!
2335 Slog.e(TAG, "Unable to emit archive header", e);
2336 return;
2337 }
2338
Christopher Tateb0628bf2011-06-02 15:08:13 -07002339 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002340 int N = packagesToBackup.size();
2341 for (int i = 0; i < N; i++) {
2342 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002343 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002344 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002345
Christopher Tate6853fcf2011-08-10 17:52:21 -07002346 // Shared storage if requested
Christopher Tateb0628bf2011-06-02 15:08:13 -07002347 if (mIncludeShared) {
2348 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07002349 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07002350
2351 // Done!
2352 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002353 } catch (RemoteException e) {
2354 Slog.e(TAG, "App died during full backup");
2355 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002356 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002357 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002358 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002359 mOutputFile.close();
2360 } catch (IOException e) {
2361 /* nothing we can do about this */
2362 }
2363 synchronized (mCurrentOpLock) {
2364 mCurrentOperations.clear();
2365 }
2366 synchronized (mLatchObject) {
2367 mLatchObject.set(true);
2368 mLatchObject.notifyAll();
2369 }
2370 sendEndBackup();
2371 mWakelock.release();
2372 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
2373 }
2374 }
2375
Christopher Tate2efd2db2011-07-19 16:32:49 -07002376 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2377 OutputStream ofstream) throws Exception {
2378 // User key will be used to encrypt the master key.
2379 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002380 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002381 PBKDF2_HASH_ROUNDS);
2382
2383 // the master key is random for each backup
2384 byte[] masterPw = new byte[256 / 8];
2385 mRng.nextBytes(masterPw);
2386 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2387
2388 // primary encryption of the datastream with the random key
2389 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2390 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2391 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2392 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2393
2394 // line 4: name of encryption algorithm
2395 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2396 headerbuf.append('\n');
2397 // line 5: user password salt [hex]
2398 headerbuf.append(byteArrayToHex(newUserSalt));
2399 headerbuf.append('\n');
2400 // line 6: master key checksum salt [hex]
2401 headerbuf.append(byteArrayToHex(checksumSalt));
2402 headerbuf.append('\n');
2403 // line 7: number of PBKDF2 rounds used [decimal]
2404 headerbuf.append(PBKDF2_HASH_ROUNDS);
2405 headerbuf.append('\n');
2406
2407 // line 8: IV of the user key [hex]
2408 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2409 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2410
2411 byte[] IV = mkC.getIV();
2412 headerbuf.append(byteArrayToHex(IV));
2413 headerbuf.append('\n');
2414
2415 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2416 // [byte] IV length = Niv
2417 // [array of Niv bytes] IV itself
2418 // [byte] master key length = Nmk
2419 // [array of Nmk bytes] master key itself
2420 // [byte] MK checksum hash length = Nck
2421 // [array of Nck bytes] master key checksum hash
2422 //
2423 // The checksum is the (master key + checksum salt), run through the
2424 // stated number of PBKDF2 rounds
2425 IV = c.getIV();
2426 byte[] mk = masterKeySpec.getEncoded();
2427 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2428 checksumSalt, PBKDF2_HASH_ROUNDS);
2429
2430 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2431 + checksum.length + 3);
2432 DataOutputStream mkOut = new DataOutputStream(blob);
2433 mkOut.writeByte(IV.length);
2434 mkOut.write(IV);
2435 mkOut.writeByte(mk.length);
2436 mkOut.write(mk);
2437 mkOut.writeByte(checksum.length);
2438 mkOut.write(checksum);
2439 mkOut.flush();
2440 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2441 headerbuf.append(byteArrayToHex(encryptedMk));
2442 headerbuf.append('\n');
2443
2444 return finalOutput;
2445 }
2446
2447 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002448 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002449 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2450
2451 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2452 IApplicationThread.BACKUP_MODE_FULL);
2453 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002454 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002455 try {
Christopher Tate7926a692011-07-11 11:31:57 -07002456 pipes = ParcelFileDescriptor.createPipe();
2457
Christopher Tateb0628bf2011-06-02 15:08:13 -07002458 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07002459 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07002460 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2461 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2462 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2463
2464 sendOnBackupPackage(pkg.packageName);
2465
Christopher Tate7926a692011-07-11 11:31:57 -07002466 final int token = generateToken();
2467 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
2468 token, sendApk);
2469 pipes[1].close(); // the runner has dup'd it
2470 pipes[1] = null;
2471 Thread t = new Thread(runner);
2472 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002473
Christopher Tate7926a692011-07-11 11:31:57 -07002474 // Now pull data from the app and stuff it into the compressor
2475 try {
2476 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2477 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002478
Christopher Tate7926a692011-07-11 11:31:57 -07002479 byte[] buffer = new byte[16 * 1024];
2480 int chunkTotal;
2481 while ((chunkTotal = in.readInt()) > 0) {
2482 while (chunkTotal > 0) {
2483 int toRead = (chunkTotal > buffer.length)
2484 ? buffer.length : chunkTotal;
2485 int nRead = in.read(buffer, 0, toRead);
2486 out.write(buffer, 0, nRead);
2487 chunkTotal -= nRead;
2488 }
2489 }
2490 } catch (IOException e) {
2491 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002492 }
2493
Christopher Tateb0628bf2011-06-02 15:08:13 -07002494 if (!waitUntilOperationComplete(token)) {
2495 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2496 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002497 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002498 }
Christopher Tate7926a692011-07-11 11:31:57 -07002499
Christopher Tateb0628bf2011-06-02 15:08:13 -07002500 } catch (IOException e) {
2501 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002502 } finally {
2503 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002504 // flush after every package
2505 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002506 if (pipes != null) {
2507 if (pipes[0] != null) pipes[0].close();
2508 if (pipes[1] != null) pipes[1].close();
2509 }
Christopher Tate7926a692011-07-11 11:31:57 -07002510 } catch (IOException e) {
2511 Slog.w(TAG, "Error bringing down backup stack");
2512 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002513 }
2514 } else {
2515 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2516 }
2517 tearDown(pkg);
2518 }
2519
Christopher Tate79ec80d2011-06-24 14:58:49 -07002520 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2521 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2522 final String appSourceDir = pkg.applicationInfo.sourceDir;
2523 final String apkDir = new File(appSourceDir).getParent();
2524 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2525 apkDir, appSourceDir, output);
2526
2527 // Save associated .obb content if it exists and we did save the apk
2528 // check for .obb and save those too
2529 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2530 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002531 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002532 File[] obbFiles = obbDir.listFiles();
2533 if (obbFiles != null) {
2534 final String obbDirName = obbDir.getAbsolutePath();
2535 for (File obb : obbFiles) {
2536 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2537 obbDirName, obb.getAbsolutePath(), output);
2538 }
2539 }
2540 }
2541 }
2542
Christopher Tateb0628bf2011-06-02 15:08:13 -07002543 private void backupSharedStorage() throws RemoteException {
2544 PackageInfo pkg = null;
2545 try {
2546 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
2547 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2548 IApplicationThread.BACKUP_MODE_FULL);
2549 if (agent != null) {
2550 sendOnBackupPackage("Shared storage");
2551
2552 final int token = generateToken();
Christopher Tate8e294d42011-08-31 20:37:12 -07002553 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL, null);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002554 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002555 if (!waitUntilOperationComplete(token)) {
2556 Slog.e(TAG, "Full backup failed on shared storage");
2557 } else {
2558 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
2559 }
2560 } else {
2561 Slog.e(TAG, "Could not bind to shared storage backup agent");
2562 }
2563 } catch (NameNotFoundException e) {
2564 Slog.e(TAG, "Shared storage backup package not found");
2565 } finally {
2566 tearDown(pkg);
2567 }
2568 }
2569
Christopher Tate6853fcf2011-08-10 17:52:21 -07002570 private void finalizeBackup(OutputStream out) {
2571 try {
2572 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2573 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2574 out.write(eof);
2575 } catch (IOException e) {
2576 Slog.w(TAG, "Error attempting to finalize backup stream");
2577 }
2578 }
2579
Christopher Tate4a627c72011-04-01 14:43:32 -07002580 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2581 throws IOException {
2582 // Manifest format. All data are strings ending in LF:
2583 // BACKUP_MANIFEST_VERSION, currently 1
2584 //
2585 // Version 1:
2586 // package name
2587 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002588 // platform versionCode
2589 // getInstallerPackageName() for this package (maybe empty)
2590 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002591 // number of signatures == N
2592 // N*: signature byte array in ascii format per Signature.toCharsString()
2593 StringBuilder builder = new StringBuilder(4096);
2594 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2595
2596 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2597 printer.println(pkg.packageName);
2598 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002599 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2600
2601 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2602 printer.println((installerName != null) ? installerName : "");
2603
Christopher Tate4a627c72011-04-01 14:43:32 -07002604 printer.println(withApk ? "1" : "0");
2605 if (pkg.signatures == null) {
2606 printer.println("0");
2607 } else {
2608 printer.println(Integer.toString(pkg.signatures.length));
2609 for (Signature sig : pkg.signatures) {
2610 printer.println(sig.toCharsString());
2611 }
2612 }
2613
2614 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002615 outstream.write(builder.toString().getBytes());
2616 outstream.close();
2617 }
2618
2619 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002620 if (pkg != null) {
2621 final ApplicationInfo app = pkg.applicationInfo;
2622 if (app != null) {
2623 try {
2624 // unbind and tidy up even on timeout or failure, just in case
2625 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002626
Christopher Tateb0628bf2011-06-02 15:08:13 -07002627 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002628 if (app.uid != Process.SYSTEM_UID
2629 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002630 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002631 mActivityManager.killApplicationProcess(app.processName, app.uid);
2632 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002633 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002634 }
2635 } catch (RemoteException e) {
2636 Slog.d(TAG, "Lost app trying to shut down");
2637 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002638 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002639 }
2640 }
2641
2642 // wrappers for observer use
2643 void sendStartBackup() {
2644 if (mObserver != null) {
2645 try {
2646 mObserver.onStartBackup();
2647 } catch (RemoteException e) {
2648 Slog.w(TAG, "full backup observer went away: startBackup");
2649 mObserver = null;
2650 }
2651 }
2652 }
2653
2654 void sendOnBackupPackage(String name) {
2655 if (mObserver != null) {
2656 try {
2657 // TODO: use a more user-friendly name string
2658 mObserver.onBackupPackage(name);
2659 } catch (RemoteException e) {
2660 Slog.w(TAG, "full backup observer went away: backupPackage");
2661 mObserver = null;
2662 }
2663 }
2664 }
2665
2666 void sendEndBackup() {
2667 if (mObserver != null) {
2668 try {
2669 mObserver.onEndBackup();
2670 } catch (RemoteException e) {
2671 Slog.w(TAG, "full backup observer went away: endBackup");
2672 mObserver = null;
2673 }
2674 }
2675 }
2676 }
2677
2678
Christopher Tate75a99702011-05-18 16:28:19 -07002679 // ----- Full restore from a file/socket -----
2680
2681 // Description of a file in the restore datastream
2682 static class FileMetadata {
2683 String packageName; // name of the owning app
2684 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002685 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002686 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2687 String path; // subpath within the semantic domain
2688 long mode; // e.g. 0666 (actually int)
2689 long mtime; // last mod time, UTC time_t (actually int)
2690 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002691
2692 @Override
2693 public String toString() {
2694 StringBuilder sb = new StringBuilder(128);
2695 sb.append("FileMetadata{");
2696 sb.append(packageName); sb.append(',');
2697 sb.append(type); sb.append(',');
2698 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2699 sb.append(size);
2700 sb.append('}');
2701 return sb.toString();
2702 }
Christopher Tate75a99702011-05-18 16:28:19 -07002703 }
2704
2705 enum RestorePolicy {
2706 IGNORE,
2707 ACCEPT,
2708 ACCEPT_IF_APK
2709 }
2710
2711 class PerformFullRestoreTask implements Runnable {
2712 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002713 String mCurrentPassword;
2714 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002715 IFullBackupRestoreObserver mObserver;
2716 AtomicBoolean mLatchObject;
2717 IBackupAgent mAgent;
2718 String mAgentPackage;
2719 ApplicationInfo mTargetApp;
2720 ParcelFileDescriptor[] mPipes = null;
2721
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002722 long mBytes;
2723
Christopher Tate75a99702011-05-18 16:28:19 -07002724 // possible handling states for a given package in the restore dataset
2725 final HashMap<String, RestorePolicy> mPackagePolicies
2726 = new HashMap<String, RestorePolicy>();
2727
2728 // installer package names for each encountered app, derived from the manifests
2729 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2730
2731 // Signatures for a given package found in its manifest file
2732 final HashMap<String, Signature[]> mManifestSignatures
2733 = new HashMap<String, Signature[]>();
2734
2735 // Packages we've already wiped data on when restoring their first file
2736 final HashSet<String> mClearedPackages = new HashSet<String>();
2737
Christopher Tate728a1c42011-07-28 18:03:03 -07002738 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002739 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002740 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002741 mCurrentPassword = curPassword;
2742 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002743 mObserver = observer;
2744 mLatchObject = latch;
2745 mAgent = null;
2746 mAgentPackage = null;
2747 mTargetApp = null;
2748
2749 // Which packages we've already wiped data on. We prepopulate this
2750 // with a whitelist of packages known to be unclearable.
2751 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002752 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002753
Christopher Tate75a99702011-05-18 16:28:19 -07002754 }
2755
2756 class RestoreFileRunnable implements Runnable {
2757 IBackupAgent mAgent;
2758 FileMetadata mInfo;
2759 ParcelFileDescriptor mSocket;
2760 int mToken;
2761
2762 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2763 ParcelFileDescriptor socket, int token) throws IOException {
2764 mAgent = agent;
2765 mInfo = info;
2766 mToken = token;
2767
2768 // This class is used strictly for process-local binder invocations. The
2769 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2770 // do not automatically get a 'dup'ed descriptor that we can can continue
2771 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2772 // before proceeding to do the restore.
2773 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2774 }
2775
2776 @Override
2777 public void run() {
2778 try {
2779 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2780 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2781 mToken, mBackupManagerBinder);
2782 } catch (RemoteException e) {
2783 // never happens; this is used strictly for local binder calls
2784 }
2785 }
2786 }
2787
2788 @Override
2789 public void run() {
2790 Slog.i(TAG, "--- Performing full-dataset restore ---");
2791 sendStartRestore();
2792
Christopher Tateb0628bf2011-06-02 15:08:13 -07002793 // Are we able to restore shared-storage data?
2794 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2795 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2796 }
2797
Christopher Tate2efd2db2011-07-19 16:32:49 -07002798 FileInputStream rawInStream = null;
2799 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002800 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002801 if (hasBackupPassword()) {
2802 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2803 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2804 return;
2805 }
2806 }
2807
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002808 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002809 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002810 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2811 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002812
2813 // First, parse out the unencrypted/uncompressed header
2814 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002815 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002816 final InputStream in;
2817
2818 boolean okay = false;
2819 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2820 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002821 rawDataIn.readFully(streamHeader);
2822 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2823 if (Arrays.equals(magicBytes, streamHeader)) {
2824 // okay, header looks good. now parse out the rest of the fields.
2825 String s = readHeaderLine(rawInStream);
2826 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2827 // okay, it's a version we recognize
2828 s = readHeaderLine(rawInStream);
2829 compressed = (Integer.parseInt(s) != 0);
2830 s = readHeaderLine(rawInStream);
2831 if (s.equals("none")) {
2832 // no more header to parse; we're good to go
2833 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07002834 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002835 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
2836 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07002837 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002838 }
2839 } else Slog.w(TAG, "Archive is encrypted but no password given");
2840 } else Slog.w(TAG, "Wrong header version: " + s);
2841 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002842
2843 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002844 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002845 return;
2846 }
2847
2848 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07002849 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07002850
2851 boolean didRestore;
2852 do {
Christopher Tate7926a692011-07-11 11:31:57 -07002853 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07002854 } while (didRestore);
2855
Christopher Tatec58efa62011-08-01 19:20:14 -07002856 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002857 } catch (IOException e) {
2858 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07002859 } finally {
2860 tearDownPipes();
2861 tearDownAgent(mTargetApp);
2862
2863 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002864 if (rawDataIn != null) rawDataIn.close();
2865 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07002866 mInputFile.close();
2867 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002868 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002869 /* nothing we can do about this */
2870 }
2871 synchronized (mCurrentOpLock) {
2872 mCurrentOperations.clear();
2873 }
2874 synchronized (mLatchObject) {
2875 mLatchObject.set(true);
2876 mLatchObject.notifyAll();
2877 }
2878 sendEndRestore();
2879 mWakelock.release();
Christopher Tatec58efa62011-08-01 19:20:14 -07002880 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07002881 }
2882 }
2883
Christopher Tate7bdb0962011-07-13 19:30:21 -07002884 String readHeaderLine(InputStream in) throws IOException {
2885 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002886 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002887 while ((c = in.read()) >= 0) {
2888 if (c == '\n') break; // consume and discard the newlines
2889 buffer.append((char)c);
2890 }
2891 return buffer.toString();
2892 }
2893
Christopher Tate2efd2db2011-07-19 16:32:49 -07002894 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
2895 InputStream result = null;
2896 try {
2897 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
2898
2899 String userSaltHex = readHeaderLine(rawInStream); // 5
2900 byte[] userSalt = hexToByteArray(userSaltHex);
2901
2902 String ckSaltHex = readHeaderLine(rawInStream); // 6
2903 byte[] ckSalt = hexToByteArray(ckSaltHex);
2904
2905 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
2906 String userIvHex = readHeaderLine(rawInStream); // 8
2907
2908 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
2909
2910 // decrypt the master key blob
2911 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07002912 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002913 rounds);
2914 byte[] IV = hexToByteArray(userIvHex);
2915 IvParameterSpec ivSpec = new IvParameterSpec(IV);
2916 c.init(Cipher.DECRYPT_MODE,
2917 new SecretKeySpec(userKey.getEncoded(), "AES"),
2918 ivSpec);
2919 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
2920 byte[] mkBlob = c.doFinal(mkCipher);
2921
2922 // first, the master key IV
2923 int offset = 0;
2924 int len = mkBlob[offset++];
2925 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
2926 offset += len;
2927 // then the master key itself
2928 len = mkBlob[offset++];
2929 byte[] mk = Arrays.copyOfRange(mkBlob,
2930 offset, offset + len);
2931 offset += len;
2932 // and finally the master key checksum hash
2933 len = mkBlob[offset++];
2934 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
2935 offset, offset + len);
2936
2937 // now validate the decrypted master key against the checksum
2938 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
2939 if (Arrays.equals(calculatedCk, mkChecksum)) {
2940 ivSpec = new IvParameterSpec(IV);
2941 c.init(Cipher.DECRYPT_MODE,
2942 new SecretKeySpec(mk, "AES"),
2943 ivSpec);
2944 // Only if all of the above worked properly will 'result' be assigned
2945 result = new CipherInputStream(rawInStream, c);
2946 } else Slog.w(TAG, "Incorrect password");
2947 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
2948 } catch (InvalidAlgorithmParameterException e) {
2949 Slog.e(TAG, "Needed parameter spec unavailable!", e);
2950 } catch (BadPaddingException e) {
2951 // This case frequently occurs when the wrong password is used to decrypt
2952 // the master key. Use the identical "incorrect password" log text as is
2953 // used in the checksum failure log in order to avoid providing additional
2954 // information to an attacker.
2955 Slog.w(TAG, "Incorrect password");
2956 } catch (IllegalBlockSizeException e) {
2957 Slog.w(TAG, "Invalid block size in master key");
2958 } catch (NoSuchAlgorithmException e) {
2959 Slog.e(TAG, "Needed decryption algorithm unavailable!");
2960 } catch (NoSuchPaddingException e) {
2961 Slog.e(TAG, "Needed padding mechanism unavailable!");
2962 } catch (InvalidKeyException e) {
2963 Slog.w(TAG, "Illegal password; aborting");
2964 } catch (NumberFormatException e) {
2965 Slog.w(TAG, "Can't parse restore data header");
2966 } catch (IOException e) {
2967 Slog.w(TAG, "Can't read input header");
2968 }
2969
2970 return result;
2971 }
2972
Christopher Tate75a99702011-05-18 16:28:19 -07002973 boolean restoreOneFile(InputStream instream, byte[] buffer) {
2974 FileMetadata info;
2975 try {
2976 info = readTarHeaders(instream);
2977 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002978 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07002979 dumpFileMetadata(info);
2980 }
2981
2982 final String pkg = info.packageName;
2983 if (!pkg.equals(mAgentPackage)) {
2984 // okay, change in package; set up our various
2985 // bookkeeping if we haven't seen it yet
2986 if (!mPackagePolicies.containsKey(pkg)) {
2987 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2988 }
2989
2990 // Clean up the previous agent relationship if necessary,
2991 // and let the observer know we're considering a new app.
2992 if (mAgent != null) {
2993 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
2994 tearDownPipes();
2995 tearDownAgent(mTargetApp);
2996 mTargetApp = null;
2997 mAgentPackage = null;
2998 }
2999 }
3000
3001 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3002 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3003 mPackageInstallers.put(pkg, info.installerPackageName);
3004 // We've read only the manifest content itself at this point,
3005 // so consume the footer before looping around to the next
3006 // input file
3007 skipTarPadding(info.size, instream);
3008 sendOnRestorePackage(pkg);
3009 } else {
3010 // Non-manifest, so it's actual file data. Is this a package
3011 // we're ignoring?
3012 boolean okay = true;
3013 RestorePolicy policy = mPackagePolicies.get(pkg);
3014 switch (policy) {
3015 case IGNORE:
3016 okay = false;
3017 break;
3018
3019 case ACCEPT_IF_APK:
3020 // If we're in accept-if-apk state, then the first file we
3021 // see MUST be the apk.
3022 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3023 if (DEBUG) Slog.d(TAG, "APK file; installing");
3024 // Try to install the app.
3025 String installerName = mPackageInstallers.get(pkg);
3026 okay = installApk(info, installerName, instream);
3027 // good to go; promote to ACCEPT
3028 mPackagePolicies.put(pkg, (okay)
3029 ? RestorePolicy.ACCEPT
3030 : RestorePolicy.IGNORE);
3031 // At this point we've consumed this file entry
3032 // ourselves, so just strip the tar footer and
3033 // go on to the next file in the input stream
3034 skipTarPadding(info.size, instream);
3035 return true;
3036 } else {
3037 // File data before (or without) the apk. We can't
3038 // handle it coherently in this case so ignore it.
3039 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3040 okay = false;
3041 }
3042 break;
3043
3044 case ACCEPT:
3045 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3046 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3047 // we can take the data without the apk, so we
3048 // *want* to do so. skip the apk by declaring this
3049 // one file not-okay without changing the restore
3050 // policy for the package.
3051 okay = false;
3052 }
3053 break;
3054
3055 default:
3056 // Something has gone dreadfully wrong when determining
3057 // the restore policy from the manifest. Ignore the
3058 // rest of this package's data.
3059 Slog.e(TAG, "Invalid policy from manifest");
3060 okay = false;
3061 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3062 break;
3063 }
3064
3065 // If the policy is satisfied, go ahead and set up to pipe the
3066 // data to the agent.
3067 if (DEBUG && okay && mAgent != null) {
3068 Slog.i(TAG, "Reusing existing agent instance");
3069 }
3070 if (okay && mAgent == null) {
3071 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3072
3073 try {
3074 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3075
3076 // If we haven't sent any data to this app yet, we probably
3077 // need to clear it first. Check that.
3078 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003079 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003080 // responsible for coherently managing a full
3081 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003082 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003083 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3084 clearApplicationDataSynchronous(pkg);
3085 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003086 if (DEBUG) Slog.d(TAG, "backup agent ("
3087 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003088 }
3089 mClearedPackages.add(pkg);
3090 } else {
3091 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3092 }
3093
3094 // All set; now set up the IPC and launch the agent
3095 setUpPipes();
3096 mAgent = bindToAgentSynchronous(mTargetApp,
3097 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3098 mAgentPackage = pkg;
3099 } catch (IOException e) {
3100 // fall through to error handling
3101 } catch (NameNotFoundException e) {
3102 // fall through to error handling
3103 }
3104
3105 if (mAgent == null) {
3106 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3107 okay = false;
3108 tearDownPipes();
3109 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3110 }
3111 }
3112
3113 // Sanity check: make sure we never give data to the wrong app. This
3114 // should never happen but a little paranoia here won't go amiss.
3115 if (okay && !pkg.equals(mAgentPackage)) {
3116 Slog.e(TAG, "Restoring data for " + pkg
3117 + " but agent is for " + mAgentPackage);
3118 okay = false;
3119 }
3120
3121 // At this point we have an agent ready to handle the full
3122 // restore data as well as a pipe for sending data to
3123 // that agent. Tell the agent to start reading from the
3124 // pipe.
3125 if (okay) {
3126 boolean agentSuccess = true;
3127 long toCopy = info.size;
3128 final int token = generateToken();
3129 try {
3130 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3131 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003132 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003133 // fire up the app's agent listening on the socket. If
3134 // the agent is running in the system process we can't
3135 // just invoke it asynchronously, so we provide a thread
3136 // for it here.
3137 if (mTargetApp.processName.equals("system")) {
3138 Slog.d(TAG, "system process agent - spinning a thread");
3139 RestoreFileRunnable runner = new RestoreFileRunnable(
3140 mAgent, info, mPipes[0], token);
3141 new Thread(runner).start();
3142 } else {
3143 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3144 info.domain, info.path, info.mode, info.mtime,
3145 token, mBackupManagerBinder);
3146 }
3147 } catch (IOException e) {
3148 // couldn't dup the socket for a process-local restore
3149 Slog.d(TAG, "Couldn't establish restore");
3150 agentSuccess = false;
3151 okay = false;
3152 } catch (RemoteException e) {
3153 // whoops, remote agent went away. We'll eat the content
3154 // ourselves, then, and not copy it over.
3155 Slog.e(TAG, "Agent crashed during full restore");
3156 agentSuccess = false;
3157 okay = false;
3158 }
3159
3160 // Copy over the data if the agent is still good
3161 if (okay) {
3162 boolean pipeOkay = true;
3163 FileOutputStream pipe = new FileOutputStream(
3164 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003165 while (toCopy > 0) {
3166 int toRead = (toCopy > buffer.length)
3167 ? buffer.length : (int)toCopy;
3168 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003169 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003170 if (nRead <= 0) break;
3171 toCopy -= nRead;
3172
3173 // send it to the output pipe as long as things
3174 // are still good
3175 if (pipeOkay) {
3176 try {
3177 pipe.write(buffer, 0, nRead);
3178 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003179 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003180 pipeOkay = false;
3181 }
3182 }
3183 }
3184
3185 // done sending that file! Now we just need to consume
3186 // the delta from info.size to the end of block.
3187 skipTarPadding(info.size, instream);
3188
3189 // and now that we've sent it all, wait for the remote
3190 // side to acknowledge receipt
3191 agentSuccess = waitUntilOperationComplete(token);
3192 }
3193
3194 // okay, if the remote end failed at any point, deal with
3195 // it by ignoring the rest of the restore on it
3196 if (!agentSuccess) {
3197 mBackupHandler.removeMessages(MSG_TIMEOUT);
3198 tearDownPipes();
3199 tearDownAgent(mTargetApp);
3200 mAgent = null;
3201 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3202 }
3203 }
3204
3205 // Problems setting up the agent communication, or an already-
3206 // ignored package: skip to the next tar stream entry by
3207 // reading and discarding this file.
3208 if (!okay) {
3209 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3210 long bytesToConsume = (info.size + 511) & ~511;
3211 while (bytesToConsume > 0) {
3212 int toRead = (bytesToConsume > buffer.length)
3213 ? buffer.length : (int)bytesToConsume;
3214 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003215 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003216 if (nRead <= 0) break;
3217 bytesToConsume -= nRead;
3218 }
3219 }
3220 }
3221 }
3222 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003223 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003224 // treat as EOF
3225 info = null;
3226 }
3227
3228 return (info != null);
3229 }
3230
3231 void setUpPipes() throws IOException {
3232 mPipes = ParcelFileDescriptor.createPipe();
3233 }
3234
3235 void tearDownPipes() {
3236 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003237 try {
3238 mPipes[0].close();
3239 mPipes[0] = null;
3240 mPipes[1].close();
3241 mPipes[1] = null;
3242 } catch (IOException e) {
3243 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003244 }
3245 mPipes = null;
3246 }
3247 }
3248
3249 void tearDownAgent(ApplicationInfo app) {
3250 if (mAgent != null) {
3251 try {
3252 // unbind and tidy up even on timeout or failure, just in case
3253 mActivityManager.unbindBackupAgent(app);
3254
3255 // The agent was running with a stub Application object, so shut it down.
3256 // !!! We hardcode the confirmation UI's package name here rather than use a
3257 // manifest flag! TODO something less direct.
3258 if (app.uid != Process.SYSTEM_UID
3259 && !app.packageName.equals("com.android.backupconfirm")) {
3260 if (DEBUG) Slog.d(TAG, "Killing host process");
3261 mActivityManager.killApplicationProcess(app.processName, app.uid);
3262 } else {
3263 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3264 }
3265 } catch (RemoteException e) {
3266 Slog.d(TAG, "Lost app trying to shut down");
3267 }
3268 mAgent = null;
3269 }
3270 }
3271
3272 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3273 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003274 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003275 int mResult;
3276
3277 public void reset() {
3278 synchronized (mDone) {
3279 mDone.set(false);
3280 }
3281 }
3282
3283 public void waitForCompletion() {
3284 synchronized (mDone) {
3285 while (mDone.get() == false) {
3286 try {
3287 mDone.wait();
3288 } catch (InterruptedException e) { }
3289 }
3290 }
3291 }
3292
3293 int getResult() {
3294 return mResult;
3295 }
3296
3297 @Override
3298 public void packageInstalled(String packageName, int returnCode)
3299 throws RemoteException {
3300 synchronized (mDone) {
3301 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003302 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003303 mDone.set(true);
3304 mDone.notifyAll();
3305 }
3306 }
3307 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003308
3309 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3310 final AtomicBoolean mDone = new AtomicBoolean();
3311 int mResult;
3312
3313 public void reset() {
3314 synchronized (mDone) {
3315 mDone.set(false);
3316 }
3317 }
3318
3319 public void waitForCompletion() {
3320 synchronized (mDone) {
3321 while (mDone.get() == false) {
3322 try {
3323 mDone.wait();
3324 } catch (InterruptedException e) { }
3325 }
3326 }
3327 }
3328
3329 @Override
3330 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3331 synchronized (mDone) {
3332 mResult = returnCode;
3333 mDone.set(true);
3334 mDone.notifyAll();
3335 }
3336 }
3337 }
3338
Christopher Tate75a99702011-05-18 16:28:19 -07003339 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003340 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003341
3342 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3343 boolean okay = true;
3344
3345 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3346
3347 // The file content is an .apk file. Copy it out to a staging location and
3348 // attempt to install it.
3349 File apkFile = new File(mDataDir, info.packageName);
3350 try {
3351 FileOutputStream apkStream = new FileOutputStream(apkFile);
3352 byte[] buffer = new byte[32 * 1024];
3353 long size = info.size;
3354 while (size > 0) {
3355 long toRead = (buffer.length < size) ? buffer.length : size;
3356 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003357 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003358 apkStream.write(buffer, 0, didRead);
3359 size -= didRead;
3360 }
3361 apkStream.close();
3362
3363 // make sure the installer can read it
3364 apkFile.setReadable(true, false);
3365
3366 // Now install it
3367 Uri packageUri = Uri.fromFile(apkFile);
3368 mInstallObserver.reset();
3369 mPackageManager.installPackage(packageUri, mInstallObserver,
3370 PackageManager.INSTALL_REPLACE_EXISTING, installerPackage);
3371 mInstallObserver.waitForCompletion();
3372
3373 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3374 // The only time we continue to accept install of data even if the
3375 // apk install failed is if we had already determined that we could
3376 // accept the data regardless.
3377 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3378 okay = false;
3379 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003380 } else {
3381 // Okay, the install succeeded. Make sure it was the right app.
3382 boolean uninstall = false;
3383 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3384 Slog.w(TAG, "Restore stream claimed to include apk for "
3385 + info.packageName + " but apk was really "
3386 + mInstallObserver.mPackageName);
3387 // delete the package we just put in place; it might be fraudulent
3388 okay = false;
3389 uninstall = true;
3390 } else {
3391 try {
3392 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3393 PackageManager.GET_SIGNATURES);
3394 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3395 Slog.w(TAG, "Restore stream contains apk of package "
3396 + info.packageName + " but it disallows backup/restore");
3397 okay = false;
3398 } else {
3399 // So far so good -- do the signatures match the manifest?
3400 Signature[] sigs = mManifestSignatures.get(info.packageName);
3401 if (!signaturesMatch(sigs, pkg)) {
3402 Slog.w(TAG, "Installed app " + info.packageName
3403 + " signatures do not match restore manifest");
3404 okay = false;
3405 uninstall = true;
3406 }
3407 }
3408 } catch (NameNotFoundException e) {
3409 Slog.w(TAG, "Install of package " + info.packageName
3410 + " succeeded but now not found");
3411 okay = false;
3412 }
3413 }
3414
3415 // If we're not okay at this point, we need to delete the package
3416 // that we just installed.
3417 if (uninstall) {
3418 mDeleteObserver.reset();
3419 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3420 mDeleteObserver, 0);
3421 mDeleteObserver.waitForCompletion();
3422 }
Christopher Tate75a99702011-05-18 16:28:19 -07003423 }
3424 } catch (IOException e) {
3425 Slog.e(TAG, "Unable to transcribe restored apk for install");
3426 okay = false;
3427 } finally {
3428 apkFile.delete();
3429 }
3430
3431 return okay;
3432 }
3433
3434 // Given an actual file content size, consume the post-content padding mandated
3435 // by the tar format.
3436 void skipTarPadding(long size, InputStream instream) throws IOException {
3437 long partial = (size + 512) % 512;
3438 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003439 final int needed = 512 - (int)partial;
3440 byte[] buffer = new byte[needed];
3441 if (readExactly(instream, buffer, 0, needed) == needed) {
3442 mBytes += needed;
3443 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003444 }
3445 }
3446
3447 // Returns a policy constant; takes a buffer arg to reduce memory churn
3448 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3449 throws IOException {
3450 // Fail on suspiciously large manifest files
3451 if (info.size > 64 * 1024) {
3452 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3453 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003454
Christopher Tate75a99702011-05-18 16:28:19 -07003455 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003456 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3457 mBytes += info.size;
3458 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003459
3460 RestorePolicy policy = RestorePolicy.IGNORE;
3461 String[] str = new String[1];
3462 int offset = 0;
3463
3464 try {
3465 offset = extractLine(buffer, offset, str);
3466 int version = Integer.parseInt(str[0]);
3467 if (version == BACKUP_MANIFEST_VERSION) {
3468 offset = extractLine(buffer, offset, str);
3469 String manifestPackage = str[0];
3470 // TODO: handle <original-package>
3471 if (manifestPackage.equals(info.packageName)) {
3472 offset = extractLine(buffer, offset, str);
3473 version = Integer.parseInt(str[0]); // app version
3474 offset = extractLine(buffer, offset, str);
3475 int platformVersion = Integer.parseInt(str[0]);
3476 offset = extractLine(buffer, offset, str);
3477 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3478 offset = extractLine(buffer, offset, str);
3479 boolean hasApk = str[0].equals("1");
3480 offset = extractLine(buffer, offset, str);
3481 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003482 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003483 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003484 for (int i = 0; i < numSigs; i++) {
3485 offset = extractLine(buffer, offset, str);
3486 sigs[i] = new Signature(str[0]);
3487 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003488 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003489
3490 // Okay, got the manifest info we need...
3491 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003492 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3493 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003494 // Fall through to IGNORE if the app explicitly disallows backup
3495 final int flags = pkgInfo.applicationInfo.flags;
3496 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3497 // Verify signatures against any installed version; if they
3498 // don't match, then we fall though and ignore the data. The
3499 // signatureMatch() method explicitly ignores the signature
3500 // check for packages installed on the system partition, because
3501 // such packages are signed with the platform cert instead of
3502 // the app developer's cert, so they're different on every
3503 // device.
3504 if (signaturesMatch(sigs, pkgInfo)) {
3505 if (pkgInfo.versionCode >= version) {
3506 Slog.i(TAG, "Sig + version match; taking data");
3507 policy = RestorePolicy.ACCEPT;
3508 } else {
3509 // The data is from a newer version of the app than
3510 // is presently installed. That means we can only
3511 // use it if the matching apk is also supplied.
3512 Slog.d(TAG, "Data version " + version
3513 + " is newer than installed version "
3514 + pkgInfo.versionCode + " - requiring apk");
3515 policy = RestorePolicy.ACCEPT_IF_APK;
3516 }
Christopher Tate75a99702011-05-18 16:28:19 -07003517 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003518 Slog.w(TAG, "Restore manifest signatures do not match "
3519 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003520 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003521 } else {
3522 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3523 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003524 }
3525 } catch (NameNotFoundException e) {
3526 // Okay, the target app isn't installed. We can process
3527 // the restore properly only if the dataset provides the
3528 // apk file and we can successfully install it.
3529 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3530 + " not installed; requiring apk in dataset");
3531 policy = RestorePolicy.ACCEPT_IF_APK;
3532 }
3533
3534 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3535 Slog.i(TAG, "Cannot restore package " + info.packageName
3536 + " without the matching .apk");
3537 }
3538 } else {
3539 Slog.i(TAG, "Missing signature on backed-up package "
3540 + info.packageName);
3541 }
3542 } else {
3543 Slog.i(TAG, "Expected package " + info.packageName
3544 + " but restore manifest claims " + manifestPackage);
3545 }
3546 } else {
3547 Slog.i(TAG, "Unknown restore manifest version " + version
3548 + " for package " + info.packageName);
3549 }
3550 } catch (NumberFormatException e) {
3551 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003552 } catch (IllegalArgumentException e) {
3553 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003554 }
3555
3556 return policy;
3557 }
3558
3559 // Builds a line from a byte buffer starting at 'offset', and returns
3560 // the index of the next unconsumed data in the buffer.
3561 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3562 final int end = buffer.length;
3563 if (offset >= end) throw new IOException("Incomplete data");
3564
3565 int pos;
3566 for (pos = offset; pos < end; pos++) {
3567 byte c = buffer[pos];
3568 // at LF we declare end of line, and return the next char as the
3569 // starting point for the next time through
3570 if (c == '\n') {
3571 break;
3572 }
3573 }
3574 outStr[0] = new String(buffer, offset, pos - offset);
3575 pos++; // may be pointing an extra byte past the end but that's okay
3576 return pos;
3577 }
3578
3579 void dumpFileMetadata(FileMetadata info) {
3580 if (DEBUG) {
3581 StringBuilder b = new StringBuilder(128);
3582
3583 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003584 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003585 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3586 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3587 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3588 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3589 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3590 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3591 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3592 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3593 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3594 b.append(String.format(" %9d ", info.size));
3595
3596 Date stamp = new Date(info.mtime);
3597 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3598
3599 b.append(info.packageName);
3600 b.append(" :: ");
3601 b.append(info.domain);
3602 b.append(" :: ");
3603 b.append(info.path);
3604
3605 Slog.i(TAG, b.toString());
3606 }
3607 }
3608 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3609 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3610 byte[] block = new byte[512];
3611 FileMetadata info = null;
3612
3613 boolean gotHeader = readTarHeader(instream, block);
3614 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003615 try {
3616 // okay, presume we're okay, and extract the various metadata
3617 info = new FileMetadata();
3618 info.size = extractRadix(block, 124, 12, 8);
3619 info.mtime = extractRadix(block, 136, 12, 8);
3620 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003621
Christopher Tate2efd2db2011-07-19 16:32:49 -07003622 info.path = extractString(block, 345, 155); // prefix
3623 String path = extractString(block, 0, 100);
3624 if (path.length() > 0) {
3625 if (info.path.length() > 0) info.path += '/';
3626 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003627 }
Christopher Tate75a99702011-05-18 16:28:19 -07003628
Christopher Tate2efd2db2011-07-19 16:32:49 -07003629 // tar link indicator field: 1 byte at offset 156 in the header.
3630 int typeChar = block[156];
3631 if (typeChar == 'x') {
3632 // pax extended header, so we need to read that
3633 gotHeader = readPaxExtendedHeader(instream, info);
3634 if (gotHeader) {
3635 // and after a pax extended header comes another real header -- read
3636 // that to find the real file type
3637 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003638 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003639 if (!gotHeader) throw new IOException("Bad or missing pax header");
3640
3641 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003642 }
Christopher Tate75a99702011-05-18 16:28:19 -07003643
Christopher Tate2efd2db2011-07-19 16:32:49 -07003644 switch (typeChar) {
3645 case '0': info.type = BackupAgent.TYPE_FILE; break;
3646 case '5': {
3647 info.type = BackupAgent.TYPE_DIRECTORY;
3648 if (info.size != 0) {
3649 Slog.w(TAG, "Directory entry with nonzero size in header");
3650 info.size = 0;
3651 }
3652 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003653 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003654 case 0: {
3655 // presume EOF
3656 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3657 return null;
3658 }
3659 default: {
3660 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3661 throw new IOException("Unknown entity type " + typeChar);
3662 }
Christopher Tate75a99702011-05-18 16:28:19 -07003663 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003664
3665 // Parse out the path
3666 //
3667 // first: apps/shared/unrecognized
3668 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3669 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3670 // File in shared storage. !!! TODO: implement this.
3671 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
3672 info.packageName = "com.android.sharedstoragebackup";
3673 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3674 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3675 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3676 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3677 // App content! Parse out the package name and domain
3678
3679 // strip the apps/ prefix
3680 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3681
3682 // extract the package name
3683 int slash = info.path.indexOf('/');
3684 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3685 info.packageName = info.path.substring(0, slash);
3686 info.path = info.path.substring(slash+1);
3687
3688 // if it's a manifest we're done, otherwise parse out the domains
3689 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3690 slash = info.path.indexOf('/');
3691 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3692 info.domain = info.path.substring(0, slash);
3693 // validate that it's one of the domains we understand
3694 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3695 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3696 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3697 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3698 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3699 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3700 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3701 throw new IOException("Unrecognized domain " + info.domain);
3702 }
3703
3704 info.path = info.path.substring(slash + 1);
3705 }
3706 }
3707 } catch (IOException e) {
3708 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003709 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003710 HEXLOG(block);
3711 }
3712 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003713 }
3714 }
3715 return info;
3716 }
3717
Christopher Tate2efd2db2011-07-19 16:32:49 -07003718 private void HEXLOG(byte[] block) {
3719 int offset = 0;
3720 int todo = block.length;
3721 StringBuilder buf = new StringBuilder(64);
3722 while (todo > 0) {
3723 buf.append(String.format("%04x ", offset));
3724 int numThisLine = (todo > 16) ? 16 : todo;
3725 for (int i = 0; i < numThisLine; i++) {
3726 buf.append(String.format("%02x ", block[offset+i]));
3727 }
3728 Slog.i("hexdump", buf.toString());
3729 buf.setLength(0);
3730 todo -= numThisLine;
3731 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003732 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003733 }
3734
Christopher Tate6853fcf2011-08-10 17:52:21 -07003735 // Read exactly the given number of bytes into a buffer at the stated offset.
3736 // Returns false if EOF is encountered before the requested number of bytes
3737 // could be read.
3738 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3739 throws IOException {
3740 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3741
3742 int soFar = 0;
3743 while (soFar < size) {
3744 int nRead = in.read(buffer, offset + soFar, size - soFar);
3745 if (nRead <= 0) {
3746 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3747 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003748 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003749 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003750 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003751 return soFar;
3752 }
3753
3754 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3755 final int got = readExactly(instream, block, 0, 512);
3756 if (got == 0) return false; // Clean EOF
3757 if (got < 512) throw new IOException("Unable to read full block header");
3758 mBytes += 512;
3759 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003760 }
3761
3762 // overwrites 'info' fields based on the pax extended header
3763 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3764 throws IOException {
3765 // We should never see a pax extended header larger than this
3766 if (info.size > 32*1024) {
3767 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3768 + " - aborting");
3769 throw new IOException("Sanity failure: pax header size " + info.size);
3770 }
3771
3772 // read whole blocks, not just the content size
3773 int numBlocks = (int)((info.size + 511) >> 9);
3774 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003775 if (readExactly(instream, data, 0, data.length) < data.length) {
3776 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003777 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003778 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003779
3780 final int contentSize = (int) info.size;
3781 int offset = 0;
3782 do {
3783 // extract the line at 'offset'
3784 int eol = offset+1;
3785 while (eol < contentSize && data[eol] != ' ') eol++;
3786 if (eol >= contentSize) {
3787 // error: we just hit EOD looking for the end of the size field
3788 throw new IOException("Invalid pax data");
3789 }
3790 // eol points to the space between the count and the key
3791 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3792 int key = eol + 1; // start of key=value
3793 eol = offset + linelen - 1; // trailing LF
3794 int value;
3795 for (value = key+1; data[value] != '=' && value <= eol; value++);
3796 if (value > eol) {
3797 throw new IOException("Invalid pax declaration");
3798 }
3799
3800 // pax requires that key/value strings be in UTF-8
3801 String keyStr = new String(data, key, value-key, "UTF-8");
3802 // -1 to strip the trailing LF
3803 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3804
3805 if ("path".equals(keyStr)) {
3806 info.path = valStr;
3807 } else if ("size".equals(keyStr)) {
3808 info.size = Long.parseLong(valStr);
3809 } else {
3810 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3811 }
3812
3813 offset += linelen;
3814 } while (offset < contentSize);
3815
3816 return true;
3817 }
3818
3819 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3820 throws IOException {
3821 long value = 0;
3822 final int end = offset + maxChars;
3823 for (int i = offset; i < end; i++) {
3824 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003825 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003826 if (b == 0 || b == ' ') break;
3827 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003828 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07003829 }
3830 value = radix * value + (b - '0');
3831 }
3832 return value;
3833 }
3834
3835 String extractString(byte[] data, int offset, int maxChars) throws IOException {
3836 final int end = offset + maxChars;
3837 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003838 // tar string fields terminate early with a NUL
3839 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07003840 return new String(data, offset, eos-offset, "US-ASCII");
3841 }
3842
3843 void sendStartRestore() {
3844 if (mObserver != null) {
3845 try {
3846 mObserver.onStartRestore();
3847 } catch (RemoteException e) {
3848 Slog.w(TAG, "full restore observer went away: startRestore");
3849 mObserver = null;
3850 }
3851 }
3852 }
3853
3854 void sendOnRestorePackage(String name) {
3855 if (mObserver != null) {
3856 try {
3857 // TODO: use a more user-friendly name string
3858 mObserver.onRestorePackage(name);
3859 } catch (RemoteException e) {
3860 Slog.w(TAG, "full restore observer went away: restorePackage");
3861 mObserver = null;
3862 }
3863 }
3864 }
3865
3866 void sendEndRestore() {
3867 if (mObserver != null) {
3868 try {
3869 mObserver.onEndRestore();
3870 } catch (RemoteException e) {
3871 Slog.w(TAG, "full restore observer went away: endRestore");
3872 mObserver = null;
3873 }
3874 }
3875 }
3876 }
3877
Christopher Tatedf01dea2009-06-09 20:45:02 -07003878 // ----- Restore handling -----
3879
Christopher Tate78dd4a72009-11-04 11:49:08 -08003880 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
3881 // If the target resides on the system partition, we allow it to restore
3882 // data from the like-named package in a restore set even if the signatures
3883 // do not match. (Unlike general applications, those flashed to the system
3884 // partition will be signed with the device's platform certificate, so on
3885 // different phones the same system app will have different signatures.)
3886 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003887 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08003888 return true;
3889 }
3890
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003891 // Allow unsigned apps, but not signed on one device and unsigned on the other
3892 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08003893 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07003894 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07003895 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003896 if ((storedSigs == null || storedSigs.length == 0)
3897 && (deviceSigs == null || deviceSigs.length == 0)) {
3898 return true;
3899 }
3900 if (storedSigs == null || deviceSigs == null) {
3901 return false;
3902 }
3903
Christopher Tateabce4e82009-06-18 18:35:32 -07003904 // !!! TODO: this demands that every stored signature match one
3905 // that is present on device, and does not demand the converse.
3906 // Is this this right policy?
3907 int nStored = storedSigs.length;
3908 int nDevice = deviceSigs.length;
3909
3910 for (int i=0; i < nStored; i++) {
3911 boolean match = false;
3912 for (int j=0; j < nDevice; j++) {
3913 if (storedSigs[i].equals(deviceSigs[j])) {
3914 match = true;
3915 break;
3916 }
3917 }
3918 if (!match) {
3919 return false;
3920 }
3921 }
3922 return true;
3923 }
3924
Christopher Tate44a27902010-01-27 17:15:49 -08003925 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003926 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003927 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003928 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003929 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003930 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003931 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003932 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07003933 private HashSet<String> mFilterSet;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003934
Christopher Tate5cbbf562009-06-22 16:44:51 -07003935 class RestoreRequest {
3936 public PackageInfo app;
3937 public int storedAppVersion;
3938
3939 RestoreRequest(PackageInfo _app, int _version) {
3940 app = _app;
3941 storedAppVersion = _version;
3942 }
3943 }
3944
Christopher Tate44a27902010-01-27 17:15:49 -08003945 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07003946 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07003947 boolean needFullBackup, String[] filterSet) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003948 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003949 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003950 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08003951 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08003952 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003953 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003954
Christopher Tate284f1bb2011-07-07 14:31:18 -07003955 if (filterSet != null) {
3956 mFilterSet = new HashSet<String>();
3957 for (String pkg : filterSet) {
3958 mFilterSet.add(pkg);
3959 }
3960 } else {
3961 mFilterSet = null;
3962 }
3963
Christopher Tate5cb400b2009-06-25 16:03:14 -07003964 try {
3965 mStateDir = new File(mBaseStateDir, transport.transportDirName());
3966 } catch (RemoteException e) {
3967 // can't happen; the transport is local
3968 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003969 }
3970
Christopher Tatedf01dea2009-06-09 20:45:02 -07003971 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003972 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003973 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08003974 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate284f1bb2011-07-07 14:31:18 -07003975 + " mTargetPackage=" + mTargetPackage + " mFilterSet=" + mFilterSet
3976 + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003977
Christopher Tateb49ceb32010-02-08 16:22:24 -08003978 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003979 int error = -1; // assume error
3980
Dan Egnorefe52642009-06-24 00:16:33 -07003981 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07003982 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003983 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003984 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07003985
Dan Egnorefe52642009-06-24 00:16:33 -07003986 // Get the list of all packages which have backup enabled.
3987 // (Include the Package Manager metadata pseudo-package first.)
3988 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
3989 PackageInfo omPackage = new PackageInfo();
3990 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
3991 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003992
Dan Egnorefe52642009-06-24 00:16:33 -07003993 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003994 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07003995 // if there's a filter set, strip out anything that isn't
3996 // present before proceeding
3997 if (mFilterSet != null) {
3998 for (int i = agentPackages.size() - 1; i >= 0; i--) {
3999 final PackageInfo pkg = agentPackages.get(i);
4000 if (! mFilterSet.contains(pkg.packageName)) {
4001 agentPackages.remove(i);
4002 }
4003 }
4004 if (DEBUG) {
4005 Slog.i(TAG, "Post-filter package set for restore:");
4006 for (PackageInfo p : agentPackages) {
4007 Slog.i(TAG, " " + p);
4008 }
4009 }
4010 }
Christopher Tate84725812010-02-04 15:52:40 -08004011 restorePackages.addAll(agentPackages);
4012 } else {
4013 // Just one package to attempt restore of
4014 restorePackages.add(mTargetPackage);
4015 }
Dan Egnorefe52642009-06-24 00:16:33 -07004016
Christopher Tate7d562ec2009-06-25 18:03:43 -07004017 // let the observer know that we're running
4018 if (mObserver != null) {
4019 try {
4020 // !!! TODO: get an actual count from the transport after
4021 // its startRestore() runs?
4022 mObserver.restoreStarting(restorePackages.size());
4023 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004024 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004025 mObserver = null;
4026 }
4027 }
4028
Dan Egnor01445162009-09-21 17:04:05 -07004029 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
4030 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004031 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004032 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07004033 return;
4034 }
4035
4036 String packageName = mTransport.nextRestorePackage();
4037 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004038 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004039 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07004040 return;
4041 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004042 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07004043 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004044 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07004045 return;
4046 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004047 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07004048 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004049 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004050 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07004051 return;
4052 }
4053
4054 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08004055 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07004056 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07004057 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
4058 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07004059
Christopher Tate8c032472009-07-02 14:28:47 -07004060 // Verify that the backup set includes metadata. If not, we can't do
4061 // signature/version verification etc, so we simply do not proceed with
4062 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07004063 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004064 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004065 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004066 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07004067 return;
4068 }
4069
Christopher Tate7d562ec2009-06-25 18:03:43 -07004070 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07004071 for (;;) {
4072 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004073
Dan Egnorefe52642009-06-24 00:16:33 -07004074 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004075 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004076 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07004077 return;
4078 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004079 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07004080 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004081 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004082
Christopher Tate7d562ec2009-06-25 18:03:43 -07004083 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07004084 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07004085 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004086 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004087 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004088 mObserver = null;
4089 }
4090 }
4091
Dan Egnorefe52642009-06-24 00:16:33 -07004092 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
4093 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004094 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004095 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004096 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07004097 continue;
4098 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004099
Dan Egnorbb9001c2009-07-27 12:20:13 -07004100 PackageInfo packageInfo;
4101 try {
4102 int flags = PackageManager.GET_SIGNATURES;
4103 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4104 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004105 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004106 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004107 "Package missing on device");
4108 continue;
4109 }
4110
Dan Egnorefe52642009-06-24 00:16:33 -07004111 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08004112 // Data is from a "newer" version of the app than we have currently
4113 // installed. If the app has not declared that it is prepared to
4114 // handle this case, we do not attempt the restore.
4115 if ((packageInfo.applicationInfo.flags
4116 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4117 String message = "Version " + metaInfo.versionCode
4118 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004119 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08004120 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4121 packageName, message);
4122 continue;
4123 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004124 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08004125 + " > installed " + packageInfo.versionCode
4126 + " but restoreAnyVersion");
4127 }
Dan Egnorefe52642009-06-24 00:16:33 -07004128 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004129
Christopher Tate78dd4a72009-11-04 11:49:08 -08004130 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004131 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004132 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004133 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07004134 continue;
4135 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004136
Joe Onorato8a9b2202010-02-26 18:56:32 -08004137 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07004138 + " restore version [" + metaInfo.versionCode
4139 + "] is compatible with installed version ["
4140 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07004141
Christopher Tate3de55bc2010-03-12 17:28:08 -08004142 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07004143 IBackupAgent agent = bindToAgentSynchronous(
4144 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08004145 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004146 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004147 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004148 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004149 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07004150 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004151 }
4152
Christopher Tate5e1ab332009-09-01 20:32:49 -07004153 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07004154 try {
Chris Tate249345b2010-10-29 12:57:04 -07004155 processOneRestore(packageInfo, metaInfo.versionCode, agent,
4156 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004157 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07004158 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07004159 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07004160 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07004161
4162 // The agent was probably running with a stub Application object,
4163 // which isn't a valid run mode for the main app logic. Shut
4164 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08004165 // usual full initialization. Note that this is only done for
4166 // full-system restores: when a single app has requested a restore,
4167 // it is explicitly not killed following that operation.
4168 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07004169 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004170 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07004171 + packageInfo.applicationInfo.processName);
4172 mActivityManager.killApplicationProcess(
4173 packageInfo.applicationInfo.processName,
4174 packageInfo.applicationInfo.uid);
4175 }
Dan Egnorefe52642009-06-24 00:16:33 -07004176 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004177 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004178
4179 // if we get this far, report success to the observer
4180 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07004181 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004182 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004183 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004184 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07004185 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004186 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004187
Dan Egnorefe52642009-06-24 00:16:33 -07004188 try {
4189 mTransport.finishRestore();
4190 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004191 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07004192 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004193
4194 if (mObserver != null) {
4195 try {
4196 mObserver.restoreFinished(error);
4197 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004198 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004199 }
4200 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004201
Christopher Tate84725812010-02-04 15:52:40 -08004202 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08004203 // ancestral dataset, as well as the set of apps that are possibly
4204 // restoreable from the dataset
4205 if (mTargetPackage == null && pmAgent != null) {
4206 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004207 mAncestralToken = mToken;
4208 writeRestoreTokens();
4209 }
4210
Christopher Tate1bb69062010-02-19 17:02:12 -08004211 // We must under all circumstances tell the Package Manager to
4212 // proceed with install notifications if it's waiting for us.
4213 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004214 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08004215 try {
4216 mPackageManagerBinder.finishPackageInstall(mPmToken);
4217 } catch (RemoteException e) { /* can't happen */ }
4218 }
4219
Christopher Tate73a3cb32010-12-13 18:27:26 -08004220 // Furthermore we need to reset the session timeout clock
4221 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4222 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4223 TIMEOUT_RESTORE_INTERVAL);
4224
Christopher Tateb6787f22009-07-02 17:40:45 -07004225 // done; we can finally release the wakelock
4226 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004227 }
4228 }
4229
Dan Egnorefe52642009-06-24 00:16:33 -07004230 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07004231 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
4232 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004233 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07004234 final String packageName = app.packageName;
4235
Joe Onorato8a9b2202010-02-26 18:56:32 -08004236 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004237
Christopher Tatec7b31e32009-06-10 15:49:30 -07004238 // !!! TODO: get the dirs from the transport
4239 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07004240 File newStateName = new File(mStateDir, packageName + ".new");
4241 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004242
Dan Egnorbb9001c2009-07-27 12:20:13 -07004243 ParcelFileDescriptor backupData = null;
4244 ParcelFileDescriptor newState = null;
4245
Christopher Tate4a627c72011-04-01 14:43:32 -07004246 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004247 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004248 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07004249 backupData = ParcelFileDescriptor.open(backupDataName,
4250 ParcelFileDescriptor.MODE_READ_WRITE |
4251 ParcelFileDescriptor.MODE_CREATE |
4252 ParcelFileDescriptor.MODE_TRUNCATE);
4253
Dan Egnor01445162009-09-21 17:04:05 -07004254 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004255 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004256 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004257 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004258 }
4259
4260 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07004261 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07004262 backupData = ParcelFileDescriptor.open(backupDataName,
4263 ParcelFileDescriptor.MODE_READ_ONLY);
4264
Dan Egnorbb9001c2009-07-27 12:20:13 -07004265 newState = ParcelFileDescriptor.open(newStateName,
4266 ParcelFileDescriptor.MODE_READ_WRITE |
4267 ParcelFileDescriptor.MODE_CREATE |
4268 ParcelFileDescriptor.MODE_TRUNCATE);
4269
Christopher Tate44a27902010-01-27 17:15:49 -08004270 // Kick off the restore, checking for hung agents
Christopher Tate8e294d42011-08-31 20:37:12 -07004271 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, null);
Christopher Tate44a27902010-01-27 17:15:49 -08004272 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
4273 boolean success = waitUntilOperationComplete(token);
4274
4275 if (!success) {
4276 throw new RuntimeException("restore timeout");
4277 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004278
4279 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07004280 //
4281 // !!! TODO: the restored data should be migrated on the server
4282 // side into the current dataset. In that case the new state file
4283 // we just created would reflect the data already extant in the
4284 // backend, so there'd be nothing more to do. Until that happens,
4285 // however, we need to make sure that we record the data to the
4286 // current backend dataset. (Yes, this means shipping the data over
4287 // the wire in both directions. That's bad, but consistency comes
4288 // first, then efficiency.) Once we introduce server-side data
4289 // migration to the newly-restored device's dataset, we will change
4290 // the following from a discard of the newly-written state to the
4291 // "correct" operation of renaming into the canonical state blob.
4292 newStateName.delete(); // TODO: remove; see above comment
4293 //newStateName.renameTo(savedStateName); // TODO: replace with this
4294
Dan Egnorbb9001c2009-07-27 12:20:13 -07004295 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004296 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004297 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004298 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004299 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07004300
Christopher Tate96733042009-07-20 14:49:13 -07004301 // If the agent fails restore, it might have put the app's data
4302 // into an incoherent state. For consistency we wipe its data
4303 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07004304 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07004305 } finally {
4306 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004307 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
4308 try { if (newState != null) newState.close(); } catch (IOException e) {}
4309 backupData = newState = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07004310 synchronized (mCurrentOperations) {
4311 mCurrentOperations.delete(token);
4312 }
Chris Tate249345b2010-10-29 12:57:04 -07004313
4314 // If we know a priori that we'll need to perform a full post-restore backup
4315 // pass, clear the new state file data. This means we're discarding work that
4316 // was just done by the app's agent, but this way the agent doesn't need to
4317 // take any special action based on global device state.
4318 if (needFullBackup) {
4319 newStateName.delete();
4320 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004321 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004322 }
4323 }
4324
Christopher Tate44a27902010-01-27 17:15:49 -08004325 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004326 IBackupTransport mTransport;
4327 PackageInfo mPackage;
4328
Christopher Tate44a27902010-01-27 17:15:49 -08004329 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004330 mTransport = transport;
4331 mPackage = packageInfo;
4332 }
4333
Christopher Tateee0e78a2009-07-02 11:17:03 -07004334 public void run() {
4335 try {
4336 // Clear the on-device backup state to ensure a full backup next time
4337 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4338 File stateFile = new File(stateDir, mPackage.packageName);
4339 stateFile.delete();
4340
4341 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004342 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004343 mTransport.clearBackupData(mPackage);
4344 } catch (RemoteException e) {
4345 // can't happen; the transport is local
4346 } finally {
4347 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004348 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004349 mTransport.finishBackup();
4350 } catch (RemoteException e) {
4351 // can't happen; the transport is local
4352 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004353
4354 // Last but not least, release the cpu
4355 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004356 }
4357 }
4358 }
4359
Christopher Tate44a27902010-01-27 17:15:49 -08004360 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004361 HashSet<String> mQueue;
4362
Christopher Tate44a27902010-01-27 17:15:49 -08004363 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004364 mQueue = transportNames;
4365 }
4366
Christopher Tate4cc86e12009-09-21 19:36:51 -07004367 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004368 try {
4369 for (String transportName : mQueue) {
4370 IBackupTransport transport = getTransport(transportName);
4371 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004372 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004373 continue;
4374 }
4375
Joe Onorato8a9b2202010-02-26 18:56:32 -08004376 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004377 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004378 long startRealtime = SystemClock.elapsedRealtime();
4379 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004380
Christopher Tate4cc86e12009-09-21 19:36:51 -07004381 if (status == BackupConstants.TRANSPORT_OK) {
4382 status = transport.finishBackup();
4383 }
4384
4385 // Okay, the wipe really happened. Clean up our local bookkeeping.
4386 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004387 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004388 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004389 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004390 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004391 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004392 synchronized (mQueueLock) {
4393 recordInitPendingLocked(false, transportName);
4394 }
Dan Egnor726247c2009-09-29 19:12:31 -07004395 } else {
4396 // If this didn't work, requeue this one and try again
4397 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004398 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004399 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004400 synchronized (mQueueLock) {
4401 recordInitPendingLocked(true, transportName);
4402 }
4403 // do this via another alarm to make sure of the wakelock states
4404 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004405 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004406 + transportName + " resched in " + delay);
4407 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4408 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004409 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004410 }
4411 } catch (RemoteException e) {
4412 // can't happen; the transports are local
4413 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004414 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004415 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004416 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004417 mWakelock.release();
4418 }
4419 }
4420 }
4421
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004422 private void dataChangedImpl(String packageName) {
4423 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4424 dataChangedImpl(packageName, targets);
4425 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004426
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004427 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004428 // Record that we need a backup pass for the caller. Since multiple callers
4429 // may share a uid, we need to note all candidates within that uid and schedule
4430 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004431 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004432
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004433 if (targets == null) {
4434 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4435 + " uid=" + Binder.getCallingUid());
4436 return;
4437 }
4438
4439 synchronized (mQueueLock) {
4440 // Note that this client has made data changes that need to be backed up
4441 for (ApplicationInfo app : targets) {
4442 // validate the caller-supplied package name against the known set of
4443 // packages associated with this uid
4444 if (app.packageName.equals(packageName)) {
4445 // Add the caller to the set of pending backups. If there is
4446 // one already there, then overwrite it, but no harm done.
Christopher Tatecc55f812011-08-16 16:06:53 -07004447 BackupRequest req = new BackupRequest(packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08004448 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004449 // Journal this request in case of crash. The put()
4450 // operation returned null when this package was not already
4451 // in the set; we want to avoid touching the disk redundantly.
4452 writeToJournalLocked(packageName);
4453
Christopher Tatec58efa62011-08-01 19:20:14 -07004454 if (MORE_DEBUG) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004455 int numKeys = mPendingBackups.size();
4456 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4457 for (BackupRequest b : mPendingBackups.values()) {
Christopher Tatecc55f812011-08-16 16:06:53 -07004458 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004459 }
4460 }
4461 }
4462 }
4463 }
4464 }
4465 }
4466
4467 // Note: packageName is currently unused, but may be in the future
4468 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004469 // If the caller does not hold the BACKUP permission, it can only request a
4470 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004471 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004472 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004473 synchronized (mBackupParticipants) {
4474 return mBackupParticipants.get(Binder.getCallingUid());
4475 }
4476 }
4477
4478 // a caller with full permission can ask to back up any participating app
4479 // !!! TODO: allow backup of ANY app?
4480 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4481 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004482 int N = mBackupParticipants.size();
4483 for (int i = 0; i < N; i++) {
4484 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4485 if (s != null) {
4486 targets.addAll(s);
4487 }
4488 }
4489 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004490 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004491 }
Christopher Tate46758122009-05-06 11:22:00 -07004492
Christopher Tatecde87f42009-06-12 12:55:53 -07004493 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004494 RandomAccessFile out = null;
4495 try {
4496 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4497 out = new RandomAccessFile(mJournal, "rws");
4498 out.seek(out.length());
4499 out.writeUTF(str);
4500 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004501 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004502 mJournal = null;
4503 } finally {
4504 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004505 }
4506 }
4507
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004508 // ----- IBackupManager binder interface -----
4509
4510 public void dataChanged(final String packageName) {
4511 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4512 if (targets == null) {
4513 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4514 + " uid=" + Binder.getCallingUid());
4515 return;
4516 }
4517
4518 mBackupHandler.post(new Runnable() {
4519 public void run() {
4520 dataChangedImpl(packageName, targets);
4521 }
4522 });
4523 }
4524
Christopher Tateee0e78a2009-07-02 11:17:03 -07004525 // Clear the given package's backup data from the current transport
4526 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004527 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004528 PackageInfo info;
4529 try {
4530 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4531 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004532 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004533 return;
4534 }
4535
4536 // If the caller does not hold the BACKUP permission, it can only request a
4537 // wipe of its own backed-up data.
4538 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004539 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004540 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4541 apps = mBackupParticipants.get(Binder.getCallingUid());
4542 } else {
4543 // a caller with full permission can ask to back up any participating app
4544 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004545 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004546 apps = new HashSet<ApplicationInfo>();
4547 int N = mBackupParticipants.size();
4548 for (int i = 0; i < N; i++) {
4549 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4550 if (s != null) {
4551 apps.addAll(s);
4552 }
4553 }
4554 }
4555
4556 // now find the given package in the set of candidate apps
4557 for (ApplicationInfo app : apps) {
4558 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004559 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004560 // found it; fire off the clear request
4561 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004562 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004563 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004564 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4565 new ClearParams(getTransport(mCurrentTransport), info));
4566 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004567 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004568 }
4569 break;
4570 }
4571 }
4572 }
4573
Christopher Tateace7f092009-06-15 18:07:25 -07004574 // Run a backup pass immediately for any applications that have declared
4575 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004576 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004577 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004578
Joe Onorato8a9b2202010-02-26 18:56:32 -08004579 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004580 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004581 // Because the alarms we are using can jitter, and we want an *immediate*
4582 // backup pass to happen, we restart the timer beginning with "next time,"
4583 // then manually fire the backup trigger intent ourselves.
4584 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004585 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004586 mRunBackupIntent.send();
4587 } catch (PendingIntent.CanceledException e) {
4588 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004589 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004590 }
Christopher Tate46758122009-05-06 11:22:00 -07004591 }
4592 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004593
Christopher Tate4a627c72011-04-01 14:43:32 -07004594 // Run a *full* backup pass for the given package, writing the resulting data stream
4595 // to the supplied file descriptor. This method is synchronous and does not return
4596 // to the caller until the backup has been completed.
4597 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
4598 boolean doAllApps, String[] pkgList) {
4599 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4600
4601 // Validate
4602 if (!doAllApps) {
4603 if (!includeShared) {
4604 // If we're backing up shared data (sdcard or equivalent), then we can run
4605 // without any supplied app names. Otherwise, we'd be doing no work, so
4606 // report the error.
4607 if (pkgList == null || pkgList.length == 0) {
4608 throw new IllegalArgumentException(
4609 "Backup requested but neither shared nor any apps named");
4610 }
4611 }
4612 }
4613
4614 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4615 + " shared=" + includeShared + " all=" + doAllApps
4616 + " pkgs=" + pkgList);
4617
4618 long oldId = Binder.clearCallingIdentity();
4619 try {
4620 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
4621 doAllApps, pkgList);
4622 final int token = generateToken();
4623 synchronized (mFullConfirmations) {
4624 mFullConfirmations.put(token, params);
4625 }
4626
Christopher Tate75a99702011-05-18 16:28:19 -07004627 // start up the confirmation UI
4628 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4629 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4630 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004631 mFullConfirmations.delete(token);
4632 return;
4633 }
Christopher Tate75a99702011-05-18 16:28:19 -07004634
4635 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004636 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4637
4638 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07004639 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004640
4641 // wait for the backup to be performed
4642 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
4643 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004644 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07004645 try {
4646 fd.close();
4647 } catch (IOException e) {
4648 // just eat it
4649 }
Christopher Tate75a99702011-05-18 16:28:19 -07004650 Binder.restoreCallingIdentity(oldId);
Christopher Tate4a627c72011-04-01 14:43:32 -07004651 }
Christopher Tatec58efa62011-08-01 19:20:14 -07004652 if (MORE_DEBUG) Slog.d(TAG, "Full backup done; returning to caller");
Christopher Tate75a99702011-05-18 16:28:19 -07004653 }
4654
4655 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004656 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07004657 Slog.i(TAG, "Beginning full restore...");
4658
4659 long oldId = Binder.clearCallingIdentity();
4660
4661 try {
4662 FullRestoreParams params = new FullRestoreParams(fd);
4663 final int token = generateToken();
4664 synchronized (mFullConfirmations) {
4665 mFullConfirmations.put(token, params);
4666 }
4667
4668 // start up the confirmation UI
4669 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
4670 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
4671 Slog.e(TAG, "Unable to launch full restore confirmation");
4672 mFullConfirmations.delete(token);
4673 return;
4674 }
4675
4676 // make sure the screen is lit for the user interaction
4677 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4678
4679 // start the confirmation countdown
4680 startConfirmationTimeout(token, params);
4681
4682 // wait for the restore to be performed
4683 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
4684 waitForCompletion(params);
4685 } finally {
4686 try {
4687 fd.close();
4688 } catch (IOException e) {
4689 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
4690 }
4691 Binder.restoreCallingIdentity(oldId);
4692 Slog.i(TAG, "Full restore completed");
4693 }
4694 }
4695
4696 boolean startConfirmationUi(int token, String action) {
4697 try {
4698 Intent confIntent = new Intent(action);
4699 confIntent.setClassName("com.android.backupconfirm",
4700 "com.android.backupconfirm.BackupRestoreConfirmation");
4701 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
4702 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4703 mContext.startActivity(confIntent);
4704 } catch (ActivityNotFoundException e) {
4705 return false;
4706 }
4707 return true;
4708 }
4709
4710 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07004711 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07004712 + TIMEOUT_FULL_CONFIRMATION + " millis");
4713 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
4714 token, 0, params);
4715 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07004716 }
4717
4718 void waitForCompletion(FullParams params) {
4719 synchronized (params.latch) {
4720 while (params.latch.get() == false) {
4721 try {
4722 params.latch.wait();
4723 } catch (InterruptedException e) { /* never interrupted */ }
4724 }
4725 }
4726 }
4727
4728 void signalFullBackupRestoreCompletion(FullParams params) {
4729 synchronized (params.latch) {
4730 params.latch.set(true);
4731 params.latch.notifyAll();
4732 }
4733 }
4734
4735 // Confirm that the previously-requested full backup/restore operation can proceed. This
4736 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07004737 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07004738 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07004739 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004740 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
4741 + " allow=" + allow);
4742
4743 // TODO: possibly require not just this signature-only permission, but even
4744 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07004745 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07004746
4747 long oldId = Binder.clearCallingIdentity();
4748 try {
4749
4750 FullParams params;
4751 synchronized (mFullConfirmations) {
4752 params = mFullConfirmations.get(token);
4753 if (params != null) {
4754 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
4755 mFullConfirmations.delete(token);
4756
4757 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004758 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07004759 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07004760 : MSG_RUN_FULL_RESTORE;
4761
Christopher Tate728a1c42011-07-28 18:03:03 -07004762 params.observer = observer;
4763 params.curPassword = curPassword;
4764 params.encryptPassword = encPpassword;
4765
Christopher Tate75a99702011-05-18 16:28:19 -07004766 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07004767 mWakelock.acquire();
4768 Message msg = mBackupHandler.obtainMessage(verb, params);
4769 mBackupHandler.sendMessage(msg);
4770 } else {
4771 Slog.w(TAG, "User rejected full backup/restore operation");
4772 // indicate completion without having actually transferred any data
4773 signalFullBackupRestoreCompletion(params);
4774 }
4775 } else {
4776 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
4777 }
4778 }
4779 } finally {
4780 Binder.restoreCallingIdentity(oldId);
4781 }
4782 }
4783
Christopher Tate8031a3d2009-07-06 16:36:05 -07004784 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07004785 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004786 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004787 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004788
Joe Onorato8a9b2202010-02-26 18:56:32 -08004789 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004790
Christopher Tate6ef58a12009-06-29 14:56:28 -07004791 boolean wasEnabled = mEnabled;
4792 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07004793 Settings.Secure.putInt(mContext.getContentResolver(),
4794 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07004795 mEnabled = enable;
4796 }
4797
Christopher Tate49401dd2009-07-01 12:34:29 -07004798 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07004799 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07004800 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07004801 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07004802 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004803 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004804 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004805
Christopher Tateb6787f22009-07-02 17:40:45 -07004806 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004807
4808 // This also constitutes an opt-out, so we wipe any data for
4809 // this device from the backend. We start that process with
4810 // an alarm in order to guarantee wakelock states.
4811 if (wasEnabled && mProvisioned) {
4812 // NOTE: we currently flush every registered transport, not just
4813 // the currently-active one.
4814 HashSet<String> allTransports;
4815 synchronized (mTransports) {
4816 allTransports = new HashSet<String>(mTransports.keySet());
4817 }
4818 // build the set of transports for which we are posting an init
4819 for (String transport : allTransports) {
4820 recordInitPendingLocked(true, transport);
4821 }
4822 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
4823 mRunInitIntent);
4824 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004825 }
4826 }
Christopher Tate49401dd2009-07-01 12:34:29 -07004827 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004828
Christopher Tatecce9da52010-02-03 15:11:15 -08004829 // Enable/disable automatic restore of app data at install time
4830 public void setAutoRestore(boolean doAutoRestore) {
4831 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004832 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08004833
Joe Onorato8a9b2202010-02-26 18:56:32 -08004834 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08004835
4836 synchronized (this) {
4837 Settings.Secure.putInt(mContext.getContentResolver(),
4838 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
4839 mAutoRestore = doAutoRestore;
4840 }
4841 }
4842
Christopher Tate8031a3d2009-07-06 16:36:05 -07004843 // Mark the backup service as having been provisioned
4844 public void setBackupProvisioned(boolean available) {
4845 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4846 "setBackupProvisioned");
4847
4848 boolean wasProvisioned = mProvisioned;
4849 synchronized (this) {
4850 Settings.Secure.putInt(mContext.getContentResolver(),
4851 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
4852 mProvisioned = available;
4853 }
4854
4855 synchronized (mQueueLock) {
4856 if (available && !wasProvisioned && mEnabled) {
4857 // we're now good to go, so start the backup alarms
4858 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
4859 } else if (!available) {
4860 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004861 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07004862 mAlarmManager.cancel(mRunBackupIntent);
4863 }
4864 }
4865 }
4866
4867 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07004868 // We used to use setInexactRepeating(), but that may be linked to
4869 // backups running at :00 more often than not, creating load spikes.
4870 // Schedule at an exact time for now, and also add a bit of "fuzz".
4871
4872 Random random = new Random();
4873 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
4874 random.nextInt(FUZZ_MILLIS);
4875 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
4876 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07004877 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07004878 }
4879
Christopher Tate6ef58a12009-06-29 14:56:28 -07004880 // Report whether the backup mechanism is currently enabled
4881 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04004882 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004883 return mEnabled; // no need to synchronize just to read it
4884 }
4885
Christopher Tate91717492009-06-26 21:07:13 -07004886 // Report the name of the currently active transport
4887 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04004888 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004889 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07004890 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07004891 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07004892 }
4893
Christopher Tate91717492009-06-26 21:07:13 -07004894 // Report all known, available backup transports
4895 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07004896 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07004897
Christopher Tate91717492009-06-26 21:07:13 -07004898 String[] list = null;
4899 ArrayList<String> known = new ArrayList<String>();
4900 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
4901 if (entry.getValue() != null) {
4902 known.add(entry.getKey());
4903 }
4904 }
4905
4906 if (known.size() > 0) {
4907 list = new String[known.size()];
4908 known.toArray(list);
4909 }
4910 return list;
4911 }
4912
4913 // Select which transport to use for the next backup operation. If the given
4914 // name is not one of the available transports, no action is taken and the method
4915 // returns null.
4916 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04004917 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07004918
4919 synchronized (mTransports) {
4920 String prevTransport = null;
4921 if (mTransports.get(transport) != null) {
4922 prevTransport = mCurrentTransport;
4923 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07004924 Settings.Secure.putString(mContext.getContentResolver(),
4925 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004926 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07004927 + " returning " + prevTransport);
4928 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004929 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07004930 }
4931 return prevTransport;
4932 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004933 }
4934
Christopher Tatef5e1c292010-12-08 18:40:26 -08004935 // Supply the configuration Intent for the given transport. If the name is not one
4936 // of the available transports, or if the transport does not supply any configuration
4937 // UI, the method returns null.
4938 public Intent getConfigurationIntent(String transportName) {
4939 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4940 "getConfigurationIntent");
4941
4942 synchronized (mTransports) {
4943 final IBackupTransport transport = mTransports.get(transportName);
4944 if (transport != null) {
4945 try {
4946 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07004947 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08004948 + intent);
4949 return intent;
4950 } catch (RemoteException e) {
4951 /* fall through to return null */
4952 }
4953 }
4954 }
4955
4956 return null;
4957 }
4958
4959 // Supply the configuration summary string for the given transport. If the name is
4960 // not one of the available transports, or if the transport does not supply any
4961 // summary / destination string, the method can return null.
4962 //
4963 // This string is used VERBATIM as the summary text of the relevant Settings item!
4964 public String getDestinationString(String transportName) {
4965 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004966 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08004967
4968 synchronized (mTransports) {
4969 final IBackupTransport transport = mTransports.get(transportName);
4970 if (transport != null) {
4971 try {
4972 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07004973 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08004974 return text;
4975 } catch (RemoteException e) {
4976 /* fall through to return null */
4977 }
4978 }
4979 }
4980
4981 return null;
4982 }
4983
Christopher Tate043dadc2009-06-02 16:11:00 -07004984 // Callback: a requested backup agent has been instantiated. This should only
4985 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004986 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07004987 synchronized(mAgentConnectLock) {
4988 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004989 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07004990 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
4991 mConnectedAgent = agent;
4992 mConnecting = false;
4993 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004994 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004995 + " claiming agent connected");
4996 }
4997 mAgentConnectLock.notifyAll();
4998 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004999 }
5000
5001 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5002 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005003 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005004 public void agentDisconnected(String packageName) {
5005 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005006 synchronized(mAgentConnectLock) {
5007 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5008 mConnectedAgent = null;
5009 mConnecting = false;
5010 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005011 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005012 + " claiming agent disconnected");
5013 }
5014 mAgentConnectLock.notifyAll();
5015 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005016 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005017
Christopher Tate1bb69062010-02-19 17:02:12 -08005018 // An application being installed will need a restore pass, then the Package Manager
5019 // will need to be told when the restore is finished.
5020 public void restoreAtInstall(String packageName, int token) {
5021 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005022 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005023 + " attemping install-time restore");
5024 return;
5025 }
5026
5027 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005028 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08005029 + " token=" + Integer.toHexString(token));
5030
Christopher Tatef0872722010-02-25 15:22:48 -08005031 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005032 // okay, we're going to attempt a restore of this package from this restore set.
5033 // The eventual message back into the Package Manager to run the post-install
5034 // steps for 'token' will be issued from the restore handling code.
5035
5036 // We can use a synthetic PackageInfo here because:
5037 // 1. We know it's valid, since the Package Manager supplied the name
5038 // 2. Only the packageName field will be used by the restore code
5039 PackageInfo pkg = new PackageInfo();
5040 pkg.packageName = packageName;
5041
5042 mWakelock.acquire();
5043 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5044 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005045 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005046 mBackupHandler.sendMessage(msg);
5047 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005048 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5049 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005050 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005051 try {
5052 mPackageManagerBinder.finishPackageInstall(token);
5053 } catch (RemoteException e) { /* can't happen */ }
5054 }
5055 }
5056
Christopher Tate8c850b72009-06-07 19:33:20 -07005057 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005058 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5059 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5060 + " transport=" + transport);
5061
5062 boolean needPermission = true;
5063 if (transport == null) {
5064 transport = mCurrentTransport;
5065
5066 if (packageName != null) {
5067 PackageInfo app = null;
5068 try {
5069 app = mPackageManager.getPackageInfo(packageName, 0);
5070 } catch (NameNotFoundException nnf) {
5071 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5072 throw new IllegalArgumentException("Package " + packageName + " not found");
5073 }
5074
5075 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5076 // So: using the current active transport, and the caller has asked
5077 // that its own package will be restored. In this narrow use case
5078 // we do not require the caller to hold the permission.
5079 needPermission = false;
5080 }
5081 }
5082 }
5083
5084 if (needPermission) {
5085 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5086 "beginRestoreSession");
5087 } else {
5088 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5089 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005090
5091 synchronized(this) {
5092 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005093 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005094 return null;
5095 }
Chris Tate44ab8452010-11-16 15:10:49 -08005096 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005097 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005098 }
5099 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005100 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005101
Christopher Tate73a3cb32010-12-13 18:27:26 -08005102 void clearRestoreSession(ActiveRestoreSession currentSession) {
5103 synchronized(this) {
5104 if (currentSession != mActiveRestoreSession) {
5105 Slog.e(TAG, "ending non-current restore session");
5106 } else {
5107 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5108 mActiveRestoreSession = null;
5109 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5110 }
5111 }
5112 }
5113
Christopher Tate44a27902010-01-27 17:15:49 -08005114 // Note that a currently-active backup agent has notified us that it has
5115 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005116 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005117 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005118 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5119 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005120 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005121 op = mCurrentOperations.get(token);
5122 if (op != null) {
5123 op.state = OP_ACKNOWLEDGED;
5124 }
Christopher Tate44a27902010-01-27 17:15:49 -08005125 mCurrentOpLock.notifyAll();
5126 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005127
5128 // The completion callback, if any, is invoked on the handler
5129 if (op != null && op.callback != null) {
5130 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5131 mBackupHandler.sendMessage(msg);
5132 }
Christopher Tate44a27902010-01-27 17:15:49 -08005133 }
5134
Christopher Tate9b3905c2009-06-08 15:24:01 -07005135 // ----- Restore session -----
5136
Christopher Tate80202c82010-01-25 19:37:47 -08005137 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005138 private static final String TAG = "RestoreSession";
5139
Chris Tate44ab8452010-11-16 15:10:49 -08005140 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005141 private IBackupTransport mRestoreTransport = null;
5142 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005143 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005144
Chris Tate44ab8452010-11-16 15:10:49 -08005145 ActiveRestoreSession(String packageName, String transport) {
5146 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005147 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005148 }
5149
5150 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005151 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005152 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005153 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005154 if (observer == null) {
5155 throw new IllegalArgumentException("Observer must not be null");
5156 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005157
Christopher Tate73a3cb32010-12-13 18:27:26 -08005158 if (mEnded) {
5159 throw new IllegalStateException("Restore session already ended");
5160 }
5161
Christopher Tate1bb69062010-02-19 17:02:12 -08005162 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005163 try {
Christopher Tate43383042009-07-13 15:17:13 -07005164 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005165 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005166 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005167 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005168 // spin off the transport request to our service thread
5169 mWakelock.acquire();
5170 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5171 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5172 mBackupHandler.sendMessage(msg);
5173 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005174 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005175 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005176 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005177 } finally {
5178 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005179 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005180 }
5181
Christopher Tate84725812010-02-04 15:52:40 -08005182 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005183 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5184 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005185
Chris Tate44ab8452010-11-16 15:10:49 -08005186 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005187 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005188
Christopher Tate73a3cb32010-12-13 18:27:26 -08005189 if (mEnded) {
5190 throw new IllegalStateException("Restore session already ended");
5191 }
5192
Dan Egnor0084da52009-07-29 12:57:16 -07005193 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005194 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5195 return -1;
5196 }
5197
5198 if (mPackageName != null) {
5199 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005200 return -1;
5201 }
5202
Christopher Tate21ab6a52009-09-24 18:01:46 -07005203 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005204 for (int i = 0; i < mRestoreSets.length; i++) {
5205 if (token == mRestoreSets[i].token) {
5206 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005207 mWakelock.acquire();
5208 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005209 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005210 mBackupHandler.sendMessage(msg);
5211 Binder.restoreCallingIdentity(oldId);
5212 return 0;
5213 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005214 }
5215 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005216
Joe Onorato8a9b2202010-02-26 18:56:32 -08005217 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005218 return -1;
5219 }
5220
Christopher Tate284f1bb2011-07-07 14:31:18 -07005221 public synchronized int restoreSome(long token, IRestoreObserver observer,
5222 String[] packages) {
5223 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5224 "performRestore");
5225
5226 if (DEBUG) {
5227 StringBuilder b = new StringBuilder(128);
5228 b.append("restoreSome token=");
5229 b.append(Long.toHexString(token));
5230 b.append(" observer=");
5231 b.append(observer.toString());
5232 b.append(" packages=");
5233 if (packages == null) {
5234 b.append("null");
5235 } else {
5236 b.append('{');
5237 boolean first = true;
5238 for (String s : packages) {
5239 if (!first) {
5240 b.append(", ");
5241 } else first = false;
5242 b.append(s);
5243 }
5244 b.append('}');
5245 }
5246 Slog.d(TAG, b.toString());
5247 }
5248
5249 if (mEnded) {
5250 throw new IllegalStateException("Restore session already ended");
5251 }
5252
5253 if (mRestoreTransport == null || mRestoreSets == null) {
5254 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5255 return -1;
5256 }
5257
5258 if (mPackageName != null) {
5259 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5260 return -1;
5261 }
5262
5263 synchronized (mQueueLock) {
5264 for (int i = 0; i < mRestoreSets.length; i++) {
5265 if (token == mRestoreSets[i].token) {
5266 long oldId = Binder.clearCallingIdentity();
5267 mWakelock.acquire();
5268 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5269 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5270 packages, true);
5271 mBackupHandler.sendMessage(msg);
5272 Binder.restoreCallingIdentity(oldId);
5273 return 0;
5274 }
5275 }
5276 }
5277
5278 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5279 return -1;
5280 }
5281
Christopher Tate84725812010-02-04 15:52:40 -08005282 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005283 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005284
Christopher Tate73a3cb32010-12-13 18:27:26 -08005285 if (mEnded) {
5286 throw new IllegalStateException("Restore session already ended");
5287 }
5288
Chris Tate44ab8452010-11-16 15:10:49 -08005289 if (mPackageName != null) {
5290 if (! mPackageName.equals(packageName)) {
5291 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5292 + " on session for package " + mPackageName);
5293 return -1;
5294 }
5295 }
5296
Christopher Tate84725812010-02-04 15:52:40 -08005297 PackageInfo app = null;
5298 try {
5299 app = mPackageManager.getPackageInfo(packageName, 0);
5300 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005301 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005302 return -1;
5303 }
5304
5305 // If the caller is not privileged and is not coming from the target
5306 // app's uid, throw a permission exception back to the caller.
5307 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5308 Binder.getCallingPid(), Binder.getCallingUid());
5309 if ((perm == PackageManager.PERMISSION_DENIED) &&
5310 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005311 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005312 + " or calling uid=" + Binder.getCallingUid());
5313 throw new SecurityException("No permission to restore other packages");
5314 }
5315
Christopher Tate7d411a32010-02-26 11:27:08 -08005316 // If the package has no backup agent, we obviously cannot proceed
5317 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005318 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005319 return -1;
5320 }
5321
Christopher Tate84725812010-02-04 15:52:40 -08005322 // So far so good; we're allowed to try to restore this package. Now
5323 // check whether there is data for it in the current dataset, falling back
5324 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005325 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005326
5327 // If we didn't come up with a place to look -- no ancestral dataset and
5328 // the app has never been backed up from this device -- there's nothing
5329 // to do but return failure.
5330 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005331 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005332 return -1;
5333 }
5334
5335 // Ready to go: enqueue the restore request and claim success
5336 long oldId = Binder.clearCallingIdentity();
5337 mWakelock.acquire();
5338 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005339 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005340 mBackupHandler.sendMessage(msg);
5341 Binder.restoreCallingIdentity(oldId);
5342 return 0;
5343 }
5344
Christopher Tate73a3cb32010-12-13 18:27:26 -08005345 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5346 class EndRestoreRunnable implements Runnable {
5347 BackupManagerService mBackupManager;
5348 ActiveRestoreSession mSession;
5349
5350 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5351 mBackupManager = manager;
5352 mSession = session;
5353 }
5354
5355 public void run() {
5356 // clean up the session's bookkeeping
5357 synchronized (mSession) {
5358 try {
5359 if (mSession.mRestoreTransport != null) {
5360 mSession.mRestoreTransport.finishRestore();
5361 }
5362 } catch (Exception e) {
5363 Slog.e(TAG, "Error in finishRestore", e);
5364 } finally {
5365 mSession.mRestoreTransport = null;
5366 mSession.mEnded = true;
5367 }
5368 }
5369
5370 // clean up the BackupManagerService side of the bookkeeping
5371 // and cancel any pending timeout message
5372 mBackupManager.clearRestoreSession(mSession);
5373 }
5374 }
5375
Dan Egnor0084da52009-07-29 12:57:16 -07005376 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005377 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005378
Christopher Tate73a3cb32010-12-13 18:27:26 -08005379 if (mEnded) {
5380 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005381 }
5382
Christopher Tate73a3cb32010-12-13 18:27:26 -08005383 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005384 }
5385 }
5386
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005387 @Override
5388 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005389 long identityToken = Binder.clearCallingIdentity();
5390 try {
5391 dumpInternal(pw);
5392 } finally {
5393 Binder.restoreCallingIdentity(identityToken);
5394 }
5395 }
5396
5397 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005398 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005399 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005400 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005401 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005402 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07005403 pw.println("Last backup pass: " + mLastBackupPass
5404 + " (now = " + System.currentTimeMillis() + ')');
5405 pw.println(" next scheduled: " + mNextBackupPass);
5406
Christopher Tate91717492009-06-26 21:07:13 -07005407 pw.println("Available transports:");
5408 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005409 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5410 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005411 IBackupTransport transport = getTransport(t);
5412 File dir = new File(mBaseStateDir, transport.transportDirName());
5413 pw.println(" destination: " + transport.currentDestinationString());
5414 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005415 for (File f : dir.listFiles()) {
5416 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5417 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005418 } catch (Exception e) {
5419 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005420 pw.println(" Error: " + e);
5421 }
Christopher Tate91717492009-06-26 21:07:13 -07005422 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005423
5424 pw.println("Pending init: " + mPendingInits.size());
5425 for (String s : mPendingInits) {
5426 pw.println(" " + s);
5427 }
5428
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005429 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005430 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005431 for (int i=0; i<N; i++) {
5432 int uid = mBackupParticipants.keyAt(i);
5433 pw.print(" uid: ");
5434 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005435 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5436 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005437 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005438 }
5439 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005440
Christopher Tateb49ceb32010-02-08 16:22:24 -08005441 pw.println("Ancestral packages: "
5442 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005443 if (mAncestralPackages != null) {
5444 for (String pkg : mAncestralPackages) {
5445 pw.println(" " + pkg);
5446 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005447 }
5448
Christopher Tate73e02522009-07-15 14:18:26 -07005449 pw.println("Ever backed up: " + mEverStoredApps.size());
5450 for (String pkg : mEverStoredApps) {
5451 pw.println(" " + pkg);
5452 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005453
5454 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005455 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005456 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005457 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005458 }
5459 }
Christopher Tate487529a2009-04-29 14:03:25 -07005460}