blob: 997318a0de8fd2e7d6dabe84be5578dc955614e4 [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070021import android.app.AppGlobals;
Christopher Tate181fafa2009-05-14 11:12:14 -070022import android.app.IActivityManager;
23import android.app.IApplicationThread;
24import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070025import android.app.PendingIntent;
Christopher Tate79ec80d2011-06-24 14:58:49 -070026import android.app.backup.BackupAgent;
Christopher Tate4a627c72011-04-01 14:43:32 -070027import android.app.backup.BackupDataOutput;
28import android.app.backup.FullBackup;
Jason parksa3cdaa52011-01-13 14:15:43 -060029import android.app.backup.RestoreSet;
Christopher Tate45281862010-03-05 15:46:30 -080030import android.app.backup.IBackupManager;
Christopher Tate4a627c72011-04-01 14:43:32 -070031import android.app.backup.IFullBackupRestoreObserver;
Christopher Tate45281862010-03-05 15:46:30 -080032import android.app.backup.IRestoreObserver;
33import android.app.backup.IRestoreSession;
Christopher Tate4a627c72011-04-01 14:43:32 -070034import android.content.ActivityNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070035import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070036import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070037import android.content.Context;
38import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070039import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070040import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070041import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070042import android.content.pm.IPackageDataObserver;
Christopher Tatea858cb02011-06-03 12:27:51 -070043import android.content.pm.IPackageDeleteObserver;
Christopher Tate75a99702011-05-18 16:28:19 -070044import android.content.pm.IPackageInstallObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080045import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070046import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070047import android.content.pm.PackageManager;
Jason parks1125d782011-01-12 09:47:26 -060048import android.content.pm.Signature;
Jason parksa3cdaa52011-01-13 14:15:43 -060049import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070050import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.os.Binder;
Christopher Tate75a99702011-05-18 16:28:19 -070052import android.os.Build;
Christopher Tate3799bc22009-05-06 16:13:56 -070053import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070054import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070055import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080056import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070057import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080058import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070059import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070060import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070061import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070062import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070063import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070064import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070065import android.os.WorkSource;
Oscar Montemayora8529f62009-11-18 10:14:20 -080066import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070067import android.util.EventLog;
Christopher Tate79ec80d2011-06-24 14:58:49 -070068import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080069import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070070import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080071import android.util.SparseIntArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070072import android.util.StringBuilderPrinter;
73
Jason parksa3cdaa52011-01-13 14:15:43 -060074import com.android.internal.backup.BackupConstants;
75import com.android.internal.backup.IBackupTransport;
76import com.android.internal.backup.LocalTransport;
77import com.android.server.PackageManagerBackupAgent.Metadata;
78
Christopher Tate2efd2db2011-07-19 16:32:49 -070079import java.io.BufferedInputStream;
80import java.io.BufferedOutputStream;
81import java.io.ByteArrayOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -070082import java.io.DataInputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070083import java.io.DataOutputStream;
Christopher Tatecde87f42009-06-12 12:55:53 -070084import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070085import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070086import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070087import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080088import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070089import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070090import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070091import java.io.InputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070092import java.io.OutputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070093import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070094import java.io.RandomAccessFile;
Christopher Tate2efd2db2011-07-19 16:32:49 -070095import java.security.InvalidAlgorithmParameterException;
96import java.security.InvalidKeyException;
97import java.security.Key;
98import java.security.NoSuchAlgorithmException;
99import java.security.SecureRandom;
100import java.security.spec.InvalidKeySpecException;
101import java.security.spec.KeySpec;
Christopher Tate75a99702011-05-18 16:28:19 -0700102import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -0400103import java.util.ArrayList;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700104import java.util.Arrays;
Christopher Tate75a99702011-05-18 16:28:19 -0700105import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -0400106import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -0700107import java.util.HashSet;
108import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -0700109import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -0700110import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800111import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -0700112import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate7926a692011-07-11 11:31:57 -0700113import java.util.zip.Deflater;
114import java.util.zip.DeflaterOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -0700115import java.util.zip.InflaterInputStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700116
Christopher Tate2efd2db2011-07-19 16:32:49 -0700117import javax.crypto.BadPaddingException;
118import javax.crypto.Cipher;
119import javax.crypto.CipherInputStream;
120import javax.crypto.CipherOutputStream;
121import javax.crypto.IllegalBlockSizeException;
122import javax.crypto.NoSuchPaddingException;
123import javax.crypto.SecretKey;
124import javax.crypto.SecretKeyFactory;
125import javax.crypto.spec.IvParameterSpec;
126import javax.crypto.spec.PBEKeySpec;
127import javax.crypto.spec.SecretKeySpec;
128
Christopher Tate487529a2009-04-29 14:03:25 -0700129class BackupManagerService extends IBackupManager.Stub {
130 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -0700131 private static final boolean DEBUG = true;
Christopher Tatec58efa62011-08-01 19:20:14 -0700132 private static final boolean MORE_DEBUG = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700133
134 // Name and current contents version of the full-backup manifest file
135 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
136 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700137 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
138 static final int BACKUP_FILE_VERSION = 1;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700139 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
Christopher Tateaa088442009-06-16 18:25:46 -0700140
Christopher Tate49401dd2009-07-01 12:34:29 -0700141 // How often we perform a backup pass. Privileged external callers can
142 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700143 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700144
Dan Egnorc1c49c02009-10-30 17:35:39 -0700145 // Random variation in backup scheduling time to avoid server load spikes
146 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
147
Christopher Tate8031a3d2009-07-06 16:36:05 -0700148 // The amount of time between the initial provisioning of the device and
149 // the first backup pass.
150 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
151
Christopher Tate45281862010-03-05 15:46:30 -0800152 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
153 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
154 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700155 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700156 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700157 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700158 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700159 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700160 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
161 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800162 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700163 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
164 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700165
166 // Timeout interval for deciding that a bind or clear-data has taken too long
167 static final long TIMEOUT_INTERVAL = 10 * 1000;
168
Christopher Tate44a27902010-01-27 17:15:49 -0800169 // Timeout intervals for agent backup & restore operations
170 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700171 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700172 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800173 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
174
Christopher Tate2efd2db2011-07-19 16:32:49 -0700175 // User confirmation timeout for a full backup/restore operation. It's this long in
176 // order to give them time to enter the backup password.
177 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700178
Christopher Tate487529a2009-04-29 14:03:25 -0700179 private Context mContext;
180 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800181 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700182 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700183 private PowerManager mPowerManager;
184 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800185 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700186
Christopher Tate73e02522009-07-15 14:18:26 -0700187 boolean mEnabled; // access to this is synchronized on 'this'
188 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800189 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700190 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800191 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
192 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700193 PendingIntent mRunBackupIntent, mRunInitIntent;
194 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700195 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700196 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700197 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700198 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700199 class BackupRequest {
Christopher Tatecc55f812011-08-16 16:06:53 -0700200 public String packageName;
Christopher Tateaa088442009-06-16 18:25:46 -0700201
Christopher Tatecc55f812011-08-16 16:06:53 -0700202 BackupRequest(String pkgName) {
203 packageName = pkgName;
Christopher Tate46758122009-05-06 11:22:00 -0700204 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700205
206 public String toString() {
Christopher Tatecc55f812011-08-16 16:06:53 -0700207 return "BackupRequest{pkg=" + packageName + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700208 }
Christopher Tate46758122009-05-06 11:22:00 -0700209 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800210 // Backups that we haven't started yet. Keys are package names.
211 HashMap<String,BackupRequest> mPendingBackups
212 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700213
214 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700215 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700216
217 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700218 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700219
Christopher Tate043dadc2009-06-02 16:11:00 -0700220 // The thread performing the sequence of queued backups binds to each app's agent
221 // in succession. Bind notifications are asynchronously delivered through the
222 // Activity Manager; use this lock object to signal when a requested binding has
223 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700224 final Object mAgentConnectLock = new Object();
225 IBackupAgent mConnectedAgent;
226 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700227 volatile long mLastBackupPass;
228 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700229
Christopher Tate55f931a2009-09-29 17:17:34 -0700230 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700231 final Object mClearDataLock = new Object();
232 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700233
Christopher Tate91717492009-06-26 21:07:13 -0700234 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700235 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700236 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700237 String mCurrentTransport;
238 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800239 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700240
Christopher Tate2d449afe2010-03-29 19:14:24 -0700241 class RestoreGetSetsParams {
242 public IBackupTransport transport;
243 public ActiveRestoreSession session;
244 public IRestoreObserver observer;
245
246 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
247 IRestoreObserver _observer) {
248 transport = _transport;
249 session = _session;
250 observer = _observer;
251 }
252 }
253
Christopher Tate73e02522009-07-15 14:18:26 -0700254 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700255 public IBackupTransport transport;
256 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700257 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800258 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800259 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700260 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700261 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800262
263 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700264 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800265 transport = _transport;
266 observer = _obs;
267 token = _token;
268 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800269 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700270 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700271 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800272 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700273
Chris Tate249345b2010-10-29 12:57:04 -0700274 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
275 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700276 transport = _transport;
277 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700278 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800279 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800280 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700281 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700282 filterSet = null;
283 }
284
285 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
286 String[] _filterSet, boolean _needFullBackup) {
287 transport = _transport;
288 observer = _obs;
289 token = _token;
290 pkgInfo = null;
291 pmToken = 0;
292 needFullBackup = _needFullBackup;
293 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700294 }
295 }
296
Christopher Tate73e02522009-07-15 14:18:26 -0700297 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700298 public IBackupTransport transport;
299 public PackageInfo packageInfo;
300
301 ClearParams(IBackupTransport _transport, PackageInfo _info) {
302 transport = _transport;
303 packageInfo = _info;
304 }
305 }
306
Christopher Tate4a627c72011-04-01 14:43:32 -0700307 class FullParams {
308 public ParcelFileDescriptor fd;
309 public final AtomicBoolean latch;
310 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700311 public String curPassword; // filled in by the confirmation step
312 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700313
314 FullParams() {
315 latch = new AtomicBoolean(false);
316 }
317 }
318
319 class FullBackupParams extends FullParams {
320 public boolean includeApks;
321 public boolean includeShared;
322 public boolean allApps;
323 public String[] packages;
324
325 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
326 boolean doAllApps, String[] pkgList) {
327 fd = output;
328 includeApks = saveApks;
329 includeShared = saveShared;
330 allApps = doAllApps;
331 packages = pkgList;
332 }
333 }
334
335 class FullRestoreParams extends FullParams {
336 FullRestoreParams(ParcelFileDescriptor input) {
337 fd = input;
338 }
339 }
340
Christopher Tate44a27902010-01-27 17:15:49 -0800341 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
342 // token is the index of the entry in the pending-operations list.
343 static final int OP_PENDING = 0;
344 static final int OP_ACKNOWLEDGED = 1;
345 static final int OP_TIMEOUT = -1;
346
347 final SparseIntArray mCurrentOperations = new SparseIntArray();
348 final Object mCurrentOpLock = new Object();
349 final Random mTokenGenerator = new Random();
350
Christopher Tate4a627c72011-04-01 14:43:32 -0700351 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
352
Christopher Tate5cb400b2009-06-25 16:03:14 -0700353 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700354 File mBaseStateDir;
355 File mDataDir;
356 File mJournalDir;
357 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700358
Christopher Tate2efd2db2011-07-19 16:32:49 -0700359 // Backup password, if any, and the file where it's saved. What is stored is not the
360 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
361 // persisted) salt. Validation is performed by running the challenge text through the
362 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
363 // the saved hash string, then the challenge text matches the originally supplied
364 // password text.
365 private final SecureRandom mRng = new SecureRandom();
366 private String mPasswordHash;
367 private File mPasswordHashFile;
368 private byte[] mPasswordSalt;
369
370 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
371 static final int PBKDF2_HASH_ROUNDS = 10000;
372 static final int PBKDF2_KEY_SIZE = 256; // bits
373 static final int PBKDF2_SALT_SIZE = 512; // bits
374 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
375
Christopher Tate84725812010-02-04 15:52:40 -0800376 // Keep a log of all the apps we've ever backed up, and what the
377 // dataset tokens are for both the current backup dataset and
378 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700379 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700380 HashSet<String> mEverStoredApps = new HashSet<String>();
381
Christopher Tateb49ceb32010-02-08 16:22:24 -0800382 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800383 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800384 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800385 long mAncestralToken = 0;
386 long mCurrentToken = 0;
387
Christopher Tate4cc86e12009-09-21 19:36:51 -0700388 // Persistently track the need to do a full init
389 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
390 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700391
Christopher Tate4a627c72011-04-01 14:43:32 -0700392 // Utility: build a new random integer token
393 int generateToken() {
394 int token;
395 do {
396 synchronized (mTokenGenerator) {
397 token = mTokenGenerator.nextInt();
398 }
399 } while (token < 0);
400 return token;
401 }
402
Christopher Tate44a27902010-01-27 17:15:49 -0800403 // ----- Asynchronous backup/restore handler thread -----
404
405 private class BackupHandler extends Handler {
406 public BackupHandler(Looper looper) {
407 super(looper);
408 }
409
410 public void handleMessage(Message msg) {
411
412 switch (msg.what) {
413 case MSG_RUN_BACKUP:
414 {
415 mLastBackupPass = System.currentTimeMillis();
416 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
417
418 IBackupTransport transport = getTransport(mCurrentTransport);
419 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800420 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800421 mWakelock.release();
422 break;
423 }
424
425 // snapshot the pending-backup set and work on that
426 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800427 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800428 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800429 // Do we have any work to do? Construct the work queue
430 // then release the synchronization lock to actually run
431 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800432 if (mPendingBackups.size() > 0) {
433 for (BackupRequest b: mPendingBackups.values()) {
434 queue.add(b);
435 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800436 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800437 mPendingBackups.clear();
438
439 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800440 mJournal = null;
441
Christopher Tate44a27902010-01-27 17:15:49 -0800442 }
443 }
Christopher Tatec61da312010-02-05 10:41:27 -0800444
445 if (queue.size() > 0) {
446 // At this point, we have started a new journal file, and the old
447 // file identity is being passed to the backup processing thread.
448 // When it completes successfully, that old journal file will be
449 // deleted. If we crash prior to that, the old journal is parsed
450 // at next boot and the journaled requests fulfilled.
451 (new PerformBackupTask(transport, queue, oldJournal)).run();
452 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800453 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800454 mWakelock.release();
455 }
Christopher Tate44a27902010-01-27 17:15:49 -0800456 break;
457 }
458
459 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700460 {
461 FullBackupParams params = (FullBackupParams)msg.obj;
462 (new PerformFullBackupTask(params.fd, params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700463 params.includeShared, params.curPassword, params.encryptPassword,
464 params.allApps, params.packages, params.latch)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800465 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700466 }
Christopher Tate44a27902010-01-27 17:15:49 -0800467
468 case MSG_RUN_RESTORE:
469 {
470 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800471 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800472 (new PerformRestoreTask(params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700473 params.token, params.pkgInfo, params.pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -0700474 params.needFullBackup, params.filterSet)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800475 break;
476 }
477
Christopher Tate75a99702011-05-18 16:28:19 -0700478 case MSG_RUN_FULL_RESTORE:
479 {
480 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tate728a1c42011-07-28 18:03:03 -0700481 (new PerformFullRestoreTask(params.fd, params.curPassword, params.encryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -0700482 params.observer, params.latch)).run();
Christopher Tate75a99702011-05-18 16:28:19 -0700483 break;
484 }
485
Christopher Tate44a27902010-01-27 17:15:49 -0800486 case MSG_RUN_CLEAR:
487 {
488 ClearParams params = (ClearParams)msg.obj;
489 (new PerformClearTask(params.transport, params.packageInfo)).run();
490 break;
491 }
492
493 case MSG_RUN_INITIALIZE:
494 {
495 HashSet<String> queue;
496
497 // Snapshot the pending-init queue and work on that
498 synchronized (mQueueLock) {
499 queue = new HashSet<String>(mPendingInits);
500 mPendingInits.clear();
501 }
502
503 (new PerformInitializeTask(queue)).run();
504 break;
505 }
506
Christopher Tate2d449afe2010-03-29 19:14:24 -0700507 case MSG_RUN_GET_RESTORE_SETS:
508 {
509 // Like other async operations, this is entered with the wakelock held
510 RestoreSet[] sets = null;
511 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
512 try {
513 sets = params.transport.getAvailableRestoreSets();
514 // cache the result in the active session
515 synchronized (params.session) {
516 params.session.mRestoreSets = sets;
517 }
518 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
519 } catch (Exception e) {
520 Slog.e(TAG, "Error from transport getting set list");
521 } finally {
522 if (params.observer != null) {
523 try {
524 params.observer.restoreSetsAvailable(sets);
525 } catch (RemoteException re) {
526 Slog.e(TAG, "Unable to report listing to observer");
527 } catch (Exception e) {
528 Slog.e(TAG, "Restore observer threw", e);
529 }
530 }
531
Christopher Tate2a935092011-03-03 17:30:32 -0800532 // Done: reset the session timeout clock
533 removeMessages(MSG_RESTORE_TIMEOUT);
534 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
535
Christopher Tate2d449afe2010-03-29 19:14:24 -0700536 mWakelock.release();
537 }
538 break;
539 }
540
Christopher Tate44a27902010-01-27 17:15:49 -0800541 case MSG_TIMEOUT:
542 {
543 synchronized (mCurrentOpLock) {
544 final int token = msg.arg1;
545 int state = mCurrentOperations.get(token, OP_TIMEOUT);
546 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800547 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800548 mCurrentOperations.put(token, OP_TIMEOUT);
549 }
550 mCurrentOpLock.notifyAll();
551 }
552 break;
553 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800554
555 case MSG_RESTORE_TIMEOUT:
556 {
557 synchronized (BackupManagerService.this) {
558 if (mActiveRestoreSession != null) {
559 // Client app left the restore session dangling. We know that it
560 // can't be in the middle of an actual restore operation because
561 // those are executed serially on this same handler thread. Clean
562 // up now.
563 Slog.w(TAG, "Restore session timed out; aborting");
564 post(mActiveRestoreSession.new EndRestoreRunnable(
565 BackupManagerService.this, mActiveRestoreSession));
566 }
567 }
568 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700569
570 case MSG_FULL_CONFIRMATION_TIMEOUT:
571 {
572 synchronized (mFullConfirmations) {
573 FullParams params = mFullConfirmations.get(msg.arg1);
574 if (params != null) {
575 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
576
577 // Release the waiter; timeout == completion
578 signalFullBackupRestoreCompletion(params);
579
580 // Remove the token from the set
581 mFullConfirmations.delete(msg.arg1);
582
583 // Report a timeout to the observer, if any
584 if (params.observer != null) {
585 try {
586 params.observer.onTimeout();
587 } catch (RemoteException e) {
588 /* don't care if the app has gone away */
589 }
590 }
591 } else {
592 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
593 }
594 }
595 break;
596 }
Christopher Tate44a27902010-01-27 17:15:49 -0800597 }
598 }
599 }
600
601 // ----- Main service implementation -----
602
Christopher Tate487529a2009-04-29 14:03:25 -0700603 public BackupManagerService(Context context) {
604 mContext = context;
605 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700606 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700607 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700608
Christopher Tateb6787f22009-07-02 17:40:45 -0700609 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
610 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
611
Christopher Tate44a27902010-01-27 17:15:49 -0800612 mBackupManagerBinder = asInterface(asBinder());
613
614 // spin up the backup/restore handler thread
615 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
616 mHandlerThread.start();
617 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
618
Christopher Tate22b87872009-05-04 16:41:53 -0700619 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700620 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700621 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700622 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700623 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800624 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800625 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800626 // If Encrypted file systems is enabled or disabled, this call will return the
627 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600628 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800629 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700630 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700631
Christopher Tate2efd2db2011-07-19 16:32:49 -0700632 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
633 if (mPasswordHashFile.exists()) {
634 FileInputStream fin = null;
635 DataInputStream in = null;
636 try {
637 fin = new FileInputStream(mPasswordHashFile);
638 in = new DataInputStream(new BufferedInputStream(fin));
639 // integer length of the salt array, followed by the salt,
640 // then the hex pw hash string
641 int saltLen = in.readInt();
642 byte[] salt = new byte[saltLen];
643 in.readFully(salt);
644 mPasswordHash = in.readUTF();
645 mPasswordSalt = salt;
646 } catch (IOException e) {
647 Slog.e(TAG, "Unable to read saved backup pw hash");
648 } finally {
649 try {
650 if (in != null) in.close();
651 if (fin != null) fin.close();
652 } catch (IOException e) {
653 Slog.w(TAG, "Unable to close streams");
654 }
655 }
656 }
657
Christopher Tate4cc86e12009-09-21 19:36:51 -0700658 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700659 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700660 IntentFilter filter = new IntentFilter();
661 filter.addAction(RUN_BACKUP_ACTION);
662 context.registerReceiver(mRunBackupReceiver, filter,
663 android.Manifest.permission.BACKUP, null);
664
665 mRunInitReceiver = new RunInitializeReceiver();
666 filter = new IntentFilter();
667 filter.addAction(RUN_INITIALIZE_ACTION);
668 context.registerReceiver(mRunInitReceiver, filter,
669 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700670
671 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700672 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
673 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
674
Christopher Tate4cc86e12009-09-21 19:36:51 -0700675 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
676 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
677 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
678
Christopher Tatecde87f42009-06-12 12:55:53 -0700679 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700680 mJournalDir = new File(mBaseStateDir, "pending");
681 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700682 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700683
Christopher Tate73e02522009-07-15 14:18:26 -0700684 // Set up the various sorts of package tracking we do
685 initPackageTracking();
686
Christopher Tateabce4e82009-06-18 18:35:32 -0700687 // Build our mapping of uid to backup client services. This implicitly
688 // schedules a backup pass on the Package Manager metadata the first
689 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700690 synchronized (mBackupParticipants) {
691 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700692 }
693
Dan Egnor87a02bc2009-06-17 02:30:10 -0700694 // Set up our transport options and initialize the default transport
695 // TODO: Have transports register themselves somehow?
696 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700697 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700698 ComponentName localName = new ComponentName(context, LocalTransport.class);
699 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700700
Christopher Tate91717492009-06-26 21:07:13 -0700701 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700702 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
703 Settings.Secure.BACKUP_TRANSPORT);
704 if ("".equals(mCurrentTransport)) {
705 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700706 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800707 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700708
709 // Attach to the Google backup transport. When this comes up, it will set
710 // itself as the current transport because we explicitly reset mCurrentTransport
711 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700712 ComponentName transportComponent = new ComponentName("com.google.android.backup",
713 "com.google.android.backup.BackupTransportService");
714 try {
715 // If there's something out there that is supposed to be the Google
716 // backup transport, make sure it's legitimately part of the OS build
717 // and not an app lying about its package name.
718 ApplicationInfo info = mPackageManager.getApplicationInfo(
719 transportComponent.getPackageName(), 0);
720 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
721 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
722 Intent intent = new Intent().setComponent(transportComponent);
723 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
724 } else {
725 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
726 }
727 } catch (PackageManager.NameNotFoundException nnf) {
728 // No such package? No binding.
729 if (DEBUG) Slog.v(TAG, "Google transport not present");
730 }
Christopher Tateaa088442009-06-16 18:25:46 -0700731
Christopher Tatecde87f42009-06-12 12:55:53 -0700732 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700733 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700734 parseLeftoverJournals();
735
Christopher Tateb6787f22009-07-02 17:40:45 -0700736 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700737 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700738
739 // Start the backup passes going
740 setBackupEnabled(areEnabled);
741 }
742
743 private class RunBackupReceiver extends BroadcastReceiver {
744 public void onReceive(Context context, Intent intent) {
745 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700746 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700747 if (mPendingInits.size() > 0) {
748 // If there are pending init operations, we process those
749 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800750 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700751 try {
752 mAlarmManager.cancel(mRunInitIntent);
753 mRunInitIntent.send();
754 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800755 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700756 // can't really do more than bail here
757 }
758 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800759 // Don't run backups now if we're disabled or not yet
760 // fully set up.
761 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800762 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700763
764 // Acquire the wakelock and pass it to the backup thread. it will
765 // be released once backup concludes.
766 mWakelock.acquire();
767
768 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
769 mBackupHandler.sendMessage(msg);
770 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800771 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700772 }
773 }
774 }
775 }
776 }
777 }
778
779 private class RunInitializeReceiver extends BroadcastReceiver {
780 public void onReceive(Context context, Intent intent) {
781 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
782 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800783 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700784
785 // Acquire the wakelock and pass it to the init thread. it will
786 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700787 mWakelock.acquire();
788
Christopher Tate4cc86e12009-09-21 19:36:51 -0700789 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700790 mBackupHandler.sendMessage(msg);
791 }
792 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700793 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700794 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700795
Christopher Tate73e02522009-07-15 14:18:26 -0700796 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800797 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700798
Christopher Tate84725812010-02-04 15:52:40 -0800799 // Remember our ancestral dataset
800 mTokenFile = new File(mBaseStateDir, "ancestral");
801 try {
802 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800803 int version = tf.readInt();
804 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
805 mAncestralToken = tf.readLong();
806 mCurrentToken = tf.readLong();
807
808 int numPackages = tf.readInt();
809 if (numPackages >= 0) {
810 mAncestralPackages = new HashSet<String>();
811 for (int i = 0; i < numPackages; i++) {
812 String pkgName = tf.readUTF();
813 mAncestralPackages.add(pkgName);
814 }
815 }
816 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800817 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800818 } catch (FileNotFoundException fnf) {
819 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800820 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800821 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800822 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800823 }
824
Christopher Tatee97e8072009-07-15 16:45:50 -0700825 // Keep a log of what apps we've ever backed up. Because we might have
826 // rebooted in the middle of an operation that was removing something from
827 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700828 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700829 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700830
Christopher Tatee97e8072009-07-15 16:45:50 -0700831 // If we were in the middle of removing something from the ever-backed-up
832 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700833 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700834 if (tempProcessedFile.exists()) {
835 tempProcessedFile.delete();
836 }
837
Dan Egnor852f8e42009-09-30 11:20:45 -0700838 // If there are previous contents, parse them out then start a new
839 // file to continue the recordkeeping.
840 if (mEverStored.exists()) {
841 RandomAccessFile temp = null;
842 RandomAccessFile in = null;
843
844 try {
845 temp = new RandomAccessFile(tempProcessedFile, "rws");
846 in = new RandomAccessFile(mEverStored, "r");
847
848 while (true) {
849 PackageInfo info;
850 String pkg = in.readUTF();
851 try {
852 info = mPackageManager.getPackageInfo(pkg, 0);
853 mEverStoredApps.add(pkg);
854 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700855 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700856 } catch (NameNotFoundException e) {
857 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700858 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700859 }
860 }
861 } catch (EOFException e) {
862 // Once we've rewritten the backup history log, atomically replace the
863 // old one with the new one then reopen the file for continuing use.
864 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800865 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700866 }
867 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800868 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700869 } finally {
870 try { if (temp != null) temp.close(); } catch (IOException e) {}
871 try { if (in != null) in.close(); } catch (IOException e) {}
872 }
873 }
874
Christopher Tate73e02522009-07-15 14:18:26 -0700875 // Register for broadcasts about package install, etc., so we can
876 // update the provider list.
877 IntentFilter filter = new IntentFilter();
878 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
879 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Christopher Tatecc55f812011-08-16 16:06:53 -0700880 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Christopher Tate73e02522009-07-15 14:18:26 -0700881 filter.addDataScheme("package");
882 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800883 // Register for events related to sdcard installation.
884 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800885 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
886 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800887 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700888 }
889
Christopher Tatecde87f42009-06-12 12:55:53 -0700890 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700891 for (File f : mJournalDir.listFiles()) {
892 if (mJournal == null || f.compareTo(mJournal) != 0) {
893 // This isn't the current journal, so it must be a leftover. Read
894 // out the package names mentioned there and schedule them for
895 // backup.
896 RandomAccessFile in = null;
897 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400898 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700899 in = new RandomAccessFile(f, "r");
900 while (true) {
901 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400902 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700903 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700904 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700905 } catch (EOFException e) {
906 // no more data; we're done
907 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800908 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700909 } finally {
910 // close/delete the file
911 try { if (in != null) in.close(); } catch (IOException e) {}
912 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700913 }
914 }
915 }
916 }
917
Christopher Tate2efd2db2011-07-19 16:32:49 -0700918 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
919 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
920 }
921
922 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
923 try {
924 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
925 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
926 return keyFactory.generateSecret(ks);
927 } catch (InvalidKeySpecException e) {
928 Slog.e(TAG, "Invalid key spec for PBKDF2!");
929 } catch (NoSuchAlgorithmException e) {
930 Slog.e(TAG, "PBKDF2 unavailable!");
931 }
932 return null;
933 }
934
935 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
936 SecretKey key = buildPasswordKey(pw, salt, rounds);
937 if (key != null) {
938 return byteArrayToHex(key.getEncoded());
939 }
940 return null;
941 }
942
943 private String byteArrayToHex(byte[] data) {
944 StringBuilder buf = new StringBuilder(data.length * 2);
945 for (int i = 0; i < data.length; i++) {
946 buf.append(Byte.toHexString(data[i], true));
947 }
948 return buf.toString();
949 }
950
951 private byte[] hexToByteArray(String digits) {
952 final int bytes = digits.length() / 2;
953 if (2*bytes != digits.length()) {
954 throw new IllegalArgumentException("Hex string must have an even number of digits");
955 }
956
957 byte[] result = new byte[bytes];
958 for (int i = 0; i < digits.length(); i += 2) {
959 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
960 }
961 return result;
962 }
963
964 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
965 char[] mkAsChar = new char[pwBytes.length];
966 for (int i = 0; i < pwBytes.length; i++) {
967 mkAsChar[i] = (char) pwBytes[i];
968 }
969
970 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
971 return checksum.getEncoded();
972 }
973
974 // Used for generating random salts or passwords
975 private byte[] randomBytes(int bits) {
976 byte[] array = new byte[bits / 8];
977 mRng.nextBytes(array);
978 return array;
979 }
980
981 // Backup password management
982 boolean passwordMatchesSaved(String candidatePw, int rounds) {
983 if (mPasswordHash == null) {
984 // no current password case -- require that 'currentPw' be null or empty
985 if (candidatePw == null || "".equals(candidatePw)) {
986 return true;
987 } // else the non-empty candidate does not match the empty stored pw
988 } else {
989 // hash the stated current pw and compare to the stored one
990 if (candidatePw != null && candidatePw.length() > 0) {
991 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
992 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
993 // candidate hash matches the stored hash -- the password matches
994 return true;
995 }
996 } // else the stored pw is nonempty but the candidate is empty; no match
997 }
998 return false;
999 }
1000
1001 @Override
1002 public boolean setBackupPassword(String currentPw, String newPw) {
1003 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1004 "setBackupPassword");
1005
1006 // If the supplied pw doesn't hash to the the saved one, fail
1007 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1008 return false;
1009 }
1010
1011 // Clearing the password is okay
1012 if (newPw == null || newPw.isEmpty()) {
1013 if (mPasswordHashFile.exists()) {
1014 if (!mPasswordHashFile.delete()) {
1015 // Unable to delete the old pw file, so fail
1016 Slog.e(TAG, "Unable to clear backup password");
1017 return false;
1018 }
1019 }
1020 mPasswordHash = null;
1021 mPasswordSalt = null;
1022 return true;
1023 }
1024
1025 try {
1026 // Okay, build the hash of the new backup password
1027 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1028 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1029
1030 OutputStream pwf = null, buffer = null;
1031 DataOutputStream out = null;
1032 try {
1033 pwf = new FileOutputStream(mPasswordHashFile);
1034 buffer = new BufferedOutputStream(pwf);
1035 out = new DataOutputStream(buffer);
1036 // integer length of the salt array, followed by the salt,
1037 // then the hex pw hash string
1038 out.writeInt(salt.length);
1039 out.write(salt);
1040 out.writeUTF(newPwHash);
1041 out.flush();
1042 mPasswordHash = newPwHash;
1043 mPasswordSalt = salt;
1044 return true;
1045 } finally {
1046 if (out != null) out.close();
1047 if (buffer != null) buffer.close();
1048 if (pwf != null) pwf.close();
1049 }
1050 } catch (IOException e) {
1051 Slog.e(TAG, "Unable to set backup password");
1052 }
1053 return false;
1054 }
1055
1056 @Override
1057 public boolean hasBackupPassword() {
1058 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1059 "hasBackupPassword");
1060 return (mPasswordHash != null && mPasswordHash.length() > 0);
1061 }
1062
Christopher Tate4cc86e12009-09-21 19:36:51 -07001063 // Maintain persistent state around whether need to do an initialize operation.
1064 // Must be called with the queue lock held.
1065 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001066 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001067 + " on transport " + transportName);
1068 try {
1069 IBackupTransport transport = getTransport(transportName);
1070 String transportDirName = transport.transportDirName();
1071 File stateDir = new File(mBaseStateDir, transportDirName);
1072 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1073
1074 if (isPending) {
1075 // We need an init before we can proceed with sending backup data.
1076 // Record that with an entry in our set of pending inits, as well as
1077 // journaling it via creation of a sentinel file.
1078 mPendingInits.add(transportName);
1079 try {
1080 (new FileOutputStream(initPendingFile)).close();
1081 } catch (IOException ioe) {
1082 // Something is badly wrong with our permissions; just try to move on
1083 }
1084 } else {
1085 // No more initialization needed; wipe the journal and reset our state.
1086 initPendingFile.delete();
1087 mPendingInits.remove(transportName);
1088 }
1089 } catch (RemoteException e) {
1090 // can't happen; the transport is local
1091 }
1092 }
1093
Christopher Tated55e18a2009-09-21 10:12:59 -07001094 // Reset all of our bookkeeping, in response to having been told that
1095 // the backend data has been wiped [due to idle expiry, for example],
1096 // so we must re-upload all saved settings.
1097 void resetBackupState(File stateFileDir) {
1098 synchronized (mQueueLock) {
1099 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001100 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001101 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001102
Christopher Tate84725812010-02-04 15:52:40 -08001103 mCurrentToken = 0;
1104 writeRestoreTokens();
1105
Christopher Tated55e18a2009-09-21 10:12:59 -07001106 // Remove all the state files
1107 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001108 // ... but don't touch the needs-init sentinel
1109 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1110 sf.delete();
1111 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001112 }
Christopher Tate45597642011-04-04 16:59:21 -07001113 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001114
Christopher Tate45597642011-04-04 16:59:21 -07001115 // Enqueue a new backup of every participant
1116 int N = mBackupParticipants.size();
1117 for (int i=0; i<N; i++) {
1118 int uid = mBackupParticipants.keyAt(i);
1119 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1120 for (ApplicationInfo app: participants) {
1121 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -07001122 }
1123 }
1124 }
1125
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001126 // Add a transport to our set of available backends. If 'transport' is null, this
1127 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001128 private void registerTransport(String name, IBackupTransport transport) {
1129 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001130 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001131 if (transport != null) {
1132 mTransports.put(name, transport);
1133 } else {
1134 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001135 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001136 mCurrentTransport = null;
1137 }
1138 // Nothing further to do in the unregistration case
1139 return;
1140 }
Christopher Tate91717492009-06-26 21:07:13 -07001141 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001142
1143 // If the init sentinel file exists, we need to be sure to perform the init
1144 // as soon as practical. We also create the state directory at registration
1145 // time to ensure it's present from the outset.
1146 try {
1147 String transportName = transport.transportDirName();
1148 File stateDir = new File(mBaseStateDir, transportName);
1149 stateDir.mkdirs();
1150
1151 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1152 if (initSentinel.exists()) {
1153 synchronized (mQueueLock) {
1154 mPendingInits.add(transportName);
1155
1156 // TODO: pick a better starting time than now + 1 minute
1157 long delay = 1000 * 60; // one minute, in milliseconds
1158 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1159 System.currentTimeMillis() + delay, mRunInitIntent);
1160 }
1161 }
1162 } catch (RemoteException e) {
1163 // can't happen, the transport is local
1164 }
Christopher Tate91717492009-06-26 21:07:13 -07001165 }
1166
Christopher Tate3799bc22009-05-06 16:13:56 -07001167 // ----- Track installation/removal of packages -----
1168 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1169 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001170 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001171
Christopher Tate3799bc22009-05-06 16:13:56 -07001172 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001173 boolean replacing = false;
1174 boolean added = false;
1175 Bundle extras = intent.getExtras();
1176 String pkgList[] = null;
1177 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatecc55f812011-08-16 16:06:53 -07001178 Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
1179 Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001180 Uri uri = intent.getData();
1181 if (uri == null) {
1182 return;
1183 }
1184 String pkgName = uri.getSchemeSpecificPart();
1185 if (pkgName != null) {
1186 pkgList = new String[] { pkgName };
1187 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001188 if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
1189 // use the existing "add with replacement" logic
1190 if (MORE_DEBUG) Slog.d(TAG, "PACKAGE_REPLACED, updating package " + pkgName);
1191 added = replacing = true;
1192 } else {
1193 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1194 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
1195 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001196 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001197 added = true;
1198 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001199 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001200 added = false;
1201 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1202 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001203
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001204 if (pkgList == null || pkgList.length == 0) {
1205 return;
1206 }
1207 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001208 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001209 for (String pkgName : pkgList) {
1210 if (replacing) {
1211 // The package was just upgraded
1212 updatePackageParticipantsLocked(pkgName);
1213 } else {
1214 // The package was just added
1215 addPackageParticipantsLocked(pkgName);
1216 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001217 }
1218 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001219 } else {
1220 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001221 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1222 } else {
1223 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001224 for (String pkgName : pkgList) {
1225 removePackageParticipantsLocked(pkgName);
1226 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001227 }
1228 }
1229 }
1230 }
1231 };
1232
Dan Egnor87a02bc2009-06-17 02:30:10 -07001233 // ----- Track connection to GoogleBackupTransport service -----
1234 ServiceConnection mGoogleConnection = new ServiceConnection() {
1235 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001236 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001237 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001238 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001239 }
1240
1241 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001242 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001243 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001244 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001245 }
1246 };
1247
Christopher Tate181fafa2009-05-14 11:12:14 -07001248 // Add the backup agents in the given package to our set of known backup participants.
1249 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -07001250 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001251 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -08001252 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -07001253 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001254 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001255 }
1256
Christopher Tate181fafa2009-05-14 11:12:14 -07001257 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001258 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001259 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001260 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -07001261 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001262 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001263 + " uid=" + p.applicationInfo.uid
1264 + " killAfterRestore="
1265 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001266 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001267 }
1268 }
1269
Dan Egnorefe52642009-06-24 00:16:33 -07001270 for (PackageInfo pkg : targetPkgs) {
1271 if (packageName == null || pkg.packageName.equals(packageName)) {
1272 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001273 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001274 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001275 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001276 mBackupParticipants.put(uid, set);
1277 }
Dan Egnorefe52642009-06-24 00:16:33 -07001278 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001279
1280 // If we've never seen this app before, schedule a backup for it
1281 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001282 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001283 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001284 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001285 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001286 }
Christopher Tate487529a2009-04-29 14:03:25 -07001287 }
1288 }
1289
Christopher Tate6785dd82009-06-18 15:58:25 -07001290 // Remove the given package's entry from our known active set. If
1291 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001292 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001293 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001294 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001295 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001296 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001297 } else {
1298 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001299 List<PackageInfo> knownPackages = allAgentPackages();
1300 for (PackageInfo pkg : knownPackages) {
1301 allApps.add(pkg.packageName);
1302 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001303 }
1304 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001305 }
1306
Joe Onorato8ad02812009-05-13 01:41:44 -04001307 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001308 List<String> allPackageNames) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001309 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001310 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001311 + ") removing " + allPackageNames.size() + " entries");
1312 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001313 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001314 }
1315 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001316 for (String pkg : allPackageNames) {
1317 if (packageName == null || pkg.equals(packageName)) {
1318 int uid = -1;
1319 try {
1320 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1321 uid = info.applicationInfo.uid;
1322 } catch (NameNotFoundException e) {
1323 // we don't know this package name, so just skip it for now
1324 continue;
1325 }
1326
Christopher Tate181fafa2009-05-14 11:12:14 -07001327 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001328 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001329 // Find the existing entry with the same package name, and remove it.
1330 // We can't just remove(app) because the instances are different.
1331 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001332 if (entry.packageName.equals(pkg)) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001333 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001334 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001335 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001336 break;
1337 }
1338 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001339 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001340 mBackupParticipants.delete(uid);
1341 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001342 }
1343 }
1344 }
1345 }
1346
Christopher Tate181fafa2009-05-14 11:12:14 -07001347 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001348 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001349 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001350 int flags = PackageManager.GET_SIGNATURES;
1351 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1352 int N = packages.size();
1353 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001354 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001355 try {
1356 ApplicationInfo app = pkg.applicationInfo;
1357 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001358 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001359 packages.remove(a);
1360 }
1361 else {
1362 // we will need the shared library path, so look that up and store it here
1363 app = mPackageManager.getApplicationInfo(pkg.packageName,
1364 PackageManager.GET_SHARED_LIBRARY_FILES);
1365 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1366 }
1367 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001368 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001369 }
1370 }
Dan Egnorefe52642009-06-24 00:16:33 -07001371 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001372 }
Christopher Tateaa088442009-06-16 18:25:46 -07001373
Christopher Tate3799bc22009-05-06 16:13:56 -07001374 // Reset the given package's known backup participants. Unlike add/remove, the update
1375 // action cannot be passed a null package name.
1376 void updatePackageParticipantsLocked(String packageName) {
1377 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001378 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001379 return;
1380 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001381 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001382
1383 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001384 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001385 List<String> allAppNames = new ArrayList<String>();
1386 for (PackageInfo pkg : allApps) {
1387 allAppNames.add(pkg.packageName);
1388 }
1389 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001390 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001391 }
1392
Christopher Tate84725812010-02-04 15:52:40 -08001393 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001394 // backed up at least once
1395 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001396 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1397
1398 synchronized (mEverStoredApps) {
1399 if (!mEverStoredApps.add(packageName)) return;
1400
1401 RandomAccessFile out = null;
1402 try {
1403 out = new RandomAccessFile(mEverStored, "rws");
1404 out.seek(out.length());
1405 out.writeUTF(packageName);
1406 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001407 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001408 } finally {
1409 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001410 }
1411 }
1412 }
1413
Christopher Tatee97e8072009-07-15 16:45:50 -07001414 // Remove our awareness of having ever backed up the given package
1415 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001416 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1417 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001418
Dan Egnor852f8e42009-09-30 11:20:45 -07001419 synchronized (mEverStoredApps) {
1420 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1421 // we'll recognize on initialization time that the package no longer
1422 // exists and fix it up then.
1423 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1424 RandomAccessFile known = null;
1425 try {
1426 known = new RandomAccessFile(tempKnownFile, "rws");
1427 mEverStoredApps.remove(packageName);
1428 for (String s : mEverStoredApps) {
1429 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001430 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001431 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001432 known.close();
1433 known = null;
1434 if (!tempKnownFile.renameTo(mEverStored)) {
1435 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1436 }
1437 } catch (IOException e) {
1438 // Bad: we couldn't create the new copy. For safety's sake we
1439 // abandon the whole process and remove all what's-backed-up
1440 // state entirely, meaning we'll force a backup pass for every
1441 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001442 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001443 mEverStoredApps.clear();
1444 tempKnownFile.delete();
1445 mEverStored.delete();
1446 } finally {
1447 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001448 }
1449 }
1450 }
1451
Christopher Tateb49ceb32010-02-08 16:22:24 -08001452 // Persistently record the current and ancestral backup tokens as well
1453 // as the set of packages with data [supposedly] available in the
1454 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001455 void writeRestoreTokens() {
1456 try {
1457 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001458
1459 // First, the version number of this record, for futureproofing
1460 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1461
1462 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001463 af.writeLong(mAncestralToken);
1464 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001465
1466 // Now write the set of ancestral packages
1467 if (mAncestralPackages == null) {
1468 af.writeInt(-1);
1469 } else {
1470 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001471 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001472 for (String pkgName : mAncestralPackages) {
1473 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001474 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001475 }
1476 }
Christopher Tate84725812010-02-04 15:52:40 -08001477 af.close();
1478 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001479 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001480 }
1481 }
1482
Dan Egnor87a02bc2009-06-17 02:30:10 -07001483 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001484 private IBackupTransport getTransport(String transportName) {
1485 synchronized (mTransports) {
1486 IBackupTransport transport = mTransports.get(transportName);
1487 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001488 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001489 }
1490 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001491 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001492 }
1493
Christopher Tatedf01dea2009-06-09 20:45:02 -07001494 // fire off a backup agent, blocking until it attaches or times out
1495 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1496 IBackupAgent agent = null;
1497 synchronized(mAgentConnectLock) {
1498 mConnecting = true;
1499 mConnectedAgent = null;
1500 try {
1501 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001502 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001503
1504 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001505 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001506 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1507 while (mConnecting && mConnectedAgent == null
1508 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001509 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001510 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001511 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001512 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001513 return null;
1514 }
1515 }
1516
1517 // if we timed out with no connect, abort and move on
1518 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001519 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001520 return null;
1521 }
1522 agent = mConnectedAgent;
1523 }
1524 } catch (RemoteException e) {
1525 // can't happen
1526 }
1527 }
1528 return agent;
1529 }
1530
Christopher Tatec7b31e32009-06-10 15:49:30 -07001531 // clear an application's data, blocking until the operation completes or times out
1532 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001533 // Don't wipe packages marked allowClearUserData=false
1534 try {
1535 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1536 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001537 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001538 + packageName);
1539 return;
1540 }
1541 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001542 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001543 return;
1544 }
1545
Christopher Tatec7b31e32009-06-10 15:49:30 -07001546 ClearDataObserver observer = new ClearDataObserver();
1547
1548 synchronized(mClearDataLock) {
1549 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001550 try {
1551 mActivityManager.clearApplicationUserData(packageName, observer);
1552 } catch (RemoteException e) {
1553 // can't happen because the activity manager is in this process
1554 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001555
1556 // only wait 10 seconds for the clear data to happen
1557 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1558 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1559 try {
1560 mClearDataLock.wait(5000);
1561 } catch (InterruptedException e) {
1562 // won't happen, but still.
1563 mClearingData = false;
1564 }
1565 }
1566 }
1567 }
1568
1569 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001570 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001571 synchronized(mClearDataLock) {
1572 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001573 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001574 }
1575 }
1576 }
1577
Christopher Tate1bb69062010-02-19 17:02:12 -08001578 // Get the restore-set token for the best-available restore set for this package:
1579 // the active set if possible, else the ancestral one. Returns zero if none available.
1580 long getAvailableRestoreToken(String packageName) {
1581 long token = mAncestralToken;
1582 synchronized (mQueueLock) {
1583 if (mEverStoredApps.contains(packageName)) {
1584 token = mCurrentToken;
1585 }
1586 }
1587 return token;
1588 }
1589
Christopher Tate44a27902010-01-27 17:15:49 -08001590 // -----
1591 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1592 boolean waitUntilOperationComplete(int token) {
1593 int finalState = OP_PENDING;
1594 synchronized (mCurrentOpLock) {
1595 try {
1596 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1597 try {
1598 mCurrentOpLock.wait();
1599 } catch (InterruptedException e) {}
1600 }
1601 } catch (IndexOutOfBoundsException e) {
1602 // the operation has been mysteriously cleared from our
1603 // bookkeeping -- consider this a success and ignore it.
1604 }
1605 }
1606 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001607 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001608 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001609 return finalState == OP_ACKNOWLEDGED;
1610 }
1611
1612 void prepareOperationTimeout(int token, long interval) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001613 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001614 + " interval=" + interval);
Christopher Tate4a627c72011-04-01 14:43:32 -07001615 synchronized (mCurrentOpLock) {
1616 mCurrentOperations.put(token, OP_PENDING);
1617 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1618 mBackupHandler.sendMessageDelayed(msg, interval);
1619 }
Christopher Tate44a27902010-01-27 17:15:49 -08001620 }
1621
Christopher Tate043dadc2009-06-02 16:11:00 -07001622 // ----- Back up a set of applications via a worker thread -----
1623
Christopher Tate44a27902010-01-27 17:15:49 -08001624 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001625 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001626 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001627 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001628 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001629 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001630
Christopher Tate44a27902010-01-27 17:15:49 -08001631 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001632 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001633 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001634 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001635 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001636
1637 try {
1638 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1639 } catch (RemoteException e) {
1640 // can't happen; the transport is local
1641 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001642 }
1643
Christopher Tate043dadc2009-06-02 16:11:00 -07001644 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001645 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001646 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001647 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001648
Christopher Tate79588342009-06-30 16:11:49 -07001649 // Backups run at background priority
1650 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1651
Christopher Tate043dadc2009-06-02 16:11:00 -07001652 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001653 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001654
Dan Egnor852f8e42009-09-30 11:20:45 -07001655 // If we haven't stored package manager metadata yet, we must init the transport.
1656 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1657 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001658 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001659 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001660 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001661 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001662 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001663 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001664 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001665 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001666 }
Dan Egnor01445162009-09-21 17:04:05 -07001667 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001668
1669 // The package manager doesn't have a proper <application> etc, but since
1670 // it's running here in the system process we can just set up its agent
1671 // directly and use a synthetic BackupRequest. We always run this pass
1672 // because it's cheap and this way we guarantee that we don't get out of
1673 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001674 if (status == BackupConstants.TRANSPORT_OK) {
1675 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1676 mPackageManager, allAgentPackages());
Christopher Tatecc55f812011-08-16 16:06:53 -07001677 status = processOneBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001678 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1679 }
Christopher Tate90967f42009-09-20 15:28:33 -07001680
Dan Egnor01445162009-09-21 17:04:05 -07001681 if (status == BackupConstants.TRANSPORT_OK) {
1682 // Now run all the backups in our queue
1683 status = doQueuedBackups(mTransport);
1684 }
1685
1686 if (status == BackupConstants.TRANSPORT_OK) {
1687 // Tell the transport to finish everything it has buffered
1688 status = mTransport.finishBackup();
1689 if (status == BackupConstants.TRANSPORT_OK) {
1690 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001691 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001692 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001693 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001694 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001695 }
1696 }
1697
Dan Egnor01445162009-09-21 17:04:05 -07001698 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001699 // The backend reports that our dataset has been wiped. We need to
1700 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001701 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001702 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001703 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001704 }
1705 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001706 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001707 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001708 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001709 // If everything actually went through and this is the first time we've
1710 // done a backup, we can now record what the current backup dataset token
1711 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001712 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001713 try {
1714 mCurrentToken = mTransport.getCurrentRestoreSet();
1715 } catch (RemoteException e) { /* cannot happen */ }
1716 writeRestoreTokens();
1717 }
1718
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001719 // If things went wrong, we need to re-stage the apps we had expected
1720 // to be backing up in this pass. This journals the package names in
1721 // the current active pending-backup file, not in the we are holding
1722 // here in mJournal.
1723 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001724 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001725 for (BackupRequest req : mQueue) {
Christopher Tatecc55f812011-08-16 16:06:53 -07001726 dataChangedImpl(req.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001727 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001728
1729 // We also want to reset the backup schedule based on whatever
1730 // the transport suggests by way of retry/backoff time.
1731 try {
1732 startBackupAlarmsLocked(mTransport.requestBackupTime());
1733 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001734 }
1735
1736 // Either backup was successful, in which case we of course do not need
1737 // this pass's journal any more; or it failed, in which case we just
1738 // re-enqueued all of these packages in the current active journal.
1739 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001740 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001741 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001742 }
1743
Christopher Tatec2af5d32010-02-02 15:18:58 -08001744 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001745 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001746 backupNow();
1747 }
1748
Dan Egnorbb9001c2009-07-27 12:20:13 -07001749 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001750 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001751 }
1752
Dan Egnor01445162009-09-21 17:04:05 -07001753 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001754 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001755 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001756
Christopher Tatec28083a2010-12-14 16:16:44 -08001757 // Verify that the requested app exists; it might be something that
1758 // requested a backup but was then uninstalled. The request was
1759 // journalled and rather than tamper with the journal it's safer
Christopher Tatecc55f812011-08-16 16:06:53 -07001760 // to sanity-check here. This also gives us the classname of the
1761 // package's backup agent.
1762 PackageInfo pkg;
Christopher Tatec28083a2010-12-14 16:16:44 -08001763 try {
Christopher Tatecc55f812011-08-16 16:06:53 -07001764 pkg = mPackageManager.getPackageInfo(request.packageName, 0);
Christopher Tatec28083a2010-12-14 16:16:44 -08001765 } catch (NameNotFoundException e) {
1766 Slog.d(TAG, "Package does not exist; skipping");
1767 continue;
1768 }
1769
Christopher Tate043dadc2009-06-02 16:11:00 -07001770 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001771 try {
Christopher Tatecc55f812011-08-16 16:06:53 -07001772 mWakelock.setWorkSource(new WorkSource(pkg.applicationInfo.uid));
1773 agent = bindToAgentSynchronous(pkg.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001774 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001775 if (agent != null) {
Christopher Tatecc55f812011-08-16 16:06:53 -07001776 int result = processOneBackup(request.packageName, agent, transport);
Dan Egnor01445162009-09-21 17:04:05 -07001777 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001778 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001779 } catch (SecurityException ex) {
1780 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001781 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001782 } finally {
1783 try { // unbind even on timeout, just in case
Christopher Tatecc55f812011-08-16 16:06:53 -07001784 mActivityManager.unbindBackupAgent(pkg.applicationInfo);
Dan Egnor01445162009-09-21 17:04:05 -07001785 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001786 }
1787 }
Dan Egnor01445162009-09-21 17:04:05 -07001788
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001789 mWakelock.setWorkSource(null);
1790
Dan Egnor01445162009-09-21 17:04:05 -07001791 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001792 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001793
Christopher Tatecc55f812011-08-16 16:06:53 -07001794 private int processOneBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07001795 IBackupTransport transport) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001796 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001797
Dan Egnorbb9001c2009-07-27 12:20:13 -07001798 File savedStateName = new File(mStateDir, packageName);
1799 File backupDataName = new File(mDataDir, packageName + ".data");
1800 File newStateName = new File(mStateDir, packageName + ".new");
1801
1802 ParcelFileDescriptor savedState = null;
1803 ParcelFileDescriptor backupData = null;
1804 ParcelFileDescriptor newState = null;
1805
1806 PackageInfo packInfo;
Christopher Tate4a627c72011-04-01 14:43:32 -07001807 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001808 try {
1809 // Look up the package info & signatures. This is first so that if it
1810 // throws an exception, there's no file setup yet that would need to
1811 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001812 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1813 // The metadata 'package' is synthetic
1814 packInfo = new PackageInfo();
1815 packInfo.packageName = packageName;
1816 } else {
1817 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001818 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001819 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001820
Christopher Tatec7b31e32009-06-10 15:49:30 -07001821 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001822 // the saved-state "file". This is by definition an incremental,
1823 // so we build a saved state file to pass.
1824 savedState = ParcelFileDescriptor.open(savedStateName,
1825 ParcelFileDescriptor.MODE_READ_ONLY |
1826 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001827
Dan Egnorbb9001c2009-07-27 12:20:13 -07001828 backupData = ParcelFileDescriptor.open(backupDataName,
1829 ParcelFileDescriptor.MODE_READ_WRITE |
1830 ParcelFileDescriptor.MODE_CREATE |
1831 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001832
Dan Egnorbb9001c2009-07-27 12:20:13 -07001833 newState = ParcelFileDescriptor.open(newStateName,
1834 ParcelFileDescriptor.MODE_READ_WRITE |
1835 ParcelFileDescriptor.MODE_CREATE |
1836 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001837
Christopher Tate44a27902010-01-27 17:15:49 -08001838 // Initiate the target's backup pass
1839 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07001840 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
Christopher Tate44a27902010-01-27 17:15:49 -08001841 boolean success = waitUntilOperationComplete(token);
1842
1843 if (!success) {
1844 // timeout -- bail out into the failed-transaction logic
1845 throw new RuntimeException("Backup timeout");
1846 }
1847
Dan Egnorbb9001c2009-07-27 12:20:13 -07001848 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001849 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001850 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001851 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001852 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001853 backupDataName.delete();
1854 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001855 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001856 } finally {
1857 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1858 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1859 try { if (newState != null) newState.close(); } catch (IOException e) {}
1860 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001861 synchronized (mCurrentOpLock) {
1862 mCurrentOperations.clear();
1863 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001864 }
1865
1866 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001867 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001868 try {
1869 int size = (int) backupDataName.length();
1870 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001871 if (result == BackupConstants.TRANSPORT_OK) {
1872 backupData = ParcelFileDescriptor.open(backupDataName,
1873 ParcelFileDescriptor.MODE_READ_ONLY);
1874 result = transport.performBackup(packInfo, backupData);
1875 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001876
Dan Egnor83861e72009-09-17 16:17:55 -07001877 // TODO - We call finishBackup() for each application backed up, because
1878 // we need to know now whether it succeeded or failed. Instead, we should
1879 // hold off on finishBackup() until the end, which implies holding off on
1880 // renaming *all* the output state files (see below) until that happens.
1881
Dan Egnor01445162009-09-21 17:04:05 -07001882 if (result == BackupConstants.TRANSPORT_OK) {
1883 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001884 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001885 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001886 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001887 }
1888
1889 // After successful transport, delete the now-stale data
1890 // and juggle the files so that next time we supply the agent
1891 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001892 if (result == BackupConstants.TRANSPORT_OK) {
1893 backupDataName.delete();
1894 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001895 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001896 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001897 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001898 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001899 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001900 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001901 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001902 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001903 } finally {
1904 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001905 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001906
Dan Egnor01445162009-09-21 17:04:05 -07001907 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001908 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001909 }
1910
Christopher Tatedf01dea2009-06-09 20:45:02 -07001911
Christopher Tate4a627c72011-04-01 14:43:32 -07001912 // ----- Full backup to a file/socket -----
1913
1914 class PerformFullBackupTask implements Runnable {
1915 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07001916 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07001917 IFullBackupRestoreObserver mObserver;
1918 boolean mIncludeApks;
1919 boolean mIncludeShared;
1920 boolean mAllApps;
1921 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07001922 String mCurrentPassword;
1923 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07001924 AtomicBoolean mLatchObject;
1925 File mFilesDir;
1926 File mManifestFile;
1927
Christopher Tate7926a692011-07-11 11:31:57 -07001928 class FullBackupRunner implements Runnable {
1929 PackageInfo mPackage;
1930 IBackupAgent mAgent;
1931 ParcelFileDescriptor mPipe;
1932 int mToken;
1933 boolean mSendApk;
1934
1935 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
1936 int token, boolean sendApk) throws IOException {
1937 mPackage = pack;
1938 mAgent = agent;
1939 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
1940 mToken = token;
1941 mSendApk = sendApk;
1942 }
1943
1944 @Override
1945 public void run() {
1946 try {
1947 BackupDataOutput output = new BackupDataOutput(
1948 mPipe.getFileDescriptor());
1949
Christopher Tatec58efa62011-08-01 19:20:14 -07001950 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
Christopher Tate7926a692011-07-11 11:31:57 -07001951 writeAppManifest(mPackage, mManifestFile, mSendApk);
1952 FullBackup.backupToTar(mPackage.packageName, null, null,
1953 mFilesDir.getAbsolutePath(),
1954 mManifestFile.getAbsolutePath(),
1955 output);
1956
1957 if (mSendApk) {
1958 writeApkToBackup(mPackage, output);
1959 }
1960
Christopher Tatec58efa62011-08-01 19:20:14 -07001961 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate7926a692011-07-11 11:31:57 -07001962 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL);
1963 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
1964 } catch (IOException e) {
1965 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
1966 } catch (RemoteException e) {
1967 Slog.e(TAG, "Remote agent vanished during full backup of "
1968 + mPackage.packageName);
1969 } finally {
1970 try {
1971 mPipe.close();
1972 } catch (IOException e) {}
1973 }
1974 }
1975 }
1976
Christopher Tate4a627c72011-04-01 14:43:32 -07001977 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07001978 boolean includeApks, boolean includeShared, String curPassword,
1979 String encryptPassword, boolean doAllApps, String[] packages,
1980 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07001981 mOutputFile = fd;
1982 mObserver = observer;
1983 mIncludeApks = includeApks;
1984 mIncludeShared = includeShared;
1985 mAllApps = doAllApps;
1986 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07001987 mCurrentPassword = curPassword;
1988 // when backing up, if there is a current backup password, we require that
1989 // the user use a nonempty encryption password as well. if one is supplied
1990 // in the UI we use that, but if the UI was left empty we fall back to the
1991 // current backup password (which was supplied by the user as well).
1992 if (encryptPassword == null || "".equals(encryptPassword)) {
1993 mEncryptPassword = curPassword;
1994 } else {
1995 mEncryptPassword = encryptPassword;
1996 }
Christopher Tate4a627c72011-04-01 14:43:32 -07001997 mLatchObject = latch;
1998
1999 mFilesDir = new File("/data/system");
2000 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2001 }
2002
2003 @Override
2004 public void run() {
2005 final List<PackageInfo> packagesToBackup;
2006
Christopher Tateb0628bf2011-06-02 15:08:13 -07002007 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002008 sendStartBackup();
2009
2010 // doAllApps supersedes the package set if any
2011 if (mAllApps) {
2012 packagesToBackup = mPackageManager.getInstalledPackages(
2013 PackageManager.GET_SIGNATURES);
2014 } else {
2015 packagesToBackup = new ArrayList<PackageInfo>();
2016 for (String pkgName : mPackages) {
2017 try {
2018 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2019 PackageManager.GET_SIGNATURES));
2020 } catch (NameNotFoundException e) {
2021 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2022 }
2023 }
2024 }
2025
Christopher Tatea858cb02011-06-03 12:27:51 -07002026 // Cull any packages that have indicated that backups are not permitted.
2027 for (int i = 0; i < packagesToBackup.size(); ) {
2028 PackageInfo info = packagesToBackup.get(i);
2029 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
2030 packagesToBackup.remove(i);
2031 } else {
2032 i++;
2033 }
2034 }
2035
Christopher Tate7926a692011-07-11 11:31:57 -07002036 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002037 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002038
Christopher Tate4a627c72011-04-01 14:43:32 -07002039 PackageInfo pkg = null;
2040 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002041 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002042 boolean compressing = COMPRESS_FULL_BACKUPS;
2043 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002044
Christopher Tateeef4ae42011-08-05 13:15:53 -07002045 // Verify that the given password matches the currently-active
2046 // backup password, if any
2047 if (hasBackupPassword()) {
2048 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2049 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2050 return;
2051 }
2052 }
2053
Christopher Tate7bdb0962011-07-13 19:30:21 -07002054 // Write the global file header. All strings are UTF-8 encoded; lines end
2055 // with a '\n' byte. Actual backup data begins immediately following the
2056 // final '\n'.
2057 //
2058 // line 1: "ANDROID BACKUP"
2059 // line 2: backup file format version, currently "1"
2060 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002061 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2062 //
2063 // When line 4 is not "none", then additional header data follows:
2064 //
2065 // line 5: user password salt [hex]
2066 // line 6: master key checksum salt [hex]
2067 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2068 // line 8: IV of the user key [hex]
2069 // line 9: master key blob [hex]
2070 // IV of the master key, master key itself, master key checksum hash
2071 //
2072 // The master key checksum is the master key plus its checksum salt, run through
2073 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2074 // correct password for decrypting the archive: the master key decrypted from
2075 // the archive using the user-supplied password is also run through PBKDF2 in
2076 // this way, and if the result does not match the checksum as stored in the
2077 // archive, then we know that the user-supplied password does not match the
2078 // archive's.
2079 StringBuilder headerbuf = new StringBuilder(1024);
2080
Christopher Tate7bdb0962011-07-13 19:30:21 -07002081 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002082 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2083 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002084
2085 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002086 // Set up the encryption stage if appropriate, and emit the correct header
2087 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002088 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2089 } else {
2090 headerbuf.append("none\n");
2091 }
2092
Christopher Tate7bdb0962011-07-13 19:30:21 -07002093 byte[] header = headerbuf.toString().getBytes("UTF-8");
2094 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002095
2096 // Set up the compression stage feeding into the encryption stage (if any)
2097 if (compressing) {
2098 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2099 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2100 }
2101
2102 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002103 } catch (Exception e) {
2104 // Should never happen!
2105 Slog.e(TAG, "Unable to emit archive header", e);
2106 return;
2107 }
2108
Christopher Tateb0628bf2011-06-02 15:08:13 -07002109 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002110 int N = packagesToBackup.size();
2111 for (int i = 0; i < N; i++) {
2112 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002113 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002114 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002115
Christopher Tate6853fcf2011-08-10 17:52:21 -07002116 // Shared storage if requested
Christopher Tateb0628bf2011-06-02 15:08:13 -07002117 if (mIncludeShared) {
2118 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07002119 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07002120
2121 // Done!
2122 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002123 } catch (RemoteException e) {
2124 Slog.e(TAG, "App died during full backup");
2125 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002126 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002127 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002128 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002129 mOutputFile.close();
2130 } catch (IOException e) {
2131 /* nothing we can do about this */
2132 }
2133 synchronized (mCurrentOpLock) {
2134 mCurrentOperations.clear();
2135 }
2136 synchronized (mLatchObject) {
2137 mLatchObject.set(true);
2138 mLatchObject.notifyAll();
2139 }
2140 sendEndBackup();
2141 mWakelock.release();
2142 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
2143 }
2144 }
2145
Christopher Tate2efd2db2011-07-19 16:32:49 -07002146 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2147 OutputStream ofstream) throws Exception {
2148 // User key will be used to encrypt the master key.
2149 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002150 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002151 PBKDF2_HASH_ROUNDS);
2152
2153 // the master key is random for each backup
2154 byte[] masterPw = new byte[256 / 8];
2155 mRng.nextBytes(masterPw);
2156 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2157
2158 // primary encryption of the datastream with the random key
2159 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2160 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2161 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2162 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2163
2164 // line 4: name of encryption algorithm
2165 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2166 headerbuf.append('\n');
2167 // line 5: user password salt [hex]
2168 headerbuf.append(byteArrayToHex(newUserSalt));
2169 headerbuf.append('\n');
2170 // line 6: master key checksum salt [hex]
2171 headerbuf.append(byteArrayToHex(checksumSalt));
2172 headerbuf.append('\n');
2173 // line 7: number of PBKDF2 rounds used [decimal]
2174 headerbuf.append(PBKDF2_HASH_ROUNDS);
2175 headerbuf.append('\n');
2176
2177 // line 8: IV of the user key [hex]
2178 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2179 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2180
2181 byte[] IV = mkC.getIV();
2182 headerbuf.append(byteArrayToHex(IV));
2183 headerbuf.append('\n');
2184
2185 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2186 // [byte] IV length = Niv
2187 // [array of Niv bytes] IV itself
2188 // [byte] master key length = Nmk
2189 // [array of Nmk bytes] master key itself
2190 // [byte] MK checksum hash length = Nck
2191 // [array of Nck bytes] master key checksum hash
2192 //
2193 // The checksum is the (master key + checksum salt), run through the
2194 // stated number of PBKDF2 rounds
2195 IV = c.getIV();
2196 byte[] mk = masterKeySpec.getEncoded();
2197 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2198 checksumSalt, PBKDF2_HASH_ROUNDS);
2199
2200 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2201 + checksum.length + 3);
2202 DataOutputStream mkOut = new DataOutputStream(blob);
2203 mkOut.writeByte(IV.length);
2204 mkOut.write(IV);
2205 mkOut.writeByte(mk.length);
2206 mkOut.write(mk);
2207 mkOut.writeByte(checksum.length);
2208 mkOut.write(checksum);
2209 mkOut.flush();
2210 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2211 headerbuf.append(byteArrayToHex(encryptedMk));
2212 headerbuf.append('\n');
2213
2214 return finalOutput;
2215 }
2216
2217 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002218 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002219 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2220
2221 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2222 IApplicationThread.BACKUP_MODE_FULL);
2223 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002224 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002225 try {
Christopher Tate7926a692011-07-11 11:31:57 -07002226 pipes = ParcelFileDescriptor.createPipe();
2227
Christopher Tateb0628bf2011-06-02 15:08:13 -07002228 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07002229 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07002230 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2231 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2232 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2233
2234 sendOnBackupPackage(pkg.packageName);
2235
Christopher Tate7926a692011-07-11 11:31:57 -07002236 final int token = generateToken();
2237 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
2238 token, sendApk);
2239 pipes[1].close(); // the runner has dup'd it
2240 pipes[1] = null;
2241 Thread t = new Thread(runner);
2242 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002243
Christopher Tate7926a692011-07-11 11:31:57 -07002244 // Now pull data from the app and stuff it into the compressor
2245 try {
2246 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2247 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002248
Christopher Tate7926a692011-07-11 11:31:57 -07002249 byte[] buffer = new byte[16 * 1024];
2250 int chunkTotal;
2251 while ((chunkTotal = in.readInt()) > 0) {
2252 while (chunkTotal > 0) {
2253 int toRead = (chunkTotal > buffer.length)
2254 ? buffer.length : chunkTotal;
2255 int nRead = in.read(buffer, 0, toRead);
2256 out.write(buffer, 0, nRead);
2257 chunkTotal -= nRead;
2258 }
2259 }
2260 } catch (IOException e) {
2261 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002262 }
2263
Christopher Tateb0628bf2011-06-02 15:08:13 -07002264 if (!waitUntilOperationComplete(token)) {
2265 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2266 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002267 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002268 }
Christopher Tate7926a692011-07-11 11:31:57 -07002269
Christopher Tateb0628bf2011-06-02 15:08:13 -07002270 } catch (IOException e) {
2271 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002272 } finally {
2273 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002274 // flush after every package
2275 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002276 if (pipes != null) {
2277 if (pipes[0] != null) pipes[0].close();
2278 if (pipes[1] != null) pipes[1].close();
2279 }
Christopher Tate7926a692011-07-11 11:31:57 -07002280 } catch (IOException e) {
2281 Slog.w(TAG, "Error bringing down backup stack");
2282 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002283 }
2284 } else {
2285 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2286 }
2287 tearDown(pkg);
2288 }
2289
Christopher Tate79ec80d2011-06-24 14:58:49 -07002290 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2291 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2292 final String appSourceDir = pkg.applicationInfo.sourceDir;
2293 final String apkDir = new File(appSourceDir).getParent();
2294 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2295 apkDir, appSourceDir, output);
2296
2297 // Save associated .obb content if it exists and we did save the apk
2298 // check for .obb and save those too
2299 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2300 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002301 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002302 File[] obbFiles = obbDir.listFiles();
2303 if (obbFiles != null) {
2304 final String obbDirName = obbDir.getAbsolutePath();
2305 for (File obb : obbFiles) {
2306 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2307 obbDirName, obb.getAbsolutePath(), output);
2308 }
2309 }
2310 }
2311 }
2312
Christopher Tateb0628bf2011-06-02 15:08:13 -07002313 private void backupSharedStorage() throws RemoteException {
2314 PackageInfo pkg = null;
2315 try {
2316 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
2317 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2318 IApplicationThread.BACKUP_MODE_FULL);
2319 if (agent != null) {
2320 sendOnBackupPackage("Shared storage");
2321
2322 final int token = generateToken();
2323 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002324 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002325 if (!waitUntilOperationComplete(token)) {
2326 Slog.e(TAG, "Full backup failed on shared storage");
2327 } else {
2328 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
2329 }
2330 } else {
2331 Slog.e(TAG, "Could not bind to shared storage backup agent");
2332 }
2333 } catch (NameNotFoundException e) {
2334 Slog.e(TAG, "Shared storage backup package not found");
2335 } finally {
2336 tearDown(pkg);
2337 }
2338 }
2339
Christopher Tate6853fcf2011-08-10 17:52:21 -07002340 private void finalizeBackup(OutputStream out) {
2341 try {
2342 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2343 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2344 out.write(eof);
2345 } catch (IOException e) {
2346 Slog.w(TAG, "Error attempting to finalize backup stream");
2347 }
2348 }
2349
Christopher Tate4a627c72011-04-01 14:43:32 -07002350 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2351 throws IOException {
2352 // Manifest format. All data are strings ending in LF:
2353 // BACKUP_MANIFEST_VERSION, currently 1
2354 //
2355 // Version 1:
2356 // package name
2357 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002358 // platform versionCode
2359 // getInstallerPackageName() for this package (maybe empty)
2360 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002361 // number of signatures == N
2362 // N*: signature byte array in ascii format per Signature.toCharsString()
2363 StringBuilder builder = new StringBuilder(4096);
2364 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2365
2366 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2367 printer.println(pkg.packageName);
2368 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002369 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2370
2371 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2372 printer.println((installerName != null) ? installerName : "");
2373
Christopher Tate4a627c72011-04-01 14:43:32 -07002374 printer.println(withApk ? "1" : "0");
2375 if (pkg.signatures == null) {
2376 printer.println("0");
2377 } else {
2378 printer.println(Integer.toString(pkg.signatures.length));
2379 for (Signature sig : pkg.signatures) {
2380 printer.println(sig.toCharsString());
2381 }
2382 }
2383
2384 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002385 outstream.write(builder.toString().getBytes());
2386 outstream.close();
2387 }
2388
2389 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002390 if (pkg != null) {
2391 final ApplicationInfo app = pkg.applicationInfo;
2392 if (app != null) {
2393 try {
2394 // unbind and tidy up even on timeout or failure, just in case
2395 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002396
Christopher Tateb0628bf2011-06-02 15:08:13 -07002397 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002398 if (app.uid != Process.SYSTEM_UID
2399 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002400 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002401 mActivityManager.killApplicationProcess(app.processName, app.uid);
2402 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002403 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002404 }
2405 } catch (RemoteException e) {
2406 Slog.d(TAG, "Lost app trying to shut down");
2407 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002408 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002409 }
2410 }
2411
2412 // wrappers for observer use
2413 void sendStartBackup() {
2414 if (mObserver != null) {
2415 try {
2416 mObserver.onStartBackup();
2417 } catch (RemoteException e) {
2418 Slog.w(TAG, "full backup observer went away: startBackup");
2419 mObserver = null;
2420 }
2421 }
2422 }
2423
2424 void sendOnBackupPackage(String name) {
2425 if (mObserver != null) {
2426 try {
2427 // TODO: use a more user-friendly name string
2428 mObserver.onBackupPackage(name);
2429 } catch (RemoteException e) {
2430 Slog.w(TAG, "full backup observer went away: backupPackage");
2431 mObserver = null;
2432 }
2433 }
2434 }
2435
2436 void sendEndBackup() {
2437 if (mObserver != null) {
2438 try {
2439 mObserver.onEndBackup();
2440 } catch (RemoteException e) {
2441 Slog.w(TAG, "full backup observer went away: endBackup");
2442 mObserver = null;
2443 }
2444 }
2445 }
2446 }
2447
2448
Christopher Tate75a99702011-05-18 16:28:19 -07002449 // ----- Full restore from a file/socket -----
2450
2451 // Description of a file in the restore datastream
2452 static class FileMetadata {
2453 String packageName; // name of the owning app
2454 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002455 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002456 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2457 String path; // subpath within the semantic domain
2458 long mode; // e.g. 0666 (actually int)
2459 long mtime; // last mod time, UTC time_t (actually int)
2460 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002461
2462 @Override
2463 public String toString() {
2464 StringBuilder sb = new StringBuilder(128);
2465 sb.append("FileMetadata{");
2466 sb.append(packageName); sb.append(',');
2467 sb.append(type); sb.append(',');
2468 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2469 sb.append(size);
2470 sb.append('}');
2471 return sb.toString();
2472 }
Christopher Tate75a99702011-05-18 16:28:19 -07002473 }
2474
2475 enum RestorePolicy {
2476 IGNORE,
2477 ACCEPT,
2478 ACCEPT_IF_APK
2479 }
2480
2481 class PerformFullRestoreTask implements Runnable {
2482 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002483 String mCurrentPassword;
2484 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002485 IFullBackupRestoreObserver mObserver;
2486 AtomicBoolean mLatchObject;
2487 IBackupAgent mAgent;
2488 String mAgentPackage;
2489 ApplicationInfo mTargetApp;
2490 ParcelFileDescriptor[] mPipes = null;
2491
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002492 long mBytes;
2493
Christopher Tate75a99702011-05-18 16:28:19 -07002494 // possible handling states for a given package in the restore dataset
2495 final HashMap<String, RestorePolicy> mPackagePolicies
2496 = new HashMap<String, RestorePolicy>();
2497
2498 // installer package names for each encountered app, derived from the manifests
2499 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2500
2501 // Signatures for a given package found in its manifest file
2502 final HashMap<String, Signature[]> mManifestSignatures
2503 = new HashMap<String, Signature[]>();
2504
2505 // Packages we've already wiped data on when restoring their first file
2506 final HashSet<String> mClearedPackages = new HashSet<String>();
2507
Christopher Tate728a1c42011-07-28 18:03:03 -07002508 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002509 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002510 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002511 mCurrentPassword = curPassword;
2512 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002513 mObserver = observer;
2514 mLatchObject = latch;
2515 mAgent = null;
2516 mAgentPackage = null;
2517 mTargetApp = null;
2518
2519 // Which packages we've already wiped data on. We prepopulate this
2520 // with a whitelist of packages known to be unclearable.
2521 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002522 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002523
Christopher Tate75a99702011-05-18 16:28:19 -07002524 }
2525
2526 class RestoreFileRunnable implements Runnable {
2527 IBackupAgent mAgent;
2528 FileMetadata mInfo;
2529 ParcelFileDescriptor mSocket;
2530 int mToken;
2531
2532 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2533 ParcelFileDescriptor socket, int token) throws IOException {
2534 mAgent = agent;
2535 mInfo = info;
2536 mToken = token;
2537
2538 // This class is used strictly for process-local binder invocations. The
2539 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2540 // do not automatically get a 'dup'ed descriptor that we can can continue
2541 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2542 // before proceeding to do the restore.
2543 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2544 }
2545
2546 @Override
2547 public void run() {
2548 try {
2549 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2550 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2551 mToken, mBackupManagerBinder);
2552 } catch (RemoteException e) {
2553 // never happens; this is used strictly for local binder calls
2554 }
2555 }
2556 }
2557
2558 @Override
2559 public void run() {
2560 Slog.i(TAG, "--- Performing full-dataset restore ---");
2561 sendStartRestore();
2562
Christopher Tateb0628bf2011-06-02 15:08:13 -07002563 // Are we able to restore shared-storage data?
2564 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2565 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2566 }
2567
Christopher Tate2efd2db2011-07-19 16:32:49 -07002568 FileInputStream rawInStream = null;
2569 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002570 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002571 if (hasBackupPassword()) {
2572 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2573 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2574 return;
2575 }
2576 }
2577
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002578 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002579 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002580 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2581 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002582
2583 // First, parse out the unencrypted/uncompressed header
2584 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002585 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002586 final InputStream in;
2587
2588 boolean okay = false;
2589 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2590 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002591 rawDataIn.readFully(streamHeader);
2592 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2593 if (Arrays.equals(magicBytes, streamHeader)) {
2594 // okay, header looks good. now parse out the rest of the fields.
2595 String s = readHeaderLine(rawInStream);
2596 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2597 // okay, it's a version we recognize
2598 s = readHeaderLine(rawInStream);
2599 compressed = (Integer.parseInt(s) != 0);
2600 s = readHeaderLine(rawInStream);
2601 if (s.equals("none")) {
2602 // no more header to parse; we're good to go
2603 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07002604 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002605 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
2606 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07002607 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002608 }
2609 } else Slog.w(TAG, "Archive is encrypted but no password given");
2610 } else Slog.w(TAG, "Wrong header version: " + s);
2611 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002612
2613 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002614 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002615 return;
2616 }
2617
2618 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07002619 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07002620
2621 boolean didRestore;
2622 do {
Christopher Tate7926a692011-07-11 11:31:57 -07002623 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07002624 } while (didRestore);
2625
Christopher Tatec58efa62011-08-01 19:20:14 -07002626 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002627 } catch (IOException e) {
2628 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07002629 } finally {
2630 tearDownPipes();
2631 tearDownAgent(mTargetApp);
2632
2633 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002634 if (rawDataIn != null) rawDataIn.close();
2635 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07002636 mInputFile.close();
2637 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002638 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002639 /* nothing we can do about this */
2640 }
2641 synchronized (mCurrentOpLock) {
2642 mCurrentOperations.clear();
2643 }
2644 synchronized (mLatchObject) {
2645 mLatchObject.set(true);
2646 mLatchObject.notifyAll();
2647 }
2648 sendEndRestore();
2649 mWakelock.release();
Christopher Tatec58efa62011-08-01 19:20:14 -07002650 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07002651 }
2652 }
2653
Christopher Tate7bdb0962011-07-13 19:30:21 -07002654 String readHeaderLine(InputStream in) throws IOException {
2655 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002656 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002657 while ((c = in.read()) >= 0) {
2658 if (c == '\n') break; // consume and discard the newlines
2659 buffer.append((char)c);
2660 }
2661 return buffer.toString();
2662 }
2663
Christopher Tate2efd2db2011-07-19 16:32:49 -07002664 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
2665 InputStream result = null;
2666 try {
2667 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
2668
2669 String userSaltHex = readHeaderLine(rawInStream); // 5
2670 byte[] userSalt = hexToByteArray(userSaltHex);
2671
2672 String ckSaltHex = readHeaderLine(rawInStream); // 6
2673 byte[] ckSalt = hexToByteArray(ckSaltHex);
2674
2675 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
2676 String userIvHex = readHeaderLine(rawInStream); // 8
2677
2678 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
2679
2680 // decrypt the master key blob
2681 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07002682 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002683 rounds);
2684 byte[] IV = hexToByteArray(userIvHex);
2685 IvParameterSpec ivSpec = new IvParameterSpec(IV);
2686 c.init(Cipher.DECRYPT_MODE,
2687 new SecretKeySpec(userKey.getEncoded(), "AES"),
2688 ivSpec);
2689 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
2690 byte[] mkBlob = c.doFinal(mkCipher);
2691
2692 // first, the master key IV
2693 int offset = 0;
2694 int len = mkBlob[offset++];
2695 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
2696 offset += len;
2697 // then the master key itself
2698 len = mkBlob[offset++];
2699 byte[] mk = Arrays.copyOfRange(mkBlob,
2700 offset, offset + len);
2701 offset += len;
2702 // and finally the master key checksum hash
2703 len = mkBlob[offset++];
2704 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
2705 offset, offset + len);
2706
2707 // now validate the decrypted master key against the checksum
2708 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
2709 if (Arrays.equals(calculatedCk, mkChecksum)) {
2710 ivSpec = new IvParameterSpec(IV);
2711 c.init(Cipher.DECRYPT_MODE,
2712 new SecretKeySpec(mk, "AES"),
2713 ivSpec);
2714 // Only if all of the above worked properly will 'result' be assigned
2715 result = new CipherInputStream(rawInStream, c);
2716 } else Slog.w(TAG, "Incorrect password");
2717 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
2718 } catch (InvalidAlgorithmParameterException e) {
2719 Slog.e(TAG, "Needed parameter spec unavailable!", e);
2720 } catch (BadPaddingException e) {
2721 // This case frequently occurs when the wrong password is used to decrypt
2722 // the master key. Use the identical "incorrect password" log text as is
2723 // used in the checksum failure log in order to avoid providing additional
2724 // information to an attacker.
2725 Slog.w(TAG, "Incorrect password");
2726 } catch (IllegalBlockSizeException e) {
2727 Slog.w(TAG, "Invalid block size in master key");
2728 } catch (NoSuchAlgorithmException e) {
2729 Slog.e(TAG, "Needed decryption algorithm unavailable!");
2730 } catch (NoSuchPaddingException e) {
2731 Slog.e(TAG, "Needed padding mechanism unavailable!");
2732 } catch (InvalidKeyException e) {
2733 Slog.w(TAG, "Illegal password; aborting");
2734 } catch (NumberFormatException e) {
2735 Slog.w(TAG, "Can't parse restore data header");
2736 } catch (IOException e) {
2737 Slog.w(TAG, "Can't read input header");
2738 }
2739
2740 return result;
2741 }
2742
Christopher Tate75a99702011-05-18 16:28:19 -07002743 boolean restoreOneFile(InputStream instream, byte[] buffer) {
2744 FileMetadata info;
2745 try {
2746 info = readTarHeaders(instream);
2747 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002748 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07002749 dumpFileMetadata(info);
2750 }
2751
2752 final String pkg = info.packageName;
2753 if (!pkg.equals(mAgentPackage)) {
2754 // okay, change in package; set up our various
2755 // bookkeeping if we haven't seen it yet
2756 if (!mPackagePolicies.containsKey(pkg)) {
2757 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2758 }
2759
2760 // Clean up the previous agent relationship if necessary,
2761 // and let the observer know we're considering a new app.
2762 if (mAgent != null) {
2763 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
2764 tearDownPipes();
2765 tearDownAgent(mTargetApp);
2766 mTargetApp = null;
2767 mAgentPackage = null;
2768 }
2769 }
2770
2771 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
2772 mPackagePolicies.put(pkg, readAppManifest(info, instream));
2773 mPackageInstallers.put(pkg, info.installerPackageName);
2774 // We've read only the manifest content itself at this point,
2775 // so consume the footer before looping around to the next
2776 // input file
2777 skipTarPadding(info.size, instream);
2778 sendOnRestorePackage(pkg);
2779 } else {
2780 // Non-manifest, so it's actual file data. Is this a package
2781 // we're ignoring?
2782 boolean okay = true;
2783 RestorePolicy policy = mPackagePolicies.get(pkg);
2784 switch (policy) {
2785 case IGNORE:
2786 okay = false;
2787 break;
2788
2789 case ACCEPT_IF_APK:
2790 // If we're in accept-if-apk state, then the first file we
2791 // see MUST be the apk.
2792 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2793 if (DEBUG) Slog.d(TAG, "APK file; installing");
2794 // Try to install the app.
2795 String installerName = mPackageInstallers.get(pkg);
2796 okay = installApk(info, installerName, instream);
2797 // good to go; promote to ACCEPT
2798 mPackagePolicies.put(pkg, (okay)
2799 ? RestorePolicy.ACCEPT
2800 : RestorePolicy.IGNORE);
2801 // At this point we've consumed this file entry
2802 // ourselves, so just strip the tar footer and
2803 // go on to the next file in the input stream
2804 skipTarPadding(info.size, instream);
2805 return true;
2806 } else {
2807 // File data before (or without) the apk. We can't
2808 // handle it coherently in this case so ignore it.
2809 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2810 okay = false;
2811 }
2812 break;
2813
2814 case ACCEPT:
2815 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2816 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
2817 // we can take the data without the apk, so we
2818 // *want* to do so. skip the apk by declaring this
2819 // one file not-okay without changing the restore
2820 // policy for the package.
2821 okay = false;
2822 }
2823 break;
2824
2825 default:
2826 // Something has gone dreadfully wrong when determining
2827 // the restore policy from the manifest. Ignore the
2828 // rest of this package's data.
2829 Slog.e(TAG, "Invalid policy from manifest");
2830 okay = false;
2831 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2832 break;
2833 }
2834
2835 // If the policy is satisfied, go ahead and set up to pipe the
2836 // data to the agent.
2837 if (DEBUG && okay && mAgent != null) {
2838 Slog.i(TAG, "Reusing existing agent instance");
2839 }
2840 if (okay && mAgent == null) {
2841 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
2842
2843 try {
2844 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
2845
2846 // If we haven't sent any data to this app yet, we probably
2847 // need to clear it first. Check that.
2848 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002849 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07002850 // responsible for coherently managing a full
2851 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07002852 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07002853 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
2854 clearApplicationDataSynchronous(pkg);
2855 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002856 if (DEBUG) Slog.d(TAG, "backup agent ("
2857 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07002858 }
2859 mClearedPackages.add(pkg);
2860 } else {
2861 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
2862 }
2863
2864 // All set; now set up the IPC and launch the agent
2865 setUpPipes();
2866 mAgent = bindToAgentSynchronous(mTargetApp,
2867 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
2868 mAgentPackage = pkg;
2869 } catch (IOException e) {
2870 // fall through to error handling
2871 } catch (NameNotFoundException e) {
2872 // fall through to error handling
2873 }
2874
2875 if (mAgent == null) {
2876 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
2877 okay = false;
2878 tearDownPipes();
2879 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2880 }
2881 }
2882
2883 // Sanity check: make sure we never give data to the wrong app. This
2884 // should never happen but a little paranoia here won't go amiss.
2885 if (okay && !pkg.equals(mAgentPackage)) {
2886 Slog.e(TAG, "Restoring data for " + pkg
2887 + " but agent is for " + mAgentPackage);
2888 okay = false;
2889 }
2890
2891 // At this point we have an agent ready to handle the full
2892 // restore data as well as a pipe for sending data to
2893 // that agent. Tell the agent to start reading from the
2894 // pipe.
2895 if (okay) {
2896 boolean agentSuccess = true;
2897 long toCopy = info.size;
2898 final int token = generateToken();
2899 try {
2900 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
2901 + info.path);
2902 prepareOperationTimeout(token,
2903 TIMEOUT_FULL_BACKUP_INTERVAL);
2904 // fire up the app's agent listening on the socket. If
2905 // the agent is running in the system process we can't
2906 // just invoke it asynchronously, so we provide a thread
2907 // for it here.
2908 if (mTargetApp.processName.equals("system")) {
2909 Slog.d(TAG, "system process agent - spinning a thread");
2910 RestoreFileRunnable runner = new RestoreFileRunnable(
2911 mAgent, info, mPipes[0], token);
2912 new Thread(runner).start();
2913 } else {
2914 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
2915 info.domain, info.path, info.mode, info.mtime,
2916 token, mBackupManagerBinder);
2917 }
2918 } catch (IOException e) {
2919 // couldn't dup the socket for a process-local restore
2920 Slog.d(TAG, "Couldn't establish restore");
2921 agentSuccess = false;
2922 okay = false;
2923 } catch (RemoteException e) {
2924 // whoops, remote agent went away. We'll eat the content
2925 // ourselves, then, and not copy it over.
2926 Slog.e(TAG, "Agent crashed during full restore");
2927 agentSuccess = false;
2928 okay = false;
2929 }
2930
2931 // Copy over the data if the agent is still good
2932 if (okay) {
2933 boolean pipeOkay = true;
2934 FileOutputStream pipe = new FileOutputStream(
2935 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07002936 while (toCopy > 0) {
2937 int toRead = (toCopy > buffer.length)
2938 ? buffer.length : (int)toCopy;
2939 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002940 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002941 if (nRead <= 0) break;
2942 toCopy -= nRead;
2943
2944 // send it to the output pipe as long as things
2945 // are still good
2946 if (pipeOkay) {
2947 try {
2948 pipe.write(buffer, 0, nRead);
2949 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002950 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002951 pipeOkay = false;
2952 }
2953 }
2954 }
2955
2956 // done sending that file! Now we just need to consume
2957 // the delta from info.size to the end of block.
2958 skipTarPadding(info.size, instream);
2959
2960 // and now that we've sent it all, wait for the remote
2961 // side to acknowledge receipt
2962 agentSuccess = waitUntilOperationComplete(token);
2963 }
2964
2965 // okay, if the remote end failed at any point, deal with
2966 // it by ignoring the rest of the restore on it
2967 if (!agentSuccess) {
2968 mBackupHandler.removeMessages(MSG_TIMEOUT);
2969 tearDownPipes();
2970 tearDownAgent(mTargetApp);
2971 mAgent = null;
2972 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2973 }
2974 }
2975
2976 // Problems setting up the agent communication, or an already-
2977 // ignored package: skip to the next tar stream entry by
2978 // reading and discarding this file.
2979 if (!okay) {
2980 if (DEBUG) Slog.d(TAG, "[discarding file content]");
2981 long bytesToConsume = (info.size + 511) & ~511;
2982 while (bytesToConsume > 0) {
2983 int toRead = (bytesToConsume > buffer.length)
2984 ? buffer.length : (int)bytesToConsume;
2985 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002986 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002987 if (nRead <= 0) break;
2988 bytesToConsume -= nRead;
2989 }
2990 }
2991 }
2992 }
2993 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002994 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002995 // treat as EOF
2996 info = null;
2997 }
2998
2999 return (info != null);
3000 }
3001
3002 void setUpPipes() throws IOException {
3003 mPipes = ParcelFileDescriptor.createPipe();
3004 }
3005
3006 void tearDownPipes() {
3007 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003008 try {
3009 mPipes[0].close();
3010 mPipes[0] = null;
3011 mPipes[1].close();
3012 mPipes[1] = null;
3013 } catch (IOException e) {
3014 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003015 }
3016 mPipes = null;
3017 }
3018 }
3019
3020 void tearDownAgent(ApplicationInfo app) {
3021 if (mAgent != null) {
3022 try {
3023 // unbind and tidy up even on timeout or failure, just in case
3024 mActivityManager.unbindBackupAgent(app);
3025
3026 // The agent was running with a stub Application object, so shut it down.
3027 // !!! We hardcode the confirmation UI's package name here rather than use a
3028 // manifest flag! TODO something less direct.
3029 if (app.uid != Process.SYSTEM_UID
3030 && !app.packageName.equals("com.android.backupconfirm")) {
3031 if (DEBUG) Slog.d(TAG, "Killing host process");
3032 mActivityManager.killApplicationProcess(app.processName, app.uid);
3033 } else {
3034 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3035 }
3036 } catch (RemoteException e) {
3037 Slog.d(TAG, "Lost app trying to shut down");
3038 }
3039 mAgent = null;
3040 }
3041 }
3042
3043 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3044 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003045 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003046 int mResult;
3047
3048 public void reset() {
3049 synchronized (mDone) {
3050 mDone.set(false);
3051 }
3052 }
3053
3054 public void waitForCompletion() {
3055 synchronized (mDone) {
3056 while (mDone.get() == false) {
3057 try {
3058 mDone.wait();
3059 } catch (InterruptedException e) { }
3060 }
3061 }
3062 }
3063
3064 int getResult() {
3065 return mResult;
3066 }
3067
3068 @Override
3069 public void packageInstalled(String packageName, int returnCode)
3070 throws RemoteException {
3071 synchronized (mDone) {
3072 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003073 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003074 mDone.set(true);
3075 mDone.notifyAll();
3076 }
3077 }
3078 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003079
3080 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3081 final AtomicBoolean mDone = new AtomicBoolean();
3082 int mResult;
3083
3084 public void reset() {
3085 synchronized (mDone) {
3086 mDone.set(false);
3087 }
3088 }
3089
3090 public void waitForCompletion() {
3091 synchronized (mDone) {
3092 while (mDone.get() == false) {
3093 try {
3094 mDone.wait();
3095 } catch (InterruptedException e) { }
3096 }
3097 }
3098 }
3099
3100 @Override
3101 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3102 synchronized (mDone) {
3103 mResult = returnCode;
3104 mDone.set(true);
3105 mDone.notifyAll();
3106 }
3107 }
3108 }
3109
Christopher Tate75a99702011-05-18 16:28:19 -07003110 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003111 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003112
3113 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3114 boolean okay = true;
3115
3116 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3117
3118 // The file content is an .apk file. Copy it out to a staging location and
3119 // attempt to install it.
3120 File apkFile = new File(mDataDir, info.packageName);
3121 try {
3122 FileOutputStream apkStream = new FileOutputStream(apkFile);
3123 byte[] buffer = new byte[32 * 1024];
3124 long size = info.size;
3125 while (size > 0) {
3126 long toRead = (buffer.length < size) ? buffer.length : size;
3127 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003128 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003129 apkStream.write(buffer, 0, didRead);
3130 size -= didRead;
3131 }
3132 apkStream.close();
3133
3134 // make sure the installer can read it
3135 apkFile.setReadable(true, false);
3136
3137 // Now install it
3138 Uri packageUri = Uri.fromFile(apkFile);
3139 mInstallObserver.reset();
3140 mPackageManager.installPackage(packageUri, mInstallObserver,
3141 PackageManager.INSTALL_REPLACE_EXISTING, installerPackage);
3142 mInstallObserver.waitForCompletion();
3143
3144 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3145 // The only time we continue to accept install of data even if the
3146 // apk install failed is if we had already determined that we could
3147 // accept the data regardless.
3148 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3149 okay = false;
3150 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003151 } else {
3152 // Okay, the install succeeded. Make sure it was the right app.
3153 boolean uninstall = false;
3154 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3155 Slog.w(TAG, "Restore stream claimed to include apk for "
3156 + info.packageName + " but apk was really "
3157 + mInstallObserver.mPackageName);
3158 // delete the package we just put in place; it might be fraudulent
3159 okay = false;
3160 uninstall = true;
3161 } else {
3162 try {
3163 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3164 PackageManager.GET_SIGNATURES);
3165 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3166 Slog.w(TAG, "Restore stream contains apk of package "
3167 + info.packageName + " but it disallows backup/restore");
3168 okay = false;
3169 } else {
3170 // So far so good -- do the signatures match the manifest?
3171 Signature[] sigs = mManifestSignatures.get(info.packageName);
3172 if (!signaturesMatch(sigs, pkg)) {
3173 Slog.w(TAG, "Installed app " + info.packageName
3174 + " signatures do not match restore manifest");
3175 okay = false;
3176 uninstall = true;
3177 }
3178 }
3179 } catch (NameNotFoundException e) {
3180 Slog.w(TAG, "Install of package " + info.packageName
3181 + " succeeded but now not found");
3182 okay = false;
3183 }
3184 }
3185
3186 // If we're not okay at this point, we need to delete the package
3187 // that we just installed.
3188 if (uninstall) {
3189 mDeleteObserver.reset();
3190 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3191 mDeleteObserver, 0);
3192 mDeleteObserver.waitForCompletion();
3193 }
Christopher Tate75a99702011-05-18 16:28:19 -07003194 }
3195 } catch (IOException e) {
3196 Slog.e(TAG, "Unable to transcribe restored apk for install");
3197 okay = false;
3198 } finally {
3199 apkFile.delete();
3200 }
3201
3202 return okay;
3203 }
3204
3205 // Given an actual file content size, consume the post-content padding mandated
3206 // by the tar format.
3207 void skipTarPadding(long size, InputStream instream) throws IOException {
3208 long partial = (size + 512) % 512;
3209 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003210 final int needed = 512 - (int)partial;
3211 byte[] buffer = new byte[needed];
3212 if (readExactly(instream, buffer, 0, needed) == needed) {
3213 mBytes += needed;
3214 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003215 }
3216 }
3217
3218 // Returns a policy constant; takes a buffer arg to reduce memory churn
3219 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3220 throws IOException {
3221 // Fail on suspiciously large manifest files
3222 if (info.size > 64 * 1024) {
3223 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3224 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003225
Christopher Tate75a99702011-05-18 16:28:19 -07003226 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003227 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3228 mBytes += info.size;
3229 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003230
3231 RestorePolicy policy = RestorePolicy.IGNORE;
3232 String[] str = new String[1];
3233 int offset = 0;
3234
3235 try {
3236 offset = extractLine(buffer, offset, str);
3237 int version = Integer.parseInt(str[0]);
3238 if (version == BACKUP_MANIFEST_VERSION) {
3239 offset = extractLine(buffer, offset, str);
3240 String manifestPackage = str[0];
3241 // TODO: handle <original-package>
3242 if (manifestPackage.equals(info.packageName)) {
3243 offset = extractLine(buffer, offset, str);
3244 version = Integer.parseInt(str[0]); // app version
3245 offset = extractLine(buffer, offset, str);
3246 int platformVersion = Integer.parseInt(str[0]);
3247 offset = extractLine(buffer, offset, str);
3248 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3249 offset = extractLine(buffer, offset, str);
3250 boolean hasApk = str[0].equals("1");
3251 offset = extractLine(buffer, offset, str);
3252 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003253 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003254 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003255 for (int i = 0; i < numSigs; i++) {
3256 offset = extractLine(buffer, offset, str);
3257 sigs[i] = new Signature(str[0]);
3258 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003259 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003260
3261 // Okay, got the manifest info we need...
3262 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003263 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3264 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003265 // Fall through to IGNORE if the app explicitly disallows backup
3266 final int flags = pkgInfo.applicationInfo.flags;
3267 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3268 // Verify signatures against any installed version; if they
3269 // don't match, then we fall though and ignore the data. The
3270 // signatureMatch() method explicitly ignores the signature
3271 // check for packages installed on the system partition, because
3272 // such packages are signed with the platform cert instead of
3273 // the app developer's cert, so they're different on every
3274 // device.
3275 if (signaturesMatch(sigs, pkgInfo)) {
3276 if (pkgInfo.versionCode >= version) {
3277 Slog.i(TAG, "Sig + version match; taking data");
3278 policy = RestorePolicy.ACCEPT;
3279 } else {
3280 // The data is from a newer version of the app than
3281 // is presently installed. That means we can only
3282 // use it if the matching apk is also supplied.
3283 Slog.d(TAG, "Data version " + version
3284 + " is newer than installed version "
3285 + pkgInfo.versionCode + " - requiring apk");
3286 policy = RestorePolicy.ACCEPT_IF_APK;
3287 }
Christopher Tate75a99702011-05-18 16:28:19 -07003288 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003289 Slog.w(TAG, "Restore manifest signatures do not match "
3290 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003291 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003292 } else {
3293 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3294 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003295 }
3296 } catch (NameNotFoundException e) {
3297 // Okay, the target app isn't installed. We can process
3298 // the restore properly only if the dataset provides the
3299 // apk file and we can successfully install it.
3300 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3301 + " not installed; requiring apk in dataset");
3302 policy = RestorePolicy.ACCEPT_IF_APK;
3303 }
3304
3305 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3306 Slog.i(TAG, "Cannot restore package " + info.packageName
3307 + " without the matching .apk");
3308 }
3309 } else {
3310 Slog.i(TAG, "Missing signature on backed-up package "
3311 + info.packageName);
3312 }
3313 } else {
3314 Slog.i(TAG, "Expected package " + info.packageName
3315 + " but restore manifest claims " + manifestPackage);
3316 }
3317 } else {
3318 Slog.i(TAG, "Unknown restore manifest version " + version
3319 + " for package " + info.packageName);
3320 }
3321 } catch (NumberFormatException e) {
3322 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003323 } catch (IllegalArgumentException e) {
3324 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003325 }
3326
3327 return policy;
3328 }
3329
3330 // Builds a line from a byte buffer starting at 'offset', and returns
3331 // the index of the next unconsumed data in the buffer.
3332 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3333 final int end = buffer.length;
3334 if (offset >= end) throw new IOException("Incomplete data");
3335
3336 int pos;
3337 for (pos = offset; pos < end; pos++) {
3338 byte c = buffer[pos];
3339 // at LF we declare end of line, and return the next char as the
3340 // starting point for the next time through
3341 if (c == '\n') {
3342 break;
3343 }
3344 }
3345 outStr[0] = new String(buffer, offset, pos - offset);
3346 pos++; // may be pointing an extra byte past the end but that's okay
3347 return pos;
3348 }
3349
3350 void dumpFileMetadata(FileMetadata info) {
3351 if (DEBUG) {
3352 StringBuilder b = new StringBuilder(128);
3353
3354 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003355 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003356 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3357 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3358 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3359 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3360 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3361 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3362 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3363 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3364 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3365 b.append(String.format(" %9d ", info.size));
3366
3367 Date stamp = new Date(info.mtime);
3368 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3369
3370 b.append(info.packageName);
3371 b.append(" :: ");
3372 b.append(info.domain);
3373 b.append(" :: ");
3374 b.append(info.path);
3375
3376 Slog.i(TAG, b.toString());
3377 }
3378 }
3379 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3380 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3381 byte[] block = new byte[512];
3382 FileMetadata info = null;
3383
3384 boolean gotHeader = readTarHeader(instream, block);
3385 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003386 try {
3387 // okay, presume we're okay, and extract the various metadata
3388 info = new FileMetadata();
3389 info.size = extractRadix(block, 124, 12, 8);
3390 info.mtime = extractRadix(block, 136, 12, 8);
3391 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003392
Christopher Tate2efd2db2011-07-19 16:32:49 -07003393 info.path = extractString(block, 345, 155); // prefix
3394 String path = extractString(block, 0, 100);
3395 if (path.length() > 0) {
3396 if (info.path.length() > 0) info.path += '/';
3397 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003398 }
Christopher Tate75a99702011-05-18 16:28:19 -07003399
Christopher Tate2efd2db2011-07-19 16:32:49 -07003400 // tar link indicator field: 1 byte at offset 156 in the header.
3401 int typeChar = block[156];
3402 if (typeChar == 'x') {
3403 // pax extended header, so we need to read that
3404 gotHeader = readPaxExtendedHeader(instream, info);
3405 if (gotHeader) {
3406 // and after a pax extended header comes another real header -- read
3407 // that to find the real file type
3408 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003409 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003410 if (!gotHeader) throw new IOException("Bad or missing pax header");
3411
3412 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003413 }
Christopher Tate75a99702011-05-18 16:28:19 -07003414
Christopher Tate2efd2db2011-07-19 16:32:49 -07003415 switch (typeChar) {
3416 case '0': info.type = BackupAgent.TYPE_FILE; break;
3417 case '5': {
3418 info.type = BackupAgent.TYPE_DIRECTORY;
3419 if (info.size != 0) {
3420 Slog.w(TAG, "Directory entry with nonzero size in header");
3421 info.size = 0;
3422 }
3423 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003424 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003425 case 0: {
3426 // presume EOF
3427 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3428 return null;
3429 }
3430 default: {
3431 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3432 throw new IOException("Unknown entity type " + typeChar);
3433 }
Christopher Tate75a99702011-05-18 16:28:19 -07003434 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003435
3436 // Parse out the path
3437 //
3438 // first: apps/shared/unrecognized
3439 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3440 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3441 // File in shared storage. !!! TODO: implement this.
3442 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
3443 info.packageName = "com.android.sharedstoragebackup";
3444 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3445 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3446 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3447 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3448 // App content! Parse out the package name and domain
3449
3450 // strip the apps/ prefix
3451 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3452
3453 // extract the package name
3454 int slash = info.path.indexOf('/');
3455 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3456 info.packageName = info.path.substring(0, slash);
3457 info.path = info.path.substring(slash+1);
3458
3459 // if it's a manifest we're done, otherwise parse out the domains
3460 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3461 slash = info.path.indexOf('/');
3462 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3463 info.domain = info.path.substring(0, slash);
3464 // validate that it's one of the domains we understand
3465 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3466 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3467 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3468 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3469 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3470 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3471 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3472 throw new IOException("Unrecognized domain " + info.domain);
3473 }
3474
3475 info.path = info.path.substring(slash + 1);
3476 }
3477 }
3478 } catch (IOException e) {
3479 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003480 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003481 HEXLOG(block);
3482 }
3483 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003484 }
3485 }
3486 return info;
3487 }
3488
Christopher Tate2efd2db2011-07-19 16:32:49 -07003489 private void HEXLOG(byte[] block) {
3490 int offset = 0;
3491 int todo = block.length;
3492 StringBuilder buf = new StringBuilder(64);
3493 while (todo > 0) {
3494 buf.append(String.format("%04x ", offset));
3495 int numThisLine = (todo > 16) ? 16 : todo;
3496 for (int i = 0; i < numThisLine; i++) {
3497 buf.append(String.format("%02x ", block[offset+i]));
3498 }
3499 Slog.i("hexdump", buf.toString());
3500 buf.setLength(0);
3501 todo -= numThisLine;
3502 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003503 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003504 }
3505
Christopher Tate6853fcf2011-08-10 17:52:21 -07003506 // Read exactly the given number of bytes into a buffer at the stated offset.
3507 // Returns false if EOF is encountered before the requested number of bytes
3508 // could be read.
3509 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3510 throws IOException {
3511 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3512
3513 int soFar = 0;
3514 while (soFar < size) {
3515 int nRead = in.read(buffer, offset + soFar, size - soFar);
3516 if (nRead <= 0) {
3517 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3518 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003519 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003520 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003521 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003522 return soFar;
3523 }
3524
3525 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3526 final int got = readExactly(instream, block, 0, 512);
3527 if (got == 0) return false; // Clean EOF
3528 if (got < 512) throw new IOException("Unable to read full block header");
3529 mBytes += 512;
3530 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003531 }
3532
3533 // overwrites 'info' fields based on the pax extended header
3534 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3535 throws IOException {
3536 // We should never see a pax extended header larger than this
3537 if (info.size > 32*1024) {
3538 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3539 + " - aborting");
3540 throw new IOException("Sanity failure: pax header size " + info.size);
3541 }
3542
3543 // read whole blocks, not just the content size
3544 int numBlocks = (int)((info.size + 511) >> 9);
3545 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003546 if (readExactly(instream, data, 0, data.length) < data.length) {
3547 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003548 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003549 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003550
3551 final int contentSize = (int) info.size;
3552 int offset = 0;
3553 do {
3554 // extract the line at 'offset'
3555 int eol = offset+1;
3556 while (eol < contentSize && data[eol] != ' ') eol++;
3557 if (eol >= contentSize) {
3558 // error: we just hit EOD looking for the end of the size field
3559 throw new IOException("Invalid pax data");
3560 }
3561 // eol points to the space between the count and the key
3562 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3563 int key = eol + 1; // start of key=value
3564 eol = offset + linelen - 1; // trailing LF
3565 int value;
3566 for (value = key+1; data[value] != '=' && value <= eol; value++);
3567 if (value > eol) {
3568 throw new IOException("Invalid pax declaration");
3569 }
3570
3571 // pax requires that key/value strings be in UTF-8
3572 String keyStr = new String(data, key, value-key, "UTF-8");
3573 // -1 to strip the trailing LF
3574 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3575
3576 if ("path".equals(keyStr)) {
3577 info.path = valStr;
3578 } else if ("size".equals(keyStr)) {
3579 info.size = Long.parseLong(valStr);
3580 } else {
3581 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3582 }
3583
3584 offset += linelen;
3585 } while (offset < contentSize);
3586
3587 return true;
3588 }
3589
3590 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3591 throws IOException {
3592 long value = 0;
3593 final int end = offset + maxChars;
3594 for (int i = offset; i < end; i++) {
3595 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003596 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003597 if (b == 0 || b == ' ') break;
3598 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003599 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07003600 }
3601 value = radix * value + (b - '0');
3602 }
3603 return value;
3604 }
3605
3606 String extractString(byte[] data, int offset, int maxChars) throws IOException {
3607 final int end = offset + maxChars;
3608 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003609 // tar string fields terminate early with a NUL
3610 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07003611 return new String(data, offset, eos-offset, "US-ASCII");
3612 }
3613
3614 void sendStartRestore() {
3615 if (mObserver != null) {
3616 try {
3617 mObserver.onStartRestore();
3618 } catch (RemoteException e) {
3619 Slog.w(TAG, "full restore observer went away: startRestore");
3620 mObserver = null;
3621 }
3622 }
3623 }
3624
3625 void sendOnRestorePackage(String name) {
3626 if (mObserver != null) {
3627 try {
3628 // TODO: use a more user-friendly name string
3629 mObserver.onRestorePackage(name);
3630 } catch (RemoteException e) {
3631 Slog.w(TAG, "full restore observer went away: restorePackage");
3632 mObserver = null;
3633 }
3634 }
3635 }
3636
3637 void sendEndRestore() {
3638 if (mObserver != null) {
3639 try {
3640 mObserver.onEndRestore();
3641 } catch (RemoteException e) {
3642 Slog.w(TAG, "full restore observer went away: endRestore");
3643 mObserver = null;
3644 }
3645 }
3646 }
3647 }
3648
Christopher Tatedf01dea2009-06-09 20:45:02 -07003649 // ----- Restore handling -----
3650
Christopher Tate78dd4a72009-11-04 11:49:08 -08003651 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
3652 // If the target resides on the system partition, we allow it to restore
3653 // data from the like-named package in a restore set even if the signatures
3654 // do not match. (Unlike general applications, those flashed to the system
3655 // partition will be signed with the device's platform certificate, so on
3656 // different phones the same system app will have different signatures.)
3657 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003658 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08003659 return true;
3660 }
3661
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003662 // Allow unsigned apps, but not signed on one device and unsigned on the other
3663 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08003664 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07003665 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07003666 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003667 if ((storedSigs == null || storedSigs.length == 0)
3668 && (deviceSigs == null || deviceSigs.length == 0)) {
3669 return true;
3670 }
3671 if (storedSigs == null || deviceSigs == null) {
3672 return false;
3673 }
3674
Christopher Tateabce4e82009-06-18 18:35:32 -07003675 // !!! TODO: this demands that every stored signature match one
3676 // that is present on device, and does not demand the converse.
3677 // Is this this right policy?
3678 int nStored = storedSigs.length;
3679 int nDevice = deviceSigs.length;
3680
3681 for (int i=0; i < nStored; i++) {
3682 boolean match = false;
3683 for (int j=0; j < nDevice; j++) {
3684 if (storedSigs[i].equals(deviceSigs[j])) {
3685 match = true;
3686 break;
3687 }
3688 }
3689 if (!match) {
3690 return false;
3691 }
3692 }
3693 return true;
3694 }
3695
Christopher Tate44a27902010-01-27 17:15:49 -08003696 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003697 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003698 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003699 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003700 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003701 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003702 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003703 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07003704 private HashSet<String> mFilterSet;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003705
Christopher Tate5cbbf562009-06-22 16:44:51 -07003706 class RestoreRequest {
3707 public PackageInfo app;
3708 public int storedAppVersion;
3709
3710 RestoreRequest(PackageInfo _app, int _version) {
3711 app = _app;
3712 storedAppVersion = _version;
3713 }
3714 }
3715
Christopher Tate44a27902010-01-27 17:15:49 -08003716 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07003717 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07003718 boolean needFullBackup, String[] filterSet) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003719 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003720 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003721 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08003722 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08003723 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003724 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003725
Christopher Tate284f1bb2011-07-07 14:31:18 -07003726 if (filterSet != null) {
3727 mFilterSet = new HashSet<String>();
3728 for (String pkg : filterSet) {
3729 mFilterSet.add(pkg);
3730 }
3731 } else {
3732 mFilterSet = null;
3733 }
3734
Christopher Tate5cb400b2009-06-25 16:03:14 -07003735 try {
3736 mStateDir = new File(mBaseStateDir, transport.transportDirName());
3737 } catch (RemoteException e) {
3738 // can't happen; the transport is local
3739 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003740 }
3741
Christopher Tatedf01dea2009-06-09 20:45:02 -07003742 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003743 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003744 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08003745 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate284f1bb2011-07-07 14:31:18 -07003746 + " mTargetPackage=" + mTargetPackage + " mFilterSet=" + mFilterSet
3747 + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003748
Christopher Tateb49ceb32010-02-08 16:22:24 -08003749 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003750 int error = -1; // assume error
3751
Dan Egnorefe52642009-06-24 00:16:33 -07003752 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07003753 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003754 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003755 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07003756
Dan Egnorefe52642009-06-24 00:16:33 -07003757 // Get the list of all packages which have backup enabled.
3758 // (Include the Package Manager metadata pseudo-package first.)
3759 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
3760 PackageInfo omPackage = new PackageInfo();
3761 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
3762 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003763
Dan Egnorefe52642009-06-24 00:16:33 -07003764 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003765 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07003766 // if there's a filter set, strip out anything that isn't
3767 // present before proceeding
3768 if (mFilterSet != null) {
3769 for (int i = agentPackages.size() - 1; i >= 0; i--) {
3770 final PackageInfo pkg = agentPackages.get(i);
3771 if (! mFilterSet.contains(pkg.packageName)) {
3772 agentPackages.remove(i);
3773 }
3774 }
3775 if (DEBUG) {
3776 Slog.i(TAG, "Post-filter package set for restore:");
3777 for (PackageInfo p : agentPackages) {
3778 Slog.i(TAG, " " + p);
3779 }
3780 }
3781 }
Christopher Tate84725812010-02-04 15:52:40 -08003782 restorePackages.addAll(agentPackages);
3783 } else {
3784 // Just one package to attempt restore of
3785 restorePackages.add(mTargetPackage);
3786 }
Dan Egnorefe52642009-06-24 00:16:33 -07003787
Christopher Tate7d562ec2009-06-25 18:03:43 -07003788 // let the observer know that we're running
3789 if (mObserver != null) {
3790 try {
3791 // !!! TODO: get an actual count from the transport after
3792 // its startRestore() runs?
3793 mObserver.restoreStarting(restorePackages.size());
3794 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003795 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003796 mObserver = null;
3797 }
3798 }
3799
Dan Egnor01445162009-09-21 17:04:05 -07003800 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
3801 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003802 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003803 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003804 return;
3805 }
3806
3807 String packageName = mTransport.nextRestorePackage();
3808 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003809 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003810 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003811 return;
3812 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003813 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003814 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003815 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07003816 return;
3817 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003818 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07003819 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003820 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003821 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003822 return;
3823 }
3824
3825 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08003826 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07003827 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07003828 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
3829 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07003830
Christopher Tate8c032472009-07-02 14:28:47 -07003831 // Verify that the backup set includes metadata. If not, we can't do
3832 // signature/version verification etc, so we simply do not proceed with
3833 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07003834 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003835 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003836 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003837 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07003838 return;
3839 }
3840
Christopher Tate7d562ec2009-06-25 18:03:43 -07003841 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07003842 for (;;) {
3843 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003844
Dan Egnorefe52642009-06-24 00:16:33 -07003845 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003846 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003847 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003848 return;
3849 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003850 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07003851 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003852 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003853
Christopher Tate7d562ec2009-06-25 18:03:43 -07003854 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07003855 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07003856 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07003857 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003858 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003859 mObserver = null;
3860 }
3861 }
3862
Dan Egnorefe52642009-06-24 00:16:33 -07003863 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
3864 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003865 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003866 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003867 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003868 continue;
3869 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003870
Dan Egnorbb9001c2009-07-27 12:20:13 -07003871 PackageInfo packageInfo;
3872 try {
3873 int flags = PackageManager.GET_SIGNATURES;
3874 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
3875 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003876 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003877 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003878 "Package missing on device");
3879 continue;
3880 }
3881
Dan Egnorefe52642009-06-24 00:16:33 -07003882 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08003883 // Data is from a "newer" version of the app than we have currently
3884 // installed. If the app has not declared that it is prepared to
3885 // handle this case, we do not attempt the restore.
3886 if ((packageInfo.applicationInfo.flags
3887 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
3888 String message = "Version " + metaInfo.versionCode
3889 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003890 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08003891 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
3892 packageName, message);
3893 continue;
3894 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003895 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08003896 + " > installed " + packageInfo.versionCode
3897 + " but restoreAnyVersion");
3898 }
Dan Egnorefe52642009-06-24 00:16:33 -07003899 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003900
Christopher Tate78dd4a72009-11-04 11:49:08 -08003901 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003902 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003903 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003904 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07003905 continue;
3906 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003907
Joe Onorato8a9b2202010-02-26 18:56:32 -08003908 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07003909 + " restore version [" + metaInfo.versionCode
3910 + "] is compatible with installed version ["
3911 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07003912
Christopher Tate3de55bc2010-03-12 17:28:08 -08003913 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07003914 IBackupAgent agent = bindToAgentSynchronous(
3915 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08003916 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07003917 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003918 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003919 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003920 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003921 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003922 }
3923
Christopher Tate5e1ab332009-09-01 20:32:49 -07003924 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07003925 try {
Chris Tate249345b2010-10-29 12:57:04 -07003926 processOneRestore(packageInfo, metaInfo.versionCode, agent,
3927 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003928 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07003929 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003930 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07003931 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07003932
3933 // The agent was probably running with a stub Application object,
3934 // which isn't a valid run mode for the main app logic. Shut
3935 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08003936 // usual full initialization. Note that this is only done for
3937 // full-system restores: when a single app has requested a restore,
3938 // it is explicitly not killed following that operation.
3939 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07003940 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003941 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003942 + packageInfo.applicationInfo.processName);
3943 mActivityManager.killApplicationProcess(
3944 packageInfo.applicationInfo.processName,
3945 packageInfo.applicationInfo.uid);
3946 }
Dan Egnorefe52642009-06-24 00:16:33 -07003947 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003948 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003949
3950 // if we get this far, report success to the observer
3951 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07003952 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003953 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003954 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003955 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003956 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003957 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003958
Dan Egnorefe52642009-06-24 00:16:33 -07003959 try {
3960 mTransport.finishRestore();
3961 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003962 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003963 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003964
3965 if (mObserver != null) {
3966 try {
3967 mObserver.restoreFinished(error);
3968 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003969 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003970 }
3971 }
Christopher Tateb6787f22009-07-02 17:40:45 -07003972
Christopher Tate84725812010-02-04 15:52:40 -08003973 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08003974 // ancestral dataset, as well as the set of apps that are possibly
3975 // restoreable from the dataset
3976 if (mTargetPackage == null && pmAgent != null) {
3977 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003978 mAncestralToken = mToken;
3979 writeRestoreTokens();
3980 }
3981
Christopher Tate1bb69062010-02-19 17:02:12 -08003982 // We must under all circumstances tell the Package Manager to
3983 // proceed with install notifications if it's waiting for us.
3984 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003985 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08003986 try {
3987 mPackageManagerBinder.finishPackageInstall(mPmToken);
3988 } catch (RemoteException e) { /* can't happen */ }
3989 }
3990
Christopher Tate73a3cb32010-12-13 18:27:26 -08003991 // Furthermore we need to reset the session timeout clock
3992 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
3993 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
3994 TIMEOUT_RESTORE_INTERVAL);
3995
Christopher Tateb6787f22009-07-02 17:40:45 -07003996 // done; we can finally release the wakelock
3997 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07003998 }
3999 }
4000
Dan Egnorefe52642009-06-24 00:16:33 -07004001 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07004002 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
4003 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004004 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07004005 final String packageName = app.packageName;
4006
Joe Onorato8a9b2202010-02-26 18:56:32 -08004007 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004008
Christopher Tatec7b31e32009-06-10 15:49:30 -07004009 // !!! TODO: get the dirs from the transport
4010 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07004011 File newStateName = new File(mStateDir, packageName + ".new");
4012 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004013
Dan Egnorbb9001c2009-07-27 12:20:13 -07004014 ParcelFileDescriptor backupData = null;
4015 ParcelFileDescriptor newState = null;
4016
Christopher Tate4a627c72011-04-01 14:43:32 -07004017 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004018 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004019 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07004020 backupData = ParcelFileDescriptor.open(backupDataName,
4021 ParcelFileDescriptor.MODE_READ_WRITE |
4022 ParcelFileDescriptor.MODE_CREATE |
4023 ParcelFileDescriptor.MODE_TRUNCATE);
4024
Dan Egnor01445162009-09-21 17:04:05 -07004025 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004026 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004027 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004028 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004029 }
4030
4031 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07004032 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07004033 backupData = ParcelFileDescriptor.open(backupDataName,
4034 ParcelFileDescriptor.MODE_READ_ONLY);
4035
Dan Egnorbb9001c2009-07-27 12:20:13 -07004036 newState = ParcelFileDescriptor.open(newStateName,
4037 ParcelFileDescriptor.MODE_READ_WRITE |
4038 ParcelFileDescriptor.MODE_CREATE |
4039 ParcelFileDescriptor.MODE_TRUNCATE);
4040
Christopher Tate44a27902010-01-27 17:15:49 -08004041 // Kick off the restore, checking for hung agents
4042 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
4043 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
4044 boolean success = waitUntilOperationComplete(token);
4045
4046 if (!success) {
4047 throw new RuntimeException("restore timeout");
4048 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004049
4050 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07004051 //
4052 // !!! TODO: the restored data should be migrated on the server
4053 // side into the current dataset. In that case the new state file
4054 // we just created would reflect the data already extant in the
4055 // backend, so there'd be nothing more to do. Until that happens,
4056 // however, we need to make sure that we record the data to the
4057 // current backend dataset. (Yes, this means shipping the data over
4058 // the wire in both directions. That's bad, but consistency comes
4059 // first, then efficiency.) Once we introduce server-side data
4060 // migration to the newly-restored device's dataset, we will change
4061 // the following from a discard of the newly-written state to the
4062 // "correct" operation of renaming into the canonical state blob.
4063 newStateName.delete(); // TODO: remove; see above comment
4064 //newStateName.renameTo(savedStateName); // TODO: replace with this
4065
Dan Egnorbb9001c2009-07-27 12:20:13 -07004066 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004067 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004068 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004069 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004070 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07004071
Christopher Tate96733042009-07-20 14:49:13 -07004072 // If the agent fails restore, it might have put the app's data
4073 // into an incoherent state. For consistency we wipe its data
4074 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07004075 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07004076 } finally {
4077 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004078 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
4079 try { if (newState != null) newState.close(); } catch (IOException e) {}
4080 backupData = newState = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07004081 synchronized (mCurrentOperations) {
4082 mCurrentOperations.delete(token);
4083 }
Chris Tate249345b2010-10-29 12:57:04 -07004084
4085 // If we know a priori that we'll need to perform a full post-restore backup
4086 // pass, clear the new state file data. This means we're discarding work that
4087 // was just done by the app's agent, but this way the agent doesn't need to
4088 // take any special action based on global device state.
4089 if (needFullBackup) {
4090 newStateName.delete();
4091 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004092 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004093 }
4094 }
4095
Christopher Tate44a27902010-01-27 17:15:49 -08004096 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004097 IBackupTransport mTransport;
4098 PackageInfo mPackage;
4099
Christopher Tate44a27902010-01-27 17:15:49 -08004100 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004101 mTransport = transport;
4102 mPackage = packageInfo;
4103 }
4104
Christopher Tateee0e78a2009-07-02 11:17:03 -07004105 public void run() {
4106 try {
4107 // Clear the on-device backup state to ensure a full backup next time
4108 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4109 File stateFile = new File(stateDir, mPackage.packageName);
4110 stateFile.delete();
4111
4112 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004113 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004114 mTransport.clearBackupData(mPackage);
4115 } catch (RemoteException e) {
4116 // can't happen; the transport is local
4117 } finally {
4118 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004119 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004120 mTransport.finishBackup();
4121 } catch (RemoteException e) {
4122 // can't happen; the transport is local
4123 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004124
4125 // Last but not least, release the cpu
4126 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004127 }
4128 }
4129 }
4130
Christopher Tate44a27902010-01-27 17:15:49 -08004131 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004132 HashSet<String> mQueue;
4133
Christopher Tate44a27902010-01-27 17:15:49 -08004134 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004135 mQueue = transportNames;
4136 }
4137
Christopher Tate4cc86e12009-09-21 19:36:51 -07004138 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004139 try {
4140 for (String transportName : mQueue) {
4141 IBackupTransport transport = getTransport(transportName);
4142 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004143 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004144 continue;
4145 }
4146
Joe Onorato8a9b2202010-02-26 18:56:32 -08004147 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004148 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004149 long startRealtime = SystemClock.elapsedRealtime();
4150 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004151
Christopher Tate4cc86e12009-09-21 19:36:51 -07004152 if (status == BackupConstants.TRANSPORT_OK) {
4153 status = transport.finishBackup();
4154 }
4155
4156 // Okay, the wipe really happened. Clean up our local bookkeeping.
4157 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004158 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004159 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004160 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004161 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004162 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004163 synchronized (mQueueLock) {
4164 recordInitPendingLocked(false, transportName);
4165 }
Dan Egnor726247c2009-09-29 19:12:31 -07004166 } else {
4167 // If this didn't work, requeue this one and try again
4168 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004169 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004170 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004171 synchronized (mQueueLock) {
4172 recordInitPendingLocked(true, transportName);
4173 }
4174 // do this via another alarm to make sure of the wakelock states
4175 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004176 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004177 + transportName + " resched in " + delay);
4178 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4179 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004180 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004181 }
4182 } catch (RemoteException e) {
4183 // can't happen; the transports are local
4184 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004185 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004186 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004187 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004188 mWakelock.release();
4189 }
4190 }
4191 }
4192
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004193 private void dataChangedImpl(String packageName) {
4194 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4195 dataChangedImpl(packageName, targets);
4196 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004197
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004198 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004199 // Record that we need a backup pass for the caller. Since multiple callers
4200 // may share a uid, we need to note all candidates within that uid and schedule
4201 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004202 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004203
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004204 if (targets == null) {
4205 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4206 + " uid=" + Binder.getCallingUid());
4207 return;
4208 }
4209
4210 synchronized (mQueueLock) {
4211 // Note that this client has made data changes that need to be backed up
4212 for (ApplicationInfo app : targets) {
4213 // validate the caller-supplied package name against the known set of
4214 // packages associated with this uid
4215 if (app.packageName.equals(packageName)) {
4216 // Add the caller to the set of pending backups. If there is
4217 // one already there, then overwrite it, but no harm done.
Christopher Tatecc55f812011-08-16 16:06:53 -07004218 BackupRequest req = new BackupRequest(packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08004219 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004220 // Journal this request in case of crash. The put()
4221 // operation returned null when this package was not already
4222 // in the set; we want to avoid touching the disk redundantly.
4223 writeToJournalLocked(packageName);
4224
Christopher Tatec58efa62011-08-01 19:20:14 -07004225 if (MORE_DEBUG) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004226 int numKeys = mPendingBackups.size();
4227 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4228 for (BackupRequest b : mPendingBackups.values()) {
Christopher Tatecc55f812011-08-16 16:06:53 -07004229 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004230 }
4231 }
4232 }
4233 }
4234 }
4235 }
4236 }
4237
4238 // Note: packageName is currently unused, but may be in the future
4239 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004240 // If the caller does not hold the BACKUP permission, it can only request a
4241 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004242 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004243 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004244 synchronized (mBackupParticipants) {
4245 return mBackupParticipants.get(Binder.getCallingUid());
4246 }
4247 }
4248
4249 // a caller with full permission can ask to back up any participating app
4250 // !!! TODO: allow backup of ANY app?
4251 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4252 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004253 int N = mBackupParticipants.size();
4254 for (int i = 0; i < N; i++) {
4255 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4256 if (s != null) {
4257 targets.addAll(s);
4258 }
4259 }
4260 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004261 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004262 }
Christopher Tate46758122009-05-06 11:22:00 -07004263
Christopher Tatecde87f42009-06-12 12:55:53 -07004264 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004265 RandomAccessFile out = null;
4266 try {
4267 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4268 out = new RandomAccessFile(mJournal, "rws");
4269 out.seek(out.length());
4270 out.writeUTF(str);
4271 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004272 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004273 mJournal = null;
4274 } finally {
4275 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004276 }
4277 }
4278
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004279 // ----- IBackupManager binder interface -----
4280
4281 public void dataChanged(final String packageName) {
4282 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4283 if (targets == null) {
4284 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4285 + " uid=" + Binder.getCallingUid());
4286 return;
4287 }
4288
4289 mBackupHandler.post(new Runnable() {
4290 public void run() {
4291 dataChangedImpl(packageName, targets);
4292 }
4293 });
4294 }
4295
Christopher Tateee0e78a2009-07-02 11:17:03 -07004296 // Clear the given package's backup data from the current transport
4297 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004298 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004299 PackageInfo info;
4300 try {
4301 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4302 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004303 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004304 return;
4305 }
4306
4307 // If the caller does not hold the BACKUP permission, it can only request a
4308 // wipe of its own backed-up data.
4309 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004310 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004311 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4312 apps = mBackupParticipants.get(Binder.getCallingUid());
4313 } else {
4314 // a caller with full permission can ask to back up any participating app
4315 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004316 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004317 apps = new HashSet<ApplicationInfo>();
4318 int N = mBackupParticipants.size();
4319 for (int i = 0; i < N; i++) {
4320 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4321 if (s != null) {
4322 apps.addAll(s);
4323 }
4324 }
4325 }
4326
4327 // now find the given package in the set of candidate apps
4328 for (ApplicationInfo app : apps) {
4329 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004330 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004331 // found it; fire off the clear request
4332 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004333 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004334 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004335 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4336 new ClearParams(getTransport(mCurrentTransport), info));
4337 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004338 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004339 }
4340 break;
4341 }
4342 }
4343 }
4344
Christopher Tateace7f092009-06-15 18:07:25 -07004345 // Run a backup pass immediately for any applications that have declared
4346 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004347 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004348 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004349
Joe Onorato8a9b2202010-02-26 18:56:32 -08004350 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004351 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004352 // Because the alarms we are using can jitter, and we want an *immediate*
4353 // backup pass to happen, we restart the timer beginning with "next time,"
4354 // then manually fire the backup trigger intent ourselves.
4355 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004356 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004357 mRunBackupIntent.send();
4358 } catch (PendingIntent.CanceledException e) {
4359 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004360 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004361 }
Christopher Tate46758122009-05-06 11:22:00 -07004362 }
4363 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004364
Christopher Tate4a627c72011-04-01 14:43:32 -07004365 // Run a *full* backup pass for the given package, writing the resulting data stream
4366 // to the supplied file descriptor. This method is synchronous and does not return
4367 // to the caller until the backup has been completed.
4368 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
4369 boolean doAllApps, String[] pkgList) {
4370 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4371
4372 // Validate
4373 if (!doAllApps) {
4374 if (!includeShared) {
4375 // If we're backing up shared data (sdcard or equivalent), then we can run
4376 // without any supplied app names. Otherwise, we'd be doing no work, so
4377 // report the error.
4378 if (pkgList == null || pkgList.length == 0) {
4379 throw new IllegalArgumentException(
4380 "Backup requested but neither shared nor any apps named");
4381 }
4382 }
4383 }
4384
4385 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4386 + " shared=" + includeShared + " all=" + doAllApps
4387 + " pkgs=" + pkgList);
4388
4389 long oldId = Binder.clearCallingIdentity();
4390 try {
4391 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
4392 doAllApps, pkgList);
4393 final int token = generateToken();
4394 synchronized (mFullConfirmations) {
4395 mFullConfirmations.put(token, params);
4396 }
4397
Christopher Tate75a99702011-05-18 16:28:19 -07004398 // start up the confirmation UI
4399 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4400 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4401 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004402 mFullConfirmations.delete(token);
4403 return;
4404 }
Christopher Tate75a99702011-05-18 16:28:19 -07004405
4406 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004407 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4408
4409 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07004410 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004411
4412 // wait for the backup to be performed
4413 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
4414 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004415 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07004416 try {
4417 fd.close();
4418 } catch (IOException e) {
4419 // just eat it
4420 }
Christopher Tate75a99702011-05-18 16:28:19 -07004421 Binder.restoreCallingIdentity(oldId);
Christopher Tate4a627c72011-04-01 14:43:32 -07004422 }
Christopher Tatec58efa62011-08-01 19:20:14 -07004423 if (MORE_DEBUG) Slog.d(TAG, "Full backup done; returning to caller");
Christopher Tate75a99702011-05-18 16:28:19 -07004424 }
4425
4426 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004427 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07004428 Slog.i(TAG, "Beginning full restore...");
4429
4430 long oldId = Binder.clearCallingIdentity();
4431
4432 try {
4433 FullRestoreParams params = new FullRestoreParams(fd);
4434 final int token = generateToken();
4435 synchronized (mFullConfirmations) {
4436 mFullConfirmations.put(token, params);
4437 }
4438
4439 // start up the confirmation UI
4440 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
4441 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
4442 Slog.e(TAG, "Unable to launch full restore confirmation");
4443 mFullConfirmations.delete(token);
4444 return;
4445 }
4446
4447 // make sure the screen is lit for the user interaction
4448 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4449
4450 // start the confirmation countdown
4451 startConfirmationTimeout(token, params);
4452
4453 // wait for the restore to be performed
4454 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
4455 waitForCompletion(params);
4456 } finally {
4457 try {
4458 fd.close();
4459 } catch (IOException e) {
4460 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
4461 }
4462 Binder.restoreCallingIdentity(oldId);
4463 Slog.i(TAG, "Full restore completed");
4464 }
4465 }
4466
4467 boolean startConfirmationUi(int token, String action) {
4468 try {
4469 Intent confIntent = new Intent(action);
4470 confIntent.setClassName("com.android.backupconfirm",
4471 "com.android.backupconfirm.BackupRestoreConfirmation");
4472 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
4473 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4474 mContext.startActivity(confIntent);
4475 } catch (ActivityNotFoundException e) {
4476 return false;
4477 }
4478 return true;
4479 }
4480
4481 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07004482 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07004483 + TIMEOUT_FULL_CONFIRMATION + " millis");
4484 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
4485 token, 0, params);
4486 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07004487 }
4488
4489 void waitForCompletion(FullParams params) {
4490 synchronized (params.latch) {
4491 while (params.latch.get() == false) {
4492 try {
4493 params.latch.wait();
4494 } catch (InterruptedException e) { /* never interrupted */ }
4495 }
4496 }
4497 }
4498
4499 void signalFullBackupRestoreCompletion(FullParams params) {
4500 synchronized (params.latch) {
4501 params.latch.set(true);
4502 params.latch.notifyAll();
4503 }
4504 }
4505
4506 // Confirm that the previously-requested full backup/restore operation can proceed. This
4507 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07004508 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07004509 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07004510 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004511 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
4512 + " allow=" + allow);
4513
4514 // TODO: possibly require not just this signature-only permission, but even
4515 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07004516 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07004517
4518 long oldId = Binder.clearCallingIdentity();
4519 try {
4520
4521 FullParams params;
4522 synchronized (mFullConfirmations) {
4523 params = mFullConfirmations.get(token);
4524 if (params != null) {
4525 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
4526 mFullConfirmations.delete(token);
4527
4528 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004529 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07004530 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07004531 : MSG_RUN_FULL_RESTORE;
4532
Christopher Tate728a1c42011-07-28 18:03:03 -07004533 params.observer = observer;
4534 params.curPassword = curPassword;
4535 params.encryptPassword = encPpassword;
4536
Christopher Tate75a99702011-05-18 16:28:19 -07004537 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07004538 mWakelock.acquire();
4539 Message msg = mBackupHandler.obtainMessage(verb, params);
4540 mBackupHandler.sendMessage(msg);
4541 } else {
4542 Slog.w(TAG, "User rejected full backup/restore operation");
4543 // indicate completion without having actually transferred any data
4544 signalFullBackupRestoreCompletion(params);
4545 }
4546 } else {
4547 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
4548 }
4549 }
4550 } finally {
4551 Binder.restoreCallingIdentity(oldId);
4552 }
4553 }
4554
Christopher Tate8031a3d2009-07-06 16:36:05 -07004555 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07004556 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004557 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004558 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004559
Joe Onorato8a9b2202010-02-26 18:56:32 -08004560 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004561
Christopher Tate6ef58a12009-06-29 14:56:28 -07004562 boolean wasEnabled = mEnabled;
4563 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07004564 Settings.Secure.putInt(mContext.getContentResolver(),
4565 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07004566 mEnabled = enable;
4567 }
4568
Christopher Tate49401dd2009-07-01 12:34:29 -07004569 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07004570 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07004571 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07004572 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07004573 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004574 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004575 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004576
Christopher Tateb6787f22009-07-02 17:40:45 -07004577 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004578
4579 // This also constitutes an opt-out, so we wipe any data for
4580 // this device from the backend. We start that process with
4581 // an alarm in order to guarantee wakelock states.
4582 if (wasEnabled && mProvisioned) {
4583 // NOTE: we currently flush every registered transport, not just
4584 // the currently-active one.
4585 HashSet<String> allTransports;
4586 synchronized (mTransports) {
4587 allTransports = new HashSet<String>(mTransports.keySet());
4588 }
4589 // build the set of transports for which we are posting an init
4590 for (String transport : allTransports) {
4591 recordInitPendingLocked(true, transport);
4592 }
4593 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
4594 mRunInitIntent);
4595 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004596 }
4597 }
Christopher Tate49401dd2009-07-01 12:34:29 -07004598 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004599
Christopher Tatecce9da52010-02-03 15:11:15 -08004600 // Enable/disable automatic restore of app data at install time
4601 public void setAutoRestore(boolean doAutoRestore) {
4602 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004603 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08004604
Joe Onorato8a9b2202010-02-26 18:56:32 -08004605 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08004606
4607 synchronized (this) {
4608 Settings.Secure.putInt(mContext.getContentResolver(),
4609 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
4610 mAutoRestore = doAutoRestore;
4611 }
4612 }
4613
Christopher Tate8031a3d2009-07-06 16:36:05 -07004614 // Mark the backup service as having been provisioned
4615 public void setBackupProvisioned(boolean available) {
4616 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4617 "setBackupProvisioned");
4618
4619 boolean wasProvisioned = mProvisioned;
4620 synchronized (this) {
4621 Settings.Secure.putInt(mContext.getContentResolver(),
4622 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
4623 mProvisioned = available;
4624 }
4625
4626 synchronized (mQueueLock) {
4627 if (available && !wasProvisioned && mEnabled) {
4628 // we're now good to go, so start the backup alarms
4629 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
4630 } else if (!available) {
4631 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004632 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07004633 mAlarmManager.cancel(mRunBackupIntent);
4634 }
4635 }
4636 }
4637
4638 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07004639 // We used to use setInexactRepeating(), but that may be linked to
4640 // backups running at :00 more often than not, creating load spikes.
4641 // Schedule at an exact time for now, and also add a bit of "fuzz".
4642
4643 Random random = new Random();
4644 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
4645 random.nextInt(FUZZ_MILLIS);
4646 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
4647 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07004648 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07004649 }
4650
Christopher Tate6ef58a12009-06-29 14:56:28 -07004651 // Report whether the backup mechanism is currently enabled
4652 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04004653 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004654 return mEnabled; // no need to synchronize just to read it
4655 }
4656
Christopher Tate91717492009-06-26 21:07:13 -07004657 // Report the name of the currently active transport
4658 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04004659 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004660 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07004661 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07004662 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07004663 }
4664
Christopher Tate91717492009-06-26 21:07:13 -07004665 // Report all known, available backup transports
4666 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07004667 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07004668
Christopher Tate91717492009-06-26 21:07:13 -07004669 String[] list = null;
4670 ArrayList<String> known = new ArrayList<String>();
4671 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
4672 if (entry.getValue() != null) {
4673 known.add(entry.getKey());
4674 }
4675 }
4676
4677 if (known.size() > 0) {
4678 list = new String[known.size()];
4679 known.toArray(list);
4680 }
4681 return list;
4682 }
4683
4684 // Select which transport to use for the next backup operation. If the given
4685 // name is not one of the available transports, no action is taken and the method
4686 // returns null.
4687 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04004688 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07004689
4690 synchronized (mTransports) {
4691 String prevTransport = null;
4692 if (mTransports.get(transport) != null) {
4693 prevTransport = mCurrentTransport;
4694 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07004695 Settings.Secure.putString(mContext.getContentResolver(),
4696 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004697 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07004698 + " returning " + prevTransport);
4699 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004700 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07004701 }
4702 return prevTransport;
4703 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004704 }
4705
Christopher Tatef5e1c292010-12-08 18:40:26 -08004706 // Supply the configuration Intent for the given transport. If the name is not one
4707 // of the available transports, or if the transport does not supply any configuration
4708 // UI, the method returns null.
4709 public Intent getConfigurationIntent(String transportName) {
4710 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4711 "getConfigurationIntent");
4712
4713 synchronized (mTransports) {
4714 final IBackupTransport transport = mTransports.get(transportName);
4715 if (transport != null) {
4716 try {
4717 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07004718 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08004719 + intent);
4720 return intent;
4721 } catch (RemoteException e) {
4722 /* fall through to return null */
4723 }
4724 }
4725 }
4726
4727 return null;
4728 }
4729
4730 // Supply the configuration summary string for the given transport. If the name is
4731 // not one of the available transports, or if the transport does not supply any
4732 // summary / destination string, the method can return null.
4733 //
4734 // This string is used VERBATIM as the summary text of the relevant Settings item!
4735 public String getDestinationString(String transportName) {
4736 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004737 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08004738
4739 synchronized (mTransports) {
4740 final IBackupTransport transport = mTransports.get(transportName);
4741 if (transport != null) {
4742 try {
4743 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07004744 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08004745 return text;
4746 } catch (RemoteException e) {
4747 /* fall through to return null */
4748 }
4749 }
4750 }
4751
4752 return null;
4753 }
4754
Christopher Tate043dadc2009-06-02 16:11:00 -07004755 // Callback: a requested backup agent has been instantiated. This should only
4756 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004757 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07004758 synchronized(mAgentConnectLock) {
4759 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004760 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07004761 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
4762 mConnectedAgent = agent;
4763 mConnecting = false;
4764 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004765 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004766 + " claiming agent connected");
4767 }
4768 mAgentConnectLock.notifyAll();
4769 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004770 }
4771
4772 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
4773 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07004774 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004775 public void agentDisconnected(String packageName) {
4776 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07004777 synchronized(mAgentConnectLock) {
4778 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
4779 mConnectedAgent = null;
4780 mConnecting = false;
4781 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004782 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004783 + " claiming agent disconnected");
4784 }
4785 mAgentConnectLock.notifyAll();
4786 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004787 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004788
Christopher Tate1bb69062010-02-19 17:02:12 -08004789 // An application being installed will need a restore pass, then the Package Manager
4790 // will need to be told when the restore is finished.
4791 public void restoreAtInstall(String packageName, int token) {
4792 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004793 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08004794 + " attemping install-time restore");
4795 return;
4796 }
4797
4798 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004799 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08004800 + " token=" + Integer.toHexString(token));
4801
Christopher Tatef0872722010-02-25 15:22:48 -08004802 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08004803 // okay, we're going to attempt a restore of this package from this restore set.
4804 // The eventual message back into the Package Manager to run the post-install
4805 // steps for 'token' will be issued from the restore handling code.
4806
4807 // We can use a synthetic PackageInfo here because:
4808 // 1. We know it's valid, since the Package Manager supplied the name
4809 // 2. Only the packageName field will be used by the restore code
4810 PackageInfo pkg = new PackageInfo();
4811 pkg.packageName = packageName;
4812
4813 mWakelock.acquire();
4814 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
4815 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07004816 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08004817 mBackupHandler.sendMessage(msg);
4818 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08004819 // Auto-restore disabled or no way to attempt a restore; just tell the Package
4820 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004821 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08004822 try {
4823 mPackageManagerBinder.finishPackageInstall(token);
4824 } catch (RemoteException e) { /* can't happen */ }
4825 }
4826 }
4827
Christopher Tate8c850b72009-06-07 19:33:20 -07004828 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08004829 public IRestoreSession beginRestoreSession(String packageName, String transport) {
4830 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
4831 + " transport=" + transport);
4832
4833 boolean needPermission = true;
4834 if (transport == null) {
4835 transport = mCurrentTransport;
4836
4837 if (packageName != null) {
4838 PackageInfo app = null;
4839 try {
4840 app = mPackageManager.getPackageInfo(packageName, 0);
4841 } catch (NameNotFoundException nnf) {
4842 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
4843 throw new IllegalArgumentException("Package " + packageName + " not found");
4844 }
4845
4846 if (app.applicationInfo.uid == Binder.getCallingUid()) {
4847 // So: using the current active transport, and the caller has asked
4848 // that its own package will be restored. In this narrow use case
4849 // we do not require the caller to hold the permission.
4850 needPermission = false;
4851 }
4852 }
4853 }
4854
4855 if (needPermission) {
4856 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4857 "beginRestoreSession");
4858 } else {
4859 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
4860 }
Christopher Tatef68eb502009-06-16 11:02:01 -07004861
4862 synchronized(this) {
4863 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004864 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07004865 return null;
4866 }
Chris Tate44ab8452010-11-16 15:10:49 -08004867 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08004868 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07004869 }
4870 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07004871 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004872
Christopher Tate73a3cb32010-12-13 18:27:26 -08004873 void clearRestoreSession(ActiveRestoreSession currentSession) {
4874 synchronized(this) {
4875 if (currentSession != mActiveRestoreSession) {
4876 Slog.e(TAG, "ending non-current restore session");
4877 } else {
4878 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
4879 mActiveRestoreSession = null;
4880 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4881 }
4882 }
4883 }
4884
Christopher Tate44a27902010-01-27 17:15:49 -08004885 // Note that a currently-active backup agent has notified us that it has
4886 // completed the given outstanding asynchronous backup/restore operation.
4887 public void opComplete(int token) {
4888 synchronized (mCurrentOpLock) {
Christopher Tatec58efa62011-08-01 19:20:14 -07004889 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08004890 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
4891 mCurrentOpLock.notifyAll();
4892 }
4893 }
4894
Christopher Tate9b3905c2009-06-08 15:24:01 -07004895 // ----- Restore session -----
4896
Christopher Tate80202c82010-01-25 19:37:47 -08004897 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07004898 private static final String TAG = "RestoreSession";
4899
Chris Tate44ab8452010-11-16 15:10:49 -08004900 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004901 private IBackupTransport mRestoreTransport = null;
4902 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08004903 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004904
Chris Tate44ab8452010-11-16 15:10:49 -08004905 ActiveRestoreSession(String packageName, String transport) {
4906 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07004907 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07004908 }
4909
4910 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07004911 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04004912 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004913 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004914 if (observer == null) {
4915 throw new IllegalArgumentException("Observer must not be null");
4916 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004917
Christopher Tate73a3cb32010-12-13 18:27:26 -08004918 if (mEnded) {
4919 throw new IllegalStateException("Restore session already ended");
4920 }
4921
Christopher Tate1bb69062010-02-19 17:02:12 -08004922 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07004923 try {
Christopher Tate43383042009-07-13 15:17:13 -07004924 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004925 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004926 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07004927 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07004928 // spin off the transport request to our service thread
4929 mWakelock.acquire();
4930 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
4931 new RestoreGetSetsParams(mRestoreTransport, this, observer));
4932 mBackupHandler.sendMessage(msg);
4933 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07004934 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004935 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07004936 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08004937 } finally {
4938 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07004939 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07004940 }
4941
Christopher Tate84725812010-02-04 15:52:40 -08004942 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07004943 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4944 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004945
Chris Tate44ab8452010-11-16 15:10:49 -08004946 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07004947 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004948
Christopher Tate73a3cb32010-12-13 18:27:26 -08004949 if (mEnded) {
4950 throw new IllegalStateException("Restore session already ended");
4951 }
4952
Dan Egnor0084da52009-07-29 12:57:16 -07004953 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08004954 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
4955 return -1;
4956 }
4957
4958 if (mPackageName != null) {
4959 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07004960 return -1;
4961 }
4962
Christopher Tate21ab6a52009-09-24 18:01:46 -07004963 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004964 for (int i = 0; i < mRestoreSets.length; i++) {
4965 if (token == mRestoreSets[i].token) {
4966 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07004967 mWakelock.acquire();
4968 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07004969 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07004970 mBackupHandler.sendMessage(msg);
4971 Binder.restoreCallingIdentity(oldId);
4972 return 0;
4973 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004974 }
4975 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07004976
Joe Onorato8a9b2202010-02-26 18:56:32 -08004977 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07004978 return -1;
4979 }
4980
Christopher Tate284f1bb2011-07-07 14:31:18 -07004981 public synchronized int restoreSome(long token, IRestoreObserver observer,
4982 String[] packages) {
4983 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4984 "performRestore");
4985
4986 if (DEBUG) {
4987 StringBuilder b = new StringBuilder(128);
4988 b.append("restoreSome token=");
4989 b.append(Long.toHexString(token));
4990 b.append(" observer=");
4991 b.append(observer.toString());
4992 b.append(" packages=");
4993 if (packages == null) {
4994 b.append("null");
4995 } else {
4996 b.append('{');
4997 boolean first = true;
4998 for (String s : packages) {
4999 if (!first) {
5000 b.append(", ");
5001 } else first = false;
5002 b.append(s);
5003 }
5004 b.append('}');
5005 }
5006 Slog.d(TAG, b.toString());
5007 }
5008
5009 if (mEnded) {
5010 throw new IllegalStateException("Restore session already ended");
5011 }
5012
5013 if (mRestoreTransport == null || mRestoreSets == null) {
5014 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5015 return -1;
5016 }
5017
5018 if (mPackageName != null) {
5019 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5020 return -1;
5021 }
5022
5023 synchronized (mQueueLock) {
5024 for (int i = 0; i < mRestoreSets.length; i++) {
5025 if (token == mRestoreSets[i].token) {
5026 long oldId = Binder.clearCallingIdentity();
5027 mWakelock.acquire();
5028 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5029 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5030 packages, true);
5031 mBackupHandler.sendMessage(msg);
5032 Binder.restoreCallingIdentity(oldId);
5033 return 0;
5034 }
5035 }
5036 }
5037
5038 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5039 return -1;
5040 }
5041
Christopher Tate84725812010-02-04 15:52:40 -08005042 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005043 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005044
Christopher Tate73a3cb32010-12-13 18:27:26 -08005045 if (mEnded) {
5046 throw new IllegalStateException("Restore session already ended");
5047 }
5048
Chris Tate44ab8452010-11-16 15:10:49 -08005049 if (mPackageName != null) {
5050 if (! mPackageName.equals(packageName)) {
5051 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5052 + " on session for package " + mPackageName);
5053 return -1;
5054 }
5055 }
5056
Christopher Tate84725812010-02-04 15:52:40 -08005057 PackageInfo app = null;
5058 try {
5059 app = mPackageManager.getPackageInfo(packageName, 0);
5060 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005061 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005062 return -1;
5063 }
5064
5065 // If the caller is not privileged and is not coming from the target
5066 // app's uid, throw a permission exception back to the caller.
5067 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5068 Binder.getCallingPid(), Binder.getCallingUid());
5069 if ((perm == PackageManager.PERMISSION_DENIED) &&
5070 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005071 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005072 + " or calling uid=" + Binder.getCallingUid());
5073 throw new SecurityException("No permission to restore other packages");
5074 }
5075
Christopher Tate7d411a32010-02-26 11:27:08 -08005076 // If the package has no backup agent, we obviously cannot proceed
5077 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005078 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005079 return -1;
5080 }
5081
Christopher Tate84725812010-02-04 15:52:40 -08005082 // So far so good; we're allowed to try to restore this package. Now
5083 // check whether there is data for it in the current dataset, falling back
5084 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005085 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005086
5087 // If we didn't come up with a place to look -- no ancestral dataset and
5088 // the app has never been backed up from this device -- there's nothing
5089 // to do but return failure.
5090 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005091 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005092 return -1;
5093 }
5094
5095 // Ready to go: enqueue the restore request and claim success
5096 long oldId = Binder.clearCallingIdentity();
5097 mWakelock.acquire();
5098 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005099 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005100 mBackupHandler.sendMessage(msg);
5101 Binder.restoreCallingIdentity(oldId);
5102 return 0;
5103 }
5104
Christopher Tate73a3cb32010-12-13 18:27:26 -08005105 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5106 class EndRestoreRunnable implements Runnable {
5107 BackupManagerService mBackupManager;
5108 ActiveRestoreSession mSession;
5109
5110 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5111 mBackupManager = manager;
5112 mSession = session;
5113 }
5114
5115 public void run() {
5116 // clean up the session's bookkeeping
5117 synchronized (mSession) {
5118 try {
5119 if (mSession.mRestoreTransport != null) {
5120 mSession.mRestoreTransport.finishRestore();
5121 }
5122 } catch (Exception e) {
5123 Slog.e(TAG, "Error in finishRestore", e);
5124 } finally {
5125 mSession.mRestoreTransport = null;
5126 mSession.mEnded = true;
5127 }
5128 }
5129
5130 // clean up the BackupManagerService side of the bookkeeping
5131 // and cancel any pending timeout message
5132 mBackupManager.clearRestoreSession(mSession);
5133 }
5134 }
5135
Dan Egnor0084da52009-07-29 12:57:16 -07005136 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005137 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005138
Christopher Tate73a3cb32010-12-13 18:27:26 -08005139 if (mEnded) {
5140 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005141 }
5142
Christopher Tate73a3cb32010-12-13 18:27:26 -08005143 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005144 }
5145 }
5146
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005147 @Override
5148 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005149 long identityToken = Binder.clearCallingIdentity();
5150 try {
5151 dumpInternal(pw);
5152 } finally {
5153 Binder.restoreCallingIdentity(identityToken);
5154 }
5155 }
5156
5157 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005158 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005159 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005160 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005161 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005162 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07005163 pw.println("Last backup pass: " + mLastBackupPass
5164 + " (now = " + System.currentTimeMillis() + ')');
5165 pw.println(" next scheduled: " + mNextBackupPass);
5166
Christopher Tate91717492009-06-26 21:07:13 -07005167 pw.println("Available transports:");
5168 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005169 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5170 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005171 IBackupTransport transport = getTransport(t);
5172 File dir = new File(mBaseStateDir, transport.transportDirName());
5173 pw.println(" destination: " + transport.currentDestinationString());
5174 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005175 for (File f : dir.listFiles()) {
5176 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5177 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005178 } catch (Exception e) {
5179 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005180 pw.println(" Error: " + e);
5181 }
Christopher Tate91717492009-06-26 21:07:13 -07005182 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005183
5184 pw.println("Pending init: " + mPendingInits.size());
5185 for (String s : mPendingInits) {
5186 pw.println(" " + s);
5187 }
5188
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005189 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005190 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005191 for (int i=0; i<N; i++) {
5192 int uid = mBackupParticipants.keyAt(i);
5193 pw.print(" uid: ");
5194 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005195 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5196 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005197 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005198 }
5199 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005200
Christopher Tateb49ceb32010-02-08 16:22:24 -08005201 pw.println("Ancestral packages: "
5202 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005203 if (mAncestralPackages != null) {
5204 for (String pkg : mAncestralPackages) {
5205 pw.println(" " + pkg);
5206 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005207 }
5208
Christopher Tate73e02522009-07-15 14:18:26 -07005209 pw.println("Ever backed up: " + mEverStoredApps.size());
5210 for (String pkg : mEverStoredApps) {
5211 pw.println(" " + pkg);
5212 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005213
5214 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005215 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005216 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005217 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005218 }
5219 }
Christopher Tate487529a2009-04-29 14:03:25 -07005220}