blob: 3657ea3480c9dafa5ecc197f57d046572af1c178 [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 Tate73d73692012-01-20 17:11:31 -0800143 static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
144
Christopher Tate49401dd2009-07-01 12:34:29 -0700145 // How often we perform a backup pass. Privileged external callers can
146 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700147 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700148
Dan Egnorc1c49c02009-10-30 17:35:39 -0700149 // Random variation in backup scheduling time to avoid server load spikes
150 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
151
Christopher Tate8031a3d2009-07-06 16:36:05 -0700152 // The amount of time between the initial provisioning of the device and
153 // the first backup pass.
154 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
155
Christopher Tate45281862010-03-05 15:46:30 -0800156 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
157 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
158 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700159 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700160 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700161 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700162 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700163 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700164 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
165 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800166 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700167 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
168 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700169
Christopher Tate8e294d42011-08-31 20:37:12 -0700170 // backup task state machine tick
171 static final int MSG_BACKUP_RESTORE_STEP = 20;
172 static final int MSG_OP_COMPLETE = 21;
173
Christopher Tatec7b31e32009-06-10 15:49:30 -0700174 // Timeout interval for deciding that a bind or clear-data has taken too long
175 static final long TIMEOUT_INTERVAL = 10 * 1000;
176
Christopher Tate44a27902010-01-27 17:15:49 -0800177 // Timeout intervals for agent backup & restore operations
178 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700179 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700180 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800181 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
182
Christopher Tate2efd2db2011-07-19 16:32:49 -0700183 // User confirmation timeout for a full backup/restore operation. It's this long in
184 // order to give them time to enter the backup password.
185 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700186
Christopher Tate487529a2009-04-29 14:03:25 -0700187 private Context mContext;
188 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800189 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700190 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700191 private PowerManager mPowerManager;
192 private AlarmManager mAlarmManager;
Christopher Tate32418be2011-10-10 13:51:12 -0700193 private IMountService mMountService;
Christopher Tate44a27902010-01-27 17:15:49 -0800194 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700195
Christopher Tate73e02522009-07-15 14:18:26 -0700196 boolean mEnabled; // access to this is synchronized on 'this'
197 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800198 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700199 PowerManager.WakeLock mWakelock;
Christopher Tate0bacfd22012-01-11 14:41:19 -0800200 HandlerThread mHandlerThread;
Christopher Tate44a27902010-01-27 17:15:49 -0800201 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700202 PendingIntent mRunBackupIntent, mRunInitIntent;
203 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700204 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700205 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700206 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700207 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700208 class BackupRequest {
Christopher Tatecc55f812011-08-16 16:06:53 -0700209 public String packageName;
Christopher Tateaa088442009-06-16 18:25:46 -0700210
Christopher Tatecc55f812011-08-16 16:06:53 -0700211 BackupRequest(String pkgName) {
212 packageName = pkgName;
Christopher Tate46758122009-05-06 11:22:00 -0700213 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700214
215 public String toString() {
Christopher Tatecc55f812011-08-16 16:06:53 -0700216 return "BackupRequest{pkg=" + packageName + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700217 }
Christopher Tate46758122009-05-06 11:22:00 -0700218 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800219 // Backups that we haven't started yet. Keys are package names.
220 HashMap<String,BackupRequest> mPendingBackups
221 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700222
223 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700224 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700225
226 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700227 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700228
Christopher Tate043dadc2009-06-02 16:11:00 -0700229 // The thread performing the sequence of queued backups binds to each app's agent
230 // in succession. Bind notifications are asynchronously delivered through the
231 // Activity Manager; use this lock object to signal when a requested binding has
232 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700233 final Object mAgentConnectLock = new Object();
234 IBackupAgent mConnectedAgent;
Christopher Tate336a6492011-10-05 16:05:43 -0700235 volatile boolean mBackupRunning;
Christopher Tate73e02522009-07-15 14:18:26 -0700236 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700237 volatile long mLastBackupPass;
238 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700239
Christopher Tate6de74ff2012-01-17 15:20:32 -0800240 // For debugging, we maintain a progress trace of operations during backup
241 static final boolean DEBUG_BACKUP_TRACE = true;
242 final List<String> mBackupTrace = new ArrayList<String>();
243
Christopher Tate55f931a2009-09-29 17:17:34 -0700244 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700245 final Object mClearDataLock = new Object();
246 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700247
Christopher Tate91717492009-06-26 21:07:13 -0700248 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700249 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700250 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700251 String mCurrentTransport;
252 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800253 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700254
Christopher Tate2d449afe2010-03-29 19:14:24 -0700255 class RestoreGetSetsParams {
256 public IBackupTransport transport;
257 public ActiveRestoreSession session;
258 public IRestoreObserver observer;
259
260 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
261 IRestoreObserver _observer) {
262 transport = _transport;
263 session = _session;
264 observer = _observer;
265 }
266 }
267
Christopher Tate73e02522009-07-15 14:18:26 -0700268 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700269 public IBackupTransport transport;
270 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700271 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800272 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800273 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700274 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700275 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800276
277 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700278 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800279 transport = _transport;
280 observer = _obs;
281 token = _token;
282 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800283 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700284 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700285 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800286 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700287
Chris Tate249345b2010-10-29 12:57:04 -0700288 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
289 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700290 transport = _transport;
291 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700292 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800293 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800294 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700295 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700296 filterSet = null;
297 }
298
299 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
300 String[] _filterSet, boolean _needFullBackup) {
301 transport = _transport;
302 observer = _obs;
303 token = _token;
304 pkgInfo = null;
305 pmToken = 0;
306 needFullBackup = _needFullBackup;
307 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700308 }
309 }
310
Christopher Tate73e02522009-07-15 14:18:26 -0700311 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700312 public IBackupTransport transport;
313 public PackageInfo packageInfo;
314
315 ClearParams(IBackupTransport _transport, PackageInfo _info) {
316 transport = _transport;
317 packageInfo = _info;
318 }
319 }
320
Christopher Tate4a627c72011-04-01 14:43:32 -0700321 class FullParams {
322 public ParcelFileDescriptor fd;
323 public final AtomicBoolean latch;
324 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700325 public String curPassword; // filled in by the confirmation step
326 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700327
328 FullParams() {
329 latch = new AtomicBoolean(false);
330 }
331 }
332
333 class FullBackupParams extends FullParams {
334 public boolean includeApks;
335 public boolean includeShared;
336 public boolean allApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700337 public boolean includeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700338 public String[] packages;
339
340 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
Christopher Tate240c7d22011-10-03 18:13:44 -0700341 boolean doAllApps, boolean doSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -0700342 fd = output;
343 includeApks = saveApks;
344 includeShared = saveShared;
345 allApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700346 includeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700347 packages = pkgList;
348 }
349 }
350
351 class FullRestoreParams extends FullParams {
352 FullRestoreParams(ParcelFileDescriptor input) {
353 fd = input;
354 }
355 }
356
Christopher Tate44a27902010-01-27 17:15:49 -0800357 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
358 // token is the index of the entry in the pending-operations list.
359 static final int OP_PENDING = 0;
360 static final int OP_ACKNOWLEDGED = 1;
361 static final int OP_TIMEOUT = -1;
362
Christopher Tate8e294d42011-08-31 20:37:12 -0700363 class Operation {
364 public int state;
365 public BackupRestoreTask callback;
366
367 Operation(int initialState, BackupRestoreTask callbackObj) {
368 state = initialState;
369 callback = callbackObj;
370 }
371 }
372 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
Christopher Tate44a27902010-01-27 17:15:49 -0800373 final Object mCurrentOpLock = new Object();
374 final Random mTokenGenerator = new Random();
375
Christopher Tate4a627c72011-04-01 14:43:32 -0700376 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
377
Christopher Tate5cb400b2009-06-25 16:03:14 -0700378 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700379 File mBaseStateDir;
380 File mDataDir;
381 File mJournalDir;
382 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700383
Christopher Tate2efd2db2011-07-19 16:32:49 -0700384 // Backup password, if any, and the file where it's saved. What is stored is not the
385 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
386 // persisted) salt. Validation is performed by running the challenge text through the
387 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
388 // the saved hash string, then the challenge text matches the originally supplied
389 // password text.
390 private final SecureRandom mRng = new SecureRandom();
391 private String mPasswordHash;
392 private File mPasswordHashFile;
393 private byte[] mPasswordSalt;
394
395 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
396 static final int PBKDF2_HASH_ROUNDS = 10000;
397 static final int PBKDF2_KEY_SIZE = 256; // bits
398 static final int PBKDF2_SALT_SIZE = 512; // bits
399 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
400
Christopher Tate84725812010-02-04 15:52:40 -0800401 // Keep a log of all the apps we've ever backed up, and what the
402 // dataset tokens are for both the current backup dataset and
403 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700404 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700405 HashSet<String> mEverStoredApps = new HashSet<String>();
406
Christopher Tateb49ceb32010-02-08 16:22:24 -0800407 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800408 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800409 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800410 long mAncestralToken = 0;
411 long mCurrentToken = 0;
412
Christopher Tate4cc86e12009-09-21 19:36:51 -0700413 // Persistently track the need to do a full init
414 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
415 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700416
Christopher Tate4a627c72011-04-01 14:43:32 -0700417 // Utility: build a new random integer token
418 int generateToken() {
419 int token;
420 do {
421 synchronized (mTokenGenerator) {
422 token = mTokenGenerator.nextInt();
423 }
424 } while (token < 0);
425 return token;
426 }
427
Christopher Tate44a27902010-01-27 17:15:49 -0800428 // ----- Asynchronous backup/restore handler thread -----
429
430 private class BackupHandler extends Handler {
431 public BackupHandler(Looper looper) {
432 super(looper);
433 }
434
435 public void handleMessage(Message msg) {
436
437 switch (msg.what) {
438 case MSG_RUN_BACKUP:
439 {
440 mLastBackupPass = System.currentTimeMillis();
441 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
442
443 IBackupTransport transport = getTransport(mCurrentTransport);
444 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800445 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate336a6492011-10-05 16:05:43 -0700446 synchronized (mQueueLock) {
447 mBackupRunning = false;
448 }
Christopher Tate44a27902010-01-27 17:15:49 -0800449 mWakelock.release();
450 break;
451 }
452
453 // snapshot the pending-backup set and work on that
454 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800455 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800456 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800457 // Do we have any work to do? Construct the work queue
458 // then release the synchronization lock to actually run
459 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800460 if (mPendingBackups.size() > 0) {
461 for (BackupRequest b: mPendingBackups.values()) {
462 queue.add(b);
463 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800464 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800465 mPendingBackups.clear();
466
467 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800468 mJournal = null;
469
Christopher Tate44a27902010-01-27 17:15:49 -0800470 }
471 }
Christopher Tatec61da312010-02-05 10:41:27 -0800472
Christopher Tate8e294d42011-08-31 20:37:12 -0700473 // At this point, we have started a new journal file, and the old
474 // file identity is being passed to the backup processing task.
475 // When it completes successfully, that old journal file will be
476 // deleted. If we crash prior to that, the old journal is parsed
477 // at next boot and the journaled requests fulfilled.
Christopher Tatec61da312010-02-05 10:41:27 -0800478 if (queue.size() > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -0700479 // Spin up a backup state sequence and set it running
480 PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
481 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
482 sendMessage(pbtMessage);
Christopher Tatec61da312010-02-05 10:41:27 -0800483 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800484 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tate336a6492011-10-05 16:05:43 -0700485 synchronized (mQueueLock) {
486 mBackupRunning = false;
487 }
Christopher Tatec61da312010-02-05 10:41:27 -0800488 mWakelock.release();
489 }
Christopher Tate44a27902010-01-27 17:15:49 -0800490 break;
491 }
492
Christopher Tate8e294d42011-08-31 20:37:12 -0700493 case MSG_BACKUP_RESTORE_STEP:
494 {
495 try {
496 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
497 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
498 task.execute();
499 } catch (ClassCastException e) {
500 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
501 }
502 break;
503 }
504
505 case MSG_OP_COMPLETE:
506 {
507 try {
Christopher Tate2982d062011-09-06 20:35:24 -0700508 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
509 task.operationComplete();
Christopher Tate8e294d42011-08-31 20:37:12 -0700510 } catch (ClassCastException e) {
511 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
512 }
513 break;
514 }
515
Christopher Tate44a27902010-01-27 17:15:49 -0800516 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700517 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700518 // TODO: refactor full backup to be a looper-based state machine
519 // similar to normal backup/restore.
Christopher Tate4a627c72011-04-01 14:43:32 -0700520 FullBackupParams params = (FullBackupParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700521 PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
522 params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700523 params.includeShared, params.curPassword, params.encryptPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -0700524 params.allApps, params.includeSystem, params.packages, params.latch);
Christopher Tatea28e8542011-09-12 13:45:21 -0700525 (new Thread(task)).start();
Christopher Tate44a27902010-01-27 17:15:49 -0800526 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700527 }
Christopher Tate44a27902010-01-27 17:15:49 -0800528
529 case MSG_RUN_RESTORE:
530 {
531 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800532 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate2982d062011-09-06 20:35:24 -0700533 PerformRestoreTask task = new PerformRestoreTask(
534 params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700535 params.token, params.pkgInfo, params.pmToken,
Christopher Tate2982d062011-09-06 20:35:24 -0700536 params.needFullBackup, params.filterSet);
537 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
538 sendMessage(restoreMsg);
Christopher Tate44a27902010-01-27 17:15:49 -0800539 break;
540 }
541
Christopher Tate75a99702011-05-18 16:28:19 -0700542 case MSG_RUN_FULL_RESTORE:
543 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700544 // TODO: refactor full restore to be a looper-based state machine
545 // similar to normal backup/restore.
Christopher Tate75a99702011-05-18 16:28:19 -0700546 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700547 PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
548 params.curPassword, params.encryptPassword,
549 params.observer, params.latch);
550 (new Thread(task)).start();
Christopher Tate75a99702011-05-18 16:28:19 -0700551 break;
552 }
553
Christopher Tate44a27902010-01-27 17:15:49 -0800554 case MSG_RUN_CLEAR:
555 {
556 ClearParams params = (ClearParams)msg.obj;
557 (new PerformClearTask(params.transport, params.packageInfo)).run();
558 break;
559 }
560
561 case MSG_RUN_INITIALIZE:
562 {
563 HashSet<String> queue;
564
565 // Snapshot the pending-init queue and work on that
566 synchronized (mQueueLock) {
567 queue = new HashSet<String>(mPendingInits);
568 mPendingInits.clear();
569 }
570
571 (new PerformInitializeTask(queue)).run();
572 break;
573 }
574
Christopher Tate2d449afe2010-03-29 19:14:24 -0700575 case MSG_RUN_GET_RESTORE_SETS:
576 {
577 // Like other async operations, this is entered with the wakelock held
578 RestoreSet[] sets = null;
579 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
580 try {
581 sets = params.transport.getAvailableRestoreSets();
582 // cache the result in the active session
583 synchronized (params.session) {
584 params.session.mRestoreSets = sets;
585 }
586 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
587 } catch (Exception e) {
588 Slog.e(TAG, "Error from transport getting set list");
589 } finally {
590 if (params.observer != null) {
591 try {
592 params.observer.restoreSetsAvailable(sets);
593 } catch (RemoteException re) {
594 Slog.e(TAG, "Unable to report listing to observer");
595 } catch (Exception e) {
596 Slog.e(TAG, "Restore observer threw", e);
597 }
598 }
599
Christopher Tate2a935092011-03-03 17:30:32 -0800600 // Done: reset the session timeout clock
601 removeMessages(MSG_RESTORE_TIMEOUT);
602 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
603
Christopher Tate2d449afe2010-03-29 19:14:24 -0700604 mWakelock.release();
605 }
606 break;
607 }
608
Christopher Tate44a27902010-01-27 17:15:49 -0800609 case MSG_TIMEOUT:
610 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700611 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800612 break;
613 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800614
615 case MSG_RESTORE_TIMEOUT:
616 {
617 synchronized (BackupManagerService.this) {
618 if (mActiveRestoreSession != null) {
619 // Client app left the restore session dangling. We know that it
620 // can't be in the middle of an actual restore operation because
Christopher Tate2982d062011-09-06 20:35:24 -0700621 // the timeout is suspended while a restore is in progress. Clean
Christopher Tate73a3cb32010-12-13 18:27:26 -0800622 // up now.
623 Slog.w(TAG, "Restore session timed out; aborting");
624 post(mActiveRestoreSession.new EndRestoreRunnable(
625 BackupManagerService.this, mActiveRestoreSession));
626 }
627 }
628 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700629
630 case MSG_FULL_CONFIRMATION_TIMEOUT:
631 {
632 synchronized (mFullConfirmations) {
633 FullParams params = mFullConfirmations.get(msg.arg1);
634 if (params != null) {
635 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
636
637 // Release the waiter; timeout == completion
638 signalFullBackupRestoreCompletion(params);
639
640 // Remove the token from the set
641 mFullConfirmations.delete(msg.arg1);
642
643 // Report a timeout to the observer, if any
644 if (params.observer != null) {
645 try {
646 params.observer.onTimeout();
647 } catch (RemoteException e) {
648 /* don't care if the app has gone away */
649 }
650 }
651 } else {
652 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
653 }
654 }
655 break;
656 }
Christopher Tate44a27902010-01-27 17:15:49 -0800657 }
658 }
659 }
660
Christopher Tate6de74ff2012-01-17 15:20:32 -0800661 // ----- Debug-only backup operation trace -----
662 void addBackupTrace(String s) {
663 if (DEBUG_BACKUP_TRACE) {
664 synchronized (mBackupTrace) {
665 mBackupTrace.add(s);
666 }
667 }
668 }
669
670 void clearBackupTrace() {
671 if (DEBUG_BACKUP_TRACE) {
672 synchronized (mBackupTrace) {
673 mBackupTrace.clear();
674 }
675 }
676 }
677
Christopher Tate44a27902010-01-27 17:15:49 -0800678 // ----- Main service implementation -----
679
Christopher Tate487529a2009-04-29 14:03:25 -0700680 public BackupManagerService(Context context) {
681 mContext = context;
682 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700683 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700684 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700685
Christopher Tateb6787f22009-07-02 17:40:45 -0700686 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
687 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
Christopher Tate32418be2011-10-10 13:51:12 -0700688 mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
Christopher Tateb6787f22009-07-02 17:40:45 -0700689
Christopher Tate44a27902010-01-27 17:15:49 -0800690 mBackupManagerBinder = asInterface(asBinder());
691
692 // spin up the backup/restore handler thread
693 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
694 mHandlerThread.start();
695 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
696
Christopher Tate22b87872009-05-04 16:41:53 -0700697 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700698 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700699 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700700 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700701 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800702 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800703 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800704 // If Encrypted file systems is enabled or disabled, this call will return the
705 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600706 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800707 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700708 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700709
Christopher Tate2efd2db2011-07-19 16:32:49 -0700710 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
711 if (mPasswordHashFile.exists()) {
712 FileInputStream fin = null;
713 DataInputStream in = null;
714 try {
715 fin = new FileInputStream(mPasswordHashFile);
716 in = new DataInputStream(new BufferedInputStream(fin));
717 // integer length of the salt array, followed by the salt,
718 // then the hex pw hash string
719 int saltLen = in.readInt();
720 byte[] salt = new byte[saltLen];
721 in.readFully(salt);
722 mPasswordHash = in.readUTF();
723 mPasswordSalt = salt;
724 } catch (IOException e) {
725 Slog.e(TAG, "Unable to read saved backup pw hash");
726 } finally {
727 try {
728 if (in != null) in.close();
729 if (fin != null) fin.close();
730 } catch (IOException e) {
731 Slog.w(TAG, "Unable to close streams");
732 }
733 }
734 }
735
Christopher Tate4cc86e12009-09-21 19:36:51 -0700736 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700737 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700738 IntentFilter filter = new IntentFilter();
739 filter.addAction(RUN_BACKUP_ACTION);
740 context.registerReceiver(mRunBackupReceiver, filter,
741 android.Manifest.permission.BACKUP, null);
742
743 mRunInitReceiver = new RunInitializeReceiver();
744 filter = new IntentFilter();
745 filter.addAction(RUN_INITIALIZE_ACTION);
746 context.registerReceiver(mRunInitReceiver, filter,
747 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700748
749 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700750 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
751 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
752
Christopher Tate4cc86e12009-09-21 19:36:51 -0700753 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
754 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
755 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
756
Christopher Tatecde87f42009-06-12 12:55:53 -0700757 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700758 mJournalDir = new File(mBaseStateDir, "pending");
759 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700760 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700761
Christopher Tate73e02522009-07-15 14:18:26 -0700762 // Set up the various sorts of package tracking we do
763 initPackageTracking();
764
Christopher Tateabce4e82009-06-18 18:35:32 -0700765 // Build our mapping of uid to backup client services. This implicitly
766 // schedules a backup pass on the Package Manager metadata the first
767 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700768 synchronized (mBackupParticipants) {
769 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700770 }
771
Dan Egnor87a02bc2009-06-17 02:30:10 -0700772 // Set up our transport options and initialize the default transport
773 // TODO: Have transports register themselves somehow?
774 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700775 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700776 ComponentName localName = new ComponentName(context, LocalTransport.class);
777 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700778
Christopher Tate91717492009-06-26 21:07:13 -0700779 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700780 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
781 Settings.Secure.BACKUP_TRANSPORT);
782 if ("".equals(mCurrentTransport)) {
783 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700784 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800785 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700786
787 // Attach to the Google backup transport. When this comes up, it will set
788 // itself as the current transport because we explicitly reset mCurrentTransport
789 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700790 ComponentName transportComponent = new ComponentName("com.google.android.backup",
791 "com.google.android.backup.BackupTransportService");
792 try {
793 // If there's something out there that is supposed to be the Google
794 // backup transport, make sure it's legitimately part of the OS build
795 // and not an app lying about its package name.
796 ApplicationInfo info = mPackageManager.getApplicationInfo(
797 transportComponent.getPackageName(), 0);
798 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
799 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
800 Intent intent = new Intent().setComponent(transportComponent);
801 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
802 } else {
803 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
804 }
805 } catch (PackageManager.NameNotFoundException nnf) {
806 // No such package? No binding.
807 if (DEBUG) Slog.v(TAG, "Google transport not present");
808 }
Christopher Tateaa088442009-06-16 18:25:46 -0700809
Christopher Tatecde87f42009-06-12 12:55:53 -0700810 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700811 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700812 parseLeftoverJournals();
813
Christopher Tateb6787f22009-07-02 17:40:45 -0700814 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700815 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700816
817 // Start the backup passes going
818 setBackupEnabled(areEnabled);
819 }
820
821 private class RunBackupReceiver extends BroadcastReceiver {
822 public void onReceive(Context context, Intent intent) {
823 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700824 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700825 if (mPendingInits.size() > 0) {
826 // If there are pending init operations, we process those
827 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800828 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700829 try {
830 mAlarmManager.cancel(mRunInitIntent);
831 mRunInitIntent.send();
832 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800833 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700834 // can't really do more than bail here
835 }
836 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800837 // Don't run backups now if we're disabled or not yet
838 // fully set up.
839 if (mEnabled && mProvisioned) {
Christopher Tate336a6492011-10-05 16:05:43 -0700840 if (!mBackupRunning) {
841 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700842
Christopher Tate336a6492011-10-05 16:05:43 -0700843 // Acquire the wakelock and pass it to the backup thread. it will
844 // be released once backup concludes.
845 mBackupRunning = true;
846 mWakelock.acquire();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700847
Christopher Tate336a6492011-10-05 16:05:43 -0700848 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
849 mBackupHandler.sendMessage(msg);
850 } else {
851 Slog.i(TAG, "Backup time but one already running");
852 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700853 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800854 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700855 }
856 }
857 }
858 }
859 }
860 }
861
862 private class RunInitializeReceiver extends BroadcastReceiver {
863 public void onReceive(Context context, Intent intent) {
864 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
865 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800866 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700867
868 // Acquire the wakelock and pass it to the init thread. it will
869 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700870 mWakelock.acquire();
871
Christopher Tate4cc86e12009-09-21 19:36:51 -0700872 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700873 mBackupHandler.sendMessage(msg);
874 }
875 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700876 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700877 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700878
Christopher Tate73e02522009-07-15 14:18:26 -0700879 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800880 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700881
Christopher Tate84725812010-02-04 15:52:40 -0800882 // Remember our ancestral dataset
883 mTokenFile = new File(mBaseStateDir, "ancestral");
884 try {
885 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800886 int version = tf.readInt();
887 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
888 mAncestralToken = tf.readLong();
889 mCurrentToken = tf.readLong();
890
891 int numPackages = tf.readInt();
892 if (numPackages >= 0) {
893 mAncestralPackages = new HashSet<String>();
894 for (int i = 0; i < numPackages; i++) {
895 String pkgName = tf.readUTF();
896 mAncestralPackages.add(pkgName);
897 }
898 }
899 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800900 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800901 } catch (FileNotFoundException fnf) {
902 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800903 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800904 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800905 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800906 }
907
Christopher Tatee97e8072009-07-15 16:45:50 -0700908 // Keep a log of what apps we've ever backed up. Because we might have
909 // rebooted in the middle of an operation that was removing something from
910 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700911 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700912 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700913
Christopher Tatee97e8072009-07-15 16:45:50 -0700914 // If we were in the middle of removing something from the ever-backed-up
915 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700916 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700917 if (tempProcessedFile.exists()) {
918 tempProcessedFile.delete();
919 }
920
Dan Egnor852f8e42009-09-30 11:20:45 -0700921 // If there are previous contents, parse them out then start a new
922 // file to continue the recordkeeping.
923 if (mEverStored.exists()) {
924 RandomAccessFile temp = null;
925 RandomAccessFile in = null;
926
927 try {
928 temp = new RandomAccessFile(tempProcessedFile, "rws");
929 in = new RandomAccessFile(mEverStored, "r");
930
931 while (true) {
932 PackageInfo info;
933 String pkg = in.readUTF();
934 try {
935 info = mPackageManager.getPackageInfo(pkg, 0);
936 mEverStoredApps.add(pkg);
937 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700938 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700939 } catch (NameNotFoundException e) {
940 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700941 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700942 }
943 }
944 } catch (EOFException e) {
945 // Once we've rewritten the backup history log, atomically replace the
946 // old one with the new one then reopen the file for continuing use.
947 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800948 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700949 }
950 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800951 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700952 } finally {
953 try { if (temp != null) temp.close(); } catch (IOException e) {}
954 try { if (in != null) in.close(); } catch (IOException e) {}
955 }
956 }
957
Christopher Tate73e02522009-07-15 14:18:26 -0700958 // Register for broadcasts about package install, etc., so we can
959 // update the provider list.
960 IntentFilter filter = new IntentFilter();
961 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
962 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Christopher Tatecc55f812011-08-16 16:06:53 -0700963 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Christopher Tate73e02522009-07-15 14:18:26 -0700964 filter.addDataScheme("package");
965 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800966 // Register for events related to sdcard installation.
967 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800968 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
969 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800970 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700971 }
972
Christopher Tatecde87f42009-06-12 12:55:53 -0700973 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700974 for (File f : mJournalDir.listFiles()) {
975 if (mJournal == null || f.compareTo(mJournal) != 0) {
976 // This isn't the current journal, so it must be a leftover. Read
977 // out the package names mentioned there and schedule them for
978 // backup.
979 RandomAccessFile in = null;
980 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400981 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700982 in = new RandomAccessFile(f, "r");
983 while (true) {
984 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400985 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700986 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700987 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700988 } catch (EOFException e) {
989 // no more data; we're done
990 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800991 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700992 } finally {
993 // close/delete the file
994 try { if (in != null) in.close(); } catch (IOException e) {}
995 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700996 }
997 }
998 }
999 }
1000
Christopher Tate2efd2db2011-07-19 16:32:49 -07001001 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
1002 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
1003 }
1004
1005 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
1006 try {
1007 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
1008 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
1009 return keyFactory.generateSecret(ks);
1010 } catch (InvalidKeySpecException e) {
1011 Slog.e(TAG, "Invalid key spec for PBKDF2!");
1012 } catch (NoSuchAlgorithmException e) {
1013 Slog.e(TAG, "PBKDF2 unavailable!");
1014 }
1015 return null;
1016 }
1017
1018 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
1019 SecretKey key = buildPasswordKey(pw, salt, rounds);
1020 if (key != null) {
1021 return byteArrayToHex(key.getEncoded());
1022 }
1023 return null;
1024 }
1025
1026 private String byteArrayToHex(byte[] data) {
1027 StringBuilder buf = new StringBuilder(data.length * 2);
1028 for (int i = 0; i < data.length; i++) {
1029 buf.append(Byte.toHexString(data[i], true));
1030 }
1031 return buf.toString();
1032 }
1033
1034 private byte[] hexToByteArray(String digits) {
1035 final int bytes = digits.length() / 2;
1036 if (2*bytes != digits.length()) {
1037 throw new IllegalArgumentException("Hex string must have an even number of digits");
1038 }
1039
1040 byte[] result = new byte[bytes];
1041 for (int i = 0; i < digits.length(); i += 2) {
1042 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1043 }
1044 return result;
1045 }
1046
1047 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1048 char[] mkAsChar = new char[pwBytes.length];
1049 for (int i = 0; i < pwBytes.length; i++) {
1050 mkAsChar[i] = (char) pwBytes[i];
1051 }
1052
1053 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1054 return checksum.getEncoded();
1055 }
1056
1057 // Used for generating random salts or passwords
1058 private byte[] randomBytes(int bits) {
1059 byte[] array = new byte[bits / 8];
1060 mRng.nextBytes(array);
1061 return array;
1062 }
1063
1064 // Backup password management
1065 boolean passwordMatchesSaved(String candidatePw, int rounds) {
Christopher Tate32418be2011-10-10 13:51:12 -07001066 // First, on an encrypted device we require matching the device pw
1067 final boolean isEncrypted;
1068 try {
1069 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
1070 if (isEncrypted) {
1071 if (DEBUG) {
1072 Slog.i(TAG, "Device encrypted; verifying against device data pw");
1073 }
1074 // 0 means the password validated
1075 // -2 means device not encrypted
1076 // Any other result is either password failure or an error condition,
1077 // so we refuse the match
1078 final int result = mMountService.verifyEncryptionPassword(candidatePw);
1079 if (result == 0) {
1080 if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
1081 return true;
1082 } else if (result != -2) {
1083 if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
1084 return false;
1085 } else {
1086 // ...else the device is supposedly not encrypted. HOWEVER, the
1087 // query about the encryption state said that the device *is*
1088 // encrypted, so ... we may have a problem. Log it and refuse
1089 // the backup.
1090 Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
1091 return false;
1092 }
1093 }
1094 } catch (Exception e) {
1095 // Something went wrong talking to the mount service. This is very bad;
1096 // assume that we fail password validation.
1097 return false;
1098 }
1099
Christopher Tate2efd2db2011-07-19 16:32:49 -07001100 if (mPasswordHash == null) {
1101 // no current password case -- require that 'currentPw' be null or empty
1102 if (candidatePw == null || "".equals(candidatePw)) {
1103 return true;
1104 } // else the non-empty candidate does not match the empty stored pw
1105 } else {
1106 // hash the stated current pw and compare to the stored one
1107 if (candidatePw != null && candidatePw.length() > 0) {
1108 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1109 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1110 // candidate hash matches the stored hash -- the password matches
1111 return true;
1112 }
1113 } // else the stored pw is nonempty but the candidate is empty; no match
1114 }
1115 return false;
1116 }
1117
1118 @Override
1119 public boolean setBackupPassword(String currentPw, String newPw) {
1120 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1121 "setBackupPassword");
1122
1123 // If the supplied pw doesn't hash to the the saved one, fail
1124 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1125 return false;
1126 }
1127
1128 // Clearing the password is okay
1129 if (newPw == null || newPw.isEmpty()) {
1130 if (mPasswordHashFile.exists()) {
1131 if (!mPasswordHashFile.delete()) {
1132 // Unable to delete the old pw file, so fail
1133 Slog.e(TAG, "Unable to clear backup password");
1134 return false;
1135 }
1136 }
1137 mPasswordHash = null;
1138 mPasswordSalt = null;
1139 return true;
1140 }
1141
1142 try {
1143 // Okay, build the hash of the new backup password
1144 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1145 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1146
1147 OutputStream pwf = null, buffer = null;
1148 DataOutputStream out = null;
1149 try {
1150 pwf = new FileOutputStream(mPasswordHashFile);
1151 buffer = new BufferedOutputStream(pwf);
1152 out = new DataOutputStream(buffer);
1153 // integer length of the salt array, followed by the salt,
1154 // then the hex pw hash string
1155 out.writeInt(salt.length);
1156 out.write(salt);
1157 out.writeUTF(newPwHash);
1158 out.flush();
1159 mPasswordHash = newPwHash;
1160 mPasswordSalt = salt;
1161 return true;
1162 } finally {
1163 if (out != null) out.close();
1164 if (buffer != null) buffer.close();
1165 if (pwf != null) pwf.close();
1166 }
1167 } catch (IOException e) {
1168 Slog.e(TAG, "Unable to set backup password");
1169 }
1170 return false;
1171 }
1172
1173 @Override
1174 public boolean hasBackupPassword() {
1175 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1176 "hasBackupPassword");
Christopher Tate32418be2011-10-10 13:51:12 -07001177
1178 try {
1179 return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
1180 || (mPasswordHash != null && mPasswordHash.length() > 0);
1181 } catch (Exception e) {
1182 // If we can't talk to the mount service we have a serious problem; fail
1183 // "secure" i.e. assuming that we require a password
1184 return true;
1185 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07001186 }
1187
Christopher Tate4cc86e12009-09-21 19:36:51 -07001188 // Maintain persistent state around whether need to do an initialize operation.
1189 // Must be called with the queue lock held.
1190 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001191 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001192 + " on transport " + transportName);
1193 try {
1194 IBackupTransport transport = getTransport(transportName);
1195 String transportDirName = transport.transportDirName();
1196 File stateDir = new File(mBaseStateDir, transportDirName);
1197 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1198
1199 if (isPending) {
1200 // We need an init before we can proceed with sending backup data.
1201 // Record that with an entry in our set of pending inits, as well as
1202 // journaling it via creation of a sentinel file.
1203 mPendingInits.add(transportName);
1204 try {
1205 (new FileOutputStream(initPendingFile)).close();
1206 } catch (IOException ioe) {
1207 // Something is badly wrong with our permissions; just try to move on
1208 }
1209 } else {
1210 // No more initialization needed; wipe the journal and reset our state.
1211 initPendingFile.delete();
1212 mPendingInits.remove(transportName);
1213 }
1214 } catch (RemoteException e) {
1215 // can't happen; the transport is local
1216 }
1217 }
1218
Christopher Tated55e18a2009-09-21 10:12:59 -07001219 // Reset all of our bookkeeping, in response to having been told that
1220 // the backend data has been wiped [due to idle expiry, for example],
1221 // so we must re-upload all saved settings.
1222 void resetBackupState(File stateFileDir) {
1223 synchronized (mQueueLock) {
1224 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001225 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001226 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001227
Christopher Tate84725812010-02-04 15:52:40 -08001228 mCurrentToken = 0;
1229 writeRestoreTokens();
1230
Christopher Tated55e18a2009-09-21 10:12:59 -07001231 // Remove all the state files
1232 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001233 // ... but don't touch the needs-init sentinel
1234 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1235 sf.delete();
1236 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001237 }
Christopher Tate45597642011-04-04 16:59:21 -07001238 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001239
Christopher Tate45597642011-04-04 16:59:21 -07001240 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001241 synchronized (mBackupParticipants) {
1242 int N = mBackupParticipants.size();
1243 for (int i=0; i<N; i++) {
1244 int uid = mBackupParticipants.keyAt(i);
1245 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1246 for (ApplicationInfo app: participants) {
1247 dataChangedImpl(app.packageName);
1248 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001249 }
1250 }
1251 }
1252
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001253 // Add a transport to our set of available backends. If 'transport' is null, this
1254 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001255 private void registerTransport(String name, IBackupTransport transport) {
1256 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001257 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001258 if (transport != null) {
1259 mTransports.put(name, transport);
1260 } else {
1261 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001262 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001263 mCurrentTransport = null;
1264 }
1265 // Nothing further to do in the unregistration case
1266 return;
1267 }
Christopher Tate91717492009-06-26 21:07:13 -07001268 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001269
1270 // If the init sentinel file exists, we need to be sure to perform the init
1271 // as soon as practical. We also create the state directory at registration
1272 // time to ensure it's present from the outset.
1273 try {
1274 String transportName = transport.transportDirName();
1275 File stateDir = new File(mBaseStateDir, transportName);
1276 stateDir.mkdirs();
1277
1278 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1279 if (initSentinel.exists()) {
1280 synchronized (mQueueLock) {
1281 mPendingInits.add(transportName);
1282
1283 // TODO: pick a better starting time than now + 1 minute
1284 long delay = 1000 * 60; // one minute, in milliseconds
1285 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1286 System.currentTimeMillis() + delay, mRunInitIntent);
1287 }
1288 }
1289 } catch (RemoteException e) {
1290 // can't happen, the transport is local
1291 }
Christopher Tate91717492009-06-26 21:07:13 -07001292 }
1293
Christopher Tate3799bc22009-05-06 16:13:56 -07001294 // ----- Track installation/removal of packages -----
1295 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1296 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001297 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001298
Christopher Tate3799bc22009-05-06 16:13:56 -07001299 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001300 boolean replacing = false;
1301 boolean added = false;
1302 Bundle extras = intent.getExtras();
1303 String pkgList[] = null;
1304 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatecc55f812011-08-16 16:06:53 -07001305 Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
1306 Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001307 Uri uri = intent.getData();
1308 if (uri == null) {
1309 return;
1310 }
1311 String pkgName = uri.getSchemeSpecificPart();
1312 if (pkgName != null) {
1313 pkgList = new String[] { pkgName };
1314 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001315 if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
1316 // use the existing "add with replacement" logic
1317 if (MORE_DEBUG) Slog.d(TAG, "PACKAGE_REPLACED, updating package " + pkgName);
1318 added = replacing = true;
1319 } else {
1320 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1321 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
1322 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001323 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001324 added = true;
1325 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001326 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001327 added = false;
1328 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1329 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001330
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001331 if (pkgList == null || pkgList.length == 0) {
1332 return;
1333 }
1334 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001335 synchronized (mBackupParticipants) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001336 if (replacing) {
1337 updatePackageParticipantsLocked(pkgList);
1338 } else {
1339 addPackageParticipantsLocked(pkgList);
Christopher Tate3799bc22009-05-06 16:13:56 -07001340 }
1341 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001342 } else {
1343 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001344 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1345 } else {
1346 synchronized (mBackupParticipants) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001347 removePackageParticipantsLocked(pkgList);
Christopher Tate3799bc22009-05-06 16:13:56 -07001348 }
1349 }
1350 }
1351 }
1352 };
1353
Dan Egnor87a02bc2009-06-17 02:30:10 -07001354 // ----- Track connection to GoogleBackupTransport service -----
1355 ServiceConnection mGoogleConnection = new ServiceConnection() {
1356 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001357 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001358 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001359 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001360 }
1361
1362 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001363 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001364 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001365 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001366 }
1367 };
1368
Christopher Tate0bacfd22012-01-11 14:41:19 -08001369 // Add the backup agents in the given packages to our set of known backup participants.
1370 // If 'packageNames' is null, adds all backup agents in the whole system.
1371 void addPackageParticipantsLocked(String[] packageNames) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001372 // Look for apps that define the android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -07001373 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate0bacfd22012-01-11 14:41:19 -08001374 if (packageNames != null) {
1375 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: #" + packageNames.length);
1376 for (String packageName : packageNames) {
1377 addPackageParticipantsLockedInner(packageName, targetApps);
1378 }
1379 } else {
1380 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: all");
1381 addPackageParticipantsLockedInner(null, targetApps);
1382 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001383 }
1384
Christopher Tate181fafa2009-05-14 11:12:14 -07001385 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001386 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001387 if (MORE_DEBUG) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001388 Slog.v(TAG, "Examining " + packageName + " for backup agent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001389 }
1390
Dan Egnorefe52642009-06-24 00:16:33 -07001391 for (PackageInfo pkg : targetPkgs) {
1392 if (packageName == null || pkg.packageName.equals(packageName)) {
1393 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001394 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001395 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001396 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001397 mBackupParticipants.put(uid, set);
1398 }
Dan Egnorefe52642009-06-24 00:16:33 -07001399 set.add(pkg.applicationInfo);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001400 if (MORE_DEBUG) Slog.v(TAG, "Agent found; added");
Christopher Tate73e02522009-07-15 14:18:26 -07001401
1402 // If we've never seen this app before, schedule a backup for it
1403 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001404 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001405 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001406 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001407 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001408 }
Christopher Tate487529a2009-04-29 14:03:25 -07001409 }
1410 }
1411
Christopher Tate0bacfd22012-01-11 14:41:19 -08001412 // Remove the given packages' entries from our known active set.
1413 void removePackageParticipantsLocked(String[] packageNames) {
1414 if (packageNames == null) {
1415 Slog.w(TAG, "removePackageParticipants with null list");
1416 return;
Christopher Tate181fafa2009-05-14 11:12:14 -07001417 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001418
1419 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: #" + packageNames.length);
1420 List<PackageInfo> knownPackages = allAgentPackages();
1421 for (String pkg : packageNames) {
1422 removePackageParticipantsLockedInner(pkg, knownPackages);
1423 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001424 }
1425
Joe Onorato8ad02812009-05-13 01:41:44 -04001426 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tate0bacfd22012-01-11 14:41:19 -08001427 List<PackageInfo> allPackages) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001428 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001429 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tate0bacfd22012-01-11 14:41:19 -08001430 + ") removing from " + allPackages.size() + " entries");
1431 for (PackageInfo p : allPackages) {
1432 Slog.v(TAG, " - " + p.packageName);
Christopher Tate043dadc2009-06-02 16:11:00 -07001433 }
1434 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001435 for (PackageInfo pkg : allPackages) {
1436 if (packageName == null || pkg.packageName.equals(packageName)) {
1437 /*
Christopher Tatec28083a2010-12-14 16:16:44 -08001438 int uid = -1;
1439 try {
1440 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1441 uid = info.applicationInfo.uid;
1442 } catch (NameNotFoundException e) {
1443 // we don't know this package name, so just skip it for now
1444 continue;
1445 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001446 */
1447 final int uid = pkg.applicationInfo.uid;
1448 if (MORE_DEBUG) Slog.i(TAG, " found pkg " + packageName + " uid=" + uid);
Christopher Tatec28083a2010-12-14 16:16:44 -08001449
Christopher Tate181fafa2009-05-14 11:12:14 -07001450 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001451 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001452 // Find the existing entry with the same package name, and remove it.
1453 // We can't just remove(app) because the instances are different.
1454 for (ApplicationInfo entry: set) {
Christopher Tate0bacfd22012-01-11 14:41:19 -08001455 if (MORE_DEBUG) Slog.i(TAG, " checking against " + entry.packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001456 if (entry.packageName.equals(pkg)) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001457 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001458 set.remove(entry);
Christopher Tate0bacfd22012-01-11 14:41:19 -08001459 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001460 break;
1461 }
1462 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001463 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001464 mBackupParticipants.delete(uid);
1465 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001466 } else {
1467 if (MORE_DEBUG) Slog.i(TAG, " ... not found in uid mapping");
Christopher Tate3799bc22009-05-06 16:13:56 -07001468 }
1469 }
1470 }
1471 }
1472
Christopher Tate181fafa2009-05-14 11:12:14 -07001473 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001474 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001475 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001476 int flags = PackageManager.GET_SIGNATURES;
1477 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1478 int N = packages.size();
1479 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001480 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001481 try {
1482 ApplicationInfo app = pkg.applicationInfo;
1483 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001484 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001485 packages.remove(a);
1486 }
1487 else {
1488 // we will need the shared library path, so look that up and store it here
1489 app = mPackageManager.getApplicationInfo(pkg.packageName,
1490 PackageManager.GET_SHARED_LIBRARY_FILES);
1491 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1492 }
1493 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001494 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001495 }
1496 }
Dan Egnorefe52642009-06-24 00:16:33 -07001497 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001498 }
Christopher Tateaa088442009-06-16 18:25:46 -07001499
Christopher Tate3799bc22009-05-06 16:13:56 -07001500 // Reset the given package's known backup participants. Unlike add/remove, the update
1501 // action cannot be passed a null package name.
Christopher Tate0bacfd22012-01-11 14:41:19 -08001502 void updatePackageParticipantsLocked(String[] packageNames) {
1503 if (packageNames == null) {
1504 Slog.e(TAG, "updatePackageParticipants called with null package list");
Christopher Tate3799bc22009-05-06 16:13:56 -07001505 return;
1506 }
Christopher Tate0bacfd22012-01-11 14:41:19 -08001507 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: #" + packageNames.length);
Christopher Tate3799bc22009-05-06 16:13:56 -07001508
Christopher Tate0bacfd22012-01-11 14:41:19 -08001509 if (packageNames.length > 0) {
1510 List<PackageInfo> allApps = allAgentPackages();
1511 for (String packageName : packageNames) {
1512 removePackageParticipantsLockedInner(packageName, allApps);
1513 addPackageParticipantsLockedInner(packageName, allApps);
1514 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001515 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001516 }
1517
Christopher Tate84725812010-02-04 15:52:40 -08001518 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001519 // backed up at least once
1520 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001521 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1522
1523 synchronized (mEverStoredApps) {
1524 if (!mEverStoredApps.add(packageName)) return;
1525
1526 RandomAccessFile out = null;
1527 try {
1528 out = new RandomAccessFile(mEverStored, "rws");
1529 out.seek(out.length());
1530 out.writeUTF(packageName);
1531 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001532 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001533 } finally {
1534 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001535 }
1536 }
1537 }
1538
Christopher Tatee97e8072009-07-15 16:45:50 -07001539 // Remove our awareness of having ever backed up the given package
1540 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001541 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1542 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001543
Dan Egnor852f8e42009-09-30 11:20:45 -07001544 synchronized (mEverStoredApps) {
1545 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1546 // we'll recognize on initialization time that the package no longer
1547 // exists and fix it up then.
1548 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1549 RandomAccessFile known = null;
1550 try {
1551 known = new RandomAccessFile(tempKnownFile, "rws");
1552 mEverStoredApps.remove(packageName);
1553 for (String s : mEverStoredApps) {
1554 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001555 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001556 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001557 known.close();
1558 known = null;
1559 if (!tempKnownFile.renameTo(mEverStored)) {
1560 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1561 }
1562 } catch (IOException e) {
1563 // Bad: we couldn't create the new copy. For safety's sake we
1564 // abandon the whole process and remove all what's-backed-up
1565 // state entirely, meaning we'll force a backup pass for every
1566 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001567 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001568 mEverStoredApps.clear();
1569 tempKnownFile.delete();
1570 mEverStored.delete();
1571 } finally {
1572 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001573 }
1574 }
1575 }
1576
Christopher Tateb49ceb32010-02-08 16:22:24 -08001577 // Persistently record the current and ancestral backup tokens as well
1578 // as the set of packages with data [supposedly] available in the
1579 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001580 void writeRestoreTokens() {
1581 try {
1582 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001583
1584 // First, the version number of this record, for futureproofing
1585 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1586
1587 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001588 af.writeLong(mAncestralToken);
1589 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001590
1591 // Now write the set of ancestral packages
1592 if (mAncestralPackages == null) {
1593 af.writeInt(-1);
1594 } else {
1595 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001596 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001597 for (String pkgName : mAncestralPackages) {
1598 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001599 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001600 }
1601 }
Christopher Tate84725812010-02-04 15:52:40 -08001602 af.close();
1603 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001604 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001605 }
1606 }
1607
Dan Egnor87a02bc2009-06-17 02:30:10 -07001608 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001609 private IBackupTransport getTransport(String transportName) {
1610 synchronized (mTransports) {
1611 IBackupTransport transport = mTransports.get(transportName);
1612 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001613 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001614 }
1615 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001616 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001617 }
1618
Christopher Tatedf01dea2009-06-09 20:45:02 -07001619 // fire off a backup agent, blocking until it attaches or times out
1620 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1621 IBackupAgent agent = null;
1622 synchronized(mAgentConnectLock) {
1623 mConnecting = true;
1624 mConnectedAgent = null;
1625 try {
1626 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001627 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001628
1629 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001630 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001631 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1632 while (mConnecting && mConnectedAgent == null
1633 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001634 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001635 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001636 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001637 // just bail
Christopher Tate6de74ff2012-01-17 15:20:32 -08001638 if (DEBUG) Slog.w(TAG, "Interrupted: " + e);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001639 return null;
1640 }
1641 }
1642
1643 // if we timed out with no connect, abort and move on
1644 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001645 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001646 return null;
1647 }
Christopher Tate6de74ff2012-01-17 15:20:32 -08001648 if (DEBUG) Slog.i(TAG, "got agent " + mConnectedAgent);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001649 agent = mConnectedAgent;
1650 }
1651 } catch (RemoteException e) {
1652 // can't happen
1653 }
1654 }
1655 return agent;
1656 }
1657
Christopher Tatec7b31e32009-06-10 15:49:30 -07001658 // clear an application's data, blocking until the operation completes or times out
1659 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001660 // Don't wipe packages marked allowClearUserData=false
1661 try {
1662 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1663 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001664 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001665 + packageName);
1666 return;
1667 }
1668 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001669 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001670 return;
1671 }
1672
Christopher Tatec7b31e32009-06-10 15:49:30 -07001673 ClearDataObserver observer = new ClearDataObserver();
1674
1675 synchronized(mClearDataLock) {
1676 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001677 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07001678 mActivityManager.clearApplicationUserData(packageName, observer,
1679 Binder.getOrigCallingUser());
Christopher Tate9dfdac52009-08-06 14:57:53 -07001680 } catch (RemoteException e) {
1681 // can't happen because the activity manager is in this process
1682 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001683
1684 // only wait 10 seconds for the clear data to happen
1685 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1686 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1687 try {
1688 mClearDataLock.wait(5000);
1689 } catch (InterruptedException e) {
1690 // won't happen, but still.
1691 mClearingData = false;
1692 }
1693 }
1694 }
1695 }
1696
1697 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001698 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001699 synchronized(mClearDataLock) {
1700 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001701 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001702 }
1703 }
1704 }
1705
Christopher Tate1bb69062010-02-19 17:02:12 -08001706 // Get the restore-set token for the best-available restore set for this package:
1707 // the active set if possible, else the ancestral one. Returns zero if none available.
1708 long getAvailableRestoreToken(String packageName) {
1709 long token = mAncestralToken;
1710 synchronized (mQueueLock) {
1711 if (mEverStoredApps.contains(packageName)) {
1712 token = mCurrentToken;
1713 }
1714 }
1715 return token;
1716 }
1717
Christopher Tate44a27902010-01-27 17:15:49 -08001718 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001719 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1720
1721 interface BackupRestoreTask {
1722 // Execute one tick of whatever state machine the task implements
1723 void execute();
1724
1725 // An operation that wanted a callback has completed
1726 void operationComplete();
1727
1728 // An operation that wanted a callback has timed out
1729 void handleTimeout();
1730 }
1731
1732 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1733 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1734 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001735 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001736 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1737
1738 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1739 mBackupHandler.sendMessageDelayed(msg, interval);
1740 }
1741 }
1742
1743 // synchronous waiter case
1744 boolean waitUntilOperationComplete(int token) {
1745 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1746 + Integer.toHexString(token));
1747 int finalState = OP_PENDING;
1748 Operation op = null;
1749 synchronized (mCurrentOpLock) {
1750 while (true) {
1751 op = mCurrentOperations.get(token);
1752 if (op == null) {
1753 // mysterious disappearance: treat as success with no callback
1754 break;
1755 } else {
1756 if (op.state == OP_PENDING) {
1757 try {
1758 mCurrentOpLock.wait();
1759 } catch (InterruptedException e) {}
1760 // When the wait is notified we loop around and recheck the current state
1761 } else {
1762 // No longer pending; we're done
1763 finalState = op.state;
1764 break;
1765 }
Christopher Tate44a27902010-01-27 17:15:49 -08001766 }
Christopher Tate44a27902010-01-27 17:15:49 -08001767 }
1768 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001769
Christopher Tate44a27902010-01-27 17:15:49 -08001770 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001771 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001772 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001773 return finalState == OP_ACKNOWLEDGED;
1774 }
1775
Christopher Tate8e294d42011-08-31 20:37:12 -07001776 void handleTimeout(int token, Object obj) {
1777 // Notify any synchronous waiters
1778 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001779 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001780 op = mCurrentOperations.get(token);
1781 if (MORE_DEBUG) {
1782 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1783 + " but no op found");
1784 }
1785 int state = (op != null) ? op.state : OP_TIMEOUT;
1786 if (state == OP_PENDING) {
1787 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1788 op.state = OP_TIMEOUT;
1789 mCurrentOperations.put(token, op);
1790 }
1791 mCurrentOpLock.notifyAll();
1792 }
1793
1794 // If there's a TimeoutHandler for this event, call it
1795 if (op != null && op.callback != null) {
1796 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001797 }
Christopher Tate44a27902010-01-27 17:15:49 -08001798 }
1799
Christopher Tate043dadc2009-06-02 16:11:00 -07001800 // ----- Back up a set of applications via a worker thread -----
1801
Christopher Tate8e294d42011-08-31 20:37:12 -07001802 enum BackupState {
1803 INITIAL,
1804 RUNNING_QUEUE,
1805 FINAL
1806 }
1807
1808 class PerformBackupTask implements BackupRestoreTask {
1809 private static final String TAG = "PerformBackupTask";
1810
Christopher Tateaa088442009-06-16 18:25:46 -07001811 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001812 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001813 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001814 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001815 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001816 BackupState mCurrentState;
1817
1818 // carried information about the current in-flight operation
1819 PackageInfo mCurrentPackage;
1820 File mSavedStateName;
1821 File mBackupDataName;
1822 File mNewStateName;
1823 ParcelFileDescriptor mSavedState;
1824 ParcelFileDescriptor mBackupData;
1825 ParcelFileDescriptor mNewState;
1826 int mStatus;
1827 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001828
Christopher Tate44a27902010-01-27 17:15:49 -08001829 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001830 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001831 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001832 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001833 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001834
1835 try {
1836 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1837 } catch (RemoteException e) {
1838 // can't happen; the transport is local
1839 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001840
1841 mCurrentState = BackupState.INITIAL;
1842 mFinished = false;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001843
1844 addBackupTrace("STATE => INITIAL");
Christopher Tate043dadc2009-06-02 16:11:00 -07001845 }
1846
Christopher Tate8e294d42011-08-31 20:37:12 -07001847 // Main entry point: perform one chunk of work, updating the state as appropriate
1848 // and reposting the next chunk to the primary backup handler thread.
1849 @Override
1850 public void execute() {
1851 switch (mCurrentState) {
1852 case INITIAL:
1853 beginBackup();
1854 break;
1855
1856 case RUNNING_QUEUE:
1857 invokeNextAgent();
1858 break;
1859
1860 case FINAL:
1861 if (!mFinished) finalizeBackup();
1862 else {
1863 Slog.e(TAG, "Duplicate finish");
1864 }
Christopher Tate2982d062011-09-06 20:35:24 -07001865 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001866 break;
1867 }
1868 }
1869
1870 // We're starting a backup pass. Initialize the transport and send
1871 // the PM metadata blob if we haven't already.
1872 void beginBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001873 if (DEBUG_BACKUP_TRACE) {
1874 clearBackupTrace();
1875 StringBuilder b = new StringBuilder(256);
1876 b.append("beginBackup: [");
1877 for (BackupRequest req : mOriginalQueue) {
1878 b.append(' ');
1879 b.append(req.packageName);
1880 }
1881 b.append(" ]");
1882 addBackupTrace(b.toString());
1883 }
1884
Christopher Tate8e294d42011-08-31 20:37:12 -07001885 mStatus = BackupConstants.TRANSPORT_OK;
1886
1887 // Sanity check: if the queue is empty we have no work to do.
1888 if (mOriginalQueue.isEmpty()) {
1889 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001890 addBackupTrace("queue empty at begin");
1891 executeNextState(BackupState.FINAL);
Christopher Tate8e294d42011-08-31 20:37:12 -07001892 return;
1893 }
1894
1895 // We need to retain the original queue contents in case of transport
1896 // failure, but we want a working copy that we can manipulate along
1897 // the way.
1898 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1899
Joe Onorato8a9b2202010-02-26 18:56:32 -08001900 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001901
Christopher Tate8e294d42011-08-31 20:37:12 -07001902 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001903 try {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001904 final String transportName = mTransport.transportDirName();
1905 EventLog.writeEvent(EventLogTags.BACKUP_START, transportName);
Dan Egnor01445162009-09-21 17:04:05 -07001906
Dan Egnor852f8e42009-09-30 11:20:45 -07001907 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001908 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001909 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Christopher Tate6de74ff2012-01-17 15:20:32 -08001910 addBackupTrace("initializing transport " + transportName);
Dan Egnor852f8e42009-09-30 11:20:45 -07001911 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001912 mStatus = mTransport.initializeDevice();
Christopher Tate6de74ff2012-01-17 15:20:32 -08001913
1914 addBackupTrace("transport.initializeDevice() == " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001915 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001916 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001917 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001918 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001919 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001920 }
Dan Egnor01445162009-09-21 17:04:05 -07001921 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001922
1923 // The package manager doesn't have a proper <application> etc, but since
1924 // it's running here in the system process we can just set up its agent
1925 // directly and use a synthetic BackupRequest. We always run this pass
1926 // because it's cheap and this way we guarantee that we don't get out of
1927 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001928 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001929 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1930 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001931 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001932 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001933 addBackupTrace("PMBA invoke: " + mStatus);
Dan Egnor01445162009-09-21 17:04:05 -07001934 }
Christopher Tate90967f42009-09-20 15:28:33 -07001935
Christopher Tate8e294d42011-08-31 20:37:12 -07001936 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1937 // The backend reports that our dataset has been wiped. Note this in
1938 // the event log; the no-success code below will reset the backup
1939 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001940 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001941 }
1942 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001943 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001944 addBackupTrace("Exception in backup thread: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001945 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001946 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001947 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1948 // metadata and its completion/timeout callback will continue the state
1949 // machine chain. If it failed that won't happen; we handle that now.
Christopher Tate6de74ff2012-01-17 15:20:32 -08001950 addBackupTrace("exiting prelim: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07001951 if (mStatus != BackupConstants.TRANSPORT_OK) {
1952 // if things went wrong at this point, we need to
1953 // restage everything and try again later.
1954 resetBackupState(mStateDir); // Just to make sure.
1955 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001956 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001957 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001958 }
1959
Christopher Tate8e294d42011-08-31 20:37:12 -07001960 // Transport has been initialized and the PM metadata submitted successfully
1961 // if that was warranted. Now we process the single next thing in the queue.
1962 void invokeNextAgent() {
1963 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate6de74ff2012-01-17 15:20:32 -08001964 addBackupTrace("invoke q=" + mQueue.size());
Christopher Tate043dadc2009-06-02 16:11:00 -07001965
Christopher Tate8e294d42011-08-31 20:37:12 -07001966 // Sanity check that we have work to do. If not, skip to the end where
1967 // we reestablish the wakelock invariants etc.
1968 if (mQueue.isEmpty()) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08001969 if (DEBUG) Slog.i(TAG, "queue now empty");
Christopher Tate8e294d42011-08-31 20:37:12 -07001970 executeNextState(BackupState.FINAL);
1971 return;
1972 }
1973
1974 // pop the entry we're going to process on this step
1975 BackupRequest request = mQueue.get(0);
1976 mQueue.remove(0);
1977
1978 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001979 addBackupTrace("launch agent for " + request.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07001980
1981 // Verify that the requested app exists; it might be something that
1982 // requested a backup but was then uninstalled. The request was
1983 // journalled and rather than tamper with the journal it's safer
1984 // to sanity-check here. This also gives us the classname of the
1985 // package's backup agent.
1986 try {
1987 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1988 PackageManager.GET_SIGNATURES);
Christopher Tatec28083a2010-12-14 16:16:44 -08001989
Christopher Tate043dadc2009-06-02 16:11:00 -07001990 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001991 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001992 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1993 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001994 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tate6de74ff2012-01-17 15:20:32 -08001995 addBackupTrace("agent bound; a? = " + (agent != null));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001996 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001997 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
1998 // at this point we'll either get a completion callback from the
1999 // agent, or a timeout message on the main handler. either way, we're
2000 // done here as long as we're successful so far.
2001 } else {
2002 // Timeout waiting for the agent
2003 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07002004 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002005 } catch (SecurityException ex) {
2006 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002007 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07002008 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002009 addBackupTrace("agent SE");
Christopher Tate8e294d42011-08-31 20:37:12 -07002010 }
2011 } catch (NameNotFoundException e) {
2012 Slog.d(TAG, "Package does not exist; skipping");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002013 addBackupTrace("no such package");
2014 mStatus = BackupConstants.AGENT_UNKNOWN;
Christopher Tate8e294d42011-08-31 20:37:12 -07002015 } finally {
2016 mWakelock.setWorkSource(null);
2017
2018 // If there was an agent error, no timeout/completion handling will occur.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002019 // That means we need to direct to the next state ourselves.
Christopher Tate8e294d42011-08-31 20:37:12 -07002020 if (mStatus != BackupConstants.TRANSPORT_OK) {
2021 BackupState nextState = BackupState.RUNNING_QUEUE;
2022
2023 // An agent-level failure means we reenqueue this one agent for
2024 // a later retry, but otherwise proceed normally.
2025 if (mStatus == BackupConstants.AGENT_ERROR) {
2026 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
2027 + " - restaging");
2028 dataChangedImpl(request.packageName);
2029 mStatus = BackupConstants.TRANSPORT_OK;
2030 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
Christopher Tate6de74ff2012-01-17 15:20:32 -08002031 } else if (mStatus == BackupConstants.AGENT_UNKNOWN) {
2032 // Failed lookup of the app, so we couldn't bring up an agent, but
2033 // we're otherwise fine. Just drop it and go on to the next as usual.
2034 mStatus = BackupConstants.TRANSPORT_OK;
2035 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002036 // Transport-level failure means we reenqueue everything
2037 revertAndEndBackup();
2038 nextState = BackupState.FINAL;
2039 }
2040
2041 executeNextState(nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002042 } else {
2043 addBackupTrace("expecting completion/timeout callback");
Christopher Tate043dadc2009-06-02 16:11:00 -07002044 }
2045 }
2046 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002047
Christopher Tate8e294d42011-08-31 20:37:12 -07002048 void finalizeBackup() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002049 addBackupTrace("finishing");
2050
Christopher Tate8e294d42011-08-31 20:37:12 -07002051 // Either backup was successful, in which case we of course do not need
2052 // this pass's journal any more; or it failed, in which case we just
2053 // re-enqueued all of these packages in the current active journal.
2054 // Either way, we no longer need this pass's journal.
2055 if (mJournal != null && !mJournal.delete()) {
2056 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
2057 }
2058
2059 // If everything actually went through and this is the first time we've
2060 // done a backup, we can now record what the current backup dataset token
2061 // is.
2062 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002063 addBackupTrace("success; recording token");
Christopher Tate8e294d42011-08-31 20:37:12 -07002064 try {
2065 mCurrentToken = mTransport.getCurrentRestoreSet();
2066 } catch (RemoteException e) {} // can't happen
2067 writeRestoreTokens();
2068 }
2069
Christopher Tate336a6492011-10-05 16:05:43 -07002070 // Set up the next backup pass - at this point we can set mBackupRunning
2071 // to false to allow another pass to fire, because we're done with the
2072 // state machine sequence and the wakelock is refcounted.
2073 synchronized (mQueueLock) {
2074 mBackupRunning = false;
2075 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tatee659fb92011-10-10 16:34:50 -07002076 // Make sure we back up everything and perform the one-time init
2077 clearMetadata();
2078 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002079 addBackupTrace("init required; rerunning");
Christopher Tate336a6492011-10-05 16:05:43 -07002080 backupNow();
2081 }
Christopher Tate8e294d42011-08-31 20:37:12 -07002082 }
2083
2084 // Only once we're entirely finished do we release the wakelock
Christopher Tate6de74ff2012-01-17 15:20:32 -08002085 clearBackupTrace();
Christopher Tate8e294d42011-08-31 20:37:12 -07002086 Slog.i(TAG, "Backup pass finished.");
2087 mWakelock.release();
2088 }
2089
Christopher Tatee659fb92011-10-10 16:34:50 -07002090 // Remove the PM metadata state. This will generate an init on the next pass.
2091 void clearMetadata() {
2092 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
2093 if (pmState.exists()) pmState.delete();
2094 }
2095
Christopher Tate8e294d42011-08-31 20:37:12 -07002096 // Invoke an agent's doBackup() and start a timeout message spinning on the main
2097 // handler in case it doesn't get back to us.
2098 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07002099 IBackupTransport transport) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002100 if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
2101 addBackupTrace("invoking " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002102
Christopher Tate8e294d42011-08-31 20:37:12 -07002103 mSavedStateName = new File(mStateDir, packageName);
2104 mBackupDataName = new File(mDataDir, packageName + ".data");
2105 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002106
Christopher Tate8e294d42011-08-31 20:37:12 -07002107 mSavedState = null;
2108 mBackupData = null;
2109 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002110
Christopher Tate4a627c72011-04-01 14:43:32 -07002111 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002112 try {
2113 // Look up the package info & signatures. This is first so that if it
2114 // throws an exception, there's no file setup yet that would need to
2115 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07002116 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002117 // The metadata 'package' is synthetic; construct one and make
2118 // sure our global state is pointed at it
2119 mCurrentPackage = new PackageInfo();
2120 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002121 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002122
Christopher Tatec7b31e32009-06-10 15:49:30 -07002123 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002124 // the saved-state "file". This is by definition an incremental,
2125 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002126 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002127 ParcelFileDescriptor.MODE_READ_ONLY |
2128 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002129
Christopher Tate8e294d42011-08-31 20:37:12 -07002130 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002131 ParcelFileDescriptor.MODE_READ_WRITE |
2132 ParcelFileDescriptor.MODE_CREATE |
2133 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002134
Christopher Tate8e294d42011-08-31 20:37:12 -07002135 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002136 ParcelFileDescriptor.MODE_READ_WRITE |
2137 ParcelFileDescriptor.MODE_CREATE |
2138 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002139
Christopher Tate44a27902010-01-27 17:15:49 -08002140 // Initiate the target's backup pass
Christopher Tate6de74ff2012-01-17 15:20:32 -08002141 addBackupTrace("setting timeout");
Christopher Tate8e294d42011-08-31 20:37:12 -07002142 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002143 addBackupTrace("calling agent doBackup()");
Christopher Tate8e294d42011-08-31 20:37:12 -07002144 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002145 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002146 Slog.e(TAG, "Error invoking for backup on " + packageName);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002147 addBackupTrace("exception: " + e);
Christopher Tate8e294d42011-08-31 20:37:12 -07002148 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2149 e.toString());
2150 agentErrorCleanup();
2151 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002152 }
2153
Christopher Tate8e294d42011-08-31 20:37:12 -07002154 // At this point the agent is off and running. The next thing to happen will
2155 // either be a callback from the agent, at which point we'll process its data
2156 // for transport, or a timeout. Either way the next phase will happen in
2157 // response to the TimeoutHandler interface callbacks.
Christopher Tate6de74ff2012-01-17 15:20:32 -08002158 addBackupTrace("invoke success");
Christopher Tate8e294d42011-08-31 20:37:12 -07002159 return BackupConstants.TRANSPORT_OK;
2160 }
2161
2162 @Override
2163 public void operationComplete() {
2164 // Okay, the agent successfully reported back to us. Spin the data off to the
2165 // transport and proceed with the next stage.
2166 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2167 + mCurrentPackage.packageName);
2168 mBackupHandler.removeMessages(MSG_TIMEOUT);
2169 clearAgentState();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002170 addBackupTrace("operation complete");
Christopher Tate8e294d42011-08-31 20:37:12 -07002171
2172 ParcelFileDescriptor backupData = null;
2173 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002174 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002175 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002176 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002177 if (mStatus == BackupConstants.TRANSPORT_OK) {
2178 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002179 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002180 addBackupTrace("sending data to transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002181 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002182 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002183
Dan Egnor83861e72009-09-17 16:17:55 -07002184 // TODO - We call finishBackup() for each application backed up, because
2185 // we need to know now whether it succeeded or failed. Instead, we should
2186 // hold off on finishBackup() until the end, which implies holding off on
2187 // renaming *all* the output state files (see below) until that happens.
2188
Christopher Tate6de74ff2012-01-17 15:20:32 -08002189 addBackupTrace("data delivered: " + mStatus);
Christopher Tate8e294d42011-08-31 20:37:12 -07002190 if (mStatus == BackupConstants.TRANSPORT_OK) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002191 addBackupTrace("finishing op on transport");
Christopher Tate8e294d42011-08-31 20:37:12 -07002192 mStatus = mTransport.finishBackup();
Christopher Tate6de74ff2012-01-17 15:20:32 -08002193 addBackupTrace("finished: " + mStatus);
Dan Egnor83861e72009-09-17 16:17:55 -07002194 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002195 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002196 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002197 addBackupTrace("no data to send");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002198 }
2199
2200 // After successful transport, delete the now-stale data
2201 // and juggle the files so that next time we supply the agent
2202 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002203 if (mStatus == BackupConstants.TRANSPORT_OK) {
2204 mBackupDataName.delete();
2205 mNewStateName.renameTo(mSavedStateName);
2206 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2207 mCurrentPackage.packageName, size);
2208 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002209 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002210 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2211 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002212 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002213 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002214 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2215 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2216 mCurrentPackage.packageName);
2217 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002218 } finally {
2219 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002220 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002221
Christopher Tate8e294d42011-08-31 20:37:12 -07002222 // If we encountered an error here it's a transport-level failure. That
2223 // means we need to halt everything and reschedule everything for next time.
2224 final BackupState nextState;
2225 if (mStatus != BackupConstants.TRANSPORT_OK) {
2226 revertAndEndBackup();
2227 nextState = BackupState.FINAL;
2228 } else {
2229 // Success! Proceed with the next app if any, otherwise we're done.
2230 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2231 }
2232
2233 executeNextState(nextState);
2234 }
2235
2236 @Override
2237 public void handleTimeout() {
2238 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2239 // it for the next time we run a backup pass.
2240 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2241 // fail repeatedly (i.e. have proved themselves to be buggy).
2242 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2243 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2244 "timeout");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002245 addBackupTrace("timeout of " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002246 agentErrorCleanup();
2247 dataChangedImpl(mCurrentPackage.packageName);
2248 }
2249
2250 void revertAndEndBackup() {
2251 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
Christopher Tate6de74ff2012-01-17 15:20:32 -08002252 addBackupTrace("transport error; reverting");
Christopher Tate8e294d42011-08-31 20:37:12 -07002253 for (BackupRequest request : mOriginalQueue) {
2254 dataChangedImpl(request.packageName);
2255 }
2256 // We also want to reset the backup schedule based on whatever
2257 // the transport suggests by way of retry/backoff time.
2258 restartBackupAlarm();
2259 }
2260
2261 void agentErrorCleanup() {
2262 mBackupDataName.delete();
2263 mNewStateName.delete();
2264 clearAgentState();
2265
2266 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2267 }
2268
2269 // Cleanup common to both success and failure cases
2270 void clearAgentState() {
2271 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2272 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2273 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2274 mSavedState = mBackupData = mNewState = null;
2275 synchronized (mCurrentOpLock) {
2276 mCurrentOperations.clear();
2277 }
2278
2279 // If this was a pseudopackage there's no associated Activity Manager state
2280 if (mCurrentPackage.applicationInfo != null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002281 addBackupTrace("unbinding " + mCurrentPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002282 try { // unbind even on timeout, just in case
2283 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2284 } catch (RemoteException e) {}
2285 }
2286 }
2287
2288 void restartBackupAlarm() {
Christopher Tate6de74ff2012-01-17 15:20:32 -08002289 addBackupTrace("setting backup trigger");
Christopher Tate8e294d42011-08-31 20:37:12 -07002290 synchronized (mQueueLock) {
2291 try {
2292 startBackupAlarmsLocked(mTransport.requestBackupTime());
2293 } catch (RemoteException e) { /* cannot happen */ }
2294 }
2295 }
2296
2297 void executeNextState(BackupState nextState) {
2298 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2299 + this + " nextState=" + nextState);
Christopher Tate6de74ff2012-01-17 15:20:32 -08002300 addBackupTrace("executeNextState => " + nextState);
Christopher Tate8e294d42011-08-31 20:37:12 -07002301 mCurrentState = nextState;
2302 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2303 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002304 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002305 }
2306
Christopher Tatedf01dea2009-06-09 20:45:02 -07002307
Christopher Tate4a627c72011-04-01 14:43:32 -07002308 // ----- Full backup to a file/socket -----
2309
2310 class PerformFullBackupTask implements Runnable {
2311 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002312 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002313 IFullBackupRestoreObserver mObserver;
2314 boolean mIncludeApks;
2315 boolean mIncludeShared;
2316 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002317 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002318 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002319 String mCurrentPassword;
2320 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002321 AtomicBoolean mLatchObject;
2322 File mFilesDir;
2323 File mManifestFile;
2324
Christopher Tate7926a692011-07-11 11:31:57 -07002325 class FullBackupRunner implements Runnable {
2326 PackageInfo mPackage;
2327 IBackupAgent mAgent;
2328 ParcelFileDescriptor mPipe;
2329 int mToken;
2330 boolean mSendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002331 boolean mWriteManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002332
2333 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
Christopher Tate73d73692012-01-20 17:11:31 -08002334 int token, boolean sendApk, boolean writeManifest) throws IOException {
Christopher Tate7926a692011-07-11 11:31:57 -07002335 mPackage = pack;
2336 mAgent = agent;
2337 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2338 mToken = token;
2339 mSendApk = sendApk;
Christopher Tate73d73692012-01-20 17:11:31 -08002340 mWriteManifest = writeManifest;
Christopher Tate7926a692011-07-11 11:31:57 -07002341 }
2342
2343 @Override
2344 public void run() {
2345 try {
2346 BackupDataOutput output = new BackupDataOutput(
2347 mPipe.getFileDescriptor());
2348
Christopher Tate73d73692012-01-20 17:11:31 -08002349 if (mWriteManifest) {
2350 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
2351 writeAppManifest(mPackage, mManifestFile, mSendApk);
2352 FullBackup.backupToTar(mPackage.packageName, null, null,
2353 mFilesDir.getAbsolutePath(),
2354 mManifestFile.getAbsolutePath(),
2355 output);
2356 }
Christopher Tate7926a692011-07-11 11:31:57 -07002357
2358 if (mSendApk) {
2359 writeApkToBackup(mPackage, output);
2360 }
2361
Christopher Tatec58efa62011-08-01 19:20:14 -07002362 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002363 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002364 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2365 } catch (IOException e) {
2366 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2367 } catch (RemoteException e) {
2368 Slog.e(TAG, "Remote agent vanished during full backup of "
2369 + mPackage.packageName);
2370 } finally {
2371 try {
2372 mPipe.close();
2373 } catch (IOException e) {}
2374 }
2375 }
2376 }
2377
Christopher Tate4a627c72011-04-01 14:43:32 -07002378 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002379 boolean includeApks, boolean includeShared, String curPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -07002380 String encryptPassword, boolean doAllApps, boolean doSystem, String[] packages,
Christopher Tate728a1c42011-07-28 18:03:03 -07002381 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002382 mOutputFile = fd;
2383 mObserver = observer;
2384 mIncludeApks = includeApks;
2385 mIncludeShared = includeShared;
2386 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002387 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002388 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002389 mCurrentPassword = curPassword;
2390 // when backing up, if there is a current backup password, we require that
2391 // the user use a nonempty encryption password as well. if one is supplied
2392 // in the UI we use that, but if the UI was left empty we fall back to the
2393 // current backup password (which was supplied by the user as well).
2394 if (encryptPassword == null || "".equals(encryptPassword)) {
2395 mEncryptPassword = curPassword;
2396 } else {
2397 mEncryptPassword = encryptPassword;
2398 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002399 mLatchObject = latch;
2400
2401 mFilesDir = new File("/data/system");
2402 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2403 }
2404
2405 @Override
2406 public void run() {
Christopher Tate240c7d22011-10-03 18:13:44 -07002407 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
Christopher Tate4a627c72011-04-01 14:43:32 -07002408
Christopher Tateb0628bf2011-06-02 15:08:13 -07002409 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002410 sendStartBackup();
2411
2412 // doAllApps supersedes the package set if any
2413 if (mAllApps) {
2414 packagesToBackup = mPackageManager.getInstalledPackages(
2415 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002416 // Exclude system apps if we've been asked to do so
2417 if (mIncludeSystem == false) {
2418 for (int i = 0; i < packagesToBackup.size(); ) {
2419 PackageInfo pkg = packagesToBackup.get(i);
2420 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2421 packagesToBackup.remove(i);
2422 } else {
2423 i++;
2424 }
2425 }
2426 }
2427 }
2428
2429 // Now process the command line argument packages, if any. Note that explicitly-
2430 // named system-partition packages will be included even if includeSystem was
2431 // set to false.
2432 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002433 for (String pkgName : mPackages) {
2434 try {
2435 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2436 PackageManager.GET_SIGNATURES));
2437 } catch (NameNotFoundException e) {
2438 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2439 }
2440 }
2441 }
2442
Christopher Tate73d73692012-01-20 17:11:31 -08002443 // Cull any packages that have indicated that backups are not permitted, as well
2444 // as any explicit mention of the 'special' shared-storage agent package (we
2445 // handle that one at the end).
Christopher Tatea858cb02011-06-03 12:27:51 -07002446 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002447 PackageInfo pkg = packagesToBackup.get(i);
Christopher Tate73d73692012-01-20 17:11:31 -08002448 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0
2449 || pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE)) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002450 packagesToBackup.remove(i);
2451 } else {
2452 i++;
2453 }
2454 }
2455
Christopher Tate7926a692011-07-11 11:31:57 -07002456 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002457 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002458
Christopher Tate4a627c72011-04-01 14:43:32 -07002459 PackageInfo pkg = null;
2460 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002461 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002462 boolean compressing = COMPRESS_FULL_BACKUPS;
2463 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002464
Christopher Tateeef4ae42011-08-05 13:15:53 -07002465 // Verify that the given password matches the currently-active
2466 // backup password, if any
2467 if (hasBackupPassword()) {
2468 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2469 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2470 return;
2471 }
2472 }
2473
Christopher Tate7bdb0962011-07-13 19:30:21 -07002474 // Write the global file header. All strings are UTF-8 encoded; lines end
2475 // with a '\n' byte. Actual backup data begins immediately following the
2476 // final '\n'.
2477 //
2478 // line 1: "ANDROID BACKUP"
2479 // line 2: backup file format version, currently "1"
2480 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002481 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2482 //
2483 // When line 4 is not "none", then additional header data follows:
2484 //
2485 // line 5: user password salt [hex]
2486 // line 6: master key checksum salt [hex]
2487 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2488 // line 8: IV of the user key [hex]
2489 // line 9: master key blob [hex]
2490 // IV of the master key, master key itself, master key checksum hash
2491 //
2492 // The master key checksum is the master key plus its checksum salt, run through
2493 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2494 // correct password for decrypting the archive: the master key decrypted from
2495 // the archive using the user-supplied password is also run through PBKDF2 in
2496 // this way, and if the result does not match the checksum as stored in the
2497 // archive, then we know that the user-supplied password does not match the
2498 // archive's.
2499 StringBuilder headerbuf = new StringBuilder(1024);
2500
Christopher Tate7bdb0962011-07-13 19:30:21 -07002501 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002502 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2503 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002504
2505 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002506 // Set up the encryption stage if appropriate, and emit the correct header
2507 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002508 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2509 } else {
2510 headerbuf.append("none\n");
2511 }
2512
Christopher Tate7bdb0962011-07-13 19:30:21 -07002513 byte[] header = headerbuf.toString().getBytes("UTF-8");
2514 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002515
2516 // Set up the compression stage feeding into the encryption stage (if any)
2517 if (compressing) {
2518 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2519 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2520 }
2521
2522 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002523 } catch (Exception e) {
2524 // Should never happen!
2525 Slog.e(TAG, "Unable to emit archive header", e);
2526 return;
2527 }
2528
Christopher Tate73d73692012-01-20 17:11:31 -08002529 // Shared storage if requested
2530 if (mIncludeShared) {
2531 try {
2532 pkg = mPackageManager.getPackageInfo(SHARED_BACKUP_AGENT_PACKAGE, 0);
2533 packagesToBackup.add(pkg);
2534 } catch (NameNotFoundException e) {
2535 Slog.e(TAG, "Unable to find shared-storage backup handler");
2536 }
2537 }
2538
Christopher Tateb0628bf2011-06-02 15:08:13 -07002539 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002540 int N = packagesToBackup.size();
2541 for (int i = 0; i < N; i++) {
2542 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002543 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002544 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002545
Christopher Tate6853fcf2011-08-10 17:52:21 -07002546 // Done!
2547 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002548 } catch (RemoteException e) {
2549 Slog.e(TAG, "App died during full backup");
Christopher Tateaa0c02d2012-03-23 13:56:34 -07002550 } catch (Exception e) {
2551 Slog.e(TAG, "Internal exception during full backup", e);
Christopher Tate4a627c72011-04-01 14:43:32 -07002552 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002553 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002554 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002555 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002556 mOutputFile.close();
2557 } catch (IOException e) {
2558 /* nothing we can do about this */
2559 }
2560 synchronized (mCurrentOpLock) {
2561 mCurrentOperations.clear();
2562 }
2563 synchronized (mLatchObject) {
2564 mLatchObject.set(true);
2565 mLatchObject.notifyAll();
2566 }
2567 sendEndBackup();
Christopher Tate4a627c72011-04-01 14:43:32 -07002568 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002569 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002570 }
2571 }
2572
Christopher Tate2efd2db2011-07-19 16:32:49 -07002573 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2574 OutputStream ofstream) throws Exception {
2575 // User key will be used to encrypt the master key.
2576 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002577 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002578 PBKDF2_HASH_ROUNDS);
2579
2580 // the master key is random for each backup
2581 byte[] masterPw = new byte[256 / 8];
2582 mRng.nextBytes(masterPw);
2583 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2584
2585 // primary encryption of the datastream with the random key
2586 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2587 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2588 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2589 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2590
2591 // line 4: name of encryption algorithm
2592 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2593 headerbuf.append('\n');
2594 // line 5: user password salt [hex]
2595 headerbuf.append(byteArrayToHex(newUserSalt));
2596 headerbuf.append('\n');
2597 // line 6: master key checksum salt [hex]
2598 headerbuf.append(byteArrayToHex(checksumSalt));
2599 headerbuf.append('\n');
2600 // line 7: number of PBKDF2 rounds used [decimal]
2601 headerbuf.append(PBKDF2_HASH_ROUNDS);
2602 headerbuf.append('\n');
2603
2604 // line 8: IV of the user key [hex]
2605 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2606 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2607
2608 byte[] IV = mkC.getIV();
2609 headerbuf.append(byteArrayToHex(IV));
2610 headerbuf.append('\n');
2611
2612 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2613 // [byte] IV length = Niv
2614 // [array of Niv bytes] IV itself
2615 // [byte] master key length = Nmk
2616 // [array of Nmk bytes] master key itself
2617 // [byte] MK checksum hash length = Nck
2618 // [array of Nck bytes] master key checksum hash
2619 //
2620 // The checksum is the (master key + checksum salt), run through the
2621 // stated number of PBKDF2 rounds
2622 IV = c.getIV();
2623 byte[] mk = masterKeySpec.getEncoded();
2624 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2625 checksumSalt, PBKDF2_HASH_ROUNDS);
2626
2627 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2628 + checksum.length + 3);
2629 DataOutputStream mkOut = new DataOutputStream(blob);
2630 mkOut.writeByte(IV.length);
2631 mkOut.write(IV);
2632 mkOut.writeByte(mk.length);
2633 mkOut.write(mk);
2634 mkOut.writeByte(checksum.length);
2635 mkOut.write(checksum);
2636 mkOut.flush();
2637 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2638 headerbuf.append(byteArrayToHex(encryptedMk));
2639 headerbuf.append('\n');
2640
2641 return finalOutput;
2642 }
2643
2644 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002645 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002646 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2647
2648 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2649 IApplicationThread.BACKUP_MODE_FULL);
2650 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002651 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002652 try {
Christopher Tate73d73692012-01-20 17:11:31 -08002653 pipes = ParcelFileDescriptor.createPipe();
Christopher Tate7926a692011-07-11 11:31:57 -07002654
Christopher Tateb0628bf2011-06-02 15:08:13 -07002655 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate73d73692012-01-20 17:11:31 -08002656 final boolean isSharedStorage = pkg.packageName.equals(SHARED_BACKUP_AGENT_PACKAGE);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002657 final boolean sendApk = mIncludeApks
Christopher Tate73d73692012-01-20 17:11:31 -08002658 && !isSharedStorage
Christopher Tateb0628bf2011-06-02 15:08:13 -07002659 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2660 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2661 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2662
Christopher Tate73d73692012-01-20 17:11:31 -08002663 sendOnBackupPackage(isSharedStorage ? "Shared storage" : pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002664
Christopher Tate7926a692011-07-11 11:31:57 -07002665 final int token = generateToken();
2666 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
Christopher Tate73d73692012-01-20 17:11:31 -08002667 token, sendApk, !isSharedStorage);
Christopher Tate7926a692011-07-11 11:31:57 -07002668 pipes[1].close(); // the runner has dup'd it
2669 pipes[1] = null;
2670 Thread t = new Thread(runner);
2671 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002672
Christopher Tate7926a692011-07-11 11:31:57 -07002673 // Now pull data from the app and stuff it into the compressor
2674 try {
2675 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2676 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002677
Christopher Tate7926a692011-07-11 11:31:57 -07002678 byte[] buffer = new byte[16 * 1024];
2679 int chunkTotal;
2680 while ((chunkTotal = in.readInt()) > 0) {
2681 while (chunkTotal > 0) {
2682 int toRead = (chunkTotal > buffer.length)
2683 ? buffer.length : chunkTotal;
2684 int nRead = in.read(buffer, 0, toRead);
2685 out.write(buffer, 0, nRead);
2686 chunkTotal -= nRead;
2687 }
2688 }
2689 } catch (IOException e) {
2690 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002691 }
2692
Christopher Tateb0628bf2011-06-02 15:08:13 -07002693 if (!waitUntilOperationComplete(token)) {
2694 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2695 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002696 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002697 }
Christopher Tate7926a692011-07-11 11:31:57 -07002698
Christopher Tateb0628bf2011-06-02 15:08:13 -07002699 } catch (IOException e) {
2700 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002701 } finally {
2702 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002703 // flush after every package
2704 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002705 if (pipes != null) {
2706 if (pipes[0] != null) pipes[0].close();
2707 if (pipes[1] != null) pipes[1].close();
2708 }
Christopher Tate7926a692011-07-11 11:31:57 -07002709 } catch (IOException e) {
2710 Slog.w(TAG, "Error bringing down backup stack");
2711 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002712 }
2713 } else {
2714 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2715 }
2716 tearDown(pkg);
2717 }
2718
Christopher Tate79ec80d2011-06-24 14:58:49 -07002719 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2720 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2721 final String appSourceDir = pkg.applicationInfo.sourceDir;
2722 final String apkDir = new File(appSourceDir).getParent();
2723 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2724 apkDir, appSourceDir, output);
2725
2726 // Save associated .obb content if it exists and we did save the apk
2727 // check for .obb and save those too
2728 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2729 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002730 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002731 File[] obbFiles = obbDir.listFiles();
2732 if (obbFiles != null) {
2733 final String obbDirName = obbDir.getAbsolutePath();
2734 for (File obb : obbFiles) {
2735 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2736 obbDirName, obb.getAbsolutePath(), output);
2737 }
2738 }
2739 }
2740 }
2741
Christopher Tate6853fcf2011-08-10 17:52:21 -07002742 private void finalizeBackup(OutputStream out) {
2743 try {
2744 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2745 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2746 out.write(eof);
2747 } catch (IOException e) {
2748 Slog.w(TAG, "Error attempting to finalize backup stream");
2749 }
2750 }
2751
Christopher Tate4a627c72011-04-01 14:43:32 -07002752 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2753 throws IOException {
2754 // Manifest format. All data are strings ending in LF:
2755 // BACKUP_MANIFEST_VERSION, currently 1
2756 //
2757 // Version 1:
2758 // package name
2759 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002760 // platform versionCode
2761 // getInstallerPackageName() for this package (maybe empty)
2762 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002763 // number of signatures == N
2764 // N*: signature byte array in ascii format per Signature.toCharsString()
2765 StringBuilder builder = new StringBuilder(4096);
2766 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2767
2768 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2769 printer.println(pkg.packageName);
2770 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002771 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2772
2773 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2774 printer.println((installerName != null) ? installerName : "");
2775
Christopher Tate4a627c72011-04-01 14:43:32 -07002776 printer.println(withApk ? "1" : "0");
2777 if (pkg.signatures == null) {
2778 printer.println("0");
2779 } else {
2780 printer.println(Integer.toString(pkg.signatures.length));
2781 for (Signature sig : pkg.signatures) {
2782 printer.println(sig.toCharsString());
2783 }
2784 }
2785
2786 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002787 outstream.write(builder.toString().getBytes());
2788 outstream.close();
2789 }
2790
2791 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002792 if (pkg != null) {
2793 final ApplicationInfo app = pkg.applicationInfo;
2794 if (app != null) {
2795 try {
2796 // unbind and tidy up even on timeout or failure, just in case
2797 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002798
Christopher Tateb0628bf2011-06-02 15:08:13 -07002799 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002800 if (app.uid != Process.SYSTEM_UID
2801 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002802 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002803 mActivityManager.killApplicationProcess(app.processName, app.uid);
2804 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002805 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002806 }
2807 } catch (RemoteException e) {
2808 Slog.d(TAG, "Lost app trying to shut down");
2809 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002810 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002811 }
2812 }
2813
2814 // wrappers for observer use
2815 void sendStartBackup() {
2816 if (mObserver != null) {
2817 try {
2818 mObserver.onStartBackup();
2819 } catch (RemoteException e) {
2820 Slog.w(TAG, "full backup observer went away: startBackup");
2821 mObserver = null;
2822 }
2823 }
2824 }
2825
2826 void sendOnBackupPackage(String name) {
2827 if (mObserver != null) {
2828 try {
2829 // TODO: use a more user-friendly name string
2830 mObserver.onBackupPackage(name);
2831 } catch (RemoteException e) {
2832 Slog.w(TAG, "full backup observer went away: backupPackage");
2833 mObserver = null;
2834 }
2835 }
2836 }
2837
2838 void sendEndBackup() {
2839 if (mObserver != null) {
2840 try {
2841 mObserver.onEndBackup();
2842 } catch (RemoteException e) {
2843 Slog.w(TAG, "full backup observer went away: endBackup");
2844 mObserver = null;
2845 }
2846 }
2847 }
2848 }
2849
2850
Christopher Tate75a99702011-05-18 16:28:19 -07002851 // ----- Full restore from a file/socket -----
2852
2853 // Description of a file in the restore datastream
2854 static class FileMetadata {
2855 String packageName; // name of the owning app
2856 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002857 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002858 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2859 String path; // subpath within the semantic domain
2860 long mode; // e.g. 0666 (actually int)
2861 long mtime; // last mod time, UTC time_t (actually int)
2862 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002863
2864 @Override
2865 public String toString() {
2866 StringBuilder sb = new StringBuilder(128);
2867 sb.append("FileMetadata{");
2868 sb.append(packageName); sb.append(',');
2869 sb.append(type); sb.append(',');
2870 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2871 sb.append(size);
2872 sb.append('}');
2873 return sb.toString();
2874 }
Christopher Tate75a99702011-05-18 16:28:19 -07002875 }
2876
2877 enum RestorePolicy {
2878 IGNORE,
2879 ACCEPT,
2880 ACCEPT_IF_APK
2881 }
2882
2883 class PerformFullRestoreTask implements Runnable {
2884 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002885 String mCurrentPassword;
2886 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002887 IFullBackupRestoreObserver mObserver;
2888 AtomicBoolean mLatchObject;
2889 IBackupAgent mAgent;
2890 String mAgentPackage;
2891 ApplicationInfo mTargetApp;
2892 ParcelFileDescriptor[] mPipes = null;
2893
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002894 long mBytes;
2895
Christopher Tate75a99702011-05-18 16:28:19 -07002896 // possible handling states for a given package in the restore dataset
2897 final HashMap<String, RestorePolicy> mPackagePolicies
2898 = new HashMap<String, RestorePolicy>();
2899
2900 // installer package names for each encountered app, derived from the manifests
2901 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2902
2903 // Signatures for a given package found in its manifest file
2904 final HashMap<String, Signature[]> mManifestSignatures
2905 = new HashMap<String, Signature[]>();
2906
2907 // Packages we've already wiped data on when restoring their first file
2908 final HashSet<String> mClearedPackages = new HashSet<String>();
2909
Christopher Tate728a1c42011-07-28 18:03:03 -07002910 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002911 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002912 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002913 mCurrentPassword = curPassword;
2914 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002915 mObserver = observer;
2916 mLatchObject = latch;
2917 mAgent = null;
2918 mAgentPackage = null;
2919 mTargetApp = null;
2920
2921 // Which packages we've already wiped data on. We prepopulate this
2922 // with a whitelist of packages known to be unclearable.
2923 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002924 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002925
Christopher Tate75a99702011-05-18 16:28:19 -07002926 }
2927
2928 class RestoreFileRunnable implements Runnable {
2929 IBackupAgent mAgent;
2930 FileMetadata mInfo;
2931 ParcelFileDescriptor mSocket;
2932 int mToken;
2933
2934 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2935 ParcelFileDescriptor socket, int token) throws IOException {
2936 mAgent = agent;
2937 mInfo = info;
2938 mToken = token;
2939
2940 // This class is used strictly for process-local binder invocations. The
2941 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2942 // do not automatically get a 'dup'ed descriptor that we can can continue
2943 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2944 // before proceeding to do the restore.
2945 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2946 }
2947
2948 @Override
2949 public void run() {
2950 try {
2951 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2952 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2953 mToken, mBackupManagerBinder);
2954 } catch (RemoteException e) {
2955 // never happens; this is used strictly for local binder calls
2956 }
2957 }
2958 }
2959
2960 @Override
2961 public void run() {
2962 Slog.i(TAG, "--- Performing full-dataset restore ---");
2963 sendStartRestore();
2964
Christopher Tateb0628bf2011-06-02 15:08:13 -07002965 // Are we able to restore shared-storage data?
2966 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Christopher Tate73d73692012-01-20 17:11:31 -08002967 mPackagePolicies.put(SHARED_BACKUP_AGENT_PACKAGE, RestorePolicy.ACCEPT);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002968 }
2969
Christopher Tate2efd2db2011-07-19 16:32:49 -07002970 FileInputStream rawInStream = null;
2971 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002972 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002973 if (hasBackupPassword()) {
2974 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2975 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2976 return;
2977 }
2978 }
2979
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002980 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002981 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002982 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2983 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002984
2985 // First, parse out the unencrypted/uncompressed header
2986 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002987 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002988 final InputStream in;
2989
2990 boolean okay = false;
2991 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2992 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002993 rawDataIn.readFully(streamHeader);
2994 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2995 if (Arrays.equals(magicBytes, streamHeader)) {
2996 // okay, header looks good. now parse out the rest of the fields.
2997 String s = readHeaderLine(rawInStream);
2998 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2999 // okay, it's a version we recognize
3000 s = readHeaderLine(rawInStream);
3001 compressed = (Integer.parseInt(s) != 0);
3002 s = readHeaderLine(rawInStream);
3003 if (s.equals("none")) {
3004 // no more header to parse; we're good to go
3005 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07003006 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003007 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
3008 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07003009 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003010 }
3011 } else Slog.w(TAG, "Archive is encrypted but no password given");
3012 } else Slog.w(TAG, "Wrong header version: " + s);
3013 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003014
3015 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003016 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07003017 return;
3018 }
3019
3020 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07003021 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07003022
3023 boolean didRestore;
3024 do {
Christopher Tate7926a692011-07-11 11:31:57 -07003025 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07003026 } while (didRestore);
3027
Christopher Tatec58efa62011-08-01 19:20:14 -07003028 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003029 } catch (IOException e) {
3030 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07003031 } finally {
3032 tearDownPipes();
3033 tearDownAgent(mTargetApp);
3034
3035 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003036 if (rawDataIn != null) rawDataIn.close();
3037 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07003038 mInputFile.close();
3039 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003040 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003041 /* nothing we can do about this */
3042 }
3043 synchronized (mCurrentOpLock) {
3044 mCurrentOperations.clear();
3045 }
3046 synchronized (mLatchObject) {
3047 mLatchObject.set(true);
3048 mLatchObject.notifyAll();
3049 }
3050 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07003051 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07003052 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07003053 }
3054 }
3055
Christopher Tate7bdb0962011-07-13 19:30:21 -07003056 String readHeaderLine(InputStream in) throws IOException {
3057 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003058 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07003059 while ((c = in.read()) >= 0) {
3060 if (c == '\n') break; // consume and discard the newlines
3061 buffer.append((char)c);
3062 }
3063 return buffer.toString();
3064 }
3065
Christopher Tate2efd2db2011-07-19 16:32:49 -07003066 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
3067 InputStream result = null;
3068 try {
3069 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
3070
3071 String userSaltHex = readHeaderLine(rawInStream); // 5
3072 byte[] userSalt = hexToByteArray(userSaltHex);
3073
3074 String ckSaltHex = readHeaderLine(rawInStream); // 6
3075 byte[] ckSalt = hexToByteArray(ckSaltHex);
3076
3077 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
3078 String userIvHex = readHeaderLine(rawInStream); // 8
3079
3080 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
3081
3082 // decrypt the master key blob
3083 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07003084 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07003085 rounds);
3086 byte[] IV = hexToByteArray(userIvHex);
3087 IvParameterSpec ivSpec = new IvParameterSpec(IV);
3088 c.init(Cipher.DECRYPT_MODE,
3089 new SecretKeySpec(userKey.getEncoded(), "AES"),
3090 ivSpec);
3091 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
3092 byte[] mkBlob = c.doFinal(mkCipher);
3093
3094 // first, the master key IV
3095 int offset = 0;
3096 int len = mkBlob[offset++];
3097 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
3098 offset += len;
3099 // then the master key itself
3100 len = mkBlob[offset++];
3101 byte[] mk = Arrays.copyOfRange(mkBlob,
3102 offset, offset + len);
3103 offset += len;
3104 // and finally the master key checksum hash
3105 len = mkBlob[offset++];
3106 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
3107 offset, offset + len);
3108
3109 // now validate the decrypted master key against the checksum
3110 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
3111 if (Arrays.equals(calculatedCk, mkChecksum)) {
3112 ivSpec = new IvParameterSpec(IV);
3113 c.init(Cipher.DECRYPT_MODE,
3114 new SecretKeySpec(mk, "AES"),
3115 ivSpec);
3116 // Only if all of the above worked properly will 'result' be assigned
3117 result = new CipherInputStream(rawInStream, c);
3118 } else Slog.w(TAG, "Incorrect password");
3119 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3120 } catch (InvalidAlgorithmParameterException e) {
3121 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3122 } catch (BadPaddingException e) {
3123 // This case frequently occurs when the wrong password is used to decrypt
3124 // the master key. Use the identical "incorrect password" log text as is
3125 // used in the checksum failure log in order to avoid providing additional
3126 // information to an attacker.
3127 Slog.w(TAG, "Incorrect password");
3128 } catch (IllegalBlockSizeException e) {
3129 Slog.w(TAG, "Invalid block size in master key");
3130 } catch (NoSuchAlgorithmException e) {
3131 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3132 } catch (NoSuchPaddingException e) {
3133 Slog.e(TAG, "Needed padding mechanism unavailable!");
3134 } catch (InvalidKeyException e) {
3135 Slog.w(TAG, "Illegal password; aborting");
3136 } catch (NumberFormatException e) {
3137 Slog.w(TAG, "Can't parse restore data header");
3138 } catch (IOException e) {
3139 Slog.w(TAG, "Can't read input header");
3140 }
3141
3142 return result;
3143 }
3144
Christopher Tate75a99702011-05-18 16:28:19 -07003145 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3146 FileMetadata info;
3147 try {
3148 info = readTarHeaders(instream);
3149 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003150 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003151 dumpFileMetadata(info);
3152 }
3153
3154 final String pkg = info.packageName;
3155 if (!pkg.equals(mAgentPackage)) {
3156 // okay, change in package; set up our various
3157 // bookkeeping if we haven't seen it yet
3158 if (!mPackagePolicies.containsKey(pkg)) {
3159 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3160 }
3161
3162 // Clean up the previous agent relationship if necessary,
3163 // and let the observer know we're considering a new app.
3164 if (mAgent != null) {
3165 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3166 tearDownPipes();
3167 tearDownAgent(mTargetApp);
3168 mTargetApp = null;
3169 mAgentPackage = null;
3170 }
3171 }
3172
3173 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3174 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3175 mPackageInstallers.put(pkg, info.installerPackageName);
3176 // We've read only the manifest content itself at this point,
3177 // so consume the footer before looping around to the next
3178 // input file
3179 skipTarPadding(info.size, instream);
3180 sendOnRestorePackage(pkg);
3181 } else {
3182 // Non-manifest, so it's actual file data. Is this a package
3183 // we're ignoring?
3184 boolean okay = true;
3185 RestorePolicy policy = mPackagePolicies.get(pkg);
3186 switch (policy) {
3187 case IGNORE:
3188 okay = false;
3189 break;
3190
3191 case ACCEPT_IF_APK:
3192 // If we're in accept-if-apk state, then the first file we
3193 // see MUST be the apk.
3194 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3195 if (DEBUG) Slog.d(TAG, "APK file; installing");
3196 // Try to install the app.
3197 String installerName = mPackageInstallers.get(pkg);
3198 okay = installApk(info, installerName, instream);
3199 // good to go; promote to ACCEPT
3200 mPackagePolicies.put(pkg, (okay)
3201 ? RestorePolicy.ACCEPT
3202 : RestorePolicy.IGNORE);
3203 // At this point we've consumed this file entry
3204 // ourselves, so just strip the tar footer and
3205 // go on to the next file in the input stream
3206 skipTarPadding(info.size, instream);
3207 return true;
3208 } else {
3209 // File data before (or without) the apk. We can't
3210 // handle it coherently in this case so ignore it.
3211 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3212 okay = false;
3213 }
3214 break;
3215
3216 case ACCEPT:
3217 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3218 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3219 // we can take the data without the apk, so we
3220 // *want* to do so. skip the apk by declaring this
3221 // one file not-okay without changing the restore
3222 // policy for the package.
3223 okay = false;
3224 }
3225 break;
3226
3227 default:
3228 // Something has gone dreadfully wrong when determining
3229 // the restore policy from the manifest. Ignore the
3230 // rest of this package's data.
3231 Slog.e(TAG, "Invalid policy from manifest");
3232 okay = false;
3233 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3234 break;
3235 }
3236
3237 // If the policy is satisfied, go ahead and set up to pipe the
3238 // data to the agent.
3239 if (DEBUG && okay && mAgent != null) {
3240 Slog.i(TAG, "Reusing existing agent instance");
3241 }
3242 if (okay && mAgent == null) {
3243 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3244
3245 try {
3246 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3247
3248 // If we haven't sent any data to this app yet, we probably
3249 // need to clear it first. Check that.
3250 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003251 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003252 // responsible for coherently managing a full
3253 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003254 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003255 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3256 clearApplicationDataSynchronous(pkg);
3257 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003258 if (DEBUG) Slog.d(TAG, "backup agent ("
3259 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003260 }
3261 mClearedPackages.add(pkg);
3262 } else {
3263 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3264 }
3265
3266 // All set; now set up the IPC and launch the agent
3267 setUpPipes();
3268 mAgent = bindToAgentSynchronous(mTargetApp,
3269 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3270 mAgentPackage = pkg;
3271 } catch (IOException e) {
3272 // fall through to error handling
3273 } catch (NameNotFoundException e) {
3274 // fall through to error handling
3275 }
3276
3277 if (mAgent == null) {
3278 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3279 okay = false;
3280 tearDownPipes();
3281 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3282 }
3283 }
3284
3285 // Sanity check: make sure we never give data to the wrong app. This
3286 // should never happen but a little paranoia here won't go amiss.
3287 if (okay && !pkg.equals(mAgentPackage)) {
3288 Slog.e(TAG, "Restoring data for " + pkg
3289 + " but agent is for " + mAgentPackage);
3290 okay = false;
3291 }
3292
3293 // At this point we have an agent ready to handle the full
3294 // restore data as well as a pipe for sending data to
3295 // that agent. Tell the agent to start reading from the
3296 // pipe.
3297 if (okay) {
3298 boolean agentSuccess = true;
3299 long toCopy = info.size;
3300 final int token = generateToken();
3301 try {
3302 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3303 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003304 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003305 // fire up the app's agent listening on the socket. If
3306 // the agent is running in the system process we can't
3307 // just invoke it asynchronously, so we provide a thread
3308 // for it here.
3309 if (mTargetApp.processName.equals("system")) {
3310 Slog.d(TAG, "system process agent - spinning a thread");
3311 RestoreFileRunnable runner = new RestoreFileRunnable(
3312 mAgent, info, mPipes[0], token);
3313 new Thread(runner).start();
3314 } else {
3315 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3316 info.domain, info.path, info.mode, info.mtime,
3317 token, mBackupManagerBinder);
3318 }
3319 } catch (IOException e) {
3320 // couldn't dup the socket for a process-local restore
3321 Slog.d(TAG, "Couldn't establish restore");
3322 agentSuccess = false;
3323 okay = false;
3324 } catch (RemoteException e) {
3325 // whoops, remote agent went away. We'll eat the content
3326 // ourselves, then, and not copy it over.
3327 Slog.e(TAG, "Agent crashed during full restore");
3328 agentSuccess = false;
3329 okay = false;
3330 }
3331
3332 // Copy over the data if the agent is still good
3333 if (okay) {
3334 boolean pipeOkay = true;
3335 FileOutputStream pipe = new FileOutputStream(
3336 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003337 while (toCopy > 0) {
3338 int toRead = (toCopy > buffer.length)
3339 ? buffer.length : (int)toCopy;
3340 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003341 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003342 if (nRead <= 0) break;
3343 toCopy -= nRead;
3344
3345 // send it to the output pipe as long as things
3346 // are still good
3347 if (pipeOkay) {
3348 try {
3349 pipe.write(buffer, 0, nRead);
3350 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003351 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003352 pipeOkay = false;
3353 }
3354 }
3355 }
3356
3357 // done sending that file! Now we just need to consume
3358 // the delta from info.size to the end of block.
3359 skipTarPadding(info.size, instream);
3360
3361 // and now that we've sent it all, wait for the remote
3362 // side to acknowledge receipt
3363 agentSuccess = waitUntilOperationComplete(token);
3364 }
3365
3366 // okay, if the remote end failed at any point, deal with
3367 // it by ignoring the rest of the restore on it
3368 if (!agentSuccess) {
3369 mBackupHandler.removeMessages(MSG_TIMEOUT);
3370 tearDownPipes();
3371 tearDownAgent(mTargetApp);
3372 mAgent = null;
3373 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3374 }
3375 }
3376
3377 // Problems setting up the agent communication, or an already-
3378 // ignored package: skip to the next tar stream entry by
3379 // reading and discarding this file.
3380 if (!okay) {
3381 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3382 long bytesToConsume = (info.size + 511) & ~511;
3383 while (bytesToConsume > 0) {
3384 int toRead = (bytesToConsume > buffer.length)
3385 ? buffer.length : (int)bytesToConsume;
3386 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003387 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003388 if (nRead <= 0) break;
3389 bytesToConsume -= nRead;
3390 }
3391 }
3392 }
3393 }
3394 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003395 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003396 // treat as EOF
3397 info = null;
3398 }
3399
3400 return (info != null);
3401 }
3402
3403 void setUpPipes() throws IOException {
3404 mPipes = ParcelFileDescriptor.createPipe();
3405 }
3406
3407 void tearDownPipes() {
3408 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003409 try {
3410 mPipes[0].close();
3411 mPipes[0] = null;
3412 mPipes[1].close();
3413 mPipes[1] = null;
3414 } catch (IOException e) {
3415 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003416 }
3417 mPipes = null;
3418 }
3419 }
3420
3421 void tearDownAgent(ApplicationInfo app) {
3422 if (mAgent != null) {
3423 try {
3424 // unbind and tidy up even on timeout or failure, just in case
3425 mActivityManager.unbindBackupAgent(app);
3426
3427 // The agent was running with a stub Application object, so shut it down.
3428 // !!! We hardcode the confirmation UI's package name here rather than use a
3429 // manifest flag! TODO something less direct.
3430 if (app.uid != Process.SYSTEM_UID
3431 && !app.packageName.equals("com.android.backupconfirm")) {
3432 if (DEBUG) Slog.d(TAG, "Killing host process");
3433 mActivityManager.killApplicationProcess(app.processName, app.uid);
3434 } else {
3435 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3436 }
3437 } catch (RemoteException e) {
3438 Slog.d(TAG, "Lost app trying to shut down");
3439 }
3440 mAgent = null;
3441 }
3442 }
3443
3444 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3445 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003446 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003447 int mResult;
3448
3449 public void reset() {
3450 synchronized (mDone) {
3451 mDone.set(false);
3452 }
3453 }
3454
3455 public void waitForCompletion() {
3456 synchronized (mDone) {
3457 while (mDone.get() == false) {
3458 try {
3459 mDone.wait();
3460 } catch (InterruptedException e) { }
3461 }
3462 }
3463 }
3464
3465 int getResult() {
3466 return mResult;
3467 }
3468
3469 @Override
3470 public void packageInstalled(String packageName, int returnCode)
3471 throws RemoteException {
3472 synchronized (mDone) {
3473 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003474 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003475 mDone.set(true);
3476 mDone.notifyAll();
3477 }
3478 }
3479 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003480
3481 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3482 final AtomicBoolean mDone = new AtomicBoolean();
3483 int mResult;
3484
3485 public void reset() {
3486 synchronized (mDone) {
3487 mDone.set(false);
3488 }
3489 }
3490
3491 public void waitForCompletion() {
3492 synchronized (mDone) {
3493 while (mDone.get() == false) {
3494 try {
3495 mDone.wait();
3496 } catch (InterruptedException e) { }
3497 }
3498 }
3499 }
3500
3501 @Override
3502 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3503 synchronized (mDone) {
3504 mResult = returnCode;
3505 mDone.set(true);
3506 mDone.notifyAll();
3507 }
3508 }
3509 }
3510
Christopher Tate75a99702011-05-18 16:28:19 -07003511 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003512 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003513
3514 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3515 boolean okay = true;
3516
3517 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3518
3519 // The file content is an .apk file. Copy it out to a staging location and
3520 // attempt to install it.
3521 File apkFile = new File(mDataDir, info.packageName);
3522 try {
3523 FileOutputStream apkStream = new FileOutputStream(apkFile);
3524 byte[] buffer = new byte[32 * 1024];
3525 long size = info.size;
3526 while (size > 0) {
3527 long toRead = (buffer.length < size) ? buffer.length : size;
3528 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003529 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003530 apkStream.write(buffer, 0, didRead);
3531 size -= didRead;
3532 }
3533 apkStream.close();
3534
3535 // make sure the installer can read it
3536 apkFile.setReadable(true, false);
3537
3538 // Now install it
3539 Uri packageUri = Uri.fromFile(apkFile);
3540 mInstallObserver.reset();
3541 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003542 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3543 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003544 mInstallObserver.waitForCompletion();
3545
3546 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3547 // The only time we continue to accept install of data even if the
3548 // apk install failed is if we had already determined that we could
3549 // accept the data regardless.
3550 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3551 okay = false;
3552 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003553 } else {
3554 // Okay, the install succeeded. Make sure it was the right app.
3555 boolean uninstall = false;
3556 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3557 Slog.w(TAG, "Restore stream claimed to include apk for "
3558 + info.packageName + " but apk was really "
3559 + mInstallObserver.mPackageName);
3560 // delete the package we just put in place; it might be fraudulent
3561 okay = false;
3562 uninstall = true;
3563 } else {
3564 try {
3565 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3566 PackageManager.GET_SIGNATURES);
3567 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3568 Slog.w(TAG, "Restore stream contains apk of package "
3569 + info.packageName + " but it disallows backup/restore");
3570 okay = false;
3571 } else {
3572 // So far so good -- do the signatures match the manifest?
3573 Signature[] sigs = mManifestSignatures.get(info.packageName);
3574 if (!signaturesMatch(sigs, pkg)) {
3575 Slog.w(TAG, "Installed app " + info.packageName
3576 + " signatures do not match restore manifest");
3577 okay = false;
3578 uninstall = true;
3579 }
3580 }
3581 } catch (NameNotFoundException e) {
3582 Slog.w(TAG, "Install of package " + info.packageName
3583 + " succeeded but now not found");
3584 okay = false;
3585 }
3586 }
3587
3588 // If we're not okay at this point, we need to delete the package
3589 // that we just installed.
3590 if (uninstall) {
3591 mDeleteObserver.reset();
3592 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3593 mDeleteObserver, 0);
3594 mDeleteObserver.waitForCompletion();
3595 }
Christopher Tate75a99702011-05-18 16:28:19 -07003596 }
3597 } catch (IOException e) {
3598 Slog.e(TAG, "Unable to transcribe restored apk for install");
3599 okay = false;
3600 } finally {
3601 apkFile.delete();
3602 }
3603
3604 return okay;
3605 }
3606
3607 // Given an actual file content size, consume the post-content padding mandated
3608 // by the tar format.
3609 void skipTarPadding(long size, InputStream instream) throws IOException {
3610 long partial = (size + 512) % 512;
3611 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003612 final int needed = 512 - (int)partial;
3613 byte[] buffer = new byte[needed];
3614 if (readExactly(instream, buffer, 0, needed) == needed) {
3615 mBytes += needed;
3616 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003617 }
3618 }
3619
3620 // Returns a policy constant; takes a buffer arg to reduce memory churn
3621 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3622 throws IOException {
3623 // Fail on suspiciously large manifest files
3624 if (info.size > 64 * 1024) {
3625 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3626 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003627
Christopher Tate75a99702011-05-18 16:28:19 -07003628 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003629 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3630 mBytes += info.size;
3631 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003632
3633 RestorePolicy policy = RestorePolicy.IGNORE;
3634 String[] str = new String[1];
3635 int offset = 0;
3636
3637 try {
3638 offset = extractLine(buffer, offset, str);
3639 int version = Integer.parseInt(str[0]);
3640 if (version == BACKUP_MANIFEST_VERSION) {
3641 offset = extractLine(buffer, offset, str);
3642 String manifestPackage = str[0];
3643 // TODO: handle <original-package>
3644 if (manifestPackage.equals(info.packageName)) {
3645 offset = extractLine(buffer, offset, str);
3646 version = Integer.parseInt(str[0]); // app version
3647 offset = extractLine(buffer, offset, str);
3648 int platformVersion = Integer.parseInt(str[0]);
3649 offset = extractLine(buffer, offset, str);
3650 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3651 offset = extractLine(buffer, offset, str);
3652 boolean hasApk = str[0].equals("1");
3653 offset = extractLine(buffer, offset, str);
3654 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003655 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003656 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003657 for (int i = 0; i < numSigs; i++) {
3658 offset = extractLine(buffer, offset, str);
3659 sigs[i] = new Signature(str[0]);
3660 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003661 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003662
3663 // Okay, got the manifest info we need...
3664 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003665 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3666 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003667 // Fall through to IGNORE if the app explicitly disallows backup
3668 final int flags = pkgInfo.applicationInfo.flags;
3669 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3670 // Verify signatures against any installed version; if they
3671 // don't match, then we fall though and ignore the data. The
3672 // signatureMatch() method explicitly ignores the signature
3673 // check for packages installed on the system partition, because
3674 // such packages are signed with the platform cert instead of
3675 // the app developer's cert, so they're different on every
3676 // device.
3677 if (signaturesMatch(sigs, pkgInfo)) {
3678 if (pkgInfo.versionCode >= version) {
3679 Slog.i(TAG, "Sig + version match; taking data");
3680 policy = RestorePolicy.ACCEPT;
3681 } else {
3682 // The data is from a newer version of the app than
3683 // is presently installed. That means we can only
3684 // use it if the matching apk is also supplied.
3685 Slog.d(TAG, "Data version " + version
3686 + " is newer than installed version "
3687 + pkgInfo.versionCode + " - requiring apk");
3688 policy = RestorePolicy.ACCEPT_IF_APK;
3689 }
Christopher Tate75a99702011-05-18 16:28:19 -07003690 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003691 Slog.w(TAG, "Restore manifest signatures do not match "
3692 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003693 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003694 } else {
3695 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3696 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003697 }
3698 } catch (NameNotFoundException e) {
3699 // Okay, the target app isn't installed. We can process
3700 // the restore properly only if the dataset provides the
3701 // apk file and we can successfully install it.
3702 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3703 + " not installed; requiring apk in dataset");
3704 policy = RestorePolicy.ACCEPT_IF_APK;
3705 }
3706
3707 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3708 Slog.i(TAG, "Cannot restore package " + info.packageName
3709 + " without the matching .apk");
3710 }
3711 } else {
3712 Slog.i(TAG, "Missing signature on backed-up package "
3713 + info.packageName);
3714 }
3715 } else {
3716 Slog.i(TAG, "Expected package " + info.packageName
3717 + " but restore manifest claims " + manifestPackage);
3718 }
3719 } else {
3720 Slog.i(TAG, "Unknown restore manifest version " + version
3721 + " for package " + info.packageName);
3722 }
3723 } catch (NumberFormatException e) {
3724 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003725 } catch (IllegalArgumentException e) {
3726 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003727 }
3728
3729 return policy;
3730 }
3731
3732 // Builds a line from a byte buffer starting at 'offset', and returns
3733 // the index of the next unconsumed data in the buffer.
3734 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3735 final int end = buffer.length;
3736 if (offset >= end) throw new IOException("Incomplete data");
3737
3738 int pos;
3739 for (pos = offset; pos < end; pos++) {
3740 byte c = buffer[pos];
3741 // at LF we declare end of line, and return the next char as the
3742 // starting point for the next time through
3743 if (c == '\n') {
3744 break;
3745 }
3746 }
3747 outStr[0] = new String(buffer, offset, pos - offset);
3748 pos++; // may be pointing an extra byte past the end but that's okay
3749 return pos;
3750 }
3751
3752 void dumpFileMetadata(FileMetadata info) {
3753 if (DEBUG) {
3754 StringBuilder b = new StringBuilder(128);
3755
3756 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003757 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003758 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3759 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3760 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3761 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3762 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3763 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3764 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3765 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3766 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3767 b.append(String.format(" %9d ", info.size));
3768
3769 Date stamp = new Date(info.mtime);
3770 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3771
3772 b.append(info.packageName);
3773 b.append(" :: ");
3774 b.append(info.domain);
3775 b.append(" :: ");
3776 b.append(info.path);
3777
3778 Slog.i(TAG, b.toString());
3779 }
3780 }
3781 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3782 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3783 byte[] block = new byte[512];
3784 FileMetadata info = null;
3785
3786 boolean gotHeader = readTarHeader(instream, block);
3787 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003788 try {
3789 // okay, presume we're okay, and extract the various metadata
3790 info = new FileMetadata();
3791 info.size = extractRadix(block, 124, 12, 8);
3792 info.mtime = extractRadix(block, 136, 12, 8);
3793 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003794
Christopher Tate2efd2db2011-07-19 16:32:49 -07003795 info.path = extractString(block, 345, 155); // prefix
3796 String path = extractString(block, 0, 100);
3797 if (path.length() > 0) {
3798 if (info.path.length() > 0) info.path += '/';
3799 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003800 }
Christopher Tate75a99702011-05-18 16:28:19 -07003801
Christopher Tate2efd2db2011-07-19 16:32:49 -07003802 // tar link indicator field: 1 byte at offset 156 in the header.
3803 int typeChar = block[156];
3804 if (typeChar == 'x') {
3805 // pax extended header, so we need to read that
3806 gotHeader = readPaxExtendedHeader(instream, info);
3807 if (gotHeader) {
3808 // and after a pax extended header comes another real header -- read
3809 // that to find the real file type
3810 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003811 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003812 if (!gotHeader) throw new IOException("Bad or missing pax header");
3813
3814 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003815 }
Christopher Tate75a99702011-05-18 16:28:19 -07003816
Christopher Tate2efd2db2011-07-19 16:32:49 -07003817 switch (typeChar) {
3818 case '0': info.type = BackupAgent.TYPE_FILE; break;
3819 case '5': {
3820 info.type = BackupAgent.TYPE_DIRECTORY;
3821 if (info.size != 0) {
3822 Slog.w(TAG, "Directory entry with nonzero size in header");
3823 info.size = 0;
3824 }
3825 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003826 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003827 case 0: {
3828 // presume EOF
3829 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3830 return null;
3831 }
3832 default: {
3833 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3834 throw new IOException("Unknown entity type " + typeChar);
3835 }
Christopher Tate75a99702011-05-18 16:28:19 -07003836 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003837
3838 // Parse out the path
3839 //
3840 // first: apps/shared/unrecognized
3841 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3842 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3843 // File in shared storage. !!! TODO: implement this.
3844 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tate73d73692012-01-20 17:11:31 -08003845 info.packageName = SHARED_BACKUP_AGENT_PACKAGE;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003846 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3847 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3848 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3849 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3850 // App content! Parse out the package name and domain
3851
3852 // strip the apps/ prefix
3853 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3854
3855 // extract the package name
3856 int slash = info.path.indexOf('/');
3857 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3858 info.packageName = info.path.substring(0, slash);
3859 info.path = info.path.substring(slash+1);
3860
3861 // if it's a manifest we're done, otherwise parse out the domains
3862 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3863 slash = info.path.indexOf('/');
3864 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3865 info.domain = info.path.substring(0, slash);
3866 // validate that it's one of the domains we understand
3867 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3868 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3869 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3870 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3871 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3872 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3873 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3874 throw new IOException("Unrecognized domain " + info.domain);
3875 }
3876
3877 info.path = info.path.substring(slash + 1);
3878 }
3879 }
3880 } catch (IOException e) {
3881 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003882 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003883 HEXLOG(block);
3884 }
3885 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003886 }
3887 }
3888 return info;
3889 }
3890
Christopher Tate2efd2db2011-07-19 16:32:49 -07003891 private void HEXLOG(byte[] block) {
3892 int offset = 0;
3893 int todo = block.length;
3894 StringBuilder buf = new StringBuilder(64);
3895 while (todo > 0) {
3896 buf.append(String.format("%04x ", offset));
3897 int numThisLine = (todo > 16) ? 16 : todo;
3898 for (int i = 0; i < numThisLine; i++) {
3899 buf.append(String.format("%02x ", block[offset+i]));
3900 }
3901 Slog.i("hexdump", buf.toString());
3902 buf.setLength(0);
3903 todo -= numThisLine;
3904 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003905 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003906 }
3907
Christopher Tate6853fcf2011-08-10 17:52:21 -07003908 // Read exactly the given number of bytes into a buffer at the stated offset.
3909 // Returns false if EOF is encountered before the requested number of bytes
3910 // could be read.
3911 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3912 throws IOException {
3913 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3914
3915 int soFar = 0;
3916 while (soFar < size) {
3917 int nRead = in.read(buffer, offset + soFar, size - soFar);
3918 if (nRead <= 0) {
3919 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3920 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003921 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003922 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003923 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003924 return soFar;
3925 }
3926
3927 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3928 final int got = readExactly(instream, block, 0, 512);
3929 if (got == 0) return false; // Clean EOF
3930 if (got < 512) throw new IOException("Unable to read full block header");
3931 mBytes += 512;
3932 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003933 }
3934
3935 // overwrites 'info' fields based on the pax extended header
3936 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3937 throws IOException {
3938 // We should never see a pax extended header larger than this
3939 if (info.size > 32*1024) {
3940 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3941 + " - aborting");
3942 throw new IOException("Sanity failure: pax header size " + info.size);
3943 }
3944
3945 // read whole blocks, not just the content size
3946 int numBlocks = (int)((info.size + 511) >> 9);
3947 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003948 if (readExactly(instream, data, 0, data.length) < data.length) {
3949 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003950 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003951 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003952
3953 final int contentSize = (int) info.size;
3954 int offset = 0;
3955 do {
3956 // extract the line at 'offset'
3957 int eol = offset+1;
3958 while (eol < contentSize && data[eol] != ' ') eol++;
3959 if (eol >= contentSize) {
3960 // error: we just hit EOD looking for the end of the size field
3961 throw new IOException("Invalid pax data");
3962 }
3963 // eol points to the space between the count and the key
3964 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3965 int key = eol + 1; // start of key=value
3966 eol = offset + linelen - 1; // trailing LF
3967 int value;
3968 for (value = key+1; data[value] != '=' && value <= eol; value++);
3969 if (value > eol) {
3970 throw new IOException("Invalid pax declaration");
3971 }
3972
3973 // pax requires that key/value strings be in UTF-8
3974 String keyStr = new String(data, key, value-key, "UTF-8");
3975 // -1 to strip the trailing LF
3976 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3977
3978 if ("path".equals(keyStr)) {
3979 info.path = valStr;
3980 } else if ("size".equals(keyStr)) {
3981 info.size = Long.parseLong(valStr);
3982 } else {
3983 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3984 }
3985
3986 offset += linelen;
3987 } while (offset < contentSize);
3988
3989 return true;
3990 }
3991
3992 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3993 throws IOException {
3994 long value = 0;
3995 final int end = offset + maxChars;
3996 for (int i = offset; i < end; i++) {
3997 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003998 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003999 if (b == 0 || b == ' ') break;
4000 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004001 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07004002 }
4003 value = radix * value + (b - '0');
4004 }
4005 return value;
4006 }
4007
4008 String extractString(byte[] data, int offset, int maxChars) throws IOException {
4009 final int end = offset + maxChars;
4010 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07004011 // tar string fields terminate early with a NUL
4012 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07004013 return new String(data, offset, eos-offset, "US-ASCII");
4014 }
4015
4016 void sendStartRestore() {
4017 if (mObserver != null) {
4018 try {
4019 mObserver.onStartRestore();
4020 } catch (RemoteException e) {
4021 Slog.w(TAG, "full restore observer went away: startRestore");
4022 mObserver = null;
4023 }
4024 }
4025 }
4026
4027 void sendOnRestorePackage(String name) {
4028 if (mObserver != null) {
4029 try {
4030 // TODO: use a more user-friendly name string
4031 mObserver.onRestorePackage(name);
4032 } catch (RemoteException e) {
4033 Slog.w(TAG, "full restore observer went away: restorePackage");
4034 mObserver = null;
4035 }
4036 }
4037 }
4038
4039 void sendEndRestore() {
4040 if (mObserver != null) {
4041 try {
4042 mObserver.onEndRestore();
4043 } catch (RemoteException e) {
4044 Slog.w(TAG, "full restore observer went away: endRestore");
4045 mObserver = null;
4046 }
4047 }
4048 }
4049 }
4050
Christopher Tatedf01dea2009-06-09 20:45:02 -07004051 // ----- Restore handling -----
4052
Christopher Tate78dd4a72009-11-04 11:49:08 -08004053 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
4054 // If the target resides on the system partition, we allow it to restore
4055 // data from the like-named package in a restore set even if the signatures
4056 // do not match. (Unlike general applications, those flashed to the system
4057 // partition will be signed with the device's platform certificate, so on
4058 // different phones the same system app will have different signatures.)
4059 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004060 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08004061 return true;
4062 }
4063
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004064 // Allow unsigned apps, but not signed on one device and unsigned on the other
4065 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08004066 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07004067 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07004068 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07004069 if ((storedSigs == null || storedSigs.length == 0)
4070 && (deviceSigs == null || deviceSigs.length == 0)) {
4071 return true;
4072 }
4073 if (storedSigs == null || deviceSigs == null) {
4074 return false;
4075 }
4076
Christopher Tateabce4e82009-06-18 18:35:32 -07004077 // !!! TODO: this demands that every stored signature match one
4078 // that is present on device, and does not demand the converse.
4079 // Is this this right policy?
4080 int nStored = storedSigs.length;
4081 int nDevice = deviceSigs.length;
4082
4083 for (int i=0; i < nStored; i++) {
4084 boolean match = false;
4085 for (int j=0; j < nDevice; j++) {
4086 if (storedSigs[i].equals(deviceSigs[j])) {
4087 match = true;
4088 break;
4089 }
4090 }
4091 if (!match) {
4092 return false;
4093 }
4094 }
4095 return true;
4096 }
4097
Christopher Tate2982d062011-09-06 20:35:24 -07004098 enum RestoreState {
4099 INITIAL,
4100 DOWNLOAD_DATA,
4101 PM_METADATA,
4102 RUNNING_QUEUE,
4103 FINAL
4104 }
4105
4106 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07004107 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004108 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07004109 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08004110 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004111 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08004112 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004113 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004114 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004115 private long mStartRealtime;
4116 private PackageManagerBackupAgent mPmAgent;
4117 private List<PackageInfo> mAgentPackages;
4118 private ArrayList<PackageInfo> mRestorePackages;
4119 private RestoreState mCurrentState;
4120 private int mCount;
4121 private boolean mFinished;
4122 private int mStatus;
4123 private File mBackupDataName;
4124 private File mNewStateName;
4125 private File mSavedStateName;
4126 private ParcelFileDescriptor mBackupData;
4127 private ParcelFileDescriptor mNewState;
4128 private PackageInfo mCurrentPackage;
4129
Christopher Tatedf01dea2009-06-09 20:45:02 -07004130
Christopher Tate5cbbf562009-06-22 16:44:51 -07004131 class RestoreRequest {
4132 public PackageInfo app;
4133 public int storedAppVersion;
4134
4135 RestoreRequest(PackageInfo _app, int _version) {
4136 app = _app;
4137 storedAppVersion = _version;
4138 }
4139 }
4140
Christopher Tate44a27902010-01-27 17:15:49 -08004141 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004142 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004143 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004144 mCurrentState = RestoreState.INITIAL;
4145 mFinished = false;
4146 mPmAgent = null;
4147
Christopher Tatedf01dea2009-06-09 20:45:02 -07004148 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004149 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004150 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004151 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004152 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004153 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004154
Christopher Tate284f1bb2011-07-07 14:31:18 -07004155 if (filterSet != null) {
4156 mFilterSet = new HashSet<String>();
4157 for (String pkg : filterSet) {
4158 mFilterSet.add(pkg);
4159 }
4160 } else {
4161 mFilterSet = null;
4162 }
4163
Christopher Tate5cb400b2009-06-25 16:03:14 -07004164 try {
4165 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4166 } catch (RemoteException e) {
4167 // can't happen; the transport is local
4168 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004169 }
4170
Christopher Tate2982d062011-09-06 20:35:24 -07004171 // Execute one tick of whatever state machine the task implements
4172 @Override
4173 public void execute() {
4174 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4175 switch (mCurrentState) {
4176 case INITIAL:
4177 beginRestore();
4178 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004179
Christopher Tate2982d062011-09-06 20:35:24 -07004180 case DOWNLOAD_DATA:
4181 downloadRestoreData();
4182 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004183
Christopher Tate2982d062011-09-06 20:35:24 -07004184 case PM_METADATA:
4185 restorePmMetadata();
4186 break;
4187
4188 case RUNNING_QUEUE:
4189 restoreNextAgent();
4190 break;
4191
4192 case FINAL:
4193 if (!mFinished) finalizeRestore();
4194 else {
4195 Slog.e(TAG, "Duplicate finish");
4196 }
4197 mFinished = true;
4198 break;
4199 }
4200 }
4201
4202 // Initialize and set up for the PM metadata restore, which comes first
4203 void beginRestore() {
4204 // Don't account time doing the restore as inactivity of the app
4205 // that has opened a restore session.
4206 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4207
4208 // Assume error until we successfully init everything
4209 mStatus = BackupConstants.TRANSPORT_ERROR;
4210
Christopher Tatedf01dea2009-06-09 20:45:02 -07004211 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004212 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004213 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004214
Dan Egnorefe52642009-06-24 00:16:33 -07004215 // Get the list of all packages which have backup enabled.
4216 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004217 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004218 PackageInfo omPackage = new PackageInfo();
4219 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004220 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004221
Christopher Tate2982d062011-09-06 20:35:24 -07004222 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004223 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004224 // if there's a filter set, strip out anything that isn't
4225 // present before proceeding
4226 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004227 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4228 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004229 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004230 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004231 }
4232 }
Christopher Tate2982d062011-09-06 20:35:24 -07004233 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004234 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004235 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004236 Slog.i(TAG, " " + p);
4237 }
4238 }
4239 }
Christopher Tate2982d062011-09-06 20:35:24 -07004240 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004241 } else {
4242 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004243 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004244 }
Dan Egnorefe52642009-06-24 00:16:33 -07004245
Christopher Tate7d562ec2009-06-25 18:03:43 -07004246 // let the observer know that we're running
4247 if (mObserver != null) {
4248 try {
4249 // !!! TODO: get an actual count from the transport after
4250 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004251 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004252 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004253 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004254 mObserver = null;
4255 }
4256 }
Christopher Tate2982d062011-09-06 20:35:24 -07004257 } catch (RemoteException e) {
4258 // Something has gone catastrophically wrong with the transport
4259 Slog.e(TAG, "Error communicating with transport for restore");
4260 executeNextState(RestoreState.FINAL);
4261 return;
4262 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004263
Christopher Tate2982d062011-09-06 20:35:24 -07004264 mStatus = BackupConstants.TRANSPORT_OK;
4265 executeNextState(RestoreState.DOWNLOAD_DATA);
4266 }
4267
4268 void downloadRestoreData() {
4269 // Note that the download phase can be very time consuming, but we're executing
4270 // it inline here on the looper. This is "okay" because it is not calling out to
4271 // third party code; the transport is "trusted," and so we assume it is being a
4272 // good citizen and timing out etc when appropriate.
4273 //
4274 // TODO: when appropriate, move the download off the looper and rearrange the
4275 // error handling around that.
4276 try {
4277 mStatus = mTransport.startRestore(mToken,
4278 mRestorePackages.toArray(new PackageInfo[0]));
4279 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004280 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004281 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004282 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004283 return;
4284 }
Christopher Tate2982d062011-09-06 20:35:24 -07004285 } catch (RemoteException e) {
4286 Slog.e(TAG, "Error communicating with transport for restore");
4287 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4288 mStatus = BackupConstants.TRANSPORT_ERROR;
4289 executeNextState(RestoreState.FINAL);
4290 return;
4291 }
Dan Egnorefe52642009-06-24 00:16:33 -07004292
Christopher Tate2982d062011-09-06 20:35:24 -07004293 // Successful download of the data to be parceled out to the apps, so off we go.
4294 executeNextState(RestoreState.PM_METADATA);
4295 }
4296
4297 void restorePmMetadata() {
4298 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004299 String packageName = mTransport.nextRestorePackage();
4300 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004301 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004302 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004303 mStatus = BackupConstants.TRANSPORT_ERROR;
4304 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004305 return;
4306 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004307 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004308 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004309 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004310 mStatus = BackupConstants.TRANSPORT_OK;
4311 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004312 return;
4313 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004314 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004315 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004316 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004317 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004318 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004319 return;
4320 }
4321
4322 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004323 PackageInfo omPackage = new PackageInfo();
4324 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4325 mPmAgent = new PackageManagerBackupAgent(
4326 mPackageManager, mAgentPackages);
4327 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004328 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004329 // The PM agent called operationComplete() already, because our invocation
4330 // of it is process-local and therefore synchronous. That means that a
4331 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4332 // proceed with running the queue do we remove that pending message and
4333 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004334
Christopher Tate8c032472009-07-02 14:28:47 -07004335 // Verify that the backup set includes metadata. If not, we can't do
4336 // signature/version verification etc, so we simply do not proceed with
4337 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004338 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004339 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004340 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004341 "Package manager restore metadata missing");
4342 mStatus = BackupConstants.TRANSPORT_ERROR;
4343 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4344 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004345 return;
4346 }
Christopher Tate2982d062011-09-06 20:35:24 -07004347 } catch (RemoteException e) {
4348 Slog.e(TAG, "Error communicating with transport for restore");
4349 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4350 mStatus = BackupConstants.TRANSPORT_ERROR;
4351 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4352 executeNextState(RestoreState.FINAL);
4353 return;
4354 }
Christopher Tate8c032472009-07-02 14:28:47 -07004355
Christopher Tate2982d062011-09-06 20:35:24 -07004356 // Metadata is intact, so we can now run the restore queue. If we get here,
4357 // we have already enqueued the necessary next-step message on the looper.
4358 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004359
Christopher Tate2982d062011-09-06 20:35:24 -07004360 void restoreNextAgent() {
4361 try {
4362 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004363
Christopher Tate2982d062011-09-06 20:35:24 -07004364 if (packageName == null) {
4365 Slog.e(TAG, "Error getting next restore package");
4366 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4367 executeNextState(RestoreState.FINAL);
4368 return;
4369 } else if (packageName.equals("")) {
4370 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4371 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4372 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4373 executeNextState(RestoreState.FINAL);
4374 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004375 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004376
4377 if (mObserver != null) {
4378 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004379 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004380 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004381 Slog.d(TAG, "Restore observer died in onUpdate");
4382 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004383 }
4384 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004385
Christopher Tate2982d062011-09-06 20:35:24 -07004386 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4387 if (metaInfo == null) {
4388 Slog.e(TAG, "Missing metadata for " + packageName);
4389 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4390 "Package metadata missing");
4391 executeNextState(RestoreState.RUNNING_QUEUE);
4392 return;
Christopher Tate84725812010-02-04 15:52:40 -08004393 }
4394
Christopher Tate2982d062011-09-06 20:35:24 -07004395 PackageInfo packageInfo;
4396 try {
4397 int flags = PackageManager.GET_SIGNATURES;
4398 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4399 } catch (NameNotFoundException e) {
4400 Slog.e(TAG, "Invalid package restoring data", e);
4401 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4402 "Package missing on device");
4403 executeNextState(RestoreState.RUNNING_QUEUE);
4404 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004405 }
4406
Christopher Tate2982d062011-09-06 20:35:24 -07004407 if (metaInfo.versionCode > packageInfo.versionCode) {
4408 // Data is from a "newer" version of the app than we have currently
4409 // installed. If the app has not declared that it is prepared to
4410 // handle this case, we do not attempt the restore.
4411 if ((packageInfo.applicationInfo.flags
4412 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4413 String message = "Version " + metaInfo.versionCode
4414 + " > installed version " + packageInfo.versionCode;
4415 Slog.w(TAG, "Package " + packageName + ": " + message);
4416 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4417 packageName, message);
4418 executeNextState(RestoreState.RUNNING_QUEUE);
4419 return;
4420 } else {
4421 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4422 + " > installed " + packageInfo.versionCode
4423 + " but restoreAnyVersion");
4424 }
4425 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004426
Christopher Tate2982d062011-09-06 20:35:24 -07004427 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4428 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4429 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4430 "Signature mismatch");
4431 executeNextState(RestoreState.RUNNING_QUEUE);
4432 return;
4433 }
4434
4435 if (DEBUG) Slog.v(TAG, "Package " + packageName
4436 + " restore version [" + metaInfo.versionCode
4437 + "] is compatible with installed version ["
4438 + packageInfo.versionCode + "]");
4439
4440 // Then set up and bind the agent
4441 IBackupAgent agent = bindToAgentSynchronous(
4442 packageInfo.applicationInfo,
4443 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4444 if (agent == null) {
4445 Slog.w(TAG, "Can't find backup agent for " + packageName);
4446 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4447 "Restore agent missing");
4448 executeNextState(RestoreState.RUNNING_QUEUE);
4449 return;
4450 }
4451
4452 // And then finally start the restore on this agent
4453 try {
4454 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4455 ++mCount;
4456 } catch (Exception e) {
4457 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4458 agentErrorCleanup();
4459 executeNextState(RestoreState.RUNNING_QUEUE);
4460 }
4461 } catch (RemoteException e) {
4462 Slog.e(TAG, "Unable to fetch restore data from transport");
4463 mStatus = BackupConstants.TRANSPORT_ERROR;
4464 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004465 }
4466 }
4467
Christopher Tate2982d062011-09-06 20:35:24 -07004468 void finalizeRestore() {
4469 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4470
4471 try {
4472 mTransport.finishRestore();
4473 } catch (RemoteException e) {
4474 Slog.e(TAG, "Error finishing restore", e);
4475 }
4476
4477 if (mObserver != null) {
4478 try {
4479 mObserver.restoreFinished(mStatus);
4480 } catch (RemoteException e) {
4481 Slog.d(TAG, "Restore observer died at restoreFinished");
4482 }
4483 }
4484
4485 // If this was a restoreAll operation, record that this was our
4486 // ancestral dataset, as well as the set of apps that are possibly
4487 // restoreable from the dataset
4488 if (mTargetPackage == null && mPmAgent != null) {
4489 mAncestralPackages = mPmAgent.getRestoredPackages();
4490 mAncestralToken = mToken;
4491 writeRestoreTokens();
4492 }
4493
4494 // We must under all circumstances tell the Package Manager to
4495 // proceed with install notifications if it's waiting for us.
4496 if (mPmToken > 0) {
4497 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4498 try {
4499 mPackageManagerBinder.finishPackageInstall(mPmToken);
4500 } catch (RemoteException e) { /* can't happen */ }
4501 }
4502
4503 // Furthermore we need to reset the session timeout clock
4504 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4505 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4506 TIMEOUT_RESTORE_INTERVAL);
4507
4508 // done; we can finally release the wakelock
4509 Slog.i(TAG, "Restore complete.");
4510 mWakelock.release();
4511 }
4512
4513 // Call asynchronously into the app, passing it the restore data. The next step
4514 // after this is always a callback, either operationComplete() or handleTimeout().
4515 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004516 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004517 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004518 final String packageName = app.packageName;
4519
Christopher Tate2982d062011-09-06 20:35:24 -07004520 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004521
Christopher Tatec7b31e32009-06-10 15:49:30 -07004522 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004523 mBackupDataName = new File(mDataDir, packageName + ".restore");
4524 mNewStateName = new File(mStateDir, packageName + ".new");
4525 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004526
Christopher Tate4a627c72011-04-01 14:43:32 -07004527 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004528 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004529 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004530 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004531 ParcelFileDescriptor.MODE_READ_WRITE |
4532 ParcelFileDescriptor.MODE_CREATE |
4533 ParcelFileDescriptor.MODE_TRUNCATE);
4534
Christopher Tate2982d062011-09-06 20:35:24 -07004535 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004536 // Transport-level failure, so we wind everything up and
4537 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004538 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004539 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004540 mBackupData.close();
4541 mBackupDataName.delete();
4542 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004543 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004544 }
4545
4546 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004547 mBackupData.close();
4548 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004549 ParcelFileDescriptor.MODE_READ_ONLY);
4550
Christopher Tate2982d062011-09-06 20:35:24 -07004551 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004552 ParcelFileDescriptor.MODE_READ_WRITE |
4553 ParcelFileDescriptor.MODE_CREATE |
4554 ParcelFileDescriptor.MODE_TRUNCATE);
4555
Christopher Tate44a27902010-01-27 17:15:49 -08004556 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004557 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4558 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004559 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004560 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004561 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004562 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004563
Christopher Tate2982d062011-09-06 20:35:24 -07004564 // After a restore failure we go back to running the queue. If there
4565 // are no more packages to be restored that will be handled by the
4566 // next step.
4567 executeNextState(RestoreState.RUNNING_QUEUE);
4568 }
4569 }
Chris Tate249345b2010-10-29 12:57:04 -07004570
Christopher Tate2982d062011-09-06 20:35:24 -07004571 void agentErrorCleanup() {
4572 // If the agent fails restore, it might have put the app's data
4573 // into an incoherent state. For consistency we wipe its data
4574 // again in this case before continuing with normal teardown
4575 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4576 agentCleanup();
4577 }
4578
4579 void agentCleanup() {
4580 mBackupDataName.delete();
4581 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4582 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4583 mBackupData = mNewState = null;
4584
4585 // if everything went okay, remember the recorded state now
4586 //
4587 // !!! TODO: the restored data should be migrated on the server
4588 // side into the current dataset. In that case the new state file
4589 // we just created would reflect the data already extant in the
4590 // backend, so there'd be nothing more to do. Until that happens,
4591 // however, we need to make sure that we record the data to the
4592 // current backend dataset. (Yes, this means shipping the data over
4593 // the wire in both directions. That's bad, but consistency comes
4594 // first, then efficiency.) Once we introduce server-side data
4595 // migration to the newly-restored device's dataset, we will change
4596 // the following from a discard of the newly-written state to the
4597 // "correct" operation of renaming into the canonical state blob.
4598 mNewStateName.delete(); // TODO: remove; see above comment
4599 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4600
4601 // If this wasn't the PM pseudopackage, tear down the agent side
4602 if (mCurrentPackage.applicationInfo != null) {
4603 // unbind and tidy up even on timeout or failure
4604 try {
4605 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4606
4607 // The agent was probably running with a stub Application object,
4608 // which isn't a valid run mode for the main app logic. Shut
4609 // down the app so that next time it's launched, it gets the
4610 // usual full initialization. Note that this is only done for
4611 // full-system restores: when a single app has requested a restore,
4612 // it is explicitly not killed following that operation.
4613 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4614 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4615 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4616 + mCurrentPackage.applicationInfo.processName);
4617 mActivityManager.killApplicationProcess(
4618 mCurrentPackage.applicationInfo.processName,
4619 mCurrentPackage.applicationInfo.uid);
4620 }
4621 } catch (RemoteException e) {
4622 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004623 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004624 }
Christopher Tate2982d062011-09-06 20:35:24 -07004625
4626 // The caller is responsible for reestablishing the state machine; our
4627 // responsibility here is to clear the decks for whatever comes next.
4628 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4629 synchronized (mCurrentOpLock) {
4630 mCurrentOperations.clear();
4631 }
4632 }
4633
4634 // A call to agent.doRestore() has been positively acknowledged as complete
4635 @Override
4636 public void operationComplete() {
4637 int size = (int) mBackupDataName.length();
4638 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4639 // Just go back to running the restore queue
4640 agentCleanup();
4641
4642 executeNextState(RestoreState.RUNNING_QUEUE);
4643 }
4644
4645 // A call to agent.doRestore() has timed out
4646 @Override
4647 public void handleTimeout() {
4648 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4649 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4650 mCurrentPackage.packageName, "restore timeout");
4651 // Handle like an agent that threw on invocation: wipe it and go on to the next
4652 agentErrorCleanup();
4653 executeNextState(RestoreState.RUNNING_QUEUE);
4654 }
4655
4656 void executeNextState(RestoreState nextState) {
4657 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4658 + this + " nextState=" + nextState);
4659 mCurrentState = nextState;
4660 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4661 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004662 }
4663 }
4664
Christopher Tate44a27902010-01-27 17:15:49 -08004665 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004666 IBackupTransport mTransport;
4667 PackageInfo mPackage;
4668
Christopher Tate44a27902010-01-27 17:15:49 -08004669 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004670 mTransport = transport;
4671 mPackage = packageInfo;
4672 }
4673
Christopher Tateee0e78a2009-07-02 11:17:03 -07004674 public void run() {
4675 try {
4676 // Clear the on-device backup state to ensure a full backup next time
4677 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4678 File stateFile = new File(stateDir, mPackage.packageName);
4679 stateFile.delete();
4680
4681 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004682 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004683 mTransport.clearBackupData(mPackage);
4684 } catch (RemoteException e) {
4685 // can't happen; the transport is local
4686 } finally {
4687 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004688 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004689 mTransport.finishBackup();
4690 } catch (RemoteException e) {
4691 // can't happen; the transport is local
4692 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004693
4694 // Last but not least, release the cpu
4695 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004696 }
4697 }
4698 }
4699
Christopher Tate44a27902010-01-27 17:15:49 -08004700 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004701 HashSet<String> mQueue;
4702
Christopher Tate44a27902010-01-27 17:15:49 -08004703 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004704 mQueue = transportNames;
4705 }
4706
Christopher Tate4cc86e12009-09-21 19:36:51 -07004707 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004708 try {
4709 for (String transportName : mQueue) {
4710 IBackupTransport transport = getTransport(transportName);
4711 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004712 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004713 continue;
4714 }
4715
Joe Onorato8a9b2202010-02-26 18:56:32 -08004716 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004717 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004718 long startRealtime = SystemClock.elapsedRealtime();
4719 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004720
Christopher Tate4cc86e12009-09-21 19:36:51 -07004721 if (status == BackupConstants.TRANSPORT_OK) {
4722 status = transport.finishBackup();
4723 }
4724
4725 // Okay, the wipe really happened. Clean up our local bookkeeping.
4726 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004727 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004728 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004729 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004730 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004731 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004732 synchronized (mQueueLock) {
4733 recordInitPendingLocked(false, transportName);
4734 }
Dan Egnor726247c2009-09-29 19:12:31 -07004735 } else {
4736 // If this didn't work, requeue this one and try again
4737 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004738 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004739 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004740 synchronized (mQueueLock) {
4741 recordInitPendingLocked(true, transportName);
4742 }
4743 // do this via another alarm to make sure of the wakelock states
4744 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004745 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004746 + transportName + " resched in " + delay);
4747 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4748 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004749 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004750 }
4751 } catch (RemoteException e) {
4752 // can't happen; the transports are local
4753 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004754 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004755 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004756 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004757 mWakelock.release();
4758 }
4759 }
4760 }
4761
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004762 private void dataChangedImpl(String packageName) {
4763 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4764 dataChangedImpl(packageName, targets);
4765 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004766
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004767 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004768 // Record that we need a backup pass for the caller. Since multiple callers
4769 // may share a uid, we need to note all candidates within that uid and schedule
4770 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004771 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004772
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004773 if (targets == null) {
4774 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4775 + " uid=" + Binder.getCallingUid());
4776 return;
4777 }
4778
4779 synchronized (mQueueLock) {
4780 // Note that this client has made data changes that need to be backed up
4781 for (ApplicationInfo app : targets) {
4782 // validate the caller-supplied package name against the known set of
4783 // packages associated with this uid
4784 if (app.packageName.equals(packageName)) {
4785 // Add the caller to the set of pending backups. If there is
4786 // one already there, then overwrite it, but no harm done.
Christopher Tatecc55f812011-08-16 16:06:53 -07004787 BackupRequest req = new BackupRequest(packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08004788 if (mPendingBackups.put(app.packageName, req) == null) {
Christopher Tate6de74ff2012-01-17 15:20:32 -08004789 if (DEBUG) Slog.d(TAG, "Now staging backup of " + packageName);
4790
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004791 // Journal this request in case of crash. The put()
4792 // operation returned null when this package was not already
4793 // in the set; we want to avoid touching the disk redundantly.
4794 writeToJournalLocked(packageName);
4795
Christopher Tatec58efa62011-08-01 19:20:14 -07004796 if (MORE_DEBUG) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004797 int numKeys = mPendingBackups.size();
4798 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4799 for (BackupRequest b : mPendingBackups.values()) {
Christopher Tatecc55f812011-08-16 16:06:53 -07004800 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004801 }
4802 }
4803 }
4804 }
4805 }
4806 }
4807 }
4808
4809 // Note: packageName is currently unused, but may be in the future
4810 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004811 // If the caller does not hold the BACKUP permission, it can only request a
4812 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004813 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004814 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004815 synchronized (mBackupParticipants) {
4816 return mBackupParticipants.get(Binder.getCallingUid());
4817 }
4818 }
4819
4820 // a caller with full permission can ask to back up any participating app
4821 // !!! TODO: allow backup of ANY app?
4822 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4823 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004824 int N = mBackupParticipants.size();
4825 for (int i = 0; i < N; i++) {
4826 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4827 if (s != null) {
4828 targets.addAll(s);
4829 }
4830 }
4831 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004832 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004833 }
Christopher Tate46758122009-05-06 11:22:00 -07004834
Christopher Tatecde87f42009-06-12 12:55:53 -07004835 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004836 RandomAccessFile out = null;
4837 try {
4838 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4839 out = new RandomAccessFile(mJournal, "rws");
4840 out.seek(out.length());
4841 out.writeUTF(str);
4842 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004843 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004844 mJournal = null;
4845 } finally {
4846 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004847 }
4848 }
4849
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004850 // ----- IBackupManager binder interface -----
4851
4852 public void dataChanged(final String packageName) {
4853 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4854 if (targets == null) {
4855 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4856 + " uid=" + Binder.getCallingUid());
4857 return;
4858 }
4859
4860 mBackupHandler.post(new Runnable() {
4861 public void run() {
4862 dataChangedImpl(packageName, targets);
4863 }
4864 });
4865 }
4866
Christopher Tateee0e78a2009-07-02 11:17:03 -07004867 // Clear the given package's backup data from the current transport
4868 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004869 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004870 PackageInfo info;
4871 try {
4872 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4873 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004874 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004875 return;
4876 }
4877
4878 // If the caller does not hold the BACKUP permission, it can only request a
4879 // wipe of its own backed-up data.
4880 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004881 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004882 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4883 apps = mBackupParticipants.get(Binder.getCallingUid());
4884 } else {
4885 // a caller with full permission can ask to back up any participating app
4886 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004887 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004888 apps = new HashSet<ApplicationInfo>();
4889 int N = mBackupParticipants.size();
4890 for (int i = 0; i < N; i++) {
4891 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4892 if (s != null) {
4893 apps.addAll(s);
4894 }
4895 }
4896 }
4897
4898 // now find the given package in the set of candidate apps
4899 for (ApplicationInfo app : apps) {
4900 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004901 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004902 // found it; fire off the clear request
4903 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004904 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004905 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004906 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4907 new ClearParams(getTransport(mCurrentTransport), info));
4908 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004909 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004910 }
4911 break;
4912 }
4913 }
4914 }
4915
Christopher Tateace7f092009-06-15 18:07:25 -07004916 // Run a backup pass immediately for any applications that have declared
4917 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004918 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004919 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004920
Joe Onorato8a9b2202010-02-26 18:56:32 -08004921 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004922 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004923 // Because the alarms we are using can jitter, and we want an *immediate*
4924 // backup pass to happen, we restart the timer beginning with "next time,"
4925 // then manually fire the backup trigger intent ourselves.
4926 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004927 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004928 mRunBackupIntent.send();
4929 } catch (PendingIntent.CanceledException e) {
4930 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004931 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004932 }
Christopher Tate46758122009-05-06 11:22:00 -07004933 }
4934 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004935
Christopher Tated2c0cd42011-09-15 15:51:29 -07004936 boolean deviceIsProvisioned() {
4937 final ContentResolver resolver = mContext.getContentResolver();
4938 return (Settings.Secure.getInt(resolver, Settings.Secure.DEVICE_PROVISIONED, 0) != 0);
4939 }
4940
Christopher Tate4a627c72011-04-01 14:43:32 -07004941 // Run a *full* backup pass for the given package, writing the resulting data stream
4942 // to the supplied file descriptor. This method is synchronous and does not return
4943 // to the caller until the backup has been completed.
4944 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004945 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004946 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4947
4948 // Validate
4949 if (!doAllApps) {
4950 if (!includeShared) {
4951 // If we're backing up shared data (sdcard or equivalent), then we can run
4952 // without any supplied app names. Otherwise, we'd be doing no work, so
4953 // report the error.
4954 if (pkgList == null || pkgList.length == 0) {
4955 throw new IllegalArgumentException(
4956 "Backup requested but neither shared nor any apps named");
4957 }
4958 }
4959 }
4960
Christopher Tate4a627c72011-04-01 14:43:32 -07004961 long oldId = Binder.clearCallingIdentity();
4962 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07004963 // Doesn't make sense to do a full backup prior to setup
4964 if (!deviceIsProvisioned()) {
4965 Slog.i(TAG, "Full backup not supported before setup");
4966 return;
4967 }
4968
4969 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4970 + " shared=" + includeShared + " all=" + doAllApps
4971 + " pkgs=" + pkgList);
4972 Slog.i(TAG, "Beginning full backup...");
4973
Christopher Tate4a627c72011-04-01 14:43:32 -07004974 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004975 doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07004976 final int token = generateToken();
4977 synchronized (mFullConfirmations) {
4978 mFullConfirmations.put(token, params);
4979 }
4980
Christopher Tate75a99702011-05-18 16:28:19 -07004981 // start up the confirmation UI
4982 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4983 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4984 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004985 mFullConfirmations.delete(token);
4986 return;
4987 }
Christopher Tate75a99702011-05-18 16:28:19 -07004988
4989 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004990 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4991
4992 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07004993 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004994
4995 // wait for the backup to be performed
4996 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
4997 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004998 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07004999 try {
5000 fd.close();
5001 } catch (IOException e) {
5002 // just eat it
5003 }
Christopher Tate75a99702011-05-18 16:28:19 -07005004 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005005 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07005006 }
Christopher Tate75a99702011-05-18 16:28:19 -07005007 }
5008
5009 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07005010 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07005011
5012 long oldId = Binder.clearCallingIdentity();
5013
5014 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07005015 // Check whether the device has been provisioned -- we don't handle
5016 // full restores prior to completing the setup process.
5017 if (!deviceIsProvisioned()) {
5018 Slog.i(TAG, "Full restore not permitted before setup");
5019 return;
5020 }
5021
5022 Slog.i(TAG, "Beginning full restore...");
5023
Christopher Tate75a99702011-05-18 16:28:19 -07005024 FullRestoreParams params = new FullRestoreParams(fd);
5025 final int token = generateToken();
5026 synchronized (mFullConfirmations) {
5027 mFullConfirmations.put(token, params);
5028 }
5029
5030 // start up the confirmation UI
5031 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
5032 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
5033 Slog.e(TAG, "Unable to launch full restore confirmation");
5034 mFullConfirmations.delete(token);
5035 return;
5036 }
5037
5038 // make sure the screen is lit for the user interaction
5039 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5040
5041 // start the confirmation countdown
5042 startConfirmationTimeout(token, params);
5043
5044 // wait for the restore to be performed
5045 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
5046 waitForCompletion(params);
5047 } finally {
5048 try {
5049 fd.close();
5050 } catch (IOException e) {
5051 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
5052 }
5053 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07005054 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07005055 }
5056 }
5057
5058 boolean startConfirmationUi(int token, String action) {
5059 try {
5060 Intent confIntent = new Intent(action);
5061 confIntent.setClassName("com.android.backupconfirm",
5062 "com.android.backupconfirm.BackupRestoreConfirmation");
5063 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
5064 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5065 mContext.startActivity(confIntent);
5066 } catch (ActivityNotFoundException e) {
5067 return false;
5068 }
5069 return true;
5070 }
5071
5072 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07005073 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07005074 + TIMEOUT_FULL_CONFIRMATION + " millis");
5075 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
5076 token, 0, params);
5077 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07005078 }
5079
5080 void waitForCompletion(FullParams params) {
5081 synchronized (params.latch) {
5082 while (params.latch.get() == false) {
5083 try {
5084 params.latch.wait();
5085 } catch (InterruptedException e) { /* never interrupted */ }
5086 }
5087 }
5088 }
5089
5090 void signalFullBackupRestoreCompletion(FullParams params) {
5091 synchronized (params.latch) {
5092 params.latch.set(true);
5093 params.latch.notifyAll();
5094 }
5095 }
5096
5097 // Confirm that the previously-requested full backup/restore operation can proceed. This
5098 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07005099 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07005100 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07005101 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005102 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
5103 + " allow=" + allow);
5104
5105 // TODO: possibly require not just this signature-only permission, but even
5106 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07005107 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07005108
5109 long oldId = Binder.clearCallingIdentity();
5110 try {
5111
5112 FullParams params;
5113 synchronized (mFullConfirmations) {
5114 params = mFullConfirmations.get(token);
5115 if (params != null) {
5116 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5117 mFullConfirmations.delete(token);
5118
5119 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005120 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005121 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005122 : MSG_RUN_FULL_RESTORE;
5123
Christopher Tate728a1c42011-07-28 18:03:03 -07005124 params.observer = observer;
5125 params.curPassword = curPassword;
Christopher Tate32418be2011-10-10 13:51:12 -07005126
5127 boolean isEncrypted;
5128 try {
5129 isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
5130 if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
5131 } catch (RemoteException e) {
5132 // couldn't contact the mount service; fail "safe" and assume encryption
5133 Slog.e(TAG, "Unable to contact mount service!");
5134 isEncrypted = true;
5135 }
5136 params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
Christopher Tate728a1c42011-07-28 18:03:03 -07005137
Christopher Tate75a99702011-05-18 16:28:19 -07005138 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005139 mWakelock.acquire();
5140 Message msg = mBackupHandler.obtainMessage(verb, params);
5141 mBackupHandler.sendMessage(msg);
5142 } else {
5143 Slog.w(TAG, "User rejected full backup/restore operation");
5144 // indicate completion without having actually transferred any data
5145 signalFullBackupRestoreCompletion(params);
5146 }
5147 } else {
5148 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5149 }
5150 }
5151 } finally {
5152 Binder.restoreCallingIdentity(oldId);
5153 }
5154 }
5155
Christopher Tate8031a3d2009-07-06 16:36:05 -07005156 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005157 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005158 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005159 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005160
Joe Onorato8a9b2202010-02-26 18:56:32 -08005161 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005162
Christopher Tate6ef58a12009-06-29 14:56:28 -07005163 boolean wasEnabled = mEnabled;
5164 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005165 Settings.Secure.putInt(mContext.getContentResolver(),
5166 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005167 mEnabled = enable;
5168 }
5169
Christopher Tate49401dd2009-07-01 12:34:29 -07005170 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005171 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005172 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005173 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005174 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005175 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005176 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005177
Christopher Tateb6787f22009-07-02 17:40:45 -07005178 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005179
5180 // This also constitutes an opt-out, so we wipe any data for
5181 // this device from the backend. We start that process with
5182 // an alarm in order to guarantee wakelock states.
5183 if (wasEnabled && mProvisioned) {
5184 // NOTE: we currently flush every registered transport, not just
5185 // the currently-active one.
5186 HashSet<String> allTransports;
5187 synchronized (mTransports) {
5188 allTransports = new HashSet<String>(mTransports.keySet());
5189 }
5190 // build the set of transports for which we are posting an init
5191 for (String transport : allTransports) {
5192 recordInitPendingLocked(true, transport);
5193 }
5194 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5195 mRunInitIntent);
5196 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005197 }
5198 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005199 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005200
Christopher Tatecce9da52010-02-03 15:11:15 -08005201 // Enable/disable automatic restore of app data at install time
5202 public void setAutoRestore(boolean doAutoRestore) {
5203 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005204 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005205
Joe Onorato8a9b2202010-02-26 18:56:32 -08005206 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005207
5208 synchronized (this) {
5209 Settings.Secure.putInt(mContext.getContentResolver(),
5210 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5211 mAutoRestore = doAutoRestore;
5212 }
5213 }
5214
Christopher Tate8031a3d2009-07-06 16:36:05 -07005215 // Mark the backup service as having been provisioned
5216 public void setBackupProvisioned(boolean available) {
5217 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5218 "setBackupProvisioned");
5219
5220 boolean wasProvisioned = mProvisioned;
5221 synchronized (this) {
5222 Settings.Secure.putInt(mContext.getContentResolver(),
5223 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
5224 mProvisioned = available;
5225 }
5226
5227 synchronized (mQueueLock) {
5228 if (available && !wasProvisioned && mEnabled) {
5229 // we're now good to go, so start the backup alarms
5230 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
5231 } else if (!available) {
5232 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005233 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07005234 mAlarmManager.cancel(mRunBackupIntent);
5235 }
5236 }
5237 }
5238
5239 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005240 // We used to use setInexactRepeating(), but that may be linked to
5241 // backups running at :00 more often than not, creating load spikes.
5242 // Schedule at an exact time for now, and also add a bit of "fuzz".
5243
5244 Random random = new Random();
5245 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5246 random.nextInt(FUZZ_MILLIS);
5247 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5248 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005249 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005250 }
5251
Christopher Tate6ef58a12009-06-29 14:56:28 -07005252 // Report whether the backup mechanism is currently enabled
5253 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005254 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005255 return mEnabled; // no need to synchronize just to read it
5256 }
5257
Christopher Tate91717492009-06-26 21:07:13 -07005258 // Report the name of the currently active transport
5259 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005260 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005261 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005262 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005263 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005264 }
5265
Christopher Tate91717492009-06-26 21:07:13 -07005266 // Report all known, available backup transports
5267 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005268 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005269
Christopher Tate91717492009-06-26 21:07:13 -07005270 String[] list = null;
5271 ArrayList<String> known = new ArrayList<String>();
5272 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5273 if (entry.getValue() != null) {
5274 known.add(entry.getKey());
5275 }
5276 }
5277
5278 if (known.size() > 0) {
5279 list = new String[known.size()];
5280 known.toArray(list);
5281 }
5282 return list;
5283 }
5284
5285 // Select which transport to use for the next backup operation. If the given
5286 // name is not one of the available transports, no action is taken and the method
5287 // returns null.
5288 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005289 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005290
5291 synchronized (mTransports) {
5292 String prevTransport = null;
5293 if (mTransports.get(transport) != null) {
5294 prevTransport = mCurrentTransport;
5295 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005296 Settings.Secure.putString(mContext.getContentResolver(),
5297 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005298 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005299 + " returning " + prevTransport);
5300 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005301 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005302 }
5303 return prevTransport;
5304 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005305 }
5306
Christopher Tatef5e1c292010-12-08 18:40:26 -08005307 // Supply the configuration Intent for the given transport. If the name is not one
5308 // of the available transports, or if the transport does not supply any configuration
5309 // UI, the method returns null.
5310 public Intent getConfigurationIntent(String transportName) {
5311 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5312 "getConfigurationIntent");
5313
5314 synchronized (mTransports) {
5315 final IBackupTransport transport = mTransports.get(transportName);
5316 if (transport != null) {
5317 try {
5318 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005319 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005320 + intent);
5321 return intent;
5322 } catch (RemoteException e) {
5323 /* fall through to return null */
5324 }
5325 }
5326 }
5327
5328 return null;
5329 }
5330
5331 // Supply the configuration summary string for the given transport. If the name is
5332 // not one of the available transports, or if the transport does not supply any
5333 // summary / destination string, the method can return null.
5334 //
5335 // This string is used VERBATIM as the summary text of the relevant Settings item!
5336 public String getDestinationString(String transportName) {
5337 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005338 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005339
5340 synchronized (mTransports) {
5341 final IBackupTransport transport = mTransports.get(transportName);
5342 if (transport != null) {
5343 try {
5344 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005345 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005346 return text;
5347 } catch (RemoteException e) {
5348 /* fall through to return null */
5349 }
5350 }
5351 }
5352
5353 return null;
5354 }
5355
Christopher Tate043dadc2009-06-02 16:11:00 -07005356 // Callback: a requested backup agent has been instantiated. This should only
5357 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005358 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005359 synchronized(mAgentConnectLock) {
5360 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005361 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005362 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5363 mConnectedAgent = agent;
5364 mConnecting = false;
5365 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005366 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005367 + " claiming agent connected");
5368 }
5369 mAgentConnectLock.notifyAll();
5370 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005371 }
5372
5373 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5374 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005375 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005376 public void agentDisconnected(String packageName) {
5377 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005378 synchronized(mAgentConnectLock) {
5379 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5380 mConnectedAgent = null;
5381 mConnecting = false;
5382 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005383 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005384 + " claiming agent disconnected");
5385 }
5386 mAgentConnectLock.notifyAll();
5387 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005388 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005389
Christopher Tate1bb69062010-02-19 17:02:12 -08005390 // An application being installed will need a restore pass, then the Package Manager
5391 // will need to be told when the restore is finished.
5392 public void restoreAtInstall(String packageName, int token) {
5393 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005394 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005395 + " attemping install-time restore");
5396 return;
5397 }
5398
5399 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005400 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08005401 + " token=" + Integer.toHexString(token));
5402
Christopher Tatef0872722010-02-25 15:22:48 -08005403 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005404 // okay, we're going to attempt a restore of this package from this restore set.
5405 // The eventual message back into the Package Manager to run the post-install
5406 // steps for 'token' will be issued from the restore handling code.
5407
5408 // We can use a synthetic PackageInfo here because:
5409 // 1. We know it's valid, since the Package Manager supplied the name
5410 // 2. Only the packageName field will be used by the restore code
5411 PackageInfo pkg = new PackageInfo();
5412 pkg.packageName = packageName;
5413
5414 mWakelock.acquire();
5415 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5416 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005417 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005418 mBackupHandler.sendMessage(msg);
5419 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005420 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5421 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005422 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005423 try {
5424 mPackageManagerBinder.finishPackageInstall(token);
5425 } catch (RemoteException e) { /* can't happen */ }
5426 }
5427 }
5428
Christopher Tate8c850b72009-06-07 19:33:20 -07005429 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005430 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5431 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5432 + " transport=" + transport);
5433
5434 boolean needPermission = true;
5435 if (transport == null) {
5436 transport = mCurrentTransport;
5437
5438 if (packageName != null) {
5439 PackageInfo app = null;
5440 try {
5441 app = mPackageManager.getPackageInfo(packageName, 0);
5442 } catch (NameNotFoundException nnf) {
5443 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5444 throw new IllegalArgumentException("Package " + packageName + " not found");
5445 }
5446
5447 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5448 // So: using the current active transport, and the caller has asked
5449 // that its own package will be restored. In this narrow use case
5450 // we do not require the caller to hold the permission.
5451 needPermission = false;
5452 }
5453 }
5454 }
5455
5456 if (needPermission) {
5457 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5458 "beginRestoreSession");
5459 } else {
5460 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5461 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005462
5463 synchronized(this) {
5464 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005465 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005466 return null;
5467 }
Chris Tate44ab8452010-11-16 15:10:49 -08005468 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005469 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005470 }
5471 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005472 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005473
Christopher Tate73a3cb32010-12-13 18:27:26 -08005474 void clearRestoreSession(ActiveRestoreSession currentSession) {
5475 synchronized(this) {
5476 if (currentSession != mActiveRestoreSession) {
5477 Slog.e(TAG, "ending non-current restore session");
5478 } else {
5479 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5480 mActiveRestoreSession = null;
5481 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5482 }
5483 }
5484 }
5485
Christopher Tate44a27902010-01-27 17:15:49 -08005486 // Note that a currently-active backup agent has notified us that it has
5487 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005488 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005489 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005490 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5491 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005492 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005493 op = mCurrentOperations.get(token);
5494 if (op != null) {
5495 op.state = OP_ACKNOWLEDGED;
5496 }
Christopher Tate44a27902010-01-27 17:15:49 -08005497 mCurrentOpLock.notifyAll();
5498 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005499
5500 // The completion callback, if any, is invoked on the handler
5501 if (op != null && op.callback != null) {
5502 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5503 mBackupHandler.sendMessage(msg);
5504 }
Christopher Tate44a27902010-01-27 17:15:49 -08005505 }
5506
Christopher Tate9b3905c2009-06-08 15:24:01 -07005507 // ----- Restore session -----
5508
Christopher Tate80202c82010-01-25 19:37:47 -08005509 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005510 private static final String TAG = "RestoreSession";
5511
Chris Tate44ab8452010-11-16 15:10:49 -08005512 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005513 private IBackupTransport mRestoreTransport = null;
5514 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005515 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005516
Chris Tate44ab8452010-11-16 15:10:49 -08005517 ActiveRestoreSession(String packageName, String transport) {
5518 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005519 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005520 }
5521
5522 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005523 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005524 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005525 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005526 if (observer == null) {
5527 throw new IllegalArgumentException("Observer must not be null");
5528 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005529
Christopher Tate73a3cb32010-12-13 18:27:26 -08005530 if (mEnded) {
5531 throw new IllegalStateException("Restore session already ended");
5532 }
5533
Christopher Tate1bb69062010-02-19 17:02:12 -08005534 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005535 try {
Christopher Tate43383042009-07-13 15:17:13 -07005536 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005537 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005538 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005539 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005540 // spin off the transport request to our service thread
5541 mWakelock.acquire();
5542 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5543 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5544 mBackupHandler.sendMessage(msg);
5545 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005546 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005547 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005548 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005549 } finally {
5550 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005551 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005552 }
5553
Christopher Tate84725812010-02-04 15:52:40 -08005554 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005555 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5556 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005557
Chris Tate44ab8452010-11-16 15:10:49 -08005558 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005559 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005560
Christopher Tate73a3cb32010-12-13 18:27:26 -08005561 if (mEnded) {
5562 throw new IllegalStateException("Restore session already ended");
5563 }
5564
Dan Egnor0084da52009-07-29 12:57:16 -07005565 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005566 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5567 return -1;
5568 }
5569
5570 if (mPackageName != null) {
5571 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005572 return -1;
5573 }
5574
Christopher Tate21ab6a52009-09-24 18:01:46 -07005575 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005576 for (int i = 0; i < mRestoreSets.length; i++) {
5577 if (token == mRestoreSets[i].token) {
5578 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005579 mWakelock.acquire();
5580 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005581 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005582 mBackupHandler.sendMessage(msg);
5583 Binder.restoreCallingIdentity(oldId);
5584 return 0;
5585 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005586 }
5587 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005588
Joe Onorato8a9b2202010-02-26 18:56:32 -08005589 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005590 return -1;
5591 }
5592
Christopher Tate284f1bb2011-07-07 14:31:18 -07005593 public synchronized int restoreSome(long token, IRestoreObserver observer,
5594 String[] packages) {
5595 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5596 "performRestore");
5597
5598 if (DEBUG) {
5599 StringBuilder b = new StringBuilder(128);
5600 b.append("restoreSome token=");
5601 b.append(Long.toHexString(token));
5602 b.append(" observer=");
5603 b.append(observer.toString());
5604 b.append(" packages=");
5605 if (packages == null) {
5606 b.append("null");
5607 } else {
5608 b.append('{');
5609 boolean first = true;
5610 for (String s : packages) {
5611 if (!first) {
5612 b.append(", ");
5613 } else first = false;
5614 b.append(s);
5615 }
5616 b.append('}');
5617 }
5618 Slog.d(TAG, b.toString());
5619 }
5620
5621 if (mEnded) {
5622 throw new IllegalStateException("Restore session already ended");
5623 }
5624
5625 if (mRestoreTransport == null || mRestoreSets == null) {
5626 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5627 return -1;
5628 }
5629
5630 if (mPackageName != null) {
5631 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5632 return -1;
5633 }
5634
5635 synchronized (mQueueLock) {
5636 for (int i = 0; i < mRestoreSets.length; i++) {
5637 if (token == mRestoreSets[i].token) {
5638 long oldId = Binder.clearCallingIdentity();
5639 mWakelock.acquire();
5640 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5641 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5642 packages, true);
5643 mBackupHandler.sendMessage(msg);
5644 Binder.restoreCallingIdentity(oldId);
5645 return 0;
5646 }
5647 }
5648 }
5649
5650 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5651 return -1;
5652 }
5653
Christopher Tate84725812010-02-04 15:52:40 -08005654 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005655 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005656
Christopher Tate73a3cb32010-12-13 18:27:26 -08005657 if (mEnded) {
5658 throw new IllegalStateException("Restore session already ended");
5659 }
5660
Chris Tate44ab8452010-11-16 15:10:49 -08005661 if (mPackageName != null) {
5662 if (! mPackageName.equals(packageName)) {
5663 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5664 + " on session for package " + mPackageName);
5665 return -1;
5666 }
5667 }
5668
Christopher Tate84725812010-02-04 15:52:40 -08005669 PackageInfo app = null;
5670 try {
5671 app = mPackageManager.getPackageInfo(packageName, 0);
5672 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005673 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005674 return -1;
5675 }
5676
5677 // If the caller is not privileged and is not coming from the target
5678 // app's uid, throw a permission exception back to the caller.
5679 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5680 Binder.getCallingPid(), Binder.getCallingUid());
5681 if ((perm == PackageManager.PERMISSION_DENIED) &&
5682 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005683 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005684 + " or calling uid=" + Binder.getCallingUid());
5685 throw new SecurityException("No permission to restore other packages");
5686 }
5687
Christopher Tate7d411a32010-02-26 11:27:08 -08005688 // If the package has no backup agent, we obviously cannot proceed
5689 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005690 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005691 return -1;
5692 }
5693
Christopher Tate84725812010-02-04 15:52:40 -08005694 // So far so good; we're allowed to try to restore this package. Now
5695 // check whether there is data for it in the current dataset, falling back
5696 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005697 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005698
5699 // If we didn't come up with a place to look -- no ancestral dataset and
5700 // the app has never been backed up from this device -- there's nothing
5701 // to do but return failure.
5702 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005703 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005704 return -1;
5705 }
5706
5707 // Ready to go: enqueue the restore request and claim success
5708 long oldId = Binder.clearCallingIdentity();
5709 mWakelock.acquire();
5710 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005711 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005712 mBackupHandler.sendMessage(msg);
5713 Binder.restoreCallingIdentity(oldId);
5714 return 0;
5715 }
5716
Christopher Tate73a3cb32010-12-13 18:27:26 -08005717 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5718 class EndRestoreRunnable implements Runnable {
5719 BackupManagerService mBackupManager;
5720 ActiveRestoreSession mSession;
5721
5722 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5723 mBackupManager = manager;
5724 mSession = session;
5725 }
5726
5727 public void run() {
5728 // clean up the session's bookkeeping
5729 synchronized (mSession) {
5730 try {
5731 if (mSession.mRestoreTransport != null) {
5732 mSession.mRestoreTransport.finishRestore();
5733 }
5734 } catch (Exception e) {
5735 Slog.e(TAG, "Error in finishRestore", e);
5736 } finally {
5737 mSession.mRestoreTransport = null;
5738 mSession.mEnded = true;
5739 }
5740 }
5741
5742 // clean up the BackupManagerService side of the bookkeeping
5743 // and cancel any pending timeout message
5744 mBackupManager.clearRestoreSession(mSession);
5745 }
5746 }
5747
Dan Egnor0084da52009-07-29 12:57:16 -07005748 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005749 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005750
Christopher Tate73a3cb32010-12-13 18:27:26 -08005751 if (mEnded) {
5752 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005753 }
5754
Christopher Tate73a3cb32010-12-13 18:27:26 -08005755 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005756 }
5757 }
5758
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005759 @Override
5760 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005761 long identityToken = Binder.clearCallingIdentity();
5762 try {
5763 dumpInternal(pw);
5764 } finally {
5765 Binder.restoreCallingIdentity(identityToken);
5766 }
5767 }
5768
5769 private void dumpInternal(PrintWriter pw) {
Christopher Tateb8491bb2011-09-29 15:13:11 -07005770 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5771 != PackageManager.PERMISSION_GRANTED) {
5772 pw.println("Permission Denial: can't dump Backup Manager service from from pid="
5773 + Binder.getCallingPid()
5774 + ", uid=" + Binder.getCallingUid()
5775 + " without permission "
5776 + android.Manifest.permission.DUMP);
5777 return;
5778 }
5779
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005780 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005781 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005782 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005783 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005784 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005785 if (mBackupRunning) pw.println("Backup currently running");
5786 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005787 + " (now = " + System.currentTimeMillis() + ')');
5788 pw.println(" next scheduled: " + mNextBackupPass);
5789
Christopher Tate91717492009-06-26 21:07:13 -07005790 pw.println("Available transports:");
5791 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005792 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5793 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005794 IBackupTransport transport = getTransport(t);
5795 File dir = new File(mBaseStateDir, transport.transportDirName());
5796 pw.println(" destination: " + transport.currentDestinationString());
5797 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005798 for (File f : dir.listFiles()) {
5799 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5800 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005801 } catch (Exception e) {
5802 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005803 pw.println(" Error: " + e);
5804 }
Christopher Tate91717492009-06-26 21:07:13 -07005805 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005806
5807 pw.println("Pending init: " + mPendingInits.size());
5808 for (String s : mPendingInits) {
5809 pw.println(" " + s);
5810 }
5811
Christopher Tate6de74ff2012-01-17 15:20:32 -08005812 if (DEBUG_BACKUP_TRACE) {
5813 synchronized (mBackupTrace) {
5814 if (!mBackupTrace.isEmpty()) {
5815 pw.println("Most recent backup trace:");
5816 for (String s : mBackupTrace) {
5817 pw.println(" " + s);
5818 }
5819 }
5820 }
5821 }
5822
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005823 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005824 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005825 for (int i=0; i<N; i++) {
5826 int uid = mBackupParticipants.keyAt(i);
5827 pw.print(" uid: ");
5828 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005829 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5830 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005831 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005832 }
5833 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005834
Christopher Tateb49ceb32010-02-08 16:22:24 -08005835 pw.println("Ancestral packages: "
5836 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005837 if (mAncestralPackages != null) {
5838 for (String pkg : mAncestralPackages) {
5839 pw.println(" " + pkg);
5840 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005841 }
5842
Christopher Tate73e02522009-07-15 14:18:26 -07005843 pw.println("Ever backed up: " + mEverStoredApps.size());
5844 for (String pkg : mEverStoredApps) {
5845 pw.println(" " + pkg);
5846 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005847
5848 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005849 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005850 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005851 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005852 }
5853 }
Christopher Tate487529a2009-04-29 14:03:25 -07005854}