blob: 83b55c5351432b201b19e1045b34bef9e3c3b102 [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;
Christopher Tate181fafa2009-05-14 11:12:14 -070021import android.app.IActivityManager;
22import android.app.IApplicationThread;
23import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070024import android.app.PendingIntent;
Christopher Tate3799bc22009-05-06 16:13:56 -070025import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070026import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070027import android.content.Context;
28import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070029import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070030import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070031import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070032import android.content.pm.IPackageDataObserver;
Christopher Tate7b881282009-06-07 13:52:37 -070033import android.content.pm.PackageInfo;
Christopher Tate043dadc2009-06-02 16:11:00 -070034import android.content.pm.PackageManager.NameNotFoundException;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070036import android.content.pm.Signature;
Christopher Tate3799bc22009-05-06 16:13:56 -070037import android.net.Uri;
Christopher Tatece0bf062009-07-01 11:43:53 -070038import android.provider.Settings;
Christopher Tate487529a2009-04-29 14:03:25 -070039import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070040import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070041import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070042import android.os.Handler;
43import android.os.IBinder;
44import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070045import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070046import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070047import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070048import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070049import android.os.SystemClock;
50import android.util.EventLog;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.util.Log;
52import android.util.SparseArray;
53
54import android.backup.IBackupManager;
Christopher Tate7d562ec2009-06-25 18:03:43 -070055import android.backup.IRestoreObserver;
Christopher Tate8c850b72009-06-07 19:33:20 -070056import android.backup.IRestoreSession;
Christopher Tate9b3905c2009-06-08 15:24:01 -070057import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070058
Christopher Tated55e18a2009-09-21 10:12:59 -070059import com.android.internal.backup.BackupConstants;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070060import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070061import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070062
Christopher Tate6785dd82009-06-18 15:58:25 -070063import com.android.server.PackageManagerBackupAgent;
Christopher Tate6aa41f42009-06-19 14:14:22 -070064import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070065
Christopher Tatecde87f42009-06-12 12:55:53 -070066import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070067import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070068import java.io.FileDescriptor;
Christopher Tate4cc86e12009-09-21 19:36:51 -070069import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070070import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070071import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070072import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070073import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040074import java.util.ArrayList;
75import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070076import java.util.HashSet;
77import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070078import java.util.Map;
Christopher Tate487529a2009-04-29 14:03:25 -070079
80class BackupManagerService extends IBackupManager.Stub {
81 private static final String TAG = "BackupManagerService";
82 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070083
Christopher Tate49401dd2009-07-01 12:34:29 -070084 // How often we perform a backup pass. Privileged external callers can
85 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070086 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070087
Christopher Tate8031a3d2009-07-06 16:36:05 -070088 // The amount of time between the initial provisioning of the device and
89 // the first backup pass.
90 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
91
Christopher Tate4cc86e12009-09-21 19:36:51 -070092 private static final String RUN_BACKUP_ACTION = "android.backup.intent.RUN";
93 private static final String RUN_INITIALIZE_ACTION = "android.backup.intent.INIT";
94 private static final String RUN_CLEAR_ACTION = "android.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -070095 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070096 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070097 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -070098 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -070099 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700100
Dan Egnorbb9001c2009-07-27 12:20:13 -0700101 // Event tags -- see system/core/logcat/event-log-tags
102 private static final int BACKUP_DATA_CHANGED_EVENT = 2820;
103 private static final int BACKUP_START_EVENT = 2821;
104 private static final int BACKUP_TRANSPORT_FAILURE_EVENT = 2822;
105 private static final int BACKUP_AGENT_FAILURE_EVENT = 2823;
106 private static final int BACKUP_PACKAGE_EVENT = 2824;
107 private static final int BACKUP_SUCCESS_EVENT = 2825;
Christopher Tated55e18a2009-09-21 10:12:59 -0700108 private static final int BACKUP_RESET_EVENT = 2826;
Dan Egnorbb9001c2009-07-27 12:20:13 -0700109
110 private static final int RESTORE_START_EVENT = 2830;
111 private static final int RESTORE_TRANSPORT_FAILURE_EVENT = 2831;
112 private static final int RESTORE_AGENT_FAILURE_EVENT = 2832;
113 private static final int RESTORE_PACKAGE_EVENT = 2833;
114 private static final int RESTORE_SUCCESS_EVENT = 2834;
115
Christopher Tatec7b31e32009-06-10 15:49:30 -0700116 // Timeout interval for deciding that a bind or clear-data has taken too long
117 static final long TIMEOUT_INTERVAL = 10 * 1000;
118
Christopher Tate487529a2009-04-29 14:03:25 -0700119 private Context mContext;
120 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700121 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700122 private PowerManager mPowerManager;
123 private AlarmManager mAlarmManager;
124
Christopher Tate73e02522009-07-15 14:18:26 -0700125 boolean mEnabled; // access to this is synchronized on 'this'
126 boolean mProvisioned;
127 PowerManager.WakeLock mWakelock;
128 final BackupHandler mBackupHandler = new BackupHandler();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700129 PendingIntent mRunBackupIntent, mRunInitIntent;
130 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700131 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700132 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700133 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700134 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700135 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700136 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700137 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700138
Christopher Tate181fafa2009-05-14 11:12:14 -0700139 BackupRequest(ApplicationInfo app, boolean isFull) {
140 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700141 fullBackup = isFull;
142 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700143
144 public String toString() {
145 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
146 }
Christopher Tate46758122009-05-06 11:22:00 -0700147 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400148 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700149 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700150 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700151
152 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700153 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700154
155 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700156 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700157
Christopher Tate043dadc2009-06-02 16:11:00 -0700158 // The thread performing the sequence of queued backups binds to each app's agent
159 // in succession. Bind notifications are asynchronously delivered through the
160 // Activity Manager; use this lock object to signal when a requested binding has
161 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700162 final Object mAgentConnectLock = new Object();
163 IBackupAgent mConnectedAgent;
164 volatile boolean mConnecting;
Christopher Tate043dadc2009-06-02 16:11:00 -0700165
Christopher Tatec7b31e32009-06-10 15:49:30 -0700166 // A similar synchronicity mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700167 final Object mClearDataLock = new Object();
168 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700169
Christopher Tate91717492009-06-26 21:07:13 -0700170 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700171 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700172 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700173 String mCurrentTransport;
174 IBackupTransport mLocalTransport, mGoogleTransport;
175 RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700176
Christopher Tate73e02522009-07-15 14:18:26 -0700177 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700178 public IBackupTransport transport;
179 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700180 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700181
Dan Egnor156411d2009-06-26 13:20:02 -0700182 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700183 transport = _transport;
184 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700185 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700186 }
187 }
188
Christopher Tate73e02522009-07-15 14:18:26 -0700189 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700190 public IBackupTransport transport;
191 public PackageInfo packageInfo;
192
193 ClearParams(IBackupTransport _transport, PackageInfo _info) {
194 transport = _transport;
195 packageInfo = _info;
196 }
197 }
198
Christopher Tate5cb400b2009-06-25 16:03:14 -0700199 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700200 File mBaseStateDir;
201 File mDataDir;
202 File mJournalDir;
203 File mJournal;
204 RandomAccessFile mJournalStream;
205
206 // Keep a log of all the apps we've ever backed up
207 private File mEverStored;
208 private RandomAccessFile mEverStoredStream;
209 HashSet<String> mEverStoredApps = new HashSet<String>();
210
Christopher Tate4cc86e12009-09-21 19:36:51 -0700211 // Persistently track the need to do a full init
212 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
213 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
214 boolean mInitInProgress = false;
Christopher Tateaa088442009-06-16 18:25:46 -0700215
Christopher Tate487529a2009-04-29 14:03:25 -0700216 public BackupManagerService(Context context) {
217 mContext = context;
218 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700219 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700220
Christopher Tateb6787f22009-07-02 17:40:45 -0700221 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
222 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
223
Christopher Tate22b87872009-05-04 16:41:53 -0700224 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700225 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700226 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700227 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700228 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700229 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700230 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700231
Christopher Tate4cc86e12009-09-21 19:36:51 -0700232 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700233 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700234 IntentFilter filter = new IntentFilter();
235 filter.addAction(RUN_BACKUP_ACTION);
236 context.registerReceiver(mRunBackupReceiver, filter,
237 android.Manifest.permission.BACKUP, null);
238
239 mRunInitReceiver = new RunInitializeReceiver();
240 filter = new IntentFilter();
241 filter.addAction(RUN_INITIALIZE_ACTION);
242 context.registerReceiver(mRunInitReceiver, filter,
243 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700244
245 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700246 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
247 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
248
Christopher Tate4cc86e12009-09-21 19:36:51 -0700249 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
250 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
251 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
252
Christopher Tatecde87f42009-06-12 12:55:53 -0700253 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700254 mJournalDir = new File(mBaseStateDir, "pending");
255 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700256 makeJournalLocked(); // okay because no other threads are running yet
257
Christopher Tate73e02522009-07-15 14:18:26 -0700258 // Set up the various sorts of package tracking we do
259 initPackageTracking();
260
Christopher Tateabce4e82009-06-18 18:35:32 -0700261 // Build our mapping of uid to backup client services. This implicitly
262 // schedules a backup pass on the Package Manager metadata the first
263 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700264 synchronized (mBackupParticipants) {
265 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700266 }
267
Dan Egnor87a02bc2009-06-17 02:30:10 -0700268 // Set up our transport options and initialize the default transport
269 // TODO: Have transports register themselves somehow?
270 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700271 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700272 ComponentName localName = new ComponentName(context, LocalTransport.class);
273 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700274
Christopher Tate91717492009-06-26 21:07:13 -0700275 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700276 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
277 Settings.Secure.BACKUP_TRANSPORT);
278 if ("".equals(mCurrentTransport)) {
279 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700280 }
Christopher Tate91717492009-06-26 21:07:13 -0700281 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
282
283 // Attach to the Google backup transport. When this comes up, it will set
284 // itself as the current transport because we explicitly reset mCurrentTransport
285 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700286 Intent intent = new Intent().setComponent(new ComponentName(
287 "com.google.android.backup",
288 "com.google.android.backup.BackupTransportService"));
289 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700290
Christopher Tatecde87f42009-06-12 12:55:53 -0700291 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700292 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700293 parseLeftoverJournals();
294
Christopher Tateb6787f22009-07-02 17:40:45 -0700295 // Power management
296 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
297
298 // Start the backup passes going
299 setBackupEnabled(areEnabled);
300 }
301
302 private class RunBackupReceiver extends BroadcastReceiver {
303 public void onReceive(Context context, Intent intent) {
304 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700305 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700306 if (mPendingInits.size() > 0) {
307 // If there are pending init operations, we process those
308 // and then settle into the usual periodic backup schedule.
309 if (DEBUG) Log.v(TAG, "Init pending at scheduled backup");
310 try {
311 mAlarmManager.cancel(mRunInitIntent);
312 mRunInitIntent.send();
313 } catch (PendingIntent.CanceledException ce) {
314 Log.e(TAG, "Run init intent cancelled");
315 // can't really do more than bail here
316 }
317 } else {
318 // Don't run backups now if we're disabled, not yet
319 // fully set up, or racing with an initialize pass.
320 if (mEnabled && mProvisioned && !mInitInProgress) {
321 if (DEBUG) Log.v(TAG, "Running a backup pass");
322
323 // Acquire the wakelock and pass it to the backup thread. it will
324 // be released once backup concludes.
325 mWakelock.acquire();
326
327 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
328 mBackupHandler.sendMessage(msg);
329 } else {
330 Log.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned
331 + " i=" + mInitInProgress);
332 }
333 }
334 }
335 }
336 }
337 }
338
339 private class RunInitializeReceiver extends BroadcastReceiver {
340 public void onReceive(Context context, Intent intent) {
341 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
342 synchronized (mQueueLock) {
343 if (DEBUG) Log.v(TAG, "Running a device init");
344 mInitInProgress = true;
345
346 // Acquire the wakelock and pass it to the init thread. it will
347 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700348 mWakelock.acquire();
349
Christopher Tate4cc86e12009-09-21 19:36:51 -0700350 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700351 mBackupHandler.sendMessage(msg);
352 }
353 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700354 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700355 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700356
Christopher Tate73e02522009-07-15 14:18:26 -0700357 private void initPackageTracking() {
358 if (DEBUG) Log.v(TAG, "Initializing package tracking");
359
Christopher Tatee97e8072009-07-15 16:45:50 -0700360 // Keep a log of what apps we've ever backed up. Because we might have
361 // rebooted in the middle of an operation that was removing something from
362 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700363 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700364 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700365 try {
Christopher Tatedfec20b2009-08-03 15:38:09 -0700366 // If there are previous contents, parse them out then start a new
367 // file to continue the recordkeeping.
368 if (mEverStored.exists()) {
369 RandomAccessFile temp = new RandomAccessFile(tempProcessedFile, "rw");
370 mEverStoredStream = new RandomAccessFile(mEverStored, "r");
Christopher Tate73e02522009-07-15 14:18:26 -0700371
Christopher Tatedfec20b2009-08-03 15:38:09 -0700372 // parse its existing contents
373 mEverStoredStream.seek(0);
374 temp.seek(0);
375 try {
376 while (true) {
377 PackageInfo info;
378 String pkg = mEverStoredStream.readUTF();
379 try {
380 info = mPackageManager.getPackageInfo(pkg, 0);
381 mEverStoredApps.add(pkg);
382 temp.writeUTF(pkg);
383 if (DEBUG) Log.v(TAG, " + " + pkg);
384 } catch (NameNotFoundException e) {
385 // nope, this package was uninstalled; don't include it
386 if (DEBUG) Log.v(TAG, " - " + pkg);
387 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700388 }
Christopher Tatedfec20b2009-08-03 15:38:09 -0700389 } catch (EOFException e) {
390 // now we're at EOF
Christopher Tate73e02522009-07-15 14:18:26 -0700391 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700392
Christopher Tatedfec20b2009-08-03 15:38:09 -0700393 // Once we've rewritten the backup history log, atomically replace the
394 // old one with the new one then reopen the file for continuing use.
395 temp.close();
396 mEverStoredStream.close();
397 tempProcessedFile.renameTo(mEverStored);
398 }
399 // This will create the file if it doesn't exist
Christopher Tatee97e8072009-07-15 16:45:50 -0700400 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
Christopher Tatedfec20b2009-08-03 15:38:09 -0700401 mEverStoredStream.seek(mEverStoredStream.length());
Christopher Tate73e02522009-07-15 14:18:26 -0700402 } catch (IOException e) {
403 Log.e(TAG, "Unable to open known-stored file!");
404 mEverStoredStream = null;
405 }
406
Christopher Tatee97e8072009-07-15 16:45:50 -0700407 // If we were in the middle of removing something from the ever-backed-up
408 // file, there might be a transient "processed.new" file still present.
409 // We've reconstructed a coherent state at this point though, so we can
410 // safely discard that file now.
411 if (tempProcessedFile.exists()) {
412 tempProcessedFile.delete();
413 }
414
Christopher Tate73e02522009-07-15 14:18:26 -0700415 // Register for broadcasts about package install, etc., so we can
416 // update the provider list.
417 IntentFilter filter = new IntentFilter();
418 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
419 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
420 filter.addDataScheme("package");
421 mContext.registerReceiver(mBroadcastReceiver, filter);
422 }
423
Christopher Tatecde87f42009-06-12 12:55:53 -0700424 private void makeJournalLocked() {
425 try {
426 mJournal = File.createTempFile("journal", null, mJournalDir);
427 mJournalStream = new RandomAccessFile(mJournal, "rwd");
428 } catch (IOException e) {
429 Log.e(TAG, "Unable to write backup journals");
430 mJournal = null;
431 mJournalStream = null;
432 }
433 }
434
435 private void parseLeftoverJournals() {
436 if (mJournal != null) {
437 File[] allJournals = mJournalDir.listFiles();
438 for (File f : allJournals) {
439 if (f.compareTo(mJournal) != 0) {
440 // This isn't the current journal, so it must be a leftover. Read
441 // out the package names mentioned there and schedule them for
442 // backup.
443 try {
444 Log.i(TAG, "Found stale backup journal, scheduling:");
445 RandomAccessFile in = new RandomAccessFile(f, "r");
446 while (true) {
447 String packageName = in.readUTF();
448 Log.i(TAG, " + " + packageName);
449 dataChanged(packageName);
450 }
451 } catch (EOFException e) {
452 // no more data; we're done
453 } catch (Exception e) {
454 // can't read it or other error; just skip it
455 } finally {
456 // close/delete the file
457 f.delete();
458 }
459 }
460 }
461 }
462 }
463
Christopher Tate4cc86e12009-09-21 19:36:51 -0700464 // Maintain persistent state around whether need to do an initialize operation.
465 // Must be called with the queue lock held.
466 void recordInitPendingLocked(boolean isPending, String transportName) {
467 if (DEBUG) Log.i(TAG, "recordInitPendingLocked: " + isPending
468 + " on transport " + transportName);
469 try {
470 IBackupTransport transport = getTransport(transportName);
471 String transportDirName = transport.transportDirName();
472 File stateDir = new File(mBaseStateDir, transportDirName);
473 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
474
475 if (isPending) {
476 // We need an init before we can proceed with sending backup data.
477 // Record that with an entry in our set of pending inits, as well as
478 // journaling it via creation of a sentinel file.
479 mPendingInits.add(transportName);
480 try {
481 (new FileOutputStream(initPendingFile)).close();
482 } catch (IOException ioe) {
483 // Something is badly wrong with our permissions; just try to move on
484 }
485 } else {
486 // No more initialization needed; wipe the journal and reset our state.
487 initPendingFile.delete();
488 mPendingInits.remove(transportName);
489 }
490 } catch (RemoteException e) {
491 // can't happen; the transport is local
492 }
493 }
494
Christopher Tated55e18a2009-09-21 10:12:59 -0700495 // Reset all of our bookkeeping, in response to having been told that
496 // the backend data has been wiped [due to idle expiry, for example],
497 // so we must re-upload all saved settings.
498 void resetBackupState(File stateFileDir) {
499 synchronized (mQueueLock) {
500 // Wipe the "what we've ever backed up" tracking
501 try {
502 // close the ever-stored journal...
503 if (mEverStoredStream != null) {
504 mEverStoredStream.close();
505 }
506 // ... so we can delete it and start over
507 mEverStored.delete();
508 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
509 } catch (IOException e) {
510 Log.e(TAG, "Unable to open known-stored file!");
511 mEverStoredStream = null;
512 }
513 mEverStoredApps.clear();
514
515 // Remove all the state files
516 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700517 // ... but don't touch the needs-init sentinel
518 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
519 sf.delete();
520 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700521 }
522
523 // Enqueue a new backup of every participant
524 int N = mBackupParticipants.size();
525 for (int i=0; i<N; i++) {
526 int uid = mBackupParticipants.keyAt(i);
527 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
528 for (ApplicationInfo app: participants) {
529 try {
530 dataChanged(app.packageName);
531 } catch (RemoteException e) {
532 // can't happen; we're in the same process
533 }
534 }
535 }
536 }
537 }
538
Christopher Tate91717492009-06-26 21:07:13 -0700539 // Add a transport to our set of available backends
540 private void registerTransport(String name, IBackupTransport transport) {
541 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700542 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tate91717492009-06-26 21:07:13 -0700543 mTransports.put(name, transport);
544 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700545
546 // If the init sentinel file exists, we need to be sure to perform the init
547 // as soon as practical. We also create the state directory at registration
548 // time to ensure it's present from the outset.
549 try {
550 String transportName = transport.transportDirName();
551 File stateDir = new File(mBaseStateDir, transportName);
552 stateDir.mkdirs();
553
554 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
555 if (initSentinel.exists()) {
556 synchronized (mQueueLock) {
557 mPendingInits.add(transportName);
558
559 // TODO: pick a better starting time than now + 1 minute
560 long delay = 1000 * 60; // one minute, in milliseconds
561 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
562 System.currentTimeMillis() + delay, mRunInitIntent);
563 }
564 }
565 } catch (RemoteException e) {
566 // can't happen, the transport is local
567 }
Christopher Tate91717492009-06-26 21:07:13 -0700568 }
569
Christopher Tate3799bc22009-05-06 16:13:56 -0700570 // ----- Track installation/removal of packages -----
571 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
572 public void onReceive(Context context, Intent intent) {
573 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
574
575 Uri uri = intent.getData();
576 if (uri == null) {
577 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700578 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700579 String pkgName = uri.getSchemeSpecificPart();
580 if (pkgName == null) {
581 return;
582 }
583
584 String action = intent.getAction();
585 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
586 synchronized (mBackupParticipants) {
587 Bundle extras = intent.getExtras();
588 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
589 // The package was just upgraded
590 updatePackageParticipantsLocked(pkgName);
591 } else {
592 // The package was just added
593 addPackageParticipantsLocked(pkgName);
594 }
595 }
596 }
597 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
598 Bundle extras = intent.getExtras();
599 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
600 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
601 } else {
602 synchronized (mBackupParticipants) {
603 removePackageParticipantsLocked(pkgName);
604 }
605 }
606 }
607 }
608 };
609
Dan Egnor87a02bc2009-06-17 02:30:10 -0700610 // ----- Track connection to GoogleBackupTransport service -----
611 ServiceConnection mGoogleConnection = new ServiceConnection() {
612 public void onServiceConnected(ComponentName name, IBinder service) {
613 if (DEBUG) Log.v(TAG, "Connected to Google transport");
614 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700615 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700616 }
617
618 public void onServiceDisconnected(ComponentName name) {
619 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
620 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700621 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700622 }
623 };
624
Joe Onorato8ad02812009-05-13 01:41:44 -0400625 // ----- Run the actual backup process asynchronously -----
626
Christopher Tate181fafa2009-05-14 11:12:14 -0700627 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400628 public void handleMessage(Message msg) {
629
630 switch (msg.what) {
631 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700632 {
Christopher Tate91717492009-06-26 21:07:13 -0700633 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700634 if (transport == null) {
635 Log.v(TAG, "Backup requested but no transport available");
Christopher Tateb6787f22009-07-02 17:40:45 -0700636 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700637 break;
638 }
639
Joe Onorato8ad02812009-05-13 01:41:44 -0400640 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700641 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700642 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400643 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700644 // Do we have any work to do?
645 if (mPendingBackups.size() > 0) {
646 for (BackupRequest b: mPendingBackups.values()) {
647 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700648 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700649 Log.v(TAG, "clearing pending backups");
650 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700651
Christopher Tate49401dd2009-07-01 12:34:29 -0700652 // Start a new backup-queue journal file too
653 if (mJournalStream != null) {
654 try {
655 mJournalStream.close();
656 } catch (IOException e) {
657 // don't need to do anything
658 }
659 makeJournalLocked();
660 }
661
662 // At this point, we have started a new journal file, and the old
663 // file identity is being passed to the backup processing thread.
664 // When it completes successfully, that old journal file will be
665 // deleted. If we crash prior to that, the old journal is parsed
666 // at next boot and the journaled requests fulfilled.
667 (new PerformBackupThread(transport, queue, oldJournal)).start();
668 } else {
669 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tateb6787f22009-07-02 17:40:45 -0700670 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700671 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400672 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700673 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700674 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700675
676 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400677 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700678
679 case MSG_RUN_RESTORE:
680 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700681 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400682 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700683 (new PerformRestoreThread(params.transport, params.observer,
684 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700685 break;
686 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700687
688 case MSG_RUN_CLEAR:
689 {
690 ClearParams params = (ClearParams)msg.obj;
691 (new PerformClearThread(params.transport, params.packageInfo)).start();
692 break;
693 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700694
695 case MSG_RUN_INITIALIZE:
696 {
697 HashSet<String> queue;
698
699 // Snapshot the pending-init queue and work on that
700 synchronized (mQueueLock) {
701 queue = new HashSet<String>(mPendingInits);
702 mPendingInits.clear();
703 }
704
705 (new PerformInitializeThread(queue)).start();
706 break;
707 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400708 }
709 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400710 }
711
Christopher Tate181fafa2009-05-14 11:12:14 -0700712 // Add the backup agents in the given package to our set of known backup participants.
713 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700714 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700715 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700716 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700717 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700718 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700719 }
720
Christopher Tate181fafa2009-05-14 11:12:14 -0700721 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700722 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700723 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700724 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
725 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700726 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700727 + " uid=" + p.applicationInfo.uid
728 + " killAfterRestore="
729 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
730 + " restoreNeedsApplication="
731 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
732 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700733 }
734 }
735
Dan Egnorefe52642009-06-24 00:16:33 -0700736 for (PackageInfo pkg : targetPkgs) {
737 if (packageName == null || pkg.packageName.equals(packageName)) {
738 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700739 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700740 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700741 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700742 mBackupParticipants.put(uid, set);
743 }
Dan Egnorefe52642009-06-24 00:16:33 -0700744 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700745
746 // If we've never seen this app before, schedule a backup for it
747 if (!mEverStoredApps.contains(pkg.packageName)) {
748 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
749 + " never backed up; scheduling");
750 try {
751 dataChanged(pkg.packageName);
752 } catch (RemoteException e) {
753 // can't happen; it's a local method call
754 }
755 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700756 }
Christopher Tate487529a2009-04-29 14:03:25 -0700757 }
758 }
759
Christopher Tate6785dd82009-06-18 15:58:25 -0700760 // Remove the given package's entry from our known active set. If
761 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700762 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700763 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700764 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700765 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700766 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700767 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700768 int flags = PackageManager.GET_SIGNATURES;
769 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700770 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700771 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700772 }
773 } else {
774 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700775 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700776 }
777 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700778 }
779
Joe Onorato8ad02812009-05-13 01:41:44 -0400780 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700781 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700782 if (DEBUG) {
783 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
784 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700785 for (PackageInfo p : agents) {
786 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700787 }
788 }
Dan Egnorefe52642009-06-24 00:16:33 -0700789 for (PackageInfo pkg : agents) {
790 if (packageName == null || pkg.packageName.equals(packageName)) {
791 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700792 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700793 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700794 // Find the existing entry with the same package name, and remove it.
795 // We can't just remove(app) because the instances are different.
796 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700797 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700798 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700799 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700800 break;
801 }
802 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700803 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700804 mBackupParticipants.delete(uid);
805 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700806 }
807 }
808 }
809 }
810
Christopher Tate181fafa2009-05-14 11:12:14 -0700811 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700812 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700813 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700814 int flags = PackageManager.GET_SIGNATURES;
815 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
816 int N = packages.size();
817 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700818 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700819 try {
820 ApplicationInfo app = pkg.applicationInfo;
821 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
822 || app.backupAgentName == null
823 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
824 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
825 packages.remove(a);
826 }
827 else {
828 // we will need the shared library path, so look that up and store it here
829 app = mPackageManager.getApplicationInfo(pkg.packageName,
830 PackageManager.GET_SHARED_LIBRARY_FILES);
831 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
832 }
833 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700834 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700835 }
836 }
Dan Egnorefe52642009-06-24 00:16:33 -0700837 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700838 }
Christopher Tateaa088442009-06-16 18:25:46 -0700839
Christopher Tate3799bc22009-05-06 16:13:56 -0700840 // Reset the given package's known backup participants. Unlike add/remove, the update
841 // action cannot be passed a null package name.
842 void updatePackageParticipantsLocked(String packageName) {
843 if (packageName == null) {
844 Log.e(TAG, "updatePackageParticipants called with null package name");
845 return;
846 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700847 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700848
849 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700850 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700851 removePackageParticipantsLockedInner(packageName, allApps);
852 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700853 }
854
Christopher Tate73e02522009-07-15 14:18:26 -0700855 // Called from the backup thread: record that the given app has been successfully
856 // backed up at least once
857 void logBackupComplete(String packageName) {
Christopher Tatee97e8072009-07-15 16:45:50 -0700858 if (mEverStoredStream != null && !packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate73e02522009-07-15 14:18:26 -0700859 synchronized (mEverStoredApps) {
860 if (mEverStoredApps.add(packageName)) {
861 try {
862 mEverStoredStream.writeUTF(packageName);
863 } catch (IOException e) {
864 Log.e(TAG, "Unable to log backup of " + packageName + ", ceasing log");
865 try {
866 mEverStoredStream.close();
867 } catch (IOException ioe) {
868 // we're dropping it; no need to handle an exception on close here
869 }
870 mEverStoredStream = null;
871 }
872 }
873 }
874 }
875 }
876
Christopher Tatee97e8072009-07-15 16:45:50 -0700877 // Remove our awareness of having ever backed up the given package
878 void removeEverBackedUp(String packageName) {
879 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName
880 + ", new set:");
881
882 if (mEverStoredStream != null) {
883 synchronized (mEverStoredApps) {
884 // Rewrite the file and rename to overwrite. If we reboot in the middle,
885 // we'll recognize on initialization time that the package no longer
886 // exists and fix it up then.
887 File tempKnownFile = new File(mBaseStateDir, "processed.new");
888 try {
889 mEverStoredStream.close();
890 RandomAccessFile known = new RandomAccessFile(tempKnownFile, "rw");
891 mEverStoredApps.remove(packageName);
892 for (String s : mEverStoredApps) {
893 known.writeUTF(s);
894 if (DEBUG) Log.v(TAG, " " + s);
895 }
896 known.close();
897 tempKnownFile.renameTo(mEverStored);
898 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
899 } catch (IOException e) {
900 // Bad: we couldn't create the new copy. For safety's sake we
901 // abandon the whole process and remove all what's-backed-up
902 // state entirely, meaning we'll force a backup pass for every
903 // participant on the next boot or [re]install.
904 Log.w(TAG, "Error rewriting backed-up set; halting log");
905 mEverStoredStream = null;
906 mEverStoredApps.clear();
907 tempKnownFile.delete();
908 mEverStored.delete();
909 }
910 }
911 }
912 }
913
Dan Egnor87a02bc2009-06-17 02:30:10 -0700914 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700915 private IBackupTransport getTransport(String transportName) {
916 synchronized (mTransports) {
917 IBackupTransport transport = mTransports.get(transportName);
918 if (transport == null) {
919 Log.w(TAG, "Requested unavailable transport: " + transportName);
920 }
921 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700922 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700923 }
924
Christopher Tatedf01dea2009-06-09 20:45:02 -0700925 // fire off a backup agent, blocking until it attaches or times out
926 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
927 IBackupAgent agent = null;
928 synchronized(mAgentConnectLock) {
929 mConnecting = true;
930 mConnectedAgent = null;
931 try {
932 if (mActivityManager.bindBackupAgent(app, mode)) {
933 Log.d(TAG, "awaiting agent for " + app);
934
935 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700936 // only wait 10 seconds for the clear data to happen
937 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
938 while (mConnecting && mConnectedAgent == null
939 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700940 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700941 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700942 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700943 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700944 return null;
945 }
946 }
947
948 // if we timed out with no connect, abort and move on
949 if (mConnecting == true) {
950 Log.w(TAG, "Timeout waiting for agent " + app);
951 return null;
952 }
953 agent = mConnectedAgent;
954 }
955 } catch (RemoteException e) {
956 // can't happen
957 }
958 }
959 return agent;
960 }
961
Christopher Tatec7b31e32009-06-10 15:49:30 -0700962 // clear an application's data, blocking until the operation completes or times out
963 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700964 // Don't wipe packages marked allowClearUserData=false
965 try {
966 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
967 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
968 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
969 + packageName);
970 return;
971 }
972 } catch (NameNotFoundException e) {
973 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
974 return;
975 }
976
Christopher Tatec7b31e32009-06-10 15:49:30 -0700977 ClearDataObserver observer = new ClearDataObserver();
978
979 synchronized(mClearDataLock) {
980 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700981 /* This is causing some critical processes to be killed during setup.
982 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -0700983 try {
984 mActivityManager.clearApplicationUserData(packageName, observer);
985 } catch (RemoteException e) {
986 // can't happen because the activity manager is in this process
987 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700988 */
989 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700990
991 // only wait 10 seconds for the clear data to happen
992 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
993 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
994 try {
995 mClearDataLock.wait(5000);
996 } catch (InterruptedException e) {
997 // won't happen, but still.
998 mClearingData = false;
999 }
1000 }
1001 }
1002 }
1003
1004 class ClearDataObserver extends IPackageDataObserver.Stub {
1005 public void onRemoveCompleted(String packageName, boolean succeeded)
Dan Egnor0084da52009-07-29 12:57:16 -07001006 throws RemoteException {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001007 synchronized(mClearDataLock) {
1008 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001009 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001010 }
1011 }
1012 }
1013
Christopher Tate043dadc2009-06-02 16:11:00 -07001014 // ----- Back up a set of applications via a worker thread -----
1015
1016 class PerformBackupThread extends Thread {
1017 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001018 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001019 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001020 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001021 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001022
Christopher Tateaa088442009-06-16 18:25:46 -07001023 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001024 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001025 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001026 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001027 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001028
1029 try {
1030 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1031 } catch (RemoteException e) {
1032 // can't happen; the transport is local
1033 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001034 }
1035
1036 @Override
1037 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001038 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001039 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001040 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1041
Christopher Tate79588342009-06-30 16:11:49 -07001042 // Backups run at background priority
1043 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1044
Christopher Tate043dadc2009-06-02 16:11:00 -07001045 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001046 EventLog.writeEvent(BACKUP_START_EVENT, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001047
1048 // If we haven't stored anything yet, we need to do an init operation.
1049 if (status == BackupConstants.TRANSPORT_OK && mEverStoredApps.size() == 0) {
1050 status = mTransport.initializeDevice();
1051 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001052
1053 // The package manager doesn't have a proper <application> etc, but since
1054 // it's running here in the system process we can just set up its agent
1055 // directly and use a synthetic BackupRequest. We always run this pass
1056 // because it's cheap and this way we guarantee that we don't get out of
1057 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001058 if (status == BackupConstants.TRANSPORT_OK) {
1059 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1060 mPackageManager, allAgentPackages());
1061 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1062 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1063 status = processOneBackup(pmRequest,
1064 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1065 }
Christopher Tate90967f42009-09-20 15:28:33 -07001066
Dan Egnor01445162009-09-21 17:04:05 -07001067 if (status == BackupConstants.TRANSPORT_OK) {
1068 // Now run all the backups in our queue
1069 status = doQueuedBackups(mTransport);
1070 }
1071
1072 if (status == BackupConstants.TRANSPORT_OK) {
1073 // Tell the transport to finish everything it has buffered
1074 status = mTransport.finishBackup();
1075 if (status == BackupConstants.TRANSPORT_OK) {
1076 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1077 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, mQueue.size(), millis);
1078 } else {
1079 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "");
1080 Log.e(TAG, "Transport error in finishBackup()");
1081 }
1082 }
1083
Dan Egnor01445162009-09-21 17:04:05 -07001084 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001085 // The backend reports that our dataset has been wiped. We need to
1086 // reset all of our bookkeeping and instead run a new backup pass for
1087 // everything.
1088 EventLog.writeEvent(BACKUP_RESET_EVENT, mTransport.transportDirName());
1089 resetBackupState(mStateDir);
1090 backupNow();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001091 }
1092 } catch (Exception e) {
1093 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001094 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001095 } finally {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001096 // If things went wrong, we need to re-stage the apps we had expected
1097 // to be backing up in this pass. This journals the package names in
1098 // the current active pending-backup file, not in the we are holding
1099 // here in mJournal.
1100 if (status != BackupConstants.TRANSPORT_OK) {
1101 Log.w(TAG, "Backup pass unsuccessful, restaging");
1102 for (BackupRequest req : mQueue) {
1103 try {
1104 dataChanged(req.appInfo.packageName);
1105 } catch (RemoteException e) {
1106 // can't happen; it's a local call
1107 }
1108 }
1109 }
1110
1111 // Either backup was successful, in which case we of course do not need
1112 // this pass's journal any more; or it failed, in which case we just
1113 // re-enqueued all of these packages in the current active journal.
1114 // Either way, we no longer need this pass's journal.
1115 if (!mJournal.delete()) {
1116 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1117 }
1118
Dan Egnorbb9001c2009-07-27 12:20:13 -07001119 // Only once we're entirely finished do we release the wakelock
1120 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001121 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001122 }
1123
Dan Egnor01445162009-09-21 17:04:05 -07001124 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001125 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001126 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001127
Christopher Tate0749dcd2009-08-13 15:13:03 -07001128 // Don't run backup, even if requested, if the target app does not have
1129 // the requisite permission
1130 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1131 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1132 Log.w(TAG, "Skipping backup of unprivileged package "
1133 + request.appInfo.packageName);
1134 continue;
1135 }
1136
Christopher Tate043dadc2009-06-02 16:11:00 -07001137 IBackupAgent agent = null;
1138 int mode = (request.fullBackup)
1139 ? IApplicationThread.BACKUP_MODE_FULL
1140 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1141 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001142 agent = bindToAgentSynchronous(request.appInfo, mode);
1143 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001144 int result = processOneBackup(request, agent, transport);
1145 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001146 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001147 } catch (SecurityException ex) {
1148 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001149 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001150 } finally {
1151 try { // unbind even on timeout, just in case
1152 mActivityManager.unbindBackupAgent(request.appInfo);
1153 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001154 }
1155 }
Dan Egnor01445162009-09-21 17:04:05 -07001156
1157 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001158 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001159
Dan Egnor01445162009-09-21 17:04:05 -07001160 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1161 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001162 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001163 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001164
Dan Egnorbb9001c2009-07-27 12:20:13 -07001165 File savedStateName = new File(mStateDir, packageName);
1166 File backupDataName = new File(mDataDir, packageName + ".data");
1167 File newStateName = new File(mStateDir, packageName + ".new");
1168
1169 ParcelFileDescriptor savedState = null;
1170 ParcelFileDescriptor backupData = null;
1171 ParcelFileDescriptor newState = null;
1172
1173 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001174 try {
1175 // Look up the package info & signatures. This is first so that if it
1176 // throws an exception, there's no file setup yet that would need to
1177 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001178 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1179 // The metadata 'package' is synthetic
1180 packInfo = new PackageInfo();
1181 packInfo.packageName = packageName;
1182 } else {
1183 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001184 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001185 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001186
Christopher Tatec7b31e32009-06-10 15:49:30 -07001187 // In a full backup, we pass a null ParcelFileDescriptor as
1188 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001189 if (!request.fullBackup) {
1190 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001191 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001192 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1193 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001194
Dan Egnorbb9001c2009-07-27 12:20:13 -07001195 backupData = ParcelFileDescriptor.open(backupDataName,
1196 ParcelFileDescriptor.MODE_READ_WRITE |
1197 ParcelFileDescriptor.MODE_CREATE |
1198 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001199
Dan Egnorbb9001c2009-07-27 12:20:13 -07001200 newState = ParcelFileDescriptor.open(newStateName,
1201 ParcelFileDescriptor.MODE_READ_WRITE |
1202 ParcelFileDescriptor.MODE_CREATE |
1203 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001204
1205 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001206 agent.doBackup(savedState, backupData, newState);
1207 logBackupComplete(packageName);
1208 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001209 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001210 Log.e(TAG, "Error backing up " + packageName, e);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001211 EventLog.writeEvent(BACKUP_AGENT_FAILURE_EVENT, packageName, e.toString());
1212 backupDataName.delete();
1213 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001214 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001215 } finally {
1216 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1217 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1218 try { if (newState != null) newState.close(); } catch (IOException e) {}
1219 savedState = backupData = newState = null;
1220 }
1221
1222 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001223 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001224 try {
1225 int size = (int) backupDataName.length();
1226 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001227 if (result == BackupConstants.TRANSPORT_OK) {
1228 backupData = ParcelFileDescriptor.open(backupDataName,
1229 ParcelFileDescriptor.MODE_READ_ONLY);
1230 result = transport.performBackup(packInfo, backupData);
1231 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001232
Dan Egnor83861e72009-09-17 16:17:55 -07001233 // TODO - We call finishBackup() for each application backed up, because
1234 // we need to know now whether it succeeded or failed. Instead, we should
1235 // hold off on finishBackup() until the end, which implies holding off on
1236 // renaming *all* the output state files (see below) until that happens.
1237
Dan Egnor01445162009-09-21 17:04:05 -07001238 if (result == BackupConstants.TRANSPORT_OK) {
1239 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001240 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001241 } else {
1242 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1243 }
1244
1245 // After successful transport, delete the now-stale data
1246 // and juggle the files so that next time we supply the agent
1247 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001248 if (result == BackupConstants.TRANSPORT_OK) {
1249 backupDataName.delete();
1250 newStateName.renameTo(savedStateName);
1251 EventLog.writeEvent(BACKUP_PACKAGE_EVENT, packageName, size);
1252 } else {
1253 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
1254 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001255 } catch (Exception e) {
1256 Log.e(TAG, "Transport error backing up " + packageName, e);
1257 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001258 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001259 } finally {
1260 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001261 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001262
Dan Egnor01445162009-09-21 17:04:05 -07001263 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001264 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001265 }
1266
Christopher Tatedf01dea2009-06-09 20:45:02 -07001267
1268 // ----- Restore handling -----
1269
Christopher Tateabce4e82009-06-18 18:35:32 -07001270 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001271 // Allow unsigned apps, but not signed on one device and unsigned on the other
1272 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -07001273 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1274 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001275 if ((storedSigs == null || storedSigs.length == 0)
1276 && (deviceSigs == null || deviceSigs.length == 0)) {
1277 return true;
1278 }
1279 if (storedSigs == null || deviceSigs == null) {
1280 return false;
1281 }
1282
Christopher Tateabce4e82009-06-18 18:35:32 -07001283 // !!! TODO: this demands that every stored signature match one
1284 // that is present on device, and does not demand the converse.
1285 // Is this this right policy?
1286 int nStored = storedSigs.length;
1287 int nDevice = deviceSigs.length;
1288
1289 for (int i=0; i < nStored; i++) {
1290 boolean match = false;
1291 for (int j=0; j < nDevice; j++) {
1292 if (storedSigs[i].equals(deviceSigs[j])) {
1293 match = true;
1294 break;
1295 }
1296 }
1297 if (!match) {
1298 return false;
1299 }
1300 }
1301 return true;
1302 }
1303
Christopher Tatedf01dea2009-06-09 20:45:02 -07001304 class PerformRestoreThread extends Thread {
1305 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001306 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001307 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001308 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001309
Christopher Tate5cbbf562009-06-22 16:44:51 -07001310 class RestoreRequest {
1311 public PackageInfo app;
1312 public int storedAppVersion;
1313
1314 RestoreRequest(PackageInfo _app, int _version) {
1315 app = _app;
1316 storedAppVersion = _version;
1317 }
1318 }
1319
Christopher Tate7d562ec2009-06-25 18:03:43 -07001320 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001321 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001322 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001323 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001324 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001325 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001326
1327 try {
1328 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1329 } catch (RemoteException e) {
1330 // can't happen; the transport is local
1331 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001332 }
1333
1334 @Override
1335 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001336 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001337 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001338 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001339 /**
1340 * Restore sequence:
1341 *
Dan Egnorefe52642009-06-24 00:16:33 -07001342 * 1. get the restore set description for our identity
1343 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001344 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001345 * 3. for each app in the restore queue:
1346 * 3.a. clear the app data
1347 * 3.b. get the restore data for the app from the transport
1348 * 3.c. launch the backup agent for the app
1349 * 3.d. agent.doRestore() with the data from the server
1350 * 3.e. unbind the agent [and kill the app?]
1351 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001352 *
1353 * On errors, we try our best to recover and move on to the next
1354 * application, but if necessary we abort the whole operation --
1355 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001356 */
1357
Christopher Tate7d562ec2009-06-25 18:03:43 -07001358 int error = -1; // assume error
1359
Dan Egnorefe52642009-06-24 00:16:33 -07001360 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001361 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001362 // TODO: Log this before getAvailableRestoreSets, somehow
Dan Egnor313b29f2009-09-22 10:44:10 -07001363 EventLog.writeEvent(RESTORE_START_EVENT, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001364
Dan Egnorefe52642009-06-24 00:16:33 -07001365 // Get the list of all packages which have backup enabled.
1366 // (Include the Package Manager metadata pseudo-package first.)
1367 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1368 PackageInfo omPackage = new PackageInfo();
1369 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1370 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001371
Dan Egnorefe52642009-06-24 00:16:33 -07001372 List<PackageInfo> agentPackages = allAgentPackages();
1373 restorePackages.addAll(agentPackages);
1374
Christopher Tate7d562ec2009-06-25 18:03:43 -07001375 // let the observer know that we're running
1376 if (mObserver != null) {
1377 try {
1378 // !!! TODO: get an actual count from the transport after
1379 // its startRestore() runs?
1380 mObserver.restoreStarting(restorePackages.size());
1381 } catch (RemoteException e) {
1382 Log.d(TAG, "Restore observer died at restoreStarting");
1383 mObserver = null;
1384 }
1385 }
1386
Dan Egnor01445162009-09-21 17:04:05 -07001387 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1388 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001389 Log.e(TAG, "Error starting restore operation");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001390 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001391 return;
1392 }
1393
1394 String packageName = mTransport.nextRestorePackage();
1395 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001396 Log.e(TAG, "Error getting first restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001397 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001398 return;
1399 } else if (packageName.equals("")) {
1400 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001401 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1402 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001403 return;
1404 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1405 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1406 + "\", found only \"" + packageName + "\"");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001407 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1408 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001409 return;
1410 }
1411
1412 // Pull the Package Manager metadata from the restore set first
1413 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1414 mPackageManager, agentPackages);
1415 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1416
Christopher Tate8c032472009-07-02 14:28:47 -07001417 // Verify that the backup set includes metadata. If not, we can't do
1418 // signature/version verification etc, so we simply do not proceed with
1419 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001420 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001421 Log.e(TAG, "No restore metadata available, so not restoring settings");
1422 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1423 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001424 return;
1425 }
1426
Christopher Tate7d562ec2009-06-25 18:03:43 -07001427 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001428 for (;;) {
1429 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001430
Dan Egnorefe52642009-06-24 00:16:33 -07001431 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001432 Log.e(TAG, "Error getting next restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001433 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001434 return;
1435 } else if (packageName.equals("")) {
1436 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001437 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001438
Christopher Tate7d562ec2009-06-25 18:03:43 -07001439 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001440 try {
1441 mObserver.onUpdate(count);
1442 } catch (RemoteException e) {
1443 Log.d(TAG, "Restore observer died in onUpdate");
1444 mObserver = null;
1445 }
1446 }
1447
Dan Egnorefe52642009-06-24 00:16:33 -07001448 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1449 if (metaInfo == null) {
1450 Log.e(TAG, "Missing metadata for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001451 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1452 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001453 continue;
1454 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001455
Dan Egnorbb9001c2009-07-27 12:20:13 -07001456 PackageInfo packageInfo;
1457 try {
1458 int flags = PackageManager.GET_SIGNATURES;
1459 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1460 } catch (NameNotFoundException e) {
1461 Log.e(TAG, "Invalid package restoring data", e);
1462 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1463 "Package missing on device");
1464 continue;
1465 }
1466
Dan Egnorefe52642009-06-24 00:16:33 -07001467 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001468 String message = "Version " + metaInfo.versionCode
1469 + " > installed version " + packageInfo.versionCode;
1470 Log.w(TAG, "Package " + packageName + ": " + message);
1471 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001472 continue;
1473 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001474
Dan Egnorefe52642009-06-24 00:16:33 -07001475 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1476 Log.w(TAG, "Signature mismatch restoring " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001477 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1478 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001479 continue;
1480 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001481
Dan Egnorefe52642009-06-24 00:16:33 -07001482 if (DEBUG) Log.v(TAG, "Package " + packageName
1483 + " restore version [" + metaInfo.versionCode
1484 + "] is compatible with installed version ["
1485 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001486
Christopher Tate5e1ab332009-09-01 20:32:49 -07001487 // Now perform the actual restore: first clear the app's data
1488 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001489 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001490
1491 // Then set up and bind the agent (with a restricted Application object
1492 // unless the application says otherwise)
1493 boolean useRealApp = (packageInfo.applicationInfo.flags
1494 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1495 if (DEBUG && useRealApp) {
1496 Log.v(TAG, "agent requires real Application subclass for restore");
1497 }
Dan Egnorefe52642009-06-24 00:16:33 -07001498 IBackupAgent agent = bindToAgentSynchronous(
1499 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001500 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1501 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001502 if (agent == null) {
1503 Log.w(TAG, "Can't find backup agent for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001504 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1505 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001506 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001507 }
1508
Christopher Tate5e1ab332009-09-01 20:32:49 -07001509 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001510 try {
1511 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001512 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001513 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001514 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001515 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001516
1517 // The agent was probably running with a stub Application object,
1518 // which isn't a valid run mode for the main app logic. Shut
1519 // down the app so that next time it's launched, it gets the
1520 // usual full initialization.
1521 if ((packageInfo.applicationInfo.flags
1522 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1523 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1524 + packageInfo.applicationInfo.processName);
1525 mActivityManager.killApplicationProcess(
1526 packageInfo.applicationInfo.processName,
1527 packageInfo.applicationInfo.uid);
1528 }
Dan Egnorefe52642009-06-24 00:16:33 -07001529 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001530 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001531
1532 // if we get this far, report success to the observer
1533 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001534 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1535 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, count, millis);
1536 } catch (Exception e) {
1537 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001538 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001539 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1540
Dan Egnorefe52642009-06-24 00:16:33 -07001541 try {
1542 mTransport.finishRestore();
1543 } catch (RemoteException e) {
1544 Log.e(TAG, "Error finishing restore", e);
1545 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001546
1547 if (mObserver != null) {
1548 try {
1549 mObserver.restoreFinished(error);
1550 } catch (RemoteException e) {
1551 Log.d(TAG, "Restore observer died at restoreFinished");
1552 }
1553 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001554
1555 // done; we can finally release the wakelock
1556 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001557 }
1558 }
1559
Dan Egnorefe52642009-06-24 00:16:33 -07001560 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1561 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001562 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001563 final String packageName = app.packageName;
1564
Dan Egnorbb9001c2009-07-27 12:20:13 -07001565 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001566
Christopher Tate0749dcd2009-08-13 15:13:03 -07001567 // Don't restore to unprivileged packages
1568 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1569 packageName) != PackageManager.PERMISSION_GRANTED) {
1570 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1571 }
1572
Christopher Tatec7b31e32009-06-10 15:49:30 -07001573 // !!! TODO: get the dirs from the transport
1574 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001575 File newStateName = new File(mStateDir, packageName + ".new");
1576 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001577
Dan Egnorbb9001c2009-07-27 12:20:13 -07001578 ParcelFileDescriptor backupData = null;
1579 ParcelFileDescriptor newState = null;
1580
1581 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001582 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001583 backupData = ParcelFileDescriptor.open(backupDataName,
1584 ParcelFileDescriptor.MODE_READ_WRITE |
1585 ParcelFileDescriptor.MODE_CREATE |
1586 ParcelFileDescriptor.MODE_TRUNCATE);
1587
Dan Egnor01445162009-09-21 17:04:05 -07001588 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001589 Log.e(TAG, "Error getting restore data for " + packageName);
1590 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
1591 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001592 }
1593
1594 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001595 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001596 backupData = ParcelFileDescriptor.open(backupDataName,
1597 ParcelFileDescriptor.MODE_READ_ONLY);
1598
Dan Egnorbb9001c2009-07-27 12:20:13 -07001599 newState = ParcelFileDescriptor.open(newStateName,
1600 ParcelFileDescriptor.MODE_READ_WRITE |
1601 ParcelFileDescriptor.MODE_CREATE |
1602 ParcelFileDescriptor.MODE_TRUNCATE);
1603
1604 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001605
1606 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001607 //
1608 // !!! TODO: the restored data should be migrated on the server
1609 // side into the current dataset. In that case the new state file
1610 // we just created would reflect the data already extant in the
1611 // backend, so there'd be nothing more to do. Until that happens,
1612 // however, we need to make sure that we record the data to the
1613 // current backend dataset. (Yes, this means shipping the data over
1614 // the wire in both directions. That's bad, but consistency comes
1615 // first, then efficiency.) Once we introduce server-side data
1616 // migration to the newly-restored device's dataset, we will change
1617 // the following from a discard of the newly-written state to the
1618 // "correct" operation of renaming into the canonical state blob.
1619 newStateName.delete(); // TODO: remove; see above comment
1620 //newStateName.renameTo(savedStateName); // TODO: replace with this
1621
Dan Egnorbb9001c2009-07-27 12:20:13 -07001622 int size = (int) backupDataName.length();
1623 EventLog.writeEvent(RESTORE_PACKAGE_EVENT, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001624 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001625 Log.e(TAG, "Error restoring data for " + packageName, e);
1626 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, e.toString());
1627
Christopher Tate96733042009-07-20 14:49:13 -07001628 // If the agent fails restore, it might have put the app's data
1629 // into an incoherent state. For consistency we wipe its data
1630 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001631 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001632 } finally {
1633 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001634 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1635 try { if (newState != null) newState.close(); } catch (IOException e) {}
1636 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001637 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001638 }
1639 }
1640
Christopher Tateee0e78a2009-07-02 11:17:03 -07001641 class PerformClearThread extends Thread {
1642 IBackupTransport mTransport;
1643 PackageInfo mPackage;
1644
1645 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1646 mTransport = transport;
1647 mPackage = packageInfo;
1648 }
1649
1650 @Override
1651 public void run() {
1652 try {
1653 // Clear the on-device backup state to ensure a full backup next time
1654 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1655 File stateFile = new File(stateDir, mPackage.packageName);
1656 stateFile.delete();
1657
1658 // Tell the transport to remove all the persistent storage for the app
Dan Egnor83861e72009-09-17 16:17:55 -07001659 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001660 mTransport.clearBackupData(mPackage);
1661 } catch (RemoteException e) {
1662 // can't happen; the transport is local
1663 } finally {
1664 try {
Dan Egnor83861e72009-09-17 16:17:55 -07001665 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001666 mTransport.finishBackup();
1667 } catch (RemoteException e) {
1668 // can't happen; the transport is local
1669 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001670
1671 // Last but not least, release the cpu
1672 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001673 }
1674 }
1675 }
1676
Christopher Tate4cc86e12009-09-21 19:36:51 -07001677 class PerformInitializeThread extends Thread {
1678 HashSet<String> mQueue;
1679
1680 PerformInitializeThread(HashSet<String> transportNames) {
1681 mQueue = transportNames;
1682 }
1683
1684 @Override
1685 public void run() {
1686 int status;
1687 try {
1688 for (String transportName : mQueue) {
1689 IBackupTransport transport = getTransport(transportName);
1690 if (transport == null) {
1691 Log.e(TAG, "Requested init for " + transportName + " but not found");
1692 continue;
1693 }
1694
1695 status = BackupConstants.TRANSPORT_OK;
1696 File stateDir = null;
1697
1698 Log.i(TAG, "Device init on " + transport.transportDirName());
1699
1700 stateDir = new File(mBaseStateDir, transport.transportDirName());
1701
1702 status = transport.initializeDevice();
1703 if (status != BackupConstants.TRANSPORT_OK) {
1704 Log.e(TAG, "Error from initializeDevice: " + status);
1705 }
1706 if (status == BackupConstants.TRANSPORT_OK) {
1707 status = transport.finishBackup();
1708 }
1709
1710 // Okay, the wipe really happened. Clean up our local bookkeeping.
1711 if (status == BackupConstants.TRANSPORT_OK) {
1712 resetBackupState(stateDir);
1713 synchronized (mQueueLock) {
1714 recordInitPendingLocked(false, transportName);
1715 }
1716 }
1717
1718 // If this didn't work, requeue this one and try again
1719 // after a suitable interval
1720 if (status != BackupConstants.TRANSPORT_OK) {
1721 Log.i(TAG, "Device init failed");
1722 synchronized (mQueueLock) {
1723 recordInitPendingLocked(true, transportName);
1724 }
1725 // do this via another alarm to make sure of the wakelock states
1726 long delay = transport.requestBackupTime();
1727 if (DEBUG) Log.w(TAG, "init failed on "
1728 + transportName + " resched in " + delay);
1729 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1730 System.currentTimeMillis() + delay, mRunInitIntent);
1731 } else {
1732 // success!
1733 Log.i(TAG, "Device init successful");
1734 }
1735
1736 }
1737 } catch (RemoteException e) {
1738 // can't happen; the transports are local
1739 } catch (Exception e) {
1740 Log.e(TAG, "Unexpected error performing init", e);
1741 } finally {
1742 // Done; indicate that we're finished and release the wakelock
1743 synchronized (mQueueLock) {
1744 mInitInProgress = false;
1745 }
1746 mWakelock.release();
1747 }
1748 }
1749 }
1750
Christopher Tatedf01dea2009-06-09 20:45:02 -07001751
Christopher Tate487529a2009-04-29 14:03:25 -07001752 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001753
Christopher Tatea8bf8152009-04-30 11:36:21 -07001754 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001755 // Record that we need a backup pass for the caller. Since multiple callers
1756 // may share a uid, we need to note all candidates within that uid and schedule
1757 // a backup pass for each of them.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001758 EventLog.writeEvent(BACKUP_DATA_CHANGED_EVENT, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001759
Christopher Tate63d27002009-06-16 17:16:42 -07001760 // If the caller does not hold the BACKUP permission, it can only request a
1761 // backup of its own data.
1762 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001763 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001764 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1765 targets = mBackupParticipants.get(Binder.getCallingUid());
1766 } else {
1767 // a caller with full permission can ask to back up any participating app
1768 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001769 targets = new HashSet<ApplicationInfo>();
1770 int N = mBackupParticipants.size();
1771 for (int i = 0; i < N; i++) {
1772 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1773 if (s != null) {
1774 targets.addAll(s);
1775 }
1776 }
1777 }
Christopher Tate487529a2009-04-29 14:03:25 -07001778 if (targets != null) {
1779 synchronized (mQueueLock) {
1780 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001781 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001782 // validate the caller-supplied package name against the known set of
1783 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001784 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001785 // Add the caller to the set of pending backups. If there is
1786 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001787 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001788 if (mPendingBackups.put(app, req) == null) {
1789 // Journal this request in case of crash. The put()
1790 // operation returned null when this package was not already
1791 // in the set; we want to avoid touching the disk redundantly.
1792 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001793
Christopher Tate22b60d82009-07-07 16:36:02 -07001794 if (DEBUG) {
1795 int numKeys = mPendingBackups.size();
1796 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1797 for (BackupRequest b : mPendingBackups.values()) {
1798 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1799 }
1800 }
1801 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001802 }
1803 }
Christopher Tate487529a2009-04-29 14:03:25 -07001804 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001805 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001806 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1807 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001808 }
1809 }
Christopher Tate46758122009-05-06 11:22:00 -07001810
Christopher Tatecde87f42009-06-12 12:55:53 -07001811 private void writeToJournalLocked(String str) {
1812 if (mJournalStream != null) {
1813 try {
1814 mJournalStream.writeUTF(str);
1815 } catch (IOException e) {
1816 Log.e(TAG, "Error writing to backup journal");
1817 mJournalStream = null;
1818 mJournal = null;
1819 }
1820 }
1821 }
1822
Christopher Tateee0e78a2009-07-02 11:17:03 -07001823 // Clear the given package's backup data from the current transport
1824 public void clearBackupData(String packageName) {
1825 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1826 PackageInfo info;
1827 try {
1828 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1829 } catch (NameNotFoundException e) {
1830 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1831 return;
1832 }
1833
1834 // If the caller does not hold the BACKUP permission, it can only request a
1835 // wipe of its own backed-up data.
1836 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001837 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001838 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1839 apps = mBackupParticipants.get(Binder.getCallingUid());
1840 } else {
1841 // a caller with full permission can ask to back up any participating app
1842 // !!! TODO: allow data-clear of ANY app?
1843 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1844 apps = new HashSet<ApplicationInfo>();
1845 int N = mBackupParticipants.size();
1846 for (int i = 0; i < N; i++) {
1847 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1848 if (s != null) {
1849 apps.addAll(s);
1850 }
1851 }
1852 }
1853
1854 // now find the given package in the set of candidate apps
1855 for (ApplicationInfo app : apps) {
1856 if (app.packageName.equals(packageName)) {
1857 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1858 // found it; fire off the clear request
1859 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001860 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001861 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001862 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1863 new ClearParams(getTransport(mCurrentTransport), info));
1864 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001865 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001866 }
1867 break;
1868 }
1869 }
1870 }
1871
Christopher Tateace7f092009-06-15 18:07:25 -07001872 // Run a backup pass immediately for any applications that have declared
1873 // that they have pending updates.
1874 public void backupNow() throws RemoteException {
Joe Onorato5933a492009-07-23 18:24:08 -04001875 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001876
Christopher Tateace7f092009-06-15 18:07:25 -07001877 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001878 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001879 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001880 mRunBackupIntent.send();
1881 } catch (PendingIntent.CanceledException e) {
1882 // should never happen
1883 Log.e(TAG, "run-backup intent cancelled!");
1884 }
Christopher Tate46758122009-05-06 11:22:00 -07001885 }
1886 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001887
Christopher Tate8031a3d2009-07-06 16:36:05 -07001888 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001889 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001890 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1891 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001892
Christopher Tate4cc86e12009-09-21 19:36:51 -07001893 Log.i(TAG, "Backup enabled => " + enable);
1894
Christopher Tate6ef58a12009-06-29 14:56:28 -07001895 boolean wasEnabled = mEnabled;
1896 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001897 Settings.Secure.putInt(mContext.getContentResolver(),
1898 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001899 mEnabled = enable;
1900 }
1901
Christopher Tate49401dd2009-07-01 12:34:29 -07001902 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001903 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001904 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001905 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001906 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001907 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07001908 if (DEBUG) Log.i(TAG, "Opting out of backup");
1909
Christopher Tateb6787f22009-07-02 17:40:45 -07001910 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001911
1912 // This also constitutes an opt-out, so we wipe any data for
1913 // this device from the backend. We start that process with
1914 // an alarm in order to guarantee wakelock states.
1915 if (wasEnabled && mProvisioned) {
1916 // NOTE: we currently flush every registered transport, not just
1917 // the currently-active one.
1918 HashSet<String> allTransports;
1919 synchronized (mTransports) {
1920 allTransports = new HashSet<String>(mTransports.keySet());
1921 }
1922 // build the set of transports for which we are posting an init
1923 for (String transport : allTransports) {
1924 recordInitPendingLocked(true, transport);
1925 }
1926 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1927 mRunInitIntent);
1928 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001929 }
1930 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001931 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001932
Christopher Tate8031a3d2009-07-06 16:36:05 -07001933 // Mark the backup service as having been provisioned
1934 public void setBackupProvisioned(boolean available) {
1935 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1936 "setBackupProvisioned");
1937
1938 boolean wasProvisioned = mProvisioned;
1939 synchronized (this) {
1940 Settings.Secure.putInt(mContext.getContentResolver(),
1941 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1942 mProvisioned = available;
1943 }
1944
1945 synchronized (mQueueLock) {
1946 if (available && !wasProvisioned && mEnabled) {
1947 // we're now good to go, so start the backup alarms
1948 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1949 } else if (!available) {
1950 // No longer enabled, so stop running backups
1951 Log.w(TAG, "Backup service no longer provisioned");
1952 mAlarmManager.cancel(mRunBackupIntent);
1953 }
1954 }
1955 }
1956
1957 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1958 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1959 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1960 BACKUP_INTERVAL, mRunBackupIntent);
1961 }
1962
Christopher Tate6ef58a12009-06-29 14:56:28 -07001963 // Report whether the backup mechanism is currently enabled
1964 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04001965 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001966 return mEnabled; // no need to synchronize just to read it
1967 }
1968
Christopher Tate91717492009-06-26 21:07:13 -07001969 // Report the name of the currently active transport
1970 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04001971 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001972 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001973 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001974 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001975 }
1976
Christopher Tate91717492009-06-26 21:07:13 -07001977 // Report all known, available backup transports
1978 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001979 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001980
Christopher Tate91717492009-06-26 21:07:13 -07001981 String[] list = null;
1982 ArrayList<String> known = new ArrayList<String>();
1983 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1984 if (entry.getValue() != null) {
1985 known.add(entry.getKey());
1986 }
1987 }
1988
1989 if (known.size() > 0) {
1990 list = new String[known.size()];
1991 known.toArray(list);
1992 }
1993 return list;
1994 }
1995
1996 // Select which transport to use for the next backup operation. If the given
1997 // name is not one of the available transports, no action is taken and the method
1998 // returns null.
1999 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002000 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002001
2002 synchronized (mTransports) {
2003 String prevTransport = null;
2004 if (mTransports.get(transport) != null) {
2005 prevTransport = mCurrentTransport;
2006 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002007 Settings.Secure.putString(mContext.getContentResolver(),
2008 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002009 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2010 + " returning " + prevTransport);
2011 } else {
2012 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2013 }
2014 return prevTransport;
2015 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002016 }
2017
2018 // Callback: a requested backup agent has been instantiated. This should only
2019 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002020 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002021 synchronized(mAgentConnectLock) {
2022 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2023 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2024 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2025 mConnectedAgent = agent;
2026 mConnecting = false;
2027 } else {
2028 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2029 + " claiming agent connected");
2030 }
2031 mAgentConnectLock.notifyAll();
2032 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002033 }
2034
2035 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2036 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002037 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002038 public void agentDisconnected(String packageName) {
2039 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002040 synchronized(mAgentConnectLock) {
2041 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2042 mConnectedAgent = null;
2043 mConnecting = false;
2044 } else {
2045 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2046 + " claiming agent disconnected");
2047 }
2048 mAgentConnectLock.notifyAll();
2049 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002050 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002051
Christopher Tate8c850b72009-06-07 19:33:20 -07002052 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002053 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002054 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002055
2056 synchronized(this) {
2057 if (mActiveRestoreSession != null) {
2058 Log.d(TAG, "Restore session requested but one already active");
2059 return null;
2060 }
Christopher Tate91717492009-06-26 21:07:13 -07002061 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002062 }
2063 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002064 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002065
Christopher Tate9b3905c2009-06-08 15:24:01 -07002066 // ----- Restore session -----
2067
2068 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002069 private static final String TAG = "RestoreSession";
2070
Christopher Tate9b3905c2009-06-08 15:24:01 -07002071 private IBackupTransport mRestoreTransport = null;
2072 RestoreSet[] mRestoreSets = null;
2073
Christopher Tate91717492009-06-26 21:07:13 -07002074 RestoreSession(String transport) {
2075 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002076 }
2077
2078 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002079 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002080 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002081 "getAvailableRestoreSets");
2082
Christopher Tatef68eb502009-06-16 11:02:01 -07002083 try {
Christopher Tate43383042009-07-13 15:17:13 -07002084 if (mRestoreTransport == null) {
2085 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002086 return null;
2087 }
2088 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002089 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002090 if (mRestoreSets == null) EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002091 }
2092 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002093 } catch (Exception e) {
2094 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2095 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002096 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002097 }
2098
Dan Egnor0084da52009-07-29 12:57:16 -07002099 public synchronized int performRestore(long token, IRestoreObserver observer) {
2100 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2101 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002102
Christopher Tatef2c321a2009-08-10 15:43:36 -07002103 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2104 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002105
Dan Egnor0084da52009-07-29 12:57:16 -07002106 if (mRestoreTransport == null || mRestoreSets == null) {
2107 Log.e(TAG, "Ignoring performRestore() with no restore set");
2108 return -1;
2109 }
2110
2111 for (int i = 0; i < mRestoreSets.length; i++) {
2112 if (token == mRestoreSets[i].token) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002113 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07002114 mWakelock.acquire();
2115 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2116 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2117 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002118 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07002119 return 0;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002120 }
2121 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002122
2123 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002124 return -1;
2125 }
2126
Dan Egnor0084da52009-07-29 12:57:16 -07002127 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002128 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002129 "endRestoreSession");
2130
Dan Egnor0084da52009-07-29 12:57:16 -07002131 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002132
Dan Egnor0084da52009-07-29 12:57:16 -07002133 synchronized (this) {
2134 try {
2135 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2136 } catch (Exception e) {
2137 Log.e(TAG, "Error in finishRestore", e);
2138 } finally {
2139 mRestoreTransport = null;
2140 }
2141 }
2142
2143 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002144 if (BackupManagerService.this.mActiveRestoreSession == this) {
2145 BackupManagerService.this.mActiveRestoreSession = null;
2146 } else {
2147 Log.e(TAG, "ending non-current restore session");
2148 }
2149 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002150 }
2151 }
2152
Christopher Tate043dadc2009-06-02 16:11:00 -07002153
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002154 @Override
2155 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2156 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002157 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
2158 + " / " + (!mProvisioned ? "not " : "") + "provisioned");
Christopher Tate91717492009-06-26 21:07:13 -07002159 pw.println("Available transports:");
2160 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002161 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
2162 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07002163 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002164 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07002165 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002166 for (int i=0; i<N; i++) {
2167 int uid = mBackupParticipants.keyAt(i);
2168 pw.print(" uid: ");
2169 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002170 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2171 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002172 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002173 }
2174 }
Christopher Tate73e02522009-07-15 14:18:26 -07002175 pw.println("Ever backed up: " + mEverStoredApps.size());
2176 for (String pkg : mEverStoredApps) {
2177 pw.println(" " + pkg);
2178 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07002179 pw.println("Pending: " + mPendingBackups.size());
2180 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002181 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002182 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002183 }
2184 }
Christopher Tate487529a2009-04-29 14:03:25 -07002185}