blob: aebfd600b36715917c3866321288164c510e196b [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 Tated2c0cd42011-09-15 15:51:29 -070037import android.content.ContentResolver;
Christopher Tate487529a2009-04-29 14:03:25 -070038import android.content.Context;
39import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070040import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070041import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070042import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070043import android.content.pm.IPackageDataObserver;
Christopher Tatea858cb02011-06-03 12:27:51 -070044import android.content.pm.IPackageDeleteObserver;
Christopher Tate75a99702011-05-18 16:28:19 -070045import android.content.pm.IPackageInstallObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080046import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070047import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070048import android.content.pm.PackageManager;
Jason parks1125d782011-01-12 09:47:26 -060049import android.content.pm.Signature;
Jason parksa3cdaa52011-01-13 14:15:43 -060050import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070051import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070052import android.os.Binder;
Christopher Tate75a99702011-05-18 16:28:19 -070053import android.os.Build;
Christopher Tate3799bc22009-05-06 16:13:56 -070054import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070055import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070056import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080057import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070058import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080059import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070060import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070061import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070062import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070063import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070064import android.os.RemoteException;
Christopher Tate32418be2011-10-10 13:51:12 -070065import android.os.ServiceManager;
Dan Egnorbb9001c2009-07-27 12:20:13 -070066import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070067import android.os.WorkSource;
Christopher Tate32418be2011-10-10 13:51:12 -070068import android.os.storage.IMountService;
Oscar Montemayora8529f62009-11-18 10:14:20 -080069import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070070import android.util.EventLog;
Christopher Tate79ec80d2011-06-24 14:58:49 -070071import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080072import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070073import android.util.SparseArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070074import android.util.StringBuilderPrinter;
75
Jason parksa3cdaa52011-01-13 14:15:43 -060076import com.android.internal.backup.BackupConstants;
77import com.android.internal.backup.IBackupTransport;
78import com.android.internal.backup.LocalTransport;
79import com.android.server.PackageManagerBackupAgent.Metadata;
80
Christopher Tate2efd2db2011-07-19 16:32:49 -070081import java.io.BufferedInputStream;
82import java.io.BufferedOutputStream;
83import java.io.ByteArrayOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -070084import java.io.DataInputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070085import java.io.DataOutputStream;
Christopher Tatecde87f42009-06-12 12:55:53 -070086import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070087import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070088import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070089import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080090import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070091import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070092import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070093import java.io.InputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070094import java.io.OutputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070095import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070096import java.io.RandomAccessFile;
Christopher Tate2efd2db2011-07-19 16:32:49 -070097import java.security.InvalidAlgorithmParameterException;
98import java.security.InvalidKeyException;
99import java.security.Key;
100import java.security.NoSuchAlgorithmException;
101import java.security.SecureRandom;
102import java.security.spec.InvalidKeySpecException;
103import java.security.spec.KeySpec;
Christopher Tate75a99702011-05-18 16:28:19 -0700104import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -0400105import java.util.ArrayList;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700106import java.util.Arrays;
Christopher Tate75a99702011-05-18 16:28:19 -0700107import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -0400108import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -0700109import java.util.HashSet;
110import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -0700111import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -0700112import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800113import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -0700114import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate7926a692011-07-11 11:31:57 -0700115import java.util.zip.Deflater;
116import java.util.zip.DeflaterOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -0700117import java.util.zip.InflaterInputStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700118
Christopher Tate2efd2db2011-07-19 16:32:49 -0700119import javax.crypto.BadPaddingException;
120import javax.crypto.Cipher;
121import javax.crypto.CipherInputStream;
122import javax.crypto.CipherOutputStream;
123import javax.crypto.IllegalBlockSizeException;
124import javax.crypto.NoSuchPaddingException;
125import javax.crypto.SecretKey;
126import javax.crypto.SecretKeyFactory;
127import javax.crypto.spec.IvParameterSpec;
128import javax.crypto.spec.PBEKeySpec;
129import javax.crypto.spec.SecretKeySpec;
130
Christopher Tate487529a2009-04-29 14:03:25 -0700131class BackupManagerService extends IBackupManager.Stub {
132 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -0700133 private static final boolean DEBUG = true;
Christopher Tateb1543a92011-09-07 12:11:09 -0700134 private static final boolean MORE_DEBUG = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700135
136 // Name and current contents version of the full-backup manifest file
137 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
138 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700139 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
140 static final int BACKUP_FILE_VERSION = 1;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700141 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
Christopher Tateaa088442009-06-16 18:25:46 -0700142
Christopher Tate49401dd2009-07-01 12:34:29 -0700143 // How often we perform a backup pass. Privileged external callers can
144 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700145 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700146
Dan Egnorc1c49c02009-10-30 17:35:39 -0700147 // Random variation in backup scheduling time to avoid server load spikes
148 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
149
Christopher Tate8031a3d2009-07-06 16:36:05 -0700150 // The amount of time between the initial provisioning of the device and
151 // the first backup pass.
152 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
153
Christopher Tate45281862010-03-05 15:46:30 -0800154 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
155 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
156 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700157 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700158 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700159 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700160 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700161 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700162 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
163 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800164 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700165 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
166 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700167
Christopher Tate8e294d42011-08-31 20:37:12 -0700168 // backup task state machine tick
169 static final int MSG_BACKUP_RESTORE_STEP = 20;
170 static final int MSG_OP_COMPLETE = 21;
171
Christopher Tatec7b31e32009-06-10 15:49:30 -0700172 // Timeout interval for deciding that a bind or clear-data has taken too long
173 static final long TIMEOUT_INTERVAL = 10 * 1000;
174
Christopher Tate44a27902010-01-27 17:15:49 -0800175 // Timeout intervals for agent backup & restore operations
176 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700177 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700178 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800179 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
180
Christopher Tate2efd2db2011-07-19 16:32:49 -0700181 // User confirmation timeout for a full backup/restore operation. It's this long in
182 // order to give them time to enter the backup password.
183 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700184
Christopher Tate487529a2009-04-29 14:03:25 -0700185 private Context mContext;
186 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800187 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700188 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700189 private PowerManager mPowerManager;
190 private AlarmManager mAlarmManager;
Christopher Tate32418be2011-10-10 13:51:12 -0700191 private IMountService mMountService;
Christopher Tate44a27902010-01-27 17:15:49 -0800192 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700193
Christopher Tate73e02522009-07-15 14:18:26 -0700194 boolean mEnabled; // access to this is synchronized on 'this'
195 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800196 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700197 PowerManager.WakeLock mWakelock;
Christopher Tate0bacfd22012-01-11 14:41:19 -0800198 HandlerThread mHandlerThread;
Christopher Tate44a27902010-01-27 17:15:49 -0800199 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700200 PendingIntent mRunBackupIntent, mRunInitIntent;
201 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700202 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700203 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700204 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700205 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700206 class BackupRequest {
Christopher Tatecc55f812011-08-16 16:06:53 -0700207 public String packageName;
Christopher Tateaa088442009-06-16 18:25:46 -0700208
Christopher Tatecc55f812011-08-16 16:06:53 -0700209 BackupRequest(String pkgName) {
210 packageName = pkgName;
Christopher Tate46758122009-05-06 11:22:00 -0700211 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700212
213 public String toString() {
Christopher Tatecc55f812011-08-16 16:06:53 -0700214 return "BackupRequest{pkg=" + packageName + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700215 }
Christopher Tate46758122009-05-06 11:22:00 -0700216 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800217 // Backups that we haven't started yet. Keys are package names.
218 HashMap<String,BackupRequest> mPendingBackups
219 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700220
221 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700222 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700223
224 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700225 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700226
Christopher Tate043dadc2009-06-02 16:11:00 -0700227 // The thread performing the sequence of queued backups binds to each app's agent
228 // in succession. Bind notifications are asynchronously delivered through the
229 // Activity Manager; use this lock object to signal when a requested binding has
230 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700231 final Object mAgentConnectLock = new Object();
232 IBackupAgent mConnectedAgent;
Christopher Tate336a6492011-10-05 16:05:43 -0700233 volatile boolean mBackupRunning;
Christopher Tate73e02522009-07-15 14:18:26 -0700234 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700235 volatile long mLastBackupPass;
236 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700237
Christopher Tate6de74ff2012-01-17 15:20:32 -0800238 // For debugging, we maintain a progress trace of operations during backup
239 static final boolean DEBUG_BACKUP_TRACE = true;
240 final List<String> mBackupTrace = new ArrayList<String>();
241
Christopher Tate55f931a2009-09-29 17:17:34 -0700242 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700243 final Object mClearDataLock = new Object();
244 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700245
Christopher Tate91717492009-06-26 21:07:13 -0700246 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700247 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700248 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700249 String mCurrentTransport;
250 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800251 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700252
Christopher Tate2d449afe2010-03-29 19:14:24 -0700253 class RestoreGetSetsParams {
254 public IBackupTransport transport;
255 public ActiveRestoreSession session;
256 public IRestoreObserver observer;
257
258 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
259 IRestoreObserver _observer) {
260 transport = _transport;
261 session = _session;
262 observer = _observer;
263 }
264 }
265
Christopher Tate73e02522009-07-15 14:18:26 -0700266 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700267 public IBackupTransport transport;
268 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700269 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800270 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800271 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700272 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700273 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800274
275 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700276 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800277 transport = _transport;
278 observer = _obs;
279 token = _token;
280 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800281 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700282 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700283 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800284 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700285
Chris Tate249345b2010-10-29 12:57:04 -0700286 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
287 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700288 transport = _transport;
289 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700290 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800291 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800292 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700293 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700294 filterSet = null;
295 }
296
297 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
298 String[] _filterSet, boolean _needFullBackup) {
299 transport = _transport;
300 observer = _obs;
301 token = _token;
302 pkgInfo = null;
303 pmToken = 0;
304 needFullBackup = _needFullBackup;
305 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700306 }
307 }
308
Christopher Tate73e02522009-07-15 14:18:26 -0700309 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700310 public IBackupTransport transport;
311 public PackageInfo packageInfo;
312
313 ClearParams(IBackupTransport _transport, PackageInfo _info) {
314 transport = _transport;
315 packageInfo = _info;
316 }
317 }
318
Christopher Tate4a627c72011-04-01 14:43:32 -0700319 class FullParams {
320 public ParcelFileDescriptor fd;
321 public final AtomicBoolean latch;
322 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700323 public String curPassword; // filled in by the confirmation step
324 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700325
326 FullParams() {
327 latch = new AtomicBoolean(false);
328 }
329 }
330
331 class FullBackupParams extends FullParams {
332 public boolean includeApks;
333 public boolean includeShared;
334 public boolean allApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700335 public boolean includeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700336 public String[] packages;
337
338 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
Christopher Tate240c7d22011-10-03 18:13:44 -0700339 boolean doAllApps, boolean doSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -0700340 fd = output;
341 includeApks = saveApks;
342 includeShared = saveShared;
343 allApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700344 includeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700345 packages = pkgList;
346 }
347 }
348
349 class FullRestoreParams extends FullParams {
350 FullRestoreParams(ParcelFileDescriptor input) {
351 fd = input;
352 }
353 }
354
Christopher Tate44a27902010-01-27 17:15:49 -0800355 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
356 // token is the index of the entry in the pending-operations list.
357 static final int OP_PENDING = 0;
358 static final int OP_ACKNOWLEDGED = 1;
359 static final int OP_TIMEOUT = -1;
360
Christopher Tate8e294d42011-08-31 20:37:12 -0700361 class Operation {
362 public int state;
363 public BackupRestoreTask callback;
364
365 Operation(int initialState, BackupRestoreTask callbackObj) {
366 state = initialState;
367 callback = callbackObj;
368 }
369 }
370 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
Christopher Tate44a27902010-01-27 17:15:49 -0800371 final Object mCurrentOpLock = new Object();
372 final Random mTokenGenerator = new Random();
373
Christopher Tate4a627c72011-04-01 14:43:32 -0700374 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
375
Christopher Tate5cb400b2009-06-25 16:03:14 -0700376 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700377 File mBaseStateDir;
378 File mDataDir;
379 File mJournalDir;
380 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700381
Christopher Tate2efd2db2011-07-19 16:32:49 -0700382 // Backup password, if any, and the file where it's saved. What is stored is not the
383 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
384 // persisted) salt. Validation is performed by running the challenge text through the
385 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
386 // the saved hash string, then the challenge text matches the originally supplied
387 // password text.
388 private final SecureRandom mRng = new SecureRandom();
389 private String mPasswordHash;
390 private File mPasswordHashFile;
391 private byte[] mPasswordSalt;
392
393 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
394 static final int PBKDF2_HASH_ROUNDS = 10000;
395 static final int PBKDF2_KEY_SIZE = 256; // bits
396 static final int PBKDF2_SALT_SIZE = 512; // bits
397 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
398
Christopher Tate84725812010-02-04 15:52:40 -0800399 // Keep a log of all the apps we've ever backed up, and what the
400 // dataset tokens are for both the current backup dataset and
401 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700402 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700403 HashSet<String> mEverStoredApps = new HashSet<String>();
404
Christopher Tateb49ceb32010-02-08 16:22:24 -0800405 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800406 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800407 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800408 long mAncestralToken = 0;
409 long mCurrentToken = 0;
410
Christopher Tate4cc86e12009-09-21 19:36:51 -0700411 // Persistently track the need to do a full init
412 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
413 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700414
Christopher Tate4a627c72011-04-01 14:43:32 -0700415 // Utility: build a new random integer token
416 int generateToken() {
417 int token;
418 do {
419 synchronized (mTokenGenerator) {
420 token = mTokenGenerator.nextInt();
421 }
422 } while (token < 0);
423 return token;
424 }
425
Christopher Tate44a27902010-01-27 17:15:49 -0800426 // ----- Asynchronous backup/restore handler thread -----
427
428 private class BackupHandler extends Handler {
429 public BackupHandler(Looper looper) {
430 super(looper);
431 }
432
433 public void handleMessage(Message msg) {
434
435 switch (msg.what) {
436 case MSG_RUN_BACKUP:
437 {
438 mLastBackupPass = System.currentTimeMillis();
439 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
440
441 IBackupTransport transport = getTransport(mCurrentTransport);
442 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800443 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate336a6492011-10-05 16:05:43 -0700444 synchronized (mQueueLock) {
445 mBackupRunning = false;
446 }
Christopher Tate44a27902010-01-27 17:15:49 -0800447 mWakelock.release();
448 break;
449 }
450
451 // snapshot the pending-backup set and work on that
452 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800453 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800454 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800455 // Do we have any work to do? Construct the work queue
456 // then release the synchronization lock to actually run
457 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800458 if (mPendingBackups.size() > 0) {
459 for (BackupRequest b: mPendingBackups.values()) {
460 queue.add(b);
461 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800462 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800463 mPendingBackups.clear();
464
465 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800466 mJournal = null;
467
Christopher Tate44a27902010-01-27 17:15:49 -0800468 }
469 }
Christopher Tatec61da312010-02-05 10:41:27 -0800470
Christopher Tate8e294d42011-08-31 20:37:12 -0700471 // At this point, we have started a new journal file, and the old
472 // file identity is being passed to the backup processing task.
473 // When it completes successfully, that old journal file will be
474 // deleted. If we crash prior to that, the old journal is parsed
475 // at next boot and the journaled requests fulfilled.
Christopher Tatec61da312010-02-05 10:41:27 -0800476 if (queue.size() > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -0700477 // Spin up a backup state sequence and set it running
478 PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
479 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
480 sendMessage(pbtMessage);
Christopher Tatec61da312010-02-05 10:41:27 -0800481 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800482 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tate336a6492011-10-05 16:05:43 -0700483 synchronized (mQueueLock) {
484 mBackupRunning = false;
485 }
Christopher Tatec61da312010-02-05 10:41:27 -0800486 mWakelock.release();
487 }
Christopher Tate44a27902010-01-27 17:15:49 -0800488 break;
489 }
490
Christopher Tate8e294d42011-08-31 20:37:12 -0700491 case MSG_BACKUP_RESTORE_STEP:
492 {
493 try {
494 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
495 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
496 task.execute();
497 } catch (ClassCastException e) {
498 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
499 }
500 break;
501 }
502
503 case MSG_OP_COMPLETE:
504 {
505 try {
Christopher Tate2982d062011-09-06 20:35:24 -0700506 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
507 task.operationComplete();
Christopher Tate8e294d42011-08-31 20:37:12 -0700508 } catch (ClassCastException e) {
509 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
510 }
511 break;
512 }
513
Christopher Tate44a27902010-01-27 17:15:49 -0800514 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700515 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700516 // TODO: refactor full backup to be a looper-based state machine
517 // similar to normal backup/restore.
Christopher Tate4a627c72011-04-01 14:43:32 -0700518 FullBackupParams params = (FullBackupParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700519 PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
520 params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700521 params.includeShared, params.curPassword, params.encryptPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -0700522 params.allApps, params.includeSystem, params.packages, params.latch);
Christopher Tatea28e8542011-09-12 13:45:21 -0700523 (new Thread(task)).start();
Christopher Tate44a27902010-01-27 17:15:49 -0800524 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700525 }
Christopher Tate44a27902010-01-27 17:15:49 -0800526
527 case MSG_RUN_RESTORE:
528 {
529 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800530 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate2982d062011-09-06 20:35:24 -0700531 PerformRestoreTask task = new PerformRestoreTask(
532 params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700533 params.token, params.pkgInfo, params.pmToken,
Christopher Tate2982d062011-09-06 20:35:24 -0700534 params.needFullBackup, params.filterSet);
535 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
536 sendMessage(restoreMsg);
Christopher Tate44a27902010-01-27 17:15:49 -0800537 break;
538 }
539
Christopher Tate75a99702011-05-18 16:28:19 -0700540 case MSG_RUN_FULL_RESTORE:
541 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700542 // TODO: refactor full restore to be a looper-based state machine
543 // similar to normal backup/restore.
Christopher Tate75a99702011-05-18 16:28:19 -0700544 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700545 PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
546 params.curPassword, params.encryptPassword,
547 params.observer, params.latch);
548 (new Thread(task)).start();
Christopher Tate75a99702011-05-18 16:28:19 -0700549 break;
550 }
551
Christopher Tate44a27902010-01-27 17:15:49 -0800552 case MSG_RUN_CLEAR:
553 {
554 ClearParams params = (ClearParams)msg.obj;
555 (new PerformClearTask(params.transport, params.packageInfo)).run();
556 break;
557 }
558
559 case MSG_RUN_INITIALIZE:
560 {
561 HashSet<String> queue;
562
563 // Snapshot the pending-init queue and work on that
564 synchronized (mQueueLock) {
565 queue = new HashSet<String>(mPendingInits);
566 mPendingInits.clear();
567 }
568
569 (new PerformInitializeTask(queue)).run();
570 break;
571 }
572
Christopher Tate2d449afe2010-03-29 19:14:24 -0700573 case MSG_RUN_GET_RESTORE_SETS:
574 {
575 // Like other async operations, this is entered with the wakelock held
576 RestoreSet[] sets = null;
577 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
578 try {
579 sets = params.transport.getAvailableRestoreSets();
580 // cache the result in the active session
581 synchronized (params.session) {
582 params.session.mRestoreSets = sets;
583 }
584 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
585 } catch (Exception e) {
586 Slog.e(TAG, "Error from transport getting set list");
587 } finally {
588 if (params.observer != null) {
589 try {
590 params.observer.restoreSetsAvailable(sets);
591 } catch (RemoteException re) {
592 Slog.e(TAG, "Unable to report listing to observer");
593 } catch (Exception e) {
594 Slog.e(TAG, "Restore observer threw", e);
595 }
596 }
597
Christopher Tate2a935092011-03-03 17:30:32 -0800598 // Done: reset the session timeout clock
599 removeMessages(MSG_RESTORE_TIMEOUT);
600 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
601
Christopher Tate2d449afe2010-03-29 19:14:24 -0700602 mWakelock.release();
603 }
604 break;
605 }
606
Christopher Tate44a27902010-01-27 17:15:49 -0800607 case MSG_TIMEOUT:
608 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700609 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800610 break;
611 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800612
613 case MSG_RESTORE_TIMEOUT:
614 {
615 synchronized (BackupManagerService.this) {
616 if (mActiveRestoreSession != null) {
617 // Client app left the restore session dangling. We know that it
618 // can't be in the middle of an actual restore operation because
Christopher Tate2982d062011-09-06 20:35:24 -0700619 // the timeout is suspended while a restore is in progress. Clean
Christopher Tate73a3cb32010-12-13 18:27:26 -0800620 // up now.
621 Slog.w(TAG, "Restore session timed out; aborting");
622 post(mActiveRestoreSession.new EndRestoreRunnable(
623 BackupManagerService.this, mActiveRestoreSession));
624 }
625 }
626 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700627
628 case MSG_FULL_CONFIRMATION_TIMEOUT:
629 {
630 synchronized (mFullConfirmations) {
631 FullParams params = mFullConfirmations.get(msg.arg1);
632 if (params != null) {
633 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
634
635 // Release the waiter; timeout == completion
636 signalFullBackupRestoreCompletion(params);
637
638 // Remove the token from the set
639 mFullConfirmations.delete(msg.arg1);
640
641 // Report a timeout to the observer, if any
642 if (params.observer != null) {
643 try {
644 params.observer.onTimeout();
645 } catch (RemoteException e) {
646 /* don't care if the app has gone away */
647 }
648 }
649 } else {
650 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
651 }
652 }
653 break;
654 }
Christopher Tate44a27902010-01-27 17:15:49 -0800655 }
656 }
657 }
658
Christopher Tate6de74ff2012-01-17 15:20:32 -0800659 // ----- Debug-only backup operation trace -----
660 void addBackupTrace(String s) {
661 if (DEBUG_BACKUP_TRACE) {
662 synchronized (mBackupTrace) {
663 mBackupTrace.add(s);
664 }
665 }
666 }
667
668 void clearBackupTrace() {
669 if (DEBUG_BACKUP_TRACE) {
670 synchronized (mBackupTrace) {
671 mBackupTrace.clear();
672 }
673 }
674 }
675
Christopher Tate44a27902010-01-27 17:15:49 -0800676 // ----- Main service implementation -----
677
Christopher Tate487529a2009-04-29 14:03:25 -0700678 public BackupManagerService(Context context) {
679 mContext = context;
680 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700681 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700682 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700683
Christopher Tateb6787f22009-07-02 17:40:45 -0700684 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
685 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
Christopher Tate32418be2011-10-10 13:51:12 -0700686 mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
Christopher Tateb6787f22009-07-02 17:40:45 -0700687
Christopher Tate44a27902010-01-27 17:15:49 -0800688 mBackupManagerBinder = asInterface(asBinder());
689
690 // spin up the backup/restore handler thread
691 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
692 mHandlerThread.start();
693 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
694
Christopher Tate22b87872009-05-04 16:41:53 -0700695 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700696 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700697 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700698 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700699 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800700 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800701 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800702 // If Encrypted file systems is enabled or disabled, this call will return the
703 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600704 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800705 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700706 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700707
Christopher Tate2efd2db2011-07-19 16:32:49 -0700708 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
709 if (mPasswordHashFile.exists()) {
710 FileInputStream fin = null;
711 DataInputStream in = null;
712 try {
713 fin = new FileInputStream(mPasswordHashFile);
714 in = new DataInputStream(new BufferedInputStream(fin));
715 // integer length of the salt array, followed by the salt,
716 // then the hex pw hash string
717 int saltLen = in.readInt();
718 byte[] salt = new byte[saltLen];
719 in.readFully(salt);
720 mPasswordHash = in.readUTF();
721 mPasswordSalt = salt;
722 } catch (IOException e) {
723 Slog.e(TAG, "Unable to read saved backup pw hash");
724 } finally {
725 try {
726 if (in != null) in.close();
727 if (fin != null) fin.close();
728 } catch (IOException e) {
729 Slog.w(TAG, "Unable to close streams");
730 }
731 }
732 }
733
Christopher Tate4cc86e12009-09-21 19:36:51 -0700734 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700735 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700736 IntentFilter filter = new IntentFilter();
737 filter.addAction(RUN_BACKUP_ACTION);
738 context.registerReceiver(mRunBackupReceiver, filter,
739 android.Manifest.permission.BACKUP, null);
740
741 mRunInitReceiver = new RunInitializeReceiver();
742 filter = new IntentFilter();
743 filter.addAction(RUN_INITIALIZE_ACTION);
744 context.registerReceiver(mRunInitReceiver, filter,
745 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700746
747 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700748 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
749 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
750
Christopher Tate4cc86e12009-09-21 19:36:51 -0700751 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
752 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
753 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
754
Christopher Tatecde87f42009-06-12 12:55:53 -0700755 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700756 mJournalDir = new File(mBaseStateDir, "pending");
757 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700758 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700759
Christopher Tate73e02522009-07-15 14:18:26 -0700760 // Set up the various sorts of package tracking we do
761 initPackageTracking();
762
Christopher Tateabce4e82009-06-18 18:35:32 -0700763 // Build our mapping of uid to backup client services. This implicitly
764 // schedules a backup pass on the Package Manager metadata the first
765 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700766 synchronized (mBackupParticipants) {
767 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700768 }
769
Dan Egnor87a02bc2009-06-17 02:30:10 -0700770 // Set up our transport options and initialize the default transport
771 // TODO: Have transports register themselves somehow?
772 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700773 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700774 ComponentName localName = new ComponentName(context, LocalTransport.class);
775 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700776
Christopher Tate91717492009-06-26 21:07:13 -0700777 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700778 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
779 Settings.Secure.BACKUP_TRANSPORT);
780 if ("".equals(mCurrentTransport)) {
781 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700782 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800783 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700784
785 // Attach to the Google backup transport. When this comes up, it will set
786 // itself as the current transport because we explicitly reset mCurrentTransport
787 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700788 ComponentName transportComponent = new ComponentName("com.google.android.backup",
789 "com.google.android.backup.BackupTransportService");
790 try {
791 // If there's something out there that is supposed to be the Google
792 // backup transport, make sure it's legitimately part of the OS build
793 // and not an app lying about its package name.
794 ApplicationInfo info = mPackageManager.getApplicationInfo(
795 transportComponent.getPackageName(), 0);
796 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
797 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
798 Intent intent = new Intent().setComponent(transportComponent);
799 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
800 } else {
801 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
802 }
803 } catch (PackageManager.NameNotFoundException nnf) {
804 // No such package? No binding.
805 if (DEBUG) Slog.v(TAG, "Google transport not present");
806 }
Christopher Tateaa088442009-06-16 18:25:46 -0700807
Christopher Tatecde87f42009-06-12 12:55:53 -0700808 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700809 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700810 parseLeftoverJournals();
811
Christopher Tateb6787f22009-07-02 17:40:45 -0700812 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700813 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700814
815 // Start the backup passes going
816 setBackupEnabled(areEnabled);
817 }
818
819 private class RunBackupReceiver extends BroadcastReceiver {
820 public void onReceive(Context context, Intent intent) {
821 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700822 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700823 if (mPendingInits.size() > 0) {
824 // If there are pending init operations, we process those
825 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800826 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700827 try {
828 mAlarmManager.cancel(mRunInitIntent);
829 mRunInitIntent.send();
830 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800831 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700832 // can't really do more than bail here
833 }
834 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800835 // Don't run backups now if we're disabled or not yet
836 // fully set up.
837 if (mEnabled && mProvisioned) {
Christopher Tate336a6492011-10-05 16:05:43 -0700838 if (!mBackupRunning) {
839 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700840
Christopher Tate336a6492011-10-05 16:05:43 -0700841 // Acquire the wakelock and pass it to the backup thread. it will
842 // be released once backup concludes.
843 mBackupRunning = true;
844 mWakelock.acquire();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700845
Christopher Tate336a6492011-10-05 16:05:43 -0700846 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
847 mBackupHandler.sendMessage(msg);
848 } else {
849 Slog.i(TAG, "Backup time but one already running");
850 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700851 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800852 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700853 }
854 }
855 }
856 }
857 }
858 }
859
860 private class RunInitializeReceiver extends BroadcastReceiver {
861 public void onReceive(Context context, Intent intent) {
862 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
863 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800864 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700865
866 // Acquire the wakelock and pass it to the init thread. it will
867 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700868 mWakelock.acquire();
869
Christopher Tate4cc86e12009-09-21 19:36:51 -0700870 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700871 mBackupHandler.sendMessage(msg);
872 }
873 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700874 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700875 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700876
Christopher Tate73e02522009-07-15 14:18:26 -0700877 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800878 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700879
Christopher Tate84725812010-02-04 15:52:40 -0800880 // Remember our ancestral dataset
881 mTokenFile = new File(mBaseStateDir, "ancestral");
882 try {
883 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800884 int version = tf.readInt();
885 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
886 mAncestralToken = tf.readLong();
887 mCurrentToken = tf.readLong();
888
889 int numPackages = tf.readInt();
890 if (numPackages >= 0) {
891 mAncestralPackages = new HashSet<String>();
892 for (int i = 0; i < numPackages; i++) {
893 String pkgName = tf.readUTF();
894 mAncestralPackages.add(pkgName);
895 }
896 }
897 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800898 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800899 } catch (FileNotFoundException fnf) {
900 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800901 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800902 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800903 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800904 }
905
Christopher Tatee97e8072009-07-15 16:45:50 -0700906 // Keep a log of what apps we've ever backed up. Because we might have
907 // rebooted in the middle of an operation that was removing something from
908 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700909 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700910 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700911
Christopher Tatee97e8072009-07-15 16:45:50 -0700912 // If we were in the middle of removing something from the ever-backed-up
913 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700914 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700915 if (tempProcessedFile.exists()) {
916 tempProcessedFile.delete();
917 }
918
Dan Egnor852f8e42009-09-30 11:20:45 -0700919 // If there are previous contents, parse them out then start a new
920 // file to continue the recordkeeping.
921 if (mEverStored.exists()) {
922 RandomAccessFile temp = null;
923 RandomAccessFile in = null;
924
925 try {
926 temp = new RandomAccessFile(tempProcessedFile, "rws");
927 in = new RandomAccessFile(mEverStored, "r");
928
929 while (true) {
930 PackageInfo info;
931 String pkg = in.readUTF();
932 try {
933 info = mPackageManager.getPackageInfo(pkg, 0);
934 mEverStoredApps.add(pkg);
935 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700936 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700937 } catch (NameNotFoundException e) {
938 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700939 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700940 }
941 }
942 } catch (EOFException e) {
943 // Once we've rewritten the backup history log, atomically replace the
944 // old one with the new one then reopen the file for continuing use.
945 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800946 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700947 }
948 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800949 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700950 } finally {
951 try { if (temp != null) temp.close(); } catch (IOException e) {}
952 try { if (in != null) in.close(); } catch (IOException e) {}
953 }
954 }
955
Christopher Tate73e02522009-07-15 14:18:26 -0700956 // Register for broadcasts about package install, etc., so we can
957 // update the provider list.
958 IntentFilter filter = new IntentFilter();
959 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
960 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Christopher Tatecc55f812011-08-16 16:06:53 -0700961 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Christopher Tate73e02522009-07-15 14:18:26 -0700962 filter.addDataScheme("package");
963 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800964 // Register for events related to sdcard installation.
965 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800966 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
967 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800968 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700969 }
970
Christopher Tatecde87f42009-06-12 12:55:53 -0700971 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700972 for (File f : mJournalDir.listFiles()) {
973 if (mJournal == null || f.compareTo(mJournal) != 0) {
974 // This isn't the current journal, so it must be a leftover. Read
975 // out the package names mentioned there and schedule them for
976 // backup.
977 RandomAccessFile in = null;
978 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400979 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700980 in = new RandomAccessFile(f, "r");
981 while (true) {
982 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400983 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700984 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700985 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700986 } catch (EOFException e) {
987 // no more data; we're done
988 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800989 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700990 } finally {
991 // close/delete the file
992 try { if (in != null) in.close(); } catch (IOException e) {}
993 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700994 }
995 }
996 }
997 }
998
Christopher Tate2efd2db2011-07-19 16:32:49 -0700999 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
1000 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
1001 }
1002
1003 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
1004 try {
1005 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
1006 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1007 return keyFactory.generateSecret(ks);
1008 } catch (InvalidKeySpecException e) {
1009 Slog.e(TAG, "Invalid key spec for PBKDF2!");
1010 } catch (NoSuchAlgorithmException e) {
1011 Slog.e(TAG, "PBKDF2 unavailable!");
1012 }
1013 return null;
1014 }
1015
1016 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
1017 SecretKey key = buildPasswordKey(pw, salt, rounds);
1018 if (key != null) {
1019 return byteArrayToHex(key.getEncoded());
1020 }
1021 return null;
1022 }
1023
1024 private String byteArrayToHex(byte[] data) {
1025 StringBuilder buf = new StringBuilder(data.length * 2);
1026 for (int i = 0; i < data.length; i++) {
1027 buf.append(Byte.toHexString(data[i], true));
1028 }
1029 return buf.toString();
1030 }
1031
1032 private byte[] hexToByteArray(String digits) {
1033 final int bytes = digits.length() / 2;
1034 if (2*bytes != digits.length()) {
1035 throw new IllegalArgumentException("Hex string must have an even number of digits");
1036 }
1037
1038 byte[] result = new byte[bytes];
1039 for (int i = 0; i < digits.length(); i += 2) {
1040 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1041 }
1042 return result;
1043 }
1044
1045 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1046 char[] mkAsChar = new char[pwBytes.length];
1047 for (int i = 0; i < pwBytes.length; i++) {
1048 mkAsChar[i] = (char) pwBytes[i];
1049 }
1050
1051 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1052 return checksum.getEncoded();
1053 }
1054
1055 // Used for generating random salts or passwords
1056 private byte[] randomBytes(int bits) {
1057 byte[] array = new byte[bits / 8];
1058 mRng.nextBytes(array);
1059 return array;
1060 }
1061
1062 // Backup password management
1063 boolean passwordMatchesSaved(String candidatePw, int rounds) {
Christopher Tate32418be2011-10-10 13:51:12 -07001064 // First, on an encrypted device we require matching the device pw
1065 final boolean isEncrypted;
1066 try {
1067 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
1068 if (isEncrypted) {
1069 if (DEBUG) {
1070 Slog.i(TAG, "Device encrypted; verifying against device data pw");
1071 }
1072 // 0 means the password validated
1073 // -2 means device not encrypted
1074 // Any other result is either password failure or an error condition,
1075 // so we refuse the match
1076 final int result = mMountService.verifyEncryptionPassword(candidatePw);
1077 if (result == 0) {
1078 if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
1079 return true;
1080 } else if (result != -2) {
1081 if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
1082 return false;
1083 } else {
1084 // ...else the device is supposedly not encrypted. HOWEVER, the
1085 // query about the encryption state said that the device *is*
1086 // encrypted, so ... we may have a problem. Log it and refuse
1087 // the backup.
1088 Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
1089 return false;
1090 }
1091 }
1092 } catch (Exception e) {
1093 // Something went wrong talking to the mount service. This is very bad;
1094 // assume that we fail password validation.
1095 return false;
1096 }
1097
Christopher Tate2efd2db2011-07-19 16:32:49 -07001098 if (mPasswordHash == null) {
1099 // no current password case -- require that 'currentPw' be null or empty
1100 if (candidatePw == null || "".equals(candidatePw)) {
1101 return true;
1102 } // else the non-empty candidate does not match the empty stored pw
1103 } else {
1104 // hash the stated current pw and compare to the stored one
1105 if (candidatePw != null && candidatePw.length() > 0) {
1106 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1107 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1108 // candidate hash matches the stored hash -- the password matches
1109 return true;
1110 }
1111 } // else the stored pw is nonempty but the candidate is empty; no match
1112 }
1113 return false;
1114 }
1115
1116 @Override
1117 public boolean setBackupPassword(String currentPw, String newPw) {
1118 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1119 "setBackupPassword");
1120
1121 // If the supplied pw doesn't hash to the the saved one, fail
1122 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1123 return false;
1124 }
1125
1126 // Clearing the password is okay
1127 if (newPw == null || newPw.isEmpty()) {
1128 if (mPasswordHashFile.exists()) {
1129 if (!mPasswordHashFile.delete()) {
1130 // Unable to delete the old pw file, so fail
1131 Slog.e(TAG, "Unable to clear backup password");
1132 return false;
1133 }
1134 }
1135 mPasswordHash = null;
1136 mPasswordSalt = null;
1137 return true;
1138 }
1139
1140 try {
1141 // Okay, build the hash of the new backup password
1142 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1143 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1144
1145 OutputStream pwf = null, buffer = null;
1146 DataOutputStream out = null;
1147 try {
1148 pwf = new FileOutputStream(mPasswordHashFile);
1149 buffer = new BufferedOutputStream(pwf);
1150 out = new DataOutputStream(buffer);
1151 // integer length of the salt array, followed by the salt,
1152 // then the hex pw hash string
1153 out.writeInt(salt.length);
1154 out.write(salt);
1155 out.writeUTF(newPwHash);
1156 out.flush();
1157 mPasswordHash = newPwHash;
1158 mPasswordSalt = salt;
1159 return true;
1160 } finally {
1161 if (out != null) out.close();
1162 if (buffer != null) buffer.close();
1163 if (pwf != null) pwf.close();
1164 }
1165 } catch (IOException e) {
1166 Slog.e(TAG, "Unable to set backup password");
1167 }
1168 return false;
1169 }
1170
1171 @Override
1172 public boolean hasBackupPassword() {
1173 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1174 "hasBackupPassword");
Christopher Tate32418be2011-10-10 13:51:12 -07001175
1176 try {
1177 return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
1178 || (mPasswordHash != null && mPasswordHash.length() > 0);
1179 } catch (Exception e) {
1180 // If we can't talk to the mount service we have a serious problem; fail
1181 // "secure" i.e. assuming that we require a password
1182 return true;
1183 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07001184 }
1185
Christopher Tate4cc86e12009-09-21 19:36:51 -07001186 // Maintain persistent state around whether need to do an initialize operation.
1187 // Must be called with the queue lock held.
1188 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001189 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001190 + " on transport " + transportName);
1191 try {
1192 IBackupTransport transport = getTransport(transportName);
1193 String transportDirName = transport.transportDirName();
1194 File stateDir = new File(mBaseStateDir, transportDirName);
1195 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1196
1197 if (isPending) {
1198 // We need an init before we can proceed with sending backup data.
1199 // Record that with an entry in our set of pending inits, as well as
1200 // journaling it via creation of a sentinel file.
1201 mPendingInits.add(transportName);
1202 try {
1203 (new FileOutputStream(initPendingFile)).close();
1204 } catch (IOException ioe) {
1205 // Something is badly wrong with our permissions; just try to move on
1206 }
1207 } else {
1208 // No more initialization needed; wipe the journal and reset our state.
1209 initPendingFile.delete();
1210 mPendingInits.remove(transportName);
1211 }
1212 } catch (RemoteException e) {
1213 // can't happen; the transport is local
1214 }
1215 }
1216
Christopher Tated55e18a2009-09-21 10:12:59 -07001217 // Reset all of our bookkeeping, in response to having been told that
1218 // the backend data has been wiped [due to idle expiry, for example],
1219 // so we must re-upload all saved settings.
1220 void resetBackupState(File stateFileDir) {
1221 synchronized (mQueueLock) {
1222 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001223 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001224 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001225
Christopher Tate84725812010-02-04 15:52:40 -08001226 mCurrentToken = 0;
1227 writeRestoreTokens();
1228
Christopher Tated55e18a2009-09-21 10:12:59 -07001229 // Remove all the state files
1230 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001231 // ... but don't touch the needs-init sentinel
1232 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1233 sf.delete();
1234 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001235 }
Christopher Tate45597642011-04-04 16:59:21 -07001236 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001237
Christopher Tate45597642011-04-04 16:59:21 -07001238 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001239 synchronized (mBackupParticipants) {
1240 int N = mBackupParticipants.size();
1241 for (int i=0; i<N; i++) {
1242 int uid = mBackupParticipants.keyAt(i);
1243 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1244 for (ApplicationInfo app: participants) {
1245 dataChangedImpl(app.packageName);
1246 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001247 }
1248 }
1249 }
1250
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001251 // Add a transport to our set of available backends. If 'transport' is null, this
1252 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001253 private void registerTransport(String name, IBackupTransport transport) {
1254 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001255 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001256 if (transport != null) {
1257 mTransports.put(name, transport);
1258 } else {
1259 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001260 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001261 mCurrentTransport = null;
1262 }
1263 // Nothing further to do in the unregistration case
1264 return;
1265 }
Christopher Tate91717492009-06-26 21:07:13 -07001266 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001267
1268 // If the init sentinel file exists, we need to be sure to perform the init
1269 // as soon as practical. We also create the state directory at registration
1270 // time to ensure it's present from the outset.
1271 try {
1272 String transportName = transport.transportDirName();
1273 File stateDir = new File(mBaseStateDir, transportName);
1274 stateDir.mkdirs();
1275
1276 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1277 if (initSentinel.exists()) {
1278 synchronized (mQueueLock) {
1279 mPendingInits.add(transportName);
1280
1281 // TODO: pick a better starting time than now + 1 minute
1282 long delay = 1000 * 60; // one minute, in milliseconds
1283 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1284 System.currentTimeMillis() + delay, mRunInitIntent);
1285 }
1286 }
1287 } catch (RemoteException e) {
1288 // can't happen, the transport is local
1289 }
Christopher Tate91717492009-06-26 21:07:13 -07001290 }
1291
Christopher Tate3799bc22009-05-06 16:13:56 -07001292 // ----- Track installation/removal of packages -----
1293 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1294 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001295 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001296
Christopher Tate3799bc22009-05-06 16:13:56 -07001297 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001298 boolean replacing = false;
1299 boolean added = false;
1300 Bundle extras = intent.getExtras();
1301 String pkgList[] = null;
1302 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatecc55f812011-08-16 16:06:53 -07001303 Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
1304 Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001305 Uri uri = intent.getData();
1306 if (uri == null) {
1307 return;
1308 }
1309 String pkgName = uri.getSchemeSpecificPart();
1310 if (pkgName != null) {
1311 pkgList = new String[] { pkgName };
1312 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001313 if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
1314 // use the existing "add with replacement" logic
1315 if (MORE_DEBUG) Slog.d(TAG, "PACKAGE_REPLACED, updating package " + pkgName);
1316 added = replacing = true;
1317 } else {
1318 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1319 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
1320 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001321 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001322 added = true;
1323 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001324 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001325 added = false;
1326 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1327 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001328
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001329 if (pkgList == null || pkgList.length == 0) {
1330 return;
1331 }
1332 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001333 synchronized (mBackupParticipants) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001334 if (replacing) {
1335 updatePackageParticipantsLocked(pkgList);
1336 } else {
1337 addPackageParticipantsLocked(pkgList);
Christopher Tate3799bc22009-05-06 16:13:56 -07001338 }
1339 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001340 } else {
1341 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001342 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1343 } else {
1344 synchronized (mBackupParticipants) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001345 removePackageParticipantsLocked(pkgList);
Christopher Tate3799bc22009-05-06 16:13:56 -07001346 }
1347 }
1348 }
1349 }
1350 };
1351
Dan Egnor87a02bc2009-06-17 02:30:10 -07001352 // ----- Track connection to GoogleBackupTransport service -----
1353 ServiceConnection mGoogleConnection = new ServiceConnection() {
1354 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001355 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001356 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001357 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001358 }
1359
1360 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001361 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001362 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001363 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001364 }
1365 };
1366
Christopher Tate0bacfd22012-01-11 14:41:19 -08001367 // Add the backup agents in the given packages to our set of known backup participants.
1368 // If 'packageNames' is null, adds all backup agents in the whole system.
1369 void addPackageParticipantsLocked(String[] packageNames) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001370 // Look for apps that define the android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -07001371 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate0bacfd22012-01-11 14:41:19 -08001372 if (packageNames != null) {
1373 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1374 for (String packageName : packageNames) {
1375 addPackageParticipantsLockedInner(packageName, targetApps);
1376 }
1377 } else {
1378 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1379 addPackageParticipantsLockedInner(null, targetApps);
1380 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001381 }
1382
Christopher Tate181fafa2009-05-14 11:12:14 -07001383 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001384 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001385 if (MORE_DEBUG) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001386 Slog.v(TAG, "Examining " + packageName + " for backup agent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001387 }
1388
Dan Egnorefe52642009-06-24 00:16:33 -07001389 for (PackageInfo pkg : targetPkgs) {
1390 if (packageName == null || pkg.packageName.equals(packageName)) {
1391 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001392 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001393 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001394 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001395 mBackupParticipants.put(uid, set);
1396 }
Dan Egnorefe52642009-06-24 00:16:33 -07001397 set.add(pkg.applicationInfo);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001398 if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
Christopher Tate73e02522009-07-15 14:18:26 -07001399
1400 // If we've never seen this app before, schedule a backup for it
1401 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001402 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001403 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001404 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001405 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001406 }
Christopher Tate487529a2009-04-29 14:03:25 -07001407 }
1408 }
1409
Christopher Tate0bacfd22012-01-11 14:41:19 -08001410 // Remove the given packages' entries from our known active set.
1411 void removePackageParticipantsLocked(String[] packageNames) {
1412 if (packageNames == null) {
1413 Slog.w(TAG, "removePackageParticipants with null list");
1414 return;
Christopher Tate181fafa2009-05-14 11:12:14 -07001415 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001416
1417 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: #" + packageNames.length);
1418 List<PackageInfo> knownPackages = allAgentPackages();
1419 for (String pkg : packageNames) {
1420 removePackageParticipantsLockedInner(pkg, knownPackages);
1421 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001422 }
1423
Joe Onorato8ad02812009-05-13 01:41:44 -04001424 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tate0bacfd22012-01-11 14:41:19 -08001425 List<PackageInfo> allPackages) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001426 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001427 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tate0bacfd22012-01-11 14:41:19 -08001428 + ") removing from " + allPackages.size() + " entries");
1429 for (PackageInfo p : allPackages) {
1430 Slog.v(TAG, " - " + p.packageName);
Christopher Tate043dadc2009-06-02 16:11:00 -07001431 }
1432 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001433 for (PackageInfo pkg : allPackages) {
1434 if (packageName == null || pkg.packageName.equals(packageName)) {
1435 /*
Christopher Tatec28083a2010-12-14 16:16:44 -08001436 int uid = -1;
1437 try {
1438 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1439 uid = info.applicationInfo.uid;
1440 } catch (NameNotFoundException e) {
1441 // we don't know this package name, so just skip it for now
1442 continue;
1443 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001444 */
1445 final int uid = pkg.applicationInfo.uid;
1446 if (MORE_DEBUG) Slog.i(TAG, " found pkg " + packageName + " uid=" + uid);
Christopher Tatec28083a2010-12-14 16:16:44 -08001447
Christopher Tate181fafa2009-05-14 11:12:14 -07001448 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001449 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001450 // Find the existing entry with the same package name, and remove it.
1451 // We can't just remove(app) because the instances are different.
1452 for (ApplicationInfo entry: set) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001453 if (MORE_DEBUG) Slog.i(TAG, " checking against " + entry.packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001454 if (entry.packageName.equals(pkg)) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001455 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001456 set.remove(entry);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001457 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001458 break;
1459 }
1460 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001461 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001462 mBackupParticipants.delete(uid);
1463 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001464 } else {
1465 if (MORE_DEBUG) Slog.i(TAG, " ... not found in uid mapping");
Christopher Tate3799bc22009-05-06 16:13:56 -07001466 }
1467 }
1468 }
1469 }
1470
Christopher Tate181fafa2009-05-14 11:12:14 -07001471 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001472 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001473 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001474 int flags = PackageManager.GET_SIGNATURES;
1475 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1476 int N = packages.size();
1477 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001478 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001479 try {
1480 ApplicationInfo app = pkg.applicationInfo;
1481 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001482 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001483 packages.remove(a);
1484 }
1485 else {
1486 // we will need the shared library path, so look that up and store it here
1487 app = mPackageManager.getApplicationInfo(pkg.packageName,
1488 PackageManager.GET_SHARED_LIBRARY_FILES);
1489 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1490 }
1491 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001492 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001493 }
1494 }
Dan Egnorefe52642009-06-24 00:16:33 -07001495 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001496 }
Christopher Tateaa088442009-06-16 18:25:46 -07001497
Christopher Tate3799bc22009-05-06 16:13:56 -07001498 // Reset the given package's known backup participants. Unlike add/remove, the update
1499 // action cannot be passed a null package name.
Christopher Tate0bacfd22012-01-11 14:41:19 -08001500 void updatePackageParticipantsLocked(String[] packageNames) {
1501 if (packageNames == null) {
1502 Slog.e(TAG, "updatePackageParticipants called with null package list");
Christopher Tate3799bc22009-05-06 16:13:56 -07001503 return;
1504 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001505 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: #" + packageNames.length);
Christopher Tate3799bc22009-05-06 16:13:56 -07001506
Christopher Tate0bacfd22012-01-11 14:41:19 -08001507 if (packageNames.length > 0) {
1508 List<PackageInfo> allApps = allAgentPackages();
1509 for (String packageName : packageNames) {
1510 removePackageParticipantsLockedInner(packageName, allApps);
1511 addPackageParticipantsLockedInner(packageName, allApps);
1512 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001513 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001514 }
1515
Christopher Tate84725812010-02-04 15:52:40 -08001516 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001517 // backed up at least once
1518 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001519 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1520
1521 synchronized (mEverStoredApps) {
1522 if (!mEverStoredApps.add(packageName)) return;
1523
1524 RandomAccessFile out = null;
1525 try {
1526 out = new RandomAccessFile(mEverStored, "rws");
1527 out.seek(out.length());
1528 out.writeUTF(packageName);
1529 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001530 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001531 } finally {
1532 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001533 }
1534 }
1535 }
1536
Christopher Tatee97e8072009-07-15 16:45:50 -07001537 // Remove our awareness of having ever backed up the given package
1538 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001539 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1540 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001541
Dan Egnor852f8e42009-09-30 11:20:45 -07001542 synchronized (mEverStoredApps) {
1543 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1544 // we'll recognize on initialization time that the package no longer
1545 // exists and fix it up then.
1546 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1547 RandomAccessFile known = null;
1548 try {
1549 known = new RandomAccessFile(tempKnownFile, "rws");
1550 mEverStoredApps.remove(packageName);
1551 for (String s : mEverStoredApps) {
1552 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001553 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001554 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001555 known.close();
1556 known = null;
1557 if (!tempKnownFile.renameTo(mEverStored)) {
1558 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1559 }
1560 } catch (IOException e) {
1561 // Bad: we couldn't create the new copy. For safety's sake we
1562 // abandon the whole process and remove all what's-backed-up
1563 // state entirely, meaning we'll force a backup pass for every
1564 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001565 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001566 mEverStoredApps.clear();
1567 tempKnownFile.delete();
1568 mEverStored.delete();
1569 } finally {
1570 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001571 }
1572 }
1573 }
1574
Christopher Tateb49ceb32010-02-08 16:22:24 -08001575 // Persistently record the current and ancestral backup tokens as well
1576 // as the set of packages with data [supposedly] available in the
1577 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001578 void writeRestoreTokens() {
1579 try {
1580 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001581
1582 // First, the version number of this record, for futureproofing
1583 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1584
1585 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001586 af.writeLong(mAncestralToken);
1587 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001588
1589 // Now write the set of ancestral packages
1590 if (mAncestralPackages == null) {
1591 af.writeInt(-1);
1592 } else {
1593 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001594 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001595 for (String pkgName : mAncestralPackages) {
1596 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001597 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001598 }
1599 }
Christopher Tate84725812010-02-04 15:52:40 -08001600 af.close();
1601 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001602 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001603 }
1604 }
1605
Dan Egnor87a02bc2009-06-17 02:30:10 -07001606 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001607 private IBackupTransport getTransport(String transportName) {
1608 synchronized (mTransports) {
1609 IBackupTransport transport = mTransports.get(transportName);
1610 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001611 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001612 }
1613 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001614 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001615 }
1616
Christopher Tatedf01dea2009-06-09 20:45:02 -07001617 // fire off a backup agent, blocking until it attaches or times out
1618 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1619 IBackupAgent agent = null;
1620 synchronized(mAgentConnectLock) {
1621 mConnecting = true;
1622 mConnectedAgent = null;
1623 try {
1624 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001625 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001626
1627 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001628 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001629 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1630 while (mConnecting && mConnectedAgent == null
1631 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001632 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001633 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001634 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001635 // just bail
Christopher Tate6de74ff2012-01-17 15:20:32 -08001636 if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001637 return null;
1638 }
1639 }
1640
1641 // if we timed out with no connect, abort and move on
1642 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001643 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001644 return null;
1645 }
Christopher Tate6de74ff2012-01-17 15:20:32 -08001646 if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001647 agent = mConnectedAgent;
1648 }
1649 } catch (RemoteException e) {
1650 // can't happen
1651 }
1652 }
1653 return agent;
1654 }
1655
Christopher Tatec7b31e32009-06-10 15:49:30 -07001656 // clear an application's data, blocking until the operation completes or times out
1657 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001658 // Don't wipe packages marked allowClearUserData=false
1659 try {
1660 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1661 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001662 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001663 + packageName);
1664 return;
1665 }
1666 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001667 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001668 return;
1669 }
1670
Christopher Tatec7b31e32009-06-10 15:49:30 -07001671 ClearDataObserver observer = new ClearDataObserver();
1672
1673 synchronized(mClearDataLock) {
1674 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001675 try {
1676 mActivityManager.clearApplicationUserData(packageName, observer);
1677 } catch (RemoteException e) {
1678 // can't happen because the activity manager is in this process
1679 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001680
1681 // only wait 10 seconds for the clear data to happen
1682 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1683 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1684 try {
1685 mClearDataLock.wait(5000);
1686 } catch (InterruptedException e) {
1687 // won't happen, but still.
1688 mClearingData = false;
1689 }
1690 }
1691 }
1692 }
1693
1694 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001695 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001696 synchronized(mClearDataLock) {
1697 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001698 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001699 }
1700 }
1701 }
1702
Christopher Tate1bb69062010-02-19 17:02:12 -08001703 // Get the restore-set token for the best-available restore set for this package:
1704 // the active set if possible, else the ancestral one. Returns zero if none available.
1705 long getAvailableRestoreToken(String packageName) {
1706 long token = mAncestralToken;
1707 synchronized (mQueueLock) {
1708 if (mEverStoredApps.contains(packageName)) {
1709 token = mCurrentToken;
1710 }
1711 }
1712 return token;
1713 }
1714
Christopher Tate44a27902010-01-27 17:15:49 -08001715 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001716 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1717
1718 interface BackupRestoreTask {
1719 // Execute one tick of whatever state machine the task implements
1720 void execute();
1721
1722 // An operation that wanted a callback has completed
1723 void operationComplete();
1724
1725 // An operation that wanted a callback has timed out
1726 void handleTimeout();
1727 }
1728
1729 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1730 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1731 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001732 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001733 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1734
1735 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1736 mBackupHandler.sendMessageDelayed(msg, interval);
1737 }
1738 }
1739
1740 // synchronous waiter case
1741 boolean waitUntilOperationComplete(int token) {
1742 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1743 + Integer.toHexString(token));
1744 int finalState = OP_PENDING;
1745 Operation op = null;
1746 synchronized (mCurrentOpLock) {
1747 while (true) {
1748 op = mCurrentOperations.get(token);
1749 if (op == null) {
1750 // mysterious disappearance: treat as success with no callback
1751 break;
1752 } else {
1753 if (op.state == OP_PENDING) {
1754 try {
1755 mCurrentOpLock.wait();
1756 } catch (InterruptedException e) {}
1757 // When the wait is notified we loop around and recheck the current state
1758 } else {
1759 // No longer pending; we're done
1760 finalState = op.state;
1761 break;
1762 }
Christopher Tate44a27902010-01-27 17:15:49 -08001763 }
Christopher Tate44a27902010-01-27 17:15:49 -08001764 }
1765 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001766
Christopher Tate44a27902010-01-27 17:15:49 -08001767 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001768 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001769 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001770 return finalState == OP_ACKNOWLEDGED;
1771 }
1772
Christopher Tate8e294d42011-08-31 20:37:12 -07001773 void handleTimeout(int token, Object obj) {
1774 // Notify any synchronous waiters
1775 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001776 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001777 op = mCurrentOperations.get(token);
1778 if (MORE_DEBUG) {
1779 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1780 + " but no op found");
1781 }
1782 int state = (op != null) ? op.state : OP_TIMEOUT;
1783 if (state == OP_PENDING) {
1784 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1785 op.state = OP_TIMEOUT;
1786 mCurrentOperations.put(token, op);
1787 }
1788 mCurrentOpLock.notifyAll();
1789 }
1790
1791 // If there's a TimeoutHandler for this event, call it
1792 if (op != null && op.callback != null) {
1793 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001794 }
Christopher Tate44a27902010-01-27 17:15:49 -08001795 }
1796
Christopher Tate043dadc2009-06-02 16:11:00 -07001797 // ----- Back up a set of applications via a worker thread -----
1798
Christopher Tate8e294d42011-08-31 20:37:12 -07001799 enum BackupState {
1800 INITIAL,
1801 RUNNING_QUEUE,
1802 FINAL
1803 }
1804
1805 class PerformBackupTask implements BackupRestoreTask {
1806 private static final String TAG = "PerformBackupTask";
1807
Christopher Tateaa088442009-06-16 18:25:46 -07001808 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001809 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001810 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001811 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001812 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001813 BackupState mCurrentState;
1814
1815 // carried information about the current in-flight operation
1816 PackageInfo mCurrentPackage;
1817 File mSavedStateName;
1818 File mBackupDataName;
1819 File mNewStateName;
1820 ParcelFileDescriptor mSavedState;
1821 ParcelFileDescriptor mBackupData;
1822 ParcelFileDescriptor mNewState;
1823 int mStatus;
1824 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001825
Christopher Tate44a27902010-01-27 17:15:49 -08001826 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001827 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001828 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001829 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001830 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001831
1832 try {
1833 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1834 } catch (RemoteException e) {
1835 // can't happen; the transport is local
1836 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001837
1838 mCurrentState = BackupState.INITIAL;
1839 mFinished = false;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001840
1841 addBackupTrace("STATE => INITIAL");
Christopher Tate043dadc2009-06-02 16:11:00 -07001842 }
1843
Christopher Tate8e294d42011-08-31 20:37:12 -07001844 // Main entry point: perform one chunk of work, updating the state as appropriate
1845 // and reposting the next chunk to the primary backup handler thread.
1846 @Override
1847 public void execute() {
1848 switch (mCurrentState) {
1849 case INITIAL:
1850 beginBackup();
1851 break;
1852
1853 case RUNNING_QUEUE:
1854 invokeNextAgent();
1855 break;
1856
1857 case FINAL:
1858 if (!mFinished) finalizeBackup();
1859 else {
1860 Slog.e(TAG, "Duplicate finish");
1861 }
Christopher Tate2982d062011-09-06 20:35:24 -07001862 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001863 break;
1864 }
1865 }
1866
1867 // We're starting a backup pass. Initialize the transport and send
1868 // the PM metadata blob if we haven't already.
1869 void beginBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001870 if (DEBUG_BACKUP_TRACE) {
1871 clearBackupTrace();
1872 StringBuilder b = new StringBuilder(256);
1873 b.append("beginBackup: [");
1874 for (BackupRequest req : mOriginalQueue) {
1875 b.append(' ');
1876 b.append(req.packageName);
1877 }
1878 b.append(" ]");
1879 addBackupTrace(b.toString());
1880 }
1881
Christopher Tate8e294d42011-08-31 20:37:12 -07001882 mStatus = BackupConstants.TRANSPORT_OK;
1883
1884 // Sanity check: if the queue is empty we have no work to do.
1885 if (mOriginalQueue.isEmpty()) {
1886 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001887 addBackupTrace("queue empty at begin");
1888 executeNextState(BackupState.FINAL);
Christopher Tate8e294d42011-08-31 20:37:12 -07001889 return;
1890 }
1891
1892 // We need to retain the original queue contents in case of transport
1893 // failure, but we want a working copy that we can manipulate along
1894 // the way.
1895 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1896
Joe Onorato8a9b2202010-02-26 18:56:32 -08001897 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001898
Christopher Tate8e294d42011-08-31 20:37:12 -07001899 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001900 try {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001901 final String transportName = mTransport.transportDirName();
1902 EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
Dan Egnor01445162009-09-21 17:04:05 -07001903
Dan Egnor852f8e42009-09-30 11:20:45 -07001904 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001905 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001906 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001907 addBackupTrace("initializing transport " + transportName);
Dan Egnor852f8e42009-09-30 11:20:45 -07001908 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001909 mStatus = mTransport.initializeDevice();
Christopher Tate6de74ff2012-01-17 15:20:32 -08001910
1911 addBackupTrace("transport.initializeDevice() == " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001912 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001913 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001914 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001915 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001916 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001917 }
Dan Egnor01445162009-09-21 17:04:05 -07001918 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001919
1920 // The package manager doesn't have a proper <application> etc, but since
1921 // it's running here in the system process we can just set up its agent
1922 // directly and use a synthetic BackupRequest. We always run this pass
1923 // because it's cheap and this way we guarantee that we don't get out of
1924 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001925 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001926 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1927 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001928 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001929 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001930 addBackupTrace("PMBA invoke: " + mStatus);
Dan Egnor01445162009-09-21 17:04:05 -07001931 }
Christopher Tate90967f42009-09-20 15:28:33 -07001932
Christopher Tate8e294d42011-08-31 20:37:12 -07001933 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1934 // The backend reports that our dataset has been wiped. Note this in
1935 // the event log; the no-success code below will reset the backup
1936 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001937 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001938 }
1939 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001940 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001941 addBackupTrace("Exception in backup thread: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001942 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001943 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001944 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1945 // metadata and its completion/timeout callback will continue the state
1946 // machine chain. If it failed that won't happen; we handle that now.
Christopher Tate6de74ff2012-01-17 15:20:32 -08001947 addBackupTrace("exiting prelim: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001948 if (mStatus != BackupConstants.TRANSPORT_OK) {
1949 // if things went wrong at this point, we need to
1950 // restage everything and try again later.
1951 resetBackupState(mStateDir); // Just to make sure.
1952 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001953 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001954 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001955 }
1956
Christopher Tate8e294d42011-08-31 20:37:12 -07001957 // Transport has been initialized and the PM metadata submitted successfully
1958 // if that was warranted. Now we process the single next thing in the queue.
1959 void invokeNextAgent() {
1960 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001961 addBackupTrace("invoke q=" + mQueue.size());
Christopher Tate043dadc2009-06-02 16:11:00 -07001962
Christopher Tate8e294d42011-08-31 20:37:12 -07001963 // Sanity check that we have work to do. If not, skip to the end where
1964 // we reestablish the wakelock invariants etc.
1965 if (mQueue.isEmpty()) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001966 if (DEBUG) Slog.i(TAG, "queue now empty");
Christopher Tate8e294d42011-08-31 20:37:12 -07001967 executeNextState(BackupState.FINAL);
1968 return;
1969 }
1970
1971 // pop the entry we're going to process on this step
1972 BackupRequest request = mQueue.get(0);
1973 mQueue.remove(0);
1974
1975 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001976 addBackupTrace("launch agent for " + request.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07001977
1978 // Verify that the requested app exists; it might be something that
1979 // requested a backup but was then uninstalled. The request was
1980 // journalled and rather than tamper with the journal it's safer
1981 // to sanity-check here. This also gives us the classname of the
1982 // package's backup agent.
1983 try {
1984 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1985 PackageManager.GET_SIGNATURES);
Christopher Tatec28083a2010-12-14 16:16:44 -08001986
Christopher Tate043dadc2009-06-02 16:11:00 -07001987 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001988 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001989 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1990 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001991 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001992 addBackupTrace("agent bound; a? = " + (agent != null));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001993 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001994 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
1995 // at this point we'll either get a completion callback from the
1996 // agent, or a timeout message on the main handler. either way, we're
1997 // done here as long as we're successful so far.
1998 } else {
1999 // Timeout waiting for the agent
2000 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07002001 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002002 } catch (SecurityException ex) {
2003 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002004 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07002005 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002006 addBackupTrace("agent SE");
Christopher Tate8e294d42011-08-31 20:37:12 -07002007 }
2008 } catch (NameNotFoundException e) {
2009 Slog.d(TAG, "Package does not exist; skipping");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002010 addBackupTrace("no such package");
2011 mStatus = BackupConstants.AGENT_UNKNOWN;
Christopher Tate8e294d42011-08-31 20:37:12 -07002012 } finally {
2013 mWakelock.setWorkSource(null);
2014
2015 // If there was an agent error, no timeout/completion handling will occur.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002016 // That means we need to direct to the next state ourselves.
Christopher Tate8e294d42011-08-31 20:37:12 -07002017 if (mStatus != BackupConstants.TRANSPORT_OK) {
2018 BackupState nextState = BackupState.RUNNING_QUEUE;
2019
2020 // An agent-level failure means we reenqueue this one agent for
2021 // a later retry, but otherwise proceed normally.
2022 if (mStatus == BackupConstants.AGENT_ERROR) {
2023 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2024 + " - restaging");
2025 dataChangedImpl(request.packageName);
2026 mStatus = BackupConstants.TRANSPORT_OK;
2027 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002028 } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2029 // Failed lookup of the app, so we couldn't bring up an agent, but
2030 // we're otherwise fine. Just drop it and go on to the next as usual.
2031 mStatus = BackupConstants.TRANSPORT_OK;
2032 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002033 // Transport-level failure means we reenqueue everything
2034 revertAndEndBackup();
2035 nextState = BackupState.FINAL;
2036 }
2037
2038 executeNextState(nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002039 } else {
2040 addBackupTrace("expecting completion/timeout callback");
Christopher Tate043dadc2009-06-02 16:11:00 -07002041 }
2042 }
2043 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002044
Christopher Tate8e294d42011-08-31 20:37:12 -07002045 void finalizeBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002046 addBackupTrace("finishing");
2047
Christopher Tate8e294d42011-08-31 20:37:12 -07002048 // Either backup was successful, in which case we of course do not need
2049 // this pass's journal any more; or it failed, in which case we just
2050 // re-enqueued all of these packages in the current active journal.
2051 // Either way, we no longer need this pass's journal.
2052 if (mJournal != null && !mJournal.delete()) {
2053 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2054 }
2055
2056 // If everything actually went through and this is the first time we've
2057 // done a backup, we can now record what the current backup dataset token
2058 // is.
2059 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002060 addBackupTrace("success; recording token");
Christopher Tate8e294d42011-08-31 20:37:12 -07002061 try {
2062 mCurrentToken = mTransport.getCurrentRestoreSet();
2063 } catch (RemoteException e) {} // can't happen
2064 writeRestoreTokens();
2065 }
2066
Christopher Tate336a6492011-10-05 16:05:43 -07002067 // Set up the next backup pass - at this point we can set mBackupRunning
2068 // to false to allow another pass to fire, because we're done with the
2069 // state machine sequence and the wakelock is refcounted.
2070 synchronized (mQueueLock) {
2071 mBackupRunning = false;
2072 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tatee659fb92011-10-10 16:34:50 -07002073 // Make sure we back up everything and perform the one-time init
2074 clearMetadata();
2075 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002076 addBackupTrace("init required; rerunning");
Christopher Tate336a6492011-10-05 16:05:43 -07002077 backupNow();
2078 }
Christopher Tate8e294d42011-08-31 20:37:12 -07002079 }
2080
2081 // Only once we're entirely finished do we release the wakelock
Christopher Tate6de74ff2012-01-17 15:20:32 -08002082 clearBackupTrace();
Christopher Tate8e294d42011-08-31 20:37:12 -07002083 Slog.i(TAG, "Backup pass finished.");
2084 mWakelock.release();
2085 }
2086
Christopher Tatee659fb92011-10-10 16:34:50 -07002087 // Remove the PM metadata state. This will generate an init on the next pass.
2088 void clearMetadata() {
2089 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2090 if (pmState.exists()) pmState.delete();
2091 }
2092
Christopher Tate8e294d42011-08-31 20:37:12 -07002093 // Invoke an agent's doBackup() and start a timeout message spinning on the main
2094 // handler in case it doesn't get back to us.
2095 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07002096 IBackupTransport transport) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002097 if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2098 addBackupTrace("invoking " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002099
Christopher Tate8e294d42011-08-31 20:37:12 -07002100 mSavedStateName = new File(mStateDir, packageName);
2101 mBackupDataName = new File(mDataDir, packageName + ".data");
2102 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002103
Christopher Tate8e294d42011-08-31 20:37:12 -07002104 mSavedState = null;
2105 mBackupData = null;
2106 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002107
Christopher Tate4a627c72011-04-01 14:43:32 -07002108 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002109 try {
2110 // Look up the package info & signatures. This is first so that if it
2111 // throws an exception, there's no file setup yet that would need to
2112 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07002113 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002114 // The metadata 'package' is synthetic; construct one and make
2115 // sure our global state is pointed at it
2116 mCurrentPackage = new PackageInfo();
2117 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002118 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002119
Christopher Tatec7b31e32009-06-10 15:49:30 -07002120 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002121 // the saved-state "file". This is by definition an incremental,
2122 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002123 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002124 ParcelFileDescriptor.MODE_READ_ONLY |
2125 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002126
Christopher Tate8e294d42011-08-31 20:37:12 -07002127 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002128 ParcelFileDescriptor.MODE_READ_WRITE |
2129 ParcelFileDescriptor.MODE_CREATE |
2130 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002131
Christopher Tate8e294d42011-08-31 20:37:12 -07002132 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002133 ParcelFileDescriptor.MODE_READ_WRITE |
2134 ParcelFileDescriptor.MODE_CREATE |
2135 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002136
Christopher Tate44a27902010-01-27 17:15:49 -08002137 // Initiate the target's backup pass
Christopher Tate6de74ff2012-01-17 15:20:32 -08002138 addBackupTrace("setting timeout");
Christopher Tate8e294d42011-08-31 20:37:12 -07002139 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002140 addBackupTrace("calling agent doBackup()");
Christopher Tate8e294d42011-08-31 20:37:12 -07002141 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002142 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002143 Slog.e(TAG, "Error invoking for backup on " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002144 addBackupTrace("exception: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07002145 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2146 e.toString());
2147 agentErrorCleanup();
2148 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002149 }
2150
Christopher Tate8e294d42011-08-31 20:37:12 -07002151 // At this point the agent is off and running. The next thing to happen will
2152 // either be a callback from the agent, at which point we'll process its data
2153 // for transport, or a timeout. Either way the next phase will happen in
2154 // response to the TimeoutHandler interface callbacks.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002155 addBackupTrace("invoke success");
Christopher Tate8e294d42011-08-31 20:37:12 -07002156 return BackupConstants.TRANSPORT_OK;
2157 }
2158
2159 @Override
2160 public void operationComplete() {
2161 // Okay, the agent successfully reported back to us. Spin the data off to the
2162 // transport and proceed with the next stage.
2163 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2164 + mCurrentPackage.packageName);
2165 mBackupHandler.removeMessages(MSG_TIMEOUT);
2166 clearAgentState();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002167 addBackupTrace("operation complete");
Christopher Tate8e294d42011-08-31 20:37:12 -07002168
2169 ParcelFileDescriptor backupData = null;
2170 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002171 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002172 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002173 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002174 if (mStatus == BackupConstants.TRANSPORT_OK) {
2175 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002176 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002177 addBackupTrace("sending data to transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002178 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002179 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002180
Dan Egnor83861e72009-09-17 16:17:55 -07002181 // TODO - We call finishBackup() for each application backed up, because
2182 // we need to know now whether it succeeded or failed. Instead, we should
2183 // hold off on finishBackup() until the end, which implies holding off on
2184 // renaming *all* the output state files (see below) until that happens.
2185
Christopher Tate6de74ff2012-01-17 15:20:32 -08002186 addBackupTrace("data delivered: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07002187 if (mStatus == BackupConstants.TRANSPORT_OK) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002188 addBackupTrace("finishing op on transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002189 mStatus = mTransport.finishBackup();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002190 addBackupTrace("finished: " + mStatus);
Dan Egnor83861e72009-09-17 16:17:55 -07002191 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002192 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002193 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002194 addBackupTrace("no data to send");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002195 }
2196
2197 // After successful transport, delete the now-stale data
2198 // and juggle the files so that next time we supply the agent
2199 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002200 if (mStatus == BackupConstants.TRANSPORT_OK) {
2201 mBackupDataName.delete();
2202 mNewStateName.renameTo(mSavedStateName);
2203 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2204 mCurrentPackage.packageName, size);
2205 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002206 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002207 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2208 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002209 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002210 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002211 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2212 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2213 mCurrentPackage.packageName);
2214 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002215 } finally {
2216 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002217 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002218
Christopher Tate8e294d42011-08-31 20:37:12 -07002219 // If we encountered an error here it's a transport-level failure. That
2220 // means we need to halt everything and reschedule everything for next time.
2221 final BackupState nextState;
2222 if (mStatus != BackupConstants.TRANSPORT_OK) {
2223 revertAndEndBackup();
2224 nextState = BackupState.FINAL;
2225 } else {
2226 // Success! Proceed with the next app if any, otherwise we're done.
2227 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2228 }
2229
2230 executeNextState(nextState);
2231 }
2232
2233 @Override
2234 public void handleTimeout() {
2235 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2236 // it for the next time we run a backup pass.
2237 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2238 // fail repeatedly (i.e. have proved themselves to be buggy).
2239 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2240 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2241 "timeout");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002242 addBackupTrace("timeout of " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002243 agentErrorCleanup();
2244 dataChangedImpl(mCurrentPackage.packageName);
2245 }
2246
2247 void revertAndEndBackup() {
2248 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002249 addBackupTrace("transport error; reverting");
Christopher Tate8e294d42011-08-31 20:37:12 -07002250 for (BackupRequest request : mOriginalQueue) {
2251 dataChangedImpl(request.packageName);
2252 }
2253 // We also want to reset the backup schedule based on whatever
2254 // the transport suggests by way of retry/backoff time.
2255 restartBackupAlarm();
2256 }
2257
2258 void agentErrorCleanup() {
2259 mBackupDataName.delete();
2260 mNewStateName.delete();
2261 clearAgentState();
2262
2263 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2264 }
2265
2266 // Cleanup common to both success and failure cases
2267 void clearAgentState() {
2268 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2269 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2270 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2271 mSavedState = mBackupData = mNewState = null;
2272 synchronized (mCurrentOpLock) {
2273 mCurrentOperations.clear();
2274 }
2275
2276 // If this was a pseudopackage there's no associated Activity Manager state
2277 if (mCurrentPackage.applicationInfo != null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002278 addBackupTrace("unbinding " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002279 try { // unbind even on timeout, just in case
2280 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2281 } catch (RemoteException e) {}
2282 }
2283 }
2284
2285 void restartBackupAlarm() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002286 addBackupTrace("setting backup trigger");
Christopher Tate8e294d42011-08-31 20:37:12 -07002287 synchronized (mQueueLock) {
2288 try {
2289 startBackupAlarmsLocked(mTransport.requestBackupTime());
2290 } catch (RemoteException e) { /* cannot happen */ }
2291 }
2292 }
2293
2294 void executeNextState(BackupState nextState) {
2295 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2296 + this + " nextState=" + nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002297 addBackupTrace("executeNextState => " + nextState);
Christopher Tate8e294d42011-08-31 20:37:12 -07002298 mCurrentState = nextState;
2299 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2300 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002301 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002302 }
2303
Christopher Tatedf01dea2009-06-09 20:45:02 -07002304
Christopher Tate4a627c72011-04-01 14:43:32 -07002305 // ----- Full backup to a file/socket -----
2306
2307 class PerformFullBackupTask implements Runnable {
2308 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002309 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002310 IFullBackupRestoreObserver mObserver;
2311 boolean mIncludeApks;
2312 boolean mIncludeShared;
2313 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002314 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002315 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002316 String mCurrentPassword;
2317 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002318 AtomicBoolean mLatchObject;
2319 File mFilesDir;
2320 File mManifestFile;
2321
Christopher Tate7926a692011-07-11 11:31:57 -07002322 class FullBackupRunner implements Runnable {
2323 PackageInfo mPackage;
2324 IBackupAgent mAgent;
2325 ParcelFileDescriptor mPipe;
2326 int mToken;
2327 boolean mSendApk;
2328
2329 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
2330 int token, boolean sendApk) throws IOException {
2331 mPackage = pack;
2332 mAgent = agent;
2333 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2334 mToken = token;
2335 mSendApk = sendApk;
2336 }
2337
2338 @Override
2339 public void run() {
2340 try {
2341 BackupDataOutput output = new BackupDataOutput(
2342 mPipe.getFileDescriptor());
2343
Christopher Tatec58efa62011-08-01 19:20:14 -07002344 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
Christopher Tate7926a692011-07-11 11:31:57 -07002345 writeAppManifest(mPackage, mManifestFile, mSendApk);
2346 FullBackup.backupToTar(mPackage.packageName, null, null,
2347 mFilesDir.getAbsolutePath(),
2348 mManifestFile.getAbsolutePath(),
2349 output);
2350
2351 if (mSendApk) {
2352 writeApkToBackup(mPackage, output);
2353 }
2354
Christopher Tatec58efa62011-08-01 19:20:14 -07002355 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002356 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002357 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2358 } catch (IOException e) {
2359 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2360 } catch (RemoteException e) {
2361 Slog.e(TAG, "Remote agent vanished during full backup of "
2362 + mPackage.packageName);
2363 } finally {
2364 try {
2365 mPipe.close();
2366 } catch (IOException e) {}
2367 }
2368 }
2369 }
2370
Christopher Tate4a627c72011-04-01 14:43:32 -07002371 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002372 boolean includeApks, boolean includeShared, String curPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -07002373 String encryptPassword, boolean doAllApps, boolean doSystem, String[] packages,
Christopher Tate728a1c42011-07-28 18:03:03 -07002374 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002375 mOutputFile = fd;
2376 mObserver = observer;
2377 mIncludeApks = includeApks;
2378 mIncludeShared = includeShared;
2379 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002380 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002381 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002382 mCurrentPassword = curPassword;
2383 // when backing up, if there is a current backup password, we require that
2384 // the user use a nonempty encryption password as well. if one is supplied
2385 // in the UI we use that, but if the UI was left empty we fall back to the
2386 // current backup password (which was supplied by the user as well).
2387 if (encryptPassword == null || "".equals(encryptPassword)) {
2388 mEncryptPassword = curPassword;
2389 } else {
2390 mEncryptPassword = encryptPassword;
2391 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002392 mLatchObject = latch;
2393
2394 mFilesDir = new File("/data/system");
2395 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2396 }
2397
2398 @Override
2399 public void run() {
Christopher Tate240c7d22011-10-03 18:13:44 -07002400 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
Christopher Tate4a627c72011-04-01 14:43:32 -07002401
Christopher Tateb0628bf2011-06-02 15:08:13 -07002402 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002403 sendStartBackup();
2404
2405 // doAllApps supersedes the package set if any
2406 if (mAllApps) {
2407 packagesToBackup = mPackageManager.getInstalledPackages(
2408 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002409 // Exclude system apps if we've been asked to do so
2410 if (mIncludeSystem == false) {
2411 for (int i = 0; i < packagesToBackup.size(); ) {
2412 PackageInfo pkg = packagesToBackup.get(i);
2413 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2414 packagesToBackup.remove(i);
2415 } else {
2416 i++;
2417 }
2418 }
2419 }
2420 }
2421
2422 // Now process the command line argument packages, if any. Note that explicitly-
2423 // named system-partition packages will be included even if includeSystem was
2424 // set to false.
2425 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002426 for (String pkgName : mPackages) {
2427 try {
2428 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2429 PackageManager.GET_SIGNATURES));
2430 } catch (NameNotFoundException e) {
2431 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2432 }
2433 }
2434 }
2435
Christopher Tatea858cb02011-06-03 12:27:51 -07002436 // Cull any packages that have indicated that backups are not permitted.
2437 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002438 PackageInfo pkg = packagesToBackup.get(i);
2439 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002440 packagesToBackup.remove(i);
2441 } else {
2442 i++;
2443 }
2444 }
2445
Christopher Tate7926a692011-07-11 11:31:57 -07002446 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002447 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002448
Christopher Tate4a627c72011-04-01 14:43:32 -07002449 PackageInfo pkg = null;
2450 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002451 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002452 boolean compressing = COMPRESS_FULL_BACKUPS;
2453 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002454
Christopher Tateeef4ae42011-08-05 13:15:53 -07002455 // Verify that the given password matches the currently-active
2456 // backup password, if any
2457 if (hasBackupPassword()) {
2458 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2459 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2460 return;
2461 }
2462 }
2463
Christopher Tate7bdb0962011-07-13 19:30:21 -07002464 // Write the global file header. All strings are UTF-8 encoded; lines end
2465 // with a '\n' byte. Actual backup data begins immediately following the
2466 // final '\n'.
2467 //
2468 // line 1: "ANDROID BACKUP"
2469 // line 2: backup file format version, currently "1"
2470 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002471 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2472 //
2473 // When line 4 is not "none", then additional header data follows:
2474 //
2475 // line 5: user password salt [hex]
2476 // line 6: master key checksum salt [hex]
2477 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2478 // line 8: IV of the user key [hex]
2479 // line 9: master key blob [hex]
2480 // IV of the master key, master key itself, master key checksum hash
2481 //
2482 // The master key checksum is the master key plus its checksum salt, run through
2483 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2484 // correct password for decrypting the archive: the master key decrypted from
2485 // the archive using the user-supplied password is also run through PBKDF2 in
2486 // this way, and if the result does not match the checksum as stored in the
2487 // archive, then we know that the user-supplied password does not match the
2488 // archive's.
2489 StringBuilder headerbuf = new StringBuilder(1024);
2490
Christopher Tate7bdb0962011-07-13 19:30:21 -07002491 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002492 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2493 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002494
2495 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002496 // Set up the encryption stage if appropriate, and emit the correct header
2497 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002498 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2499 } else {
2500 headerbuf.append("none\n");
2501 }
2502
Christopher Tate7bdb0962011-07-13 19:30:21 -07002503 byte[] header = headerbuf.toString().getBytes("UTF-8");
2504 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002505
2506 // Set up the compression stage feeding into the encryption stage (if any)
2507 if (compressing) {
2508 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2509 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2510 }
2511
2512 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002513 } catch (Exception e) {
2514 // Should never happen!
2515 Slog.e(TAG, "Unable to emit archive header", e);
2516 return;
2517 }
2518
Christopher Tateb0628bf2011-06-02 15:08:13 -07002519 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002520 int N = packagesToBackup.size();
2521 for (int i = 0; i < N; i++) {
2522 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002523 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002524 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002525
Christopher Tate6853fcf2011-08-10 17:52:21 -07002526 // Shared storage if requested
Christopher Tateb0628bf2011-06-02 15:08:13 -07002527 if (mIncludeShared) {
2528 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07002529 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07002530
2531 // Done!
2532 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002533 } catch (RemoteException e) {
2534 Slog.e(TAG, "App died during full backup");
2535 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002536 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002537 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002538 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002539 mOutputFile.close();
2540 } catch (IOException e) {
2541 /* nothing we can do about this */
2542 }
2543 synchronized (mCurrentOpLock) {
2544 mCurrentOperations.clear();
2545 }
2546 synchronized (mLatchObject) {
2547 mLatchObject.set(true);
2548 mLatchObject.notifyAll();
2549 }
2550 sendEndBackup();
Christopher Tate4a627c72011-04-01 14:43:32 -07002551 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002552 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002553 }
2554 }
2555
Christopher Tate2efd2db2011-07-19 16:32:49 -07002556 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2557 OutputStream ofstream) throws Exception {
2558 // User key will be used to encrypt the master key.
2559 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002560 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002561 PBKDF2_HASH_ROUNDS);
2562
2563 // the master key is random for each backup
2564 byte[] masterPw = new byte[256 / 8];
2565 mRng.nextBytes(masterPw);
2566 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2567
2568 // primary encryption of the datastream with the random key
2569 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2570 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2571 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2572 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2573
2574 // line 4: name of encryption algorithm
2575 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2576 headerbuf.append('\n');
2577 // line 5: user password salt [hex]
2578 headerbuf.append(byteArrayToHex(newUserSalt));
2579 headerbuf.append('\n');
2580 // line 6: master key checksum salt [hex]
2581 headerbuf.append(byteArrayToHex(checksumSalt));
2582 headerbuf.append('\n');
2583 // line 7: number of PBKDF2 rounds used [decimal]
2584 headerbuf.append(PBKDF2_HASH_ROUNDS);
2585 headerbuf.append('\n');
2586
2587 // line 8: IV of the user key [hex]
2588 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2589 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2590
2591 byte[] IV = mkC.getIV();
2592 headerbuf.append(byteArrayToHex(IV));
2593 headerbuf.append('\n');
2594
2595 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2596 // [byte] IV length = Niv
2597 // [array of Niv bytes] IV itself
2598 // [byte] master key length = Nmk
2599 // [array of Nmk bytes] master key itself
2600 // [byte] MK checksum hash length = Nck
2601 // [array of Nck bytes] master key checksum hash
2602 //
2603 // The checksum is the (master key + checksum salt), run through the
2604 // stated number of PBKDF2 rounds
2605 IV = c.getIV();
2606 byte[] mk = masterKeySpec.getEncoded();
2607 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2608 checksumSalt, PBKDF2_HASH_ROUNDS);
2609
2610 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2611 + checksum.length + 3);
2612 DataOutputStream mkOut = new DataOutputStream(blob);
2613 mkOut.writeByte(IV.length);
2614 mkOut.write(IV);
2615 mkOut.writeByte(mk.length);
2616 mkOut.write(mk);
2617 mkOut.writeByte(checksum.length);
2618 mkOut.write(checksum);
2619 mkOut.flush();
2620 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2621 headerbuf.append(byteArrayToHex(encryptedMk));
2622 headerbuf.append('\n');
2623
2624 return finalOutput;
2625 }
2626
2627 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002628 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002629 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2630
2631 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2632 IApplicationThread.BACKUP_MODE_FULL);
2633 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002634 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002635 try {
Christopher Tate7926a692011-07-11 11:31:57 -07002636 pipes = ParcelFileDescriptor.createPipe();
2637
Christopher Tateb0628bf2011-06-02 15:08:13 -07002638 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07002639 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07002640 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2641 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2642 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2643
2644 sendOnBackupPackage(pkg.packageName);
2645
Christopher Tate7926a692011-07-11 11:31:57 -07002646 final int token = generateToken();
2647 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
2648 token, sendApk);
2649 pipes[1].close(); // the runner has dup'd it
2650 pipes[1] = null;
2651 Thread t = new Thread(runner);
2652 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002653
Christopher Tate7926a692011-07-11 11:31:57 -07002654 // Now pull data from the app and stuff it into the compressor
2655 try {
2656 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2657 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002658
Christopher Tate7926a692011-07-11 11:31:57 -07002659 byte[] buffer = new byte[16 * 1024];
2660 int chunkTotal;
2661 while ((chunkTotal = in.readInt()) > 0) {
2662 while (chunkTotal > 0) {
2663 int toRead = (chunkTotal > buffer.length)
2664 ? buffer.length : chunkTotal;
2665 int nRead = in.read(buffer, 0, toRead);
2666 out.write(buffer, 0, nRead);
2667 chunkTotal -= nRead;
2668 }
2669 }
2670 } catch (IOException e) {
2671 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002672 }
2673
Christopher Tateb0628bf2011-06-02 15:08:13 -07002674 if (!waitUntilOperationComplete(token)) {
2675 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2676 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002677 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002678 }
Christopher Tate7926a692011-07-11 11:31:57 -07002679
Christopher Tateb0628bf2011-06-02 15:08:13 -07002680 } catch (IOException e) {
2681 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002682 } finally {
2683 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002684 // flush after every package
2685 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002686 if (pipes != null) {
2687 if (pipes[0] != null) pipes[0].close();
2688 if (pipes[1] != null) pipes[1].close();
2689 }
Christopher Tate7926a692011-07-11 11:31:57 -07002690 } catch (IOException e) {
2691 Slog.w(TAG, "Error bringing down backup stack");
2692 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002693 }
2694 } else {
2695 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2696 }
2697 tearDown(pkg);
2698 }
2699
Christopher Tate79ec80d2011-06-24 14:58:49 -07002700 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2701 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2702 final String appSourceDir = pkg.applicationInfo.sourceDir;
2703 final String apkDir = new File(appSourceDir).getParent();
2704 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2705 apkDir, appSourceDir, output);
2706
2707 // Save associated .obb content if it exists and we did save the apk
2708 // check for .obb and save those too
2709 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2710 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002711 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002712 File[] obbFiles = obbDir.listFiles();
2713 if (obbFiles != null) {
2714 final String obbDirName = obbDir.getAbsolutePath();
2715 for (File obb : obbFiles) {
2716 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2717 obbDirName, obb.getAbsolutePath(), output);
2718 }
2719 }
2720 }
2721 }
2722
Christopher Tateb0628bf2011-06-02 15:08:13 -07002723 private void backupSharedStorage() throws RemoteException {
2724 PackageInfo pkg = null;
2725 try {
2726 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
2727 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2728 IApplicationThread.BACKUP_MODE_FULL);
2729 if (agent != null) {
2730 sendOnBackupPackage("Shared storage");
2731
2732 final int token = generateToken();
Christopher Tate8e294d42011-08-31 20:37:12 -07002733 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL, null);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002734 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002735 if (!waitUntilOperationComplete(token)) {
2736 Slog.e(TAG, "Full backup failed on shared storage");
2737 } else {
2738 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
2739 }
2740 } else {
2741 Slog.e(TAG, "Could not bind to shared storage backup agent");
2742 }
2743 } catch (NameNotFoundException e) {
2744 Slog.e(TAG, "Shared storage backup package not found");
2745 } finally {
2746 tearDown(pkg);
2747 }
2748 }
2749
Christopher Tate6853fcf2011-08-10 17:52:21 -07002750 private void finalizeBackup(OutputStream out) {
2751 try {
2752 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2753 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2754 out.write(eof);
2755 } catch (IOException e) {
2756 Slog.w(TAG, "Error attempting to finalize backup stream");
2757 }
2758 }
2759
Christopher Tate4a627c72011-04-01 14:43:32 -07002760 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2761 throws IOException {
2762 // Manifest format. All data are strings ending in LF:
2763 // BACKUP_MANIFEST_VERSION, currently 1
2764 //
2765 // Version 1:
2766 // package name
2767 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002768 // platform versionCode
2769 // getInstallerPackageName() for this package (maybe empty)
2770 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002771 // number of signatures == N
2772 // N*: signature byte array in ascii format per Signature.toCharsString()
2773 StringBuilder builder = new StringBuilder(4096);
2774 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2775
2776 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2777 printer.println(pkg.packageName);
2778 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002779 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2780
2781 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2782 printer.println((installerName != null) ? installerName : "");
2783
Christopher Tate4a627c72011-04-01 14:43:32 -07002784 printer.println(withApk ? "1" : "0");
2785 if (pkg.signatures == null) {
2786 printer.println("0");
2787 } else {
2788 printer.println(Integer.toString(pkg.signatures.length));
2789 for (Signature sig : pkg.signatures) {
2790 printer.println(sig.toCharsString());
2791 }
2792 }
2793
2794 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002795 outstream.write(builder.toString().getBytes());
2796 outstream.close();
2797 }
2798
2799 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002800 if (pkg != null) {
2801 final ApplicationInfo app = pkg.applicationInfo;
2802 if (app != null) {
2803 try {
2804 // unbind and tidy up even on timeout or failure, just in case
2805 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002806
Christopher Tateb0628bf2011-06-02 15:08:13 -07002807 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002808 if (app.uid != Process.SYSTEM_UID
2809 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002810 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002811 mActivityManager.killApplicationProcess(app.processName, app.uid);
2812 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002813 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002814 }
2815 } catch (RemoteException e) {
2816 Slog.d(TAG, "Lost app trying to shut down");
2817 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002818 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002819 }
2820 }
2821
2822 // wrappers for observer use
2823 void sendStartBackup() {
2824 if (mObserver != null) {
2825 try {
2826 mObserver.onStartBackup();
2827 } catch (RemoteException e) {
2828 Slog.w(TAG, "full backup observer went away: startBackup");
2829 mObserver = null;
2830 }
2831 }
2832 }
2833
2834 void sendOnBackupPackage(String name) {
2835 if (mObserver != null) {
2836 try {
2837 // TODO: use a more user-friendly name string
2838 mObserver.onBackupPackage(name);
2839 } catch (RemoteException e) {
2840 Slog.w(TAG, "full backup observer went away: backupPackage");
2841 mObserver = null;
2842 }
2843 }
2844 }
2845
2846 void sendEndBackup() {
2847 if (mObserver != null) {
2848 try {
2849 mObserver.onEndBackup();
2850 } catch (RemoteException e) {
2851 Slog.w(TAG, "full backup observer went away: endBackup");
2852 mObserver = null;
2853 }
2854 }
2855 }
2856 }
2857
2858
Christopher Tate75a99702011-05-18 16:28:19 -07002859 // ----- Full restore from a file/socket -----
2860
2861 // Description of a file in the restore datastream
2862 static class FileMetadata {
2863 String packageName; // name of the owning app
2864 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002865 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002866 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2867 String path; // subpath within the semantic domain
2868 long mode; // e.g. 0666 (actually int)
2869 long mtime; // last mod time, UTC time_t (actually int)
2870 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002871
2872 @Override
2873 public String toString() {
2874 StringBuilder sb = new StringBuilder(128);
2875 sb.append("FileMetadata{");
2876 sb.append(packageName); sb.append(',');
2877 sb.append(type); sb.append(',');
2878 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2879 sb.append(size);
2880 sb.append('}');
2881 return sb.toString();
2882 }
Christopher Tate75a99702011-05-18 16:28:19 -07002883 }
2884
2885 enum RestorePolicy {
2886 IGNORE,
2887 ACCEPT,
2888 ACCEPT_IF_APK
2889 }
2890
2891 class PerformFullRestoreTask implements Runnable {
2892 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002893 String mCurrentPassword;
2894 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002895 IFullBackupRestoreObserver mObserver;
2896 AtomicBoolean mLatchObject;
2897 IBackupAgent mAgent;
2898 String mAgentPackage;
2899 ApplicationInfo mTargetApp;
2900 ParcelFileDescriptor[] mPipes = null;
2901
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002902 long mBytes;
2903
Christopher Tate75a99702011-05-18 16:28:19 -07002904 // possible handling states for a given package in the restore dataset
2905 final HashMap<String, RestorePolicy> mPackagePolicies
2906 = new HashMap<String, RestorePolicy>();
2907
2908 // installer package names for each encountered app, derived from the manifests
2909 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2910
2911 // Signatures for a given package found in its manifest file
2912 final HashMap<String, Signature[]> mManifestSignatures
2913 = new HashMap<String, Signature[]>();
2914
2915 // Packages we've already wiped data on when restoring their first file
2916 final HashSet<String> mClearedPackages = new HashSet<String>();
2917
Christopher Tate728a1c42011-07-28 18:03:03 -07002918 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002919 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002920 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002921 mCurrentPassword = curPassword;
2922 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002923 mObserver = observer;
2924 mLatchObject = latch;
2925 mAgent = null;
2926 mAgentPackage = null;
2927 mTargetApp = null;
2928
2929 // Which packages we've already wiped data on. We prepopulate this
2930 // with a whitelist of packages known to be unclearable.
2931 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002932 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002933
Christopher Tate75a99702011-05-18 16:28:19 -07002934 }
2935
2936 class RestoreFileRunnable implements Runnable {
2937 IBackupAgent mAgent;
2938 FileMetadata mInfo;
2939 ParcelFileDescriptor mSocket;
2940 int mToken;
2941
2942 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2943 ParcelFileDescriptor socket, int token) throws IOException {
2944 mAgent = agent;
2945 mInfo = info;
2946 mToken = token;
2947
2948 // This class is used strictly for process-local binder invocations. The
2949 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2950 // do not automatically get a 'dup'ed descriptor that we can can continue
2951 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2952 // before proceeding to do the restore.
2953 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2954 }
2955
2956 @Override
2957 public void run() {
2958 try {
2959 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2960 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2961 mToken, mBackupManagerBinder);
2962 } catch (RemoteException e) {
2963 // never happens; this is used strictly for local binder calls
2964 }
2965 }
2966 }
2967
2968 @Override
2969 public void run() {
2970 Slog.i(TAG, "--- Performing full-dataset restore ---");
2971 sendStartRestore();
2972
Christopher Tateb0628bf2011-06-02 15:08:13 -07002973 // Are we able to restore shared-storage data?
2974 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2975 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2976 }
2977
Christopher Tate2efd2db2011-07-19 16:32:49 -07002978 FileInputStream rawInStream = null;
2979 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002980 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002981 if (hasBackupPassword()) {
2982 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2983 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2984 return;
2985 }
2986 }
2987
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002988 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002989 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002990 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2991 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002992
2993 // First, parse out the unencrypted/uncompressed header
2994 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002995 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002996 final InputStream in;
2997
2998 boolean okay = false;
2999 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
3000 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07003001 rawDataIn.readFully(streamHeader);
3002 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
3003 if (Arrays.equals(magicBytes, streamHeader)) {
3004 // okay, header looks good. now parse out the rest of the fields.
3005 String s = readHeaderLine(rawInStream);
3006 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
3007 // okay, it's a version we recognize
3008 s = readHeaderLine(rawInStream);
3009 compressed = (Integer.parseInt(s) != 0);
3010 s = readHeaderLine(rawInStream);
3011 if (s.equals("none")) {
3012 // no more header to parse; we're good to go
3013 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07003014 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003015 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
3016 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07003017 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003018 }
3019 } else Slog.w(TAG, "Archive is encrypted but no password given");
3020 } else Slog.w(TAG, "Wrong header version: " + s);
3021 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003022
3023 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003024 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003025 return;
3026 }
3027
3028 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07003029 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07003030
3031 boolean didRestore;
3032 do {
Christopher Tate7926a692011-07-11 11:31:57 -07003033 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07003034 } while (didRestore);
3035
Christopher Tatec58efa62011-08-01 19:20:14 -07003036 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003037 } catch (IOException e) {
3038 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07003039 } finally {
3040 tearDownPipes();
3041 tearDownAgent(mTargetApp);
3042
3043 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003044 if (rawDataIn != null) rawDataIn.close();
3045 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07003046 mInputFile.close();
3047 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003048 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003049 /* nothing we can do about this */
3050 }
3051 synchronized (mCurrentOpLock) {
3052 mCurrentOperations.clear();
3053 }
3054 synchronized (mLatchObject) {
3055 mLatchObject.set(true);
3056 mLatchObject.notifyAll();
3057 }
3058 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07003059 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07003060 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07003061 }
3062 }
3063
Christopher Tate7bdb0962011-07-13 19:30:21 -07003064 String readHeaderLine(InputStream in) throws IOException {
3065 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003066 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003067 while ((c = in.read()) >= 0) {
3068 if (c == '\n') break; // consume and discard the newlines
3069 buffer.append((char)c);
3070 }
3071 return buffer.toString();
3072 }
3073
Christopher Tate2efd2db2011-07-19 16:32:49 -07003074 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
3075 InputStream result = null;
3076 try {
3077 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3078
3079 String userSaltHex = readHeaderLine(rawInStream); // 5
3080 byte[] userSalt = hexToByteArray(userSaltHex);
3081
3082 String ckSaltHex = readHeaderLine(rawInStream); // 6
3083 byte[] ckSalt = hexToByteArray(ckSaltHex);
3084
3085 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3086 String userIvHex = readHeaderLine(rawInStream); // 8
3087
3088 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3089
3090 // decrypt the master key blob
3091 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07003092 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003093 rounds);
3094 byte[] IV = hexToByteArray(userIvHex);
3095 IvParameterSpec ivSpec = new IvParameterSpec(IV);
3096 c.init(Cipher.DECRYPT_MODE,
3097 new SecretKeySpec(userKey.getEncoded(), "AES"),
3098 ivSpec);
3099 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3100 byte[] mkBlob = c.doFinal(mkCipher);
3101
3102 // first, the master key IV
3103 int offset = 0;
3104 int len = mkBlob[offset++];
3105 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3106 offset += len;
3107 // then the master key itself
3108 len = mkBlob[offset++];
3109 byte[] mk = Arrays.copyOfRange(mkBlob,
3110 offset, offset + len);
3111 offset += len;
3112 // and finally the master key checksum hash
3113 len = mkBlob[offset++];
3114 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3115 offset, offset + len);
3116
3117 // now validate the decrypted master key against the checksum
3118 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
3119 if (Arrays.equals(calculatedCk, mkChecksum)) {
3120 ivSpec = new IvParameterSpec(IV);
3121 c.init(Cipher.DECRYPT_MODE,
3122 new SecretKeySpec(mk, "AES"),
3123 ivSpec);
3124 // Only if all of the above worked properly will 'result' be assigned
3125 result = new CipherInputStream(rawInStream, c);
3126 } else Slog.w(TAG, "Incorrect password");
3127 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3128 } catch (InvalidAlgorithmParameterException e) {
3129 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3130 } catch (BadPaddingException e) {
3131 // This case frequently occurs when the wrong password is used to decrypt
3132 // the master key. Use the identical "incorrect password" log text as is
3133 // used in the checksum failure log in order to avoid providing additional
3134 // information to an attacker.
3135 Slog.w(TAG, "Incorrect password");
3136 } catch (IllegalBlockSizeException e) {
3137 Slog.w(TAG, "Invalid block size in master key");
3138 } catch (NoSuchAlgorithmException e) {
3139 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3140 } catch (NoSuchPaddingException e) {
3141 Slog.e(TAG, "Needed padding mechanism unavailable!");
3142 } catch (InvalidKeyException e) {
3143 Slog.w(TAG, "Illegal password; aborting");
3144 } catch (NumberFormatException e) {
3145 Slog.w(TAG, "Can't parse restore data header");
3146 } catch (IOException e) {
3147 Slog.w(TAG, "Can't read input header");
3148 }
3149
3150 return result;
3151 }
3152
Christopher Tate75a99702011-05-18 16:28:19 -07003153 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3154 FileMetadata info;
3155 try {
3156 info = readTarHeaders(instream);
3157 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003158 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003159 dumpFileMetadata(info);
3160 }
3161
3162 final String pkg = info.packageName;
3163 if (!pkg.equals(mAgentPackage)) {
3164 // okay, change in package; set up our various
3165 // bookkeeping if we haven't seen it yet
3166 if (!mPackagePolicies.containsKey(pkg)) {
3167 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3168 }
3169
3170 // Clean up the previous agent relationship if necessary,
3171 // and let the observer know we're considering a new app.
3172 if (mAgent != null) {
3173 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3174 tearDownPipes();
3175 tearDownAgent(mTargetApp);
3176 mTargetApp = null;
3177 mAgentPackage = null;
3178 }
3179 }
3180
3181 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3182 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3183 mPackageInstallers.put(pkg, info.installerPackageName);
3184 // We've read only the manifest content itself at this point,
3185 // so consume the footer before looping around to the next
3186 // input file
3187 skipTarPadding(info.size, instream);
3188 sendOnRestorePackage(pkg);
3189 } else {
3190 // Non-manifest, so it's actual file data. Is this a package
3191 // we're ignoring?
3192 boolean okay = true;
3193 RestorePolicy policy = mPackagePolicies.get(pkg);
3194 switch (policy) {
3195 case IGNORE:
3196 okay = false;
3197 break;
3198
3199 case ACCEPT_IF_APK:
3200 // If we're in accept-if-apk state, then the first file we
3201 // see MUST be the apk.
3202 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3203 if (DEBUG) Slog.d(TAG, "APK file; installing");
3204 // Try to install the app.
3205 String installerName = mPackageInstallers.get(pkg);
3206 okay = installApk(info, installerName, instream);
3207 // good to go; promote to ACCEPT
3208 mPackagePolicies.put(pkg, (okay)
3209 ? RestorePolicy.ACCEPT
3210 : RestorePolicy.IGNORE);
3211 // At this point we've consumed this file entry
3212 // ourselves, so just strip the tar footer and
3213 // go on to the next file in the input stream
3214 skipTarPadding(info.size, instream);
3215 return true;
3216 } else {
3217 // File data before (or without) the apk. We can't
3218 // handle it coherently in this case so ignore it.
3219 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3220 okay = false;
3221 }
3222 break;
3223
3224 case ACCEPT:
3225 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3226 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3227 // we can take the data without the apk, so we
3228 // *want* to do so. skip the apk by declaring this
3229 // one file not-okay without changing the restore
3230 // policy for the package.
3231 okay = false;
3232 }
3233 break;
3234
3235 default:
3236 // Something has gone dreadfully wrong when determining
3237 // the restore policy from the manifest. Ignore the
3238 // rest of this package's data.
3239 Slog.e(TAG, "Invalid policy from manifest");
3240 okay = false;
3241 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3242 break;
3243 }
3244
3245 // If the policy is satisfied, go ahead and set up to pipe the
3246 // data to the agent.
3247 if (DEBUG && okay && mAgent != null) {
3248 Slog.i(TAG, "Reusing existing agent instance");
3249 }
3250 if (okay && mAgent == null) {
3251 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3252
3253 try {
3254 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3255
3256 // If we haven't sent any data to this app yet, we probably
3257 // need to clear it first. Check that.
3258 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003259 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003260 // responsible for coherently managing a full
3261 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003262 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003263 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3264 clearApplicationDataSynchronous(pkg);
3265 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003266 if (DEBUG) Slog.d(TAG, "backup agent ("
3267 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003268 }
3269 mClearedPackages.add(pkg);
3270 } else {
3271 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3272 }
3273
3274 // All set; now set up the IPC and launch the agent
3275 setUpPipes();
3276 mAgent = bindToAgentSynchronous(mTargetApp,
3277 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3278 mAgentPackage = pkg;
3279 } catch (IOException e) {
3280 // fall through to error handling
3281 } catch (NameNotFoundException e) {
3282 // fall through to error handling
3283 }
3284
3285 if (mAgent == null) {
3286 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3287 okay = false;
3288 tearDownPipes();
3289 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3290 }
3291 }
3292
3293 // Sanity check: make sure we never give data to the wrong app. This
3294 // should never happen but a little paranoia here won't go amiss.
3295 if (okay && !pkg.equals(mAgentPackage)) {
3296 Slog.e(TAG, "Restoring data for " + pkg
3297 + " but agent is for " + mAgentPackage);
3298 okay = false;
3299 }
3300
3301 // At this point we have an agent ready to handle the full
3302 // restore data as well as a pipe for sending data to
3303 // that agent. Tell the agent to start reading from the
3304 // pipe.
3305 if (okay) {
3306 boolean agentSuccess = true;
3307 long toCopy = info.size;
3308 final int token = generateToken();
3309 try {
3310 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3311 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003312 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003313 // fire up the app's agent listening on the socket. If
3314 // the agent is running in the system process we can't
3315 // just invoke it asynchronously, so we provide a thread
3316 // for it here.
3317 if (mTargetApp.processName.equals("system")) {
3318 Slog.d(TAG, "system process agent - spinning a thread");
3319 RestoreFileRunnable runner = new RestoreFileRunnable(
3320 mAgent, info, mPipes[0], token);
3321 new Thread(runner).start();
3322 } else {
3323 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3324 info.domain, info.path, info.mode, info.mtime,
3325 token, mBackupManagerBinder);
3326 }
3327 } catch (IOException e) {
3328 // couldn't dup the socket for a process-local restore
3329 Slog.d(TAG, "Couldn't establish restore");
3330 agentSuccess = false;
3331 okay = false;
3332 } catch (RemoteException e) {
3333 // whoops, remote agent went away. We'll eat the content
3334 // ourselves, then, and not copy it over.
3335 Slog.e(TAG, "Agent crashed during full restore");
3336 agentSuccess = false;
3337 okay = false;
3338 }
3339
3340 // Copy over the data if the agent is still good
3341 if (okay) {
3342 boolean pipeOkay = true;
3343 FileOutputStream pipe = new FileOutputStream(
3344 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003345 while (toCopy > 0) {
3346 int toRead = (toCopy > buffer.length)
3347 ? buffer.length : (int)toCopy;
3348 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003349 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003350 if (nRead <= 0) break;
3351 toCopy -= nRead;
3352
3353 // send it to the output pipe as long as things
3354 // are still good
3355 if (pipeOkay) {
3356 try {
3357 pipe.write(buffer, 0, nRead);
3358 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003359 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003360 pipeOkay = false;
3361 }
3362 }
3363 }
3364
3365 // done sending that file! Now we just need to consume
3366 // the delta from info.size to the end of block.
3367 skipTarPadding(info.size, instream);
3368
3369 // and now that we've sent it all, wait for the remote
3370 // side to acknowledge receipt
3371 agentSuccess = waitUntilOperationComplete(token);
3372 }
3373
3374 // okay, if the remote end failed at any point, deal with
3375 // it by ignoring the rest of the restore on it
3376 if (!agentSuccess) {
3377 mBackupHandler.removeMessages(MSG_TIMEOUT);
3378 tearDownPipes();
3379 tearDownAgent(mTargetApp);
3380 mAgent = null;
3381 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3382 }
3383 }
3384
3385 // Problems setting up the agent communication, or an already-
3386 // ignored package: skip to the next tar stream entry by
3387 // reading and discarding this file.
3388 if (!okay) {
3389 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3390 long bytesToConsume = (info.size + 511) & ~511;
3391 while (bytesToConsume > 0) {
3392 int toRead = (bytesToConsume > buffer.length)
3393 ? buffer.length : (int)bytesToConsume;
3394 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003395 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003396 if (nRead <= 0) break;
3397 bytesToConsume -= nRead;
3398 }
3399 }
3400 }
3401 }
3402 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003403 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003404 // treat as EOF
3405 info = null;
3406 }
3407
3408 return (info != null);
3409 }
3410
3411 void setUpPipes() throws IOException {
3412 mPipes = ParcelFileDescriptor.createPipe();
3413 }
3414
3415 void tearDownPipes() {
3416 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003417 try {
3418 mPipes[0].close();
3419 mPipes[0] = null;
3420 mPipes[1].close();
3421 mPipes[1] = null;
3422 } catch (IOException e) {
3423 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003424 }
3425 mPipes = null;
3426 }
3427 }
3428
3429 void tearDownAgent(ApplicationInfo app) {
3430 if (mAgent != null) {
3431 try {
3432 // unbind and tidy up even on timeout or failure, just in case
3433 mActivityManager.unbindBackupAgent(app);
3434
3435 // The agent was running with a stub Application object, so shut it down.
3436 // !!! We hardcode the confirmation UI's package name here rather than use a
3437 // manifest flag! TODO something less direct.
3438 if (app.uid != Process.SYSTEM_UID
3439 && !app.packageName.equals("com.android.backupconfirm")) {
3440 if (DEBUG) Slog.d(TAG, "Killing host process");
3441 mActivityManager.killApplicationProcess(app.processName, app.uid);
3442 } else {
3443 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3444 }
3445 } catch (RemoteException e) {
3446 Slog.d(TAG, "Lost app trying to shut down");
3447 }
3448 mAgent = null;
3449 }
3450 }
3451
3452 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3453 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003454 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003455 int mResult;
3456
3457 public void reset() {
3458 synchronized (mDone) {
3459 mDone.set(false);
3460 }
3461 }
3462
3463 public void waitForCompletion() {
3464 synchronized (mDone) {
3465 while (mDone.get() == false) {
3466 try {
3467 mDone.wait();
3468 } catch (InterruptedException e) { }
3469 }
3470 }
3471 }
3472
3473 int getResult() {
3474 return mResult;
3475 }
3476
3477 @Override
3478 public void packageInstalled(String packageName, int returnCode)
3479 throws RemoteException {
3480 synchronized (mDone) {
3481 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003482 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003483 mDone.set(true);
3484 mDone.notifyAll();
3485 }
3486 }
3487 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003488
3489 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3490 final AtomicBoolean mDone = new AtomicBoolean();
3491 int mResult;
3492
3493 public void reset() {
3494 synchronized (mDone) {
3495 mDone.set(false);
3496 }
3497 }
3498
3499 public void waitForCompletion() {
3500 synchronized (mDone) {
3501 while (mDone.get() == false) {
3502 try {
3503 mDone.wait();
3504 } catch (InterruptedException e) { }
3505 }
3506 }
3507 }
3508
3509 @Override
3510 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3511 synchronized (mDone) {
3512 mResult = returnCode;
3513 mDone.set(true);
3514 mDone.notifyAll();
3515 }
3516 }
3517 }
3518
Christopher Tate75a99702011-05-18 16:28:19 -07003519 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003520 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003521
3522 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3523 boolean okay = true;
3524
3525 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3526
3527 // The file content is an .apk file. Copy it out to a staging location and
3528 // attempt to install it.
3529 File apkFile = new File(mDataDir, info.packageName);
3530 try {
3531 FileOutputStream apkStream = new FileOutputStream(apkFile);
3532 byte[] buffer = new byte[32 * 1024];
3533 long size = info.size;
3534 while (size > 0) {
3535 long toRead = (buffer.length < size) ? buffer.length : size;
3536 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003537 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003538 apkStream.write(buffer, 0, didRead);
3539 size -= didRead;
3540 }
3541 apkStream.close();
3542
3543 // make sure the installer can read it
3544 apkFile.setReadable(true, false);
3545
3546 // Now install it
3547 Uri packageUri = Uri.fromFile(apkFile);
3548 mInstallObserver.reset();
3549 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003550 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3551 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003552 mInstallObserver.waitForCompletion();
3553
3554 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3555 // The only time we continue to accept install of data even if the
3556 // apk install failed is if we had already determined that we could
3557 // accept the data regardless.
3558 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3559 okay = false;
3560 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003561 } else {
3562 // Okay, the install succeeded. Make sure it was the right app.
3563 boolean uninstall = false;
3564 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3565 Slog.w(TAG, "Restore stream claimed to include apk for "
3566 + info.packageName + " but apk was really "
3567 + mInstallObserver.mPackageName);
3568 // delete the package we just put in place; it might be fraudulent
3569 okay = false;
3570 uninstall = true;
3571 } else {
3572 try {
3573 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3574 PackageManager.GET_SIGNATURES);
3575 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3576 Slog.w(TAG, "Restore stream contains apk of package "
3577 + info.packageName + " but it disallows backup/restore");
3578 okay = false;
3579 } else {
3580 // So far so good -- do the signatures match the manifest?
3581 Signature[] sigs = mManifestSignatures.get(info.packageName);
3582 if (!signaturesMatch(sigs, pkg)) {
3583 Slog.w(TAG, "Installed app " + info.packageName
3584 + " signatures do not match restore manifest");
3585 okay = false;
3586 uninstall = true;
3587 }
3588 }
3589 } catch (NameNotFoundException e) {
3590 Slog.w(TAG, "Install of package " + info.packageName
3591 + " succeeded but now not found");
3592 okay = false;
3593 }
3594 }
3595
3596 // If we're not okay at this point, we need to delete the package
3597 // that we just installed.
3598 if (uninstall) {
3599 mDeleteObserver.reset();
3600 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3601 mDeleteObserver, 0);
3602 mDeleteObserver.waitForCompletion();
3603 }
Christopher Tate75a99702011-05-18 16:28:19 -07003604 }
3605 } catch (IOException e) {
3606 Slog.e(TAG, "Unable to transcribe restored apk for install");
3607 okay = false;
3608 } finally {
3609 apkFile.delete();
3610 }
3611
3612 return okay;
3613 }
3614
3615 // Given an actual file content size, consume the post-content padding mandated
3616 // by the tar format.
3617 void skipTarPadding(long size, InputStream instream) throws IOException {
3618 long partial = (size + 512) % 512;
3619 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003620 final int needed = 512 - (int)partial;
3621 byte[] buffer = new byte[needed];
3622 if (readExactly(instream, buffer, 0, needed) == needed) {
3623 mBytes += needed;
3624 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003625 }
3626 }
3627
3628 // Returns a policy constant; takes a buffer arg to reduce memory churn
3629 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3630 throws IOException {
3631 // Fail on suspiciously large manifest files
3632 if (info.size > 64 * 1024) {
3633 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3634 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003635
Christopher Tate75a99702011-05-18 16:28:19 -07003636 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003637 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3638 mBytes += info.size;
3639 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003640
3641 RestorePolicy policy = RestorePolicy.IGNORE;
3642 String[] str = new String[1];
3643 int offset = 0;
3644
3645 try {
3646 offset = extractLine(buffer, offset, str);
3647 int version = Integer.parseInt(str[0]);
3648 if (version == BACKUP_MANIFEST_VERSION) {
3649 offset = extractLine(buffer, offset, str);
3650 String manifestPackage = str[0];
3651 // TODO: handle <original-package>
3652 if (manifestPackage.equals(info.packageName)) {
3653 offset = extractLine(buffer, offset, str);
3654 version = Integer.parseInt(str[0]); // app version
3655 offset = extractLine(buffer, offset, str);
3656 int platformVersion = Integer.parseInt(str[0]);
3657 offset = extractLine(buffer, offset, str);
3658 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3659 offset = extractLine(buffer, offset, str);
3660 boolean hasApk = str[0].equals("1");
3661 offset = extractLine(buffer, offset, str);
3662 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003663 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003664 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003665 for (int i = 0; i < numSigs; i++) {
3666 offset = extractLine(buffer, offset, str);
3667 sigs[i] = new Signature(str[0]);
3668 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003669 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003670
3671 // Okay, got the manifest info we need...
3672 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003673 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3674 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003675 // Fall through to IGNORE if the app explicitly disallows backup
3676 final int flags = pkgInfo.applicationInfo.flags;
3677 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3678 // Verify signatures against any installed version; if they
3679 // don't match, then we fall though and ignore the data. The
3680 // signatureMatch() method explicitly ignores the signature
3681 // check for packages installed on the system partition, because
3682 // such packages are signed with the platform cert instead of
3683 // the app developer's cert, so they're different on every
3684 // device.
3685 if (signaturesMatch(sigs, pkgInfo)) {
3686 if (pkgInfo.versionCode >= version) {
3687 Slog.i(TAG, "Sig + version match; taking data");
3688 policy = RestorePolicy.ACCEPT;
3689 } else {
3690 // The data is from a newer version of the app than
3691 // is presently installed. That means we can only
3692 // use it if the matching apk is also supplied.
3693 Slog.d(TAG, "Data version " + version
3694 + " is newer than installed version "
3695 + pkgInfo.versionCode + " - requiring apk");
3696 policy = RestorePolicy.ACCEPT_IF_APK;
3697 }
Christopher Tate75a99702011-05-18 16:28:19 -07003698 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003699 Slog.w(TAG, "Restore manifest signatures do not match "
3700 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003701 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003702 } else {
3703 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3704 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003705 }
3706 } catch (NameNotFoundException e) {
3707 // Okay, the target app isn't installed. We can process
3708 // the restore properly only if the dataset provides the
3709 // apk file and we can successfully install it.
3710 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3711 + " not installed; requiring apk in dataset");
3712 policy = RestorePolicy.ACCEPT_IF_APK;
3713 }
3714
3715 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3716 Slog.i(TAG, "Cannot restore package " + info.packageName
3717 + " without the matching .apk");
3718 }
3719 } else {
3720 Slog.i(TAG, "Missing signature on backed-up package "
3721 + info.packageName);
3722 }
3723 } else {
3724 Slog.i(TAG, "Expected package " + info.packageName
3725 + " but restore manifest claims " + manifestPackage);
3726 }
3727 } else {
3728 Slog.i(TAG, "Unknown restore manifest version " + version
3729 + " for package " + info.packageName);
3730 }
3731 } catch (NumberFormatException e) {
3732 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003733 } catch (IllegalArgumentException e) {
3734 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003735 }
3736
3737 return policy;
3738 }
3739
3740 // Builds a line from a byte buffer starting at 'offset', and returns
3741 // the index of the next unconsumed data in the buffer.
3742 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3743 final int end = buffer.length;
3744 if (offset >= end) throw new IOException("Incomplete data");
3745
3746 int pos;
3747 for (pos = offset; pos < end; pos++) {
3748 byte c = buffer[pos];
3749 // at LF we declare end of line, and return the next char as the
3750 // starting point for the next time through
3751 if (c == '\n') {
3752 break;
3753 }
3754 }
3755 outStr[0] = new String(buffer, offset, pos - offset);
3756 pos++; // may be pointing an extra byte past the end but that's okay
3757 return pos;
3758 }
3759
3760 void dumpFileMetadata(FileMetadata info) {
3761 if (DEBUG) {
3762 StringBuilder b = new StringBuilder(128);
3763
3764 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003765 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003766 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3767 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3768 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3769 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3770 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3771 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3772 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3773 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3774 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3775 b.append(String.format(" %9d ", info.size));
3776
3777 Date stamp = new Date(info.mtime);
3778 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3779
3780 b.append(info.packageName);
3781 b.append(" :: ");
3782 b.append(info.domain);
3783 b.append(" :: ");
3784 b.append(info.path);
3785
3786 Slog.i(TAG, b.toString());
3787 }
3788 }
3789 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3790 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3791 byte[] block = new byte[512];
3792 FileMetadata info = null;
3793
3794 boolean gotHeader = readTarHeader(instream, block);
3795 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003796 try {
3797 // okay, presume we're okay, and extract the various metadata
3798 info = new FileMetadata();
3799 info.size = extractRadix(block, 124, 12, 8);
3800 info.mtime = extractRadix(block, 136, 12, 8);
3801 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003802
Christopher Tate2efd2db2011-07-19 16:32:49 -07003803 info.path = extractString(block, 345, 155); // prefix
3804 String path = extractString(block, 0, 100);
3805 if (path.length() > 0) {
3806 if (info.path.length() > 0) info.path += '/';
3807 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003808 }
Christopher Tate75a99702011-05-18 16:28:19 -07003809
Christopher Tate2efd2db2011-07-19 16:32:49 -07003810 // tar link indicator field: 1 byte at offset 156 in the header.
3811 int typeChar = block[156];
3812 if (typeChar == 'x') {
3813 // pax extended header, so we need to read that
3814 gotHeader = readPaxExtendedHeader(instream, info);
3815 if (gotHeader) {
3816 // and after a pax extended header comes another real header -- read
3817 // that to find the real file type
3818 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003819 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003820 if (!gotHeader) throw new IOException("Bad or missing pax header");
3821
3822 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003823 }
Christopher Tate75a99702011-05-18 16:28:19 -07003824
Christopher Tate2efd2db2011-07-19 16:32:49 -07003825 switch (typeChar) {
3826 case '0': info.type = BackupAgent.TYPE_FILE; break;
3827 case '5': {
3828 info.type = BackupAgent.TYPE_DIRECTORY;
3829 if (info.size != 0) {
3830 Slog.w(TAG, "Directory entry with nonzero size in header");
3831 info.size = 0;
3832 }
3833 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003834 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003835 case 0: {
3836 // presume EOF
3837 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3838 return null;
3839 }
3840 default: {
3841 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3842 throw new IOException("Unknown entity type " + typeChar);
3843 }
Christopher Tate75a99702011-05-18 16:28:19 -07003844 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003845
3846 // Parse out the path
3847 //
3848 // first: apps/shared/unrecognized
3849 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3850 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3851 // File in shared storage. !!! TODO: implement this.
3852 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
3853 info.packageName = "com.android.sharedstoragebackup";
3854 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3855 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3856 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3857 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3858 // App content! Parse out the package name and domain
3859
3860 // strip the apps/ prefix
3861 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3862
3863 // extract the package name
3864 int slash = info.path.indexOf('/');
3865 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3866 info.packageName = info.path.substring(0, slash);
3867 info.path = info.path.substring(slash+1);
3868
3869 // if it's a manifest we're done, otherwise parse out the domains
3870 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3871 slash = info.path.indexOf('/');
3872 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3873 info.domain = info.path.substring(0, slash);
3874 // validate that it's one of the domains we understand
3875 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3876 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3877 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3878 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3879 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3880 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3881 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3882 throw new IOException("Unrecognized domain " + info.domain);
3883 }
3884
3885 info.path = info.path.substring(slash + 1);
3886 }
3887 }
3888 } catch (IOException e) {
3889 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003890 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003891 HEXLOG(block);
3892 }
3893 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003894 }
3895 }
3896 return info;
3897 }
3898
Christopher Tate2efd2db2011-07-19 16:32:49 -07003899 private void HEXLOG(byte[] block) {
3900 int offset = 0;
3901 int todo = block.length;
3902 StringBuilder buf = new StringBuilder(64);
3903 while (todo > 0) {
3904 buf.append(String.format("%04x ", offset));
3905 int numThisLine = (todo > 16) ? 16 : todo;
3906 for (int i = 0; i < numThisLine; i++) {
3907 buf.append(String.format("%02x ", block[offset+i]));
3908 }
3909 Slog.i("hexdump", buf.toString());
3910 buf.setLength(0);
3911 todo -= numThisLine;
3912 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003913 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003914 }
3915
Christopher Tate6853fcf2011-08-10 17:52:21 -07003916 // Read exactly the given number of bytes into a buffer at the stated offset.
3917 // Returns false if EOF is encountered before the requested number of bytes
3918 // could be read.
3919 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3920 throws IOException {
3921 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3922
3923 int soFar = 0;
3924 while (soFar < size) {
3925 int nRead = in.read(buffer, offset + soFar, size - soFar);
3926 if (nRead <= 0) {
3927 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3928 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003929 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003930 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003931 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003932 return soFar;
3933 }
3934
3935 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3936 final int got = readExactly(instream, block, 0, 512);
3937 if (got == 0) return false; // Clean EOF
3938 if (got < 512) throw new IOException("Unable to read full block header");
3939 mBytes += 512;
3940 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003941 }
3942
3943 // overwrites 'info' fields based on the pax extended header
3944 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3945 throws IOException {
3946 // We should never see a pax extended header larger than this
3947 if (info.size > 32*1024) {
3948 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3949 + " - aborting");
3950 throw new IOException("Sanity failure: pax header size " + info.size);
3951 }
3952
3953 // read whole blocks, not just the content size
3954 int numBlocks = (int)((info.size + 511) >> 9);
3955 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003956 if (readExactly(instream, data, 0, data.length) < data.length) {
3957 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003958 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003959 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003960
3961 final int contentSize = (int) info.size;
3962 int offset = 0;
3963 do {
3964 // extract the line at 'offset'
3965 int eol = offset+1;
3966 while (eol < contentSize && data[eol] != ' ') eol++;
3967 if (eol >= contentSize) {
3968 // error: we just hit EOD looking for the end of the size field
3969 throw new IOException("Invalid pax data");
3970 }
3971 // eol points to the space between the count and the key
3972 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3973 int key = eol + 1; // start of key=value
3974 eol = offset + linelen - 1; // trailing LF
3975 int value;
3976 for (value = key+1; data[value] != '=' && value <= eol; value++);
3977 if (value > eol) {
3978 throw new IOException("Invalid pax declaration");
3979 }
3980
3981 // pax requires that key/value strings be in UTF-8
3982 String keyStr = new String(data, key, value-key, "UTF-8");
3983 // -1 to strip the trailing LF
3984 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3985
3986 if ("path".equals(keyStr)) {
3987 info.path = valStr;
3988 } else if ("size".equals(keyStr)) {
3989 info.size = Long.parseLong(valStr);
3990 } else {
3991 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3992 }
3993
3994 offset += linelen;
3995 } while (offset < contentSize);
3996
3997 return true;
3998 }
3999
4000 long extractRadix(byte[] data, int offset, int maxChars, int radix)
4001 throws IOException {
4002 long value = 0;
4003 final int end = offset + maxChars;
4004 for (int i = offset; i < end; i++) {
4005 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004006 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07004007 if (b == 0 || b == ' ') break;
4008 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004009 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07004010 }
4011 value = radix * value + (b - '0');
4012 }
4013 return value;
4014 }
4015
4016 String extractString(byte[] data, int offset, int maxChars) throws IOException {
4017 final int end = offset + maxChars;
4018 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004019 // tar string fields terminate early with a NUL
4020 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07004021 return new String(data, offset, eos-offset, "US-ASCII");
4022 }
4023
4024 void sendStartRestore() {
4025 if (mObserver != null) {
4026 try {
4027 mObserver.onStartRestore();
4028 } catch (RemoteException e) {
4029 Slog.w(TAG, "full restore observer went away: startRestore");
4030 mObserver = null;
4031 }
4032 }
4033 }
4034
4035 void sendOnRestorePackage(String name) {
4036 if (mObserver != null) {
4037 try {
4038 // TODO: use a more user-friendly name string
4039 mObserver.onRestorePackage(name);
4040 } catch (RemoteException e) {
4041 Slog.w(TAG, "full restore observer went away: restorePackage");
4042 mObserver = null;
4043 }
4044 }
4045 }
4046
4047 void sendEndRestore() {
4048 if (mObserver != null) {
4049 try {
4050 mObserver.onEndRestore();
4051 } catch (RemoteException e) {
4052 Slog.w(TAG, "full restore observer went away: endRestore");
4053 mObserver = null;
4054 }
4055 }
4056 }
4057 }
4058
Christopher Tatedf01dea2009-06-09 20:45:02 -07004059 // ----- Restore handling -----
4060
Christopher Tate78dd4a72009-11-04 11:49:08 -08004061 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4062 // If the target resides on the system partition, we allow it to restore
4063 // data from the like-named package in a restore set even if the signatures
4064 // do not match. (Unlike general applications, those flashed to the system
4065 // partition will be signed with the device's platform certificate, so on
4066 // different phones the same system app will have different signatures.)
4067 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004068 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08004069 return true;
4070 }
4071
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004072 // Allow unsigned apps, but not signed on one device and unsigned on the other
4073 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08004074 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07004075 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07004076 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004077 if ((storedSigs == null || storedSigs.length == 0)
4078 && (deviceSigs == null || deviceSigs.length == 0)) {
4079 return true;
4080 }
4081 if (storedSigs == null || deviceSigs == null) {
4082 return false;
4083 }
4084
Christopher Tateabce4e82009-06-18 18:35:32 -07004085 // !!! TODO: this demands that every stored signature match one
4086 // that is present on device, and does not demand the converse.
4087 // Is this this right policy?
4088 int nStored = storedSigs.length;
4089 int nDevice = deviceSigs.length;
4090
4091 for (int i=0; i < nStored; i++) {
4092 boolean match = false;
4093 for (int j=0; j < nDevice; j++) {
4094 if (storedSigs[i].equals(deviceSigs[j])) {
4095 match = true;
4096 break;
4097 }
4098 }
4099 if (!match) {
4100 return false;
4101 }
4102 }
4103 return true;
4104 }
4105
Christopher Tate2982d062011-09-06 20:35:24 -07004106 enum RestoreState {
4107 INITIAL,
4108 DOWNLOAD_DATA,
4109 PM_METADATA,
4110 RUNNING_QUEUE,
4111 FINAL
4112 }
4113
4114 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004115 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004116 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07004117 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08004118 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004119 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08004120 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004121 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004122 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004123 private long mStartRealtime;
4124 private PackageManagerBackupAgent mPmAgent;
4125 private List<PackageInfo> mAgentPackages;
4126 private ArrayList<PackageInfo> mRestorePackages;
4127 private RestoreState mCurrentState;
4128 private int mCount;
4129 private boolean mFinished;
4130 private int mStatus;
4131 private File mBackupDataName;
4132 private File mNewStateName;
4133 private File mSavedStateName;
4134 private ParcelFileDescriptor mBackupData;
4135 private ParcelFileDescriptor mNewState;
4136 private PackageInfo mCurrentPackage;
4137
Christopher Tatedf01dea2009-06-09 20:45:02 -07004138
Christopher Tate5cbbf562009-06-22 16:44:51 -07004139 class RestoreRequest {
4140 public PackageInfo app;
4141 public int storedAppVersion;
4142
4143 RestoreRequest(PackageInfo _app, int _version) {
4144 app = _app;
4145 storedAppVersion = _version;
4146 }
4147 }
4148
Christopher Tate44a27902010-01-27 17:15:49 -08004149 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004150 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004151 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004152 mCurrentState = RestoreState.INITIAL;
4153 mFinished = false;
4154 mPmAgent = null;
4155
Christopher Tatedf01dea2009-06-09 20:45:02 -07004156 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004157 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004158 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004159 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004160 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004161 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004162
Christopher Tate284f1bb2011-07-07 14:31:18 -07004163 if (filterSet != null) {
4164 mFilterSet = new HashSet<String>();
4165 for (String pkg : filterSet) {
4166 mFilterSet.add(pkg);
4167 }
4168 } else {
4169 mFilterSet = null;
4170 }
4171
Christopher Tate5cb400b2009-06-25 16:03:14 -07004172 try {
4173 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4174 } catch (RemoteException e) {
4175 // can't happen; the transport is local
4176 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004177 }
4178
Christopher Tate2982d062011-09-06 20:35:24 -07004179 // Execute one tick of whatever state machine the task implements
4180 @Override
4181 public void execute() {
4182 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4183 switch (mCurrentState) {
4184 case INITIAL:
4185 beginRestore();
4186 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004187
Christopher Tate2982d062011-09-06 20:35:24 -07004188 case DOWNLOAD_DATA:
4189 downloadRestoreData();
4190 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004191
Christopher Tate2982d062011-09-06 20:35:24 -07004192 case PM_METADATA:
4193 restorePmMetadata();
4194 break;
4195
4196 case RUNNING_QUEUE:
4197 restoreNextAgent();
4198 break;
4199
4200 case FINAL:
4201 if (!mFinished) finalizeRestore();
4202 else {
4203 Slog.e(TAG, "Duplicate finish");
4204 }
4205 mFinished = true;
4206 break;
4207 }
4208 }
4209
4210 // Initialize and set up for the PM metadata restore, which comes first
4211 void beginRestore() {
4212 // Don't account time doing the restore as inactivity of the app
4213 // that has opened a restore session.
4214 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4215
4216 // Assume error until we successfully init everything
4217 mStatus = BackupConstants.TRANSPORT_ERROR;
4218
Christopher Tatedf01dea2009-06-09 20:45:02 -07004219 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004220 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004221 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004222
Dan Egnorefe52642009-06-24 00:16:33 -07004223 // Get the list of all packages which have backup enabled.
4224 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004225 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004226 PackageInfo omPackage = new PackageInfo();
4227 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004228 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004229
Christopher Tate2982d062011-09-06 20:35:24 -07004230 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004231 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004232 // if there's a filter set, strip out anything that isn't
4233 // present before proceeding
4234 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004235 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4236 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004237 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004238 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004239 }
4240 }
Christopher Tate2982d062011-09-06 20:35:24 -07004241 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004242 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004243 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004244 Slog.i(TAG, " " + p);
4245 }
4246 }
4247 }
Christopher Tate2982d062011-09-06 20:35:24 -07004248 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004249 } else {
4250 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004251 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004252 }
Dan Egnorefe52642009-06-24 00:16:33 -07004253
Christopher Tate7d562ec2009-06-25 18:03:43 -07004254 // let the observer know that we're running
4255 if (mObserver != null) {
4256 try {
4257 // !!! TODO: get an actual count from the transport after
4258 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004259 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004260 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004261 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004262 mObserver = null;
4263 }
4264 }
Christopher Tate2982d062011-09-06 20:35:24 -07004265 } catch (RemoteException e) {
4266 // Something has gone catastrophically wrong with the transport
4267 Slog.e(TAG, "Error communicating with transport for restore");
4268 executeNextState(RestoreState.FINAL);
4269 return;
4270 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004271
Christopher Tate2982d062011-09-06 20:35:24 -07004272 mStatus = BackupConstants.TRANSPORT_OK;
4273 executeNextState(RestoreState.DOWNLOAD_DATA);
4274 }
4275
4276 void downloadRestoreData() {
4277 // Note that the download phase can be very time consuming, but we're executing
4278 // it inline here on the looper. This is "okay" because it is not calling out to
4279 // third party code; the transport is "trusted," and so we assume it is being a
4280 // good citizen and timing out etc when appropriate.
4281 //
4282 // TODO: when appropriate, move the download off the looper and rearrange the
4283 // error handling around that.
4284 try {
4285 mStatus = mTransport.startRestore(mToken,
4286 mRestorePackages.toArray(new PackageInfo[0]));
4287 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004288 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004289 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004290 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004291 return;
4292 }
Christopher Tate2982d062011-09-06 20:35:24 -07004293 } catch (RemoteException e) {
4294 Slog.e(TAG, "Error communicating with transport for restore");
4295 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4296 mStatus = BackupConstants.TRANSPORT_ERROR;
4297 executeNextState(RestoreState.FINAL);
4298 return;
4299 }
Dan Egnorefe52642009-06-24 00:16:33 -07004300
Christopher Tate2982d062011-09-06 20:35:24 -07004301 // Successful download of the data to be parceled out to the apps, so off we go.
4302 executeNextState(RestoreState.PM_METADATA);
4303 }
4304
4305 void restorePmMetadata() {
4306 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004307 String packageName = mTransport.nextRestorePackage();
4308 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004309 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004310 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004311 mStatus = BackupConstants.TRANSPORT_ERROR;
4312 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004313 return;
4314 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004315 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004316 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004317 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004318 mStatus = BackupConstants.TRANSPORT_OK;
4319 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004320 return;
4321 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004322 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004323 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004324 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004325 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004326 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004327 return;
4328 }
4329
4330 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004331 PackageInfo omPackage = new PackageInfo();
4332 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4333 mPmAgent = new PackageManagerBackupAgent(
4334 mPackageManager, mAgentPackages);
4335 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004336 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004337 // The PM agent called operationComplete() already, because our invocation
4338 // of it is process-local and therefore synchronous. That means that a
4339 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4340 // proceed with running the queue do we remove that pending message and
4341 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004342
Christopher Tate8c032472009-07-02 14:28:47 -07004343 // Verify that the backup set includes metadata. If not, we can't do
4344 // signature/version verification etc, so we simply do not proceed with
4345 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004346 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004347 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004348 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004349 "Package manager restore metadata missing");
4350 mStatus = BackupConstants.TRANSPORT_ERROR;
4351 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4352 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004353 return;
4354 }
Christopher Tate2982d062011-09-06 20:35:24 -07004355 } catch (RemoteException e) {
4356 Slog.e(TAG, "Error communicating with transport for restore");
4357 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4358 mStatus = BackupConstants.TRANSPORT_ERROR;
4359 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4360 executeNextState(RestoreState.FINAL);
4361 return;
4362 }
Christopher Tate8c032472009-07-02 14:28:47 -07004363
Christopher Tate2982d062011-09-06 20:35:24 -07004364 // Metadata is intact, so we can now run the restore queue. If we get here,
4365 // we have already enqueued the necessary next-step message on the looper.
4366 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004367
Christopher Tate2982d062011-09-06 20:35:24 -07004368 void restoreNextAgent() {
4369 try {
4370 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004371
Christopher Tate2982d062011-09-06 20:35:24 -07004372 if (packageName == null) {
4373 Slog.e(TAG, "Error getting next restore package");
4374 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4375 executeNextState(RestoreState.FINAL);
4376 return;
4377 } else if (packageName.equals("")) {
4378 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4379 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4380 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4381 executeNextState(RestoreState.FINAL);
4382 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004383 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004384
4385 if (mObserver != null) {
4386 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004387 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004388 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004389 Slog.d(TAG, "Restore observer died in onUpdate");
4390 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004391 }
4392 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004393
Christopher Tate2982d062011-09-06 20:35:24 -07004394 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4395 if (metaInfo == null) {
4396 Slog.e(TAG, "Missing metadata for " + packageName);
4397 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4398 "Package metadata missing");
4399 executeNextState(RestoreState.RUNNING_QUEUE);
4400 return;
Christopher Tate84725812010-02-04 15:52:40 -08004401 }
4402
Christopher Tate2982d062011-09-06 20:35:24 -07004403 PackageInfo packageInfo;
4404 try {
4405 int flags = PackageManager.GET_SIGNATURES;
4406 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4407 } catch (NameNotFoundException e) {
4408 Slog.e(TAG, "Invalid package restoring data", e);
4409 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4410 "Package missing on device");
4411 executeNextState(RestoreState.RUNNING_QUEUE);
4412 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004413 }
4414
Christopher Tate2982d062011-09-06 20:35:24 -07004415 if (metaInfo.versionCode > packageInfo.versionCode) {
4416 // Data is from a "newer" version of the app than we have currently
4417 // installed. If the app has not declared that it is prepared to
4418 // handle this case, we do not attempt the restore.
4419 if ((packageInfo.applicationInfo.flags
4420 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4421 String message = "Version " + metaInfo.versionCode
4422 + " > installed version " + packageInfo.versionCode;
4423 Slog.w(TAG, "Package " + packageName + ": " + message);
4424 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4425 packageName, message);
4426 executeNextState(RestoreState.RUNNING_QUEUE);
4427 return;
4428 } else {
4429 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4430 + " > installed " + packageInfo.versionCode
4431 + " but restoreAnyVersion");
4432 }
4433 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004434
Christopher Tate2982d062011-09-06 20:35:24 -07004435 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4436 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4437 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4438 "Signature mismatch");
4439 executeNextState(RestoreState.RUNNING_QUEUE);
4440 return;
4441 }
4442
4443 if (DEBUG) Slog.v(TAG, "Package " + packageName
4444 + " restore version [" + metaInfo.versionCode
4445 + "] is compatible with installed version ["
4446 + packageInfo.versionCode + "]");
4447
4448 // Then set up and bind the agent
4449 IBackupAgent agent = bindToAgentSynchronous(
4450 packageInfo.applicationInfo,
4451 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4452 if (agent == null) {
4453 Slog.w(TAG, "Can't find backup agent for " + packageName);
4454 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4455 "Restore agent missing");
4456 executeNextState(RestoreState.RUNNING_QUEUE);
4457 return;
4458 }
4459
4460 // And then finally start the restore on this agent
4461 try {
4462 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4463 ++mCount;
4464 } catch (Exception e) {
4465 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4466 agentErrorCleanup();
4467 executeNextState(RestoreState.RUNNING_QUEUE);
4468 }
4469 } catch (RemoteException e) {
4470 Slog.e(TAG, "Unable to fetch restore data from transport");
4471 mStatus = BackupConstants.TRANSPORT_ERROR;
4472 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004473 }
4474 }
4475
Christopher Tate2982d062011-09-06 20:35:24 -07004476 void finalizeRestore() {
4477 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4478
4479 try {
4480 mTransport.finishRestore();
4481 } catch (RemoteException e) {
4482 Slog.e(TAG, "Error finishing restore", e);
4483 }
4484
4485 if (mObserver != null) {
4486 try {
4487 mObserver.restoreFinished(mStatus);
4488 } catch (RemoteException e) {
4489 Slog.d(TAG, "Restore observer died at restoreFinished");
4490 }
4491 }
4492
4493 // If this was a restoreAll operation, record that this was our
4494 // ancestral dataset, as well as the set of apps that are possibly
4495 // restoreable from the dataset
4496 if (mTargetPackage == null && mPmAgent != null) {
4497 mAncestralPackages = mPmAgent.getRestoredPackages();
4498 mAncestralToken = mToken;
4499 writeRestoreTokens();
4500 }
4501
4502 // We must under all circumstances tell the Package Manager to
4503 // proceed with install notifications if it's waiting for us.
4504 if (mPmToken > 0) {
4505 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4506 try {
4507 mPackageManagerBinder.finishPackageInstall(mPmToken);
4508 } catch (RemoteException e) { /* can't happen */ }
4509 }
4510
4511 // Furthermore we need to reset the session timeout clock
4512 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4513 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4514 TIMEOUT_RESTORE_INTERVAL);
4515
4516 // done; we can finally release the wakelock
4517 Slog.i(TAG, "Restore complete.");
4518 mWakelock.release();
4519 }
4520
4521 // Call asynchronously into the app, passing it the restore data. The next step
4522 // after this is always a callback, either operationComplete() or handleTimeout().
4523 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004524 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004525 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004526 final String packageName = app.packageName;
4527
Christopher Tate2982d062011-09-06 20:35:24 -07004528 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004529
Christopher Tatec7b31e32009-06-10 15:49:30 -07004530 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004531 mBackupDataName = new File(mDataDir, packageName + ".restore");
4532 mNewStateName = new File(mStateDir, packageName + ".new");
4533 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004534
Christopher Tate4a627c72011-04-01 14:43:32 -07004535 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004536 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004537 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004538 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004539 ParcelFileDescriptor.MODE_READ_WRITE |
4540 ParcelFileDescriptor.MODE_CREATE |
4541 ParcelFileDescriptor.MODE_TRUNCATE);
4542
Christopher Tate2982d062011-09-06 20:35:24 -07004543 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004544 // Transport-level failure, so we wind everything up and
4545 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004546 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004547 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004548 mBackupData.close();
4549 mBackupDataName.delete();
4550 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004551 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004552 }
4553
4554 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004555 mBackupData.close();
4556 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004557 ParcelFileDescriptor.MODE_READ_ONLY);
4558
Christopher Tate2982d062011-09-06 20:35:24 -07004559 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004560 ParcelFileDescriptor.MODE_READ_WRITE |
4561 ParcelFileDescriptor.MODE_CREATE |
4562 ParcelFileDescriptor.MODE_TRUNCATE);
4563
Christopher Tate44a27902010-01-27 17:15:49 -08004564 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004565 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4566 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004567 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004568 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004569 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004570 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004571
Christopher Tate2982d062011-09-06 20:35:24 -07004572 // After a restore failure we go back to running the queue. If there
4573 // are no more packages to be restored that will be handled by the
4574 // next step.
4575 executeNextState(RestoreState.RUNNING_QUEUE);
4576 }
4577 }
Chris Tate249345b2010-10-29 12:57:04 -07004578
Christopher Tate2982d062011-09-06 20:35:24 -07004579 void agentErrorCleanup() {
4580 // If the agent fails restore, it might have put the app's data
4581 // into an incoherent state. For consistency we wipe its data
4582 // again in this case before continuing with normal teardown
4583 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4584 agentCleanup();
4585 }
4586
4587 void agentCleanup() {
4588 mBackupDataName.delete();
4589 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4590 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4591 mBackupData = mNewState = null;
4592
4593 // if everything went okay, remember the recorded state now
4594 //
4595 // !!! TODO: the restored data should be migrated on the server
4596 // side into the current dataset. In that case the new state file
4597 // we just created would reflect the data already extant in the
4598 // backend, so there'd be nothing more to do. Until that happens,
4599 // however, we need to make sure that we record the data to the
4600 // current backend dataset. (Yes, this means shipping the data over
4601 // the wire in both directions. That's bad, but consistency comes
4602 // first, then efficiency.) Once we introduce server-side data
4603 // migration to the newly-restored device's dataset, we will change
4604 // the following from a discard of the newly-written state to the
4605 // "correct" operation of renaming into the canonical state blob.
4606 mNewStateName.delete(); // TODO: remove; see above comment
4607 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4608
4609 // If this wasn't the PM pseudopackage, tear down the agent side
4610 if (mCurrentPackage.applicationInfo != null) {
4611 // unbind and tidy up even on timeout or failure
4612 try {
4613 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4614
4615 // The agent was probably running with a stub Application object,
4616 // which isn't a valid run mode for the main app logic. Shut
4617 // down the app so that next time it's launched, it gets the
4618 // usual full initialization. Note that this is only done for
4619 // full-system restores: when a single app has requested a restore,
4620 // it is explicitly not killed following that operation.
4621 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4622 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4623 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4624 + mCurrentPackage.applicationInfo.processName);
4625 mActivityManager.killApplicationProcess(
4626 mCurrentPackage.applicationInfo.processName,
4627 mCurrentPackage.applicationInfo.uid);
4628 }
4629 } catch (RemoteException e) {
4630 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004631 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004632 }
Christopher Tate2982d062011-09-06 20:35:24 -07004633
4634 // The caller is responsible for reestablishing the state machine; our
4635 // responsibility here is to clear the decks for whatever comes next.
4636 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4637 synchronized (mCurrentOpLock) {
4638 mCurrentOperations.clear();
4639 }
4640 }
4641
4642 // A call to agent.doRestore() has been positively acknowledged as complete
4643 @Override
4644 public void operationComplete() {
4645 int size = (int) mBackupDataName.length();
4646 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4647 // Just go back to running the restore queue
4648 agentCleanup();
4649
4650 executeNextState(RestoreState.RUNNING_QUEUE);
4651 }
4652
4653 // A call to agent.doRestore() has timed out
4654 @Override
4655 public void handleTimeout() {
4656 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4657 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4658 mCurrentPackage.packageName, "restore timeout");
4659 // Handle like an agent that threw on invocation: wipe it and go on to the next
4660 agentErrorCleanup();
4661 executeNextState(RestoreState.RUNNING_QUEUE);
4662 }
4663
4664 void executeNextState(RestoreState nextState) {
4665 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4666 + this + " nextState=" + nextState);
4667 mCurrentState = nextState;
4668 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4669 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004670 }
4671 }
4672
Christopher Tate44a27902010-01-27 17:15:49 -08004673 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004674 IBackupTransport mTransport;
4675 PackageInfo mPackage;
4676
Christopher Tate44a27902010-01-27 17:15:49 -08004677 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004678 mTransport = transport;
4679 mPackage = packageInfo;
4680 }
4681
Christopher Tateee0e78a2009-07-02 11:17:03 -07004682 public void run() {
4683 try {
4684 // Clear the on-device backup state to ensure a full backup next time
4685 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4686 File stateFile = new File(stateDir, mPackage.packageName);
4687 stateFile.delete();
4688
4689 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004690 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004691 mTransport.clearBackupData(mPackage);
4692 } catch (RemoteException e) {
4693 // can't happen; the transport is local
4694 } finally {
4695 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004696 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004697 mTransport.finishBackup();
4698 } catch (RemoteException e) {
4699 // can't happen; the transport is local
4700 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004701
4702 // Last but not least, release the cpu
4703 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004704 }
4705 }
4706 }
4707
Christopher Tate44a27902010-01-27 17:15:49 -08004708 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004709 HashSet<String> mQueue;
4710
Christopher Tate44a27902010-01-27 17:15:49 -08004711 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004712 mQueue = transportNames;
4713 }
4714
Christopher Tate4cc86e12009-09-21 19:36:51 -07004715 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004716 try {
4717 for (String transportName : mQueue) {
4718 IBackupTransport transport = getTransport(transportName);
4719 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004720 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004721 continue;
4722 }
4723
Joe Onorato8a9b2202010-02-26 18:56:32 -08004724 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004725 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004726 long startRealtime = SystemClock.elapsedRealtime();
4727 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004728
Christopher Tate4cc86e12009-09-21 19:36:51 -07004729 if (status == BackupConstants.TRANSPORT_OK) {
4730 status = transport.finishBackup();
4731 }
4732
4733 // Okay, the wipe really happened. Clean up our local bookkeeping.
4734 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004735 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004736 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004737 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004738 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004739 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004740 synchronized (mQueueLock) {
4741 recordInitPendingLocked(false, transportName);
4742 }
Dan Egnor726247c2009-09-29 19:12:31 -07004743 } else {
4744 // If this didn't work, requeue this one and try again
4745 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004746 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004747 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004748 synchronized (mQueueLock) {
4749 recordInitPendingLocked(true, transportName);
4750 }
4751 // do this via another alarm to make sure of the wakelock states
4752 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004753 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004754 + transportName + " resched in " + delay);
4755 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4756 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004757 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004758 }
4759 } catch (RemoteException e) {
4760 // can't happen; the transports are local
4761 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004762 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004763 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004764 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004765 mWakelock.release();
4766 }
4767 }
4768 }
4769
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004770 private void dataChangedImpl(String packageName) {
4771 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4772 dataChangedImpl(packageName, targets);
4773 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004774
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004775 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004776 // Record that we need a backup pass for the caller. Since multiple callers
4777 // may share a uid, we need to note all candidates within that uid and schedule
4778 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004779 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004780
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004781 if (targets == null) {
4782 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4783 + " uid=" + Binder.getCallingUid());
4784 return;
4785 }
4786
4787 synchronized (mQueueLock) {
4788 // Note that this client has made data changes that need to be backed up
4789 for (ApplicationInfo app : targets) {
4790 // validate the caller-supplied package name against the known set of
4791 // packages associated with this uid
4792 if (app.packageName.equals(packageName)) {
4793 // Add the caller to the set of pending backups. If there is
4794 // one already there, then overwrite it, but no harm done.
Christopher Tatecc55f812011-08-16 16:06:53 -07004795 BackupRequest req = new BackupRequest(packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08004796 if (mPendingBackups.put(app.packageName, req) == null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08004797 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
4798
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004799 // Journal this request in case of crash. The put()
4800 // operation returned null when this package was not already
4801 // in the set; we want to avoid touching the disk redundantly.
4802 writeToJournalLocked(packageName);
4803
Christopher Tatec58efa62011-08-01 19:20:14 -07004804 if (MORE_DEBUG) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004805 int numKeys = mPendingBackups.size();
4806 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4807 for (BackupRequest b : mPendingBackups.values()) {
Christopher Tatecc55f812011-08-16 16:06:53 -07004808 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004809 }
4810 }
4811 }
4812 }
4813 }
4814 }
4815 }
4816
4817 // Note: packageName is currently unused, but may be in the future
4818 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004819 // If the caller does not hold the BACKUP permission, it can only request a
4820 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004821 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004822 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004823 synchronized (mBackupParticipants) {
4824 return mBackupParticipants.get(Binder.getCallingUid());
4825 }
4826 }
4827
4828 // a caller with full permission can ask to back up any participating app
4829 // !!! TODO: allow backup of ANY app?
4830 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4831 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004832 int N = mBackupParticipants.size();
4833 for (int i = 0; i < N; i++) {
4834 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4835 if (s != null) {
4836 targets.addAll(s);
4837 }
4838 }
4839 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004840 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004841 }
Christopher Tate46758122009-05-06 11:22:00 -07004842
Christopher Tatecde87f42009-06-12 12:55:53 -07004843 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004844 RandomAccessFile out = null;
4845 try {
4846 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4847 out = new RandomAccessFile(mJournal, "rws");
4848 out.seek(out.length());
4849 out.writeUTF(str);
4850 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004851 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004852 mJournal = null;
4853 } finally {
4854 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004855 }
4856 }
4857
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004858 // ----- IBackupManager binder interface -----
4859
4860 public void dataChanged(final String packageName) {
4861 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4862 if (targets == null) {
4863 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4864 + " uid=" + Binder.getCallingUid());
4865 return;
4866 }
4867
4868 mBackupHandler.post(new Runnable() {
4869 public void run() {
4870 dataChangedImpl(packageName, targets);
4871 }
4872 });
4873 }
4874
Christopher Tateee0e78a2009-07-02 11:17:03 -07004875 // Clear the given package's backup data from the current transport
4876 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004877 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004878 PackageInfo info;
4879 try {
4880 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4881 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004882 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004883 return;
4884 }
4885
4886 // If the caller does not hold the BACKUP permission, it can only request a
4887 // wipe of its own backed-up data.
4888 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004889 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004890 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4891 apps = mBackupParticipants.get(Binder.getCallingUid());
4892 } else {
4893 // a caller with full permission can ask to back up any participating app
4894 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004895 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004896 apps = new HashSet<ApplicationInfo>();
4897 int N = mBackupParticipants.size();
4898 for (int i = 0; i < N; i++) {
4899 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4900 if (s != null) {
4901 apps.addAll(s);
4902 }
4903 }
4904 }
4905
4906 // now find the given package in the set of candidate apps
4907 for (ApplicationInfo app : apps) {
4908 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004909 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004910 // found it; fire off the clear request
4911 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004912 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004913 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004914 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4915 new ClearParams(getTransport(mCurrentTransport), info));
4916 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004917 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004918 }
4919 break;
4920 }
4921 }
4922 }
4923
Christopher Tateace7f092009-06-15 18:07:25 -07004924 // Run a backup pass immediately for any applications that have declared
4925 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004926 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004927 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004928
Joe Onorato8a9b2202010-02-26 18:56:32 -08004929 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004930 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004931 // Because the alarms we are using can jitter, and we want an *immediate*
4932 // backup pass to happen, we restart the timer beginning with "next time,"
4933 // then manually fire the backup trigger intent ourselves.
4934 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004935 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004936 mRunBackupIntent.send();
4937 } catch (PendingIntent.CanceledException e) {
4938 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004939 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004940 }
Christopher Tate46758122009-05-06 11:22:00 -07004941 }
4942 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004943
Christopher Tated2c0cd42011-09-15 15:51:29 -07004944 boolean deviceIsProvisioned() {
4945 final ContentResolver resolver = mContext.getContentResolver();
4946 return (Settings.Secure.getInt(resolver, Settings.Secure.DEVICE_PROVISIONED, 0) != 0);
4947 }
4948
Christopher Tate4a627c72011-04-01 14:43:32 -07004949 // Run a *full* backup pass for the given package, writing the resulting data stream
4950 // to the supplied file descriptor. This method is synchronous and does not return
4951 // to the caller until the backup has been completed.
4952 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004953 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004954 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4955
4956 // Validate
4957 if (!doAllApps) {
4958 if (!includeShared) {
4959 // If we're backing up shared data (sdcard or equivalent), then we can run
4960 // without any supplied app names. Otherwise, we'd be doing no work, so
4961 // report the error.
4962 if (pkgList == null || pkgList.length == 0) {
4963 throw new IllegalArgumentException(
4964 "Backup requested but neither shared nor any apps named");
4965 }
4966 }
4967 }
4968
Christopher Tate4a627c72011-04-01 14:43:32 -07004969 long oldId = Binder.clearCallingIdentity();
4970 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07004971 // Doesn't make sense to do a full backup prior to setup
4972 if (!deviceIsProvisioned()) {
4973 Slog.i(TAG, "Full backup not supported before setup");
4974 return;
4975 }
4976
4977 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4978 + " shared=" + includeShared + " all=" + doAllApps
4979 + " pkgs=" + pkgList);
4980 Slog.i(TAG, "Beginning full backup...");
4981
Christopher Tate4a627c72011-04-01 14:43:32 -07004982 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004983 doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07004984 final int token = generateToken();
4985 synchronized (mFullConfirmations) {
4986 mFullConfirmations.put(token, params);
4987 }
4988
Christopher Tate75a99702011-05-18 16:28:19 -07004989 // start up the confirmation UI
4990 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4991 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4992 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004993 mFullConfirmations.delete(token);
4994 return;
4995 }
Christopher Tate75a99702011-05-18 16:28:19 -07004996
4997 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004998 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4999
5000 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07005001 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005002
5003 // wait for the backup to be performed
5004 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
5005 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07005006 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07005007 try {
5008 fd.close();
5009 } catch (IOException e) {
5010 // just eat it
5011 }
Christopher Tate75a99702011-05-18 16:28:19 -07005012 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005013 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07005014 }
Christopher Tate75a99702011-05-18 16:28:19 -07005015 }
5016
5017 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07005018 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07005019
5020 long oldId = Binder.clearCallingIdentity();
5021
5022 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005023 // Check whether the device has been provisioned -- we don't handle
5024 // full restores prior to completing the setup process.
5025 if (!deviceIsProvisioned()) {
5026 Slog.i(TAG, "Full restore not permitted before setup");
5027 return;
5028 }
5029
5030 Slog.i(TAG, "Beginning full restore...");
5031
Christopher Tate75a99702011-05-18 16:28:19 -07005032 FullRestoreParams params = new FullRestoreParams(fd);
5033 final int token = generateToken();
5034 synchronized (mFullConfirmations) {
5035 mFullConfirmations.put(token, params);
5036 }
5037
5038 // start up the confirmation UI
5039 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5040 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5041 Slog.e(TAG, "Unable to launch full restore confirmation");
5042 mFullConfirmations.delete(token);
5043 return;
5044 }
5045
5046 // make sure the screen is lit for the user interaction
5047 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5048
5049 // start the confirmation countdown
5050 startConfirmationTimeout(token, params);
5051
5052 // wait for the restore to be performed
5053 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5054 waitForCompletion(params);
5055 } finally {
5056 try {
5057 fd.close();
5058 } catch (IOException e) {
5059 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5060 }
5061 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005062 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07005063 }
5064 }
5065
5066 boolean startConfirmationUi(int token, String action) {
5067 try {
5068 Intent confIntent = new Intent(action);
5069 confIntent.setClassName("com.android.backupconfirm",
5070 "com.android.backupconfirm.BackupRestoreConfirmation");
5071 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5072 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5073 mContext.startActivity(confIntent);
5074 } catch (ActivityNotFoundException e) {
5075 return false;
5076 }
5077 return true;
5078 }
5079
5080 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07005081 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07005082 + TIMEOUT_FULL_CONFIRMATION + " millis");
5083 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5084 token, 0, params);
5085 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07005086 }
5087
5088 void waitForCompletion(FullParams params) {
5089 synchronized (params.latch) {
5090 while (params.latch.get() == false) {
5091 try {
5092 params.latch.wait();
5093 } catch (InterruptedException e) { /* never interrupted */ }
5094 }
5095 }
5096 }
5097
5098 void signalFullBackupRestoreCompletion(FullParams params) {
5099 synchronized (params.latch) {
5100 params.latch.set(true);
5101 params.latch.notifyAll();
5102 }
5103 }
5104
5105 // Confirm that the previously-requested full backup/restore operation can proceed. This
5106 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07005107 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07005108 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07005109 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005110 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5111 + " allow=" + allow);
5112
5113 // TODO: possibly require not just this signature-only permission, but even
5114 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07005115 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07005116
5117 long oldId = Binder.clearCallingIdentity();
5118 try {
5119
5120 FullParams params;
5121 synchronized (mFullConfirmations) {
5122 params = mFullConfirmations.get(token);
5123 if (params != null) {
5124 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5125 mFullConfirmations.delete(token);
5126
5127 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005128 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005129 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005130 : MSG_RUN_FULL_RESTORE;
5131
Christopher Tate728a1c42011-07-28 18:03:03 -07005132 params.observer = observer;
5133 params.curPassword = curPassword;
Christopher Tate32418be2011-10-10 13:51:12 -07005134
5135 boolean isEncrypted;
5136 try {
5137 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
5138 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5139 } catch (RemoteException e) {
5140 // couldn't contact the mount service; fail "safe" and assume encryption
5141 Slog.e(TAG, "Unable to contact mount service!");
5142 isEncrypted = true;
5143 }
5144 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
Christopher Tate728a1c42011-07-28 18:03:03 -07005145
Christopher Tate75a99702011-05-18 16:28:19 -07005146 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005147 mWakelock.acquire();
5148 Message msg = mBackupHandler.obtainMessage(verb, params);
5149 mBackupHandler.sendMessage(msg);
5150 } else {
5151 Slog.w(TAG, "User rejected full backup/restore operation");
5152 // indicate completion without having actually transferred any data
5153 signalFullBackupRestoreCompletion(params);
5154 }
5155 } else {
5156 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5157 }
5158 }
5159 } finally {
5160 Binder.restoreCallingIdentity(oldId);
5161 }
5162 }
5163
Christopher Tate8031a3d2009-07-06 16:36:05 -07005164 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005165 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005166 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005167 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005168
Joe Onorato8a9b2202010-02-26 18:56:32 -08005169 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005170
Christopher Tate6ef58a12009-06-29 14:56:28 -07005171 boolean wasEnabled = mEnabled;
5172 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005173 Settings.Secure.putInt(mContext.getContentResolver(),
5174 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005175 mEnabled = enable;
5176 }
5177
Christopher Tate49401dd2009-07-01 12:34:29 -07005178 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005179 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005180 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005181 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005182 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005183 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005184 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005185
Christopher Tateb6787f22009-07-02 17:40:45 -07005186 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005187
5188 // This also constitutes an opt-out, so we wipe any data for
5189 // this device from the backend. We start that process with
5190 // an alarm in order to guarantee wakelock states.
5191 if (wasEnabled && mProvisioned) {
5192 // NOTE: we currently flush every registered transport, not just
5193 // the currently-active one.
5194 HashSet<String> allTransports;
5195 synchronized (mTransports) {
5196 allTransports = new HashSet<String>(mTransports.keySet());
5197 }
5198 // build the set of transports for which we are posting an init
5199 for (String transport : allTransports) {
5200 recordInitPendingLocked(true, transport);
5201 }
5202 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5203 mRunInitIntent);
5204 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005205 }
5206 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005207 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005208
Christopher Tatecce9da52010-02-03 15:11:15 -08005209 // Enable/disable automatic restore of app data at install time
5210 public void setAutoRestore(boolean doAutoRestore) {
5211 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005212 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005213
Joe Onorato8a9b2202010-02-26 18:56:32 -08005214 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005215
5216 synchronized (this) {
5217 Settings.Secure.putInt(mContext.getContentResolver(),
5218 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5219 mAutoRestore = doAutoRestore;
5220 }
5221 }
5222
Christopher Tate8031a3d2009-07-06 16:36:05 -07005223 // Mark the backup service as having been provisioned
5224 public void setBackupProvisioned(boolean available) {
5225 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5226 "setBackupProvisioned");
5227
5228 boolean wasProvisioned = mProvisioned;
5229 synchronized (this) {
5230 Settings.Secure.putInt(mContext.getContentResolver(),
5231 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
5232 mProvisioned = available;
5233 }
5234
5235 synchronized (mQueueLock) {
5236 if (available && !wasProvisioned && mEnabled) {
5237 // we're now good to go, so start the backup alarms
5238 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
5239 } else if (!available) {
5240 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005241 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07005242 mAlarmManager.cancel(mRunBackupIntent);
5243 }
5244 }
5245 }
5246
5247 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005248 // We used to use setInexactRepeating(), but that may be linked to
5249 // backups running at :00 more often than not, creating load spikes.
5250 // Schedule at an exact time for now, and also add a bit of "fuzz".
5251
5252 Random random = new Random();
5253 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5254 random.nextInt(FUZZ_MILLIS);
5255 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5256 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005257 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005258 }
5259
Christopher Tate6ef58a12009-06-29 14:56:28 -07005260 // Report whether the backup mechanism is currently enabled
5261 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005262 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005263 return mEnabled; // no need to synchronize just to read it
5264 }
5265
Christopher Tate91717492009-06-26 21:07:13 -07005266 // Report the name of the currently active transport
5267 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005268 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005269 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005270 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005271 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005272 }
5273
Christopher Tate91717492009-06-26 21:07:13 -07005274 // Report all known, available backup transports
5275 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005276 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005277
Christopher Tate91717492009-06-26 21:07:13 -07005278 String[] list = null;
5279 ArrayList<String> known = new ArrayList<String>();
5280 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5281 if (entry.getValue() != null) {
5282 known.add(entry.getKey());
5283 }
5284 }
5285
5286 if (known.size() > 0) {
5287 list = new String[known.size()];
5288 known.toArray(list);
5289 }
5290 return list;
5291 }
5292
5293 // Select which transport to use for the next backup operation. If the given
5294 // name is not one of the available transports, no action is taken and the method
5295 // returns null.
5296 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005297 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005298
5299 synchronized (mTransports) {
5300 String prevTransport = null;
5301 if (mTransports.get(transport) != null) {
5302 prevTransport = mCurrentTransport;
5303 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005304 Settings.Secure.putString(mContext.getContentResolver(),
5305 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005306 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005307 + " returning " + prevTransport);
5308 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005309 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005310 }
5311 return prevTransport;
5312 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005313 }
5314
Christopher Tatef5e1c292010-12-08 18:40:26 -08005315 // Supply the configuration Intent for the given transport. If the name is not one
5316 // of the available transports, or if the transport does not supply any configuration
5317 // UI, the method returns null.
5318 public Intent getConfigurationIntent(String transportName) {
5319 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5320 "getConfigurationIntent");
5321
5322 synchronized (mTransports) {
5323 final IBackupTransport transport = mTransports.get(transportName);
5324 if (transport != null) {
5325 try {
5326 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005327 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005328 + intent);
5329 return intent;
5330 } catch (RemoteException e) {
5331 /* fall through to return null */
5332 }
5333 }
5334 }
5335
5336 return null;
5337 }
5338
5339 // Supply the configuration summary string for the given transport. If the name is
5340 // not one of the available transports, or if the transport does not supply any
5341 // summary / destination string, the method can return null.
5342 //
5343 // This string is used VERBATIM as the summary text of the relevant Settings item!
5344 public String getDestinationString(String transportName) {
5345 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005346 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005347
5348 synchronized (mTransports) {
5349 final IBackupTransport transport = mTransports.get(transportName);
5350 if (transport != null) {
5351 try {
5352 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005353 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005354 return text;
5355 } catch (RemoteException e) {
5356 /* fall through to return null */
5357 }
5358 }
5359 }
5360
5361 return null;
5362 }
5363
Christopher Tate043dadc2009-06-02 16:11:00 -07005364 // Callback: a requested backup agent has been instantiated. This should only
5365 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005366 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005367 synchronized(mAgentConnectLock) {
5368 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005369 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005370 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5371 mConnectedAgent = agent;
5372 mConnecting = false;
5373 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005374 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005375 + " claiming agent connected");
5376 }
5377 mAgentConnectLock.notifyAll();
5378 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005379 }
5380
5381 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5382 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005383 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005384 public void agentDisconnected(String packageName) {
5385 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005386 synchronized(mAgentConnectLock) {
5387 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5388 mConnectedAgent = null;
5389 mConnecting = false;
5390 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005391 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005392 + " claiming agent disconnected");
5393 }
5394 mAgentConnectLock.notifyAll();
5395 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005396 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005397
Christopher Tate1bb69062010-02-19 17:02:12 -08005398 // An application being installed will need a restore pass, then the Package Manager
5399 // will need to be told when the restore is finished.
5400 public void restoreAtInstall(String packageName, int token) {
5401 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005402 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005403 + " attemping install-time restore");
5404 return;
5405 }
5406
5407 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005408 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08005409 + " token=" + Integer.toHexString(token));
5410
Christopher Tatef0872722010-02-25 15:22:48 -08005411 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005412 // okay, we're going to attempt a restore of this package from this restore set.
5413 // The eventual message back into the Package Manager to run the post-install
5414 // steps for 'token' will be issued from the restore handling code.
5415
5416 // We can use a synthetic PackageInfo here because:
5417 // 1. We know it's valid, since the Package Manager supplied the name
5418 // 2. Only the packageName field will be used by the restore code
5419 PackageInfo pkg = new PackageInfo();
5420 pkg.packageName = packageName;
5421
5422 mWakelock.acquire();
5423 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5424 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005425 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005426 mBackupHandler.sendMessage(msg);
5427 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005428 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5429 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005430 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005431 try {
5432 mPackageManagerBinder.finishPackageInstall(token);
5433 } catch (RemoteException e) { /* can't happen */ }
5434 }
5435 }
5436
Christopher Tate8c850b72009-06-07 19:33:20 -07005437 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005438 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5439 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5440 + " transport=" + transport);
5441
5442 boolean needPermission = true;
5443 if (transport == null) {
5444 transport = mCurrentTransport;
5445
5446 if (packageName != null) {
5447 PackageInfo app = null;
5448 try {
5449 app = mPackageManager.getPackageInfo(packageName, 0);
5450 } catch (NameNotFoundException nnf) {
5451 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5452 throw new IllegalArgumentException("Package " + packageName + " not found");
5453 }
5454
5455 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5456 // So: using the current active transport, and the caller has asked
5457 // that its own package will be restored. In this narrow use case
5458 // we do not require the caller to hold the permission.
5459 needPermission = false;
5460 }
5461 }
5462 }
5463
5464 if (needPermission) {
5465 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5466 "beginRestoreSession");
5467 } else {
5468 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5469 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005470
5471 synchronized(this) {
5472 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005473 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005474 return null;
5475 }
Chris Tate44ab8452010-11-16 15:10:49 -08005476 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005477 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005478 }
5479 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005480 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005481
Christopher Tate73a3cb32010-12-13 18:27:26 -08005482 void clearRestoreSession(ActiveRestoreSession currentSession) {
5483 synchronized(this) {
5484 if (currentSession != mActiveRestoreSession) {
5485 Slog.e(TAG, "ending non-current restore session");
5486 } else {
5487 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5488 mActiveRestoreSession = null;
5489 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5490 }
5491 }
5492 }
5493
Christopher Tate44a27902010-01-27 17:15:49 -08005494 // Note that a currently-active backup agent has notified us that it has
5495 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005496 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005497 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005498 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5499 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005500 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005501 op = mCurrentOperations.get(token);
5502 if (op != null) {
5503 op.state = OP_ACKNOWLEDGED;
5504 }
Christopher Tate44a27902010-01-27 17:15:49 -08005505 mCurrentOpLock.notifyAll();
5506 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005507
5508 // The completion callback, if any, is invoked on the handler
5509 if (op != null && op.callback != null) {
5510 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5511 mBackupHandler.sendMessage(msg);
5512 }
Christopher Tate44a27902010-01-27 17:15:49 -08005513 }
5514
Christopher Tate9b3905c2009-06-08 15:24:01 -07005515 // ----- Restore session -----
5516
Christopher Tate80202c82010-01-25 19:37:47 -08005517 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005518 private static final String TAG = "RestoreSession";
5519
Chris Tate44ab8452010-11-16 15:10:49 -08005520 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005521 private IBackupTransport mRestoreTransport = null;
5522 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005523 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005524
Chris Tate44ab8452010-11-16 15:10:49 -08005525 ActiveRestoreSession(String packageName, String transport) {
5526 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005527 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005528 }
5529
5530 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005531 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005532 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005533 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005534 if (observer == null) {
5535 throw new IllegalArgumentException("Observer must not be null");
5536 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005537
Christopher Tate73a3cb32010-12-13 18:27:26 -08005538 if (mEnded) {
5539 throw new IllegalStateException("Restore session already ended");
5540 }
5541
Christopher Tate1bb69062010-02-19 17:02:12 -08005542 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005543 try {
Christopher Tate43383042009-07-13 15:17:13 -07005544 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005545 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005546 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005547 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005548 // spin off the transport request to our service thread
5549 mWakelock.acquire();
5550 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5551 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5552 mBackupHandler.sendMessage(msg);
5553 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005554 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005555 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005556 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005557 } finally {
5558 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005559 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005560 }
5561
Christopher Tate84725812010-02-04 15:52:40 -08005562 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005563 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5564 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005565
Chris Tate44ab8452010-11-16 15:10:49 -08005566 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005567 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005568
Christopher Tate73a3cb32010-12-13 18:27:26 -08005569 if (mEnded) {
5570 throw new IllegalStateException("Restore session already ended");
5571 }
5572
Dan Egnor0084da52009-07-29 12:57:16 -07005573 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005574 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5575 return -1;
5576 }
5577
5578 if (mPackageName != null) {
5579 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005580 return -1;
5581 }
5582
Christopher Tate21ab6a52009-09-24 18:01:46 -07005583 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005584 for (int i = 0; i < mRestoreSets.length; i++) {
5585 if (token == mRestoreSets[i].token) {
5586 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005587 mWakelock.acquire();
5588 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005589 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005590 mBackupHandler.sendMessage(msg);
5591 Binder.restoreCallingIdentity(oldId);
5592 return 0;
5593 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005594 }
5595 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005596
Joe Onorato8a9b2202010-02-26 18:56:32 -08005597 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005598 return -1;
5599 }
5600
Christopher Tate284f1bb2011-07-07 14:31:18 -07005601 public synchronized int restoreSome(long token, IRestoreObserver observer,
5602 String[] packages) {
5603 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5604 "performRestore");
5605
5606 if (DEBUG) {
5607 StringBuilder b = new StringBuilder(128);
5608 b.append("restoreSome token=");
5609 b.append(Long.toHexString(token));
5610 b.append(" observer=");
5611 b.append(observer.toString());
5612 b.append(" packages=");
5613 if (packages == null) {
5614 b.append("null");
5615 } else {
5616 b.append('{');
5617 boolean first = true;
5618 for (String s : packages) {
5619 if (!first) {
5620 b.append(", ");
5621 } else first = false;
5622 b.append(s);
5623 }
5624 b.append('}');
5625 }
5626 Slog.d(TAG, b.toString());
5627 }
5628
5629 if (mEnded) {
5630 throw new IllegalStateException("Restore session already ended");
5631 }
5632
5633 if (mRestoreTransport == null || mRestoreSets == null) {
5634 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5635 return -1;
5636 }
5637
5638 if (mPackageName != null) {
5639 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5640 return -1;
5641 }
5642
5643 synchronized (mQueueLock) {
5644 for (int i = 0; i < mRestoreSets.length; i++) {
5645 if (token == mRestoreSets[i].token) {
5646 long oldId = Binder.clearCallingIdentity();
5647 mWakelock.acquire();
5648 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5649 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5650 packages, true);
5651 mBackupHandler.sendMessage(msg);
5652 Binder.restoreCallingIdentity(oldId);
5653 return 0;
5654 }
5655 }
5656 }
5657
5658 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5659 return -1;
5660 }
5661
Christopher Tate84725812010-02-04 15:52:40 -08005662 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005663 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005664
Christopher Tate73a3cb32010-12-13 18:27:26 -08005665 if (mEnded) {
5666 throw new IllegalStateException("Restore session already ended");
5667 }
5668
Chris Tate44ab8452010-11-16 15:10:49 -08005669 if (mPackageName != null) {
5670 if (! mPackageName.equals(packageName)) {
5671 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5672 + " on session for package " + mPackageName);
5673 return -1;
5674 }
5675 }
5676
Christopher Tate84725812010-02-04 15:52:40 -08005677 PackageInfo app = null;
5678 try {
5679 app = mPackageManager.getPackageInfo(packageName, 0);
5680 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005681 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005682 return -1;
5683 }
5684
5685 // If the caller is not privileged and is not coming from the target
5686 // app's uid, throw a permission exception back to the caller.
5687 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5688 Binder.getCallingPid(), Binder.getCallingUid());
5689 if ((perm == PackageManager.PERMISSION_DENIED) &&
5690 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005691 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005692 + " or calling uid=" + Binder.getCallingUid());
5693 throw new SecurityException("No permission to restore other packages");
5694 }
5695
Christopher Tate7d411a32010-02-26 11:27:08 -08005696 // If the package has no backup agent, we obviously cannot proceed
5697 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005698 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005699 return -1;
5700 }
5701
Christopher Tate84725812010-02-04 15:52:40 -08005702 // So far so good; we're allowed to try to restore this package. Now
5703 // check whether there is data for it in the current dataset, falling back
5704 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005705 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005706
5707 // If we didn't come up with a place to look -- no ancestral dataset and
5708 // the app has never been backed up from this device -- there's nothing
5709 // to do but return failure.
5710 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005711 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005712 return -1;
5713 }
5714
5715 // Ready to go: enqueue the restore request and claim success
5716 long oldId = Binder.clearCallingIdentity();
5717 mWakelock.acquire();
5718 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005719 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005720 mBackupHandler.sendMessage(msg);
5721 Binder.restoreCallingIdentity(oldId);
5722 return 0;
5723 }
5724
Christopher Tate73a3cb32010-12-13 18:27:26 -08005725 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5726 class EndRestoreRunnable implements Runnable {
5727 BackupManagerService mBackupManager;
5728 ActiveRestoreSession mSession;
5729
5730 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5731 mBackupManager = manager;
5732 mSession = session;
5733 }
5734
5735 public void run() {
5736 // clean up the session's bookkeeping
5737 synchronized (mSession) {
5738 try {
5739 if (mSession.mRestoreTransport != null) {
5740 mSession.mRestoreTransport.finishRestore();
5741 }
5742 } catch (Exception e) {
5743 Slog.e(TAG, "Error in finishRestore", e);
5744 } finally {
5745 mSession.mRestoreTransport = null;
5746 mSession.mEnded = true;
5747 }
5748 }
5749
5750 // clean up the BackupManagerService side of the bookkeeping
5751 // and cancel any pending timeout message
5752 mBackupManager.clearRestoreSession(mSession);
5753 }
5754 }
5755
Dan Egnor0084da52009-07-29 12:57:16 -07005756 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005757 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005758
Christopher Tate73a3cb32010-12-13 18:27:26 -08005759 if (mEnded) {
5760 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005761 }
5762
Christopher Tate73a3cb32010-12-13 18:27:26 -08005763 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005764 }
5765 }
5766
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005767 @Override
5768 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005769 long identityToken = Binder.clearCallingIdentity();
5770 try {
5771 dumpInternal(pw);
5772 } finally {
5773 Binder.restoreCallingIdentity(identityToken);
5774 }
5775 }
5776
5777 private void dumpInternal(PrintWriter pw) {
Christopher Tateb8491bb2011-09-29 15:13:11 -07005778 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5779 != PackageManager.PERMISSION_GRANTED) {
5780 pw.println("Permission Denial: can't dump Backup Manager service from from pid="
5781 + Binder.getCallingPid()
5782 + ", uid=" + Binder.getCallingUid()
5783 + " without permission "
5784 + android.Manifest.permission.DUMP);
5785 return;
5786 }
5787
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005788 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005789 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005790 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005791 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005792 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005793 if (mBackupRunning) pw.println("Backup currently running");
5794 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005795 + " (now = " + System.currentTimeMillis() + ')');
5796 pw.println(" next scheduled: " + mNextBackupPass);
5797
Christopher Tate91717492009-06-26 21:07:13 -07005798 pw.println("Available transports:");
5799 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005800 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5801 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005802 IBackupTransport transport = getTransport(t);
5803 File dir = new File(mBaseStateDir, transport.transportDirName());
5804 pw.println(" destination: " + transport.currentDestinationString());
5805 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005806 for (File f : dir.listFiles()) {
5807 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5808 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005809 } catch (Exception e) {
5810 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005811 pw.println(" Error: " + e);
5812 }
Christopher Tate91717492009-06-26 21:07:13 -07005813 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005814
5815 pw.println("Pending init: " + mPendingInits.size());
5816 for (String s : mPendingInits) {
5817 pw.println(" " + s);
5818 }
5819
Christopher Tate6de74ff2012-01-17 15:20:32 -08005820 if (DEBUG_BACKUP_TRACE) {
5821 synchronized (mBackupTrace) {
5822 if (!mBackupTrace.isEmpty()) {
5823 pw.println("Most recent backup trace:");
5824 for (String s : mBackupTrace) {
5825 pw.println(" " + s);
5826 }
5827 }
5828 }
5829 }
5830
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005831 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005832 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005833 for (int i=0; i<N; i++) {
5834 int uid = mBackupParticipants.keyAt(i);
5835 pw.print(" uid: ");
5836 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005837 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5838 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005839 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005840 }
5841 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005842
Christopher Tateb49ceb32010-02-08 16:22:24 -08005843 pw.println("Ancestral packages: "
5844 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005845 if (mAncestralPackages != null) {
5846 for (String pkg : mAncestralPackages) {
5847 pw.println(" " + pkg);
5848 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005849 }
5850
Christopher Tate73e02522009-07-15 14:18:26 -07005851 pw.println("Ever backed up: " + mEverStoredApps.size());
5852 for (String pkg : mEverStoredApps) {
5853 pw.println(" " + pkg);
5854 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005855
5856 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005857 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005858 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005859 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005860 }
5861 }
Christopher Tate487529a2009-04-29 14:03:25 -07005862}